diff --git a/Cargo.lock b/Cargo.lock index b8ed498b..638f0c79 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2387,7 +2387,7 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "subtr-actor" -version = "1.1.0" +version = "1.2.0" dependencies = [ "anyhow", "boxcars", @@ -3060,7 +3060,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.48.0", ] [[package]] diff --git a/crates/rocket-sense-server/src/api/leaderboards.rs b/crates/rocket-sense-server/src/api/leaderboards.rs index 133c7bf5..0692eb14 100644 --- a/crates/rocket-sense-server/src/api/leaderboards.rs +++ b/crates/rocket-sense-server/src/api/leaderboards.rs @@ -22,6 +22,7 @@ mod tests; const DEFAULT_LIMIT: u32 = 50; const MAX_LIMIT: u32 = 200; +const ALL_SCOPE: &str = "*"; pub fn router() -> Router { Router::new() @@ -42,6 +43,219 @@ struct LeaderboardPaging { offset: u32, } +/// Standard windows backed by disposable player/window aggregates. The cache +/// is only a read model: live replay/fact queries remain the correctness +/// fallback and the cache is expected to be fully rebuilt often. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum LeaderboardWindow { + Daily, + TrailingSevenDays, + Season, +} + +impl LeaderboardWindow { + fn from_params(params: &QueryParams) -> Result, ApiError> { + match params + .first(&["window"]) + .map(|value| value.trim().to_ascii_lowercase()) + .as_deref() + { + None | Some("") => Ok(None), + Some("daily") | Some("day") => Ok(Some(Self::Daily)), + Some("trailing-7d") | Some("trailing_7d") | Some("7d") => { + Ok(Some(Self::TrailingSevenDays)) + } + Some("season") => Ok(Some(Self::Season)), + Some(_) => Err(ApiError::bad_request( + "window must be one of: daily, trailing-7d, season", + )), + } + } + + fn kind(self) -> &'static str { + match self { + Self::Daily => "daily", + Self::TrailingSevenDays => "trailing-7d", + Self::Season => "season", + } + } +} + +#[derive(Debug, Clone)] +struct CachedLeaderboardScope { + window: LeaderboardWindow, + season: Option, + game_type: String, + team_size: i16, + playlist: String, +} + +impl CachedLeaderboardScope { + fn from_filters(window: Option, filters: &ReplaySetFilters) -> Option { + let window = window?; + let only_standard_dimensions = filters.search_pattern.is_none() + && filters.player_name_patterns.is_empty() + && filters.replay_ids.is_empty() + && filters.file_sha256s.is_empty() + && filters.group_id.is_none() + && filters.project_id.is_none() + && filters.maps.is_empty() + && filters.pro.is_none() + && filters.uploader_user_id.is_none() + && filters.status.is_none() + && filters.created_after.is_none() + && filters.created_before.is_none() + && filters.replay_date_after.is_none() + && filters.replay_date_before.is_none() + && filters.min_rank_tier.is_none() + && filters.max_rank_tier.is_none() + && filters.rank_scope_player.is_none() + && filters.min_season_ord.is_none() + && filters.max_season_ord.is_none() + && filters.playlist_group_key.is_none() + && filters.player_outcome.is_none() + && filters.playlists.len() <= 1 + && filters.game_types.len() <= 1 + && filters.team_sizes.len() <= 1 + && filters.seasons.len() <= 1; + if !only_standard_dimensions { + return None; + } + if window != LeaderboardWindow::Season && !filters.seasons.is_empty() { + return None; + } + + Some(Self { + window, + season: filters.seasons.first().cloned(), + game_type: filters + .game_types + .first() + .cloned() + .unwrap_or_else(|| ALL_SCOPE.to_owned()), + team_size: filters + .team_sizes + .first() + .copied() + .and_then(|value| i16::try_from(value).ok()) + .unwrap_or(0), + playlist: filters + .playlists + .first() + .cloned() + .unwrap_or_else(|| ALL_SCOPE.to_owned()), + }) + } +} + +fn push_live_window_filter<'args>( + builder: &mut QueryBuilder<'args, Postgres>, + window: Option, + filters: &'args ReplaySetFilters, + replay_alias: &str, +) { + let Some(window) = window else { + return; + }; + match window { + LeaderboardWindow::Daily => { + builder.push(" AND COALESCE("); + builder.push(replay_alias); + builder.push(".replay_date, "); + builder.push(replay_alias); + builder.push( + ".created_at) >= date_trunc('day', now() AT TIME ZONE 'UTC') AT TIME ZONE 'UTC'", + ); + } + LeaderboardWindow::TrailingSevenDays => { + builder.push(" AND COALESCE("); + builder.push(replay_alias); + builder.push(".replay_date, "); + builder.push(replay_alias); + builder.push(".created_at) >= now() - interval '7 days'"); + } + LeaderboardWindow::Season if filters.seasons.is_empty() => { + builder.push(" AND lower(btrim("); + builder.push(replay_alias); + builder.push( + ".season)) = (SELECT lower(btrim(current_replay.season)) \ + FROM replays current_replay \ + WHERE current_replay.season IS NOT NULL \ + AND btrim(current_replay.season) <> '' \ + AND current_replay.canonical_analysis_run_id IS NOT NULL \ + ORDER BY COALESCE(current_replay.replay_date, current_replay.created_at) DESC \ + LIMIT 1)", + ); + } + LeaderboardWindow::Season => {} + } +} + +async fn cache_scope_available( + pool: &sqlx::PgPool, + scope: &CachedLeaderboardScope, +) -> Result { + let available = match scope.window { + LeaderboardWindow::Daily => { + sqlx::query_scalar::<_, bool>( + "SELECT EXISTS (SELECT 1 FROM leaderboard_cache_windows WHERE window_key = 'daily')", + ) + .fetch_one(pool) + .await? + } + LeaderboardWindow::TrailingSevenDays => { + sqlx::query_scalar::<_, bool>( + "SELECT EXISTS (SELECT 1 FROM leaderboard_cache_windows WHERE window_key = 'trailing-7d')", + ) + .fetch_one(pool) + .await? + } + LeaderboardWindow::Season => { + sqlx::query_scalar::<_, bool>( + "SELECT EXISTS (\ + SELECT 1 FROM leaderboard_cache_windows \ + WHERE window_kind = 'season' \ + AND (($1::text IS NULL AND is_current) OR season = $1))", + ) + .bind(scope.season.as_deref()) + .fetch_one(pool) + .await? + } + }; + Ok(available) +} + +fn push_cached_scope_filter<'args>( + builder: &mut QueryBuilder<'args, Postgres>, + scope: &'args CachedLeaderboardScope, + row_alias: &str, +) { + builder.push(" JOIN leaderboard_cache_windows cache_window ON cache_window.window_key = "); + builder.push(row_alias); + builder.push(".window_key WHERE cache_window.window_kind = "); + builder.push_bind(scope.window.kind()); + if scope.window == LeaderboardWindow::Season { + if let Some(season) = &scope.season { + builder.push(" AND cache_window.season = "); + builder.push_bind(season); + } else { + builder.push(" AND cache_window.is_current"); + } + } + builder.push(" AND "); + builder.push(row_alias); + builder.push(".scope_game_type = "); + builder.push_bind(&scope.game_type); + builder.push(" AND "); + builder.push(row_alias); + builder.push(".scope_team_size = "); + builder.push_bind(scope.team_size); + builder.push(" AND "); + builder.push(row_alias); + builder.push(".scope_playlist = "); + builder.push_bind(&scope.playlist); +} + impl LeaderboardPaging { fn from_params(params: &QueryParams) -> Result { let count = params @@ -67,12 +281,20 @@ impl LeaderboardPaging { fn parse_filters( raw_query: Option<&str>, auth_user_id: Option, -) -> Result<(ReplaySetFilters, LeaderboardPaging), ApiError> { +) -> Result< + ( + ReplaySetFilters, + LeaderboardPaging, + Option, + ), + ApiError, +> { let params = QueryParams::from_raw(raw_query); let paging = LeaderboardPaging::from_params(¶ms)?; + let window = LeaderboardWindow::from_params(¶ms)?; let input = ReplaySetFilterInput::from_query_params(¶ms)?; let filters = ReplaySetFilters::from_input(input, auth_user_id)?; - Ok((filters, paging)) + Ok((filters, paging, window)) } #[derive(Debug, Serialize, ToSchema)] @@ -119,6 +341,7 @@ pub struct AppearancesLeaderboardRowResponse { path = "/api/v1/leaderboards/uploads", tag = "leaderboards", params( + ("window" = Option, Query, description = "Standard cached window: daily, trailing-7d, or season"), ("game-type" = Option>, Query, description = "Competitive context filter (ranked, casual, tournament, ...)"), ("team-size" = Option>, Query, description = "Team size filter (1-4 or 1v1/2v2/3v3/4v4)"), ("playlist" = Option>, Query, description = "Playlist/game-mode filter"), @@ -140,11 +363,12 @@ pub async fn get_uploads_leaderboard( RawQuery(raw_query): RawQuery, ) -> Result, ApiError> { let db = require_db(&state)?; - let (filters, paging) = parse_filters(raw_query.as_deref(), auth_user.as_ref().map(|u| u.id))?; + let (filters, paging, window) = + parse_filters(raw_query.as_deref(), auth_user.as_ref().map(|u| u.id))?; let (total, rows) = tokio::try_join!( - load_uploads_total(db, &filters), - load_uploads_rows(db, &filters, &paging), + load_uploads_total(db, &filters, window), + load_uploads_rows(db, &filters, window, &paging), ) .map_err(ApiError::internal)?; @@ -163,6 +387,7 @@ pub async fn get_uploads_leaderboard( path = "/api/v1/leaderboards/appearances", tag = "leaderboards", params( + ("window" = Option, Query, description = "Standard cached window: daily, trailing-7d, or season"), ("game-type" = Option>, Query, description = "Competitive context filter (ranked, casual, tournament, ...)"), ("team-size" = Option>, Query, description = "Team size filter (1-4 or 1v1/2v2/3v3/4v4)"), ("playlist" = Option>, Query, description = "Playlist/game-mode filter"), @@ -184,11 +409,21 @@ pub async fn get_appearances_leaderboard( RawQuery(raw_query): RawQuery, ) -> Result, ApiError> { let db = require_db(&state)?; - let (filters, paging) = parse_filters(raw_query.as_deref(), auth_user.as_ref().map(|u| u.id))?; + let (filters, paging, window) = + parse_filters(raw_query.as_deref(), auth_user.as_ref().map(|u| u.id))?; + let mut cached_scope = CachedLeaderboardScope::from_filters(window, &filters); + if let Some(scope) = &cached_scope { + if !cache_scope_available(db, scope) + .await + .map_err(ApiError::internal)? + { + cached_scope = None; + } + } let (total, rows) = tokio::try_join!( - load_appearances_total(db, &filters), - load_appearances_rows(db, &filters, &paging), + load_appearances_total(db, &filters, window, cached_scope.as_ref()), + load_appearances_rows(db, &filters, window, cached_scope.as_ref(), &paging), ) .map_err(ApiError::internal)?; @@ -205,8 +440,9 @@ pub async fn get_appearances_leaderboard( async fn load_uploads_total( pool: &sqlx::PgPool, filters: &ReplaySetFilters, + window: Option, ) -> Result { - let total: i64 = uploads_total_query(filters) + let total: i64 = uploads_total_query(filters, window) .build() .fetch_one(pool) .await? @@ -217,9 +453,10 @@ async fn load_uploads_total( async fn load_uploads_rows( pool: &sqlx::PgPool, filters: &ReplaySetFilters, + window: Option, paging: &LeaderboardPaging, ) -> Result, sqlx::Error> { - let rows = uploads_rows_query(filters, paging) + let rows = uploads_rows_query(filters, window, paging) .build() .fetch_all(pool) .await?; @@ -238,17 +475,22 @@ async fn load_uploads_rows( .collect::, sqlx::Error>>() } -fn uploads_total_query(filters: &ReplaySetFilters) -> QueryBuilder<'_, Postgres> { +fn uploads_total_query( + filters: &ReplaySetFilters, + window: Option, +) -> QueryBuilder<'_, Postgres> { let mut builder = QueryBuilder::::new( "SELECT COUNT(DISTINCT r.uploaded_by_user_id) AS total FROM replays r \ WHERE r.uploaded_by_user_id IS NOT NULL", ); append_replay_set_filters(&mut builder, filters, "r"); + push_live_window_filter(&mut builder, window, filters, "r"); builder } fn uploads_rows_query<'args>( filters: &'args ReplaySetFilters, + window: Option, paging: &LeaderboardPaging, ) -> QueryBuilder<'args, Postgres> { let mut builder = QueryBuilder::::new( @@ -258,6 +500,7 @@ fn uploads_rows_query<'args>( WHERE r.uploaded_by_user_id IS NOT NULL", ); append_replay_set_filters(&mut builder, filters, "r"); + push_live_window_filter(&mut builder, window, filters, "r"); builder.push( " GROUP BY r.uploaded_by_user_id, u.display_name \ ORDER BY upload_count DESC, u.display_name ASC NULLS LAST, r.uploaded_by_user_id \ @@ -272,24 +515,34 @@ fn uploads_rows_query<'args>( async fn load_appearances_total( pool: &sqlx::PgPool, filters: &ReplaySetFilters, + window: Option, + cached_scope: Option<&CachedLeaderboardScope>, ) -> Result { - let total: i64 = appearances_total_query(filters) - .build() - .fetch_one(pool) - .await? - .try_get("total")?; + let total: i64 = match cached_scope { + Some(scope) => cached_appearances_total_query(scope), + None => appearances_total_query(filters, window), + } + .build() + .fetch_one(pool) + .await? + .try_get("total")?; Ok(total.max(0) as u64) } async fn load_appearances_rows( pool: &sqlx::PgPool, filters: &ReplaySetFilters, + window: Option, + cached_scope: Option<&CachedLeaderboardScope>, paging: &LeaderboardPaging, ) -> Result, sqlx::Error> { - let rows = appearances_rank_query(filters, paging) - .build() - .fetch_all(pool) - .await?; + let rows = match cached_scope { + Some(scope) => cached_appearances_rank_query(scope, paging), + None => appearances_rank_query(filters, window, paging), + } + .build() + .fetch_all(pool) + .await?; let mut entries = rows .into_iter() @@ -317,7 +570,7 @@ async fn load_appearances_rows( .iter() .map(|entry| (entry.platform.clone(), entry.platform_player_id.clone())) .collect(); - let profiles = load_player_profiles(pool, &pairs, filters).await?; + let profiles = load_player_profiles(pool, &pairs, filters, window).await?; for entry in &mut entries { if let Some(profile) = profiles.get(&(entry.platform.clone(), entry.platform_player_id.clone())) @@ -350,6 +603,7 @@ async fn load_player_profiles( pool: &sqlx::PgPool, pairs: &[PlayerKey], filters: &ReplaySetFilters, + window: Option, ) -> Result, sqlx::Error> { if pairs.is_empty() { return Ok(std::collections::HashMap::new()); @@ -369,7 +623,7 @@ async fn load_player_profiles( builder.push(" GROUP BY rp.platform, rp.platform_player_id"); let rows = builder.build().fetch_all(pool).await?; - let estimated_ranks = load_estimated_player_ranks(pool, pairs, filters).await?; + let estimated_ranks = load_estimated_player_ranks(pool, pairs, filters, window).await?; let mut profiles = HashMap::with_capacity(rows.len()); for row in rows { let platform: String = row.try_get("platform")?; @@ -400,6 +654,7 @@ async fn load_estimated_player_ranks( pool: &sqlx::PgPool, pairs: &[PlayerKey], filters: &ReplaySetFilters, + window: Option, ) -> Result, sqlx::Error> { let playlist_ids = rank_playlist_ids_for_filters(filters); if playlist_ids.len() != 1 { @@ -432,6 +687,7 @@ async fn load_estimated_player_ranks( ); builder.push_bind(playlist_ids[0]); append_replay_set_filters(&mut builder, filters, "r"); + push_live_window_filter(&mut builder, window, filters, "r"); builder.push( " ORDER BY s.platform_player_id, \ COALESCE(r.replay_date, r.created_at) DESC NULLS LAST, s.updated_at DESC", @@ -505,8 +761,9 @@ fn ranked_playlist_id_for_team_size(team_size: i32) -> Option { fn append_appearances_from_where<'args>( builder: &mut QueryBuilder<'args, Postgres>, filters: &'args ReplaySetFilters, + window: Option, ) { - if filters.is_empty() { + if filters.is_empty() && window.is_none() { builder.push( " FROM replay_players rp \ WHERE rp.platform IS NOT NULL AND btrim(rp.platform) <> '' \ @@ -523,10 +780,12 @@ fn append_appearances_from_where<'args>( ); push_aggregate_excluded_player_filter(builder, "rp.platform", "rp.platform_player_id"); append_replay_set_filters(builder, filters, "r"); + push_live_window_filter(builder, window, filters, "r"); } fn appearances_rank_query<'args>( filters: &'args ReplaySetFilters, + window: Option, paging: &LeaderboardPaging, ) -> QueryBuilder<'args, Postgres> { // Deliberately lean: only the columns the existing @@ -538,7 +797,7 @@ fn appearances_rank_query<'args>( "SELECT rp.platform AS platform, rp.platform_player_id AS platform_player_id, \ COUNT(DISTINCT rp.replay_id) AS appearance_count", ); - append_appearances_from_where(&mut builder, filters); + append_appearances_from_where(&mut builder, filters, window); builder.push( " GROUP BY rp.platform, rp.platform_player_id \ ORDER BY appearance_count DESC, rp.platform, rp.platform_player_id \ @@ -550,13 +809,43 @@ fn appearances_rank_query<'args>( builder } -fn appearances_total_query(filters: &ReplaySetFilters) -> QueryBuilder<'_, Postgres> { +fn appearances_total_query( + filters: &ReplaySetFilters, + window: Option, +) -> QueryBuilder<'_, Postgres> { let mut builder = QueryBuilder::::new("SELECT COUNT(*) AS total FROM (SELECT 1"); - append_appearances_from_where(&mut builder, filters); + append_appearances_from_where(&mut builder, filters, window); builder.push(" GROUP BY rp.platform, rp.platform_player_id) ranked_players"); builder } +fn cached_appearances_rank_query<'args>( + scope: &'args CachedLeaderboardScope, + paging: &LeaderboardPaging, +) -> QueryBuilder<'args, Postgres> { + let mut builder = QueryBuilder::::new( + "SELECT cached.platform, cached.platform_player_id, \ + cached.replay_count AS appearance_count \ + FROM leaderboard_player_window_totals cached", + ); + push_cached_scope_filter(&mut builder, scope, "cached"); + builder.push( + " ORDER BY cached.replay_count DESC, cached.platform, cached.platform_player_id LIMIT ", + ); + builder.push_bind(i64::from(paging.count)); + builder.push(" OFFSET "); + builder.push_bind(i64::from(paging.offset)); + builder +} + +fn cached_appearances_total_query(scope: &CachedLeaderboardScope) -> QueryBuilder<'_, Postgres> { + let mut builder = QueryBuilder::::new( + "SELECT COUNT(*) AS total FROM leaderboard_player_window_totals cached", + ); + push_cached_scope_filter(&mut builder, scope, "cached"); + builder +} + // --------------------------------------------------------------------------- // Event leaderboard: rank players by an arbitrary event type, per unit time, // under arbitrary replay filters. @@ -648,6 +937,7 @@ pub struct EventLeaderboardRowResponse { #[derive(Debug, Clone)] struct EventLeaderboardFilters { replay: ReplaySetFilters, + window: Option, stat_terms: Vec, sort: EventSort, min_games: i64, @@ -660,6 +950,7 @@ impl EventLeaderboardFilters { ) -> Result<(Self, LeaderboardPaging), ApiError> { let params = QueryParams::from_raw(raw_query); let paging = LeaderboardPaging::from_params(¶ms)?; + let window = LeaderboardWindow::from_params(¶ms)?; let replay = ReplaySetFilters::from_input( ReplaySetFilterInput::from_query_params(¶ms)?, auth_user_id, @@ -680,6 +971,7 @@ impl EventLeaderboardFilters { Ok(( Self { replay, + window, stat_terms, sort, min_games, @@ -707,6 +999,14 @@ impl EventLeaderboardFilters { _ => EventCountSource::AnySubject, } } + + fn qualifying_min_games(&self) -> i64 { + if self.sort == EventSort::PerMinute { + self.min_games + } else { + 1 + } + } } #[utoipa::path( @@ -714,6 +1014,7 @@ impl EventLeaderboardFilters { path = "/api/v1/leaderboards/event", tag = "leaderboards", params( + ("window" = Option, Query, description = "Standard cached window: daily, trailing-7d, or season"), ("event-type" = Option>, Query, description = "Event-type filter (alias stat-term); fuzzy-matches event_types key/display/category. Empty = all user-facing events"), ("sort" = Option, Query, description = "Ranking metric: total (default), per-game, or per-minute"), ("min-games" = Option, Query, description = "Minimum replay appearances to qualify (default 1)"), @@ -743,14 +1044,32 @@ pub async fn get_event_leaderboard( auth_user.as_ref().map(|u| u.id), )?; - let (total, rows, matched) = tokio::try_join!( - load_event_total(db, &filters), - load_event_rows(db, &filters, &paging), - async { - resolve_matched_event_types(db, &filters.stat_terms) - .await - .map_err(ApiError::internal) - }, + let matched = resolve_matched_event_types(db, &filters.stat_terms) + .await + .map_err(ApiError::internal)?; + let mut cached_scope = CachedLeaderboardScope::from_filters(filters.window, &filters.replay); + if let Some(scope) = &cached_scope { + if !cache_scope_available(db, scope) + .await + .map_err(ApiError::internal)? + { + cached_scope = None; + } + } + let cached_metric_key = (matched.len() == 1).then(|| matched[0].key.as_str()); + let use_cache = cached_scope.is_some() + && cached_metric_key.is_some() + && matches!(filters.sort, EventSort::Total | EventSort::PerMinute); + let cached_scope_ref = if use_cache { + cached_scope.as_ref() + } else { + None + }; + let cached_metric_key = if use_cache { cached_metric_key } else { None }; + + let (total, rows) = tokio::try_join!( + load_event_total(db, &filters, cached_scope_ref, cached_metric_key), + load_event_rows(db, &filters, cached_scope_ref, cached_metric_key, &paging,), )?; let next_offset = paging.next_offset(rows.len(), total); @@ -774,27 +1093,39 @@ pub async fn get_event_leaderboard( async fn load_event_total( pool: &sqlx::PgPool, filters: &EventLeaderboardFilters, + cached_scope: Option<&CachedLeaderboardScope>, + cached_metric_key: Option<&str>, ) -> Result { - let total: i64 = event_total_query(filters) - .build() - .fetch_one(pool) - .await - .map_err(ApiError::internal)? - .try_get("total") - .map_err(ApiError::internal)?; + let total: i64 = match (cached_scope, cached_metric_key) { + (Some(scope), Some(metric_key)) => cached_event_total_query(filters, scope, metric_key), + _ => event_total_query(filters), + } + .build() + .fetch_one(pool) + .await + .map_err(ApiError::internal)? + .try_get("total") + .map_err(ApiError::internal)?; Ok(total.max(0) as u64) } async fn load_event_rows( pool: &sqlx::PgPool, filters: &EventLeaderboardFilters, + cached_scope: Option<&CachedLeaderboardScope>, + cached_metric_key: Option<&str>, paging: &LeaderboardPaging, ) -> Result, ApiError> { - let rows = event_rank_query(filters, paging) - .build() - .fetch_all(pool) - .await - .map_err(ApiError::internal)?; + let rows = match (cached_scope, cached_metric_key) { + (Some(scope), Some(metric_key)) => { + cached_event_rank_query(filters, scope, metric_key, paging) + } + _ => event_rank_query(filters, paging), + } + .build() + .fetch_all(pool) + .await + .map_err(ApiError::internal)?; let mut entries = rows .into_iter() @@ -825,7 +1156,7 @@ async fn load_event_rows( .iter() .map(|entry| (entry.platform.clone(), entry.platform_player_id.clone())) .collect(); - let profiles = load_player_profiles(pool, &pairs, &filters.replay) + let profiles = load_player_profiles(pool, &pairs, &filters.replay, filters.window) .await .map_err(ApiError::internal)?; for entry in &mut entries { @@ -869,6 +1200,7 @@ fn push_event_ctes<'args>( ); push_aggregate_excluded_player_filter(builder, "rp.platform", "rp.platform_player_id"); append_replay_set_filters(builder, &filters.replay, "r"); + push_live_window_filter(builder, filters.window, &filters.replay, "r"); builder.push( " GROUP BY rp.platform, rp.platform_player_id \ HAVING COALESCE(SUM(rp.", @@ -889,6 +1221,7 @@ fn push_event_ctes<'args>( ); push_aggregate_excluded_player_filter(builder, "rp.platform", "rp.platform_player_id"); append_replay_set_filters(builder, &filters.replay, "r"); + push_live_window_filter(builder, filters.window, &filters.replay, "r"); builder.push(" GROUP BY rp.platform, rp.platform_player_id)"); return; } @@ -920,6 +1253,7 @@ fn push_event_ctes<'args>( ); push_aggregate_excluded_player_filter(builder, "rp.platform", "rp.platform_player_id"); append_replay_set_filters(builder, &filters.replay, "r"); + push_live_window_filter(builder, filters.window, &filters.replay, "r"); builder.push( " GROUP BY rp.platform, rp.platform_player_id), \ denominators AS (\ @@ -935,6 +1269,7 @@ fn push_event_ctes<'args>( ); push_aggregate_excluded_player_filter(builder, "rp.platform", "rp.platform_player_id"); append_replay_set_filters(builder, &filters.replay, "r"); + push_live_window_filter(builder, filters.window, &filters.replay, "r"); builder.push(" GROUP BY rp.platform, rp.platform_player_id)"); } @@ -955,7 +1290,7 @@ fn event_rank_query<'args>( JOIN denominators d ON d.platform = e.platform AND d.platform_player_id = e.platform_player_id \ WHERE d.replay_count >= ", ); - builder.push_bind(filters.min_games); + builder.push_bind(filters.qualifying_min_games()); builder.push(" ORDER BY "); builder.push(filters.sort.order_sql()); builder.push(", e.platform, e.platform_player_id LIMIT "); @@ -973,7 +1308,59 @@ fn event_total_query(filters: &EventLeaderboardFilters) -> QueryBuilder<'_, Post JOIN denominators d ON d.platform = e.platform AND d.platform_player_id = e.platform_player_id \ WHERE d.replay_count >= ", ); - builder.push_bind(filters.min_games); + builder.push_bind(filters.qualifying_min_games()); + builder +} + +fn cached_event_rank_query<'args>( + filters: &'args EventLeaderboardFilters, + scope: &'args CachedLeaderboardScope, + metric_key: &'args str, + paging: &LeaderboardPaging, +) -> QueryBuilder<'args, Postgres> { + let mut builder = QueryBuilder::::new( + "SELECT cached.platform, cached.platform_player_id, \ + ROUND(cached.total_value)::bigint AS event_count, \ + cached.replay_count, cached.active_time_seconds, \ + cached.total_value / NULLIF(cached.replay_count, 0) AS count_per_game, \ + cached.value_per_5_minutes / 5.0 AS per_active_minute \ + FROM leaderboard_player_window_metrics cached", + ); + push_cached_scope_filter(&mut builder, scope, "cached"); + builder.push(" AND cached.metric_kind = 'event' AND cached.metric_key = "); + builder.push_bind(metric_key); + if filters.sort == EventSort::PerMinute { + builder.push(" AND cached.replay_count >= "); + builder.push_bind(filters.min_games); + } + match filters.sort { + EventSort::Total => builder.push(" ORDER BY cached.total_value DESC"), + EventSort::PerMinute => builder + .push(" ORDER BY cached.value_per_5_minutes DESC NULLS LAST, cached.total_value DESC"), + EventSort::PerGame => unreachable!("per-game event rankings use the live query"), + }; + builder.push(", cached.platform, cached.platform_player_id LIMIT "); + builder.push_bind(i64::from(paging.count)); + builder.push(" OFFSET "); + builder.push_bind(i64::from(paging.offset)); + builder +} + +fn cached_event_total_query<'args>( + filters: &'args EventLeaderboardFilters, + scope: &'args CachedLeaderboardScope, + metric_key: &'args str, +) -> QueryBuilder<'args, Postgres> { + let mut builder = QueryBuilder::::new( + "SELECT COUNT(*) AS total FROM leaderboard_player_window_metrics cached", + ); + push_cached_scope_filter(&mut builder, scope, "cached"); + builder.push(" AND cached.metric_kind = 'event' AND cached.metric_key = "); + builder.push_bind(metric_key); + if filters.sort == EventSort::PerMinute { + builder.push(" AND cached.replay_count >= "); + builder.push_bind(filters.min_games); + } builder } @@ -1375,6 +1762,7 @@ pub struct StatLeaderboardRowResponse { #[derive(Debug, Clone)] struct StatLeaderboardFilters { replay: ReplaySetFilters, + window: Option, metric: StatLeaderboardMetric, sort: StatLeaderboardSort, min_games: i64, @@ -1387,6 +1775,7 @@ impl StatLeaderboardFilters { ) -> Result<(Self, LeaderboardPaging), ApiError> { let params = QueryParams::from_raw(raw_query); let paging = LeaderboardPaging::from_params(¶ms)?; + let window = LeaderboardWindow::from_params(¶ms)?; let replay = ReplaySetFilters::from_input( ReplaySetFilterInput::from_query_params(¶ms)?, auth_user_id, @@ -1408,6 +1797,7 @@ impl StatLeaderboardFilters { Ok(( Self { replay, + window, metric, sort, min_games, @@ -1415,6 +1805,14 @@ impl StatLeaderboardFilters { paging, )) } + + fn qualifying_min_games(&self) -> i64 { + if self.sort == StatLeaderboardSort::PerMinute { + self.min_games + } else { + 1 + } + } } #[utoipa::path( @@ -1422,6 +1820,7 @@ impl StatLeaderboardFilters { path = "/api/v1/leaderboards/stat", tag = "leaderboards", params( + ("window" = Option, Query, description = "Standard cached window: daily, trailing-7d, or season"), ("stat" = Option, Query, description = "Materialized stat metric: ball-opponent-half (default), possession-time, ball-advance, touches-per-possession, avg-possession-duration, high-aerial-touch-count, control-touch-count, big-boost-pad-count, small-boost-pad-count, big-boost-amount, or small-boost-amount"), ("sort" = Option, Query, description = "Ranking metric: total (default), per-game, per-minute, share, or average"), ("min-games" = Option, Query, description = "Minimum replay appearances to qualify (default 1)"), @@ -1448,10 +1847,29 @@ pub async fn get_stat_leaderboard( let db = require_db(&state)?; let (filters, paging) = StatLeaderboardFilters::from_query(raw_query.as_deref(), auth_user.as_ref().map(|u| u.id))?; + let mut cached_scope = CachedLeaderboardScope::from_filters(filters.window, &filters.replay); + if let Some(scope) = &cached_scope { + if !cache_scope_available(db, scope) + .await + .map_err(ApiError::internal)? + { + cached_scope = None; + } + } + let use_cache = cached_scope.is_some() + && matches!( + filters.sort, + StatLeaderboardSort::Total | StatLeaderboardSort::PerMinute + ); + let cached_scope = if use_cache { + cached_scope.as_ref() + } else { + None + }; let (total, rows) = tokio::try_join!( - load_stat_total(db, &filters), - load_stat_rows(db, &filters, &paging), + load_stat_total(db, &filters, cached_scope), + load_stat_rows(db, &filters, cached_scope, &paging), )?; let next_offset = paging.next_offset(rows.len(), total); @@ -1474,27 +1892,35 @@ pub async fn get_stat_leaderboard( async fn load_stat_total( pool: &sqlx::PgPool, filters: &StatLeaderboardFilters, + cached_scope: Option<&CachedLeaderboardScope>, ) -> Result { - let total: i64 = stat_total_query(filters) - .build() - .fetch_one(pool) - .await - .map_err(ApiError::internal)? - .try_get("total") - .map_err(ApiError::internal)?; + let total: i64 = match cached_scope { + Some(scope) => cached_stat_total_query(filters, scope), + None => stat_total_query(filters), + } + .build() + .fetch_one(pool) + .await + .map_err(ApiError::internal)? + .try_get("total") + .map_err(ApiError::internal)?; Ok(total.max(0) as u64) } async fn load_stat_rows( pool: &sqlx::PgPool, filters: &StatLeaderboardFilters, + cached_scope: Option<&CachedLeaderboardScope>, paging: &LeaderboardPaging, ) -> Result, ApiError> { - let rows = stat_rank_query(filters, paging) - .build() - .fetch_all(pool) - .await - .map_err(ApiError::internal)?; + let rows = match cached_scope { + Some(scope) => cached_stat_rank_query(filters, scope, paging), + None => stat_rank_query(filters, paging), + } + .build() + .fetch_all(pool) + .await + .map_err(ApiError::internal)?; let mut entries = rows .into_iter() @@ -1528,7 +1954,7 @@ async fn load_stat_rows( .iter() .map(|entry| (entry.platform.clone(), entry.platform_player_id.clone())) .collect(); - let profiles = load_player_profiles(pool, &pairs, &filters.replay) + let profiles = load_player_profiles(pool, &pairs, &filters.replay, filters.window) .await .map_err(ApiError::internal)?; for entry in &mut entries { @@ -1582,6 +2008,7 @@ fn push_stat_fact_cte<'args>( "possession.platform_player_id", ); append_replay_set_filters(builder, &filters.replay, "r"); + push_live_window_filter(builder, filters.window, &filters.replay, "r"); builder.push( " GROUP BY possession.platform, possession.platform_player_id \ HAVING SUM(possession.possession_count) > 0)", @@ -1615,6 +2042,7 @@ fn push_stat_fact_cte<'args>( "boost.platform_player_id", ); append_replay_set_filters(builder, &filters.replay, "r"); + push_live_window_filter(builder, filters.window, &filters.replay, "r"); builder.push( " GROUP BY boost.platform, boost.platform_player_id \ HAVING COALESCE(SUM(", @@ -1639,6 +2067,7 @@ fn push_stat_fact_cte<'args>( builder.push_bind(definition.fact_key()); push_aggregate_excluded_player_filter(builder, "fact.platform", "fact.platform_player_id"); append_replay_set_filters(builder, &filters.replay, "r"); + push_live_window_filter(builder, filters.window, &filters.replay, "r"); builder.push( " GROUP BY fact.platform, fact.platform_player_id \ HAVING COALESCE(SUM(fact.value), 0.0) > 0)", @@ -1675,7 +2104,7 @@ fn stat_rank_query<'args>( " FROM metric_values m \ WHERE m.replay_count >= ", ); - builder.push_bind(filters.min_games); + builder.push_bind(filters.qualifying_min_games()); builder.push(" ORDER BY "); builder.push(filters.sort.order_sql()); builder.push(", m.platform, m.platform_player_id LIMIT "); @@ -1692,6 +2121,57 @@ fn stat_total_query(filters: &StatLeaderboardFilters) -> QueryBuilder<'_, Postgr " SELECT COUNT(*) AS total FROM metric_values m \ WHERE m.replay_count >= ", ); - builder.push_bind(filters.min_games); + builder.push_bind(filters.qualifying_min_games()); + builder +} + +fn cached_stat_rank_query<'args>( + filters: &'args StatLeaderboardFilters, + scope: &'args CachedLeaderboardScope, + paging: &LeaderboardPaging, +) -> QueryBuilder<'args, Postgres> { + let mut builder = QueryBuilder::::new( + "SELECT cached.platform, cached.platform_player_id, \ + cached.total_value AS value, cached.replay_count, \ + cached.active_time_seconds, cached.sample_count, \ + cached.total_value / NULLIF(cached.replay_count, 0) AS value_per_game, \ + cached.value_per_5_minutes / 5.0 AS value_per_active_minute, \ + NULL::float8 AS share_of_active_time \ + FROM leaderboard_player_window_metrics cached", + ); + push_cached_scope_filter(&mut builder, scope, "cached"); + builder.push(" AND cached.metric_kind = 'stat' AND cached.metric_key = "); + builder.push_bind(filters.metric.definition().key); + if filters.sort == StatLeaderboardSort::PerMinute { + builder.push(" AND cached.replay_count >= "); + builder.push_bind(filters.min_games); + } + match filters.sort { + StatLeaderboardSort::Total => builder.push(" ORDER BY cached.total_value DESC"), + StatLeaderboardSort::PerMinute => builder + .push(" ORDER BY cached.value_per_5_minutes DESC NULLS LAST, cached.total_value DESC"), + _ => unreachable!("unsupported cached stat sort uses the live query"), + }; + builder.push(", cached.platform, cached.platform_player_id LIMIT "); + builder.push_bind(i64::from(paging.count)); + builder.push(" OFFSET "); + builder.push_bind(i64::from(paging.offset)); + builder +} + +fn cached_stat_total_query<'args>( + filters: &'args StatLeaderboardFilters, + scope: &'args CachedLeaderboardScope, +) -> QueryBuilder<'args, Postgres> { + let mut builder = QueryBuilder::::new( + "SELECT COUNT(*) AS total FROM leaderboard_player_window_metrics cached", + ); + push_cached_scope_filter(&mut builder, scope, "cached"); + builder.push(" AND cached.metric_kind = 'stat' AND cached.metric_key = "); + builder.push_bind(filters.metric.definition().key); + if filters.sort == StatLeaderboardSort::PerMinute { + builder.push(" AND cached.replay_count >= "); + builder.push_bind(filters.min_games); + } builder } diff --git a/crates/rocket-sense-server/src/api/leaderboards_tests.rs b/crates/rocket-sense-server/src/api/leaderboards_tests.rs index ca8fa7ce..1cf80620 100644 --- a/crates/rocket-sense-server/src/api/leaderboards_tests.rs +++ b/crates/rocket-sense-server/src/api/leaderboards_tests.rs @@ -53,7 +53,7 @@ fn uploads_rows_query_groups_and_paginates() { count: 25, offset: 50, }; - let sql = uploads_rows_query(&filters, &paging).into_sql(); + let sql = uploads_rows_query(&filters, None, &paging).into_sql(); assert!(sql.contains("FROM replays r JOIN users u ON u.id = r.uploaded_by_user_id")); assert!(sql.contains("r.uploaded_by_user_id IS NOT NULL")); @@ -69,7 +69,7 @@ fn uploads_rows_query_groups_and_paginates() { #[test] fn uploads_total_query_counts_distinct_uploaders() { let filters = filters_from_query(""); - let sql = uploads_total_query(&filters).into_sql(); + let sql = uploads_total_query(&filters, None).into_sql(); assert!(sql.contains("COUNT(DISTINCT r.uploaded_by_user_id)")); assert!(sql.contains("r.uploaded_by_user_id IS NOT NULL")); assert!(sql.contains("NOT r.exclude_from_aggregates")); @@ -82,7 +82,7 @@ fn appearances_rank_query_counts_distinct_replays() { count: 50, offset: 0, }; - let sql = appearances_rank_query(&filters, &paging).into_sql(); + let sql = appearances_rank_query(&filters, None, &paging).into_sql(); assert!(sql.contains("COUNT(DISTINCT rp.replay_id) AS appearance_count")); assert!(sql.contains("FROM replay_players rp JOIN replays r ON r.id = rp.replay_id")); @@ -101,7 +101,7 @@ fn appearances_rank_query_joins_replays_for_default_incomplete_game_exclusion() count: 50, offset: 0, }; - let sql = appearances_rank_query(&filters, &paging).into_sql(); + let sql = appearances_rank_query(&filters, None, &paging).into_sql(); assert!(sql.contains("FROM replay_players rp JOIN replays r ON r.id = rp.replay_id")); assert!(sql.contains("NOT r.exclude_from_aggregates")); @@ -117,7 +117,7 @@ fn appearances_rank_query_omits_replays_join_when_incomplete_games_are_explicitl count: 50, offset: 0, }; - let sql = appearances_rank_query(&filters, &paging).into_sql(); + let sql = appearances_rank_query(&filters, None, &paging).into_sql(); assert!(sql.contains("FROM replay_players rp WHERE")); assert!(!sql.contains("JOIN replays")); @@ -130,7 +130,7 @@ fn appearances_rank_query_omits_replays_join_when_incomplete_games_are_explicitl #[test] fn appearances_total_query_wraps_grouped_subquery() { let filters = filters_from_query(""); - let sql = appearances_total_query(&filters).into_sql(); + let sql = appearances_total_query(&filters, None).into_sql(); assert!(sql.contains("SELECT COUNT(*) AS total FROM (SELECT 1")); assert!(sql.contains("GROUP BY rp.platform, rp.platform_player_id) ranked_players")); } @@ -144,7 +144,7 @@ fn appearances_rank_query_rejects_invalid_game_type() { #[test] fn leaderboard_filters_parse_exact_season_and_replay_date_range() { - let (filters, _) = parse_filters( + let (filters, _, _) = parse_filters( Some( "season=f18&replay-date-after=2026-01-01T00%3A00%3A00Z&replay-date-before=2026-01-31T23%3A59%3A59.999Z", ), @@ -157,6 +157,42 @@ fn leaderboard_filters_parse_exact_season_and_replay_date_range() { assert!(filters.replay_date_before.is_some()); } +#[test] +fn leaderboard_window_parses_standard_windows() { + for (raw, expected) in [ + ("window=daily", LeaderboardWindow::Daily), + ("window=trailing-7d", LeaderboardWindow::TrailingSevenDays), + ("window=season", LeaderboardWindow::Season), + ] { + let params = QueryParams::from_raw(Some(raw)); + assert_eq!( + LeaderboardWindow::from_params(¶ms).unwrap(), + Some(expected) + ); + } + + let params = QueryParams::from_raw(Some("window=forever")); + assert!(LeaderboardWindow::from_params(¶ms).is_err()); +} + +#[test] +fn cached_scope_accepts_only_single_standard_dimensions() { + let filters = filters_from_query("game-type=ranked&team-size=2&playlist=ranked-doubles"); + let scope = + CachedLeaderboardScope::from_filters(Some(LeaderboardWindow::TrailingSevenDays), &filters) + .expect("standard scope should use the cache"); + assert_eq!(scope.game_type, "ranked"); + assert_eq!(scope.team_size, 2); + assert_eq!(scope.playlist, "ranked-doubles"); + + let filters = filters_from_query("game-type=ranked&game-type=casual"); + assert!(CachedLeaderboardScope::from_filters( + Some(LeaderboardWindow::TrailingSevenDays), + &filters + ) + .is_none()); +} + #[test] fn leaderboard_rank_playlist_ids_use_ranked_playlist_filter() { let filters = filters_from_query("playlist=ranked-doubles"); @@ -324,6 +360,30 @@ fn event_total_query_counts_qualifying_players() { assert!(sql.contains("d.replay_count >= ")); } +#[test] +fn cached_event_rate_query_is_an_ordered_player_window_read() { + let (filters, paging) = event_filters( + "window=trailing-7d&event-type=goal&sort=per-minute&min-games=10&game-type=ranked&team-size=2", + ); + let scope = CachedLeaderboardScope::from_filters(filters.window, &filters.replay).unwrap(); + let sql = cached_event_rank_query(&filters, &scope, "goal", &paging).into_sql(); + + assert!(sql.contains("FROM leaderboard_player_window_metrics cached")); + assert!(sql.contains("cache_window.window_kind")); + assert!(sql.contains("cached.metric_kind = 'event'")); + assert!(sql.contains("cached.replay_count >=")); + assert!(sql.contains("ORDER BY cached.value_per_5_minutes DESC NULLS LAST")); + assert!(!sql.contains("GROUP BY")); +} + +#[test] +fn event_min_games_only_changes_per_five_minute_eligibility() { + let (total, _) = event_filters("sort=total&min-games=50"); + assert_eq!(total.qualifying_min_games(), 1); + let (rate, _) = event_filters("sort=per-minute&min-games=50"); + assert_eq!(rate.qualifying_min_games(), 50); +} + fn stat_filters(raw_query: &str) -> (StatLeaderboardFilters, LeaderboardPaging) { StatLeaderboardFilters::from_query(Some(raw_query), None).expect("filters should parse") } @@ -518,3 +578,26 @@ fn stat_rank_query_reads_average_possession_duration() { assert!(sql.contains("SUM(possession.duration_seconds)::float8")); assert!(sql.contains("ORDER BY value DESC")); } + +#[test] +fn cached_stat_rate_query_is_an_ordered_player_window_read() { + let (filters, paging) = + stat_filters("window=season&season=f23&stat=possession-time&sort=per-minute&min-games=25"); + let scope = CachedLeaderboardScope::from_filters(filters.window, &filters.replay).unwrap(); + let sql = cached_stat_rank_query(&filters, &scope, &paging).into_sql(); + + assert!(sql.contains("FROM leaderboard_player_window_metrics cached")); + assert!(sql.contains("cache_window.season")); + assert!(sql.contains("cached.metric_kind = 'stat'")); + assert!(sql.contains("cached.replay_count >=")); + assert!(sql.contains("ORDER BY cached.value_per_5_minutes DESC NULLS LAST")); + assert!(!sql.contains("GROUP BY")); +} + +#[test] +fn stat_min_games_only_changes_per_five_minute_eligibility() { + let (total, _) = stat_filters("sort=total&min-games=50"); + assert_eq!(total.qualifying_min_games(), 1); + let (rate, _) = stat_filters("sort=per-minute&min-games=50"); + assert_eq!(rate.qualifying_min_games(), 50); +} diff --git a/crates/rocket-sense-server/src/app.rs b/crates/rocket-sense-server/src/app.rs index 175922f5..1ee21824 100644 --- a/crates/rocket-sense-server/src/app.rs +++ b/crates/rocket-sense-server/src/app.rs @@ -1,5 +1,5 @@ use crate::{ - api, processing, + api, leaderboard_cache, processing, rank_benchmark::{BenchmarkWindow, CalcStyle}, settings, telemetry, }; @@ -93,6 +93,12 @@ pub async fn build(settings: settings::Settings) -> Result { state.storage.clone(), settings.background_processing_concurrency, ); + if settings.leaderboard_cache_enabled { + leaderboard_cache::start_refresh_job( + pool.clone(), + settings.leaderboard_cache_refresh_interval, + ); + } if let Some(api_key) = &state.ballchasing_api_key { crate::ballchasing_sync::start_ballchasing_group_sync_workers( pool.clone(), @@ -148,6 +154,12 @@ pub async fn run_worker(settings: settings::Settings) -> Result<()> { storage.clone(), settings.background_processing_concurrency, ); + if settings.leaderboard_cache_enabled { + leaderboard_cache::start_refresh_job( + pool.clone(), + settings.leaderboard_cache_refresh_interval, + ); + } if let Some(api_key) = &settings.ballchasing_api_key { crate::ballchasing_sync::start_ballchasing_group_sync_workers( pool.clone(), diff --git a/crates/rocket-sense-server/src/leaderboard_cache.rs b/crates/rocket-sense-server/src/leaderboard_cache.rs new file mode 100644 index 00000000..f0545162 --- /dev/null +++ b/crates/rocket-sense-server/src/leaderboard_cache.rs @@ -0,0 +1,567 @@ +//! Disposable player/window aggregates for fast leaderboard reads. +//! +//! These rows are emphatically not sources of truth. Canonical replay metadata +//! and per-replay/player facts own the data; this module is expected to throw +//! away and recompute the cache often. Keeping the rebuild idempotent and +//! boring is more important than preserving cache rows across refreshes. + +use anyhow::{Context, Result}; +use sqlx::{PgPool, Row}; +use std::time::Duration; + +#[cfg(test)] +#[path = "leaderboard_cache_tests.rs"] +mod tests; + +const REFRESH_INITIAL_DELAY: Duration = Duration::from_secs(15); +const ADVISORY_LOCK_KEY: i64 = 0x5253_4c42; // "RSLB" + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct LeaderboardCacheRefreshSummary { + pub windows: u64, + pub player_rows: u64, + pub metric_rows: u64, +} + +/// Start the recurring full rebuild on the process that owns background work. +/// +/// A full rebuild is intentional: this cache must stay disposable, and a replay +/// reprocess or identity-exclusion change should heal without bespoke repair +/// logic. The transaction keeps readers on the previous generation until the +/// replacement is complete. +pub fn start_refresh_job(pool: PgPool, refresh_interval: Duration) { + tokio::spawn(async move { + tokio::time::sleep(REFRESH_INITIAL_DELAY).await; + loop { + match refresh(&pool).await { + Ok(Some(summary)) => tracing::info!( + windows = summary.windows, + player_rows = summary.player_rows, + metric_rows = summary.metric_rows, + "leaderboard player/window cache refresh complete" + ), + Ok(None) => tracing::debug!( + "leaderboard player/window cache refresh skipped because another refresh is running" + ), + Err(error) => tracing::warn!( + error = %format!("{error:#}"), + "leaderboard player/window cache refresh failed" + ), + } + tokio::time::sleep(refresh_interval).await; + } + }); +} + +/// Rebuild every cached window from authoritative replay/fact data. +/// +/// Returns `None` when another process holds the refresh lock. Cache contents +/// are replaced transactionally; no incremental state is required for repair. +pub async fn refresh(pool: &PgPool) -> Result> { + let mut tx = pool + .begin() + .await + .context("starting leaderboard cache refresh transaction")?; + let locked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock($1)") + .bind(ADVISORY_LOCK_KEY) + .fetch_one(&mut *tx) + .await + .context("acquiring leaderboard cache refresh lock")?; + if !locked { + return Ok(None); + } + + // One canonical appearance can feed three disposable windows: current UTC + // day, trailing 168 hours, and its replay season. Scope values are normalized + // before CUBE; `*` / 0 are reserved for the generated all-scope rows. + sqlx::query( + r#" + CREATE TEMP TABLE leaderboard_refresh_appearances ON COMMIT DROP AS + WITH replay_scope AS ( + SELECT + r.id AS replay_id, + r.canonical_analysis_run_id AS analysis_run_id, + COALESCE(NULLIF(lower(btrim(r.replay_game_type)), ''), '') AS game_type, + COALESCE(NULLIF(btrim(r.playlist), ''), '') AS playlist, + NULLIF(lower(btrim(r.season)), '') AS season, + COALESCE(r.replay_date, r.created_at) AS replay_time, + COALESCE(team_size.value, -1)::smallint AS team_size + FROM replays r + LEFT JOIN LATERAL ( + SELECT MAX(team_count)::integer AS value + FROM ( + SELECT COUNT(*) AS team_count + FROM replay_players size_player + WHERE size_player.replay_id = r.id + AND size_player.team IS NOT NULL + AND ( + size_player.active_time_seconds IS NULL + OR size_player.active_time_seconds > 0 + ) + GROUP BY size_player.team + ) team_counts + ) team_size ON true + WHERE r.canonical_analysis_run_id IS NOT NULL + AND COALESCE(r.replay_date, r.created_at) <= now() + ), + canonical_appearances AS ( + SELECT DISTINCT ON ( + scope.analysis_run_id, + rp.platform, + rp.platform_player_id + ) + scope.*, + rp.platform, + rp.platform_player_id, + GREATEST(COALESCE(rp.active_time_seconds, 0.0), 0.0) AS active_time_seconds + FROM replay_scope scope + JOIN replay_players rp ON rp.replay_id = scope.replay_id + WHERE rp.platform IS NOT NULL + AND btrim(rp.platform) <> '' + AND rp.platform_player_id IS NOT NULL + AND btrim(rp.platform_player_id) <> '' + AND NOT EXISTS ( + SELECT 1 + FROM player_identity_tags excluded + WHERE excluded.platform = rp.platform + AND excluded.platform_player_id = rp.platform_player_id + AND excluded.exclude_from_aggregates + ) + ORDER BY + scope.analysis_run_id, + rp.platform, + rp.platform_player_id, + rp.active_time_seconds DESC NULLS LAST + ) + SELECT + appearance.analysis_run_id, + appearance.replay_id, + appearance.platform, + appearance.platform_player_id, + appearance.active_time_seconds, + appearance.game_type, + appearance.team_size, + appearance.playlist, + appearance.replay_time, + win.window_key, + win.window_kind, + win.window_season, + win.window_start, + win.window_end + FROM canonical_appearances appearance + CROSS JOIN LATERAL ( + SELECT + 'daily'::text AS window_key, + 'daily'::text AS window_kind, + NULL::text AS window_season, + date_trunc('day', now() AT TIME ZONE 'UTC') AT TIME ZONE 'UTC' AS window_start, + now() AS window_end + WHERE appearance.replay_time >= + date_trunc('day', now() AT TIME ZONE 'UTC') AT TIME ZONE 'UTC' + + UNION ALL + + SELECT + 'trailing-7d', + 'trailing-7d', + NULL::text, + now() - interval '7 days', + now() + WHERE appearance.replay_time >= now() - interval '7 days' + + UNION ALL + + SELECT + 'season:' || appearance.season, + 'season', + appearance.season, + NULL::timestamptz, + NULL::timestamptz + WHERE appearance.season IS NOT NULL + ) win + "#, + ) + .execute(&mut *tx) + .await + .context("building leaderboard refresh appearances")?; + + sqlx::query( + r#" + CREATE INDEX leaderboard_refresh_appearances_join_idx + ON leaderboard_refresh_appearances ( + analysis_run_id, + replay_id, + platform, + platform_player_id + ) + "#, + ) + .execute(&mut *tx) + .await + .context("indexing leaderboard refresh appearances")?; + + // Contributions retain the per-replay grain. The next step aggregates them + // into every standard scope combination. Scoreboard core events preserve the + // existing leaderboard semantics; role-sensitive events use their actor role + // rather than counting both participants from the generic event-count fact. + sqlx::query( + r#" + CREATE TEMP TABLE leaderboard_refresh_metric_contributions ON COMMIT DROP AS + SELECT + fact.analysis_run_id, + fact.replay_id, + fact.platform, + fact.platform_player_id, + 'stat'::text AS metric_kind, + fact.stat_key AS metric_key, + SUM(fact.value)::float8 AS total_value, + NULL::bigint AS sample_count + FROM player_replay_stat_facts fact + JOIN replays r + ON r.id = fact.replay_id + AND r.canonical_analysis_run_id = fact.analysis_run_id + WHERE fact.stat_key IN ( + 'ball-opponent-half', + 'possession-time', + 'ball-advance', + 'high-aerial-touch-count', + 'control-touch-count' + ) + GROUP BY + fact.analysis_run_id, + fact.replay_id, + fact.platform, + fact.platform_player_id, + fact.stat_key + + UNION ALL + + SELECT + possession.analysis_run_id, + possession.replay_id, + possession.platform, + possession.platform_player_id, + 'stat', + metric.metric_key, + metric.total_value, + possession.possession_count + FROM player_replay_possession possession + JOIN replays r + ON r.id = possession.replay_id + AND r.canonical_analysis_run_id = possession.analysis_run_id + CROSS JOIN LATERAL ( + VALUES + ('touches-per-possession'::text, possession.touch_count::float8), + ('avg-possession-duration'::text, possession.duration_seconds::float8) + ) metric(metric_key, total_value) + WHERE possession.possession_count > 0 + + UNION ALL + + SELECT + boost.analysis_run_id, + boost.replay_id, + boost.platform, + boost.platform_player_id, + 'stat', + metric.metric_key, + metric.total_value, + NULL::bigint + FROM player_replay_boost boost + JOIN replays r + ON r.id = boost.replay_id + AND r.canonical_analysis_run_id = boost.analysis_run_id + CROSS JOIN LATERAL ( + VALUES + ('big-boost-pad-count'::text, boost.big_pads::float8), + ('small-boost-pad-count'::text, boost.small_pads::float8), + ('big-boost-amount'::text, boost.boost_collected_big::float8), + ('small-boost-amount'::text, boost.boost_collected_small::float8) + ) metric(metric_key, total_value) + WHERE metric.total_value > 0 + + UNION ALL + + SELECT + r.canonical_analysis_run_id, + rp.replay_id, + rp.platform, + rp.platform_player_id, + 'event', + metric.metric_key, + metric.total_value, + NULL::bigint + FROM replay_players rp + JOIN replays r ON r.id = rp.replay_id + CROSS JOIN LATERAL ( + VALUES + ('goal'::text, COALESCE(rp.goals, 0)::float8), + ('assist'::text, COALESCE(rp.assists, 0)::float8), + ('save'::text, COALESCE(rp.saves, 0)::float8), + ('shot'::text, COALESCE(rp.shots, 0)::float8) + ) metric(metric_key, total_value) + WHERE r.canonical_analysis_run_id IS NOT NULL + AND rp.platform IS NOT NULL + AND btrim(rp.platform) <> '' + AND rp.platform_player_id IS NOT NULL + AND btrim(rp.platform_player_id) <> '' + AND metric.total_value > 0 + + UNION ALL + + SELECT + counts.analysis_run_id, + counts.replay_id, + counts.platform, + counts.platform_player_id, + 'event', + event_type.key, + counts.event_count::float8, + NULL::bigint + FROM player_replay_event_counts counts + JOIN replays r + ON r.id = counts.replay_id + AND r.canonical_analysis_run_id = counts.analysis_run_id + JOIN event_types event_type ON event_type.id = counts.event_type_id + WHERE event_type.key NOT IN ( + 'goal', 'assist', 'save', 'shot', 'bump', 'demolition', 'pass' + ) + + UNION ALL + + SELECT + event.analysis_run_id, + event.replay_id, + rp.platform, + rp.platform_player_id, + 'event', + event_type.key, + COUNT(DISTINCT event.id)::float8, + NULL::bigint + FROM play_events event + JOIN event_types event_type ON event_type.id = event.event_type_id + JOIN play_event_subjects subject ON subject.event_id = event.id + JOIN replay_players rp ON rp.id = subject.replay_player_id + JOIN replays r + ON r.id = event.replay_id + AND r.canonical_analysis_run_id = event.analysis_run_id + WHERE (event_type.key = 'bump' AND subject.role = 'initiator') + OR (event_type.key = 'demolition' AND subject.role = 'attacker') + OR (event_type.key = 'pass' AND subject.role = 'passer') + GROUP BY + event.analysis_run_id, + event.replay_id, + rp.platform, + rp.platform_player_id, + event_type.key + "#, + ) + .execute(&mut *tx) + .await + .context("building leaderboard metric contributions")?; + + sqlx::query( + r#" + CREATE TEMP TABLE leaderboard_refresh_metric_sums ON COMMIT DROP AS + SELECT + appearance.window_key, + CASE WHEN GROUPING(appearance.game_type) = 1 + THEN '*' ELSE appearance.game_type END AS scope_game_type, + CASE WHEN GROUPING(appearance.team_size) = 1 + THEN 0 ELSE appearance.team_size END AS scope_team_size, + CASE WHEN GROUPING(appearance.playlist) = 1 + THEN '*' ELSE appearance.playlist END AS scope_playlist, + appearance.platform, + appearance.platform_player_id, + contribution.metric_kind, + contribution.metric_key, + SUM(contribution.total_value)::float8 AS total_value, + SUM(contribution.sample_count)::bigint AS sample_count + FROM leaderboard_refresh_appearances appearance + JOIN leaderboard_refresh_metric_contributions contribution + ON contribution.analysis_run_id = appearance.analysis_run_id + AND contribution.replay_id = appearance.replay_id + AND contribution.platform = appearance.platform + AND contribution.platform_player_id = appearance.platform_player_id + GROUP BY + appearance.window_key, + appearance.platform, + appearance.platform_player_id, + contribution.metric_kind, + contribution.metric_key, + CUBE(appearance.game_type, appearance.team_size, appearance.playlist) + HAVING SUM(contribution.total_value) > 0 + "#, + ) + .execute(&mut *tx) + .await + .context("aggregating leaderboard metric scopes")?; + + // Replace the prior generation only after all expensive source work has + // succeeded. Readers continue seeing the old committed rows until commit. + sqlx::query("DELETE FROM leaderboard_player_window_metrics") + .execute(&mut *tx) + .await + .context("clearing old leaderboard metric cache")?; + sqlx::query("DELETE FROM leaderboard_player_window_totals") + .execute(&mut *tx) + .await + .context("clearing old leaderboard player cache")?; + sqlx::query("DELETE FROM leaderboard_cache_windows") + .execute(&mut *tx) + .await + .context("clearing old leaderboard window metadata")?; + + sqlx::query( + r#" + INSERT INTO leaderboard_cache_windows ( + window_key, + window_kind, + season, + window_start, + window_end, + is_current, + refreshed_at + ) + SELECT + window_key, + MAX(window_kind), + MAX(window_season), + COALESCE(MAX(window_start), MIN(replay_time)), + COALESCE(MAX(window_end), MAX(replay_time)), + MAX(window_kind) <> 'season', + now() + FROM leaderboard_refresh_appearances + GROUP BY window_key + "#, + ) + .execute(&mut *tx) + .await + .context("inserting leaderboard window metadata")?; + + sqlx::query( + r#" + UPDATE leaderboard_cache_windows cached_window + SET is_current = cached_window.window_key = ( + SELECT current_window.window_key + FROM leaderboard_cache_windows current_window + WHERE current_window.window_kind = 'season' + ORDER BY current_window.window_end DESC NULLS LAST, current_window.season DESC + LIMIT 1 + ) + WHERE cached_window.window_kind = 'season' + "#, + ) + .execute(&mut *tx) + .await + .context("marking current leaderboard season")?; + + let player_rows = sqlx::query( + r#" + INSERT INTO leaderboard_player_window_totals ( + window_key, + scope_game_type, + scope_team_size, + scope_playlist, + platform, + platform_player_id, + replay_count, + active_time_seconds, + refreshed_at + ) + SELECT + appearance.window_key, + CASE WHEN GROUPING(appearance.game_type) = 1 + THEN '*' ELSE appearance.game_type END, + CASE WHEN GROUPING(appearance.team_size) = 1 + THEN 0 ELSE appearance.team_size END, + CASE WHEN GROUPING(appearance.playlist) = 1 + THEN '*' ELSE appearance.playlist END, + appearance.platform, + appearance.platform_player_id, + COUNT(DISTINCT appearance.replay_id), + SUM(appearance.active_time_seconds), + now() + FROM leaderboard_refresh_appearances appearance + GROUP BY + appearance.window_key, + appearance.platform, + appearance.platform_player_id, + CUBE(appearance.game_type, appearance.team_size, appearance.playlist) + "#, + ) + .execute(&mut *tx) + .await + .context("inserting leaderboard player/window totals")? + .rows_affected(); + + let metric_rows = sqlx::query( + r#" + INSERT INTO leaderboard_player_window_metrics ( + window_key, + scope_game_type, + scope_team_size, + scope_playlist, + platform, + platform_player_id, + metric_kind, + metric_key, + total_value, + replay_count, + active_time_seconds, + value_per_5_minutes, + sample_count, + average_value, + refreshed_at + ) + SELECT + metric.window_key, + metric.scope_game_type, + metric.scope_team_size, + metric.scope_playlist, + metric.platform, + metric.platform_player_id, + metric.metric_kind, + metric.metric_key, + metric.total_value, + totals.replay_count, + totals.active_time_seconds, + CASE WHEN totals.active_time_seconds > 0 + THEN metric.total_value * 300.0 / totals.active_time_seconds + ELSE NULL END, + metric.sample_count, + CASE WHEN metric.sample_count > 0 + THEN metric.total_value / metric.sample_count::float8 + ELSE NULL END, + now() + FROM leaderboard_refresh_metric_sums metric + JOIN leaderboard_player_window_totals totals + ON totals.window_key = metric.window_key + AND totals.scope_game_type = metric.scope_game_type + AND totals.scope_team_size = metric.scope_team_size + AND totals.scope_playlist = metric.scope_playlist + AND totals.platform = metric.platform + AND totals.platform_player_id = metric.platform_player_id + "#, + ) + .execute(&mut *tx) + .await + .context("inserting leaderboard player/window metrics")? + .rows_affected(); + + let windows: i64 = sqlx::query("SELECT COUNT(*) AS count FROM leaderboard_cache_windows") + .fetch_one(&mut *tx) + .await + .context("counting refreshed leaderboard windows")? + .try_get("count")?; + + tx.commit() + .await + .context("committing leaderboard cache refresh")?; + + Ok(Some(LeaderboardCacheRefreshSummary { + windows: windows.max(0) as u64, + player_rows, + metric_rows, + })) +} diff --git a/crates/rocket-sense-server/src/leaderboard_cache_tests.rs b/crates/rocket-sense-server/src/leaderboard_cache_tests.rs new file mode 100644 index 00000000..21485605 --- /dev/null +++ b/crates/rocket-sense-server/src/leaderboard_cache_tests.rs @@ -0,0 +1,130 @@ +use super::*; +use uuid::Uuid; + +#[tokio::test] +async fn refresh_rebuilds_an_empty_database() { + let Ok(database_url) = std::env::var("ROCKET_SENSE_TEST_DATABASE_URL") else { + return; + }; + let pool = rocket_sense_db::connect(&database_url) + .await + .expect("test database should connect"); + rocket_sense_db::run_migrations(&pool) + .await + .expect("test migrations should run"); + + let summary = refresh(&pool) + .await + .expect("empty cache refresh should succeed") + .expect("test should acquire the refresh lock"); + + assert_eq!(summary.windows, 0); + assert_eq!(summary.player_rows, 0); + assert_eq!(summary.metric_rows, 0); + + let replay_id = Uuid::now_v7(); + let analysis_run_id = Uuid::now_v7(); + sqlx::query( + r#" + INSERT INTO replays ( + id, file_sha256, byte_size, storage_byte_size, storage_key, playlist, + replay_game_type, season, replay_date + ) + VALUES ($1, 'leaderboard-cache-test', 1, 1, 'test.replay', + 'ranked-duels', 'ranked', 'f23', now()) + "#, + ) + .bind(replay_id) + .execute(&pool) + .await + .expect("test replay should insert"); + sqlx::query( + r#" + INSERT INTO analysis_runs ( + id, replay_id, status, extractor_name, extractor_version, + input_file_sha256, event_stream_schema_version, finished_at + ) + VALUES ($1, $2, 'succeeded', 'test', '1', + 'leaderboard-cache-test', 'test', now()) + "#, + ) + .bind(analysis_run_id) + .bind(replay_id) + .execute(&pool) + .await + .expect("test analysis run should insert"); + sqlx::query("UPDATE replays SET canonical_analysis_run_id = $2 WHERE id = $1") + .bind(replay_id) + .bind(analysis_run_id) + .execute(&pool) + .await + .expect("test replay should become canonical"); + + let player_id = Uuid::now_v7(); + for (id, platform_player_id, team, goals) in [ + (player_id, "player-one", 0, 2), + (Uuid::now_v7(), "player-two", 1, 0), + ] { + sqlx::query( + r#" + INSERT INTO replay_players ( + id, replay_id, name, platform, platform_player_id, + team, active_time_seconds, goals, assists, saves, shots + ) + VALUES ($1, $2, $3, 'steam', $3, $4, 300.0, $5, 0, 0, 0) + "#, + ) + .bind(id) + .bind(replay_id) + .bind(platform_player_id) + .bind(team) + .bind(goals) + .execute(&pool) + .await + .expect("test replay player should insert"); + } + sqlx::query( + r#" + INSERT INTO player_replay_stat_facts ( + analysis_run_id, replay_id, replay_player_id, player_subject_id, + platform, platform_player_id, team, stat_key, value, unit, + active_time_seconds, denominator_key, denominator_value + ) + VALUES ($1, $2, $3, 'steam:player-one', 'steam', 'player-one', 0, + 'possession-time', 30.0, 'seconds', 300.0, 'active_time', 300.0) + "#, + ) + .bind(analysis_run_id) + .bind(replay_id) + .bind(player_id) + .execute(&pool) + .await + .expect("test stat fact should insert"); + + let summary = refresh(&pool) + .await + .expect("populated cache refresh should succeed") + .expect("test should reacquire the refresh lock"); + assert_eq!(summary.windows, 3); + assert_eq!(summary.player_rows, 48); + assert_eq!(summary.metric_rows, 48); + + let cached_goal: (f64, i64, f64) = sqlx::query_as( + r#" + SELECT total_value, replay_count, value_per_5_minutes + FROM leaderboard_player_window_metrics + WHERE window_key = 'trailing-7d' + AND scope_game_type = '*' + AND scope_team_size = 0 + AND scope_playlist = '*' + AND platform = 'steam' + AND platform_player_id = 'player-one' + AND metric_kind = 'event' + AND metric_key = 'goal' + "#, + ) + .fetch_one(&pool) + .await + .expect("goal cache row should exist"); + assert_eq!(cached_goal, (2.0, 1, 2.0)); +} diff --git a/crates/rocket-sense-server/src/main.rs b/crates/rocket-sense-server/src/main.rs index 2f1500db..f1d02863 100644 --- a/crates/rocket-sense-server/src/main.rs +++ b/crates/rocket-sense-server/src/main.rs @@ -7,6 +7,7 @@ mod app; mod auth; mod ballchasing; mod ballchasing_sync; +mod leaderboard_cache; mod processing; mod rank_benchmark; mod ranks; diff --git a/crates/rocket-sense-server/src/settings.rs b/crates/rocket-sense-server/src/settings.rs index f02f80d0..e01abb09 100644 --- a/crates/rocket-sense-server/src/settings.rs +++ b/crates/rocket-sense-server/src/settings.rs @@ -124,6 +124,12 @@ pub struct Settings { /// `play_event_subjects`/`play_events` scan. Default false so the page stays /// correct until the reprocess backfill has populated the table. pub materialized_stat_counts: bool, + /// Enables the disposable player/window leaderboard read-model refresh. + /// Canonical replay facts remain authoritative; this cache is expected to + /// be deleted and fully rebuilt frequently. + pub leaderboard_cache_enabled: bool, + /// Cadence for full leaderboard cache rebuilds. Defaults to ten minutes. + pub leaderboard_cache_refresh_interval: Duration, /// Gates the rank-median benchmark cohort: the recurring refresh job, the /// admin trigger, and the `rank_benchmark_*` read-path fields. Default false /// until the first refresh has populated `rank_benchmark_stats`. @@ -206,6 +212,16 @@ impl Settings { let materialized_stat_counts = env::var("ROCKET_SENSE_MATERIALIZED_STAT_COUNTS") .map(|value| value == "1" || value.to_lowercase() == "true") .unwrap_or(true); + let leaderboard_cache_enabled = env::var("ROCKET_SENSE_LEADERBOARD_CACHE") + .map(|value| value != "0" && value.to_lowercase() != "false") + .unwrap_or(true); + let leaderboard_cache_refresh_interval = Duration::from_secs( + env::var("ROCKET_SENSE_LEADERBOARD_CACHE_REFRESH_SECS") + .ok() + .and_then(|value| value.parse::().ok()) + .unwrap_or(10 * 60) + .max(60), + ); let rank_benchmark_enabled = env::var("ROCKET_SENSE_RANK_BENCHMARK") .map(|value| value == "1" || value.to_lowercase() == "true") .unwrap_or(false); @@ -248,6 +264,8 @@ impl Settings { run_replay_processing_workers, background_processing_concurrency, materialized_stat_counts, + leaderboard_cache_enabled, + leaderboard_cache_refresh_interval, rank_benchmark_enabled, rank_benchmark_windows, rank_benchmark_default_window, diff --git a/crates/rocket-sense-server/static/subtr-actor/.subtr-actor-rev b/crates/rocket-sense-server/static/subtr-actor/.subtr-actor-rev index c7ba6c66..34837e84 100644 --- a/crates/rocket-sense-server/static/subtr-actor/.subtr-actor-rev +++ b/crates/rocket-sense-server/static/subtr-actor/.subtr-actor-rev @@ -1 +1 @@ -20eb0589911ea98e72fcaf55866b909e2af96a1c +db683e302b9028e5add304e449cb89d1f80702af diff --git a/crates/rocket-sense-server/static/subtr-actor/assets/index-Bi0g-Y6P.js b/crates/rocket-sense-server/static/subtr-actor/assets/index-Bi0g-Y6P.js new file mode 100644 index 00000000..61ada380 --- /dev/null +++ b/crates/rocket-sense-server/static/subtr-actor/assets/index-Bi0g-Y6P.js @@ -0,0 +1,2 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./main-DhIgxjyS.js","./preload-helper-PPVm8Dsz.js","./main-BmO1EVHp.css"])))=>i.map(i=>d[i]); +import{_ as u}from"./preload-helper-PPVm8Dsz.js";(function(){const r=document.createElement("link").relList;if(r&&r.supports&&r.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))n(e);new MutationObserver(e=>{for(const t of e)if(t.type==="childList")for(const o of t.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function c(e){const t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?t.credentials="include":e.crossOrigin==="anonymous"?t.credentials="omit":t.credentials="same-origin",t}function n(e){if(e.ep)return;e.ep=!0;const t=c(e);fetch(e.href,t)}})();const s=document.querySelector("#app");if(!(s instanceof HTMLElement))throw new Error("Missing #app mount element");const{mountStatEvaluationPlayer:a}=await u(async()=>{const{mountStatEvaluationPlayer:i}=await import("./main-DhIgxjyS.js");return{mountStatEvaluationPlayer:i}},__vite__mapDeps([0,1,2]),import.meta.url);a(s); diff --git a/crates/rocket-sense-server/static/subtr-actor/assets/index-DqmYE4Q0.js b/crates/rocket-sense-server/static/subtr-actor/assets/index-DqmYE4Q0.js deleted file mode 100644 index 061c93a6..00000000 --- a/crates/rocket-sense-server/static/subtr-actor/assets/index-DqmYE4Q0.js +++ /dev/null @@ -1,2 +0,0 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./main-DHjpjWsc.js","./main-D554jl9D.css"])))=>i.map(i=>d[i]); -(function(){const i=document.createElement("link").relList;if(i&&i.supports&&i.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))u(e);new MutationObserver(e=>{for(const t of e)if(t.type==="childList")for(const r of t.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&u(r)}).observe(document,{childList:!0,subtree:!0});function a(e){const t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?t.credentials="include":e.crossOrigin==="anonymous"?t.credentials="omit":t.credentials="same-origin",t}function u(e){if(e.ep)return;e.ep=!0;const t=a(e);fetch(e.href,t)}})();const g="modulepreload",v=function(l,i){return new URL(l,i).href},h={},P=function(i,a,u){let e=Promise.resolve();if(a&&a.length>0){let E=function(n){return Promise.all(n.map(c=>Promise.resolve(c).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}))))};const r=document.getElementsByTagName("link"),o=document.querySelector("meta[property=csp-nonce]"),p=o?.nonce||o?.getAttribute("nonce");e=E(a.map(n=>{if(n=v(n,u),n in h)return;h[n]=!0;const c=n.endsWith(".css"),f=c?'[rel="stylesheet"]':"";if(u)for(let d=r.length-1;d>=0;d--){const m=r[d];if(m.href===n&&(!c||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${n}"]${f}`))return;const s=document.createElement("link");if(s.rel=c?"stylesheet":g,c||(s.as="script"),s.crossOrigin="",s.href=n,p&&s.setAttribute("nonce",p),document.head.appendChild(s),c)return new Promise((d,m)=>{s.addEventListener("load",d),s.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${n}`)))})}))}function t(r){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=r,window.dispatchEvent(o),!o.defaultPrevented)throw r}return e.then(r=>{for(const o of r||[])o.status==="rejected"&&t(o.reason);return i().catch(t)})},y=document.querySelector("#app");if(!(y instanceof HTMLElement))throw new Error("Missing #app mount element");const{mountStatEvaluationPlayer:w}=await P(async()=>{const{mountStatEvaluationPlayer:l}=await import("./main-DHjpjWsc.js");return{mountStatEvaluationPlayer:l}},__vite__mapDeps([0,1]),import.meta.url);w(y); diff --git a/crates/rocket-sense-server/static/subtr-actor/assets/main-D554jl9D.css b/crates/rocket-sense-server/static/subtr-actor/assets/main-BmO1EVHp.css similarity index 98% rename from crates/rocket-sense-server/static/subtr-actor/assets/main-D554jl9D.css rename to crates/rocket-sense-server/static/subtr-actor/assets/main-BmO1EVHp.css index b8d95020..17d9fd0b 100644 --- a/crates/rocket-sense-server/static/subtr-actor/assets/main-D554jl9D.css +++ b/crates/rocket-sense-server/static/subtr-actor/assets/main-BmO1EVHp.css @@ -1 +1 @@ -:root{color-scheme:dark;font-family:IBM Plex Sans,Avenir Next,sans-serif;font-size:13px;--surface: rgba(8, 20, 30, .82);--surface-strong: rgba(7, 16, 24, .94);--surface-soft: rgba(12, 28, 40, .72);--border: rgba(167, 199, 222, .14);--text: #edf5fa;--muted: #9eb4c6;--blue: #4b94ff;--blue-soft: rgba(75, 148, 255, .18);--orange: #f39a37;--orange-soft: rgba(243, 154, 55, .18);--ui-gap-xs: .22rem;--ui-gap-sm: .34rem;--ui-gap-md: .5rem;--ui-panel-padding: .52rem;--ui-control-font-size: .72rem;--ui-control-line-height: 1.15;--ui-control-padding-block: .22rem;--ui-control-padding-inline: .38rem;--ui-control-height: 1.55rem;--ui-radius-sm: .36rem;--ui-radius-md: .5rem;--ui-radius-lg: .72rem;--ui-radius-pill: 999px;--ui-border-subtle: rgba(255, 255, 255, .1);--ui-border-hover: rgba(255, 255, 255, .18);--ui-overlay-bg: rgba(4, 12, 18, .82);--ui-overlay-bg-strong: rgba(4, 12, 18, .9);background:radial-gradient(circle at top left,rgba(73,112,158,.28),transparent 32%),radial-gradient(circle at top right,rgba(243,154,55,.12),transparent 24%),linear-gradient(180deg,#071018,#0b1721);color:var(--text)}*,*:before,*:after{box-sizing:border-box}html,body,#app{width:100%;height:100%;overflow:hidden}body{margin:0}button,select,input{font:inherit}.shell{min-height:100dvh;height:100dvh;padding:0;display:block}.workspace{height:100%;display:block;min-height:0}.panel h2,.stats-panel h2{margin:0}.panel-copy{color:#bdd0de}.viewport-panel,.panel,.stats-panel{position:relative;border:1px solid var(--border);border-radius:1.4rem;background:var(--surface);box-shadow:0 22px 56px #0000003d;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}.viewport-panel{width:100%;height:100%;min-height:100dvh;overflow:hidden;border:0;border-radius:0;background:#061019;box-shadow:none}.viewport{position:absolute;inset:0}.top-chrome{position:absolute;top:.8rem;left:.8rem;z-index:20}.launcher-toggle{width:2.65rem;min-width:0;aspect-ratio:1;display:grid;place-items:center;padding:0;border-color:transparent;border-radius:var(--ui-radius-md);background:#050e16ad;box-shadow:0 12px 30px #0000004d;-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px)}.launcher-toggle:hover,.launcher-toggle[aria-expanded=true]{border-color:#ffffff29;background:#081824d1}.launcher-toggle-bars,.launcher-toggle-bars:before,.launcher-toggle-bars:after{display:block;width:1.18rem;height:.12rem;border-radius:var(--ui-radius-pill);background:#edf5fa}.launcher-toggle-bars{position:relative}.launcher-toggle-bars:before,.launcher-toggle-bars:after{content:"";position:absolute;left:0}.launcher-toggle-bars:before{top:-.38rem}.launcher-toggle-bars:after{top:.38rem}.launcher-menu{position:absolute;top:calc(100% + .55rem);left:0;width:min(22rem,calc(100vw - 1.6rem));max-height:calc(100dvh - 7.5rem);overflow:auto;display:grid;gap:var(--ui-gap-md);padding:var(--ui-panel-padding);border:1px solid rgba(255,255,255,.12);border-radius:var(--ui-radius-lg);background:var(--ui-overlay-bg-strong);box-shadow:0 18px 54px #0000005c;-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px)}.launcher-menu[hidden]{display:none}.launcher-section{display:grid;gap:var(--ui-gap-xs)}.launcher-section h2{margin:0;color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase}.launcher-section button{width:100%;text-align:left}.hidden-file-input,.visually-hidden{position:fixed;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap}.team-blue{--team-accent: var(--blue);--team-soft: var(--blue-soft)}.team-orange{--team-accent: var(--orange);--team-soft: var(--orange-soft)}.floating-window-layer,.stats-window-layer{position:absolute;inset:0;z-index:12;pointer-events:none}.floating-window,.stats-window,.scoreboard-window{position:absolute;left:clamp(.8rem,var(--window-x, 1rem),calc(100vw - 18rem));top:clamp(.8rem,var(--window-y, 1rem),calc(100dvh - 12rem));width:min(26rem,calc(100vw - 1.6rem));overflow:visible;display:grid;gap:var(--ui-gap-md);padding:var(--ui-panel-padding);border:1px solid rgba(255,255,255,.12);border-radius:var(--ui-radius-lg);background:var(--ui-overlay-bg);box-shadow:0 16px 44px #00000052;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);pointer-events:auto;-webkit-user-select:none;user-select:none}.floating-window[hidden],.stats-window[hidden],.scoreboard-window[hidden]{display:none}.scoreboard-window{left:50%;top:.7rem;width:auto;min-width:4.4rem;transform:translate(-50%);gap:var(--ui-gap-sm);padding:.34rem .62rem;border-radius:999px}.scoreboard-window-body{display:grid;gap:.42rem}.scoreboard-scoreline{display:grid;grid-template-columns:minmax(1.2rem,auto) auto minmax(1.2rem,auto);align-items:center;justify-content:center;gap:.3rem;min-width:0;font-variant-numeric:tabular-nums}.scoreboard-goal-value{color:var(--team-accent);font-size:1rem;font-weight:850;line-height:1;text-align:center}.scoreboard-divider{color:var(--muted);font-size:1rem;font-weight:800;line-height:1}.scoreboard-empty{margin:0;color:var(--muted);font-size:.74rem;text-align:center}@media(max-width:900px){.scoreboard-window{top:3.25rem}}@media(max-width:640px){.scoreboard-window{min-width:4rem;padding:.32rem .56rem}.scoreboard-scoreline{gap:.24rem}.scoreboard-goal-value{font-size:.92rem}}.floating-window-camera{width:min(26rem,calc(100vw - 1.6rem))}.floating-window-recording{--window-x: calc(100vw - 27rem) ;width:min(26rem,calc(100vw - 1.6rem))}.floating-window-playback{--window-x: calc(100vw - 23rem) ;width:min(21rem,calc(100vw - 1.6rem))}.floating-window-mechanics{width:auto;min-width:min(18rem,calc(100vw - 1.6rem));max-width:min(42rem,calc(100vw - 1.6rem))}.mechanics-timeline-window-body{display:grid;gap:var(--ui-gap-sm);max-height:min(72dvh,42rem);overflow:auto}.floating-window-event-playlist{width:min(27rem,calc(100vw - 1.6rem))}.floating-window-mechanics-review{width:min(30rem,calc(100vw - 1.6rem))}.floating-window-replay-loading{width:min(32rem,calc(100vw - 1.6rem))}.floating-window-boost-pickups{width:min(34rem,calc(100vw - 1.6rem))}.floating-window-touch-controls,.floating-window-touch-legend{width:min(24rem,calc(100vw - 1.6rem))}.floating-window-shot-visualization{width:min(38rem,calc(100vw - 1.6rem))}.floating-window-header,.stats-window-header{display:flex;align-items:start;justify-content:space-between;gap:var(--ui-gap-md);cursor:grab}.stats-window-header-actions-only{justify-content:end}.floating-window:active .floating-window-header,.stats-window:active .stats-window-header{cursor:grabbing}.floating-window-header h2,.stats-window-header h2{margin:0;color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase}.floating-window-hide,.stats-window-action{flex-shrink:0;padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border-radius:var(--ui-radius-md);font-size:var(--ui-control-font-size)}.mechanics-review-window-body{display:grid;gap:var(--ui-gap-md);max-height:min(74dvh,42rem);min-height:0;overflow:hidden auto;scrollbar-width:thin}.event-playlist-window-body{display:grid;gap:var(--ui-gap-sm);min-height:0}.touch-color-legend-body{display:grid;gap:var(--ui-gap-md);max-height:min(70dvh,38rem);overflow:auto;scrollbar-width:thin}.touch-color-legend-explainer{display:grid;gap:var(--ui-gap-xs);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);color:#c3d3df;font-size:.78rem;background:#ffffff0a}.touch-color-legend-group{display:grid;gap:var(--ui-gap-xs)}.touch-color-legend-heading{width:100%;min-height:1.45rem;margin:0;padding:.12rem .32rem;border-radius:var(--ui-radius-sm);color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.1em;text-align:left;text-transform:uppercase}.touch-color-legend-heading[data-active=true]{border-color:#8ec5ff6b;background:#21476b94;color:#f3f8fc}.touch-color-legend-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-xs)}.touch-color-legend-item{min-width:0;display:flex;align-items:center;gap:var(--ui-gap-xs);color:#e8f0f7;font-size:.76rem}.touch-color-legend-swatch{flex:0 0 auto;width:.78rem;height:.78rem;border:1px solid rgba(255,255,255,.35);border-radius:50%;box-shadow:0 0 0 1px #00000038}.event-playlist-toolbar{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm)}.event-playlist-filter{position:relative;min-width:0}.event-playlist-filter summary{display:inline-flex;align-items:center;min-height:var(--ui-control-height);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);background:#ffffff0a;color:var(--text);font-size:var(--ui-control-font-size);cursor:pointer;list-style:none}.event-playlist-filter summary::-webkit-details-marker{display:none}.event-playlist-filter-panel{position:absolute;z-index:5;top:calc(100% + .4rem);left:0;width:min(22rem,calc(100vw - 3rem));max-height:min(28rem,calc(100dvh - 10rem));overflow:auto;display:grid;gap:var(--ui-gap-md);padding:.85rem;border:1px solid rgba(255,255,255,.14);border-radius:var(--ui-radius-md);background:#090e16fa;box-shadow:0 16px 34px #00000057}.event-playlist-filter-actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem}.event-playlist-filter-group{display:grid;gap:.45rem}.event-playlist-filter-group h3{margin:0;color:#87afd4;font-size:.64rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase}.event-playlist-filter-option{min-width:0}.event-playlist-follow{flex-shrink:0}.event-playlist-list{max-height:min(31rem,calc(100dvh - 11rem));overflow:auto;display:grid;gap:.45rem;padding-right:.15rem;scrollbar-width:thin}.event-playlist-item{--event-color: #d1d9e0;appearance:none;width:100%;display:grid;grid-template-columns:3.4rem minmax(0,1fr);gap:.7rem;align-items:start;padding:.6rem .7rem;border:1px solid rgba(255,255,255,.09);border-left:.28rem solid var(--event-color);border-radius:var(--ui-radius-md);background:#ffffff09;color:var(--text);font:inherit;text-align:left;cursor:pointer}.event-playlist-item:hover,.event-playlist-item[data-active=true]{border-color:color-mix(in srgb,var(--event-color) 48%,rgba(255,255,255,.12));background:color-mix(in srgb,var(--event-color) 15%,rgba(255,255,255,.045))}.event-playlist-time{color:var(--muted);font-size:.72rem;font-variant-numeric:tabular-nums;line-height:1.35}.event-playlist-main{min-width:0;display:grid;gap:.15rem}.shot-visualization{display:grid;gap:var(--ui-gap-md);min-height:0}.shot-visualization-summary{color:var(--text);font-size:.78rem;font-weight:700;font-variant-numeric:tabular-nums}.shot-chart-canvas{width:100%;aspect-ratio:16 / 10;display:block;border:1px solid rgba(255,255,255,.1);border-radius:var(--ui-radius-md);background:#0f2b24}.shot-visualization-layout{display:grid;grid-template-columns:minmax(10rem,.78fr) minmax(15rem,1.22fr);gap:var(--ui-gap-md);min-height:0}.shot-list{display:grid;align-content:start;gap:.45rem;max-height:18rem;overflow:auto;padding-right:.15rem;scrollbar-width:thin}.shot-list-item{appearance:none;width:100%;display:grid;gap:.15rem;min-height:3.1rem;padding:.52rem .62rem;border:1px solid rgba(255,255,255,.09);border-left:.24rem solid #62d2a2;border-radius:var(--ui-radius-md);background:#ffffff09;color:var(--text);font:inherit;text-align:left;cursor:pointer}.shot-list-item[data-selected=true]{border-color:#f8fafcb8;background:#87afd429}.shot-list-item[data-active=true]{border-left-color:#e11d48}.shot-list-title{min-width:0;overflow:hidden;color:var(--text);font-size:.78rem;font-weight:800;text-overflow:ellipsis;white-space:nowrap}.shot-list-meta{color:var(--muted);font-size:.68rem;font-variant-numeric:tabular-nums;white-space:nowrap}.shot-demo-panel{display:grid;gap:var(--ui-gap-sm);min-width:0}.shot-demo-scene{width:100%;height:12rem;overflow:hidden;border:1px solid rgba(255,255,255,.1);border-radius:var(--ui-radius-md);background:#07111c}.shot-demo-scene canvas{width:100%;height:100%;display:block}.shot-details{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem;margin:0}.shot-details div{min-width:0;padding:.48rem .56rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:#ffffff09}.shot-details dt{color:var(--muted);font-size:.62rem;font-weight:700;text-transform:uppercase}.shot-details dd{min-width:0;margin:.14rem 0 0;overflow:hidden;color:var(--text);font-size:.76rem;font-variant-numeric:tabular-nums;text-overflow:ellipsis;white-space:nowrap}.shot-visualization-empty{margin:0;color:var(--muted);font-size:.78rem}.event-playlist-main strong{min-width:0;overflow-wrap:anywhere;font-size:.82rem;line-height:1.3}.event-playlist-main span{min-width:0;overflow-wrap:anywhere;color:var(--muted);font-size:.68rem;line-height:1.35}.mechanics-review-load-row{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:var(--ui-gap-sm);align-items:center}.mechanics-review-file{display:inline-grid;align-items:center;min-height:var(--ui-control-height);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);background:#ffffff0e;color:var(--text);cursor:pointer}.mechanics-review-file input{position:fixed;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap}.mechanics-review-url{min-width:0}.mechanics-review-status{min-height:1.2rem;color:var(--muted);font-size:.78rem}.mechanics-review-current{display:grid;gap:var(--ui-gap-sm);padding:.55rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:#ffffff09}.mechanics-review-index{color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase}.mechanics-review-current h3{margin:0;font-size:.96rem;line-height:1.2}.mechanics-review-fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-sm);margin:0}.mechanics-review-fields div{min-width:0}.mechanics-review-fields dt{color:var(--muted);font-size:.68rem;text-transform:uppercase}.mechanics-review-fields dd{margin:.1rem 0 0;overflow-wrap:anywhere}.mechanics-review-wide{grid-column:1 / -1}.mechanics-review-actions,.mechanics-review-decision-actions,.mechanics-review-list-header{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm)}.mechanics-review-actions button,.mechanics-review-decision-actions button{flex:1 1 0}#mechanics-review-confirm{border-color:#4caf7885}#mechanics-review-reject{border-color:#dc5f5f94}.mechanics-review-list-header{color:var(--muted);font-size:.72rem;font-weight:700;text-transform:uppercase}.mechanics-review-replays{display:grid;gap:var(--ui-gap-xs)}.replay-loading-window-body{display:grid;gap:var(--ui-gap-sm);max-height:min(72dvh,40rem);min-height:0}.replay-loading-summary{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm);color:var(--muted);font-size:.72rem;font-weight:700;text-transform:uppercase}.replay-loading-list{max-height:min(38rem,calc(100dvh - 9rem));overflow:auto;display:grid;gap:var(--ui-gap-xs);padding-right:.15rem;scrollbar-width:thin}.mechanics-review-replay-load{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.35rem var(--ui-gap-sm);min-width:0;padding:.5rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:#ffffff09}.mechanics-review-replay-load.loaded{border-color:#4caf786b}.mechanics-review-replay-load.error{border-color:#dc5f5f94}.mechanics-review-replay-load-main{display:grid;min-width:0;gap:.16rem}.mechanics-review-replay-load-title,.mechanics-review-replay-load-meta{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-replay-load-title{color:var(--text);font-size:.78rem;font-weight:700}.mechanics-review-replay-load-meta{color:var(--muted);font-size:.68rem}.mechanics-review-replay-load-status{max-width:11rem;overflow:hidden;color:var(--muted);font-size:.68rem;text-align:right;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-replay-load.loaded .mechanics-review-replay-load-status{color:#83d4a4}.mechanics-review-replay-load.error .mechanics-review-replay-load-status{color:#ff9b9b}.mechanics-review-replay-load-progress{grid-column:1 / -1;height:.25rem;overflow:hidden;border-radius:999px;background:#ffffff14}.mechanics-review-replay-load-progress span{display:block;width:0;height:100%;border-radius:inherit;background:#77a9ff;transition:width .14s ease}.mechanics-review-replay-load.loaded .mechanics-review-replay-load-progress span{background:#4caf78}.mechanics-review-replay-load.error .mechanics-review-replay-load-progress span{background:#dc5f5f}.mechanics-review-list{max-height:min(22rem,calc(100dvh - 27rem));display:grid;gap:var(--ui-gap-xs);overflow:auto;padding-right:.15rem;scrollbar-width:thin}.mechanics-review-item{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--ui-gap-sm);align-items:center;width:100%;min-height:2rem;text-align:left}.mechanics-review-item span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-item strong{color:var(--muted);font-size:.72rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-item[data-active=true]{border-color:#4b94ff6b;background:#4b94ff29}.viewport canvas{display:block;width:100%;height:100%}.replay-load-modal{position:fixed;inset:0;z-index:100;display:grid;place-items:center;padding:1.25rem;background:radial-gradient(circle at top,rgba(89,157,219,.18),transparent 30%),#040b12c2;-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px)}.replay-load-modal[hidden]{display:none}.replay-load-modal__dialog{width:min(32rem,100%);display:grid;gap:.75rem;padding:1.4rem 1.45rem;border-radius:1.35rem;border:1px solid rgba(255,255,255,.12);background:linear-gradient(180deg,#0b1724f5,#070f18f0);box-shadow:0 24px 70px #0006}.replay-load-modal__eyebrow{margin:0;font-size:.72rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase;color:#87afd4}.replay-load-modal__title,.replay-load-modal__status,.replay-load-modal__meta{margin:0}.replay-load-modal__title{font-size:clamp(1.45rem,4vw,2.1rem);line-height:1.1;color:#f3f8fc}.replay-load-modal__status{color:#e6f0f7;font-size:1rem}.replay-load-modal__phase-list{display:grid;gap:.52rem}.replay-load-modal__phase-row{display:grid;gap:.28rem}.replay-load-modal__phase-label{margin:0;font-size:.82rem;letter-spacing:.04em;color:#9eb4c6}.replay-load-modal__phase-row[data-state=active] .replay-load-modal__phase-label{color:#edf5fa}.replay-load-modal__phase-row[data-state=complete] .replay-load-modal__phase-label{color:#c5d9e7}.replay-load-modal__phase-bar{overflow:hidden;height:.58rem;border-radius:999px;background:#ffffff1a}.replay-load-modal__phase-fill{width:0%;height:100%;border-radius:inherit;background:linear-gradient(90deg,#4b94ff,#8ec5ff 55%,#f39a37);transition:width .14s ease}.replay-load-modal__phase-row[data-state=complete] .replay-load-modal__phase-fill{opacity:.95}.replay-load-modal__phase-fill[data-indeterminate=true]{width:100%!important;background:linear-gradient(90deg,#4b94ff40,#4b94ffcc 28%,#8ec5fff2,#f39a37cc 72%,#f39a3740);background-size:180% 100%;animation:replay-load-phase-indeterminate 1.1s linear infinite}@keyframes replay-load-phase-indeterminate{0%{background-position:0% 0%}to{background-position:180% 0%}}.replay-load-modal__meta{color:#9eb4c6;font-size:.92rem}.empty-state{position:absolute;left:50%;top:50%;z-index:10;display:grid;gap:.55rem;min-width:min(20rem,calc(100vw - 2rem));transform:translate(-50%,-50%);padding:.85rem .95rem;border-radius:1rem;border:1px solid rgba(169,201,226,.14);background:#040c12d1;color:#bfd2de;text-align:center;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}.empty-state[hidden]{display:none}.empty-state p{margin:0}.stats-panel{padding:1.15rem 1.15rem 1rem}.panel-heading{display:flex;justify-content:space-between;align-items:start;gap:1rem;margin-bottom:1rem}.player-stats-stack{display:grid;gap:.9rem}.player-team-stack{display:grid;gap:.85rem}.player-team-group{display:grid;gap:.7rem;padding:.75rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:linear-gradient(180deg,var(--team-soft),rgba(255,255,255,.025)),#ffffff08}.player-team-header{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-md);padding-bottom:.42rem;border-bottom:1px solid color-mix(in srgb,var(--team-accent) 36%,transparent)}.player-team-header h3{margin:0;color:#edf5fa;font-size:.76rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.player-team-header span{flex-shrink:0;color:color-mix(in srgb,var(--team-accent) 62%,#edf5fa);font-size:.68rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase}.player-stats-grid{display:flex;gap:.7rem;flex-wrap:wrap}.player-card{flex:1 1 13rem;min-width:12rem;padding:.85rem;border-radius:1rem;border:1px solid rgba(255,255,255,.08);background:#ffffff09}.player-card.team-blue{background:var(--blue-soft);border-color:#4b94ff42}.player-card.team-orange{background:var(--orange-soft);border-color:#f39a3747}.player-card.shared{background:linear-gradient(180deg,#ffffff0f,#ffffff06),#ffffff09;border-color:#ffffff1f}.player-card-header{display:flex;justify-content:space-between;align-items:center;gap:.4rem;margin-bottom:.45rem}.player-name{font-size:.85rem;font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stat-row{display:flex;justify-content:space-between;gap:.5rem;padding:.15rem 0;font-size:.8rem}.label,.detail-grid dt,.stat-row .label{color:#89a4ba}.stat-row .value,.detail-grid dd{font-variant-numeric:tabular-nums}.role-indicator,.depth-indicator{flex-shrink:0;padding:.18rem .45rem;border-radius:999px;font-size:.64rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase}.role-back,.depth-last{background:#ea55552e;color:#ff9b9b}.role-forward,.depth-upfield{background:#4ac6762e;color:#9ce5a8}.role-other,.depth-level{background:#8495a82e;color:#c0cbd6}.role-mid,.depth-mid{background:#f39a372e;color:#ffc680}.stat-module-section{display:grid;gap:.45rem}.stat-module-label{font-size:.72rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase;color:#6f889d}.sidebar{min-height:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));align-content:start;align-items:start;gap:1rem}.stat-window-empty{margin:0;color:#9eb4c6;font-size:.88rem}.stats-window-toolbar,.stats-window-scope-row,.stats-window-actions{display:flex;align-items:center;gap:var(--ui-gap-sm);flex-wrap:wrap}.stats-window-toolbar{justify-content:end}.stats-window-scope-select{min-width:min(100%,13rem)}.stats-window-add-button{width:var(--ui-control-height);min-width:var(--ui-control-height);padding:0;font-size:1rem;font-weight:800;line-height:1}.stats-window-add-button[aria-expanded=true]{border-color:var(--ui-border-hover);background:#ffffff1a}.stats-window-scope-select.team-blue,.stats-window-scope-select.team-orange,.stats-window-stat-target.team-blue,.stats-window-stat-target.team-orange{border-color:var(--team-accent);box-shadow:inset .22rem 0 0 var(--team-accent)}.stats-window-picker{display:grid;gap:var(--ui-gap-sm);padding:var(--ui-panel-padding);border-radius:var(--ui-radius-md);border:1px solid rgba(255,255,255,.08);background:#ffffff0a}.stats-window-picker[hidden]{display:none}.stats-window-picker-list{display:grid;gap:var(--ui-gap-xs);overflow:visible}.stats-window-picker-item{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.45rem;align-items:center;width:100%;padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);text-align:left}.stats-window-picker-item span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stats-window-picker-item strong{color:#87afd4;font-size:.62rem;letter-spacing:.08em;text-transform:uppercase}.stats-window-stat-list,.stats-window-entity-list,.stats-window-team-list{display:grid;gap:var(--ui-gap-sm)}.stats-window-team-group{display:grid;gap:var(--ui-gap-sm);padding:.48rem .5rem .55rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:linear-gradient(180deg,var(--team-soft),rgba(255,255,255,.025)),#ffffff08}.stats-window-team-header{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-md);padding-bottom:.34rem;border-bottom:1px solid color-mix(in srgb,var(--team-accent) 36%,transparent)}.stats-window-team-header h3{margin:0;color:#edf5fa;font-size:.76rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.stats-window-team-header span{flex-shrink:0;color:color-mix(in srgb,var(--team-accent) 62%,#edf5fa);font-size:.68rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase}.stats-window-entity{display:grid;gap:var(--ui-gap-xs);padding-left:.5rem;border-left:2px solid rgba(255,255,255,.12)}.stats-window-entity.team-blue,.stats-window-entity.team-orange{border-left-color:var(--team-accent);background:linear-gradient(90deg,var(--team-soft),transparent 70%)}.stats-window-entity-title{margin:0;color:#edf5fa;font-size:.82rem;font-weight:800}.stats-window-stat-row{display:grid;grid-template-columns:minmax(0,1fr) auto auto;gap:var(--ui-gap-sm);align-items:center;min-height:1.45rem;font-size:.8rem}.stats-window-stat-name{min-width:0;color:#9eb4c6;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stats-window-stat-target{max-width:7rem;margin-left:.35rem;padding:.16rem .3rem;border-radius:var(--ui-radius-sm);font-size:.7rem}.stats-window-stat-value{color:#edf5fa;font-variant-numeric:tabular-nums}.stats-window-stat-remove{padding:.18rem .36rem;border-radius:var(--ui-radius-sm);font-size:.7rem}.goal-label-list{display:grid;gap:var(--ui-gap-sm);min-width:min(26rem,72vw)}.goal-label-item{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--ui-gap-sm);align-items:center;padding:.56rem .62rem;border-left:2px solid rgba(255,255,255,.14);border-radius:var(--ui-radius-md);background:#ffffff09}.goal-label-item.team-blue,.goal-label-item.team-orange{border-left-color:var(--team-accent);background:linear-gradient(90deg,var(--team-soft),rgba(255,255,255,.03))}.goal-label-item header{min-width:0}.goal-label-item h3{margin:0;color:#edf5fa;font-size:.82rem;font-weight:800}.goal-label-item header span{display:block;margin-top:.12rem;color:#9eb4c6;font-size:.72rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.goal-label-tags{grid-column:1 / -1;display:flex;flex-wrap:wrap;gap:.32rem}.goal-label-tag{padding:.16rem .38rem;border-radius:var(--ui-radius-sm);background:#8ec5ff21;color:#cfe6ff;font-size:.68rem;font-weight:800}.goal-label-tag-empty{background:#8495a829;color:#c0cbd6}.goal-label-actions{justify-self:end;display:flex;gap:.28rem}.goal-label-actions button{min-height:1.8rem;padding:.2rem .48rem;font-size:.72rem}.goal-label-actions .goal-label-watch{border-color:#65d6ad5c;background:#65d6ad2e;color:#d7ffef}.stats-window:has(.kickoff-overview){width:min(34rem,calc(100vw - 1.6rem))}.kickoff-overview{display:grid;gap:var(--ui-gap-md);width:100%;min-width:0}.kickoff-overview-hero{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--ui-gap-md);align-items:start;padding-bottom:.52rem;border-bottom:1px solid rgba(255,255,255,.1)}.kickoff-overview-hero h3{margin:0;color:#edf5fa;font-size:.92rem;font-weight:800}.kickoff-overview-hero span{display:block;margin-top:.12rem;color:#9eb4c6;font-size:.72rem}.kickoff-overview-victor{max-width:9rem;padding:.2rem .46rem;border-radius:var(--ui-radius-sm);background:#8495a82e;color:#d8e5ee;font-size:.72rem;font-weight:800;text-align:center}.kickoff-overview-victor.team-blue,.kickoff-overview-victor.team-orange{background:var(--team-soft);color:color-mix(in srgb,var(--team-accent) 72%,#ffffff)}.kickoff-overview-summary{display:grid;grid-template-columns:1fr;gap:var(--ui-gap-sm)}.kickoff-metric{display:grid;gap:.12rem;min-width:0;padding:.46rem .52rem;border-radius:var(--ui-radius-md);border:1px solid rgba(255,255,255,.08);background:#ffffff09}.kickoff-metric span,.kickoff-detail-row span{color:#89a4ba;font-size:.7rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.kickoff-metric strong{min-width:0;color:#edf5fa;font-size:.78rem;overflow-wrap:anywhere}.kickoff-detail-grid{display:grid;gap:.18rem}.kickoff-detail-row{display:grid;grid-template-columns:minmax(7.5rem,1fr) auto;gap:var(--ui-gap-sm);align-items:baseline;min-height:1.38rem;font-size:.78rem}.kickoff-detail-row strong{color:#edf5fa;font-variant-numeric:tabular-nums}.kickoff-strategy-list{display:grid;grid-template-columns:1fr;gap:var(--ui-gap-sm)}.kickoff-strategy-team{display:grid;gap:.34rem;min-width:0;padding:.54rem .58rem;border-radius:var(--ui-radius-md);border:1px solid color-mix(in srgb,var(--team-accent) 26%,transparent);background:linear-gradient(180deg,var(--team-soft),rgba(255,255,255,.025)),#ffffff08}.kickoff-strategy-team h4{margin:0;color:color-mix(in srgb,var(--team-accent) 62%,#edf5fa);font-size:.72rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.kickoff-strategy-line{margin:0;color:#edf5fa;font-size:.78rem;line-height:1.35;overflow-wrap:anywhere}.kickoff-support-list{display:grid;gap:.22rem;margin:0;padding:0;list-style:none}.kickoff-support-list li{color:#afc4d4;font-size:.74rem;line-height:1.3;overflow-wrap:anywhere}@media(min-width:46rem){.kickoff-overview-summary{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:720px){.kickoff-overview-summary,.kickoff-detail-grid,.kickoff-strategy-list,.kickoff-overview-hero{grid-template-columns:1fr}.kickoff-overview-victor{justify-self:start}}.panel{padding:var(--ui-panel-padding);display:grid;gap:var(--ui-gap-md)}.panel>label,.panel>.detail-grid,.panel>.transport-row,.panel>.module-list{margin-top:0}.panel-copy{margin:0;font-size:.92rem;line-height:1.45}.transport-row{display:flex;gap:var(--ui-gap-sm)}.transport-row>*{flex:1 1 auto}.playback-rate-control{display:grid;gap:var(--ui-gap-xs)}.playback-rate-header{align-items:center;display:flex;justify-content:space-between}.playback-rate-header strong{font-variant-numeric:tabular-nums}.playback-rate-notches{color:var(--ui-muted);display:grid;font-size:.72rem;grid-template-columns:repeat(5,minmax(0,1fr));line-height:1.1;text-align:center}.playback-rate-notches span:first-child{text-align:left}.playback-rate-notches span:last-child{text-align:right}.recording-controls{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-sm)}.camera-presets{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-xs)}.camera-presets button{font-size:var(--ui-control-font-size)}.camera-presets button[data-active=true]{border-color:#8ec5ff6b;background:linear-gradient(180deg,#21476bf5,#0c1b2afa);color:#f3f8fc;box-shadow:inset 0 0 0 1px #8ec5ff1f}.camera-ball-cam{display:grid;gap:var(--ui-gap-xs)}.camera-ball-cam-modes{grid-template-columns:repeat(3,minmax(0,1fr))}.camera-settings-controls{display:grid;gap:var(--ui-gap-sm)}.camera-settings-controls[hidden]{display:none}.camera-setting-label{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-md);font-size:.8rem;color:#9fb3c4}.camera-setting-label strong{color:#e8f0f7;font-variant-numeric:tabular-nums}button,select,input[type=file],input[type=range]{border-radius:var(--ui-radius-md)}button,select,input[type=file]{min-height:var(--ui-control-height);border:1px solid var(--ui-border-subtle);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);background:var(--surface-strong);color:var(--text);font-size:var(--ui-control-font-size);line-height:var(--ui-control-line-height)}button{cursor:pointer}select{appearance:none;padding-right:1.35rem;background-image:linear-gradient(45deg,transparent 50%,var(--muted) 50%),linear-gradient(135deg,var(--muted) 50%,transparent 50%);background-position:calc(100% - .76rem) 50%,calc(100% - .52rem) 50%;background-repeat:no-repeat;background-size:.24rem .24rem}button:hover:not(:disabled),select:hover:not(:disabled){border-color:var(--ui-border-hover)}button:disabled,select:disabled,input:disabled{opacity:.55;cursor:not-allowed}input[type=range]{width:100%;margin-top:var(--ui-gap-xs);accent-color:var(--blue)}.metric-readout{font-size:.88rem;font-weight:700;font-variant-numeric:tabular-nums}.toggle{display:inline-flex;align-items:center;gap:.4rem;color:#bfd0dd}.detail-grid{margin:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.55rem .7rem}.detail-grid dt,.detail-grid dd{margin:0}.detail-grid dt{font-size:.68rem;margin-bottom:.12rem}.detail-grid dd{font-size:.84rem;color:var(--text);overflow-wrap:anywhere}.module-groups{display:grid;gap:var(--ui-gap-md)}.module-summary-group{display:grid;gap:var(--ui-gap-xs)}.module-summary-group h3{margin:0;color:#87afd4;font-size:.64rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase}.module-list{display:flex;flex-wrap:wrap;gap:.5rem}.mechanics-actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem;margin-bottom:.65rem}.mechanics-event-list{display:grid;grid-template-columns:repeat(var(--event-source-columns, 1),minmax(9.5rem,1fr));align-items:stretch}.module-settings{display:grid;gap:.75rem}.module-settings-card{display:grid;gap:.75rem;padding:.85rem .9rem;border-radius:1rem;border:1px solid rgba(255,255,255,.08);background:#ffffff09}.module-settings-subgroup{display:grid;gap:.65rem;padding-top:.15rem;border-top:1px solid rgba(255,255,255,.06)}.module-settings-options{display:grid;gap:.45rem}.module-settings-group-title{margin:0;color:#d7e5ef;font-size:.78rem;font-weight:800}.module-settings-header{display:flex;align-items:start;justify-content:space-between;gap:.8rem}.module-settings-header h3{margin:.1rem 0 0;font-size:.96rem}.module-settings-eyebrow{margin:0;font-size:.66rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase;color:#87afd4}.boost-pickup-filter-panel{display:grid;gap:.65rem}.boost-pickup-filter-summary{display:flex;justify-content:end}.boost-pickup-filter-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.75rem 1rem}.boost-pickup-filter-group{display:grid;align-content:start;gap:.35rem;min-width:0}.boost-pickup-filter-group[hidden]{display:none}.boost-pickup-filter-group-wide{grid-column:1 / -1}.boost-pickup-filter-options{display:flex;flex-wrap:wrap;gap:.35rem .8rem;min-width:0}.boost-pickup-filter-options .toggle{min-width:0}.module-summary-item{appearance:none;display:inline-flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm);min-height:var(--ui-control-height);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border-radius:var(--ui-radius-pill);border:1px solid var(--ui-border-subtle);background:#ffffff08;color:var(--muted);font:inherit;font-size:var(--ui-control-font-size);line-height:var(--ui-control-line-height);cursor:pointer;transition:border-color .14s ease,background-color .14s ease,color .14s ease}.module-summary-item:hover{border-color:var(--ui-border-hover);color:var(--text)}.module-summary-item strong{font-size:.62rem;letter-spacing:.08em;text-transform:uppercase}.module-summary-item[data-active=true]{border-color:#4b94ff38;background:#4b94ff14;color:#dceafb}@media(max-width:1180px){.sidebar{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:860px){.shell{padding:0}.sidebar{grid-template-columns:1fr}.panel-heading{display:grid}.detail-grid{grid-template-columns:1fr 1fr}.viewport-panel{min-height:100dvh}}@media(max-width:560px){.detail-grid{grid-template-columns:1fr}.transport-row{flex-direction:column}.floating-window,.stats-window{left:.55rem;right:.55rem;width:auto}}@media(max-width:720px){.viewport-panel:has(.floating-window:not([hidden])) .viewport{inset:0 0 52dvh}.floating-window{position:fixed;inset:auto 0 0;width:100%;max-width:none;height:52dvh;max-height:52dvh;overflow:auto;border-width:1px 0 0 0;border-radius:1rem 1rem 0 0;transform:none;z-index:30}.floating-window .floating-window-header{cursor:default}}.missed-event-body{display:flex;flex-direction:column;gap:.5rem;padding:.6rem .7rem;max-height:50vh;font-size:.8rem}.missed-event-controls{display:flex;align-items:center;gap:.4rem}.missed-event-controls select{flex:1 1 auto}.missed-event-list{list-style:none;margin:0;padding:0;overflow-y:auto;display:flex;flex-direction:column;gap:.25rem}.missed-event-list li{display:flex;align-items:center;justify-content:space-between;gap:.4rem;padding:.2rem .3rem;border-radius:.3rem;background:#1c272ee6}.missed-event-status{margin:0;min-height:1rem;color:#9fadb7} +:root{color-scheme:dark;font-family:IBM Plex Sans,Avenir Next,sans-serif;font-size:13px;--surface: rgba(8, 20, 30, .82);--surface-strong: rgba(7, 16, 24, .94);--surface-soft: rgba(12, 28, 40, .72);--border: rgba(167, 199, 222, .14);--text: #edf5fa;--muted: #9eb4c6;--blue: #4b94ff;--blue-soft: rgba(75, 148, 255, .18);--orange: #f39a37;--orange-soft: rgba(243, 154, 55, .18);--ui-gap-xs: .22rem;--ui-gap-sm: .34rem;--ui-gap-md: .5rem;--ui-panel-padding: .52rem;--ui-control-font-size: .72rem;--ui-control-line-height: 1.15;--ui-control-padding-block: .22rem;--ui-control-padding-inline: .38rem;--ui-control-height: 1.55rem;--ui-radius-sm: .36rem;--ui-radius-md: .5rem;--ui-radius-lg: .72rem;--ui-radius-pill: 999px;--ui-border-subtle: rgba(255, 255, 255, .1);--ui-border-hover: rgba(255, 255, 255, .18);--ui-overlay-bg: rgba(4, 12, 18, .82);--ui-overlay-bg-strong: rgba(4, 12, 18, .9);background:radial-gradient(circle at top left,rgba(73,112,158,.28),transparent 32%),radial-gradient(circle at top right,rgba(243,154,55,.12),transparent 24%),linear-gradient(180deg,#071018,#0b1721);color:var(--text)}*,*:before,*:after{box-sizing:border-box}html,body,#app{width:100%;height:100%;overflow:hidden}body{margin:0}button,select,input{font:inherit}.shell{min-height:100dvh;height:100dvh;padding:0;display:block}.workspace{height:100%;display:block;min-height:0}.panel h2,.stats-panel h2{margin:0}.panel-copy{color:#bdd0de}.viewport-panel,.panel,.stats-panel{position:relative;border:1px solid var(--border);border-radius:1.4rem;background:var(--surface);box-shadow:0 22px 56px #0000003d;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}.viewport-panel{width:100%;height:100%;min-height:100dvh;overflow:hidden;border:0;border-radius:0;background:#061019;box-shadow:none}.viewport{position:absolute;inset:0}.top-chrome{position:absolute;top:.8rem;left:.8rem;z-index:20}.launcher-toggle{width:2.65rem;min-width:0;aspect-ratio:1;display:grid;place-items:center;padding:0;border-color:transparent;border-radius:var(--ui-radius-md);background:#050e16ad;box-shadow:0 12px 30px #0000004d;-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px)}.launcher-toggle:hover,.launcher-toggle[aria-expanded=true]{border-color:#ffffff29;background:#081824d1}.launcher-toggle-bars,.launcher-toggle-bars:before,.launcher-toggle-bars:after{display:block;width:1.18rem;height:.12rem;border-radius:var(--ui-radius-pill);background:#edf5fa}.launcher-toggle-bars{position:relative}.launcher-toggle-bars:before,.launcher-toggle-bars:after{content:"";position:absolute;left:0}.launcher-toggle-bars:before{top:-.38rem}.launcher-toggle-bars:after{top:.38rem}.launcher-menu{position:absolute;top:calc(100% + .55rem);left:0;width:min(22rem,calc(100vw - 1.6rem));max-height:calc(100dvh - 7.5rem);overflow:auto;display:grid;gap:var(--ui-gap-md);padding:var(--ui-panel-padding);border:1px solid rgba(255,255,255,.12);border-radius:var(--ui-radius-lg);background:var(--ui-overlay-bg-strong);box-shadow:0 18px 54px #0000005c;-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px)}.launcher-menu[hidden]{display:none}.launcher-section{display:grid;gap:var(--ui-gap-xs)}.launcher-section h2{margin:0;color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase}.launcher-section button{width:100%;text-align:left}.hidden-file-input,.visually-hidden{position:fixed;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap}.team-blue{--team-accent: var(--blue);--team-soft: var(--blue-soft)}.team-orange{--team-accent: var(--orange);--team-soft: var(--orange-soft)}.floating-window-layer,.stats-window-layer{position:absolute;inset:0;z-index:12;pointer-events:none}.floating-window,.stats-window,.scoreboard-window{position:absolute;left:clamp(.8rem,var(--window-x, 1rem),calc(100vw - 18rem));top:clamp(.8rem,var(--window-y, 1rem),calc(100dvh - 12rem));width:min(26rem,calc(100vw - 1.6rem));overflow:visible;display:grid;gap:var(--ui-gap-md);padding:var(--ui-panel-padding);border:1px solid rgba(255,255,255,.12);border-radius:var(--ui-radius-lg);background:var(--ui-overlay-bg);box-shadow:0 16px 44px #00000052;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);pointer-events:auto;-webkit-user-select:none;user-select:none}.floating-window[hidden],.stats-window[hidden],.scoreboard-window[hidden]{display:none}.scoreboard-window{left:50%;top:.7rem;width:auto;min-width:4.4rem;transform:translate(-50%);gap:var(--ui-gap-sm);padding:.34rem .62rem;border-radius:999px}.scoreboard-window-body{display:grid;gap:.42rem}.scoreboard-scoreline{display:grid;grid-template-columns:minmax(1.2rem,auto) auto minmax(1.2rem,auto);align-items:center;justify-content:center;gap:.3rem;min-width:0;font-variant-numeric:tabular-nums}.scoreboard-goal-value{color:var(--team-accent);font-size:1rem;font-weight:850;line-height:1;text-align:center}.scoreboard-divider{color:var(--muted);font-size:1rem;font-weight:800;line-height:1}.scoreboard-empty{margin:0;color:var(--muted);font-size:.74rem;text-align:center}@media(max-width:900px){.scoreboard-window{top:3.25rem}}@media(max-width:640px){.scoreboard-window{min-width:4rem;padding:.32rem .56rem}.scoreboard-scoreline{gap:.24rem}.scoreboard-goal-value{font-size:.92rem}}.floating-window-camera{width:min(26rem,calc(100vw - 1.6rem))}.floating-window-recording{--window-x: calc(100vw - 27rem) ;width:min(26rem,calc(100vw - 1.6rem))}.floating-window-playback{--window-x: calc(100vw - 23rem) ;width:min(21rem,calc(100vw - 1.6rem))}.floating-window-mechanics{width:auto;min-width:min(18rem,calc(100vw - 1.6rem));max-width:min(42rem,calc(100vw - 1.6rem))}.mechanics-timeline-window-body{display:grid;gap:var(--ui-gap-sm);max-height:min(72dvh,42rem);overflow:auto}.floating-window-event-playlist{width:min(27rem,calc(100vw - 1.6rem))}.floating-window-mechanics-review{width:min(30rem,calc(100vw - 1.6rem))}.floating-window-replay-loading{width:min(32rem,calc(100vw - 1.6rem))}.floating-window-boost-pickups{width:min(34rem,calc(100vw - 1.6rem))}.floating-window-touch-controls,.floating-window-touch-legend{width:min(24rem,calc(100vw - 1.6rem))}.floating-window-shot-visualization{width:min(38rem,calc(100vw - 1.6rem))}.floating-window-header,.stats-window-header{display:flex;align-items:start;justify-content:space-between;gap:var(--ui-gap-md);cursor:grab}.stats-window-header-actions-only{justify-content:end}.floating-window:active .floating-window-header,.stats-window:active .stats-window-header{cursor:grabbing}.floating-window-header h2,.stats-window-header h2{margin:0;color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase}.floating-window-hide,.stats-window-action{flex-shrink:0;padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border-radius:var(--ui-radius-md);font-size:var(--ui-control-font-size)}.mechanics-review-window-body{display:grid;gap:var(--ui-gap-md);max-height:min(74dvh,42rem);min-height:0;overflow:hidden auto;scrollbar-width:thin}.event-playlist-window-body{display:grid;gap:var(--ui-gap-sm);min-height:0}.touch-color-legend-body{display:grid;gap:var(--ui-gap-md);max-height:min(70dvh,38rem);overflow:auto;scrollbar-width:thin}.touch-color-legend-explainer{display:grid;gap:var(--ui-gap-xs);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);color:#c3d3df;font-size:.78rem;background:#ffffff0a}.touch-color-legend-group{display:grid;gap:var(--ui-gap-xs)}.touch-color-legend-heading{width:100%;min-height:1.45rem;margin:0;padding:.12rem .32rem;border-radius:var(--ui-radius-sm);color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.1em;text-align:left;text-transform:uppercase}.touch-color-legend-heading[data-active=true]{border-color:#8ec5ff6b;background:#21476b94;color:#f3f8fc}.touch-color-legend-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-xs)}.touch-color-legend-item{min-width:0;display:flex;align-items:center;gap:var(--ui-gap-xs);color:#e8f0f7;font-size:.76rem}.touch-color-legend-swatch{flex:0 0 auto;width:.78rem;height:.78rem;border:1px solid rgba(255,255,255,.35);border-radius:50%;box-shadow:0 0 0 1px #00000038}.event-playlist-toolbar{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm)}.event-playlist-filter{position:relative;min-width:0}.event-playlist-filter summary{display:inline-flex;align-items:center;min-height:var(--ui-control-height);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);background:#ffffff0a;color:var(--text);font-size:var(--ui-control-font-size);cursor:pointer;list-style:none}.event-playlist-filter summary::-webkit-details-marker{display:none}.event-playlist-filter-panel{position:absolute;z-index:5;top:calc(100% + .4rem);left:0;width:min(22rem,calc(100vw - 3rem));max-height:min(28rem,calc(100dvh - 10rem));overflow:auto;display:grid;gap:var(--ui-gap-md);padding:.85rem;border:1px solid rgba(255,255,255,.14);border-radius:var(--ui-radius-md);background:#090e16fa;box-shadow:0 16px 34px #00000057}.event-playlist-filter-actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem}.event-playlist-filter-group{display:grid;gap:.45rem}.event-playlist-filter-group h3{margin:0;color:#87afd4;font-size:.64rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase}.event-playlist-filter-option{min-width:0}.event-playlist-follow{flex-shrink:0}.event-playlist-list{max-height:min(31rem,calc(100dvh - 11rem));overflow:auto;display:grid;gap:.45rem;padding-right:.15rem;scrollbar-width:thin}.event-playlist-item{--event-color: #d1d9e0;appearance:none;width:100%;display:grid;grid-template-columns:3.4rem minmax(0,1fr);gap:.7rem;align-items:start;padding:.6rem .7rem;border:1px solid rgba(255,255,255,.09);border-left:.28rem solid var(--event-color);border-radius:var(--ui-radius-md);background:#ffffff09;color:var(--text);font:inherit;text-align:left;cursor:pointer}.event-playlist-item:hover,.event-playlist-item[data-active=true]{border-color:color-mix(in srgb,var(--event-color) 48%,rgba(255,255,255,.12));background:color-mix(in srgb,var(--event-color) 15%,rgba(255,255,255,.045))}.event-playlist-time{color:var(--muted);font-size:.72rem;font-variant-numeric:tabular-nums;line-height:1.35}.event-playlist-main{min-width:0;display:grid;gap:.15rem}.shot-visualization{display:grid;gap:var(--ui-gap-md);min-height:0}.shot-visualization-summary{color:var(--text);font-size:.78rem;font-weight:700;font-variant-numeric:tabular-nums}.shot-chart-canvas{width:100%;aspect-ratio:16 / 10;display:block;border:1px solid rgba(255,255,255,.1);border-radius:var(--ui-radius-md);background:#0f2b24}.shot-visualization-layout{display:grid;grid-template-columns:minmax(10rem,.78fr) minmax(15rem,1.22fr);gap:var(--ui-gap-md);min-height:0}.shot-list{display:grid;align-content:start;gap:.45rem;max-height:18rem;overflow:auto;padding-right:.15rem;scrollbar-width:thin}.shot-list-item{appearance:none;width:100%;display:grid;gap:.15rem;min-height:3.1rem;padding:.52rem .62rem;border:1px solid rgba(255,255,255,.09);border-left:.24rem solid #62d2a2;border-radius:var(--ui-radius-md);background:#ffffff09;color:var(--text);font:inherit;text-align:left;cursor:pointer}.shot-list-item[data-selected=true]{border-color:#f8fafcb8;background:#87afd429}.shot-list-item[data-active=true]{border-left-color:#e11d48}.shot-list-title{min-width:0;overflow:hidden;color:var(--text);font-size:.78rem;font-weight:800;text-overflow:ellipsis;white-space:nowrap}.shot-list-meta{color:var(--muted);font-size:.68rem;font-variant-numeric:tabular-nums;white-space:nowrap}.shot-demo-panel{display:grid;gap:var(--ui-gap-sm);min-width:0}.shot-demo-scene{width:100%;height:12rem;overflow:hidden;border:1px solid rgba(255,255,255,.1);border-radius:var(--ui-radius-md);background:#07111c}.shot-demo-scene canvas{width:100%;height:100%;display:block}.shot-details{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem;margin:0}.shot-details div{min-width:0;padding:.48rem .56rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:#ffffff09}.shot-details dt{color:var(--muted);font-size:.62rem;font-weight:700;text-transform:uppercase}.shot-details dd{min-width:0;margin:.14rem 0 0;overflow:hidden;color:var(--text);font-size:.76rem;font-variant-numeric:tabular-nums;text-overflow:ellipsis;white-space:nowrap}.shot-visualization-empty{margin:0;color:var(--muted);font-size:.78rem}.event-playlist-main strong{min-width:0;overflow-wrap:anywhere;font-size:.82rem;line-height:1.3}.event-playlist-main span{min-width:0;overflow-wrap:anywhere;color:var(--muted);font-size:.68rem;line-height:1.35}.mechanics-review-load-row{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:var(--ui-gap-sm);align-items:center}.mechanics-review-file{display:inline-grid;align-items:center;min-height:var(--ui-control-height);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);background:#ffffff0e;color:var(--text);cursor:pointer}.mechanics-review-file input{position:fixed;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap}.mechanics-review-url{min-width:0}.mechanics-review-status{min-height:1.2rem;color:var(--muted);font-size:.78rem}.mechanics-review-current{display:grid;gap:var(--ui-gap-sm);padding:.55rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:#ffffff09}.mechanics-review-index{color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase}.mechanics-review-current h3{margin:0;font-size:.96rem;line-height:1.2}.mechanics-review-fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-sm);margin:0}.mechanics-review-fields div{min-width:0}.mechanics-review-fields dt{color:var(--muted);font-size:.68rem;text-transform:uppercase}.mechanics-review-fields dd{margin:.1rem 0 0;overflow-wrap:anywhere}.mechanics-review-wide{grid-column:1 / -1}.mechanics-review-actions,.mechanics-review-decision-actions,.mechanics-review-list-header{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm)}.mechanics-review-actions button,.mechanics-review-decision-actions button{flex:1 1 0}#mechanics-review-confirm{border-color:#4caf7885}#mechanics-review-reject{border-color:#dc5f5f94}.mechanics-review-list-header{color:var(--muted);font-size:.72rem;font-weight:700;text-transform:uppercase}.mechanics-review-replays{display:grid;gap:var(--ui-gap-xs)}.replay-loading-window-body{display:grid;gap:var(--ui-gap-sm);max-height:min(72dvh,40rem);min-height:0}.replay-loading-summary{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm);color:var(--muted);font-size:.72rem;font-weight:700;text-transform:uppercase}.replay-loading-list{max-height:min(38rem,calc(100dvh - 9rem));overflow:auto;display:grid;gap:var(--ui-gap-xs);padding-right:.15rem;scrollbar-width:thin}.mechanics-review-replay-load{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.35rem var(--ui-gap-sm);min-width:0;padding:.5rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:#ffffff09}.mechanics-review-replay-load.loaded{border-color:#4caf786b}.mechanics-review-replay-load.error{border-color:#dc5f5f94}.mechanics-review-replay-load-main{display:grid;min-width:0;gap:.16rem}.mechanics-review-replay-load-title,.mechanics-review-replay-load-meta{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-replay-load-title{color:var(--text);font-size:.78rem;font-weight:700}.mechanics-review-replay-load-meta{color:var(--muted);font-size:.68rem}.mechanics-review-replay-load-status{max-width:11rem;overflow:hidden;color:var(--muted);font-size:.68rem;text-align:right;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-replay-load.loaded .mechanics-review-replay-load-status{color:#83d4a4}.mechanics-review-replay-load.error .mechanics-review-replay-load-status{color:#ff9b9b}.mechanics-review-replay-load-progress{grid-column:1 / -1;height:.25rem;overflow:hidden;border-radius:999px;background:#ffffff14}.mechanics-review-replay-load-progress span{display:block;width:0;height:100%;border-radius:inherit;background:#77a9ff;transition:width .14s ease}.mechanics-review-replay-load.loaded .mechanics-review-replay-load-progress span{background:#4caf78}.mechanics-review-replay-load.error .mechanics-review-replay-load-progress span{background:#dc5f5f}.mechanics-review-list{max-height:min(22rem,calc(100dvh - 27rem));display:grid;gap:var(--ui-gap-xs);overflow:auto;padding-right:.15rem;scrollbar-width:thin}.mechanics-review-item{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--ui-gap-sm);align-items:center;width:100%;min-height:2rem;text-align:left}.mechanics-review-item span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-item strong{color:var(--muted);font-size:.72rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-item[data-active=true]{border-color:#4b94ff6b;background:#4b94ff29}.viewport canvas{display:block;width:100%;height:100%}.replay-load-modal{position:fixed;inset:0;z-index:100;display:grid;place-items:center;padding:1.25rem;background:radial-gradient(circle at top,rgba(89,157,219,.18),transparent 30%),#040b12c2;-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px)}.replay-load-modal[hidden]{display:none}.replay-load-modal__dialog{width:min(32rem,100%);display:grid;gap:.75rem;padding:1.4rem 1.45rem;border-radius:1.35rem;border:1px solid rgba(255,255,255,.12);background:linear-gradient(180deg,#0b1724f5,#070f18f0);box-shadow:0 24px 70px #0006}.replay-load-modal__eyebrow{margin:0;font-size:.72rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase;color:#87afd4}.replay-load-modal__title,.replay-load-modal__status,.replay-load-modal__meta{margin:0}.replay-load-modal__title{font-size:clamp(1.45rem,4vw,2.1rem);line-height:1.1;color:#f3f8fc}.replay-load-modal__status{color:#e6f0f7;font-size:1rem}.replay-load-modal__phase-list{display:grid;gap:.52rem}.replay-load-modal__phase-row{display:grid;gap:.28rem}.replay-load-modal__phase-label{margin:0;font-size:.82rem;letter-spacing:.04em;color:#9eb4c6}.replay-load-modal__phase-row[data-state=active] .replay-load-modal__phase-label{color:#edf5fa}.replay-load-modal__phase-row[data-state=complete] .replay-load-modal__phase-label{color:#c5d9e7}.replay-load-modal__phase-bar{overflow:hidden;height:.58rem;border-radius:999px;background:#ffffff1a}.replay-load-modal__phase-fill{width:0%;height:100%;border-radius:inherit;background:linear-gradient(90deg,#4b94ff,#8ec5ff 55%,#f39a37);transition:width .14s ease}.replay-load-modal__phase-row[data-state=complete] .replay-load-modal__phase-fill{opacity:.95}.replay-load-modal__phase-fill[data-indeterminate=true]{width:100%!important;background:linear-gradient(90deg,#4b94ff40,#4b94ffcc 28%,#8ec5fff2,#f39a37cc 72%,#f39a3740);background-size:180% 100%;animation:replay-load-phase-indeterminate 1.1s linear infinite}@keyframes replay-load-phase-indeterminate{0%{background-position:0% 0%}to{background-position:180% 0%}}.replay-load-modal__meta{color:#9eb4c6;font-size:.92rem}.empty-state{position:absolute;left:50%;top:50%;z-index:10;display:grid;gap:.55rem;min-width:min(20rem,calc(100vw - 2rem));transform:translate(-50%,-50%);padding:.85rem .95rem;border-radius:1rem;border:1px solid rgba(169,201,226,.14);background:#040c12d1;color:#bfd2de;text-align:center;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}.empty-state[hidden]{display:none}.empty-state p{margin:0}.stats-panel{padding:1.15rem 1.15rem 1rem}.panel-heading{display:flex;justify-content:space-between;align-items:start;gap:1rem;margin-bottom:1rem}.player-stats-stack{display:grid;gap:.9rem}.player-team-stack{display:grid;gap:.85rem}.player-team-group{display:grid;gap:.7rem;padding:.75rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:linear-gradient(180deg,var(--team-soft),rgba(255,255,255,.025)),#ffffff08}.player-team-header{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-md);padding-bottom:.42rem;border-bottom:1px solid color-mix(in srgb,var(--team-accent) 36%,transparent)}.player-team-header h3{margin:0;color:#edf5fa;font-size:.76rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.player-team-header span{flex-shrink:0;color:color-mix(in srgb,var(--team-accent) 62%,#edf5fa);font-size:.68rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase}.player-stats-grid{display:flex;gap:.7rem;flex-wrap:wrap}.player-card{flex:1 1 13rem;min-width:12rem;padding:.85rem;border-radius:1rem;border:1px solid rgba(255,255,255,.08);background:#ffffff09}.player-card.team-blue{background:var(--blue-soft);border-color:#4b94ff42}.player-card.team-orange{background:var(--orange-soft);border-color:#f39a3747}.player-card.shared{background:linear-gradient(180deg,#ffffff0f,#ffffff06),#ffffff09;border-color:#ffffff1f}.player-card-header{display:flex;justify-content:space-between;align-items:center;gap:.4rem;margin-bottom:.45rem}.player-name{font-size:.85rem;font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stat-row{display:flex;justify-content:space-between;gap:.5rem;padding:.15rem 0;font-size:.8rem}.label,.detail-grid dt,.stat-row .label{color:#89a4ba}.stat-row .value,.detail-grid dd{font-variant-numeric:tabular-nums}.role-indicator,.depth-indicator{flex-shrink:0;padding:.18rem .45rem;border-radius:999px;font-size:.64rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase}.role-back,.depth-last{background:#ea55552e;color:#ff9b9b}.role-forward,.depth-upfield{background:#4ac6762e;color:#9ce5a8}.role-other,.depth-level{background:#8495a82e;color:#c0cbd6}.role-mid,.depth-mid{background:#f39a372e;color:#ffc680}.stat-module-section{display:grid;gap:.45rem}.stat-module-label{font-size:.72rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase;color:#6f889d}.sidebar{min-height:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));align-content:start;align-items:start;gap:1rem}.stat-window-empty{margin:0;color:#9eb4c6;font-size:.88rem}.stats-window-toolbar,.stats-window-scope-row,.stats-window-actions{display:flex;align-items:center;gap:var(--ui-gap-sm);flex-wrap:wrap}.stats-window-toolbar{justify-content:end}.stats-window-scope-select{min-width:min(100%,13rem)}.stats-window-add-button{width:var(--ui-control-height);min-width:var(--ui-control-height);padding:0;font-size:1rem;font-weight:800;line-height:1}.stats-window-add-button[aria-expanded=true]{border-color:var(--ui-border-hover);background:#ffffff1a}.stats-window-scope-select.team-blue,.stats-window-scope-select.team-orange,.stats-window-stat-target.team-blue,.stats-window-stat-target.team-orange{border-color:var(--team-accent);box-shadow:inset .22rem 0 0 var(--team-accent)}.stats-window-picker{display:grid;gap:var(--ui-gap-sm);padding:var(--ui-panel-padding);border-radius:var(--ui-radius-md);border:1px solid rgba(255,255,255,.08);background:#ffffff0a}.stats-window-picker[hidden]{display:none}.stats-window-picker-list{display:grid;gap:var(--ui-gap-xs);overflow:visible}.stats-window-picker-item{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.45rem;align-items:center;width:100%;padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);text-align:left}.stats-window-picker-item span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stats-window-picker-item strong{color:#87afd4;font-size:.62rem;letter-spacing:.08em;text-transform:uppercase}.stats-window-stat-list,.stats-window-entity-list,.stats-window-team-list{display:grid;gap:var(--ui-gap-sm)}.stats-window-team-group{display:grid;gap:var(--ui-gap-sm);padding:.48rem .5rem .55rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:linear-gradient(180deg,var(--team-soft),rgba(255,255,255,.025)),#ffffff08}.stats-window-team-header{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-md);padding-bottom:.34rem;border-bottom:1px solid color-mix(in srgb,var(--team-accent) 36%,transparent)}.stats-window-team-header h3{margin:0;color:#edf5fa;font-size:.76rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.stats-window-team-header span{flex-shrink:0;color:color-mix(in srgb,var(--team-accent) 62%,#edf5fa);font-size:.68rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase}.stats-window-entity{display:grid;gap:var(--ui-gap-xs);padding-left:.5rem;border-left:2px solid rgba(255,255,255,.12)}.stats-window-entity.team-blue,.stats-window-entity.team-orange{border-left-color:var(--team-accent);background:linear-gradient(90deg,var(--team-soft),transparent 70%)}.stats-window-entity-title{margin:0;color:#edf5fa;font-size:.82rem;font-weight:800}.stats-window-stat-row{display:grid;grid-template-columns:minmax(0,1fr) auto auto;gap:var(--ui-gap-sm);align-items:center;min-height:1.45rem;font-size:.8rem}.stats-window-stat-name{min-width:0;color:#9eb4c6;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stats-window-stat-target{max-width:7rem;margin-left:.35rem;padding:.16rem .3rem;border-radius:var(--ui-radius-sm);font-size:.7rem}.stats-window-stat-value{color:#edf5fa;font-variant-numeric:tabular-nums}.stats-window-stat-remove{padding:.18rem .36rem;border-radius:var(--ui-radius-sm);font-size:.7rem}.goal-label-list{display:grid;gap:var(--ui-gap-sm);min-width:min(26rem,72vw)}.goal-label-item{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--ui-gap-sm);align-items:center;padding:.56rem .62rem;border-left:2px solid rgba(255,255,255,.14);border-radius:var(--ui-radius-md);background:#ffffff09}.goal-label-item.team-blue,.goal-label-item.team-orange{border-left-color:var(--team-accent);background:linear-gradient(90deg,var(--team-soft),rgba(255,255,255,.03))}.goal-label-item header{min-width:0}.goal-label-item h3{margin:0;color:#edf5fa;font-size:.82rem;font-weight:800}.goal-label-item header span{display:block;margin-top:.12rem;color:#9eb4c6;font-size:.72rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.goal-label-tags{grid-column:1 / -1;display:flex;flex-wrap:wrap;gap:.32rem}.goal-label-tag{padding:.16rem .38rem;border-radius:var(--ui-radius-sm);background:#8ec5ff21;color:#cfe6ff;font-size:.68rem;font-weight:800}.goal-label-tag-empty{background:#8495a829;color:#c0cbd6}.goal-label-actions{justify-self:end;display:flex;gap:.28rem}.goal-label-actions button{min-height:1.8rem;padding:.2rem .48rem;font-size:.72rem}.goal-label-actions .goal-label-watch{border-color:#65d6ad5c;background:#65d6ad2e;color:#d7ffef}.stats-window:has(.kickoff-overview){width:min(34rem,calc(100vw - 1.6rem))}.kickoff-overview{display:grid;gap:var(--ui-gap-md);width:100%;min-width:0}.kickoff-overview-hero{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--ui-gap-md);align-items:start;padding-bottom:.52rem;border-bottom:1px solid rgba(255,255,255,.1)}.kickoff-overview-hero h3{margin:0;color:#edf5fa;font-size:.92rem;font-weight:800}.kickoff-overview-hero span{display:block;margin-top:.12rem;color:#9eb4c6;font-size:.72rem}.kickoff-overview-victor{max-width:9rem;padding:.2rem .46rem;border-radius:var(--ui-radius-sm);background:#8495a82e;color:#d8e5ee;font-size:.72rem;font-weight:800;text-align:center}.kickoff-overview-victor.team-blue,.kickoff-overview-victor.team-orange{background:var(--team-soft);color:color-mix(in srgb,var(--team-accent) 72%,#ffffff)}.kickoff-overview-summary{display:grid;grid-template-columns:1fr;gap:var(--ui-gap-sm)}.kickoff-metric{display:grid;gap:.12rem;min-width:0;padding:.46rem .52rem;border-radius:var(--ui-radius-md);border:1px solid rgba(255,255,255,.08);background:#ffffff09}.kickoff-metric span,.kickoff-detail-row span{color:#89a4ba;font-size:.7rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.kickoff-metric strong{min-width:0;color:#edf5fa;font-size:.78rem;overflow-wrap:anywhere}.kickoff-detail-grid{display:grid;gap:.18rem}.kickoff-detail-row{display:grid;grid-template-columns:minmax(7.5rem,1fr) auto;gap:var(--ui-gap-sm);align-items:baseline;min-height:1.38rem;font-size:.78rem}.kickoff-detail-row strong{color:#edf5fa;font-variant-numeric:tabular-nums}.kickoff-strategy-list{display:grid;grid-template-columns:1fr;gap:var(--ui-gap-sm)}.kickoff-strategy-team{display:grid;gap:.34rem;min-width:0;padding:.54rem .58rem;border-radius:var(--ui-radius-md);border:1px solid color-mix(in srgb,var(--team-accent) 26%,transparent);background:linear-gradient(180deg,var(--team-soft),rgba(255,255,255,.025)),#ffffff08}.kickoff-strategy-team h4{margin:0;color:color-mix(in srgb,var(--team-accent) 62%,#edf5fa);font-size:.72rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.kickoff-strategy-line{margin:0;color:#edf5fa;font-size:.78rem;line-height:1.35;overflow-wrap:anywhere}.kickoff-support-list{display:grid;gap:.22rem;margin:0;padding:0;list-style:none}.kickoff-support-list li{color:#afc4d4;font-size:.74rem;line-height:1.3;overflow-wrap:anywhere}@media(min-width:46rem){.kickoff-overview-summary{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:720px){.kickoff-overview-summary,.kickoff-detail-grid,.kickoff-strategy-list,.kickoff-overview-hero{grid-template-columns:1fr}.kickoff-overview-victor{justify-self:start}}.panel{padding:var(--ui-panel-padding);display:grid;gap:var(--ui-gap-md)}.panel>label,.panel>.detail-grid,.panel>.transport-row,.panel>.module-list{margin-top:0}.panel-copy{margin:0;font-size:.92rem;line-height:1.45}.transport-row{display:flex;gap:var(--ui-gap-sm)}.transport-row>*{flex:1 1 auto}.playback-rate-control{display:grid;gap:var(--ui-gap-xs)}.playback-rate-header{align-items:center;display:flex;justify-content:space-between}.playback-rate-header strong{font-variant-numeric:tabular-nums}.playback-rate-notches{color:var(--ui-muted);display:grid;font-size:.72rem;grid-template-columns:repeat(5,minmax(0,1fr));line-height:1.1;text-align:center}.playback-rate-notches span:first-child{text-align:left}.playback-rate-notches span:last-child{text-align:right}.recording-controls{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-sm)}.camera-presets{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-xs)}.camera-presets button{font-size:var(--ui-control-font-size)}.camera-presets button[data-active=true]{border-color:#8ec5ff6b;background:linear-gradient(180deg,#21476bf5,#0c1b2afa);color:#f3f8fc;box-shadow:inset 0 0 0 1px #8ec5ff1f}.camera-ball-cam{display:grid;gap:var(--ui-gap-xs)}.camera-ball-cam-modes{grid-template-columns:repeat(3,minmax(0,1fr))}.camera-settings-controls{display:grid;gap:var(--ui-gap-sm)}.camera-settings-controls[hidden]{display:none}.camera-setting-label{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-md);font-size:.8rem;color:#9fb3c4}.camera-setting-label strong{color:#e8f0f7;font-variant-numeric:tabular-nums}button,select,input[type=file],input[type=range]{border-radius:var(--ui-radius-md)}button,select,input[type=file]{min-height:var(--ui-control-height);border:1px solid var(--ui-border-subtle);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);background:var(--surface-strong);color:var(--text);font-size:var(--ui-control-font-size);line-height:var(--ui-control-line-height)}button{cursor:pointer}select{appearance:none;padding-right:1.35rem;background-image:linear-gradient(45deg,transparent 50%,var(--muted) 50%),linear-gradient(135deg,var(--muted) 50%,transparent 50%);background-position:calc(100% - .76rem) 50%,calc(100% - .52rem) 50%;background-repeat:no-repeat;background-size:.24rem .24rem}button:hover:not(:disabled),select:hover:not(:disabled){border-color:var(--ui-border-hover)}button:disabled,select:disabled,input:disabled{opacity:.55;cursor:not-allowed}input[type=range]{width:100%;margin-top:var(--ui-gap-xs);accent-color:var(--blue)}.metric-readout{font-size:.88rem;font-weight:700;font-variant-numeric:tabular-nums}.toggle{display:inline-flex;align-items:center;gap:.4rem;color:#bfd0dd}.detail-grid{margin:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.55rem .7rem}.detail-grid dt,.detail-grid dd{margin:0}.detail-grid dt{font-size:.68rem;margin-bottom:.12rem}.detail-grid dd{font-size:.84rem;color:var(--text);overflow-wrap:anywhere}.module-groups{display:grid;gap:var(--ui-gap-md)}.module-summary-group{display:grid;gap:var(--ui-gap-xs)}.module-summary-group h3{margin:0;color:#87afd4;font-size:.64rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase}.module-list{display:flex;flex-wrap:wrap;gap:.5rem}.mechanics-actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem;margin-bottom:.65rem}.mechanics-event-list{display:grid;grid-template-columns:repeat(var(--event-source-columns, 1),minmax(9.5rem,1fr));align-items:stretch}.module-settings{display:grid;gap:.75rem}.module-settings-card{display:grid;gap:.75rem;padding:.85rem .9rem;border-radius:1rem;border:1px solid rgba(255,255,255,.08);background:#ffffff09}.module-settings-subgroup{display:grid;gap:.65rem;padding-top:.15rem;border-top:1px solid rgba(255,255,255,.06)}.module-settings-options{display:grid;gap:.45rem}.module-settings-group-title{margin:0;color:#d7e5ef;font-size:.78rem;font-weight:800}.module-settings-header{display:flex;align-items:start;justify-content:space-between;gap:.8rem}.module-settings-header h3{margin:.1rem 0 0;font-size:.96rem}.module-settings-eyebrow{margin:0;font-size:.66rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase;color:#87afd4}.boost-pickup-filter-panel{display:grid;gap:.65rem}.boost-pickup-filter-summary{display:flex;justify-content:end}.boost-pickup-filter-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.75rem 1rem}.boost-pickup-filter-group{display:grid;align-content:start;gap:.35rem;min-width:0}.boost-pickup-filter-group[hidden]{display:none}.boost-pickup-filter-group-wide{grid-column:1 / -1}.boost-pickup-filter-options{display:flex;flex-wrap:wrap;gap:.35rem .8rem;min-width:0}.boost-pickup-filter-options .toggle{min-width:0}.module-summary-item{appearance:none;display:inline-flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm);min-height:var(--ui-control-height);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border-radius:var(--ui-radius-pill);border:1px solid var(--ui-border-subtle);background:#ffffff08;color:var(--muted);font:inherit;font-size:var(--ui-control-font-size);line-height:var(--ui-control-line-height);cursor:pointer;transition:border-color .14s ease,background-color .14s ease,color .14s ease}.module-summary-item:hover{border-color:var(--ui-border-hover);color:var(--text)}.module-summary-item strong{font-size:.62rem;letter-spacing:.08em;text-transform:uppercase}.module-summary-item[data-active=true]{border-color:#4b94ff38;background:#4b94ff14;color:#dceafb}@media(max-width:1180px){.sidebar{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:860px){.shell{padding:0}.sidebar{grid-template-columns:1fr}.panel-heading{display:grid}.detail-grid{grid-template-columns:1fr 1fr}.viewport-panel{min-height:100dvh}}@media(max-width:560px){.detail-grid{grid-template-columns:1fr}.transport-row{flex-direction:column}.floating-window,.stats-window{left:.55rem;right:.55rem;width:auto}}@media(max-width:720px){.viewport-panel:has(.floating-window:not([hidden])) .viewport{inset:0 0 52dvh}.floating-window{position:fixed;inset:auto 0 0;width:100%;max-width:none;height:52dvh;max-height:52dvh;overflow:auto;border-width:1px 0 0 0;border-radius:1rem 1rem 0 0;transform:none;z-index:30}.floating-window .floating-window-header{cursor:default}}.missed-event-body{display:flex;flex-direction:column;gap:.5rem;padding:.6rem .7rem;max-height:50vh;font-size:.8rem}.missed-event-controls{display:flex;align-items:center;gap:.4rem}.missed-event-controls select{flex:1 1 auto}.missed-event-list{list-style:none;margin:0;padding:0;overflow-y:auto;display:flex;flex-direction:column;gap:.25rem}.missed-event-list li{display:flex;align-items:center;justify-content:space-between;gap:.4rem;padding:.2rem .3rem;border-radius:.3rem;background:#1c272ee6}.missed-event-status{margin:0;min-height:1rem;color:#9fadb7}.training-pack-shots{list-style:none;margin:.4rem 0 0;padding:0;overflow-y:auto;max-height:12rem;display:flex;flex-direction:column;gap:.25rem;font-size:.8rem}.training-pack-shots li{display:flex;align-items:center;justify-content:space-between;gap:.4rem;padding:.2rem .3rem;border-radius:.3rem;background:#1c272ee6}.training-pack-status{margin:.4rem 0 0;min-height:1rem;font-size:.8rem;color:#9fadb7} diff --git a/crates/rocket-sense-server/static/subtr-actor/review/assets/main-DHjpjWsc.js b/crates/rocket-sense-server/static/subtr-actor/assets/main-DhIgxjyS.js similarity index 68% rename from crates/rocket-sense-server/static/subtr-actor/review/assets/main-DHjpjWsc.js rename to crates/rocket-sense-server/static/subtr-actor/assets/main-DhIgxjyS.js index 6d6e503a..e501fc2a 100644 --- a/crates/rocket-sense-server/static/subtr-actor/review/assets/main-DHjpjWsc.js +++ b/crates/rocket-sense-server/static/subtr-actor/assets/main-DhIgxjyS.js @@ -1,8 +1,8 @@ -function fh(n,e){if(n.frames.length===0)return 0;let t=0,i=n.frames.length-1;for(;t<=i;){const s=Math.floor((t+i)/2),a=n.frames[s]?.time??0;if(ae)i=s-1;else return s}return Math.max(0,t-1)}class vw{_listeners=new Map;on(e,t){let i=this._listeners.get(e);return i||(i=new Set,this._listeners.set(e,i)),i.add(t),this}once(e,t){const i=(...s)=>{this.off(e,i),t(...s)};return this.on(e,i)}off(e,t){const i=this._listeners.get(e);return i?(t?i.delete(t):i.clear(),i.size===0&&this._listeners.delete(e),this):this}removeListener(e,t){return this.off(e,t)}removeAllListeners(e){return e?this._listeners.delete(e):this._listeners.clear(),this}emit(e,...t){const i=this._listeners.get(e);if(!i||i.size===0)return!1;for(const s of[...i])s(...t);return!0}}function ff(n){return n?{x:n.x,y:n.z,z:n.y}:null}function E1(n){return n?{x:n.x,y:n.z,z:n.y,w:-n.w}:null}function C1(n){return n*100/255}const oy={Octane:{length:118.0074,width:84.19941,height:36.15907,offsetX:13.87566,offsetZ:20.75499},Dominus:{length:127.9268,width:83.27995,height:31.3,offsetX:9,offsetZ:15.75},Plank:{length:128.8198,width:84.67036,height:29.3944,offsetX:9.00857,offsetZ:12.0942},Breakout:{length:131.4924,width:80.521,height:30.3,offsetX:12.5,offsetZ:11.75},Hybrid:{length:127.0192,width:82.18787,height:34.15907,offsetX:13.87566,offsetZ:20.75499},Merc:{length:120.72,width:76.71,height:41.66,offsetX:11.37566,offsetZ:21.504988}},A1={21:{name:"Backfire",hitbox:"Octane"},22:{name:"Breakout",hitbox:"Breakout"},23:{name:"Octane",hitbox:"Octane"},24:{name:"Paladin",hitbox:"Plank"},25:{name:"Road Hog",hitbox:"Octane"},26:{name:"Gizmo",hitbox:"Octane"},28:{name:"X-Devil",hitbox:"Hybrid"},29:{name:"Hotshot",hitbox:"Dominus"},30:{name:"Merc",hitbox:"Merc"},31:{name:"Venom",hitbox:"Hybrid"},402:{name:"Takumi",hitbox:"Octane"},403:{name:"Dominus",hitbox:"Dominus"},404:{name:"Scarab",hitbox:"Octane"},523:{name:"Zippy",hitbox:"Octane"},597:{name:"DeLorean Time Machine",hitbox:"Dominus"},600:{name:"Ripper",hitbox:"Dominus"},607:{name:"Grog",hitbox:"Octane"},1018:{name:"Dominus GT",hitbox:"Dominus"},1159:{name:"X-Devil Mk2",hitbox:"Hybrid"},1171:{name:"Masamune",hitbox:"Dominus"},1172:{name:"Marauder",hitbox:"Octane"},1286:{name:"Aftershock",hitbox:"Dominus"},1295:{name:"Takumi RX-T",hitbox:"Octane"},1300:{name:"Road Hog XL",hitbox:"Octane"},1317:{name:"Esper",hitbox:"Hybrid"},1416:{name:"Breakout Type-S",hitbox:"Breakout"},1475:{name:"Proteus",hitbox:"Octane"},1478:{name:"Triton",hitbox:"Octane"},1533:{name:"Vulcan",hitbox:"Octane"},1568:{name:"Octane ZSR",hitbox:"Octane"},1603:{name:"Twin Mill III",hitbox:"Plank"},1623:{name:"Bone Shaker",hitbox:"Octane"},1624:{name:"Endo",hitbox:"Hybrid"},1675:{name:"Ice Charger",hitbox:"Dominus"},1689:{name:"Nemesis",hitbox:"Dominus"},1691:{name:"Mantis",hitbox:"Plank"},1856:{name:"Jager 619",hitbox:"Hybrid"},1883:{name:"Imperator DT5",hitbox:"Dominus"},1894:{name:"Samurai",hitbox:"Breakout"},1919:{name:"Centio",hitbox:"Plank"},1932:{name:"Animus GP",hitbox:"Breakout"},2070:{name:"Werewolf",hitbox:"Dominus"},2268:{name:"Fast & Furious Dodge Charger",hitbox:"Dominus"},2269:{name:"Fast & Furious Nissan Skyline",hitbox:"Hybrid"},2665:{name:"The Dark Knight's Tumbler",hitbox:"Octane"},2666:{name:"Batmobile (1989)",hitbox:"Dominus"},2853:{name:"Twinzer",hitbox:"Octane"},2919:{name:"Jurassic Jeep Wrangler",hitbox:"Octane"},2949:{name:"Fast 4WD",hitbox:"Octane"},2950:{name:"MR11",hitbox:"Dominus"},2951:{name:"Gazella GT",hitbox:"Dominus"},3031:{name:"Cyclone",hitbox:"Breakout"},3155:{name:"Maverick",hitbox:"Dominus"},3156:{name:"Maverick G1",hitbox:"Dominus"},3157:{name:"Maverick GXT",hitbox:"Dominus"},3265:{name:"McLaren 570S",hitbox:"Dominus"},3311:{name:"Komodo",hitbox:"Breakout"},3426:{name:"Diestro",hitbox:"Dominus"},3451:{name:"Nimbus",hitbox:"Hybrid"},3582:{name:"Insidio",hitbox:"Hybrid"},3594:{name:"Artemis G1",hitbox:"Plank"},3614:{name:"Artemis",hitbox:"Plank"},3622:{name:"Artemis GXT",hitbox:"Plank"},3702:{name:"Tygris",hitbox:"Hybrid"},3875:{name:"Guardian GXT",hitbox:"Dominus"},3879:{name:"Guardian",hitbox:"Dominus"},3880:{name:"Guardian G1",hitbox:"Dominus"},4014:{name:"K.I.T.T.",hitbox:"Dominus"},4155:{name:"Ecto-1",hitbox:"Dominus"},4268:{name:"Sentinel",hitbox:"Plank"},4284:{name:"Fennec",hitbox:"Octane"},4318:{name:"Mudcat",hitbox:"Octane"},4319:{name:"Mudcat G1",hitbox:"Octane"},4320:{name:"Mudcat GXT",hitbox:"Octane"},4367:{name:"Chikara GXT",hitbox:"Dominus"},4472:{name:"Chikara",hitbox:"Dominus"},4473:{name:"Chikara G1",hitbox:"Dominus"},4745:{name:"Ronin GXT",hitbox:"Dominus"},4770:{name:"Dominus",hitbox:"Dominus"},4780:{name:"Battle Bus",hitbox:"Merc"},4781:{name:"Peregrine TT",hitbox:"Dominus"},4782:{name:"Psyclops",hitbox:"Body_Tritip_Handling"},4861:{name:"Ronin",hitbox:"Dominus"},4864:{name:"Ronin G1",hitbox:"Dominus"},4906:{name:"Harbinger",hitbox:"Octane"},5020:{name:"Outlaw",hitbox:"Octane"},5039:{name:"Harbinger GXT",hitbox:"Octane"},5188:{name:"Scarab",hitbox:"Octane"},5265:{name:"Formula 1 2021",hitbox:"Plank"},5361:{name:"Dingo",hitbox:"Octane"},5470:{name:"R3MX",hitbox:"Hybrid"},5488:{name:"R3MX GXT",hitbox:"Hybrid"},5547:{name:"007's Aston Martin DB5",hitbox:"Octane"},5709:{name:"NASCAR Ford Mustang",hitbox:"Dominus"},5713:{name:"Ford F-150 RLE",hitbox:"Octane"},5773:{name:"NASCAR Toyota Camry",hitbox:"Dominus"},5823:{name:"NASCAR Chevrolet Camaro",hitbox:"Dominus"},5837:{name:"Outlaw GXT",hitbox:"Octane"},5858:{name:"Tyranno",hitbox:"Dominus"},5879:{name:"Fast & Furious Pontiac Fiero",hitbox:"Hybrid"},5951:{name:"Jackal",hitbox:"Octane"},5964:{name:"Lamborghini Huracan STO",hitbox:"Dominus"},5979:{name:"Tyranno GXT",hitbox:"Dominus"},6122:{name:"Masamune",hitbox:"Dominus"},6243:{name:"Nexus",hitbox:"Breakout"},6244:{name:"BMW M240i",hitbox:"Dominus"},6247:{name:"McLaren 765LT",hitbox:"Dominus"},6260:{name:"007's Aston Martin Valhalla",hitbox:"Dominus"},6489:{name:"Nexus SC",hitbox:"Breakout"},6836:{name:"Ford Mustang Shelby GT350R RLE",hitbox:"Dominus"},6939:{name:"Ford Mustang Mach-E RLE",hitbox:"Octane"},7012:{name:"Tesla Cybertruck",hitbox:"Hybrid"},7052:{name:"Formula 1 2022",hitbox:"Plank"},7211:{name:"Mamba",hitbox:"Dominus"},7336:{name:"Nomad",hitbox:"Merc"},7337:{name:"NASCAR Next Gen Chevrolet Camaro",hitbox:"Dominus"},7338:{name:"NASCAR Next Gen Ford Mustang",hitbox:"Dominus"},7341:{name:"NASCAR Next Gen Toyota Camry",hitbox:"Dominus"},7343:{name:"007's Aston Martin DBS",hitbox:"Dominus"},7415:{name:"Batmobile (2022)",hitbox:"Dominus"},7477:{name:"Nomad GXT",hitbox:"Merc"},7512:{name:"Lamborghini Countach LPI 800-4",hitbox:"Dominus"},7532:{name:"Maestro",hitbox:"Dominus"},7593:{name:"Nissan Z Performance",hitbox:"Dominus"},7651:{name:"Redline",hitbox:"Breakout"},7696:{name:"Whiplash",hitbox:"Breakout"},7772:{name:"Ferrari 296 GTB",hitbox:"Dominus"},7815:{name:"Ford Bronco Raptor RLE",hitbox:"Merc"},7890:{name:"Fuse",hitbox:"Breakout"},7901:{name:"Fast & Furious Mazda RX-7",hitbox:"Breakout"},7947:{name:"Honda Civic Type R",hitbox:"Octane"},7948:{name:"Honda Civic Type R-LE",hitbox:"Octane"},7979:{name:"Stampede",hitbox:"Merc"},8006:{name:"Mako",hitbox:"Breakout"},8360:{name:"Emperor",hitbox:"Breakout"},8361:{name:"Emperor II",hitbox:"Breakout"},8383:{name:"Xentari",hitbox:"Octane"},8454:{name:"Admiral",hitbox:"Dominus"},8524:{name:"Bugatti Centodieci",hitbox:"Plank"},8565:{name:"Emperor II: Frozen",hitbox:"Breakout"},8566:{name:"Emperor II: Scorched",hitbox:"Breakout"},8669:{name:"Ace",hitbox:"Breakout"},8806:{name:"Volkswagen Golf GTI",hitbox:"Octane"},8807:{name:"Volkswagen Golf GTI RLE",hitbox:"Octane"},9053:{name:"Fast & Furious Dodge Charger SRT Hellcat",hitbox:"Dominus"},9084:{name:"Nissan Silvia",hitbox:"Hybrid"},9085:{name:"Nissan Silvia RLE",hitbox:"Hybrid"},9088:{name:"Porsche 911 Turbo",hitbox:"Dominus"},9089:{name:"Porsche 911 Turbo RLE",hitbox:"Dominus"},9140:{name:"Bumblebee",hitbox:"Dominus"},9357:{name:"Diesel",hitbox:"Breakout"},9388:{name:"Lightning McQueen",hitbox:"Dominus"},9427:{name:"Primo",hitbox:"Hybrid"},9894:{name:"Scorpion",hitbox:"Dominus"},10044:{name:"Beskar",hitbox:"Hybrid"},10094:{name:"Ford Mustang GTD",hitbox:"Dominus"},10440:{name:"Nissan Fairlady Z",hitbox:"Dominus"},10441:{name:"Nissan Fairlady Z RLE",hitbox:"Dominus"},10689:{name:"Behemoth",hitbox:"Merc"},10694:{name:"Lockjaw",hitbox:"Dominus"},10697:{name:"The Incredibile",hitbox:"Breakout"},10698:{name:"1966 Cadillac DeVille",hitbox:"Breakout"},10805:{name:"Nissan Skyline GT-R (R32)",hitbox:"Hybrid"},10817:{name:"Quadra Turbo-R",hitbox:"Breakout"},10822:{name:"McLaren Senna",hitbox:"Breakout"},10896:{name:"BMW 1 Series",hitbox:"Octane"},10897:{name:"BMW 1 Series RLE",hitbox:"Octane"},10900:{name:"Shokunin",hitbox:"Octane"},10901:{name:"Shokunin GXT",hitbox:"Octane"},11016:{name:"Porsche 911 GT3 RS",hitbox:"Dominus"},11038:{name:"Revolver",hitbox:"Breakout"},11095:{name:"Dodge Charger Daytona Scat Pack",hitbox:"Dominus"},11098:{name:"Turtle Van",hitbox:"Merc"},11138:{name:"Void Burn",hitbox:"Hybrid"},11141:{name:"Lamborghini Urus SE",hitbox:"Hybrid"},11314:{name:"Jeep Wrangler Rubicon",hitbox:"Merc"},11315:{name:"Ford Mustang Shelby GT500",hitbox:"Dominus"},11336:{name:"Dominus: Neon",hitbox:"Dominus"},11379:{name:"Ram 1500 RHO",hitbox:"Hybrid"},11394:{name:"Azura",hitbox:"Breakout"},11505:{name:"Breakout X",hitbox:"Breakout"},11534:{name:"BMW M3 (E30)",hitbox:"Dominus"},11603:{name:"Fennec ZR-F",hitbox:"Octane"},11677:{name:"Chevrolet Corvette ZR1",hitbox:"Breakout"},11736:{name:"Recoil AV",hitbox:"Merc"},11800:{name:"Megastar",hitbox:"Breakout"},11905:{name:"The Mystery Machine",hitbox:"Merc"},11932:{name:"Hearse",hitbox:"Hybrid"},11933:{name:"Porsche 918 Spyder",hitbox:"Breakout"},11941:{name:"Mercedes-AMG GT 63 S",hitbox:"Dominus"},11949:{name:"Pontiac Firebird",hitbox:"Breakout"},11950:{name:"Chevrolet Astro",hitbox:"Merc"},12142:{name:"Homer's Car",hitbox:"Dominus"},12173:{name:"Ferrari F40",hitbox:"Breakout"}},R1=A1;function bw(n){const e=R1[String(n)];return e?{name:e.name,hitboxType:e.hitbox}:null}function P1(n){if(!n)return null;const e={fov:n.fov,height:n.height,angle:n.angle,distance:n.distance,stiffness:n.stiffness,swivelSpeed:n.swivel_speed};return n.transition_speed!=null&&(e.transitionSpeed=n.transition_speed),e}const I1=2200,L1=!0,D1=!1,k1=.15,O1=10,F1=.1,N1=10,U1=.1,B1=.15,z1=10;function Uo(n,e){if(n.length===0)return null;let t=0,i=n.length-1;if(e<=n[0].time)return n[0];if(e>=n[i].time)return n[i];for(;t>1;n[s].time<=e?t=s:i=s-1}return n[t]}class H1{position={x:0,y:0,z:0};rotation={x:0,y:0,z:0,w:1};velocity={x:0,y:0,z:0};angularVelocity={x:0,y:0,z:0};sleeping=!1;visible=!0}class V1{constructor(e,t,i){this.isBig=e,this.position=t,this.events=i}isAvailable=!0}class G1 extends vw{constructor(e,t,i,s,a,r=null){super(),this.id=e,this.name=t,this.team=i,this.carName=s,this.hitboxType=a,this.cameraSettings=r}position={x:0,y:0,z:0};rotation={x:0,y:0,z:0,w:1};velocity={x:0,y:0,z:0};angularVelocity={x:0,y:0,z:0};sleeping=!1;steer=0;boost=0;isBoosting=!1;isSupersonic=!1;isKickoffReset=!1;isVisible=!0;isBallCam=!0}class xw extends vw{constructor(e,t={}){super(),this.raw=e,this.options=t,this._compile()}duration=0;playerList=[];frameTimes=[];rawStartTime=0;ball=new H1;players=new Map;boostPads=new Map;_currentTime=0;_ballTimeline=[];_playerTimelines={};_ballFlags=[];_playerFlags={};_playerCameraEvents={};_teams={};_timelineCompaction=null;_compile(){const e=this.raw.frame_data,t=this.raw.meta,i=e.metadata_frames,s=i[0]?.time??0;this.rawStartTime=s;const a=l=>Math.max(0,l-s);this.duration=i.length?a(i[i.length-1].time):0,this.frameTimes=i.map(l=>a(l.time));const r=new Map;t.team_zero.forEach(l=>r.set(this._idKey(l.remote_id),{info:l,team:0})),t.team_one.forEach(l=>r.set(this._idKey(l.remote_id),{info:l,team:1})),e.ball_data.frames.forEach((l,c)=>{if(l==="Empty"||!("Data"in l))return;const u=this._rbToKeyframe(l.Data.rigid_body,a(i[c]?.time??s),c);u&&this._ballTimeline.push(u)}),e.players.forEach(([l,c])=>{const u=this._idKey(l),d=r.get(u);let h=d?.info.name??null,f=d?.team??0;if(!h){for(const T of c.frames)if(T!=="Empty"&&"Data"in T&&T.Data.player_name){h=T.Data.player_name,T.Data.is_team_0!=null&&(f=T.Data.is_team_0?0:1);break}}h||(h=`Player_${u}`);const p=d?.info,g=p?.car_body_id!=null?bw(p.car_body_id):null,_=p?.car_body_name??g?.name??"Octane",m=p?.car_hitbox_family??g?.hitboxType??"Octane",v=[],y=[];c.frames.forEach((T,x)=>{const M=a(i[x]?.time??s);if(T==="Empty"||!("Data"in T))return;const C=this._rbToKeyframe(T.Data.rigid_body,M,x);C&&v.push(C);const w=T.Data.input?.steer;y.push({time:M,boost:C1(T.Data.boost_amount??0),isBoosting:!!T.Data.boost_active,present:!0,steer:w==null?0:Math.max(-1,Math.min(1,(w-128)/128))})});const b=P1(p?.camera_settings);this._playerTimelines[h]=v,this._playerFlags[h]=y,this._teams[h]=f,this.playerList.push({id:u,name:h,team:f,carName:_,hitboxType:m,cameraSettings:b}),this.players.set(h,new G1(u,h,f,_,m,b))});const o=new Map;this.playerList.forEach(l=>o.set(l.id,l.name));for(const[l,c]of this.raw.player_camera_events??[]){const u=o.get(this._idKey(l));u&&(this._playerCameraEvents[u]=c.map(d=>({time:a(i[d.frame]?.time??s),ballCam:d.ball_cam_active})))}this._preprocessMotionTimelines(),this._compileBoostPads(),this.seek(0)}_timelineProcessingOptions(){return{motionSmoothing:this.options.motionSmoothing??L1,smoothingBlendFactor:this.options.smoothingBlendFactor??k1,smoothingAnchorInterval:this.options.smoothingAnchorInterval??O1,timelineCompaction:this.options.timelineCompaction??D1,disableFrameFiltering:this.options.disableFrameFiltering??!1}}_preprocessMotionTimelines(){const e=this._timelineProcessingOptions();e.motionSmoothing&&this._applyVelocityBasedPositionCorrection(e),e.timelineCompaction&&this._applyTimelineCompaction(),e.disableFrameFiltering||this._filterInconsistentFrames()}_applyTimelineCompaction(){const e=this._buildTimelineCompaction();!e||e.gaps.length===0&&e.prematchEndTime===null||(this._timelineCompaction=e,this._ballTimeline=this._compactTimeline(this._ballTimeline,e),Object.entries(this._playerTimelines).forEach(([t,i])=>{this._playerTimelines[t]=this._compactTimeline(i,e)}),Object.entries(this._playerFlags).forEach(([t,i])=>{this._playerFlags[t]=this._compactTimeline(i,e)}),this.frameTimes=this.frameTimes.map(t=>this._compactTime(t,e)),this.duration=e.compactedDuration)}_buildTimelineCompaction(){if(this.frameTimes.length===0)return null;const e=this._detectPostGoalTimeGaps(),t=this._detectFirstKickoffGoTime(),i=t==null?null:Bo(t,e),a=e.reduce((r,o)=>r+o.duration,0)+(i??0);return a<=0?null:{gaps:e,prematchEndTime:i,removedDuration:a,compactedDuration:Math.max(0,this.duration-a)}}_detectPostGoalTimeGaps(){const e=[];for(const t of this.raw.goal_events??[]){const i=t.frame;if(!Number.isInteger(i)||i<0||i>=this.frameTimes.length)continue;const s=this.frameTimes[i];for(let a=i+1;a10)break;const l=o-r;if(l>.3){e.push({beforeFrame:a-1,afterFrame:a,beforeTime:r,afterTime:o,duration:l});break}}}return e}_detectFirstKickoffGoTime(){const e=this.raw.frame_data.metadata_frames;let t=!1;for(let s=0;s0&&(t=!0),t&&a===0)return this.frameTimes[s]??null}const i=e.findIndex(s=>s.replicated_game_state_name===54);return i===-1?null:this.frameTimes[i]??null}_compactTimeline(e,t){const i=this._remapReplayGaps(e,t.gaps);return t.prematchEndTime===null?i:this._remapPrematch(i,t.prematchEndTime)}_remapReplayGaps(e,t){if(t.length===0)return e;const i=[];t.forEach((a,r)=>{const o=e.find(l=>l.time>=a.afterTime);o&&i.push({...o,time:Bo(a.afterTime,t.slice(0,r+1))})});const s=e.filter(a=>!uy(a.time,t)).map(a=>({...a,time:Bo(a.time,t)}));for(const a of i){if(s.some(o=>Math.abs(o.time-a.time)<.001))continue;let r=s.findIndex(o=>o.time>a.time);r===-1&&(r=s.length),s.splice(r,0,a)}return s}_remapPrematch(e,t){let i=null;for(const a of e)if(a.timea.time>=t).map(a=>({...a,time:a.time-t}));return i&&(s.length===0||s[0].time>.001)&&s.unshift({...i,time:0}),s}_compactTime(e,t){const i=Bo(e,t.gaps);return t.prematchEndTime===null?i:Math.max(0,i-t.prematchEndTime)}_applyVelocityBasedPositionCorrection(e){const t=i=>{if(i.length<3)return;let s=0;for(;s=i.length-1)return;let a={...i[s].position};for(let r=s+1;rF1){a={...l.position};continue}if(cy(a,l.position)>N1){a={...l.position};continue}const u={x:(o.velocity.x+l.velocity.x)/2,y:(o.velocity.y+l.velocity.y)/2,z:(o.velocity.z+l.velocity.z)/2},d={x:a.x+u.x*c,y:a.y+u.y*c,z:a.z+u.z*c},h=(r-s)%e.smoothingAnchorInterval===0?.5:e.smoothingBlendFactor;a={x:d.x*(1-h)+l.position.x*h,y:d.y*(1-h)+l.position.y*h,z:d.z*(1-h)+l.position.z*h},l.position={...a}}};t(this._ballTimeline),Object.values(this._playerTimelines).forEach(t)}_filterInconsistentFrames(){this._ballTimeline=this._filterInconsistentTimeline(this._ballTimeline),Object.entries(this._playerTimelines).forEach(([e,t])=>{this._playerTimelines[e]=this._filterInconsistentTimeline(t)})}_filterInconsistentTimeline(e){if(e.length<2)return e;const t=[e[0]];let i=0;for(let s=1;s.001){const u=o*c,d=cy(r.position,a.position),h=Math.abs(d-u)/u;if(Number.isFinite(h)&&h>B1)continue}}t.push(a),i=s}return t}_compileBoostPads(){const e=new Map;(this.raw.boost_pad_events??[]).forEach(t=>{const i=t.kind==="Available"?!0:t.kind&&typeof t.kind=="object"&&"PickedUp"in t.kind?!1:null;if(i===null)return;const s=Math.max(0,t.time-this.rawStartTime);if(this._timelineCompaction&&this._isRemovedByTimelineCompaction(s))return;const a=this._timelineCompaction?this._compactTime(s,this._timelineCompaction):s,r=e.get(t.pad_id);r?r.push({time:a,available:i}):e.set(t.pad_id,[{time:a,available:i}])}),(this.raw.boost_pads??[]).forEach(t=>{const i=(t.pad_id?e.get(t.pad_id):void 0)??[];i.sort((s,a)=>s.time-a.time),this.boostPads.set(t.index,new V1(t.size==="Big",t.position,i))})}_rbToKeyframe(e,t,i){const s=ff(e.location);return s?{time:t,frame:i,position:s,rotation:E1(e.rotation),velocity:ff(e.linear_velocity)??{x:0,y:0,z:0},angularVelocity:ff(e.angular_velocity),sleeping:!!e.sleeping}:null}_isRemovedByTimelineCompaction(e){const t=this._timelineCompaction;if(!t)return!1;if(uy(e,t.gaps))return!0;const i=Bo(e,t.gaps);return t.prematchEndTime!==null&&i=I1}const r=Uo(this._playerFlags[i]??[],e);r&&(s.boost=r.boost,s.isBoosting=r.isBoosting,s.steer=r.steer);const o=Uo(this._playerCameraEvents[i]??[],e);o&&o.ballCam!=null&&(s.isBallCam=o.ballCam);const l=this._playerTimelines[i]??[];s.isVisible=l.length>0&&e>=l[0].time-.001&&e<=l[l.length-1].time+1}for(const i of this.boostPads.values()){if(i.events.length===0)continue;const s=Uo(i.events,e);i.isAvailable=s&&s.time<=e?s.available:!0}}frameIndexAt(e){const t=this.frameTimes;if(t.length===0||e<=t[0])return 0;let i=0,s=t.length-1;if(e>=t[s])return s;for(;i>1;t[a]<=e?i=a:s=a-1}return i}getBall(){return this.ball}getPlayer(e){return this.players.get(e)}getPlayerById(e){for(const t of this.players.values())if(t.id===e)return t}getAllPlayers(){return Array.from(this.players.values())}getPlayerTeams(){return{...this._teams}}getGameTimeMap(){return[]}getCountdownEvents(){return[]}getPlayerStatsTimelines(){return{}}getGameEventTimeline(){return[]}getAdvancedStats(){return null}getEvents(){return[]}getEventsInRange(){return[]}getTextOverlaysAt(){return[]}getGamePhaseAt(){return null}}function ly(n){return Math.sqrt(n.x*n.x+n.y*n.y+n.z*n.z)}function cy(n,e){const t=e.x-n.x,i=e.y-n.y,s=e.z-n.z;return Math.sqrt(t*t+i*i+s*s)}function Bo(n,e){let t=0;for(const i of e){if(n=i.afterTime){t+=i.duration;continue}return i.beforeTime-t}return n-t}function uy(n,e){return e.some(t=>n>t.beforeTime&&n>8&255]+Mn[n>>16&255]+Mn[n>>24&255]+"-"+Mn[e&255]+Mn[e>>8&255]+"-"+Mn[e>>16&15|64]+Mn[e>>24&255]+"-"+Mn[t&63|128]+Mn[t>>8&255]+"-"+Mn[t>>16&255]+Mn[t>>24&255]+Mn[i&255]+Mn[i>>8&255]+Mn[i>>16&255]+Mn[i>>24&255]).toLowerCase()}function Ze(n,e,t){return Math.max(e,Math.min(t,n))}function Z_(n,e){return(n%e+e)%e}function MC(n,e,t,i,s){return i+(n-e)*(s-i)/(t-e)}function EC(n,e,t){return n!==e?(t-n)/(e-n):0}function Al(n,e,t){return(1-t)*n+t*e}function CC(n,e,t,i){return Al(n,e,1-Math.exp(-t*i))}function AC(n,e=1){return e-Math.abs(Z_(n,e*2)-e)}function RC(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*(3-2*n))}function PC(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*n*(n*(n*6-15)+10))}function IC(n,e){return n+Math.floor(Math.random()*(e-n+1))}function LC(n,e){return n+Math.random()*(e-n)}function DC(n){return n*(.5-Math.random())}function kC(n){n!==void 0&&(dy=n);let e=dy+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function OC(n){return n*nr}function FC(n){return n*To}function NC(n){return(n&n-1)===0&&n!==0}function UC(n){return Math.pow(2,Math.ceil(Math.log(n)/Math.LN2))}function BC(n){return Math.pow(2,Math.floor(Math.log(n)/Math.LN2))}function zC(n,e,t,i,s){const a=Math.cos,r=Math.sin,o=a(t/2),l=r(t/2),c=a((e+i)/2),u=r((e+i)/2),d=a((e-i)/2),h=r((e-i)/2),f=a((i-e)/2),p=r((i-e)/2);switch(s){case"XYX":n.set(o*u,l*d,l*h,o*c);break;case"YZY":n.set(l*h,o*u,l*d,o*c);break;case"ZXZ":n.set(l*d,l*h,o*u,o*c);break;case"XZX":n.set(o*u,l*p,l*f,o*c);break;case"YXY":n.set(l*f,o*u,l*p,o*c);break;case"ZYZ":n.set(l*p,l*f,o*u,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+s)}}function zn(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return n/4294967295;case Uint16Array:return n/65535;case Uint8Array:return n/255;case Int32Array:return Math.max(n/2147483647,-1);case Int16Array:return Math.max(n/32767,-1);case Int8Array:return Math.max(n/127,-1);default:throw new Error("Invalid component type.")}}function ut(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return Math.round(n*4294967295);case Uint16Array:return Math.round(n*65535);case Uint8Array:return Math.round(n*255);case Int32Array:return Math.round(n*2147483647);case Int16Array:return Math.round(n*32767);case Int8Array:return Math.round(n*127);default:throw new Error("Invalid component type.")}}const vt={DEG2RAD:nr,RAD2DEG:To,generateUUID:pi,clamp:Ze,euclideanModulo:Z_,mapLinear:MC,inverseLerp:EC,lerp:Al,damp:CC,pingpong:AC,smoothstep:RC,smootherstep:PC,randInt:IC,randFloat:LC,randFloatSpread:DC,seededRandom:kC,degToRad:OC,radToDeg:FC,isPowerOfTwo:NC,ceilPowerOfTwo:UC,floorPowerOfTwo:BC,setQuaternionFromProperEuler:zC,normalize:ut,denormalize:zn};class te{constructor(e=0,t=0){te.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,i=this.y,s=e.elements;return this.x=s[0]*t+s[3]*i+s[6],this.y=s[1]*t+s[4]*i+s[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Ze(this.x,e.x,t.x),this.y=Ze(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Ze(this.x,e,t),this.y=Ze(this.y,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Ze(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Ze(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),s=Math.sin(t),a=this.x-e.x,r=this.y-e.y;return this.x=a*i-r*s+e.x,this.y=a*s+r*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class dt{constructor(e=0,t=0,i=0,s=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=s}static slerpFlat(e,t,i,s,a,r,o){let l=i[s+0],c=i[s+1],u=i[s+2],d=i[s+3];const h=a[r+0],f=a[r+1],p=a[r+2],g=a[r+3];if(o===0){e[t+0]=l,e[t+1]=c,e[t+2]=u,e[t+3]=d;return}if(o===1){e[t+0]=h,e[t+1]=f,e[t+2]=p,e[t+3]=g;return}if(d!==g||l!==h||c!==f||u!==p){let _=1-o;const m=l*h+c*f+u*p+d*g,v=m>=0?1:-1,y=1-m*m;if(y>Number.EPSILON){const T=Math.sqrt(y),x=Math.atan2(T,m*v);_=Math.sin(_*x)/T,o=Math.sin(o*x)/T}const b=o*v;if(l=l*_+h*b,c=c*_+f*b,u=u*_+p*b,d=d*_+g*b,_===1-o){const T=1/Math.sqrt(l*l+c*c+u*u+d*d);l*=T,c*=T,u*=T,d*=T}}e[t]=l,e[t+1]=c,e[t+2]=u,e[t+3]=d}static multiplyQuaternionsFlat(e,t,i,s,a,r){const o=i[s],l=i[s+1],c=i[s+2],u=i[s+3],d=a[r],h=a[r+1],f=a[r+2],p=a[r+3];return e[t]=o*p+u*d+l*f-c*h,e[t+1]=l*p+u*h+c*d-o*f,e[t+2]=c*p+u*f+o*h-l*d,e[t+3]=u*p-o*d-l*h-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,i,s){return this._x=e,this._y=t,this._z=i,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const i=e._x,s=e._y,a=e._z,r=e._order,o=Math.cos,l=Math.sin,c=o(i/2),u=o(s/2),d=o(a/2),h=l(i/2),f=l(s/2),p=l(a/2);switch(r){case"XYZ":this._x=h*u*d+c*f*p,this._y=c*f*d-h*u*p,this._z=c*u*p+h*f*d,this._w=c*u*d-h*f*p;break;case"YXZ":this._x=h*u*d+c*f*p,this._y=c*f*d-h*u*p,this._z=c*u*p-h*f*d,this._w=c*u*d+h*f*p;break;case"ZXY":this._x=h*u*d-c*f*p,this._y=c*f*d+h*u*p,this._z=c*u*p+h*f*d,this._w=c*u*d-h*f*p;break;case"ZYX":this._x=h*u*d-c*f*p,this._y=c*f*d+h*u*p,this._z=c*u*p-h*f*d,this._w=c*u*d+h*f*p;break;case"YZX":this._x=h*u*d+c*f*p,this._y=c*f*d+h*u*p,this._z=c*u*p-h*f*d,this._w=c*u*d-h*f*p;break;case"XZY":this._x=h*u*d-c*f*p,this._y=c*f*d-h*u*p,this._z=c*u*p+h*f*d,this._w=c*u*d+h*f*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+r)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const i=t/2,s=Math.sin(i);return this._x=e.x*s,this._y=e.y*s,this._z=e.z*s,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],s=t[4],a=t[8],r=t[1],o=t[5],l=t[9],c=t[2],u=t[6],d=t[10],h=i+o+d;if(h>0){const f=.5/Math.sqrt(h+1);this._w=.25/f,this._x=(u-l)*f,this._y=(a-c)*f,this._z=(r-s)*f}else if(i>o&&i>d){const f=2*Math.sqrt(1+i-o-d);this._w=(u-l)/f,this._x=.25*f,this._y=(s+r)/f,this._z=(a+c)/f}else if(o>d){const f=2*Math.sqrt(1+o-i-d);this._w=(a-c)/f,this._x=(s+r)/f,this._y=.25*f,this._z=(l+u)/f}else{const f=2*Math.sqrt(1+d-i-o);this._w=(r-s)/f,this._x=(a+c)/f,this._y=(l+u)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<1e-8?(i=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Ze(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(i===0)return this;const s=Math.min(1,t/i);return this.slerp(e,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const i=e._x,s=e._y,a=e._z,r=e._w,o=t._x,l=t._y,c=t._z,u=t._w;return this._x=i*u+r*o+s*c-a*l,this._y=s*u+r*l+a*o-i*c,this._z=a*u+r*c+i*l-s*o,this._w=r*u-i*o-s*l-a*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const i=this._x,s=this._y,a=this._z,r=this._w;let o=r*e._w+i*e._x+s*e._y+a*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=r,this._x=i,this._y=s,this._z=a,this;const l=1-o*o;if(l<=Number.EPSILON){const f=1-t;return this._w=f*r+t*this._w,this._x=f*i+t*this._x,this._y=f*s+t*this._y,this._z=f*a+t*this._z,this.normalize(),this}const c=Math.sqrt(l),u=Math.atan2(c,o),d=Math.sin((1-t)*u)/c,h=Math.sin(t*u)/c;return this._w=r*d+this._w*h,this._x=i*d+this._x*h,this._y=s*d+this._y*h,this._z=a*d+this._z*h,this._onChangeCallback(),this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),s=Math.sqrt(1-i),a=Math.sqrt(i);return this.set(s*Math.sin(e),s*Math.cos(e),a*Math.sin(t),a*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class S{constructor(e=0,t=0,i=0){S.prototype.isVector3=!0,this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(hy.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(hy.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,s=this.z,a=e.elements;return this.x=a[0]*t+a[3]*i+a[6]*s,this.y=a[1]*t+a[4]*i+a[7]*s,this.z=a[2]*t+a[5]*i+a[8]*s,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,s=this.z,a=e.elements,r=1/(a[3]*t+a[7]*i+a[11]*s+a[15]);return this.x=(a[0]*t+a[4]*i+a[8]*s+a[12])*r,this.y=(a[1]*t+a[5]*i+a[9]*s+a[13])*r,this.z=(a[2]*t+a[6]*i+a[10]*s+a[14])*r,this}applyQuaternion(e){const t=this.x,i=this.y,s=this.z,a=e.x,r=e.y,o=e.z,l=e.w,c=2*(r*s-o*i),u=2*(o*t-a*s),d=2*(a*i-r*t);return this.x=t+l*c+r*d-o*u,this.y=i+l*u+o*c-a*d,this.z=s+l*d+a*u-r*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,i=this.y,s=this.z,a=e.elements;return this.x=a[0]*t+a[4]*i+a[8]*s,this.y=a[1]*t+a[5]*i+a[9]*s,this.z=a[2]*t+a[6]*i+a[10]*s,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Ze(this.x,e.x,t.x),this.y=Ze(this.y,e.y,t.y),this.z=Ze(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Ze(this.x,e,t),this.y=Ze(this.y,e,t),this.z=Ze(this.z,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Ze(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const i=e.x,s=e.y,a=e.z,r=t.x,o=t.y,l=t.z;return this.x=s*l-a*o,this.y=a*r-i*l,this.z=i*o-s*r,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return pf.copy(this).projectOnVector(e),this.sub(pf)}reflect(e){return this.sub(pf.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Ze(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,s=this.z-e.z;return t*t+i*i+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){const s=Math.sin(t)*e;return this.x=s*Math.sin(i),this.y=Math.cos(t)*e,this.z=s*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),s=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=s,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(e),this.y=t,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const pf=new S,hy=new dt;class st{constructor(e,t,i,s,a,r,o,l,c){st.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,s,a,r,o,l,c)}set(e,t,i,s,a,r,o,l,c){const u=this.elements;return u[0]=e,u[1]=s,u[2]=o,u[3]=t,u[4]=a,u[5]=l,u[6]=i,u[7]=r,u[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,s=t.elements,a=this.elements,r=i[0],o=i[3],l=i[6],c=i[1],u=i[4],d=i[7],h=i[2],f=i[5],p=i[8],g=s[0],_=s[3],m=s[6],v=s[1],y=s[4],b=s[7],T=s[2],x=s[5],M=s[8];return a[0]=r*g+o*v+l*T,a[3]=r*_+o*y+l*x,a[6]=r*m+o*b+l*M,a[1]=c*g+u*v+d*T,a[4]=c*_+u*y+d*x,a[7]=c*m+u*b+d*M,a[2]=h*g+f*v+p*T,a[5]=h*_+f*y+p*x,a[8]=h*m+f*b+p*M,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[1],s=e[2],a=e[3],r=e[4],o=e[5],l=e[6],c=e[7],u=e[8];return t*r*u-t*o*c-i*a*u+i*o*l+s*a*c-s*r*l}invert(){const e=this.elements,t=e[0],i=e[1],s=e[2],a=e[3],r=e[4],o=e[5],l=e[6],c=e[7],u=e[8],d=u*r-o*c,h=o*l-u*a,f=c*a-r*l,p=t*d+i*h+s*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);const g=1/p;return e[0]=d*g,e[1]=(s*c-u*i)*g,e[2]=(o*i-s*r)*g,e[3]=h*g,e[4]=(u*t-s*l)*g,e[5]=(s*a-o*t)*g,e[6]=f*g,e[7]=(i*l-c*t)*g,e[8]=(r*t-i*a)*g,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,s,a,r,o){const l=Math.cos(a),c=Math.sin(a);return this.set(i*l,i*c,-i*(l*r+c*o)+r+e,-s*c,s*l,-s*(-c*r+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(mf.makeScale(e,t)),this}rotate(e){return this.premultiply(mf.makeRotation(-e)),this}translate(e,t){return this.premultiply(mf.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,i=e.elements;for(let s=0;s<9;s++)if(t[s]!==i[s])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const mf=new st;function cS(n){for(let e=n.length-1;e>=0;--e)if(n[e]>=65535)return!0;return!1}const HC={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function Yr(n,e){return new HC[n](e)}function Hl(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}function uS(){const n=Hl("canvas");return n.style.display="block",n}const fy={};function Vl(n){n in fy||(fy[n]=!0,console.warn(n))}function VC(n,e,t){return new Promise(function(i,s){function a(){switch(n.clientWaitSync(e,n.SYNC_FLUSH_COMMANDS_BIT,0)){case n.WAIT_FAILED:s();break;case n.TIMEOUT_EXPIRED:setTimeout(a,t);break;default:i()}}setTimeout(a,t)})}const py=new st().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),my=new st().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function GC(){const n={enabled:!0,workingColorSpace:xn,spaces:{},convert:function(s,a,r){return this.enabled===!1||a===r||!a||!r||(this.spaces[a].transfer===Pt&&(s.r=Fs(s.r),s.g=Fs(s.g),s.b=Fs(s.b)),this.spaces[a].primaries!==this.spaces[r].primaries&&(s.applyMatrix3(this.spaces[a].toXYZ),s.applyMatrix3(this.spaces[r].fromXYZ)),this.spaces[r].transfer===Pt&&(s.r=to(s.r),s.g=to(s.g),s.b=to(s.b))),s},workingToColorSpace:function(s,a){return this.convert(s,this.workingColorSpace,a)},colorSpaceToWorking:function(s,a){return this.convert(s,a,this.workingColorSpace)},getPrimaries:function(s){return this.spaces[s].primaries},getTransfer:function(s){return s===Ls?Bl:this.spaces[s].transfer},getToneMappingMode:function(s){return this.spaces[s].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(s,a=this.workingColorSpace){return s.fromArray(this.spaces[a].luminanceCoefficients)},define:function(s){Object.assign(this.spaces,s)},_getMatrix:function(s,a,r){return s.copy(this.spaces[a].toXYZ).multiply(this.spaces[r].fromXYZ)},_getDrawingBufferColorSpace:function(s){return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(s=this.workingColorSpace){return this.spaces[s].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(s,a){return Vl("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),n.workingToColorSpace(s,a)},toWorkingColorSpace:function(s,a){return Vl("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),n.colorSpaceToWorking(s,a)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],i=[.3127,.329];return n.define({[xn]:{primaries:e,whitePoint:i,transfer:Bl,toXYZ:py,fromXYZ:my,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:gt},outputColorSpaceConfig:{drawingBufferColorSpace:gt}},[gt]:{primaries:e,whitePoint:i,transfer:Pt,toXYZ:py,fromXYZ:my,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:gt}}}),n}const at=GC();function Fs(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function to(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}let yr;class dS{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{yr===void 0&&(yr=Hl("canvas")),yr.width=e.width,yr.height=e.height;const s=yr.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),i=yr}return i.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=Hl("canvas");t.width=e.width,t.height=e.height;const i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const s=i.getImageData(0,0,e.width,e.height),a=s.data;for(let r=0;r1),this.pmremVersion=0}get width(){return this.source.getSize(gf).x}get height(){return this.source.getSize(gf).y}get depth(){return this.source.getSize(gf).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const i=e[t];if(i===void 0){console.warn(`THREE.Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){console.warn(`THREE.Texture.setValues(): property '${t}' does not exist.`);continue}s&&i&&s.isVector2&&i.isVector2||s&&i&&s.isVector3&&i.isVector3||s&&i&&s.isMatrix3&&i.isMatrix3?s.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),t||(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==mh)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case ps:e.x=e.x-Math.floor(e.x);break;case Hn:e.x=e.x<0?0:1;break;case go:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case ps:e.y=e.y-Math.floor(e.y);break;case Hn:e.y=e.y<0?0:1;break;case go:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}Bt.DEFAULT_IMAGE=null;Bt.DEFAULT_MAPPING=mh;Bt.DEFAULT_ANISOTROPY=1;class qe{constructor(e=0,t=0,i=0,s=1){qe.prototype.isVector4=!0,this.x=e,this.y=t,this.z=i,this.w=s}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,s=this.z,a=this.w,r=e.elements;return this.x=r[0]*t+r[4]*i+r[8]*s+r[12]*a,this.y=r[1]*t+r[5]*i+r[9]*s+r[13]*a,this.z=r[2]*t+r[6]*i+r[10]*s+r[14]*a,this.w=r[3]*t+r[7]*i+r[11]*s+r[15]*a,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,i,s,a;const l=e.elements,c=l[0],u=l[4],d=l[8],h=l[1],f=l[5],p=l[9],g=l[2],_=l[6],m=l[10];if(Math.abs(u-h)<.01&&Math.abs(d-g)<.01&&Math.abs(p-_)<.01){if(Math.abs(u+h)<.1&&Math.abs(d+g)<.1&&Math.abs(p+_)<.1&&Math.abs(c+f+m-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const y=(c+1)/2,b=(f+1)/2,T=(m+1)/2,x=(u+h)/4,M=(d+g)/4,C=(p+_)/4;return y>b&&y>T?y<.01?(i=0,s=.707106781,a=.707106781):(i=Math.sqrt(y),s=x/i,a=M/i):b>T?b<.01?(i=.707106781,s=0,a=.707106781):(s=Math.sqrt(b),i=x/s,a=C/s):T<.01?(i=.707106781,s=.707106781,a=0):(a=Math.sqrt(T),i=M/a,s=C/a),this.set(i,s,a,t),this}let v=Math.sqrt((_-p)*(_-p)+(d-g)*(d-g)+(h-u)*(h-u));return Math.abs(v)<.001&&(v=1),this.x=(_-p)/v,this.y=(d-g)/v,this.z=(h-u)/v,this.w=Math.acos((c+f+m-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Ze(this.x,e.x,t.x),this.y=Ze(this.y,e.y,t.y),this.z=Ze(this.z,e.z,t.z),this.w=Ze(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Ze(this.x,e,t),this.y=Ze(this.y,e,t),this.z=Ze(this.z,e,t),this.w=Ze(this.w,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Ze(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class J_ extends gs{constructor(e=1,t=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Vt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},i),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=i.depth,this.scissor=new qe(0,0,e,t),this.scissorTest=!1,this.viewport=new qe(0,0,e,t);const s={width:e,height:t,depth:i.depth},a=new Bt(s);this.textures=[];const r=i.count;for(let o=0;o1;this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,i=e.textures.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Ii),Ii.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(zo),yc.subVectors(this.max,zo),vr.subVectors(e.a,zo),br.subVectors(e.b,zo),xr.subVectors(e.c,zo),Vs.subVectors(br,vr),Gs.subVectors(xr,br),ga.subVectors(vr,xr);let t=[0,-Vs.z,Vs.y,0,-Gs.z,Gs.y,0,-ga.z,ga.y,Vs.z,0,-Vs.x,Gs.z,0,-Gs.x,ga.z,0,-ga.x,-Vs.y,Vs.x,0,-Gs.y,Gs.x,0,-ga.y,ga.x,0];return!yf(t,vr,br,xr,yc)||(t=[1,0,0,0,1,0,0,0,1],!yf(t,vr,br,xr,yc))?!1:(vc.crossVectors(Vs,Gs),t=[vc.x,vc.y,vc.z],yf(t,vr,br,xr,yc))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Ii).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Ii).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(vs[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),vs[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),vs[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),vs[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),vs[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),vs[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),vs[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),vs[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(vs),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const vs=[new S,new S,new S,new S,new S,new S,new S,new S],Ii=new S,gc=new vn,vr=new S,br=new S,xr=new S,Vs=new S,Gs=new S,ga=new S,zo=new S,yc=new S,vc=new S,ya=new S;function yf(n,e,t,i,s){for(let a=0,r=n.length-3;a<=r;a+=3){ya.fromArray(n,a);const o=s.x*Math.abs(ya.x)+s.y*Math.abs(ya.y)+s.z*Math.abs(ya.z),l=e.dot(ya),c=t.dot(ya),u=i.dot(ya);if(Math.max(-Math.max(l,c,u),Math.min(l,c,u))>o)return!1}return!0}const qC=new vn,Ho=new S,vf=new S;class bn{constructor(e=new S,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const i=this.center;t!==void 0?i.copy(t):qC.setFromPoints(e).getCenter(i);let s=0;for(let a=0,r=e.length;athis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Ho.subVectors(e,this.center);const t=Ho.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),s=(i-this.radius)*.5;this.center.addScaledVector(Ho,s/i),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(vf.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Ho.copy(e.center).add(vf)),this.expandByPoint(Ho.copy(e.center).sub(vf))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}const bs=new S,bf=new S,bc=new S,$s=new S,xf=new S,xc=new S,wf=new S;class fr{constructor(e=new S,t=new S(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,bs)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=bs.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(bs.copy(this.origin).addScaledVector(this.direction,t),bs.distanceToSquared(e))}distanceSqToSegment(e,t,i,s){bf.copy(e).add(t).multiplyScalar(.5),bc.copy(t).sub(e).normalize(),$s.copy(this.origin).sub(bf);const a=e.distanceTo(t)*.5,r=-this.direction.dot(bc),o=$s.dot(this.direction),l=-$s.dot(bc),c=$s.lengthSq(),u=Math.abs(1-r*r);let d,h,f,p;if(u>0)if(d=r*l-o,h=r*o-l,p=a*u,d>=0)if(h>=-p)if(h<=p){const g=1/u;d*=g,h*=g,f=d*(d+r*h+2*o)+h*(r*d+h+2*l)+c}else h=a,d=Math.max(0,-(r*h+o)),f=-d*d+h*(h+2*l)+c;else h=-a,d=Math.max(0,-(r*h+o)),f=-d*d+h*(h+2*l)+c;else h<=-p?(d=Math.max(0,-(-r*a+o)),h=d>0?-a:Math.min(Math.max(-a,-l),a),f=-d*d+h*(h+2*l)+c):h<=p?(d=0,h=Math.min(Math.max(-a,-l),a),f=h*(h+2*l)+c):(d=Math.max(0,-(r*a+o)),h=d>0?a:Math.min(Math.max(-a,-l),a),f=-d*d+h*(h+2*l)+c);else h=r>0?-a:a,d=Math.max(0,-(r*h+o)),f=-d*d+h*(h+2*l)+c;return i&&i.copy(this.origin).addScaledVector(this.direction,d),s&&s.copy(bf).addScaledVector(bc,h),f}intersectSphere(e,t){bs.subVectors(e.center,this.origin);const i=bs.dot(this.direction),s=bs.dot(bs)-i*i,a=e.radius*e.radius;if(s>a)return null;const r=Math.sqrt(a-s),o=i-r,l=i+r;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,s,a,r,o,l;const c=1/this.direction.x,u=1/this.direction.y,d=1/this.direction.z,h=this.origin;return c>=0?(i=(e.min.x-h.x)*c,s=(e.max.x-h.x)*c):(i=(e.max.x-h.x)*c,s=(e.min.x-h.x)*c),u>=0?(a=(e.min.y-h.y)*u,r=(e.max.y-h.y)*u):(a=(e.max.y-h.y)*u,r=(e.min.y-h.y)*u),i>r||a>s||((a>i||isNaN(i))&&(i=a),(r=0?(o=(e.min.z-h.z)*d,l=(e.max.z-h.z)*d):(o=(e.max.z-h.z)*d,l=(e.min.z-h.z)*d),i>l||o>s)||((o>i||i!==i)&&(i=o),(l=0?i:s,t)}intersectsBox(e){return this.intersectBox(e,bs)!==null}intersectTriangle(e,t,i,s,a){xf.subVectors(t,e),xc.subVectors(i,e),wf.crossVectors(xf,xc);let r=this.direction.dot(wf),o;if(r>0){if(s)return null;o=1}else if(r<0)o=-1,r=-r;else return null;$s.subVectors(this.origin,e);const l=o*this.direction.dot(xc.crossVectors($s,xc));if(l<0)return null;const c=o*this.direction.dot(xf.cross($s));if(c<0||l+c>r)return null;const u=-o*$s.dot(wf);return u<0?null:this.at(u/r,a)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Me{constructor(e,t,i,s,a,r,o,l,c,u,d,h,f,p,g,_){Me.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,i,s,a,r,o,l,c,u,d,h,f,p,g,_)}set(e,t,i,s,a,r,o,l,c,u,d,h,f,p,g,_){const m=this.elements;return m[0]=e,m[4]=t,m[8]=i,m[12]=s,m[1]=a,m[5]=r,m[9]=o,m[13]=l,m[2]=c,m[6]=u,m[10]=d,m[14]=h,m[3]=f,m[7]=p,m[11]=g,m[15]=_,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Me().fromArray(this.elements)}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(e){const t=this.elements,i=e.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,i){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(e,t,i){return this.set(e.x,t.x,i.x,0,e.y,t.y,i.y,0,e.z,t.z,i.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,i=e.elements,s=1/wr.setFromMatrixColumn(e,0).length(),a=1/wr.setFromMatrixColumn(e,1).length(),r=1/wr.setFromMatrixColumn(e,2).length();return t[0]=i[0]*s,t[1]=i[1]*s,t[2]=i[2]*s,t[3]=0,t[4]=i[4]*a,t[5]=i[5]*a,t[6]=i[6]*a,t[7]=0,t[8]=i[8]*r,t[9]=i[9]*r,t[10]=i[10]*r,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,i=e.x,s=e.y,a=e.z,r=Math.cos(i),o=Math.sin(i),l=Math.cos(s),c=Math.sin(s),u=Math.cos(a),d=Math.sin(a);if(e.order==="XYZ"){const h=r*u,f=r*d,p=o*u,g=o*d;t[0]=l*u,t[4]=-l*d,t[8]=c,t[1]=f+p*c,t[5]=h-g*c,t[9]=-o*l,t[2]=g-h*c,t[6]=p+f*c,t[10]=r*l}else if(e.order==="YXZ"){const h=l*u,f=l*d,p=c*u,g=c*d;t[0]=h+g*o,t[4]=p*o-f,t[8]=r*c,t[1]=r*d,t[5]=r*u,t[9]=-o,t[2]=f*o-p,t[6]=g+h*o,t[10]=r*l}else if(e.order==="ZXY"){const h=l*u,f=l*d,p=c*u,g=c*d;t[0]=h-g*o,t[4]=-r*d,t[8]=p+f*o,t[1]=f+p*o,t[5]=r*u,t[9]=g-h*o,t[2]=-r*c,t[6]=o,t[10]=r*l}else if(e.order==="ZYX"){const h=r*u,f=r*d,p=o*u,g=o*d;t[0]=l*u,t[4]=p*c-f,t[8]=h*c+g,t[1]=l*d,t[5]=g*c+h,t[9]=f*c-p,t[2]=-c,t[6]=o*l,t[10]=r*l}else if(e.order==="YZX"){const h=r*l,f=r*c,p=o*l,g=o*c;t[0]=l*u,t[4]=g-h*d,t[8]=p*d+f,t[1]=d,t[5]=r*u,t[9]=-o*u,t[2]=-c*u,t[6]=f*d+p,t[10]=h-g*d}else if(e.order==="XZY"){const h=r*l,f=r*c,p=o*l,g=o*c;t[0]=l*u,t[4]=-d,t[8]=c*u,t[1]=h*d+g,t[5]=r*u,t[9]=f*d-p,t[2]=p*d-f,t[6]=o*u,t[10]=g*d+h}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(YC,e,jC)}lookAt(e,t,i){const s=this.elements;return li.subVectors(e,t),li.lengthSq()===0&&(li.z=1),li.normalize(),Ws.crossVectors(i,li),Ws.lengthSq()===0&&(Math.abs(i.z)===1?li.x+=1e-4:li.z+=1e-4,li.normalize(),Ws.crossVectors(i,li)),Ws.normalize(),wc.crossVectors(li,Ws),s[0]=Ws.x,s[4]=wc.x,s[8]=li.x,s[1]=Ws.y,s[5]=wc.y,s[9]=li.y,s[2]=Ws.z,s[6]=wc.z,s[10]=li.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,s=t.elements,a=this.elements,r=i[0],o=i[4],l=i[8],c=i[12],u=i[1],d=i[5],h=i[9],f=i[13],p=i[2],g=i[6],_=i[10],m=i[14],v=i[3],y=i[7],b=i[11],T=i[15],x=s[0],M=s[4],C=s[8],w=s[12],E=s[1],R=s[5],D=s[9],O=s[13],k=s[2],U=s[6],F=s[10],W=s[14],H=s[3],ne=s[7],oe=s[11],pe=s[15];return a[0]=r*x+o*E+l*k+c*H,a[4]=r*M+o*R+l*U+c*ne,a[8]=r*C+o*D+l*F+c*oe,a[12]=r*w+o*O+l*W+c*pe,a[1]=u*x+d*E+h*k+f*H,a[5]=u*M+d*R+h*U+f*ne,a[9]=u*C+d*D+h*F+f*oe,a[13]=u*w+d*O+h*W+f*pe,a[2]=p*x+g*E+_*k+m*H,a[6]=p*M+g*R+_*U+m*ne,a[10]=p*C+g*D+_*F+m*oe,a[14]=p*w+g*O+_*W+m*pe,a[3]=v*x+y*E+b*k+T*H,a[7]=v*M+y*R+b*U+T*ne,a[11]=v*C+y*D+b*F+T*oe,a[15]=v*w+y*O+b*W+T*pe,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[4],s=e[8],a=e[12],r=e[1],o=e[5],l=e[9],c=e[13],u=e[2],d=e[6],h=e[10],f=e[14],p=e[3],g=e[7],_=e[11],m=e[15];return p*(+a*l*d-s*c*d-a*o*h+i*c*h+s*o*f-i*l*f)+g*(+t*l*f-t*c*h+a*r*h-s*r*f+s*c*u-a*l*u)+_*(+t*c*d-t*o*f-a*r*d+i*r*f+a*o*u-i*c*u)+m*(-s*o*u-t*l*d+t*o*h+s*r*d-i*r*h+i*l*u)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,i){const s=this.elements;return e.isVector3?(s[12]=e.x,s[13]=e.y,s[14]=e.z):(s[12]=e,s[13]=t,s[14]=i),this}invert(){const e=this.elements,t=e[0],i=e[1],s=e[2],a=e[3],r=e[4],o=e[5],l=e[6],c=e[7],u=e[8],d=e[9],h=e[10],f=e[11],p=e[12],g=e[13],_=e[14],m=e[15],v=d*_*c-g*h*c+g*l*f-o*_*f-d*l*m+o*h*m,y=p*h*c-u*_*c-p*l*f+r*_*f+u*l*m-r*h*m,b=u*g*c-p*d*c+p*o*f-r*g*f-u*o*m+r*d*m,T=p*d*l-u*g*l-p*o*h+r*g*h+u*o*_-r*d*_,x=t*v+i*y+s*b+a*T;if(x===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const M=1/x;return e[0]=v*M,e[1]=(g*h*a-d*_*a-g*s*f+i*_*f+d*s*m-i*h*m)*M,e[2]=(o*_*a-g*l*a+g*s*c-i*_*c-o*s*m+i*l*m)*M,e[3]=(d*l*a-o*h*a-d*s*c+i*h*c+o*s*f-i*l*f)*M,e[4]=y*M,e[5]=(u*_*a-p*h*a+p*s*f-t*_*f-u*s*m+t*h*m)*M,e[6]=(p*l*a-r*_*a-p*s*c+t*_*c+r*s*m-t*l*m)*M,e[7]=(r*h*a-u*l*a+u*s*c-t*h*c-r*s*f+t*l*f)*M,e[8]=b*M,e[9]=(p*d*a-u*g*a-p*i*f+t*g*f+u*i*m-t*d*m)*M,e[10]=(r*g*a-p*o*a+p*i*c-t*g*c-r*i*m+t*o*m)*M,e[11]=(u*o*a-r*d*a-u*i*c+t*d*c+r*i*f-t*o*f)*M,e[12]=T*M,e[13]=(u*g*s-p*d*s+p*i*h-t*g*h-u*i*_+t*d*_)*M,e[14]=(p*o*s-r*g*s-p*i*l+t*g*l+r*i*_-t*o*_)*M,e[15]=(r*d*s-u*o*s+u*i*l-t*d*l-r*i*h+t*o*h)*M,this}scale(e){const t=this.elements,i=e.x,s=e.y,a=e.z;return t[0]*=i,t[4]*=s,t[8]*=a,t[1]*=i,t[5]*=s,t[9]*=a,t[2]*=i,t[6]*=s,t[10]*=a,t[3]*=i,t[7]*=s,t[11]*=a,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],s=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,s))}makeTranslation(e,t,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const i=Math.cos(t),s=Math.sin(t),a=1-i,r=e.x,o=e.y,l=e.z,c=a*r,u=a*o;return this.set(c*r+i,c*o-s*l,c*l+s*o,0,c*o+s*l,u*o+i,u*l-s*r,0,c*l-s*o,u*l+s*r,a*l*l+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,s,a,r){return this.set(1,i,a,0,e,1,r,0,t,s,1,0,0,0,0,1),this}compose(e,t,i){const s=this.elements,a=t._x,r=t._y,o=t._z,l=t._w,c=a+a,u=r+r,d=o+o,h=a*c,f=a*u,p=a*d,g=r*u,_=r*d,m=o*d,v=l*c,y=l*u,b=l*d,T=i.x,x=i.y,M=i.z;return s[0]=(1-(g+m))*T,s[1]=(f+b)*T,s[2]=(p-y)*T,s[3]=0,s[4]=(f-b)*x,s[5]=(1-(h+m))*x,s[6]=(_+v)*x,s[7]=0,s[8]=(p+y)*M,s[9]=(_-v)*M,s[10]=(1-(h+g))*M,s[11]=0,s[12]=e.x,s[13]=e.y,s[14]=e.z,s[15]=1,this}decompose(e,t,i){const s=this.elements;let a=wr.set(s[0],s[1],s[2]).length();const r=wr.set(s[4],s[5],s[6]).length(),o=wr.set(s[8],s[9],s[10]).length();this.determinant()<0&&(a=-a),e.x=s[12],e.y=s[13],e.z=s[14],Li.copy(this);const c=1/a,u=1/r,d=1/o;return Li.elements[0]*=c,Li.elements[1]*=c,Li.elements[2]*=c,Li.elements[4]*=u,Li.elements[5]*=u,Li.elements[6]*=u,Li.elements[8]*=d,Li.elements[9]*=d,Li.elements[10]*=d,t.setFromRotationMatrix(Li),i.x=a,i.y=r,i.z=o,this}makePerspective(e,t,i,s,a,r,o=hi,l=!1){const c=this.elements,u=2*a/(t-e),d=2*a/(i-s),h=(t+e)/(t-e),f=(i+s)/(i-s);let p,g;if(l)p=a/(r-a),g=r*a/(r-a);else if(o===hi)p=-(r+a)/(r-a),g=-2*r*a/(r-a);else if(o===So)p=-r/(r-a),g=-r*a/(r-a);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return c[0]=u,c[4]=0,c[8]=h,c[12]=0,c[1]=0,c[5]=d,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=g,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,i,s,a,r,o=hi,l=!1){const c=this.elements,u=2/(t-e),d=2/(i-s),h=-(t+e)/(t-e),f=-(i+s)/(i-s);let p,g;if(l)p=1/(r-a),g=r/(r-a);else if(o===hi)p=-2/(r-a),g=-(r+a)/(r-a);else if(o===So)p=-1/(r-a),g=-a/(r-a);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return c[0]=u,c[4]=0,c[8]=0,c[12]=h,c[1]=0,c[5]=d,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=p,c[14]=g,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const t=this.elements,i=e.elements;for(let s=0;s<16;s++)if(t[s]!==i[s])return!1;return!0}fromArray(e,t=0){for(let i=0;i<16;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],e}}const wr=new S,Li=new Me,YC=new S(0,0,0),jC=new S(1,1,1),Ws=new S,wc=new S,li=new S,_y=new Me,gy=new dt;class an{constructor(e=0,t=0,i=0,s=an.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=s}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,i,s=this._order){return this._x=e,this._y=t,this._z=i,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,i=!0){const s=e.elements,a=s[0],r=s[4],o=s[8],l=s[1],c=s[5],u=s[9],d=s[2],h=s[6],f=s[10];switch(t){case"XYZ":this._y=Math.asin(Ze(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,f),this._z=Math.atan2(-r,a)):(this._x=Math.atan2(h,c),this._z=0);break;case"YXZ":this._x=Math.asin(-Ze(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-d,a),this._z=0);break;case"ZXY":this._x=Math.asin(Ze(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-d,f),this._z=Math.atan2(-r,c)):(this._y=0,this._z=Math.atan2(l,a));break;case"ZYX":this._y=Math.asin(-Ze(d,-1,1)),Math.abs(d)<.9999999?(this._x=Math.atan2(h,f),this._z=Math.atan2(l,a)):(this._x=0,this._z=Math.atan2(-r,c));break;case"YZX":this._z=Math.asin(Ze(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-u,c),this._y=Math.atan2(-d,a)):(this._x=0,this._y=Math.atan2(o,f));break;case"XZY":this._z=Math.asin(-Ze(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(h,c),this._y=Math.atan2(o,a)):(this._x=Math.atan2(-u,f),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,i===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return _y.makeRotationFromQuaternion(e),this.setFromRotationMatrix(_y,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return gy.setFromEuler(this),this.setFromQuaternion(gy,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}an.DEFAULT_ORDER="XYZ";class Eh{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let i=0;i0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(s.matrixAutoUpdate=!1),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),s.instanceInfo=this._instanceInfo.map(o=>({...o})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(e),s.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(s.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(s.boundingBox=this.boundingBox.toJSON()));function a(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=a(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const l=o.shapes;if(Array.isArray(l))for(let c=0,u=l.length;c0){s.children=[];for(let o=0;o0){s.animations=[];for(let o=0;o0&&(i.geometries=o),l.length>0&&(i.materials=l),c.length>0&&(i.textures=c),u.length>0&&(i.images=u),d.length>0&&(i.shapes=d),h.length>0&&(i.skeletons=h),f.length>0&&(i.animations=f),p.length>0&&(i.nodes=p)}return i.object=s,i;function r(o){const l=[];for(const c in o){const u=o[c];delete u.metadata,l.push(u)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let i=0;i0?s.multiplyScalar(1/Math.sqrt(a)):s.set(0,0,0)}static getBarycoord(e,t,i,s,a){Di.subVectors(s,t),ws.subVectors(i,t),Tf.subVectors(e,t);const r=Di.dot(Di),o=Di.dot(ws),l=Di.dot(Tf),c=ws.dot(ws),u=ws.dot(Tf),d=r*c-o*o;if(d===0)return a.set(0,0,0),null;const h=1/d,f=(c*l-o*u)*h,p=(r*u-o*l)*h;return a.set(1-f-p,p,f)}static containsPoint(e,t,i,s){return this.getBarycoord(e,t,i,s,Ss)===null?!1:Ss.x>=0&&Ss.y>=0&&Ss.x+Ss.y<=1}static getInterpolation(e,t,i,s,a,r,o,l){return this.getBarycoord(e,t,i,s,Ss)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(a,Ss.x),l.addScaledVector(r,Ss.y),l.addScaledVector(o,Ss.z),l)}static getInterpolatedAttribute(e,t,i,s,a,r){return Af.setScalar(0),Rf.setScalar(0),Pf.setScalar(0),Af.fromBufferAttribute(e,t),Rf.fromBufferAttribute(e,i),Pf.fromBufferAttribute(e,s),r.setScalar(0),r.addScaledVector(Af,a.x),r.addScaledVector(Rf,a.y),r.addScaledVector(Pf,a.z),r}static isFrontFacing(e,t,i,s){return Di.subVectors(i,t),ws.subVectors(e,t),Di.cross(ws).dot(s)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,s){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[s]),this}setFromAttributeAndIndices(e,t,i,s){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,s),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Di.subVectors(this.c,this.b),ws.subVectors(this.a,this.b),Di.cross(ws).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Qn.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Qn.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,s,a){return Qn.getInterpolation(e,this.a,this.b,this.c,t,i,s,a)}containsPoint(e){return Qn.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Qn.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,s=this.b,a=this.c;let r,o;Mr.subVectors(s,i),Er.subVectors(a,i),Mf.subVectors(e,i);const l=Mr.dot(Mf),c=Er.dot(Mf);if(l<=0&&c<=0)return t.copy(i);Ef.subVectors(e,s);const u=Mr.dot(Ef),d=Er.dot(Ef);if(u>=0&&d<=u)return t.copy(s);const h=l*d-u*c;if(h<=0&&l>=0&&u<=0)return r=l/(l-u),t.copy(i).addScaledVector(Mr,r);Cf.subVectors(e,a);const f=Mr.dot(Cf),p=Er.dot(Cf);if(p>=0&&f<=p)return t.copy(a);const g=f*c-l*p;if(g<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(i).addScaledVector(Er,o);const _=u*p-f*d;if(_<=0&&d-u>=0&&f-p>=0)return Sy.subVectors(a,s),o=(d-u)/(d-u+(f-p)),t.copy(s).addScaledVector(Sy,o);const m=1/(_+g+h);return r=g*m,o=h*m,t.copy(i).addScaledVector(Mr,r).addScaledVector(Er,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const hS={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Xs={h:0,s:0,l:0},Tc={h:0,s:0,l:0};function If(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*6*(2/3-t):n}class ue{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){const s=e;s&&s.isColor?this.copy(s):typeof s=="number"?this.setHex(s):typeof s=="string"&&this.setStyle(s)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=gt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,at.colorSpaceToWorking(this,t),this}setRGB(e,t,i,s=at.workingColorSpace){return this.r=e,this.g=t,this.b=i,at.colorSpaceToWorking(this,s),this}setHSL(e,t,i,s=at.workingColorSpace){if(e=Z_(e,1),t=Ze(t,0,1),i=Ze(i,0,1),t===0)this.r=this.g=this.b=i;else{const a=i<=.5?i*(1+t):i+t-i*t,r=2*i-a;this.r=If(r,a,e+1/3),this.g=If(r,a,e),this.b=If(r,a,e-1/3)}return at.colorSpaceToWorking(this,s),this}setStyle(e,t=gt){function i(a){a!==void 0&&parseFloat(a)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(e)){let a;const r=s[1],o=s[2];switch(r){case"rgb":case"rgba":if(a=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setRGB(Math.min(255,parseInt(a[1],10))/255,Math.min(255,parseInt(a[2],10))/255,Math.min(255,parseInt(a[3],10))/255,t);if(a=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setRGB(Math.min(100,parseInt(a[1],10))/100,Math.min(100,parseInt(a[2],10))/100,Math.min(100,parseInt(a[3],10))/100,t);break;case"hsl":case"hsla":if(a=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setHSL(parseFloat(a[1])/360,parseFloat(a[2])/100,parseFloat(a[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(e)){const a=s[1],r=a.length;if(r===3)return this.setRGB(parseInt(a.charAt(0),16)/15,parseInt(a.charAt(1),16)/15,parseInt(a.charAt(2),16)/15,t);if(r===6)return this.setHex(parseInt(a,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=gt){const i=hS[e.toLowerCase()];return i!==void 0?this.setHex(i,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Fs(e.r),this.g=Fs(e.g),this.b=Fs(e.b),this}copyLinearToSRGB(e){return this.r=to(e.r),this.g=to(e.g),this.b=to(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=gt){return at.workingToColorSpace(En.copy(this),e),Math.round(Ze(En.r*255,0,255))*65536+Math.round(Ze(En.g*255,0,255))*256+Math.round(Ze(En.b*255,0,255))}getHexString(e=gt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=at.workingColorSpace){at.workingToColorSpace(En.copy(this),t);const i=En.r,s=En.g,a=En.b,r=Math.max(i,s,a),o=Math.min(i,s,a);let l,c;const u=(o+r)/2;if(o===r)l=0,c=0;else{const d=r-o;switch(c=u<=.5?d/(r+o):d/(2-r-o),r){case i:l=(s-a)/d+(s0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const i=e[t];if(i===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(i):s&&s.isVector3&&i&&i.isVector3?s.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==tr&&(i.blending=this.blending),this.side!==fs&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==Ol&&(i.blendSrc=this.blendSrc),this.blendDst!==Fl&&(i.blendDst=this.blendDst),this.blendEquation!==Is&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==sr&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==xm&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Ua&&(i.stencilFail=this.stencilFail),this.stencilZFail!==Ua&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==Ua&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function s(a){const r=[];for(const o in a){const l=a[o];delete l.metadata,r.push(l)}return r}if(t){const a=s(e.textures),r=s(e.images);a.length>0&&(i.textures=a),r.length>0&&(i.images=r)}return i}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let i=null;if(t!==null){const s=t.length;i=new Array(s);for(let a=0;a!==s;++a)i[a]=t[a].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class Ye extends Qt{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new ue(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new an,this.combine=nc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Ds=nA();function nA(){const n=new ArrayBuffer(4),e=new Float32Array(n),t=new Uint32Array(n),i=new Uint32Array(512),s=new Uint32Array(512);for(let l=0;l<256;++l){const c=l-127;c<-27?(i[l]=0,i[l|256]=32768,s[l]=24,s[l|256]=24):c<-14?(i[l]=1024>>-c-14,i[l|256]=1024>>-c-14|32768,s[l]=-c-1,s[l|256]=-c-1):c<=15?(i[l]=c+15<<10,i[l|256]=c+15<<10|32768,s[l]=13,s[l|256]=13):c<128?(i[l]=31744,i[l|256]=64512,s[l]=24,s[l|256]=24):(i[l]=31744,i[l|256]=64512,s[l]=13,s[l|256]=13)}const a=new Uint32Array(2048),r=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,u=0;for(;(c&8388608)===0;)c<<=1,u-=8388608;c&=-8388609,u+=947912704,a[l]=c|u}for(let l=1024;l<2048;++l)a[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)r[l]=l<<23;r[31]=1199570944,r[32]=2147483648;for(let l=33;l<63;++l)r[l]=2147483648+(l-32<<23);r[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:e,uint32View:t,baseTable:i,shiftTable:s,mantissaTable:a,exponentTable:r,offsetTable:o}}function Yn(n){Math.abs(n)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),n=Ze(n,-65504,65504),Ds.floatView[0]=n;const e=Ds.uint32View[0],t=e>>23&511;return Ds.baseTable[t]+((e&8388607)>>Ds.shiftTable[t])}function ul(n){const e=n>>10;return Ds.uint32View[0]=Ds.mantissaTable[Ds.offsetTable[e]+(n&1023)]+Ds.exponentTable[e],Ds.floatView[0]}class dl{static toHalfFloat(e){return Yn(e)}static fromHalfFloat(e){return ul(e)}}const nn=new S,Mc=new te;let iA=0;class rt{constructor(e,t,i=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:iA++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=zl,this.updateRanges=[],this.gpuType=Sn,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,i){e*=this.itemSize,i*=t.itemSize;for(let s=0,a=this.itemSize;st.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new vn);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new S(-1/0,-1/0,-1/0),new S(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,s=t.length;i0&&(e.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const l in i){const c=i[l];e.data.attributes[l]=c.toJSON(e.data)}const s={};let a=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],u=[];for(let d=0,h=c.length;d0&&(s[l]=u,a=!0)}a&&(e.data.morphAttributes=s,e.data.morphTargetsRelative=this.morphTargetsRelative);const r=this.groups;r.length>0&&(e.data.groups=JSON.parse(JSON.stringify(r)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const i=e.index;i!==null&&this.setIndex(i.clone());const s=e.attributes;for(const c in s){const u=s[c];this.setAttribute(c,u.clone(t))}const a=e.morphAttributes;for(const c in a){const u=[],d=a[c];for(let h=0,f=d.length;h0){const s=t[i[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,r=s.length;a(e.far-e.near)**2))&&(Ty.copy(a).invert(),va.copy(e.ray).applyMatrix4(Ty),!(i.boundingBox!==null&&va.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,va)))}_computeIntersections(e,t,i){let s;const a=this.geometry,r=this.material,o=a.index,l=a.attributes.position,c=a.attributes.uv,u=a.attributes.uv1,d=a.attributes.normal,h=a.groups,f=a.drawRange;if(o!==null)if(Array.isArray(r))for(let p=0,g=h.length;pt.far?null:{distance:c,point:Ic.clone(),object:n}}function Lc(n,e,t,i,s,a,r,o,l,c){n.getVertexPosition(o,Cc),n.getVertexPosition(l,Ac),n.getVertexPosition(c,Rc);const u=dA(n,e,t,i,Cc,Ac,Rc,Ey);if(u){const d=new S;Qn.getBarycoord(Ey,Cc,Ac,Rc,d),s&&(u.uv=Qn.getInterpolatedAttribute(s,o,l,c,d,new te)),a&&(u.uv1=Qn.getInterpolatedAttribute(a,o,l,c,d,new te)),r&&(u.normal=Qn.getInterpolatedAttribute(r,o,l,c,d,new S),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));const h={a:o,b:l,c,normal:new S,materialIndex:0};Qn.getNormal(Cc,Ac,Rc,h.normal),u.face=h,u.barycoord=d}return u}class Ei extends Ge{constructor(e=1,t=1,i=1,s=1,a=1,r=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:s,heightSegments:a,depthSegments:r};const o=this;s=Math.floor(s),a=Math.floor(a),r=Math.floor(r);const l=[],c=[],u=[],d=[];let h=0,f=0;p("z","y","x",-1,-1,i,t,e,r,a,0),p("z","y","x",1,-1,i,t,-e,r,a,1),p("x","z","y",1,1,e,i,t,s,r,2),p("x","z","y",1,-1,e,i,-t,s,r,3),p("x","y","z",1,-1,e,t,i,s,a,4),p("x","y","z",-1,-1,e,t,-i,s,a,5),this.setIndex(l),this.setAttribute("position",new Ee(c,3)),this.setAttribute("normal",new Ee(u,3)),this.setAttribute("uv",new Ee(d,2));function p(g,_,m,v,y,b,T,x,M,C,w){const E=b/M,R=T/C,D=b/2,O=T/2,k=x/2,U=M+1,F=C+1;let W=0,H=0;const ne=new S;for(let oe=0;oe0?1:-1,u.push(ne.x,ne.y,ne.z),d.push(Ie/M),d.push(1-oe/C),W+=1}}for(let oe=0;oee)i=s-1;else return s}return Math.max(0,t-1)}class Cw{_listeners=new Map;on(e,t){let i=this._listeners.get(e);return i||(i=new Set,this._listeners.set(e,i)),i.add(t),this}once(e,t){const i=(...s)=>{this.off(e,i),t(...s)};return this.on(e,i)}off(e,t){const i=this._listeners.get(e);return i?(t?i.delete(t):i.clear(),i.size===0&&this._listeners.delete(e),this):this}removeListener(e,t){return this.off(e,t)}removeAllListeners(e){return e?this._listeners.delete(e):this._listeners.clear(),this}emit(e,...t){const i=this._listeners.get(e);if(!i||i.size===0)return!1;for(const s of[...i])s(...t);return!0}}function vf(n){return n?{x:n.x,y:n.z,z:n.y}:null}function N1(n){return n?{x:n.x,y:n.z,z:n.y,w:-n.w}:null}function U1(n){return n*100/255}const py={Octane:{length:118.0074,width:84.19941,height:36.15907,offsetX:13.87566,offsetZ:20.75499},Dominus:{length:127.9268,width:83.27995,height:31.3,offsetX:9,offsetZ:15.75},Plank:{length:128.8198,width:84.67036,height:29.3944,offsetX:9.00857,offsetZ:12.0942},Breakout:{length:131.4924,width:80.521,height:30.3,offsetX:12.5,offsetZ:11.75},Hybrid:{length:127.0192,width:82.18787,height:34.15907,offsetX:13.87566,offsetZ:20.75499},Merc:{length:120.72,width:76.71,height:41.66,offsetX:11.37566,offsetZ:21.504988}},B1={21:{name:"Backfire",hitbox:"Octane"},22:{name:"Breakout",hitbox:"Breakout"},23:{name:"Octane",hitbox:"Octane"},24:{name:"Paladin",hitbox:"Plank"},25:{name:"Road Hog",hitbox:"Octane"},26:{name:"Gizmo",hitbox:"Octane"},28:{name:"X-Devil",hitbox:"Hybrid"},29:{name:"Hotshot",hitbox:"Dominus"},30:{name:"Merc",hitbox:"Merc"},31:{name:"Venom",hitbox:"Hybrid"},402:{name:"Takumi",hitbox:"Octane"},403:{name:"Dominus",hitbox:"Dominus"},404:{name:"Scarab",hitbox:"Octane"},523:{name:"Zippy",hitbox:"Octane"},597:{name:"DeLorean Time Machine",hitbox:"Dominus"},600:{name:"Ripper",hitbox:"Dominus"},607:{name:"Grog",hitbox:"Octane"},1018:{name:"Dominus GT",hitbox:"Dominus"},1159:{name:"X-Devil Mk2",hitbox:"Hybrid"},1171:{name:"Masamune",hitbox:"Dominus"},1172:{name:"Marauder",hitbox:"Octane"},1286:{name:"Aftershock",hitbox:"Dominus"},1295:{name:"Takumi RX-T",hitbox:"Octane"},1300:{name:"Road Hog XL",hitbox:"Octane"},1317:{name:"Esper",hitbox:"Hybrid"},1416:{name:"Breakout Type-S",hitbox:"Breakout"},1475:{name:"Proteus",hitbox:"Octane"},1478:{name:"Triton",hitbox:"Octane"},1533:{name:"Vulcan",hitbox:"Octane"},1568:{name:"Octane ZSR",hitbox:"Octane"},1603:{name:"Twin Mill III",hitbox:"Plank"},1623:{name:"Bone Shaker",hitbox:"Octane"},1624:{name:"Endo",hitbox:"Hybrid"},1675:{name:"Ice Charger",hitbox:"Dominus"},1689:{name:"Nemesis",hitbox:"Dominus"},1691:{name:"Mantis",hitbox:"Plank"},1856:{name:"Jager 619",hitbox:"Hybrid"},1883:{name:"Imperator DT5",hitbox:"Dominus"},1894:{name:"Samurai",hitbox:"Breakout"},1919:{name:"Centio",hitbox:"Plank"},1932:{name:"Animus GP",hitbox:"Breakout"},2070:{name:"Werewolf",hitbox:"Dominus"},2268:{name:"Fast & Furious Dodge Charger",hitbox:"Dominus"},2269:{name:"Fast & Furious Nissan Skyline",hitbox:"Hybrid"},2665:{name:"The Dark Knight's Tumbler",hitbox:"Octane"},2666:{name:"Batmobile (1989)",hitbox:"Dominus"},2853:{name:"Twinzer",hitbox:"Octane"},2919:{name:"Jurassic Jeep Wrangler",hitbox:"Octane"},2949:{name:"Fast 4WD",hitbox:"Octane"},2950:{name:"MR11",hitbox:"Dominus"},2951:{name:"Gazella GT",hitbox:"Dominus"},3031:{name:"Cyclone",hitbox:"Breakout"},3155:{name:"Maverick",hitbox:"Dominus"},3156:{name:"Maverick G1",hitbox:"Dominus"},3157:{name:"Maverick GXT",hitbox:"Dominus"},3265:{name:"McLaren 570S",hitbox:"Dominus"},3311:{name:"Komodo",hitbox:"Breakout"},3426:{name:"Diestro",hitbox:"Dominus"},3451:{name:"Nimbus",hitbox:"Hybrid"},3582:{name:"Insidio",hitbox:"Hybrid"},3594:{name:"Artemis G1",hitbox:"Plank"},3614:{name:"Artemis",hitbox:"Plank"},3622:{name:"Artemis GXT",hitbox:"Plank"},3702:{name:"Tygris",hitbox:"Hybrid"},3875:{name:"Guardian GXT",hitbox:"Dominus"},3879:{name:"Guardian",hitbox:"Dominus"},3880:{name:"Guardian G1",hitbox:"Dominus"},4014:{name:"K.I.T.T.",hitbox:"Dominus"},4155:{name:"Ecto-1",hitbox:"Dominus"},4268:{name:"Sentinel",hitbox:"Plank"},4284:{name:"Fennec",hitbox:"Octane"},4318:{name:"Mudcat",hitbox:"Octane"},4319:{name:"Mudcat G1",hitbox:"Octane"},4320:{name:"Mudcat GXT",hitbox:"Octane"},4367:{name:"Chikara GXT",hitbox:"Dominus"},4472:{name:"Chikara",hitbox:"Dominus"},4473:{name:"Chikara G1",hitbox:"Dominus"},4745:{name:"Ronin GXT",hitbox:"Dominus"},4770:{name:"Dominus",hitbox:"Dominus"},4780:{name:"Battle Bus",hitbox:"Merc"},4781:{name:"Peregrine TT",hitbox:"Dominus"},4782:{name:"Psyclops",hitbox:"Body_Tritip_Handling"},4861:{name:"Ronin",hitbox:"Dominus"},4864:{name:"Ronin G1",hitbox:"Dominus"},4906:{name:"Harbinger",hitbox:"Octane"},5020:{name:"Outlaw",hitbox:"Octane"},5039:{name:"Harbinger GXT",hitbox:"Octane"},5188:{name:"Scarab",hitbox:"Octane"},5265:{name:"Formula 1 2021",hitbox:"Plank"},5361:{name:"Dingo",hitbox:"Octane"},5470:{name:"R3MX",hitbox:"Hybrid"},5488:{name:"R3MX GXT",hitbox:"Hybrid"},5547:{name:"007's Aston Martin DB5",hitbox:"Octane"},5709:{name:"NASCAR Ford Mustang",hitbox:"Dominus"},5713:{name:"Ford F-150 RLE",hitbox:"Octane"},5773:{name:"NASCAR Toyota Camry",hitbox:"Dominus"},5823:{name:"NASCAR Chevrolet Camaro",hitbox:"Dominus"},5837:{name:"Outlaw GXT",hitbox:"Octane"},5858:{name:"Tyranno",hitbox:"Dominus"},5879:{name:"Fast & Furious Pontiac Fiero",hitbox:"Hybrid"},5951:{name:"Jackal",hitbox:"Octane"},5964:{name:"Lamborghini Huracan STO",hitbox:"Dominus"},5979:{name:"Tyranno GXT",hitbox:"Dominus"},6122:{name:"Masamune",hitbox:"Dominus"},6243:{name:"Nexus",hitbox:"Breakout"},6244:{name:"BMW M240i",hitbox:"Dominus"},6247:{name:"McLaren 765LT",hitbox:"Dominus"},6260:{name:"007's Aston Martin Valhalla",hitbox:"Dominus"},6489:{name:"Nexus SC",hitbox:"Breakout"},6836:{name:"Ford Mustang Shelby GT350R RLE",hitbox:"Dominus"},6939:{name:"Ford Mustang Mach-E RLE",hitbox:"Octane"},7012:{name:"Tesla Cybertruck",hitbox:"Hybrid"},7052:{name:"Formula 1 2022",hitbox:"Plank"},7211:{name:"Mamba",hitbox:"Dominus"},7336:{name:"Nomad",hitbox:"Merc"},7337:{name:"NASCAR Next Gen Chevrolet Camaro",hitbox:"Dominus"},7338:{name:"NASCAR Next Gen Ford Mustang",hitbox:"Dominus"},7341:{name:"NASCAR Next Gen Toyota Camry",hitbox:"Dominus"},7343:{name:"007's Aston Martin DBS",hitbox:"Dominus"},7415:{name:"Batmobile (2022)",hitbox:"Dominus"},7477:{name:"Nomad GXT",hitbox:"Merc"},7512:{name:"Lamborghini Countach LPI 800-4",hitbox:"Dominus"},7532:{name:"Maestro",hitbox:"Dominus"},7593:{name:"Nissan Z Performance",hitbox:"Dominus"},7651:{name:"Redline",hitbox:"Breakout"},7696:{name:"Whiplash",hitbox:"Breakout"},7772:{name:"Ferrari 296 GTB",hitbox:"Dominus"},7815:{name:"Ford Bronco Raptor RLE",hitbox:"Merc"},7890:{name:"Fuse",hitbox:"Breakout"},7901:{name:"Fast & Furious Mazda RX-7",hitbox:"Breakout"},7947:{name:"Honda Civic Type R",hitbox:"Octane"},7948:{name:"Honda Civic Type R-LE",hitbox:"Octane"},7979:{name:"Stampede",hitbox:"Merc"},8006:{name:"Mako",hitbox:"Breakout"},8360:{name:"Emperor",hitbox:"Breakout"},8361:{name:"Emperor II",hitbox:"Breakout"},8383:{name:"Xentari",hitbox:"Octane"},8454:{name:"Admiral",hitbox:"Dominus"},8524:{name:"Bugatti Centodieci",hitbox:"Plank"},8565:{name:"Emperor II: Frozen",hitbox:"Breakout"},8566:{name:"Emperor II: Scorched",hitbox:"Breakout"},8669:{name:"Ace",hitbox:"Breakout"},8806:{name:"Volkswagen Golf GTI",hitbox:"Octane"},8807:{name:"Volkswagen Golf GTI RLE",hitbox:"Octane"},9053:{name:"Fast & Furious Dodge Charger SRT Hellcat",hitbox:"Dominus"},9084:{name:"Nissan Silvia",hitbox:"Hybrid"},9085:{name:"Nissan Silvia RLE",hitbox:"Hybrid"},9088:{name:"Porsche 911 Turbo",hitbox:"Dominus"},9089:{name:"Porsche 911 Turbo RLE",hitbox:"Dominus"},9140:{name:"Bumblebee",hitbox:"Dominus"},9357:{name:"Diesel",hitbox:"Breakout"},9388:{name:"Lightning McQueen",hitbox:"Dominus"},9427:{name:"Primo",hitbox:"Hybrid"},9894:{name:"Scorpion",hitbox:"Dominus"},10044:{name:"Beskar",hitbox:"Hybrid"},10094:{name:"Ford Mustang GTD",hitbox:"Dominus"},10440:{name:"Nissan Fairlady Z",hitbox:"Dominus"},10441:{name:"Nissan Fairlady Z RLE",hitbox:"Dominus"},10689:{name:"Behemoth",hitbox:"Merc"},10694:{name:"Lockjaw",hitbox:"Dominus"},10697:{name:"The Incredibile",hitbox:"Breakout"},10698:{name:"1966 Cadillac DeVille",hitbox:"Breakout"},10805:{name:"Nissan Skyline GT-R (R32)",hitbox:"Hybrid"},10817:{name:"Quadra Turbo-R",hitbox:"Breakout"},10822:{name:"McLaren Senna",hitbox:"Breakout"},10896:{name:"BMW 1 Series",hitbox:"Octane"},10897:{name:"BMW 1 Series RLE",hitbox:"Octane"},10900:{name:"Shokunin",hitbox:"Octane"},10901:{name:"Shokunin GXT",hitbox:"Octane"},11016:{name:"Porsche 911 GT3 RS",hitbox:"Dominus"},11038:{name:"Revolver",hitbox:"Breakout"},11095:{name:"Dodge Charger Daytona Scat Pack",hitbox:"Dominus"},11098:{name:"Turtle Van",hitbox:"Merc"},11138:{name:"Void Burn",hitbox:"Hybrid"},11141:{name:"Lamborghini Urus SE",hitbox:"Hybrid"},11314:{name:"Jeep Wrangler Rubicon",hitbox:"Merc"},11315:{name:"Ford Mustang Shelby GT500",hitbox:"Dominus"},11336:{name:"Dominus: Neon",hitbox:"Dominus"},11379:{name:"Ram 1500 RHO",hitbox:"Hybrid"},11394:{name:"Azura",hitbox:"Breakout"},11505:{name:"Breakout X",hitbox:"Breakout"},11534:{name:"BMW M3 (E30)",hitbox:"Dominus"},11603:{name:"Fennec ZR-F",hitbox:"Octane"},11677:{name:"Chevrolet Corvette ZR1",hitbox:"Breakout"},11736:{name:"Recoil AV",hitbox:"Merc"},11800:{name:"Megastar",hitbox:"Breakout"},11905:{name:"The Mystery Machine",hitbox:"Merc"},11932:{name:"Hearse",hitbox:"Hybrid"},11933:{name:"Porsche 918 Spyder",hitbox:"Breakout"},11941:{name:"Mercedes-AMG GT 63 S",hitbox:"Dominus"},11949:{name:"Pontiac Firebird",hitbox:"Breakout"},11950:{name:"Chevrolet Astro",hitbox:"Merc"},12142:{name:"Homer's Car",hitbox:"Dominus"},12173:{name:"Ferrari F40",hitbox:"Breakout"}},z1=B1;function Aw(n){const e=z1[String(n)];return e?{name:e.name,hitboxType:e.hitbox}:null}function H1(n){if(!n)return null;const e={fov:n.fov,height:n.height,angle:n.angle,distance:n.distance,stiffness:n.stiffness,swivelSpeed:n.swivel_speed};return n.transition_speed!=null&&(e.transitionSpeed=n.transition_speed),e}const V1=2200,G1=!0,$1=!1,W1=.15,X1=10,K1=.1,q1=10,Y1=.1,j1=.15,Z1=10;function Ho(n,e){if(n.length===0)return null;let t=0,i=n.length-1;if(e<=n[0].time)return n[0];if(e>=n[i].time)return n[i];for(;t>1;n[s].time<=e?t=s:i=s-1}return n[t]}class J1{position={x:0,y:0,z:0};rotation={x:0,y:0,z:0,w:1};velocity={x:0,y:0,z:0};angularVelocity={x:0,y:0,z:0};sleeping=!1;visible=!0}class Q1{constructor(e,t,i){this.isBig=e,this.position=t,this.events=i}isAvailable=!0}class eC extends Cw{constructor(e,t,i,s,a,r=null){super(),this.id=e,this.name=t,this.team=i,this.carName=s,this.hitboxType=a,this.cameraSettings=r}position={x:0,y:0,z:0};rotation={x:0,y:0,z:0,w:1};velocity={x:0,y:0,z:0};angularVelocity={x:0,y:0,z:0};sleeping=!1;steer=0;boost=0;isBoosting=!1;isSupersonic=!1;isKickoffReset=!1;isVisible=!0;isBallCam=!0}class Rw extends Cw{constructor(e,t={}){super(),this.raw=e,this.options=t,this._compile()}duration=0;playerList=[];frameTimes=[];rawStartTime=0;ball=new J1;players=new Map;boostPads=new Map;_currentTime=0;_ballTimeline=[];_playerTimelines={};_ballFlags=[];_playerFlags={};_playerCameraEvents={};_teams={};_timelineCompaction=null;_compile(){const e=this.raw.frame_data,t=this.raw.meta,i=e.metadata_frames,s=i[0]?.time??0;this.rawStartTime=s;const a=l=>Math.max(0,l-s);this.duration=i.length?a(i[i.length-1].time):0,this.frameTimes=i.map(l=>a(l.time));const r=new Map;t.team_zero.forEach(l=>r.set(this._idKey(l.remote_id),{info:l,team:0})),t.team_one.forEach(l=>r.set(this._idKey(l.remote_id),{info:l,team:1})),e.ball_data.frames.forEach((l,c)=>{if(l==="Empty"||!("Data"in l))return;const u=this._rbToKeyframe(l.Data.rigid_body,a(i[c]?.time??s),c);u&&this._ballTimeline.push(u)}),e.players.forEach(([l,c])=>{const u=this._idKey(l),d=r.get(u);let h=d?.info.name??null,f=d?.team??0;if(!h){for(const T of c.frames)if(T!=="Empty"&&"Data"in T&&T.Data.player_name){h=T.Data.player_name,T.Data.is_team_0!=null&&(f=T.Data.is_team_0?0:1);break}}h||(h=`Player_${u}`);const p=d?.info,g=p?.car_body_id!=null?Aw(p.car_body_id):null,_=p?.car_body_name??g?.name??"Octane",m=p?.car_hitbox_family??g?.hitboxType??"Octane",v=[],y=[];c.frames.forEach((T,x)=>{const M=a(i[x]?.time??s);if(T==="Empty"||!("Data"in T))return;const C=this._rbToKeyframe(T.Data.rigid_body,M,x);C&&v.push(C);const w=T.Data.input?.steer;y.push({time:M,boost:U1(T.Data.boost_amount??0),isBoosting:!!T.Data.boost_active,present:!0,steer:w==null?0:Math.max(-1,Math.min(1,(w-128)/128))})});const b=H1(p?.camera_settings);this._playerTimelines[h]=v,this._playerFlags[h]=y,this._teams[h]=f,this.playerList.push({id:u,name:h,team:f,carName:_,hitboxType:m,cameraSettings:b}),this.players.set(h,new eC(u,h,f,_,m,b))});const o=new Map;this.playerList.forEach(l=>o.set(l.id,l.name));for(const[l,c]of this.raw.player_camera_events??[]){const u=o.get(this._idKey(l));u&&(this._playerCameraEvents[u]=c.map(d=>({time:a(i[d.frame]?.time??s),ballCam:d.ball_cam_active})))}this._preprocessMotionTimelines(),this._compileBoostPads(),this.seek(0)}_timelineProcessingOptions(){return{motionSmoothing:this.options.motionSmoothing??G1,smoothingBlendFactor:this.options.smoothingBlendFactor??W1,smoothingAnchorInterval:this.options.smoothingAnchorInterval??X1,timelineCompaction:this.options.timelineCompaction??$1,disableFrameFiltering:this.options.disableFrameFiltering??!1}}_preprocessMotionTimelines(){const e=this._timelineProcessingOptions();e.motionSmoothing&&this._applyVelocityBasedPositionCorrection(e),e.timelineCompaction&&this._applyTimelineCompaction(),e.disableFrameFiltering||this._filterInconsistentFrames()}_applyTimelineCompaction(){const e=this._buildTimelineCompaction();!e||e.gaps.length===0&&e.prematchEndTime===null||(this._timelineCompaction=e,this._ballTimeline=this._compactTimeline(this._ballTimeline,e),Object.entries(this._playerTimelines).forEach(([t,i])=>{this._playerTimelines[t]=this._compactTimeline(i,e)}),Object.entries(this._playerFlags).forEach(([t,i])=>{this._playerFlags[t]=this._compactTimeline(i,e)}),this.frameTimes=this.frameTimes.map(t=>this._compactTime(t,e)),this.duration=e.compactedDuration)}_buildTimelineCompaction(){if(this.frameTimes.length===0)return null;const e=this._detectPostGoalTimeGaps(),t=this._detectFirstKickoffGoTime(),i=t==null?null:Vo(t,e),a=e.reduce((r,o)=>r+o.duration,0)+(i??0);return a<=0?null:{gaps:e,prematchEndTime:i,removedDuration:a,compactedDuration:Math.max(0,this.duration-a)}}_detectPostGoalTimeGaps(){const e=[];for(const t of this.raw.goal_events??[]){const i=t.frame;if(!Number.isInteger(i)||i<0||i>=this.frameTimes.length)continue;const s=this.frameTimes[i];for(let a=i+1;a10)break;const l=o-r;if(l>.3){e.push({beforeFrame:a-1,afterFrame:a,beforeTime:r,afterTime:o,duration:l});break}}}return e}_detectFirstKickoffGoTime(){const e=this.raw.frame_data.metadata_frames;let t=!1;for(let s=0;s0&&(t=!0),t&&a===0)return this.frameTimes[s]??null}const i=e.findIndex(s=>s.replicated_game_state_name===54);return i===-1?null:this.frameTimes[i]??null}_compactTimeline(e,t){const i=this._remapReplayGaps(e,t.gaps);return t.prematchEndTime===null?i:this._remapPrematch(i,t.prematchEndTime)}_remapReplayGaps(e,t){if(t.length===0)return e;const i=[];t.forEach((a,r)=>{const o=e.find(l=>l.time>=a.afterTime);o&&i.push({...o,time:Vo(a.afterTime,t.slice(0,r+1))})});const s=e.filter(a=>!gy(a.time,t)).map(a=>({...a,time:Vo(a.time,t)}));for(const a of i){if(s.some(o=>Math.abs(o.time-a.time)<.001))continue;let r=s.findIndex(o=>o.time>a.time);r===-1&&(r=s.length),s.splice(r,0,a)}return s}_remapPrematch(e,t){let i=null;for(const a of e)if(a.timea.time>=t).map(a=>({...a,time:a.time-t}));return i&&(s.length===0||s[0].time>.001)&&s.unshift({...i,time:0}),s}_compactTime(e,t){const i=Vo(e,t.gaps);return t.prematchEndTime===null?i:Math.max(0,i-t.prematchEndTime)}_applyVelocityBasedPositionCorrection(e){const t=i=>{if(i.length<3)return;let s=0;for(;s=i.length-1)return;let a={...i[s].position};for(let r=s+1;rK1){a={...l.position};continue}if(_y(a,l.position)>q1){a={...l.position};continue}const u={x:(o.velocity.x+l.velocity.x)/2,y:(o.velocity.y+l.velocity.y)/2,z:(o.velocity.z+l.velocity.z)/2},d={x:a.x+u.x*c,y:a.y+u.y*c,z:a.z+u.z*c},h=(r-s)%e.smoothingAnchorInterval===0?.5:e.smoothingBlendFactor;a={x:d.x*(1-h)+l.position.x*h,y:d.y*(1-h)+l.position.y*h,z:d.z*(1-h)+l.position.z*h},l.position={...a}}};t(this._ballTimeline),Object.values(this._playerTimelines).forEach(t)}_filterInconsistentFrames(){this._ballTimeline=this._filterInconsistentTimeline(this._ballTimeline),Object.entries(this._playerTimelines).forEach(([e,t])=>{this._playerTimelines[e]=this._filterInconsistentTimeline(t)})}_filterInconsistentTimeline(e){if(e.length<2)return e;const t=[e[0]];let i=0;for(let s=1;s.001){const u=o*c,d=_y(r.position,a.position),h=Math.abs(d-u)/u;if(Number.isFinite(h)&&h>j1)continue}}t.push(a),i=s}return t}_compileBoostPads(){const e=new Map;(this.raw.boost_pad_events??[]).forEach(t=>{const i=t.kind==="Available"?!0:t.kind&&typeof t.kind=="object"&&"PickedUp"in t.kind?!1:null;if(i===null)return;const s=Math.max(0,t.time-this.rawStartTime);if(this._timelineCompaction&&this._isRemovedByTimelineCompaction(s))return;const a=this._timelineCompaction?this._compactTime(s,this._timelineCompaction):s,r=e.get(t.pad_id);r?r.push({time:a,available:i}):e.set(t.pad_id,[{time:a,available:i}])}),(this.raw.boost_pads??[]).forEach(t=>{const i=(t.pad_id?e.get(t.pad_id):void 0)??[];i.sort((s,a)=>s.time-a.time),this.boostPads.set(t.index,new Q1(t.size==="Big",t.position,i))})}_rbToKeyframe(e,t,i){const s=vf(e.location);return s?{time:t,frame:i,position:s,rotation:N1(e.rotation),velocity:vf(e.linear_velocity)??{x:0,y:0,z:0},angularVelocity:vf(e.angular_velocity),sleeping:!!e.sleeping}:null}_isRemovedByTimelineCompaction(e){const t=this._timelineCompaction;if(!t)return!1;if(gy(e,t.gaps))return!0;const i=Vo(e,t.gaps);return t.prematchEndTime!==null&&i=V1}const r=Ho(this._playerFlags[i]??[],e);r&&(s.boost=r.boost,s.isBoosting=r.isBoosting,s.steer=r.steer);const o=Ho(this._playerCameraEvents[i]??[],e);o&&o.ballCam!=null&&(s.isBallCam=o.ballCam);const l=this._playerTimelines[i]??[];s.isVisible=l.length>0&&e>=l[0].time-.001&&e<=l[l.length-1].time+1}for(const i of this.boostPads.values()){if(i.events.length===0)continue;const s=Ho(i.events,e);i.isAvailable=s&&s.time<=e?s.available:!0}}frameIndexAt(e){const t=this.frameTimes;if(t.length===0||e<=t[0])return 0;let i=0,s=t.length-1;if(e>=t[s])return s;for(;i>1;t[a]<=e?i=a:s=a-1}return i}getBall(){return this.ball}getPlayer(e){return this.players.get(e)}getPlayerById(e){for(const t of this.players.values())if(t.id===e)return t}getAllPlayers(){return Array.from(this.players.values())}getPlayerTeams(){return{...this._teams}}getGameTimeMap(){return[]}getCountdownEvents(){return[]}getPlayerStatsTimelines(){return{}}getGameEventTimeline(){return[]}getAdvancedStats(){return null}getEvents(){return[]}getEventsInRange(){return[]}getTextOverlaysAt(){return[]}getGamePhaseAt(){return null}}function my(n){return Math.sqrt(n.x*n.x+n.y*n.y+n.z*n.z)}function _y(n,e){const t=e.x-n.x,i=e.y-n.y,s=e.z-n.z;return Math.sqrt(t*t+i*i+s*s)}function Vo(n,e){let t=0;for(const i of e){if(n=i.afterTime){t+=i.duration;continue}return i.beforeTime-t}return n-t}function gy(n,e){return e.some(t=>n>t.beforeTime&&n>8&255]+Mn[n>>16&255]+Mn[n>>24&255]+"-"+Mn[e&255]+Mn[e>>8&255]+"-"+Mn[e>>16&15|64]+Mn[e>>24&255]+"-"+Mn[t&63|128]+Mn[t>>8&255]+"-"+Mn[t>>16&255]+Mn[t>>24&255]+Mn[i&255]+Mn[i>>8&255]+Mn[i>>16&255]+Mn[i>>24&255]).toLowerCase()}function Ze(n,e,t){return Math.max(e,Math.min(t,n))}function sg(n,e){return(n%e+e)%e}function FC(n,e,t,i,s){return i+(n-e)*(s-i)/(t-e)}function NC(n,e,t){return n!==e?(t-n)/(e-n):0}function Il(n,e,t){return(1-t)*n+t*e}function UC(n,e,t,i){return Il(n,e,1-Math.exp(-t*i))}function BC(n,e=1){return e-Math.abs(sg(n,e*2)-e)}function zC(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*(3-2*n))}function HC(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*n*(n*(n*6-15)+10))}function VC(n,e){return n+Math.floor(Math.random()*(e-n+1))}function GC(n,e){return n+Math.random()*(e-n)}function $C(n){return n*(.5-Math.random())}function WC(n){n!==void 0&&(yy=n);let e=yy+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function XC(n){return n*ir}function KC(n){return n*Co}function qC(n){return(n&n-1)===0&&n!==0}function YC(n){return Math.pow(2,Math.ceil(Math.log(n)/Math.LN2))}function jC(n){return Math.pow(2,Math.floor(Math.log(n)/Math.LN2))}function ZC(n,e,t,i,s){const a=Math.cos,r=Math.sin,o=a(t/2),l=r(t/2),c=a((e+i)/2),u=r((e+i)/2),d=a((e-i)/2),h=r((e-i)/2),f=a((i-e)/2),p=r((i-e)/2);switch(s){case"XYX":n.set(o*u,l*d,l*h,o*c);break;case"YZY":n.set(l*h,o*u,l*d,o*c);break;case"ZXZ":n.set(l*d,l*h,o*u,o*c);break;case"XZX":n.set(o*u,l*p,l*f,o*c);break;case"YXY":n.set(l*f,o*u,l*p,o*c);break;case"ZYZ":n.set(l*p,l*f,o*u,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+s)}}function zn(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return n/4294967295;case Uint16Array:return n/65535;case Uint8Array:return n/255;case Int32Array:return Math.max(n/2147483647,-1);case Int16Array:return Math.max(n/32767,-1);case Int8Array:return Math.max(n/127,-1);default:throw new Error("Invalid component type.")}}function ut(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return Math.round(n*4294967295);case Uint16Array:return Math.round(n*65535);case Uint8Array:return Math.round(n*255);case Int32Array:return Math.round(n*2147483647);case Int16Array:return Math.round(n*32767);case Int8Array:return Math.round(n*127);default:throw new Error("Invalid component type.")}}const vt={DEG2RAD:ir,RAD2DEG:Co,generateUUID:pi,clamp:Ze,euclideanModulo:sg,mapLinear:FC,inverseLerp:NC,lerp:Il,damp:UC,pingpong:BC,smoothstep:zC,smootherstep:HC,randInt:VC,randFloat:GC,randFloatSpread:$C,seededRandom:WC,degToRad:XC,radToDeg:KC,isPowerOfTwo:qC,ceilPowerOfTwo:YC,floorPowerOfTwo:jC,setQuaternionFromProperEuler:ZC,normalize:ut,denormalize:zn};class te{constructor(e=0,t=0){te.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,i=this.y,s=e.elements;return this.x=s[0]*t+s[3]*i+s[6],this.y=s[1]*t+s[4]*i+s[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Ze(this.x,e.x,t.x),this.y=Ze(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Ze(this.x,e,t),this.y=Ze(this.y,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Ze(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Ze(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),s=Math.sin(t),a=this.x-e.x,r=this.y-e.y;return this.x=a*i-r*s+e.x,this.y=a*s+r*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class dt{constructor(e=0,t=0,i=0,s=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=s}static slerpFlat(e,t,i,s,a,r,o){let l=i[s+0],c=i[s+1],u=i[s+2],d=i[s+3];const h=a[r+0],f=a[r+1],p=a[r+2],g=a[r+3];if(o===0){e[t+0]=l,e[t+1]=c,e[t+2]=u,e[t+3]=d;return}if(o===1){e[t+0]=h,e[t+1]=f,e[t+2]=p,e[t+3]=g;return}if(d!==g||l!==h||c!==f||u!==p){let _=1-o;const m=l*h+c*f+u*p+d*g,v=m>=0?1:-1,y=1-m*m;if(y>Number.EPSILON){const T=Math.sqrt(y),x=Math.atan2(T,m*v);_=Math.sin(_*x)/T,o=Math.sin(o*x)/T}const b=o*v;if(l=l*_+h*b,c=c*_+f*b,u=u*_+p*b,d=d*_+g*b,_===1-o){const T=1/Math.sqrt(l*l+c*c+u*u+d*d);l*=T,c*=T,u*=T,d*=T}}e[t]=l,e[t+1]=c,e[t+2]=u,e[t+3]=d}static multiplyQuaternionsFlat(e,t,i,s,a,r){const o=i[s],l=i[s+1],c=i[s+2],u=i[s+3],d=a[r],h=a[r+1],f=a[r+2],p=a[r+3];return e[t]=o*p+u*d+l*f-c*h,e[t+1]=l*p+u*h+c*d-o*f,e[t+2]=c*p+u*f+o*h-l*d,e[t+3]=u*p-o*d-l*h-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,i,s){return this._x=e,this._y=t,this._z=i,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const i=e._x,s=e._y,a=e._z,r=e._order,o=Math.cos,l=Math.sin,c=o(i/2),u=o(s/2),d=o(a/2),h=l(i/2),f=l(s/2),p=l(a/2);switch(r){case"XYZ":this._x=h*u*d+c*f*p,this._y=c*f*d-h*u*p,this._z=c*u*p+h*f*d,this._w=c*u*d-h*f*p;break;case"YXZ":this._x=h*u*d+c*f*p,this._y=c*f*d-h*u*p,this._z=c*u*p-h*f*d,this._w=c*u*d+h*f*p;break;case"ZXY":this._x=h*u*d-c*f*p,this._y=c*f*d+h*u*p,this._z=c*u*p+h*f*d,this._w=c*u*d-h*f*p;break;case"ZYX":this._x=h*u*d-c*f*p,this._y=c*f*d+h*u*p,this._z=c*u*p-h*f*d,this._w=c*u*d+h*f*p;break;case"YZX":this._x=h*u*d+c*f*p,this._y=c*f*d+h*u*p,this._z=c*u*p-h*f*d,this._w=c*u*d-h*f*p;break;case"XZY":this._x=h*u*d-c*f*p,this._y=c*f*d-h*u*p,this._z=c*u*p+h*f*d,this._w=c*u*d+h*f*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+r)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const i=t/2,s=Math.sin(i);return this._x=e.x*s,this._y=e.y*s,this._z=e.z*s,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],s=t[4],a=t[8],r=t[1],o=t[5],l=t[9],c=t[2],u=t[6],d=t[10],h=i+o+d;if(h>0){const f=.5/Math.sqrt(h+1);this._w=.25/f,this._x=(u-l)*f,this._y=(a-c)*f,this._z=(r-s)*f}else if(i>o&&i>d){const f=2*Math.sqrt(1+i-o-d);this._w=(u-l)/f,this._x=.25*f,this._y=(s+r)/f,this._z=(a+c)/f}else if(o>d){const f=2*Math.sqrt(1+o-i-d);this._w=(a-c)/f,this._x=(s+r)/f,this._y=.25*f,this._z=(l+u)/f}else{const f=2*Math.sqrt(1+d-i-o);this._w=(r-s)/f,this._x=(a+c)/f,this._y=(l+u)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<1e-8?(i=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Ze(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(i===0)return this;const s=Math.min(1,t/i);return this.slerp(e,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const i=e._x,s=e._y,a=e._z,r=e._w,o=t._x,l=t._y,c=t._z,u=t._w;return this._x=i*u+r*o+s*c-a*l,this._y=s*u+r*l+a*o-i*c,this._z=a*u+r*c+i*l-s*o,this._w=r*u-i*o-s*l-a*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const i=this._x,s=this._y,a=this._z,r=this._w;let o=r*e._w+i*e._x+s*e._y+a*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=r,this._x=i,this._y=s,this._z=a,this;const l=1-o*o;if(l<=Number.EPSILON){const f=1-t;return this._w=f*r+t*this._w,this._x=f*i+t*this._x,this._y=f*s+t*this._y,this._z=f*a+t*this._z,this.normalize(),this}const c=Math.sqrt(l),u=Math.atan2(c,o),d=Math.sin((1-t)*u)/c,h=Math.sin(t*u)/c;return this._w=r*d+this._w*h,this._x=i*d+this._x*h,this._y=s*d+this._y*h,this._z=a*d+this._z*h,this._onChangeCallback(),this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),s=Math.sqrt(1-i),a=Math.sqrt(i);return this.set(s*Math.sin(e),s*Math.cos(e),a*Math.sin(t),a*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class S{constructor(e=0,t=0,i=0){S.prototype.isVector3=!0,this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(vy.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(vy.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,s=this.z,a=e.elements;return this.x=a[0]*t+a[3]*i+a[6]*s,this.y=a[1]*t+a[4]*i+a[7]*s,this.z=a[2]*t+a[5]*i+a[8]*s,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,s=this.z,a=e.elements,r=1/(a[3]*t+a[7]*i+a[11]*s+a[15]);return this.x=(a[0]*t+a[4]*i+a[8]*s+a[12])*r,this.y=(a[1]*t+a[5]*i+a[9]*s+a[13])*r,this.z=(a[2]*t+a[6]*i+a[10]*s+a[14])*r,this}applyQuaternion(e){const t=this.x,i=this.y,s=this.z,a=e.x,r=e.y,o=e.z,l=e.w,c=2*(r*s-o*i),u=2*(o*t-a*s),d=2*(a*i-r*t);return this.x=t+l*c+r*d-o*u,this.y=i+l*u+o*c-a*d,this.z=s+l*d+a*u-r*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,i=this.y,s=this.z,a=e.elements;return this.x=a[0]*t+a[4]*i+a[8]*s,this.y=a[1]*t+a[5]*i+a[9]*s,this.z=a[2]*t+a[6]*i+a[10]*s,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Ze(this.x,e.x,t.x),this.y=Ze(this.y,e.y,t.y),this.z=Ze(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Ze(this.x,e,t),this.y=Ze(this.y,e,t),this.z=Ze(this.z,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Ze(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const i=e.x,s=e.y,a=e.z,r=t.x,o=t.y,l=t.z;return this.x=s*l-a*o,this.y=a*r-i*l,this.z=i*o-s*r,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return bf.copy(this).projectOnVector(e),this.sub(bf)}reflect(e){return this.sub(bf.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Ze(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,s=this.z-e.z;return t*t+i*i+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){const s=Math.sin(t)*e;return this.x=s*Math.sin(i),this.y=Math.cos(t)*e,this.z=s*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),s=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=s,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(e),this.y=t,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const bf=new S,vy=new dt;class at{constructor(e,t,i,s,a,r,o,l,c){at.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,s,a,r,o,l,c)}set(e,t,i,s,a,r,o,l,c){const u=this.elements;return u[0]=e,u[1]=s,u[2]=o,u[3]=t,u[4]=a,u[5]=l,u[6]=i,u[7]=r,u[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,s=t.elements,a=this.elements,r=i[0],o=i[3],l=i[6],c=i[1],u=i[4],d=i[7],h=i[2],f=i[5],p=i[8],g=s[0],_=s[3],m=s[6],v=s[1],y=s[4],b=s[7],T=s[2],x=s[5],M=s[8];return a[0]=r*g+o*v+l*T,a[3]=r*_+o*y+l*x,a[6]=r*m+o*b+l*M,a[1]=c*g+u*v+d*T,a[4]=c*_+u*y+d*x,a[7]=c*m+u*b+d*M,a[2]=h*g+f*v+p*T,a[5]=h*_+f*y+p*x,a[8]=h*m+f*b+p*M,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[1],s=e[2],a=e[3],r=e[4],o=e[5],l=e[6],c=e[7],u=e[8];return t*r*u-t*o*c-i*a*u+i*o*l+s*a*c-s*r*l}invert(){const e=this.elements,t=e[0],i=e[1],s=e[2],a=e[3],r=e[4],o=e[5],l=e[6],c=e[7],u=e[8],d=u*r-o*c,h=o*l-u*a,f=c*a-r*l,p=t*d+i*h+s*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);const g=1/p;return e[0]=d*g,e[1]=(s*c-u*i)*g,e[2]=(o*i-s*r)*g,e[3]=h*g,e[4]=(u*t-s*l)*g,e[5]=(s*a-o*t)*g,e[6]=f*g,e[7]=(i*l-c*t)*g,e[8]=(r*t-i*a)*g,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,s,a,r,o){const l=Math.cos(a),c=Math.sin(a);return this.set(i*l,i*c,-i*(l*r+c*o)+r+e,-s*c,s*l,-s*(-c*r+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(xf.makeScale(e,t)),this}rotate(e){return this.premultiply(xf.makeRotation(-e)),this}translate(e,t){return this.premultiply(xf.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,i=e.elements;for(let s=0;s<9;s++)if(t[s]!==i[s])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const xf=new at;function gS(n){for(let e=n.length-1;e>=0;--e)if(n[e]>=65535)return!0;return!1}const JC={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function Zr(n,e){return new JC[n](e)}function Wl(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}function yS(){const n=Wl("canvas");return n.style.display="block",n}const by={};function Xl(n){n in by||(by[n]=!0,console.warn(n))}function QC(n,e,t){return new Promise(function(i,s){function a(){switch(n.clientWaitSync(e,n.SYNC_FLUSH_COMMANDS_BIT,0)){case n.WAIT_FAILED:s();break;case n.TIMEOUT_EXPIRED:setTimeout(a,t);break;default:i()}}setTimeout(a,t)})}const xy=new at().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),wy=new at().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function eA(){const n={enabled:!0,workingColorSpace:xn,spaces:{},convert:function(s,a,r){return this.enabled===!1||a===r||!a||!r||(this.spaces[a].transfer===Pt&&(s.r=Fs(s.r),s.g=Fs(s.g),s.b=Fs(s.b)),this.spaces[a].primaries!==this.spaces[r].primaries&&(s.applyMatrix3(this.spaces[a].toXYZ),s.applyMatrix3(this.spaces[r].fromXYZ)),this.spaces[r].transfer===Pt&&(s.r=io(s.r),s.g=io(s.g),s.b=io(s.b))),s},workingToColorSpace:function(s,a){return this.convert(s,this.workingColorSpace,a)},colorSpaceToWorking:function(s,a){return this.convert(s,a,this.workingColorSpace)},getPrimaries:function(s){return this.spaces[s].primaries},getTransfer:function(s){return s===Ls?Gl:this.spaces[s].transfer},getToneMappingMode:function(s){return this.spaces[s].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(s,a=this.workingColorSpace){return s.fromArray(this.spaces[a].luminanceCoefficients)},define:function(s){Object.assign(this.spaces,s)},_getMatrix:function(s,a,r){return s.copy(this.spaces[a].toXYZ).multiply(this.spaces[r].fromXYZ)},_getDrawingBufferColorSpace:function(s){return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(s=this.workingColorSpace){return this.spaces[s].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(s,a){return Xl("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),n.workingToColorSpace(s,a)},toWorkingColorSpace:function(s,a){return Xl("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),n.colorSpaceToWorking(s,a)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],i=[.3127,.329];return n.define({[xn]:{primaries:e,whitePoint:i,transfer:Gl,toXYZ:xy,fromXYZ:wy,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:gt},outputColorSpaceConfig:{drawingBufferColorSpace:gt}},[gt]:{primaries:e,whitePoint:i,transfer:Pt,toXYZ:xy,fromXYZ:wy,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:gt}}}),n}const rt=eA();function Fs(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function io(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}let vr;class vS{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{vr===void 0&&(vr=Wl("canvas")),vr.width=e.width,vr.height=e.height;const s=vr.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),i=vr}return i.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=Wl("canvas");t.width=e.width,t.height=e.height;const i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const s=i.getImageData(0,0,e.width,e.height),a=s.data;for(let r=0;r1),this.pmremVersion=0}get width(){return this.source.getSize(Sf).x}get height(){return this.source.getSize(Sf).y}get depth(){return this.source.getSize(Sf).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const i=e[t];if(i===void 0){console.warn(`THREE.Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){console.warn(`THREE.Texture.setValues(): property '${t}' does not exist.`);continue}s&&i&&s.isVector2&&i.isVector2||s&&i&&s.isVector3&&i.isVector3||s&&i&&s.isMatrix3&&i.isMatrix3?s.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),t||(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==xh)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case ps:e.x=e.x-Math.floor(e.x);break;case Hn:e.x=e.x<0?0:1;break;case bo:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case ps:e.y=e.y-Math.floor(e.y);break;case Hn:e.y=e.y<0?0:1;break;case bo:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}Bt.DEFAULT_IMAGE=null;Bt.DEFAULT_MAPPING=xh;Bt.DEFAULT_ANISOTROPY=1;class qe{constructor(e=0,t=0,i=0,s=1){qe.prototype.isVector4=!0,this.x=e,this.y=t,this.z=i,this.w=s}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,s=this.z,a=this.w,r=e.elements;return this.x=r[0]*t+r[4]*i+r[8]*s+r[12]*a,this.y=r[1]*t+r[5]*i+r[9]*s+r[13]*a,this.z=r[2]*t+r[6]*i+r[10]*s+r[14]*a,this.w=r[3]*t+r[7]*i+r[11]*s+r[15]*a,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,i,s,a;const l=e.elements,c=l[0],u=l[4],d=l[8],h=l[1],f=l[5],p=l[9],g=l[2],_=l[6],m=l[10];if(Math.abs(u-h)<.01&&Math.abs(d-g)<.01&&Math.abs(p-_)<.01){if(Math.abs(u+h)<.1&&Math.abs(d+g)<.1&&Math.abs(p+_)<.1&&Math.abs(c+f+m-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const y=(c+1)/2,b=(f+1)/2,T=(m+1)/2,x=(u+h)/4,M=(d+g)/4,C=(p+_)/4;return y>b&&y>T?y<.01?(i=0,s=.707106781,a=.707106781):(i=Math.sqrt(y),s=x/i,a=M/i):b>T?b<.01?(i=.707106781,s=0,a=.707106781):(s=Math.sqrt(b),i=x/s,a=C/s):T<.01?(i=.707106781,s=.707106781,a=0):(a=Math.sqrt(T),i=M/a,s=C/a),this.set(i,s,a,t),this}let v=Math.sqrt((_-p)*(_-p)+(d-g)*(d-g)+(h-u)*(h-u));return Math.abs(v)<.001&&(v=1),this.x=(_-p)/v,this.y=(d-g)/v,this.z=(h-u)/v,this.w=Math.acos((c+f+m-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Ze(this.x,e.x,t.x),this.y=Ze(this.y,e.y,t.y),this.z=Ze(this.z,e.z,t.z),this.w=Ze(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Ze(this.x,e,t),this.y=Ze(this.y,e,t),this.z=Ze(this.z,e,t),this.w=Ze(this.w,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Ze(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class ag extends gs{constructor(e=1,t=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Vt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},i),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=i.depth,this.scissor=new qe(0,0,e,t),this.scissorTest=!1,this.viewport=new qe(0,0,e,t);const s={width:e,height:t,depth:i.depth},a=new Bt(s);this.textures=[];const r=i.count;for(let o=0;o1;this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,i=e.textures.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Li),Li.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Go),wc.subVectors(this.max,Go),br.subVectors(e.a,Go),xr.subVectors(e.b,Go),wr.subVectors(e.c,Go),Vs.subVectors(xr,br),Gs.subVectors(wr,xr),ya.subVectors(br,wr);let t=[0,-Vs.z,Vs.y,0,-Gs.z,Gs.y,0,-ya.z,ya.y,Vs.z,0,-Vs.x,Gs.z,0,-Gs.x,ya.z,0,-ya.x,-Vs.y,Vs.x,0,-Gs.y,Gs.x,0,-ya.y,ya.x,0];return!Tf(t,br,xr,wr,wc)||(t=[1,0,0,0,1,0,0,0,1],!Tf(t,br,xr,wr,wc))?!1:(Sc.crossVectors(Vs,Gs),t=[Sc.x,Sc.y,Sc.z],Tf(t,br,xr,wr,wc))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Li).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Li).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(vs[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),vs[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),vs[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),vs[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),vs[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),vs[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),vs[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),vs[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(vs),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const vs=[new S,new S,new S,new S,new S,new S,new S,new S],Li=new S,xc=new vn,br=new S,xr=new S,wr=new S,Vs=new S,Gs=new S,ya=new S,Go=new S,wc=new S,Sc=new S,va=new S;function Tf(n,e,t,i,s){for(let a=0,r=n.length-3;a<=r;a+=3){va.fromArray(n,a);const o=s.x*Math.abs(va.x)+s.y*Math.abs(va.y)+s.z*Math.abs(va.z),l=e.dot(va),c=t.dot(va),u=i.dot(va);if(Math.max(-Math.max(l,c,u),Math.min(l,c,u))>o)return!1}return!0}const aA=new vn,$o=new S,Mf=new S;class bn{constructor(e=new S,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const i=this.center;t!==void 0?i.copy(t):aA.setFromPoints(e).getCenter(i);let s=0;for(let a=0,r=e.length;athis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;$o.subVectors(e,this.center);const t=$o.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),s=(i-this.radius)*.5;this.center.addScaledVector($o,s/i),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(Mf.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint($o.copy(e.center).add(Mf)),this.expandByPoint($o.copy(e.center).sub(Mf))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}const bs=new S,Ef=new S,Tc=new S,$s=new S,Cf=new S,Mc=new S,Af=new S;class pr{constructor(e=new S,t=new S(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,bs)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=bs.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(bs.copy(this.origin).addScaledVector(this.direction,t),bs.distanceToSquared(e))}distanceSqToSegment(e,t,i,s){Ef.copy(e).add(t).multiplyScalar(.5),Tc.copy(t).sub(e).normalize(),$s.copy(this.origin).sub(Ef);const a=e.distanceTo(t)*.5,r=-this.direction.dot(Tc),o=$s.dot(this.direction),l=-$s.dot(Tc),c=$s.lengthSq(),u=Math.abs(1-r*r);let d,h,f,p;if(u>0)if(d=r*l-o,h=r*o-l,p=a*u,d>=0)if(h>=-p)if(h<=p){const g=1/u;d*=g,h*=g,f=d*(d+r*h+2*o)+h*(r*d+h+2*l)+c}else h=a,d=Math.max(0,-(r*h+o)),f=-d*d+h*(h+2*l)+c;else h=-a,d=Math.max(0,-(r*h+o)),f=-d*d+h*(h+2*l)+c;else h<=-p?(d=Math.max(0,-(-r*a+o)),h=d>0?-a:Math.min(Math.max(-a,-l),a),f=-d*d+h*(h+2*l)+c):h<=p?(d=0,h=Math.min(Math.max(-a,-l),a),f=h*(h+2*l)+c):(d=Math.max(0,-(r*a+o)),h=d>0?a:Math.min(Math.max(-a,-l),a),f=-d*d+h*(h+2*l)+c);else h=r>0?-a:a,d=Math.max(0,-(r*h+o)),f=-d*d+h*(h+2*l)+c;return i&&i.copy(this.origin).addScaledVector(this.direction,d),s&&s.copy(Ef).addScaledVector(Tc,h),f}intersectSphere(e,t){bs.subVectors(e.center,this.origin);const i=bs.dot(this.direction),s=bs.dot(bs)-i*i,a=e.radius*e.radius;if(s>a)return null;const r=Math.sqrt(a-s),o=i-r,l=i+r;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,s,a,r,o,l;const c=1/this.direction.x,u=1/this.direction.y,d=1/this.direction.z,h=this.origin;return c>=0?(i=(e.min.x-h.x)*c,s=(e.max.x-h.x)*c):(i=(e.max.x-h.x)*c,s=(e.min.x-h.x)*c),u>=0?(a=(e.min.y-h.y)*u,r=(e.max.y-h.y)*u):(a=(e.max.y-h.y)*u,r=(e.min.y-h.y)*u),i>r||a>s||((a>i||isNaN(i))&&(i=a),(r=0?(o=(e.min.z-h.z)*d,l=(e.max.z-h.z)*d):(o=(e.max.z-h.z)*d,l=(e.min.z-h.z)*d),i>l||o>s)||((o>i||i!==i)&&(i=o),(l=0?i:s,t)}intersectsBox(e){return this.intersectBox(e,bs)!==null}intersectTriangle(e,t,i,s,a){Cf.subVectors(t,e),Mc.subVectors(i,e),Af.crossVectors(Cf,Mc);let r=this.direction.dot(Af),o;if(r>0){if(s)return null;o=1}else if(r<0)o=-1,r=-r;else return null;$s.subVectors(this.origin,e);const l=o*this.direction.dot(Mc.crossVectors($s,Mc));if(l<0)return null;const c=o*this.direction.dot(Cf.cross($s));if(c<0||l+c>r)return null;const u=-o*$s.dot(Af);return u<0?null:this.at(u/r,a)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Me{constructor(e,t,i,s,a,r,o,l,c,u,d,h,f,p,g,_){Me.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,i,s,a,r,o,l,c,u,d,h,f,p,g,_)}set(e,t,i,s,a,r,o,l,c,u,d,h,f,p,g,_){const m=this.elements;return m[0]=e,m[4]=t,m[8]=i,m[12]=s,m[1]=a,m[5]=r,m[9]=o,m[13]=l,m[2]=c,m[6]=u,m[10]=d,m[14]=h,m[3]=f,m[7]=p,m[11]=g,m[15]=_,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Me().fromArray(this.elements)}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(e){const t=this.elements,i=e.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,i){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(e,t,i){return this.set(e.x,t.x,i.x,0,e.y,t.y,i.y,0,e.z,t.z,i.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,i=e.elements,s=1/Sr.setFromMatrixColumn(e,0).length(),a=1/Sr.setFromMatrixColumn(e,1).length(),r=1/Sr.setFromMatrixColumn(e,2).length();return t[0]=i[0]*s,t[1]=i[1]*s,t[2]=i[2]*s,t[3]=0,t[4]=i[4]*a,t[5]=i[5]*a,t[6]=i[6]*a,t[7]=0,t[8]=i[8]*r,t[9]=i[9]*r,t[10]=i[10]*r,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,i=e.x,s=e.y,a=e.z,r=Math.cos(i),o=Math.sin(i),l=Math.cos(s),c=Math.sin(s),u=Math.cos(a),d=Math.sin(a);if(e.order==="XYZ"){const h=r*u,f=r*d,p=o*u,g=o*d;t[0]=l*u,t[4]=-l*d,t[8]=c,t[1]=f+p*c,t[5]=h-g*c,t[9]=-o*l,t[2]=g-h*c,t[6]=p+f*c,t[10]=r*l}else if(e.order==="YXZ"){const h=l*u,f=l*d,p=c*u,g=c*d;t[0]=h+g*o,t[4]=p*o-f,t[8]=r*c,t[1]=r*d,t[5]=r*u,t[9]=-o,t[2]=f*o-p,t[6]=g+h*o,t[10]=r*l}else if(e.order==="ZXY"){const h=l*u,f=l*d,p=c*u,g=c*d;t[0]=h-g*o,t[4]=-r*d,t[8]=p+f*o,t[1]=f+p*o,t[5]=r*u,t[9]=g-h*o,t[2]=-r*c,t[6]=o,t[10]=r*l}else if(e.order==="ZYX"){const h=r*u,f=r*d,p=o*u,g=o*d;t[0]=l*u,t[4]=p*c-f,t[8]=h*c+g,t[1]=l*d,t[5]=g*c+h,t[9]=f*c-p,t[2]=-c,t[6]=o*l,t[10]=r*l}else if(e.order==="YZX"){const h=r*l,f=r*c,p=o*l,g=o*c;t[0]=l*u,t[4]=g-h*d,t[8]=p*d+f,t[1]=d,t[5]=r*u,t[9]=-o*u,t[2]=-c*u,t[6]=f*d+p,t[10]=h-g*d}else if(e.order==="XZY"){const h=r*l,f=r*c,p=o*l,g=o*c;t[0]=l*u,t[4]=-d,t[8]=c*u,t[1]=h*d+g,t[5]=r*u,t[9]=f*d-p,t[2]=p*d-f,t[6]=o*u,t[10]=g*d+h}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(rA,e,oA)}lookAt(e,t,i){const s=this.elements;return li.subVectors(e,t),li.lengthSq()===0&&(li.z=1),li.normalize(),Ws.crossVectors(i,li),Ws.lengthSq()===0&&(Math.abs(i.z)===1?li.x+=1e-4:li.z+=1e-4,li.normalize(),Ws.crossVectors(i,li)),Ws.normalize(),Ec.crossVectors(li,Ws),s[0]=Ws.x,s[4]=Ec.x,s[8]=li.x,s[1]=Ws.y,s[5]=Ec.y,s[9]=li.y,s[2]=Ws.z,s[6]=Ec.z,s[10]=li.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,s=t.elements,a=this.elements,r=i[0],o=i[4],l=i[8],c=i[12],u=i[1],d=i[5],h=i[9],f=i[13],p=i[2],g=i[6],_=i[10],m=i[14],v=i[3],y=i[7],b=i[11],T=i[15],x=s[0],M=s[4],C=s[8],w=s[12],E=s[1],R=s[5],k=s[9],O=s[13],D=s[2],U=s[6],F=s[10],W=s[14],H=s[3],ne=s[7],oe=s[11],pe=s[15];return a[0]=r*x+o*E+l*D+c*H,a[4]=r*M+o*R+l*U+c*ne,a[8]=r*C+o*k+l*F+c*oe,a[12]=r*w+o*O+l*W+c*pe,a[1]=u*x+d*E+h*D+f*H,a[5]=u*M+d*R+h*U+f*ne,a[9]=u*C+d*k+h*F+f*oe,a[13]=u*w+d*O+h*W+f*pe,a[2]=p*x+g*E+_*D+m*H,a[6]=p*M+g*R+_*U+m*ne,a[10]=p*C+g*k+_*F+m*oe,a[14]=p*w+g*O+_*W+m*pe,a[3]=v*x+y*E+b*D+T*H,a[7]=v*M+y*R+b*U+T*ne,a[11]=v*C+y*k+b*F+T*oe,a[15]=v*w+y*O+b*W+T*pe,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[4],s=e[8],a=e[12],r=e[1],o=e[5],l=e[9],c=e[13],u=e[2],d=e[6],h=e[10],f=e[14],p=e[3],g=e[7],_=e[11],m=e[15];return p*(+a*l*d-s*c*d-a*o*h+i*c*h+s*o*f-i*l*f)+g*(+t*l*f-t*c*h+a*r*h-s*r*f+s*c*u-a*l*u)+_*(+t*c*d-t*o*f-a*r*d+i*r*f+a*o*u-i*c*u)+m*(-s*o*u-t*l*d+t*o*h+s*r*d-i*r*h+i*l*u)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,i){const s=this.elements;return e.isVector3?(s[12]=e.x,s[13]=e.y,s[14]=e.z):(s[12]=e,s[13]=t,s[14]=i),this}invert(){const e=this.elements,t=e[0],i=e[1],s=e[2],a=e[3],r=e[4],o=e[5],l=e[6],c=e[7],u=e[8],d=e[9],h=e[10],f=e[11],p=e[12],g=e[13],_=e[14],m=e[15],v=d*_*c-g*h*c+g*l*f-o*_*f-d*l*m+o*h*m,y=p*h*c-u*_*c-p*l*f+r*_*f+u*l*m-r*h*m,b=u*g*c-p*d*c+p*o*f-r*g*f-u*o*m+r*d*m,T=p*d*l-u*g*l-p*o*h+r*g*h+u*o*_-r*d*_,x=t*v+i*y+s*b+a*T;if(x===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const M=1/x;return e[0]=v*M,e[1]=(g*h*a-d*_*a-g*s*f+i*_*f+d*s*m-i*h*m)*M,e[2]=(o*_*a-g*l*a+g*s*c-i*_*c-o*s*m+i*l*m)*M,e[3]=(d*l*a-o*h*a-d*s*c+i*h*c+o*s*f-i*l*f)*M,e[4]=y*M,e[5]=(u*_*a-p*h*a+p*s*f-t*_*f-u*s*m+t*h*m)*M,e[6]=(p*l*a-r*_*a-p*s*c+t*_*c+r*s*m-t*l*m)*M,e[7]=(r*h*a-u*l*a+u*s*c-t*h*c-r*s*f+t*l*f)*M,e[8]=b*M,e[9]=(p*d*a-u*g*a-p*i*f+t*g*f+u*i*m-t*d*m)*M,e[10]=(r*g*a-p*o*a+p*i*c-t*g*c-r*i*m+t*o*m)*M,e[11]=(u*o*a-r*d*a-u*i*c+t*d*c+r*i*f-t*o*f)*M,e[12]=T*M,e[13]=(u*g*s-p*d*s+p*i*h-t*g*h-u*i*_+t*d*_)*M,e[14]=(p*o*s-r*g*s-p*i*l+t*g*l+r*i*_-t*o*_)*M,e[15]=(r*d*s-u*o*s+u*i*l-t*d*l-r*i*h+t*o*h)*M,this}scale(e){const t=this.elements,i=e.x,s=e.y,a=e.z;return t[0]*=i,t[4]*=s,t[8]*=a,t[1]*=i,t[5]*=s,t[9]*=a,t[2]*=i,t[6]*=s,t[10]*=a,t[3]*=i,t[7]*=s,t[11]*=a,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],s=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,s))}makeTranslation(e,t,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const i=Math.cos(t),s=Math.sin(t),a=1-i,r=e.x,o=e.y,l=e.z,c=a*r,u=a*o;return this.set(c*r+i,c*o-s*l,c*l+s*o,0,c*o+s*l,u*o+i,u*l-s*r,0,c*l-s*o,u*l+s*r,a*l*l+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,s,a,r){return this.set(1,i,a,0,e,1,r,0,t,s,1,0,0,0,0,1),this}compose(e,t,i){const s=this.elements,a=t._x,r=t._y,o=t._z,l=t._w,c=a+a,u=r+r,d=o+o,h=a*c,f=a*u,p=a*d,g=r*u,_=r*d,m=o*d,v=l*c,y=l*u,b=l*d,T=i.x,x=i.y,M=i.z;return s[0]=(1-(g+m))*T,s[1]=(f+b)*T,s[2]=(p-y)*T,s[3]=0,s[4]=(f-b)*x,s[5]=(1-(h+m))*x,s[6]=(_+v)*x,s[7]=0,s[8]=(p+y)*M,s[9]=(_-v)*M,s[10]=(1-(h+g))*M,s[11]=0,s[12]=e.x,s[13]=e.y,s[14]=e.z,s[15]=1,this}decompose(e,t,i){const s=this.elements;let a=Sr.set(s[0],s[1],s[2]).length();const r=Sr.set(s[4],s[5],s[6]).length(),o=Sr.set(s[8],s[9],s[10]).length();this.determinant()<0&&(a=-a),e.x=s[12],e.y=s[13],e.z=s[14],ki.copy(this);const c=1/a,u=1/r,d=1/o;return ki.elements[0]*=c,ki.elements[1]*=c,ki.elements[2]*=c,ki.elements[4]*=u,ki.elements[5]*=u,ki.elements[6]*=u,ki.elements[8]*=d,ki.elements[9]*=d,ki.elements[10]*=d,t.setFromRotationMatrix(ki),i.x=a,i.y=r,i.z=o,this}makePerspective(e,t,i,s,a,r,o=hi,l=!1){const c=this.elements,u=2*a/(t-e),d=2*a/(i-s),h=(t+e)/(t-e),f=(i+s)/(i-s);let p,g;if(l)p=a/(r-a),g=r*a/(r-a);else if(o===hi)p=-(r+a)/(r-a),g=-2*r*a/(r-a);else if(o===Eo)p=-r/(r-a),g=-r*a/(r-a);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return c[0]=u,c[4]=0,c[8]=h,c[12]=0,c[1]=0,c[5]=d,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=g,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,i,s,a,r,o=hi,l=!1){const c=this.elements,u=2/(t-e),d=2/(i-s),h=-(t+e)/(t-e),f=-(i+s)/(i-s);let p,g;if(l)p=1/(r-a),g=r/(r-a);else if(o===hi)p=-2/(r-a),g=-(r+a)/(r-a);else if(o===Eo)p=-1/(r-a),g=-a/(r-a);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return c[0]=u,c[4]=0,c[8]=0,c[12]=h,c[1]=0,c[5]=d,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=p,c[14]=g,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const t=this.elements,i=e.elements;for(let s=0;s<16;s++)if(t[s]!==i[s])return!1;return!0}fromArray(e,t=0){for(let i=0;i<16;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],e}}const Sr=new S,ki=new Me,rA=new S(0,0,0),oA=new S(1,1,1),Ws=new S,Ec=new S,li=new S,Sy=new Me,Ty=new dt;class an{constructor(e=0,t=0,i=0,s=an.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=s}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,i,s=this._order){return this._x=e,this._y=t,this._z=i,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,i=!0){const s=e.elements,a=s[0],r=s[4],o=s[8],l=s[1],c=s[5],u=s[9],d=s[2],h=s[6],f=s[10];switch(t){case"XYZ":this._y=Math.asin(Ze(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,f),this._z=Math.atan2(-r,a)):(this._x=Math.atan2(h,c),this._z=0);break;case"YXZ":this._x=Math.asin(-Ze(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-d,a),this._z=0);break;case"ZXY":this._x=Math.asin(Ze(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-d,f),this._z=Math.atan2(-r,c)):(this._y=0,this._z=Math.atan2(l,a));break;case"ZYX":this._y=Math.asin(-Ze(d,-1,1)),Math.abs(d)<.9999999?(this._x=Math.atan2(h,f),this._z=Math.atan2(l,a)):(this._x=0,this._z=Math.atan2(-r,c));break;case"YZX":this._z=Math.asin(Ze(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-u,c),this._y=Math.atan2(-d,a)):(this._x=0,this._y=Math.atan2(o,f));break;case"XZY":this._z=Math.asin(-Ze(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(h,c),this._y=Math.atan2(o,a)):(this._x=Math.atan2(-u,f),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,i===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return Sy.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Sy,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Ty.setFromEuler(this),this.setFromQuaternion(Ty,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}an.DEFAULT_ORDER="XYZ";class Lh{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let i=0;i0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(s.matrixAutoUpdate=!1),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),s.instanceInfo=this._instanceInfo.map(o=>({...o})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(e),s.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(s.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(s.boundingBox=this.boundingBox.toJSON()));function a(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=a(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const l=o.shapes;if(Array.isArray(l))for(let c=0,u=l.length;c0){s.children=[];for(let o=0;o0){s.animations=[];for(let o=0;o0&&(i.geometries=o),l.length>0&&(i.materials=l),c.length>0&&(i.textures=c),u.length>0&&(i.images=u),d.length>0&&(i.shapes=d),h.length>0&&(i.skeletons=h),f.length>0&&(i.animations=f),p.length>0&&(i.nodes=p)}return i.object=s,i;function r(o){const l=[];for(const c in o){const u=o[c];delete u.metadata,l.push(u)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let i=0;i0?s.multiplyScalar(1/Math.sqrt(a)):s.set(0,0,0)}static getBarycoord(e,t,i,s,a){Di.subVectors(s,t),ws.subVectors(i,t),Pf.subVectors(e,t);const r=Di.dot(Di),o=Di.dot(ws),l=Di.dot(Pf),c=ws.dot(ws),u=ws.dot(Pf),d=r*c-o*o;if(d===0)return a.set(0,0,0),null;const h=1/d,f=(c*l-o*u)*h,p=(r*u-o*l)*h;return a.set(1-f-p,p,f)}static containsPoint(e,t,i,s){return this.getBarycoord(e,t,i,s,Ss)===null?!1:Ss.x>=0&&Ss.y>=0&&Ss.x+Ss.y<=1}static getInterpolation(e,t,i,s,a,r,o,l){return this.getBarycoord(e,t,i,s,Ss)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(a,Ss.x),l.addScaledVector(r,Ss.y),l.addScaledVector(o,Ss.z),l)}static getInterpolatedAttribute(e,t,i,s,a,r){return Df.setScalar(0),Of.setScalar(0),Ff.setScalar(0),Df.fromBufferAttribute(e,t),Of.fromBufferAttribute(e,i),Ff.fromBufferAttribute(e,s),r.setScalar(0),r.addScaledVector(Df,a.x),r.addScaledVector(Of,a.y),r.addScaledVector(Ff,a.z),r}static isFrontFacing(e,t,i,s){return Di.subVectors(i,t),ws.subVectors(e,t),Di.cross(ws).dot(s)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,s){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[s]),this}setFromAttributeAndIndices(e,t,i,s){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,s),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Di.subVectors(this.c,this.b),ws.subVectors(this.a,this.b),Di.cross(ws).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Qn.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Qn.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,s,a){return Qn.getInterpolation(e,this.a,this.b,this.c,t,i,s,a)}containsPoint(e){return Qn.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Qn.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,s=this.b,a=this.c;let r,o;Er.subVectors(s,i),Cr.subVectors(a,i),If.subVectors(e,i);const l=Er.dot(If),c=Cr.dot(If);if(l<=0&&c<=0)return t.copy(i);Lf.subVectors(e,s);const u=Er.dot(Lf),d=Cr.dot(Lf);if(u>=0&&d<=u)return t.copy(s);const h=l*d-u*c;if(h<=0&&l>=0&&u<=0)return r=l/(l-u),t.copy(i).addScaledVector(Er,r);kf.subVectors(e,a);const f=Er.dot(kf),p=Cr.dot(kf);if(p>=0&&f<=p)return t.copy(a);const g=f*c-l*p;if(g<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(i).addScaledVector(Cr,o);const _=u*p-f*d;if(_<=0&&d-u>=0&&f-p>=0)return Py.subVectors(a,s),o=(d-u)/(d-u+(f-p)),t.copy(s).addScaledVector(Py,o);const m=1/(_+g+h);return r=g*m,o=h*m,t.copy(i).addScaledVector(Er,r).addScaledVector(Cr,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const bS={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Xs={h:0,s:0,l:0},Ac={h:0,s:0,l:0};function Nf(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*6*(2/3-t):n}class ue{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){const s=e;s&&s.isColor?this.copy(s):typeof s=="number"?this.setHex(s):typeof s=="string"&&this.setStyle(s)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=gt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,rt.colorSpaceToWorking(this,t),this}setRGB(e,t,i,s=rt.workingColorSpace){return this.r=e,this.g=t,this.b=i,rt.colorSpaceToWorking(this,s),this}setHSL(e,t,i,s=rt.workingColorSpace){if(e=sg(e,1),t=Ze(t,0,1),i=Ze(i,0,1),t===0)this.r=this.g=this.b=i;else{const a=i<=.5?i*(1+t):i+t-i*t,r=2*i-a;this.r=Nf(r,a,e+1/3),this.g=Nf(r,a,e),this.b=Nf(r,a,e-1/3)}return rt.colorSpaceToWorking(this,s),this}setStyle(e,t=gt){function i(a){a!==void 0&&parseFloat(a)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(e)){let a;const r=s[1],o=s[2];switch(r){case"rgb":case"rgba":if(a=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setRGB(Math.min(255,parseInt(a[1],10))/255,Math.min(255,parseInt(a[2],10))/255,Math.min(255,parseInt(a[3],10))/255,t);if(a=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setRGB(Math.min(100,parseInt(a[1],10))/100,Math.min(100,parseInt(a[2],10))/100,Math.min(100,parseInt(a[3],10))/100,t);break;case"hsl":case"hsla":if(a=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setHSL(parseFloat(a[1])/360,parseFloat(a[2])/100,parseFloat(a[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(e)){const a=s[1],r=a.length;if(r===3)return this.setRGB(parseInt(a.charAt(0),16)/15,parseInt(a.charAt(1),16)/15,parseInt(a.charAt(2),16)/15,t);if(r===6)return this.setHex(parseInt(a,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=gt){const i=bS[e.toLowerCase()];return i!==void 0?this.setHex(i,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Fs(e.r),this.g=Fs(e.g),this.b=Fs(e.b),this}copyLinearToSRGB(e){return this.r=io(e.r),this.g=io(e.g),this.b=io(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=gt){return rt.workingToColorSpace(En.copy(this),e),Math.round(Ze(En.r*255,0,255))*65536+Math.round(Ze(En.g*255,0,255))*256+Math.round(Ze(En.b*255,0,255))}getHexString(e=gt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=rt.workingColorSpace){rt.workingToColorSpace(En.copy(this),t);const i=En.r,s=En.g,a=En.b,r=Math.max(i,s,a),o=Math.min(i,s,a);let l,c;const u=(o+r)/2;if(o===r)l=0,c=0;else{const d=r-o;switch(c=u<=.5?d/(r+o):d/(2-r-o),r){case i:l=(s-a)/d+(s0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const i=e[t];if(i===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(i):s&&s.isVector3&&i&&i.isVector3?s.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==nr&&(i.blending=this.blending),this.side!==fs&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==Bl&&(i.blendSrc=this.blendSrc),this.blendDst!==zl&&(i.blendDst=this.blendDst),this.blendEquation!==Is&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==ar&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==Am&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Ba&&(i.stencilFail=this.stencilFail),this.stencilZFail!==Ba&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==Ba&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function s(a){const r=[];for(const o in a){const l=a[o];delete l.metadata,r.push(l)}return r}if(t){const a=s(e.textures),r=s(e.images);a.length>0&&(i.textures=a),r.length>0&&(i.images=r)}return i}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let i=null;if(t!==null){const s=t.length;i=new Array(s);for(let a=0;a!==s;++a)i[a]=t[a].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class Ye extends Qt{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new ue(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new an,this.combine=rc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const ks=fA();function fA(){const n=new ArrayBuffer(4),e=new Float32Array(n),t=new Uint32Array(n),i=new Uint32Array(512),s=new Uint32Array(512);for(let l=0;l<256;++l){const c=l-127;c<-27?(i[l]=0,i[l|256]=32768,s[l]=24,s[l|256]=24):c<-14?(i[l]=1024>>-c-14,i[l|256]=1024>>-c-14|32768,s[l]=-c-1,s[l|256]=-c-1):c<=15?(i[l]=c+15<<10,i[l|256]=c+15<<10|32768,s[l]=13,s[l|256]=13):c<128?(i[l]=31744,i[l|256]=64512,s[l]=24,s[l|256]=24):(i[l]=31744,i[l|256]=64512,s[l]=13,s[l|256]=13)}const a=new Uint32Array(2048),r=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,u=0;for(;(c&8388608)===0;)c<<=1,u-=8388608;c&=-8388609,u+=947912704,a[l]=c|u}for(let l=1024;l<2048;++l)a[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)r[l]=l<<23;r[31]=1199570944,r[32]=2147483648;for(let l=33;l<63;++l)r[l]=2147483648+(l-32<<23);r[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:e,uint32View:t,baseTable:i,shiftTable:s,mantissaTable:a,exponentTable:r,offsetTable:o}}function Yn(n){Math.abs(n)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),n=Ze(n,-65504,65504),ks.floatView[0]=n;const e=ks.uint32View[0],t=e>>23&511;return ks.baseTable[t]+((e&8388607)>>ks.shiftTable[t])}function fl(n){const e=n>>10;return ks.uint32View[0]=ks.mantissaTable[ks.offsetTable[e]+(n&1023)]+ks.exponentTable[e],ks.floatView[0]}class pl{static toHalfFloat(e){return Yn(e)}static fromHalfFloat(e){return fl(e)}}const nn=new S,Rc=new te;let pA=0;class ot{constructor(e,t,i=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:pA++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=$l,this.updateRanges=[],this.gpuType=Sn,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,i){e*=this.itemSize,i*=t.itemSize;for(let s=0,a=this.itemSize;st.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new vn);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new S(-1/0,-1/0,-1/0),new S(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,s=t.length;i0&&(e.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const l in i){const c=i[l];e.data.attributes[l]=c.toJSON(e.data)}const s={};let a=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],u=[];for(let d=0,h=c.length;d0&&(s[l]=u,a=!0)}a&&(e.data.morphAttributes=s,e.data.morphTargetsRelative=this.morphTargetsRelative);const r=this.groups;r.length>0&&(e.data.groups=JSON.parse(JSON.stringify(r)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const i=e.index;i!==null&&this.setIndex(i.clone());const s=e.attributes;for(const c in s){const u=s[c];this.setAttribute(c,u.clone(t))}const a=e.morphAttributes;for(const c in a){const u=[],d=a[c];for(let h=0,f=d.length;h0){const s=t[i[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,r=s.length;a(e.far-e.near)**2))&&(Iy.copy(a).invert(),ba.copy(e.ray).applyMatrix4(Iy),!(i.boundingBox!==null&&ba.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,ba)))}_computeIntersections(e,t,i){let s;const a=this.geometry,r=this.material,o=a.index,l=a.attributes.position,c=a.attributes.uv,u=a.attributes.uv1,d=a.attributes.normal,h=a.groups,f=a.drawRange;if(o!==null)if(Array.isArray(r))for(let p=0,g=h.length;pt.far?null:{distance:c,point:Oc.clone(),object:n}}function Fc(n,e,t,i,s,a,r,o,l,c){n.getVertexPosition(o,Ic),n.getVertexPosition(l,Lc),n.getVertexPosition(c,kc);const u=wA(n,e,t,i,Ic,Lc,kc,ky);if(u){const d=new S;Qn.getBarycoord(ky,Ic,Lc,kc,d),s&&(u.uv=Qn.getInterpolatedAttribute(s,o,l,c,d,new te)),a&&(u.uv1=Qn.getInterpolatedAttribute(a,o,l,c,d,new te)),r&&(u.normal=Qn.getInterpolatedAttribute(r,o,l,c,d,new S),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));const h={a:o,b:l,c,normal:new S,materialIndex:0};Qn.getNormal(Ic,Lc,kc,h.normal),u.face=h,u.barycoord=d}return u}class Ci extends Ge{constructor(e=1,t=1,i=1,s=1,a=1,r=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:s,heightSegments:a,depthSegments:r};const o=this;s=Math.floor(s),a=Math.floor(a),r=Math.floor(r);const l=[],c=[],u=[],d=[];let h=0,f=0;p("z","y","x",-1,-1,i,t,e,r,a,0),p("z","y","x",1,-1,i,t,-e,r,a,1),p("x","z","y",1,1,e,i,t,s,r,2),p("x","z","y",1,-1,e,i,-t,s,r,3),p("x","y","z",1,-1,e,t,i,s,a,4),p("x","y","z",-1,-1,e,t,-i,s,a,5),this.setIndex(l),this.setAttribute("position",new Ee(c,3)),this.setAttribute("normal",new Ee(u,3)),this.setAttribute("uv",new Ee(d,2));function p(g,_,m,v,y,b,T,x,M,C,w){const E=b/M,R=T/C,k=b/2,O=T/2,D=x/2,U=M+1,F=C+1;let W=0,H=0;const ne=new S;for(let oe=0;oe0?1:-1,u.push(ne.x,ne.y,ne.z),d.push(Ie/M),d.push(1-oe/C),W+=1}}for(let oe=0;oe0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const i={};for(const s in this.extensions)this.extensions[s]===!0&&(i[s]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}}class Ah extends Qe{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Me,this.projectionMatrix=new Me,this.projectionMatrixInverse=new Me,this.coordinateSystem=hi,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const Ks=new S,Cy=new te,Ay=new te;class Jt extends Ah{constructor(e=50,t=1,i=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=i,this.far=s,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=To*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(nr*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return To*2*Math.atan(Math.tan(nr*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,i){Ks.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Ks.x,Ks.y).multiplyScalar(-e/Ks.z),Ks.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(Ks.x,Ks.y).multiplyScalar(-e/Ks.z)}getViewSize(e,t){return this.getViewBounds(e,Cy,Ay),t.subVectors(Ay,Cy)}setViewOffset(e,t,i,s,a,r){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=s,this.view.width=a,this.view.height=r,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(nr*.5*this.fov)/this.zoom,i=2*t,s=this.aspect*i,a=-.5*s;const r=this.view;if(this.view!==null&&this.view.enabled){const l=r.fullWidth,c=r.fullHeight;a+=r.offsetX*s/l,t-=r.offsetY*i/c,s*=r.width/l,i*=r.height/c}const o=this.filmOffset;o!==0&&(a+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(a,a+s,t,t-i,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const Ar=-90,Rr=1;class mS extends Qe{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new Jt(Ar,Rr,e,t);s.layers=this.layers,this.add(s);const a=new Jt(Ar,Rr,e,t);a.layers=this.layers,this.add(a);const r=new Jt(Ar,Rr,e,t);r.layers=this.layers,this.add(r);const o=new Jt(Ar,Rr,e,t);o.layers=this.layers,this.add(o);const l=new Jt(Ar,Rr,e,t);l.layers=this.layers,this.add(l);const c=new Jt(Ar,Rr,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[i,s,a,r,o,l]=t;for(const c of t)this.remove(c);if(e===hi)i.up.set(0,1,0),i.lookAt(1,0,0),s.up.set(0,1,0),s.lookAt(-1,0,0),a.up.set(0,0,-1),a.lookAt(0,1,0),r.up.set(0,0,1),r.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===So)i.up.set(0,-1,0),i.lookAt(-1,0,0),s.up.set(0,-1,0),s.lookAt(1,0,0),a.up.set(0,0,1),a.lookAt(0,1,0),r.up.set(0,0,-1),r.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:s}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[a,r,o,l,c,u]=this.children,d=e.getRenderTarget(),h=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const g=i.texture.generateMipmaps;i.texture.generateMipmaps=!1,e.setRenderTarget(i,0,s),e.render(t,a),e.setRenderTarget(i,1,s),e.render(t,r),e.setRenderTarget(i,2,s),e.render(t,o),e.setRenderTarget(i,3,s),e.render(t,l),e.setRenderTarget(i,4,s),e.render(t,c),i.texture.generateMipmaps=g,e.setRenderTarget(i,5,s),e.render(t,u),e.setRenderTarget(d,h,f),e.xr.enabled=p,i.texture.needsPMREMUpdate=!0}}class sc extends Bt{constructor(e=[],t=Bs,i,s,a,r,o,l,c,u){super(e,t,i,s,a,r,o,l,c,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class _S extends ms{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const i={width:e,height:e,depth:1},s=[i,i,i,i,i,i];this.texture=new sc(s),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const i={uniforms:{tEquirect:{value:null}},vertexShader:` +}`;class ti extends Qt{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=TA,this.fragmentShader=MA,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=Ao(e.uniforms),this.uniformsGroups=SA(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const s in this.uniforms){const r=this.uniforms[s].value;r&&r.isTexture?t.uniforms[s]={type:"t",value:r.toJSON(e).uuid}:r&&r.isColor?t.uniforms[s]={type:"c",value:r.getHex()}:r&&r.isVector2?t.uniforms[s]={type:"v2",value:r.toArray()}:r&&r.isVector3?t.uniforms[s]={type:"v3",value:r.toArray()}:r&&r.isVector4?t.uniforms[s]={type:"v4",value:r.toArray()}:r&&r.isMatrix3?t.uniforms[s]={type:"m3",value:r.toArray()}:r&&r.isMatrix4?t.uniforms[s]={type:"m4",value:r.toArray()}:t.uniforms[s]={value:r}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const i={};for(const s in this.extensions)this.extensions[s]===!0&&(i[s]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}}class Dh extends Qe{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Me,this.projectionMatrix=new Me,this.projectionMatrixInverse=new Me,this.coordinateSystem=hi,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const Ks=new S,Dy=new te,Oy=new te;class Jt extends Dh{constructor(e=50,t=1,i=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=i,this.far=s,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=Co*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(ir*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Co*2*Math.atan(Math.tan(ir*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,i){Ks.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Ks.x,Ks.y).multiplyScalar(-e/Ks.z),Ks.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(Ks.x,Ks.y).multiplyScalar(-e/Ks.z)}getViewSize(e,t){return this.getViewBounds(e,Dy,Oy),t.subVectors(Oy,Dy)}setViewOffset(e,t,i,s,a,r){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=s,this.view.width=a,this.view.height=r,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(ir*.5*this.fov)/this.zoom,i=2*t,s=this.aspect*i,a=-.5*s;const r=this.view;if(this.view!==null&&this.view.enabled){const l=r.fullWidth,c=r.fullHeight;a+=r.offsetX*s/l,t-=r.offsetY*i/c,s*=r.width/l,i*=r.height/c}const o=this.filmOffset;o!==0&&(a+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(a,a+s,t,t-i,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const Rr=-90,Pr=1;class SS extends Qe{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new Jt(Rr,Pr,e,t);s.layers=this.layers,this.add(s);const a=new Jt(Rr,Pr,e,t);a.layers=this.layers,this.add(a);const r=new Jt(Rr,Pr,e,t);r.layers=this.layers,this.add(r);const o=new Jt(Rr,Pr,e,t);o.layers=this.layers,this.add(o);const l=new Jt(Rr,Pr,e,t);l.layers=this.layers,this.add(l);const c=new Jt(Rr,Pr,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[i,s,a,r,o,l]=t;for(const c of t)this.remove(c);if(e===hi)i.up.set(0,1,0),i.lookAt(1,0,0),s.up.set(0,1,0),s.lookAt(-1,0,0),a.up.set(0,0,-1),a.lookAt(0,1,0),r.up.set(0,0,1),r.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===Eo)i.up.set(0,-1,0),i.lookAt(-1,0,0),s.up.set(0,-1,0),s.lookAt(1,0,0),a.up.set(0,0,1),a.lookAt(0,1,0),r.up.set(0,0,-1),r.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:s}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[a,r,o,l,c,u]=this.children,d=e.getRenderTarget(),h=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const g=i.texture.generateMipmaps;i.texture.generateMipmaps=!1,e.setRenderTarget(i,0,s),e.render(t,a),e.setRenderTarget(i,1,s),e.render(t,r),e.setRenderTarget(i,2,s),e.render(t,o),e.setRenderTarget(i,3,s),e.render(t,l),e.setRenderTarget(i,4,s),e.render(t,c),i.texture.generateMipmaps=g,e.setRenderTarget(i,5,s),e.render(t,u),e.setRenderTarget(d,h,f),e.xr.enabled=p,i.texture.needsPMREMUpdate=!0}}class lc extends Bt{constructor(e=[],t=Bs,i,s,a,r,o,l,c,u){super(e,t,i,s,a,r,o,l,c,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class TS extends ms{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const i={width:e,height:e,depth:1},s=[i,i,i,i,i,i];this.texture=new lc(s),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const i={uniforms:{tEquirect:{value:null}},vertexShader:` varying vec3 vWorldDirection; @@ -37,9 +37,9 @@ function fh(n,e){if(n.frames.length===0)return 0;let t=0,i=n.frames.length-1;for gl_FragColor = texture2D( tEquirect, sampleUV ); } - `},s=new Ei(5,5,5),a=new ti({name:"CubemapFromEquirect",uniforms:Mo(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:un,blending:ks});a.uniforms.tEquirect.value=t;const r=new we(s,a),o=t.minFilter;return t.minFilter===Ti&&(t.minFilter=Vt),new mS(1,10,this).update(e,r),t.minFilter=o,r.geometry.dispose(),r.material.dispose(),this}clear(e,t=!0,i=!0,s=!0){const a=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,i,s);e.setRenderTarget(a)}}class Mt extends Qe{constructor(){super(),this.isGroup=!0,this.type="Group"}}const mA={type:"move"};class Gu{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Mt,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Mt,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new S,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new S),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Mt,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new S,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new S),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const i of e.hand.values())this._getHandJoint(t,i)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,i){let s=null,a=null,r=null;const o=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){r=!0;for(const g of e.hand.values()){const _=t.getJointPose(g,i),m=this._getHandJoint(c,g);_!==null&&(m.matrix.fromArray(_.transform.matrix),m.matrix.decompose(m.position,m.rotation,m.scale),m.matrixWorldNeedsUpdate=!0,m.jointRadius=_.radius),m.visible=_!==null}const u=c.joints["index-finger-tip"],d=c.joints["thumb-tip"],h=u.position.distanceTo(d.position),f=.02,p=.005;c.inputState.pinching&&h>f+p?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&h<=f-p&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(a=t.getPose(e.gripSpace,i),a!==null&&(l.matrix.fromArray(a.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,a.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(a.linearVelocity)):l.hasLinearVelocity=!1,a.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(a.angularVelocity)):l.hasAngularVelocity=!1));o!==null&&(s=t.getPose(e.targetRaySpace,i),s===null&&a!==null&&(s=a),s!==null&&(o.matrix.fromArray(s.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,s.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(s.linearVelocity)):o.hasLinearVelocity=!1,s.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(s.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(mA)))}return o!==null&&(o.visible=s!==null),l!==null&&(l.visible=a!==null),c!==null&&(c.visible=r!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const i=new Mt;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}class Rh{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new ue(e),this.density=t}clone(){return new Rh(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class Ph{constructor(e,t=1,i=1e3){this.isFog=!0,this.name="",this.color=new ue(e),this.near=t,this.far=i}clone(){return new Ph(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class ac extends Qe{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new an,this.environmentIntensity=1,this.environmentRotation=new an,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class rc{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=zl,this.updateRanges=[],this.version=0,this.uuid=pi()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,i){e*=this.stride,i*=t.stride;for(let s=0,a=this.stride;se.far||t.push({distance:l,point:$o.clone(),uv:Qn.getInterpolation($o,Dc,Xo,kc,Ry,kf,Py,new te),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}}function Oc(n,e,t,i,s,a){Dr.subVectors(n,t).addScalar(.5).multiply(i),s!==void 0?(Wo.x=a*Dr.x-s*Dr.y,Wo.y=s*Dr.x+a*Dr.y):Wo.copy(Dr),n.copy(e),n.x+=Wo.x,n.y+=Wo.y,n.applyMatrix4(gS)}const Fc=new S,Iy=new S;class yS extends Qe{constructor(){super(),this.isLOD=!0,this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);const t=e.levels;for(let i=0,s=t.length;i0){let i,s;for(i=1,s=t.length;i0){Fc.setFromMatrixPosition(this.matrixWorld);const s=e.ray.origin.distanceTo(Fc);this.getObjectForDistance(s).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){Fc.setFromMatrixPosition(e.matrixWorld),Iy.setFromMatrixPosition(this.matrixWorld);const i=Fc.distanceTo(Iy)/e.zoom;t[0].object.visible=!0;let s,a;for(s=1,a=t.length;s=r)t[s-1].object.visible=!1,t[s].object.visible=!0;else break}for(this._currentLevel=s-1;s1?null:t.copy(e.start).addScaledVector(i,a)}intersectsLine(e){const t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const i=t||bA.getNormalMatrix(e),s=this.coplanarPoint(Nf).applyMatrix4(e),a=this.normal.applyMatrix3(i).normalize();return this.constant=-s.dot(a),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const ba=new bn,xA=new te(.5,.5),Bc=new S;class Po{constructor(e=new Ps,t=new Ps,i=new Ps,s=new Ps,a=new Ps,r=new Ps){this.planes=[e,t,i,s,a,r]}set(e,t,i,s,a,r){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(i),o[3].copy(s),o[4].copy(a),o[5].copy(r),this}copy(e){const t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=hi,i=!1){const s=this.planes,a=e.elements,r=a[0],o=a[1],l=a[2],c=a[3],u=a[4],d=a[5],h=a[6],f=a[7],p=a[8],g=a[9],_=a[10],m=a[11],v=a[12],y=a[13],b=a[14],T=a[15];if(s[0].setComponents(c-r,f-u,m-p,T-v).normalize(),s[1].setComponents(c+r,f+u,m+p,T+v).normalize(),s[2].setComponents(c+o,f+d,m+g,T+y).normalize(),s[3].setComponents(c-o,f-d,m-g,T-y).normalize(),i)s[4].setComponents(l,h,_,b).normalize(),s[5].setComponents(c-l,f-h,m-_,T-b).normalize();else if(s[4].setComponents(c-l,f-h,m-_,T-b).normalize(),t===hi)s[5].setComponents(c+l,f+h,m+_,T+b).normalize();else if(t===So)s[5].setComponents(l,h,_,b).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),ba.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),ba.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ba)}intersectsSprite(e){ba.center.set(0,0,0);const t=xA.distanceTo(e.center);return ba.radius=.7071067811865476+t,ba.applyMatrix4(e.matrixWorld),this.intersectsSphere(ba)}intersectsSphere(e){const t=this.planes,i=e.center,s=-e.radius;for(let a=0;a<6;a++)if(t[a].distanceToPoint(i)0?e.max.x:e.min.x,Bc.y=s.normal.y>0?e.max.y:e.min.y,Bc.z=s.normal.z>0?e.max.z:e.min.z,s.distanceToPoint(Bc)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}const Ji=new Me,Qi=new Po;class Oh{constructor(){this.coordinateSystem=hi}intersectsObject(e,t){if(!t.isArrayCamera||t.cameras.length===0)return!1;for(let i=0;i=a.length&&a.push({start:-1,count:-1,z:-1,index:-1});const o=a[this.index];r.push(o),this.index++,o.start=e,o.count=t,o.z=i,o.index=s}reset(){this.list.length=0,this.index=0}}const Wn=new Me,MA=new ue(1,1,1),zy=new Po,EA=new Oh,zc=new vn,xa=new bn,Yo=new S,Hy=new S,CA=new S,Bf=new TA,Cn=new we,Hc=[];function AA(n,e,t=0){const i=e.itemSize;if(n.isInterleavedBufferAttribute||n.array.constructor!==e.array.constructor){const s=n.count;for(let a=0;a65535?new Uint32Array(s):new Uint16Array(s);t.setIndex(new rt(a,1))}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;if(!!e.getIndex()!=!!t.getIndex())throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');for(const i in t.attributes){if(!e.hasAttribute(i))throw new Error(`THREE.BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`);const s=e.getAttribute(i),a=t.getAttribute(i);if(s.itemSize!==a.itemSize||s.normalized!==a.normalized)throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}validateInstanceId(e){const t=this._instanceInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid instanceId ${e}. Instance is either out of range or has been deleted.`)}validateGeometryId(e){const t=this._geometryInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`)}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new vn);const e=this.boundingBox,t=this._instanceInfo;e.makeEmpty();for(let i=0,s=t.length;i=this.maxInstanceCount&&this._availableInstanceIds.length===0)throw new Error("THREE.BatchedMesh: Maximum item count reached.");const i={visible:!0,active:!0,geometryIndex:e};let s=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(Uf),s=this._availableInstanceIds.shift(),this._instanceInfo[s]=i):(s=this._instanceInfo.length,this._instanceInfo.push(i));const a=this._matricesTexture;Wn.identity().toArray(a.image.data,s*16),a.needsUpdate=!0;const r=this._colorsTexture;return r&&(MA.toArray(r.image.data,s*4),r.needsUpdate=!0),this._visibilityChanged=!0,s}addGeometry(e,t=-1,i=-1){this._initializeGeometry(e),this._validateGeometry(e);const s={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},a=this._geometryInfo;s.vertexStart=this._nextVertexStart,s.reservedVertexCount=t===-1?e.getAttribute("position").count:t;const r=e.getIndex();if(r!==null&&(s.indexStart=this._nextIndexStart,s.reservedIndexCount=i===-1?r.count:i),s.indexStart!==-1&&s.indexStart+s.reservedIndexCount>this._maxIndexCount||s.vertexStart+s.reservedVertexCount>this._maxVertexCount)throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");let l;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(Uf),l=this._availableGeometryIds.shift(),a[l]=s):(l=this._geometryCount,this._geometryCount++,a.push(s)),this.setGeometryAt(l,e),this._nextIndexStart=s.indexStart+s.reservedIndexCount,this._nextVertexStart=s.vertexStart+s.reservedVertexCount,l}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,s=i.getIndex()!==null,a=i.getIndex(),r=t.getIndex(),o=this._geometryInfo[e];if(s&&r.count>o.reservedIndexCount||t.attributes.position.count>o.reservedVertexCount)throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");const l=o.vertexStart,c=o.reservedVertexCount;o.vertexCount=t.getAttribute("position").count;for(const u in i.attributes){const d=t.getAttribute(u),h=i.getAttribute(u);AA(d,h,l);const f=d.itemSize;for(let p=d.count,g=c;p=t.length||t[e].active===!1)return this;const i=this._instanceInfo;for(let s=0,a=i.length;so).sort((r,o)=>i[r].vertexStart-i[o].vertexStart),a=this.geometry;for(let r=0,o=i.length;r=this._geometryCount)return null;const i=this.geometry,s=this._geometryInfo[e];if(s.boundingBox===null){const a=new vn,r=i.index,o=i.attributes.position;for(let l=s.start,c=s.start+s.count;l=this._geometryCount)return null;const i=this.geometry,s=this._geometryInfo[e];if(s.boundingSphere===null){const a=new bn;this.getBoundingBoxAt(e,zc),zc.getCenter(a.center);const r=i.index,o=i.attributes.position;let l=0;for(let c=s.start,u=s.start+s.count;co.active);if(Math.max(...i.map(o=>o.vertexStart+o.reservedVertexCount))>e)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${t}. Cannot shrink further.`);if(this.geometry.index&&Math.max(...i.map(l=>l.indexStart+l.reservedIndexCount))>t)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${t}. Cannot shrink further.`);const a=this.geometry;a.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new Ge,this._initializeGeometry(a));const r=this.geometry;a.index&&wa(a.index.array,r.index.array);for(const o in a.attributes)wa(a.attributes[o].array,r.attributes[o].array)}raycast(e,t){const i=this._instanceInfo,s=this._geometryInfo,a=this.matrixWorld,r=this.geometry;Cn.material=this.material,Cn.geometry.index=r.index,Cn.geometry.attributes=r.attributes,Cn.geometry.boundingBox===null&&(Cn.geometry.boundingBox=new vn),Cn.geometry.boundingSphere===null&&(Cn.geometry.boundingSphere=new bn);for(let o=0,l=i.length;o({...t,boundingBox:t.boundingBox!==null?t.boundingBox.clone():null,boundingSphere:t.boundingSphere!==null?t.boundingSphere.clone():null})),this._instanceInfo=e._instanceInfo.map(t=>({...t})),this._availableInstanceIds=e._availableInstanceIds.slice(),this._availableGeometryIds=e._availableGeometryIds.slice(),this._nextIndexStart=e._nextIndexStart,this._nextVertexStart=e._nextVertexStart,this._geometryCount=e._geometryCount,this._maxInstanceCount=e._maxInstanceCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._indirectTexture=e._indirectTexture.clone(),this._indirectTexture.image.data=this._indirectTexture.image.data.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),this._colorsTexture!==null&&(this._colorsTexture=e._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,this._colorsTexture!==null&&(this._colorsTexture.dispose(),this._colorsTexture=null)}onBeforeRender(e,t,i,s,a){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const r=s.getIndex(),o=r===null?1:r.array.BYTES_PER_ELEMENT,l=this._instanceInfo,c=this._multiDrawStarts,u=this._multiDrawCounts,d=this._geometryInfo,h=this.perObjectFrustumCulled,f=this._indirectTexture,p=f.image.data,g=i.isArrayCamera?EA:zy;h&&!i.isArrayCamera&&(Wn.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse).multiply(this.matrixWorld),zy.setFromProjectionMatrix(Wn,i.coordinateSystem,i.reversedDepth));let _=0;if(this.sortObjects){Wn.copy(this.matrixWorld).invert(),Yo.setFromMatrixPosition(i.matrixWorld).applyMatrix4(Wn),Hy.set(0,0,-1).transformDirection(i.matrixWorld).transformDirection(Wn);for(let y=0,b=l.length;y0){const s=t[i[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,r=s.length;ai)return;zf.applyMatrix4(n.matrixWorld);const c=e.ray.origin.distanceTo(zf);if(!(ce.far))return{distance:c,point:Gy.clone().applyMatrix4(n.matrixWorld),index:r,face:null,faceIndex:null,barycoord:null,object:n}}const $y=new S,Wy=new S;class Ln extends In{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,i=[];for(let s=0,a=t.count;s0){const s=t[i[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,r=s.length;as.far)return;a.push({distance:c,distanceToRay:Math.sqrt(o),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:r})}}class bS extends Bt{constructor(e,t,i,s,a=Vt,r=Vt,o,l,c){super(e,t,i,s,a,r,o,l,c),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;const u=this;function d(){u.needsUpdate=!0,u._requestVideoFrameCallbackId=e.requestVideoFrameCallback(d)}"requestVideoFrameCallback"in e&&(this._requestVideoFrameCallbackId=e.requestVideoFrameCallback(d))}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;"requestVideoFrameCallback"in e===!1&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),super.dispose()}}class RA extends bS{constructor(e,t,i,s,a,r,o,l){super({},e,t,i,s,a,r,o,l),this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(e){this.image=e,this.needsUpdate=!0}}class PA extends Bt{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=dn,this.minFilter=dn,this.generateMipmaps=!1,this.needsUpdate=!0}}class Fh extends Bt{constructor(e,t,i,s,a,r,o,l,c,u,d,h){super(null,r,o,l,c,u,s,a,d,h),this.isCompressedTexture=!0,this.image={width:t,height:i},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class IA extends Fh{constructor(e,t,i,s,a,r){super(e,t,i,a,r),this.isCompressedArrayTexture=!0,this.image.depth=s,this.wrapR=Hn,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class LA extends Fh{constructor(e,t,i){super(void 0,e[0].width,e[0].height,t,i,Bs),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class oc extends Bt{constructor(e,t,i,s,a,r,o,l,c){super(e,t,i,s,a,r,o,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}}class tg extends Bt{constructor(e,t,i=zs,s,a,r,o=dn,l=dn,c,u=bo,d=1){if(u!==bo&&u!==xo)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const h={width:e,height:t,depth:d};super(h,s,a,r,o,l,u,i,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new ia(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class ng extends Bt{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class Nh extends Ge{constructor(e=1,t=1,i=4,s=8,a=1){super(),this.type="CapsuleGeometry",this.parameters={radius:e,height:t,capSegments:i,radialSegments:s,heightSegments:a},t=Math.max(0,t),i=Math.max(1,Math.floor(i)),s=Math.max(3,Math.floor(s)),a=Math.max(1,Math.floor(a));const r=[],o=[],l=[],c=[],u=t/2,d=Math.PI/2*e,h=t,f=2*d+h,p=i*2+a,g=s+1,_=new S,m=new S;for(let v=0;v<=p;v++){let y=0,b=0,T=0,x=0;if(v<=i){const w=v/i,E=w*Math.PI/2;b=-u-e*Math.cos(E),T=e*Math.sin(E),x=-e*Math.cos(E),y=w*d}else if(v<=i+a){const w=(v-i)/a;b=-u+w*t,T=e,x=0,y=d+w*h}else{const w=(v-i-a)/i,E=w*Math.PI/2;b=u+e*Math.sin(E),T=e*Math.cos(E),x=e*Math.sin(E),y=d+h+w*d}const M=Math.max(0,Math.min(1,y/f));let C=0;v===0?C=.5/s:v===p&&(C=-.5/s);for(let w=0;w<=s;w++){const E=w/s,R=E*Math.PI*2,D=Math.sin(R),O=Math.cos(R);m.x=-T*O,m.y=b,m.z=T*D,o.push(m.x,m.y,m.z),_.set(-T*O,x,T*D),_.normalize(),l.push(_.x,_.y,_.z),c.push(E+C,M)}if(v>0){const w=(v-1)*g;for(let E=0;E0&&y(!0),t>0&&y(!1)),this.setIndex(u),this.setAttribute("position",new Ee(d,3)),this.setAttribute("normal",new Ee(h,3)),this.setAttribute("uv",new Ee(f,2));function v(){const b=new S,T=new S;let x=0;const M=(t-e)/i;for(let C=0;C<=a;C++){const w=[],E=C/a,R=E*(t-e)+e;for(let D=0;D<=s;D++){const O=D/s,k=O*l+o,U=Math.sin(k),F=Math.cos(k);T.x=R*U,T.y=-E*i+_,T.z=R*F,d.push(T.x,T.y,T.z),b.set(U,M,F).normalize(),h.push(b.x,b.y,b.z),f.push(O,1-E),w.push(p++)}g.push(w)}for(let C=0;C0||w!==0)&&(u.push(E,R,O),x+=3),(t>0||w!==a-1)&&(u.push(R,D,O),x+=3)}c.addGroup(m,x,0),m+=x}function y(b){const T=p,x=new te,M=new S;let C=0;const w=b===!0?e:t,E=b===!0?1:-1;for(let D=1;D<=s;D++)d.push(0,_*E,0),h.push(0,E,0),f.push(.5,.5),p++;const R=p;for(let D=0;D<=s;D++){const k=D/s*l+o,U=Math.cos(k),F=Math.sin(k);M.x=w*F,M.y=_*E,M.z=w*U,d.push(M.x,M.y,M.z),h.push(0,E,0),x.x=U*.5+.5,x.y=F*.5*E+.5,f.push(x.x,x.y),p++}for(let D=0;D.9&&M<.1&&(y<.2&&(r[v+0]+=1),b<.2&&(r[v+2]+=1),T<.2&&(r[v+4]+=1))}}function h(v){a.push(v.x,v.y,v.z)}function f(v,y){const b=v*3;y.x=e[b+0],y.y=e[b+1],y.z=e[b+2]}function p(){const v=new S,y=new S,b=new S,T=new S,x=new te,M=new te,C=new te;for(let w=0,E=0;w0)l=s-1;else{l=s;break}if(s=l,i[s]===r)return s/(a-1);const u=i[s],h=i[s+1]-u,f=(r-u)/h;return(s+f)/(a-1)}getTangent(e,t){let s=e-1e-4,a=e+1e-4;s<0&&(s=0),a>1&&(a=1);const r=this.getPoint(s),o=this.getPoint(a),l=t||(r.isVector2?new te:new S);return l.copy(o).sub(r).normalize(),l}getTangentAt(e,t){const i=this.getUtoTmapping(e);return this.getTangent(i,t)}computeFrenetFrames(e,t=!1){const i=new S,s=[],a=[],r=[],o=new S,l=new Me;for(let f=0;f<=e;f++){const p=f/e;s[f]=this.getTangentAt(p,new S)}a[0]=new S,r[0]=new S;let c=Number.MAX_VALUE;const u=Math.abs(s[0].x),d=Math.abs(s[0].y),h=Math.abs(s[0].z);u<=c&&(c=u,i.set(1,0,0)),d<=c&&(c=d,i.set(0,1,0)),h<=c&&i.set(0,0,1),o.crossVectors(s[0],i).normalize(),a[0].crossVectors(s[0],o),r[0].crossVectors(s[0],a[0]);for(let f=1;f<=e;f++){if(a[f]=a[f-1].clone(),r[f]=r[f-1].clone(),o.crossVectors(s[f-1],s[f]),o.length()>Number.EPSILON){o.normalize();const p=Math.acos(Ze(s[f-1].dot(s[f]),-1,1));a[f].applyMatrix4(l.makeRotationAxis(o,p))}r[f].crossVectors(s[f],a[f])}if(t===!0){let f=Math.acos(Ze(a[0].dot(a[e]),-1,1));f/=e,s[0].dot(o.crossVectors(a[0],a[e]))>0&&(f=-f);for(let p=1;p<=e;p++)a[p].applyMatrix4(l.makeRotationAxis(s[p],f*p)),r[p].crossVectors(s[p],a[p])}return{tangents:s,normals:a,binormals:r}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class zh extends Ri{constructor(e=0,t=0,i=1,s=1,a=0,r=Math.PI*2,o=!1,l=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=i,this.yRadius=s,this.aStartAngle=a,this.aEndAngle=r,this.aClockwise=o,this.aRotation=l}getPoint(e,t=new te){const i=t,s=Math.PI*2;let a=this.aEndAngle-this.aStartAngle;const r=Math.abs(a)s;)a-=s;a0?0:(Math.floor(Math.abs(o)/a)+1)*a:l===0&&o===a-1&&(o=a-2,l=1);let c,u;this.closed||o>0?c=s[(o-1)%a]:(Yc.subVectors(s[0],s[1]).add(s[0]),c=Yc);const d=s[o%a],h=s[(o+1)%a];if(this.closed||o+2s.length-2?s.length-1:r+1],d=s[r>s.length-3?s.length-1:r+2];return i.set(qy(o,l.x,c.x,u.x,d.x),qy(o,l.y,c.y,u.y,d.y)),i}copy(e){super.copy(e),this.points=[];for(let t=0,i=e.points.length;t=i){const r=s[a]-i,o=this.curves[a],l=o.getLength(),c=l===0?0:1-r/l;return o.getPointAt(c,t)}a++}return null}getLength(){const e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const e=[];let t=0;for(let i=0,s=this.curves.length;i1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,i=e.curves.length;t0){const d=c.getPoint(0);d.equals(this.currentPoint)||this.lineTo(d.x,d.y)}this.curves.push(c);const u=c.getPoint(1);return this.currentPoint.copy(u),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class Ns extends Zd{constructor(e){super(e),this.uuid=pi(),this.type="Shape",this.holes=[]}getPointsHoles(e){const t=[];for(let i=0,s=this.holes.length;i80*t){o=1/0,l=1/0;let u=-1/0,d=-1/0;for(let h=t;hu&&(u=f),p>d&&(d=p)}c=Math.max(u-o,d-l),c=c!==0?32767/c:0}return Gl(a,r,t,o,l,c,0),r}function MS(n,e,t,i,s){let a;if(s===nR(n,e,t,i)>0)for(let r=e;r=e;r-=i)a=Yy(r/i|0,n[r],n[r+1],a);return a&&Co(a,a.next)&&(Wl(a),a=a.next),a}function cr(n,e){if(!n)return n;e||(e=n);let t=n,i;do if(i=!1,!t.steiner&&(Co(t,t.next)||Kt(t.prev,t,t.next)===0)){if(Wl(t),t=e=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==e);return e}function Gl(n,e,t,i,s,a,r){if(!n)return;!r&&a&&jA(n,i,s,a);let o=n;for(;n.prev!==n.next;){const l=n.prev,c=n.next;if(a?VA(n,i,s,a):HA(n)){e.push(l.i,n.i,c.i),Wl(n),n=c.next,o=c.next;continue}if(n=c,n===o){r?r===1?(n=GA(cr(n),e),Gl(n,e,t,i,s,a,2)):r===2&&$A(n,e,t,i,s,a):Gl(cr(n),e,t,i,s,a,1);break}}}function HA(n){const e=n.prev,t=n,i=n.next;if(Kt(e,t,i)>=0)return!1;const s=e.x,a=t.x,r=i.x,o=e.y,l=t.y,c=i.y,u=Math.min(s,a,r),d=Math.min(o,l,c),h=Math.max(s,a,r),f=Math.max(o,l,c);let p=i.next;for(;p!==e;){if(p.x>=u&&p.x<=h&&p.y>=d&&p.y<=f&&hl(s,o,a,l,r,c,p.x,p.y)&&Kt(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function VA(n,e,t,i){const s=n.prev,a=n,r=n.next;if(Kt(s,a,r)>=0)return!1;const o=s.x,l=a.x,c=r.x,u=s.y,d=a.y,h=r.y,f=Math.min(o,l,c),p=Math.min(u,d,h),g=Math.max(o,l,c),_=Math.max(u,d,h),m=Tm(f,p,e,t,i),v=Tm(g,_,e,t,i);let y=n.prevZ,b=n.nextZ;for(;y&&y.z>=m&&b&&b.z<=v;){if(y.x>=f&&y.x<=g&&y.y>=p&&y.y<=_&&y!==s&&y!==r&&hl(o,u,l,d,c,h,y.x,y.y)&&Kt(y.prev,y,y.next)>=0||(y=y.prevZ,b.x>=f&&b.x<=g&&b.y>=p&&b.y<=_&&b!==s&&b!==r&&hl(o,u,l,d,c,h,b.x,b.y)&&Kt(b.prev,b,b.next)>=0))return!1;b=b.nextZ}for(;y&&y.z>=m;){if(y.x>=f&&y.x<=g&&y.y>=p&&y.y<=_&&y!==s&&y!==r&&hl(o,u,l,d,c,h,y.x,y.y)&&Kt(y.prev,y,y.next)>=0)return!1;y=y.prevZ}for(;b&&b.z<=v;){if(b.x>=f&&b.x<=g&&b.y>=p&&b.y<=_&&b!==s&&b!==r&&hl(o,u,l,d,c,h,b.x,b.y)&&Kt(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function GA(n,e){let t=n;do{const i=t.prev,s=t.next.next;!Co(i,s)&&CS(i,t,t.next,s)&&$l(i,s)&&$l(s,i)&&(e.push(i.i,t.i,s.i),Wl(t),Wl(t.next),t=n=s),t=t.next}while(t!==n);return cr(t)}function $A(n,e,t,i,s,a){let r=n;do{let o=r.next.next;for(;o!==r.prev;){if(r.i!==o.i&&QA(r,o)){let l=AS(r,o);r=cr(r,r.next),l=cr(l,l.next),Gl(r,e,t,i,s,a,0),Gl(l,e,t,i,s,a,0);return}o=o.next}r=r.next}while(r!==n)}function WA(n,e,t,i){const s=[];for(let a=0,r=e.length;a=t.next.y&&t.next.y!==t.y){const d=t.x+(s-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(d<=i&&d>a&&(a=d,r=t.x=t.x&&t.x>=l&&i!==t.x&&ES(sr.x||t.x===r.x&&YA(r,t)))&&(r=t,u=d)}t=t.next}while(t!==o);return r}function YA(n,e){return Kt(n.prev,n,e.prev)<0&&Kt(e.next,n,n.next)<0}function jA(n,e,t,i){let s=n;do s.z===0&&(s.z=Tm(s.x,s.y,e,t,i)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next;while(s!==n);s.prevZ.nextZ=null,s.prevZ=null,ZA(s)}function ZA(n){let e,t=1;do{let i=n,s;n=null;let a=null;for(e=0;i;){e++;let r=i,o=0;for(let c=0;c0||l>0&&r;)o!==0&&(l===0||!r||i.z<=r.z)?(s=i,i=i.nextZ,o--):(s=r,r=r.nextZ,l--),a?a.nextZ=s:n=s,s.prevZ=a,a=s;i=r}a.nextZ=null,t*=2}while(e>1);return n}function Tm(n,e,t,i,s){return n=(n-t)*s|0,e=(e-i)*s|0,n=(n|n<<8)&16711935,n=(n|n<<4)&252645135,n=(n|n<<2)&858993459,n=(n|n<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,n|e<<1}function JA(n){let e=n,t=n;do(e.x=(n-r)*(a-o)&&(n-r)*(i-o)>=(t-r)*(e-o)&&(t-r)*(a-o)>=(s-r)*(i-o)}function hl(n,e,t,i,s,a,r,o){return!(n===r&&e===o)&&ES(n,e,t,i,s,a,r,o)}function QA(n,e){return n.next.i!==e.i&&n.prev.i!==e.i&&!eR(n,e)&&($l(n,e)&&$l(e,n)&&tR(n,e)&&(Kt(n.prev,n,e.prev)||Kt(n,e.prev,e))||Co(n,e)&&Kt(n.prev,n,n.next)>0&&Kt(e.prev,e,e.next)>0)}function Kt(n,e,t){return(e.y-n.y)*(t.x-e.x)-(e.x-n.x)*(t.y-e.y)}function Co(n,e){return n.x===e.x&&n.y===e.y}function CS(n,e,t,i){const s=Zc(Kt(n,e,t)),a=Zc(Kt(n,e,i)),r=Zc(Kt(t,i,n)),o=Zc(Kt(t,i,e));return!!(s!==a&&r!==o||s===0&&jc(n,t,e)||a===0&&jc(n,i,e)||r===0&&jc(t,n,i)||o===0&&jc(t,e,i))}function jc(n,e,t){return e.x<=Math.max(n.x,t.x)&&e.x>=Math.min(n.x,t.x)&&e.y<=Math.max(n.y,t.y)&&e.y>=Math.min(n.y,t.y)}function Zc(n){return n>0?1:n<0?-1:0}function eR(n,e){let t=n;do{if(t.i!==n.i&&t.next.i!==n.i&&t.i!==e.i&&t.next.i!==e.i&&CS(t,t.next,n,e))return!0;t=t.next}while(t!==n);return!1}function $l(n,e){return Kt(n.prev,n,n.next)<0?Kt(n,e,n.next)>=0&&Kt(n,n.prev,e)>=0:Kt(n,e,n.prev)<0||Kt(n,n.next,e)<0}function tR(n,e){let t=n,i=!1;const s=(n.x+e.x)/2,a=(n.y+e.y)/2;do t.y>a!=t.next.y>a&&t.next.y!==t.y&&s<(t.next.x-t.x)*(a-t.y)/(t.next.y-t.y)+t.x&&(i=!i),t=t.next;while(t!==n);return i}function AS(n,e){const t=Mm(n.i,n.x,n.y),i=Mm(e.i,e.x,e.y),s=n.next,a=e.prev;return n.next=e,e.prev=n,t.next=s,s.prev=t,i.next=t,t.prev=i,a.next=i,i.prev=a,i}function Yy(n,e,t,i){const s=Mm(n,e,t);return i?(s.next=i.next,s.prev=i,i.next.prev=s,i.next=s):(s.prev=s,s.next=s),s}function Wl(n){n.next.prev=n.prev,n.prev.next=n.next,n.prevZ&&(n.prevZ.nextZ=n.nextZ),n.nextZ&&(n.nextZ.prevZ=n.prevZ)}function Mm(n,e,t){return{i:n,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function nR(n,e,t,i){let s=0;for(let a=e,r=t-i;a2&&n[e-1].equals(n[0])&&n.pop()}function Zy(n,e){for(let t=0;tNumber.EPSILON){const J=Math.sqrt(A),le=Math.sqrt(it*it+I*I),ee=j.x-$e/J,He=j.y+ge/J,ye=Y.x-I/le,Ue=Y.y+it/le,Be=((ye-ee)*I-(Ue-He)*it)/(ge*I-$e*it);Q=ee+ge*Be-G.x,_e=He+$e*Be-G.y;const de=Q*Q+_e*_e;if(de<=2)return new te(Q,_e);ce=Math.sqrt(de/2)}else{let J=!1;ge>Number.EPSILON?it>Number.EPSILON&&(J=!0):ge<-Number.EPSILON?it<-Number.EPSILON&&(J=!0):Math.sign($e)===Math.sign(I)&&(J=!0),J?(Q=-$e,_e=ge,ce=Math.sqrt(A)):(Q=ge,_e=$e,ce=Math.sqrt(A/2))}return new te(Q/ce,_e/ce)}const ne=[];for(let G=0,j=U.length,Y=j-1,Q=G+1;G=0;G--){const j=G/_,Y=f*Math.cos(j*Math.PI/2),Q=p*Math.sin(j*Math.PI/2)+g;for(let _e=0,ce=U.length;_e=0;){const Q=Y;let _e=Y-1;_e<0&&(_e=G.length-1);for(let ce=0,ge=u+_*2;ce0)&&f.push(y,b,x),(m!==i-1||l0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class Ya extends Qt{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new ue(16777215),this.specular=new ue(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ue(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ha,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new an,this.combine=nc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class IS extends Qt{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new ue(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ue(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ha,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class LS extends Qt{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ha,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class qh extends Qt{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new ue(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ue(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ha,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new an,this.combine=nc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class dg extends Qt{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=Qw,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class hg extends Qt{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class DS extends Qt{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new ue(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ha,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}class kS extends Rt{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}function ja(n,e){return!n||n.constructor===e?n:typeof e.BYTES_PER_ELEMENT=="number"?new e(n):Array.prototype.slice.call(n)}function OS(n){return ArrayBuffer.isView(n)&&!(n instanceof DataView)}function FS(n){function e(s,a){return n[s]-n[a]}const t=n.length,i=new Array(t);for(let s=0;s!==t;++s)i[s]=s;return i.sort(e),i}function Em(n,e,t){const i=n.length,s=new n.constructor(i);for(let a=0,r=0;r!==i;++a){const o=t[a]*e;for(let l=0;l!==e;++l)s[r++]=n[o+l]}return s}function fg(n,e,t,i){let s=1,a=n[0];for(;a!==void 0&&a[i]===void 0;)a=n[s++];if(a===void 0)return;let r=a[i];if(r!==void 0)if(Array.isArray(r))do r=a[i],r!==void 0&&(e.push(a.time),t.push(...r)),a=n[s++];while(a!==void 0);else if(r.toArray!==void 0)do r=a[i],r!==void 0&&(e.push(a.time),r.toArray(t,t.length)),a=n[s++];while(a!==void 0);else do r=a[i],r!==void 0&&(e.push(a.time),t.push(r)),a=n[s++];while(a!==void 0)}function oR(n,e,t,i,s=30){const a=n.clone();a.name=e;const r=[];for(let l=0;l=i)){d.push(c.times[f]);for(let g=0;ga.tracks[l].times[0]&&(o=a.tracks[l].times[0]);for(let l=0;l=o.times[p]){const m=p*d+u,v=m+d-u;g=o.values.slice(m,v)}else{const m=o.createInterpolant(),v=u,y=d-u;m.evaluate(a),g=m.resultBuffer.slice(v,y)}l==="quaternion"&&new dt().fromArray(g).normalize().conjugate().toArray(g);const _=c.times.length;for(let m=0;m<_;++m){const v=m*f+h;if(l==="quaternion")dt.multiplyQuaternionsFlat(c.values,v,g,0,c.values,v);else{const y=f-h*2;for(let b=0;b=a)){const o=t[1];e=a)break t}r=i,i=0;break n}break e}for(;i>>1;et;)--r;if(++r,a!==0||r!==s){a>=r&&(r=Math.max(r,1),a=r-1);const o=this.getValueSize();this.times=i.slice(a,r),this.values=this.values.slice(a*o,r*o)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const i=this.times,s=this.values,a=i.length;a===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let r=null;for(let o=0;o!==a;o++){const l=i[o];if(typeof l=="number"&&isNaN(l)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,o,l),e=!1;break}if(r!==null&&r>l){console.error("THREE.KeyframeTrack: Out of order keys.",this,o,l,r),e=!1;break}r=l}if(s!==void 0&&OS(s))for(let o=0,l=s.length;o!==l;++o){const c=s[o];if(isNaN(c)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,o,c),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),i=this.getValueSize(),s=this.getInterpolation()===Vu,a=e.length-1;let r=1;for(let o=1;o0){e[r]=e[a];for(let o=a*i,l=r*i,c=0;c!==i;++c)t[l+c]=t[o+c];++r}return r!==e.length?(this.times=e.slice(0,r),this.values=t.slice(0,r*i)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),i=this.constructor,s=new i(this.name,e,t);return s.createInterpolant=this.createInterpolant,s}}Pi.prototype.ValueTypeName="";Pi.prototype.TimeBufferType=Float32Array;Pi.prototype.ValueBufferType=Float32Array;Pi.prototype.DefaultInterpolation=rr;class pr extends Pi{constructor(e,t,i){super(e,t,i)}}pr.prototype.ValueTypeName="bool";pr.prototype.ValueBufferType=Array;pr.prototype.DefaultInterpolation=wo;pr.prototype.InterpolantFactoryMethodLinear=void 0;pr.prototype.InterpolantFactoryMethodSmooth=void 0;class mg extends Pi{constructor(e,t,i,s){super(e,t,i,s)}}mg.prototype.ValueTypeName="color";class ca extends Pi{constructor(e,t,i,s){super(e,t,i,s)}}ca.prototype.ValueTypeName="number";class BS extends Lo{constructor(e,t,i,s){super(e,t,i,s)}interpolate_(e,t,i,s){const a=this.resultBuffer,r=this.sampleValues,o=this.valueSize,l=(i-t)/(s-t);let c=e*o;for(let u=c+o;c!==u;c+=4)dt.slerpFlat(a,0,r,c-o,r,c,l);return a}}class _s extends Pi{constructor(e,t,i,s){super(e,t,i,s)}InterpolantFactoryMethodLinear(e){return new BS(this.times,this.values,this.getValueSize(),e)}}_s.prototype.ValueTypeName="quaternion";_s.prototype.InterpolantFactoryMethodSmooth=void 0;class mr extends Pi{constructor(e,t,i){super(e,t,i)}}mr.prototype.ValueTypeName="string";mr.prototype.ValueBufferType=Array;mr.prototype.DefaultInterpolation=wo;mr.prototype.InterpolantFactoryMethodLinear=void 0;mr.prototype.InterpolantFactoryMethodSmooth=void 0;class Hs extends Pi{constructor(e,t,i,s){super(e,t,i,s)}}Hs.prototype.ValueTypeName="vector";class ua{constructor(e="",t=-1,i=[],s=Sh){this.name=e,this.tracks=i,this.duration=t,this.blendMode=s,this.uuid=pi(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){const t=[],i=e.tracks,s=1/(e.fps||1);for(let r=0,o=i.length;r!==o;++r)t.push(dR(i[r]).scale(s));const a=new this(e.name,e.duration,t,e.blendMode);return a.uuid=e.uuid,a.userData=JSON.parse(e.userData||"{}"),a}static toJSON(e){const t=[],i=e.tracks,s={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let a=0,r=i.length;a!==r;++a)t.push(Pi.toJSON(i[a]));return s}static CreateFromMorphTargetSequence(e,t,i,s){const a=t.length,r=[];for(let o=0;o1){const d=u[1];let h=s[d];h||(s[d]=h=[]),h.push(c)}}const r=[];for(const o in s)r.push(this.CreateFromMorphTargetSequence(o,s[o],t,i));return r}static parseAnimation(e,t){if(console.warn("THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const i=function(d,h,f,p,g){if(f.length!==0){const _=[],m=[];fg(f,_,m,p),_.length!==0&&g.push(new d(h,_,m))}},s=[],a=e.name||"default",r=e.fps||30,o=e.blendMode;let l=e.length||-1;const c=e.hierarchy||[];for(let d=0;d{t&&t(a),this.manager.itemEnd(e)},0),a;if(Ts[e]!==void 0){Ts[e].push({onLoad:t,onProgress:i,onError:s});return}Ts[e]=[],Ts[e].push({onLoad:t,onProgress:i,onError:s});const r=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,l=this.responseType;fetch(r).then(c=>{if(c.status===200||c.status===0){if(c.status===0&&console.warn("THREE.FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||c.body===void 0||c.body.getReader===void 0)return c;const u=Ts[e],d=c.body.getReader(),h=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),f=h?parseInt(h):0,p=f!==0;let g=0;const _=new ReadableStream({start(m){v();function v(){d.read().then(({done:y,value:b})=>{if(y)m.close();else{g+=b.byteLength;const T=new ProgressEvent("progress",{lengthComputable:p,loaded:g,total:f});for(let x=0,M=u.length;x{m.error(y)})}}});return new Response(_)}else throw new hR(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`,c)}).then(c=>{switch(l){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then(u=>new DOMParser().parseFromString(u,o));case"json":return c.json();default:if(o==="")return c.text();{const d=/charset="?([^;"\s]*)"?/i.exec(o),h=d&&d[1]?d[1].toLowerCase():void 0,f=new TextDecoder(h);return c.arrayBuffer().then(p=>f.decode(p))}}}).then(c=>{cs.add(`file:${e}`,c);const u=Ts[e];delete Ts[e];for(let d=0,h=u.length;d{const u=Ts[e];if(u===void 0)throw this.manager.itemError(e),c;delete Ts[e];for(let d=0,h=u.length;d{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}class fR extends on{constructor(e){super(e)}load(e,t,i,s){const a=this,r=new Gn(this.manager);r.setPath(this.path),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,function(o){try{t(a.parse(JSON.parse(o)))}catch(l){s?s(l):console.error(l),a.manager.itemError(e)}},i,s)}parse(e){const t=[];for(let i=0;i0:s.vertexColors=e.vertexColors),e.uniforms!==void 0)for(const a in e.uniforms){const r=e.uniforms[a];switch(s.uniforms[a]={},r.type){case"t":s.uniforms[a].value=i(r.value);break;case"c":s.uniforms[a].value=new ue().setHex(r.value);break;case"v2":s.uniforms[a].value=new te().fromArray(r.value);break;case"v3":s.uniforms[a].value=new S().fromArray(r.value);break;case"v4":s.uniforms[a].value=new qe().fromArray(r.value);break;case"m3":s.uniforms[a].value=new st().fromArray(r.value);break;case"m4":s.uniforms[a].value=new Me().fromArray(r.value);break;default:s.uniforms[a].value=r.value}}if(e.defines!==void 0&&(s.defines=e.defines),e.vertexShader!==void 0&&(s.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(s.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(s.glslVersion=e.glslVersion),e.extensions!==void 0)for(const a in e.extensions)s.extensions[a]=e.extensions[a];if(e.lights!==void 0&&(s.lights=e.lights),e.clipping!==void 0&&(s.clipping=e.clipping),e.size!==void 0&&(s.size=e.size),e.sizeAttenuation!==void 0&&(s.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(s.map=i(e.map)),e.matcap!==void 0&&(s.matcap=i(e.matcap)),e.alphaMap!==void 0&&(s.alphaMap=i(e.alphaMap)),e.bumpMap!==void 0&&(s.bumpMap=i(e.bumpMap)),e.bumpScale!==void 0&&(s.bumpScale=e.bumpScale),e.normalMap!==void 0&&(s.normalMap=i(e.normalMap)),e.normalMapType!==void 0&&(s.normalMapType=e.normalMapType),e.normalScale!==void 0){let a=e.normalScale;Array.isArray(a)===!1&&(a=[a,a]),s.normalScale=new te().fromArray(a)}return e.displacementMap!==void 0&&(s.displacementMap=i(e.displacementMap)),e.displacementScale!==void 0&&(s.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(s.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(s.roughnessMap=i(e.roughnessMap)),e.metalnessMap!==void 0&&(s.metalnessMap=i(e.metalnessMap)),e.emissiveMap!==void 0&&(s.emissiveMap=i(e.emissiveMap)),e.emissiveIntensity!==void 0&&(s.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(s.specularMap=i(e.specularMap)),e.specularIntensityMap!==void 0&&(s.specularIntensityMap=i(e.specularIntensityMap)),e.specularColorMap!==void 0&&(s.specularColorMap=i(e.specularColorMap)),e.envMap!==void 0&&(s.envMap=i(e.envMap)),e.envMapRotation!==void 0&&s.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(s.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(s.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(s.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(s.lightMap=i(e.lightMap)),e.lightMapIntensity!==void 0&&(s.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(s.aoMap=i(e.aoMap)),e.aoMapIntensity!==void 0&&(s.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(s.gradientMap=i(e.gradientMap)),e.clearcoatMap!==void 0&&(s.clearcoatMap=i(e.clearcoatMap)),e.clearcoatRoughnessMap!==void 0&&(s.clearcoatRoughnessMap=i(e.clearcoatRoughnessMap)),e.clearcoatNormalMap!==void 0&&(s.clearcoatNormalMap=i(e.clearcoatNormalMap)),e.clearcoatNormalScale!==void 0&&(s.clearcoatNormalScale=new te().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(s.iridescenceMap=i(e.iridescenceMap)),e.iridescenceThicknessMap!==void 0&&(s.iridescenceThicknessMap=i(e.iridescenceThicknessMap)),e.transmissionMap!==void 0&&(s.transmissionMap=i(e.transmissionMap)),e.thicknessMap!==void 0&&(s.thicknessMap=i(e.thicknessMap)),e.anisotropyMap!==void 0&&(s.anisotropyMap=i(e.anisotropyMap)),e.sheenColorMap!==void 0&&(s.sheenColorMap=i(e.sheenColorMap)),e.sheenRoughnessMap!==void 0&&(s.sheenRoughnessMap=i(e.sheenRoughnessMap)),s}setTextures(e){return this.textures=e,this}createMaterialFromType(e){return Zh.createMaterialFromType(e)}static createMaterialFromType(e){const t={ShadowMaterial:RS,SpriteMaterial:Ih,RawShaderMaterial:PS,ShaderMaterial:ti,PointsMaterial:sa,MeshPhysicalMaterial:ii,MeshStandardMaterial:Pn,MeshPhongMaterial:Ya,MeshToonMaterial:IS,MeshNormalMaterial:LS,MeshLambertMaterial:qh,MeshDepthMaterial:dg,MeshDistanceMaterial:hg,MeshBasicMaterial:Ye,MeshMatcapMaterial:DS,LineDashedMaterial:kS,LineBasicMaterial:Rt,Material:Qt};return new t[e]}}class Us{static extractUrlBase(e){const t=e.lastIndexOf("/");return t===-1?"./":e.slice(0,t+1)}static resolveURL(e,t){return typeof e!="string"||e===""?"":(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}}class XS extends Ge{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){const e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}}class KS extends on{constructor(e){super(e)}load(e,t,i,s){const a=this,r=new Gn(a.manager);r.setPath(a.path),r.setRequestHeader(a.requestHeader),r.setWithCredentials(a.withCredentials),r.load(e,function(o){try{t(a.parse(JSON.parse(o)))}catch(l){s?s(l):console.error(l),a.manager.itemError(e)}},i,s)}parse(e){const t={},i={};function s(f,p){if(t[p]!==void 0)return t[p];const _=f.interleavedBuffers[p],m=a(f,_.buffer),v=Yr(_.type,m),y=new rc(v,_.stride);return y.uuid=_.uuid,t[p]=y,y}function a(f,p){if(i[p]!==void 0)return i[p];const _=f.arrayBuffers[p],m=new Uint32Array(_).buffer;return i[p]=m,m}const r=e.isInstancedBufferGeometry?new XS:new Ge,o=e.data.index;if(o!==void 0){const f=Yr(o.type,o.array);r.setIndex(new rt(f,1))}const l=e.data.attributes;for(const f in l){const p=l[f];let g;if(p.isInterleavedBufferAttribute){const _=s(e.data,p.data);g=new la(_,p.itemSize,p.offset,p.normalized)}else{const _=Yr(p.type,p.array),m=p.isInstancedBufferAttribute?or:rt;g=new m(_,p.itemSize,p.normalized)}p.name!==void 0&&(g.name=p.name),p.usage!==void 0&&g.setUsage(p.usage),r.setAttribute(f,g)}const c=e.data.morphAttributes;if(c)for(const f in c){const p=c[f],g=[];for(let _=0,m=p.length;_0){const l=new _g(t);a=new Xl(l),a.setCrossOrigin(this.crossOrigin);for(let c=0,u=e.length;c0){s=new Xl(this.manager),s.setCrossOrigin(this.crossOrigin);for(let r=0,o=e.length;r{let _=null,m=null;return g.boundingBox!==void 0&&(_=new vn().fromJSON(g.boundingBox)),g.boundingSphere!==void 0&&(m=new bn().fromJSON(g.boundingSphere)),{...g,boundingBox:_,boundingSphere:m}}),r._instanceInfo=e.instanceInfo,r._availableInstanceIds=e._availableInstanceIds,r._availableGeometryIds=e._availableGeometryIds,r._nextIndexStart=e.nextIndexStart,r._nextVertexStart=e.nextVertexStart,r._geometryCount=e.geometryCount,r._maxInstanceCount=e.maxInstanceCount,r._maxVertexCount=e.maxVertexCount,r._maxIndexCount=e.maxIndexCount,r._geometryInitialized=e.geometryInitialized,r._matricesTexture=c(e.matricesTexture.uuid),r._indirectTexture=c(e.indirectTexture.uuid),e.colorsTexture!==void 0&&(r._colorsTexture=c(e.colorsTexture.uuid)),e.boundingSphere!==void 0&&(r.boundingSphere=new bn().fromJSON(e.boundingSphere)),e.boundingBox!==void 0&&(r.boundingBox=new vn().fromJSON(e.boundingBox));break;case"LOD":r=new yS;break;case"Line":r=new In(o(e.geometry),l(e.material));break;case"LineLoop":r=new eg(o(e.geometry),l(e.material));break;case"LineSegments":r=new Ln(o(e.geometry),l(e.material));break;case"PointCloud":case"Points":r=new ir(o(e.geometry),l(e.material));break;case"Sprite":r=new Lh(l(e.material));break;case"Group":r=new Mt;break;case"Bone":r=new Eo;break;default:r=new Qe}if(r.uuid=e.uuid,e.name!==void 0&&(r.name=e.name),e.matrix!==void 0?(r.matrix.fromArray(e.matrix),e.matrixAutoUpdate!==void 0&&(r.matrixAutoUpdate=e.matrixAutoUpdate),r.matrixAutoUpdate&&r.matrix.decompose(r.position,r.quaternion,r.scale)):(e.position!==void 0&&r.position.fromArray(e.position),e.rotation!==void 0&&r.rotation.fromArray(e.rotation),e.quaternion!==void 0&&r.quaternion.fromArray(e.quaternion),e.scale!==void 0&&r.scale.fromArray(e.scale)),e.up!==void 0&&r.up.fromArray(e.up),e.castShadow!==void 0&&(r.castShadow=e.castShadow),e.receiveShadow!==void 0&&(r.receiveShadow=e.receiveShadow),e.shadow&&(e.shadow.intensity!==void 0&&(r.shadow.intensity=e.shadow.intensity),e.shadow.bias!==void 0&&(r.shadow.bias=e.shadow.bias),e.shadow.normalBias!==void 0&&(r.shadow.normalBias=e.shadow.normalBias),e.shadow.radius!==void 0&&(r.shadow.radius=e.shadow.radius),e.shadow.mapSize!==void 0&&r.shadow.mapSize.fromArray(e.shadow.mapSize),e.shadow.camera!==void 0&&(r.shadow.camera=this.parseObject(e.shadow.camera))),e.visible!==void 0&&(r.visible=e.visible),e.frustumCulled!==void 0&&(r.frustumCulled=e.frustumCulled),e.renderOrder!==void 0&&(r.renderOrder=e.renderOrder),e.userData!==void 0&&(r.userData=e.userData),e.layers!==void 0&&(r.layers.mask=e.layers),e.children!==void 0){const h=e.children;for(let f=0;f"u"&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,i,s){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const a=this,r=cs.get(`image-bitmap:${e}`);if(r!==void 0){if(a.manager.itemStart(e),r.then){r.then(c=>{if(Kf.has(r)===!0)s&&s(Kf.get(r)),a.manager.itemError(e),a.manager.itemEnd(e);else return t&&t(c),a.manager.itemEnd(e),c});return}return setTimeout(function(){t&&t(r),a.manager.itemEnd(e)},0),r}const o={};o.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",o.headers=this.requestHeader,o.signal=typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;const l=fetch(e,o).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign(a.options,{colorSpaceConversion:"none"}))}).then(function(c){return cs.add(`image-bitmap:${e}`,c),t&&t(c),a.manager.itemEnd(e),c}).catch(function(c){s&&s(c),Kf.set(l,c),cs.remove(`image-bitmap:${e}`),a.manager.itemError(e),a.manager.itemEnd(e)});cs.add(`image-bitmap:${e}`,l),a.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}let Jc;class yg{static getContext(){return Jc===void 0&&(Jc=new(window.AudioContext||window.webkitAudioContext)),Jc}static setContext(e){Jc=e}}class xR extends on{constructor(e){super(e)}load(e,t,i,s){const a=this,r=new Gn(this.manager);r.setResponseType("arraybuffer"),r.setPath(this.path),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,function(l){try{const c=l.slice(0);yg.getContext().decodeAudioData(c,function(d){t(d)}).catch(o)}catch(c){o(c)}},i,s);function o(l){s?s(l):console.error(l),a.manager.itemError(e)}}}const a0=new Me,r0=new Me,Sa=new Me;class wR{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new Jt,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Jt,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){const t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,Sa.copy(e.projectionMatrix);const s=t.eyeSep/2,a=s*t.near/t.focus,r=t.near*Math.tan(nr*t.fov*.5)/t.zoom;let o,l;r0.elements[12]=-s,a0.elements[12]=s,o=-r*t.aspect+a,l=r*t.aspect+a,Sa.elements[0]=2*t.near/(l-o),Sa.elements[8]=(l+o)/(l-o),this.cameraL.projectionMatrix.copy(Sa),o=-r*t.aspect-a,l=r*t.aspect-a,Sa.elements[0]=2*t.near/(l-o),Sa.elements[8]=(l+o)/(l-o),this.cameraR.projectionMatrix.copy(Sa)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(r0),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(a0)}}class YS extends Jt{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class vg{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}const Ta=new S,qf=new dt,SR=new S,Ma=new S,Ea=new S;class TR extends Qe{constructor(){super(),this.type="AudioListener",this.context=yg.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new vg}getInput(){return this.gain}removeFilter(){return this.filter!==null&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return this.filter!==null?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e);const t=this.context.listener;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(Ta,qf,SR),Ma.set(0,0,-1).applyQuaternion(qf),Ea.set(0,1,0).applyQuaternion(qf),t.positionX){const i=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(Ta.x,i),t.positionY.linearRampToValueAtTime(Ta.y,i),t.positionZ.linearRampToValueAtTime(Ta.z,i),t.forwardX.linearRampToValueAtTime(Ma.x,i),t.forwardY.linearRampToValueAtTime(Ma.y,i),t.forwardZ.linearRampToValueAtTime(Ma.z,i),t.upX.linearRampToValueAtTime(Ea.x,i),t.upY.linearRampToValueAtTime(Ea.y,i),t.upZ.linearRampToValueAtTime(Ea.z,i)}else t.setPosition(Ta.x,Ta.y,Ta.z),t.setOrientation(Ma.x,Ma.y,Ma.z,Ea.x,Ea.y,Ea.z)}}class jS extends Qe{constructor(e){super(),this.type="Audio",this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType="buffer",this.autoplay&&this.play(),this}play(e=0){if(this.isPlaying===!0){console.warn("THREE.Audio: Audio is already playing.");return}if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}this._startedAt=this.context.currentTime+e;const t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.isPlaying===!0&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this}stop(e=0){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this._progress=0,this.source!==null&&(this.source.stop(this.context.currentTime+e),this.source.onended=null),this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(i,s,this._addIndex*t,1,t);for(let l=t,c=t+t;l!==c;++l)if(i[l]!==i[l+t]){o.setValue(i,s);break}}saveOriginalState(){const e=this.binding,t=this.buffer,i=this.valueSize,s=i*this._origIndex;e.getValue(t,s);for(let a=i,r=s;a!==r;++a)t[a]=t[s+a%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let i=e;i=.5)for(let r=0;r!==a;++r)e[t+r]=e[i+r]}_slerp(e,t,i,s){dt.slerpFlat(e,t,e,t,e,i,s)}_slerpAdditive(e,t,i,s,a){const r=this._workIndex*a;dt.multiplyQuaternionsFlat(e,r,e,t,e,i),dt.slerpFlat(e,t,e,t,e,r,s)}_lerp(e,t,i,s,a){const r=1-s;for(let o=0;o!==a;++o){const l=t+o;e[l]=e[l]*r+e[i+o]*s}}_lerpAdditive(e,t,i,s,a){for(let r=0;r!==a;++r){const o=t+r;e[o]=e[o]+e[i+r]*s}}}const bg="\\[\\]\\.:\\/",AR=new RegExp("["+bg+"]","g"),xg="[^"+bg+"]",RR="[^"+bg.replace("\\.","")+"]",PR=/((?:WC+[\/:])*)/.source.replace("WC",xg),IR=/(WCOD+)?/.source.replace("WCOD",RR),LR=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",xg),DR=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",xg),kR=new RegExp("^"+PR+IR+LR+DR+"$"),OR=["material","materials","bones","map"];class FR{constructor(e,t,i){const s=i||yt.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,s)}getValue(e,t){this.bind();const i=this._targetGroup.nCachedObjects_,s=this._bindings[i];s!==void 0&&s.getValue(e,t)}setValue(e,t){const i=this._bindings;for(let s=this._targetGroup.nCachedObjects_,a=i.length;s!==a;++s)i[s].setValue(e,t)}bind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].bind()}unbind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].unbind()}}class yt{constructor(e,t,i){this.path=t,this.parsedPath=i||yt.parseTrackName(t),this.node=yt.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,i){return e&&e.isAnimationObjectGroup?new yt.Composite(e,t,i):new yt(e,t,i)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(AR,"")}static parseTrackName(e){const t=kR.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const i={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},s=i.nodeName&&i.nodeName.lastIndexOf(".");if(s!==void 0&&s!==-1){const a=i.nodeName.substring(s+1);OR.indexOf(a)!==-1&&(i.nodeName=i.nodeName.substring(0,s),i.objectName=a)}if(i.propertyName===null||i.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return i}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){const i=e.skeleton.getBoneByName(t);if(i!==void 0)return i}if(e.children){const i=function(a){for(let r=0;r=a){const d=a++,h=e[d];t[h.uuid]=u,e[u]=h,t[c]=d,e[d]=l;for(let f=0,p=s;f!==p;++f){const g=i[f],_=g[d],m=g[u];g[u]=_,g[d]=m}}}this.nCachedObjects_=a}uncache(){const e=this._objects,t=this._indicesByUUID,i=this._bindings,s=i.length;let a=this.nCachedObjects_,r=e.length;for(let o=0,l=arguments.length;o!==l;++o){const c=arguments[o],u=c.uuid,d=t[u];if(d!==void 0)if(delete t[u],d0&&(t[f.uuid]=d),e[d]=f,e.pop();for(let p=0,g=s;p!==g;++p){const _=i[p];_[d]=_[h],_.pop()}}}this.nCachedObjects_=a}subscribe_(e,t){const i=this._bindingsIndicesByPath;let s=i[e];const a=this._bindings;if(s!==void 0)return a[s];const r=this._paths,o=this._parsedPaths,l=this._objects,c=l.length,u=this.nCachedObjects_,d=new Array(c);s=a.length,i[e]=s,r.push(e),o.push(t),a.push(d);for(let h=u,f=l.length;h!==f;++h){const p=l[h];d[h]=new yt(p,e,t)}return d}unsubscribe_(e){const t=this._bindingsIndicesByPath,i=t[e];if(i!==void 0){const s=this._paths,a=this._parsedPaths,r=this._bindings,o=r.length-1,l=r[o],c=e[o];t[c]=i,r[i]=l,r.pop(),a[i]=a[o],a.pop(),s[i]=s[o],s.pop()}}}class JS{constructor(e,t,i=null,s=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=i,this.blendMode=s;const a=t.tracks,r=a.length,o=new Array(r),l={endingStart:Ka,endingEnd:Ka};for(let c=0;c!==r;++c){const u=a[c].createInterpolant(null);o[c]=u,u.settings=l}this._interpolantSettings=l,this._interpolants=o,this._propertyBindings=new Array(r),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=jw,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,i=!1){if(e.fadeOut(t),this.fadeIn(t),i===!0){const s=this._clip.duration,a=e._clip.duration,r=a/s,o=s/a;e.warp(1,r,t),this.warp(o,1,t)}return this}crossFadeTo(e,t,i=!1){return e.crossFadeFrom(this,t,i)}stopFading(){const e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,i){const s=this._mixer,a=s.time,r=this.timeScale;let o=this._timeScaleInterpolant;o===null&&(o=s._lendControlInterpolant(),this._timeScaleInterpolant=o);const l=o.parameterPositions,c=o.sampleValues;return l[0]=a,l[1]=a+i,c[0]=e/r,c[1]=t/r,this}stopWarping(){const e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,i,s){if(!this.enabled){this._updateWeight(e);return}const a=this._startTime;if(a!==null){const l=(e-a)*i;l<0||i===0?t=0:(this._startTime=null,t=i*l)}t*=this._updateTimeScale(e);const r=this._updateTime(t),o=this._updateWeight(e);if(o>0){const l=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case q_:for(let u=0,d=l.length;u!==d;++u)l[u].evaluate(r),c[u].accumulateAdditive(o);break;case Sh:default:for(let u=0,d=l.length;u!==d;++u)l[u].evaluate(r),c[u].accumulate(s,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const i=this._weightInterpolant;if(i!==null){const s=i.evaluate(e)[0];t*=s,e>i.parameterPositions[1]&&(this.stopFading(),s===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const i=this._timeScaleInterpolant;if(i!==null){const s=i.evaluate(e)[0];t*=s,e>i.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,i=this.loop;let s=this.time+e,a=this._loopCount;const r=i===Zw;if(e===0)return a===-1?s:r&&(a&1)===1?t-s:s;if(i===Xd){a===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(s>=t)s=t;else if(s<0)s=0;else{this.time=s;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(a===-1&&(e>=0?(a=0,this._setEndings(!0,this.repetitions===0,r)):this._setEndings(this.repetitions===0,!0,r)),s>=t||s<0){const o=Math.floor(s/t);s-=t*o,a+=Math.abs(o);const l=this.repetitions-a;if(l<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,s=e>0?t:0,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(l===1){const c=e<0;this._setEndings(c,!c,r)}else this._setEndings(!1,!1,r);this._loopCount=a,this.time=s,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this.time=s;if(r&&(a&1)===1)return t-s}return s}_setEndings(e,t,i){const s=this._interpolantSettings;i?(s.endingStart=qa,s.endingEnd=qa):(e?s.endingStart=this.zeroSlopeAtStart?qa:Ka:s.endingStart=Ul,t?s.endingEnd=this.zeroSlopeAtEnd?qa:Ka:s.endingEnd=Ul)}_scheduleFading(e,t,i){const s=this._mixer,a=s.time;let r=this._weightInterpolant;r===null&&(r=s._lendControlInterpolant(),this._weightInterpolant=r);const o=r.parameterPositions,l=r.sampleValues;return o[0]=a,l[0]=t,o[1]=a+e,l[1]=i,this}}const UR=new Float32Array(1);class QS extends gs{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const i=e._localRoot||this._root,s=e._clip.tracks,a=s.length,r=e._propertyBindings,o=e._interpolants,l=i.uuid,c=this._bindingsByRootAndName;let u=c[l];u===void 0&&(u={},c[l]=u);for(let d=0;d!==a;++d){const h=s[d],f=h.name;let p=u[f];if(p!==void 0)++p.referenceCount,r[d]=p;else{if(p=r[d],p!==void 0){p._cacheIndex===null&&(++p.referenceCount,this._addInactiveBinding(p,l,f));continue}const g=t&&t._propertyBindings[d].binding.parsedPath;p=new ZS(yt.create(i,f,g),h.ValueTypeName,h.getValueSize()),++p.referenceCount,this._addInactiveBinding(p,l,f),r[d]=p}o[d].resultBuffer=p.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){const i=(e._localRoot||this._root).uuid,s=e._clip.uuid,a=this._actionsByClip[s];this._bindAction(e,a&&a.knownActions[0]),this._addInactiveAction(e,s,i)}const t=e._propertyBindings;for(let i=0,s=t.length;i!==s;++i){const a=t[i];a.useCount++===0&&(this._lendBinding(a),a.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let i=0,s=t.length;i!==s;++i){const a=t[i];--a.useCount===0&&(a.restoreOriginalState(),this._takeBackBinding(a))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return t!==null&&t=0;--i)e[i].stop();return this}update(e){e*=this.timeScale;const t=this._actions,i=this._nActiveActions,s=this.time+=e,a=Math.sign(e),r=this._accuIndex^=1;for(let c=0;c!==i;++c)t[c]._update(s,e,a,r);const o=this._bindings,l=this._nActiveBindings;for(let c=0;c!==l;++c)o[c].apply(r);return this}setTime(e){this.time=0;for(let t=0;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,u0).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const d0=new S,Qc=new S,Fr=new S,Nr=new S,Yf=new S,YR=new S,jR=new S;class ZR{constructor(e=new S,t=new S){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){d0.subVectors(e,this.start),Qc.subVectors(this.end,this.start);const i=Qc.dot(Qc);let a=Qc.dot(d0)/i;return t&&(a=Ze(a,0,1)),a}closestPointToPoint(e,t,i){const s=this.closestPointToPointParameter(e,t);return this.delta(i).multiplyScalar(s).add(this.start)}distanceSqToLine3(e,t=YR,i=jR){const s=10000000000000001e-32;let a,r;const o=this.start,l=e.start,c=this.end,u=e.end;Fr.subVectors(c,o),Nr.subVectors(u,l),Yf.subVectors(o,l);const d=Fr.dot(Fr),h=Nr.dot(Nr),f=Nr.dot(Yf);if(d<=s&&h<=s)return t.copy(o),i.copy(l),t.sub(i),t.dot(t);if(d<=s)a=0,r=f/h,r=Ze(r,0,1);else{const p=Fr.dot(Yf);if(h<=s)r=0,a=Ze(-p/d,0,1);else{const g=Fr.dot(Nr),_=d*h-g*g;_!==0?a=Ze((g*f-p*h)/_,0,1):a=0,r=(g*a+f)/h,r<0?(r=0,a=Ze(-p/d,0,1)):r>1&&(r=1,a=Ze((g-p)/d,0,1))}}return t.copy(o).add(Fr.multiplyScalar(a)),i.copy(l).add(Nr.multiplyScalar(r)),t.sub(i),t.dot(t)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}const h0=new S;class JR extends Qe{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const i=new Ge,s=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let r=0,o=1,l=32;r1)for(let d=0;d.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{g0.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(g0,t)}}setLength(e,t=e*.2,i=t*.2){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(i,t,i),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class uP extends Ln{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],i=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],s=new Ge;s.setAttribute("position",new Ee(t,3)),s.setAttribute("color",new Ee(i,3));const a=new Rt({vertexColors:!0,toneMapped:!1});super(s,a),this.type="AxesHelper"}setColors(e,t,i){const s=new ue,a=this.geometry.attributes.color.array;return s.set(e),s.toArray(a,0),s.toArray(a,3),s.set(t),s.toArray(a,6),s.toArray(a,9),s.set(i),s.toArray(a,12),s.toArray(a,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class dP{constructor(){this.type="ShapePath",this.color=new ue,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new Zd,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,i,s){return this.currentPath.quadraticCurveTo(e,t,i,s),this}bezierCurveTo(e,t,i,s,a,r){return this.currentPath.bezierCurveTo(e,t,i,s,a,r),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(m){const v=[];for(let y=0,b=m.length;yNumber.EPSILON){if(E<0&&(M=v[x],w=-w,C=v[T],E=-E),m.yC.y)continue;if(m.y===M.y){if(m.x===M.x)return!0}else{const R=E*(m.x-M.x)-w*(m.y-M.y);if(R===0)return!0;if(R<0)continue;b=!b}}else{if(m.y!==M.y)continue;if(C.x<=m.x&&m.x<=M.x||M.x<=m.x&&m.x<=C.x)return!0}}return b}const s=Mi.isClockWise,a=this.subPaths;if(a.length===0)return[];let r,o,l;const c=[];if(a.length===1)return o=a[0],l=new Ns,l.curves=o.curves,c.push(l),c;let u=!s(a[0].getPoints());u=e?!u:u;const d=[],h=[];let f=[],p=0,g;h[p]=void 0,f[p]=[];for(let m=0,v=a.length;m1){let m=!1,v=0;for(let y=0,b=h.length;y0&&m===!1&&(f=d)}let _;for(let m=0,v=h.length;me?(n.repeat.x=1,n.repeat.y=t/e,n.offset.x=0,n.offset.y=(1-n.repeat.y)/2):(n.repeat.x=e/t,n.repeat.y=1,n.offset.x=(1-n.repeat.x)/2,n.offset.y=0),n}function fP(n,e){const t=n.image&&n.image.width?n.image.width/n.image.height:1;return t>e?(n.repeat.x=e/t,n.repeat.y=1,n.offset.x=(1-n.repeat.x)/2,n.offset.y=0):(n.repeat.x=1,n.repeat.y=t/e,n.offset.x=0,n.offset.y=(1-n.repeat.y)/2),n}function pP(n){return n.repeat.x=1,n.repeat.y=1,n.offset.x=0,n.offset.y=0,n}function Rm(n,e,t,i){const s=mP(i);switch(t){case W_:return n*e;case bh:return n*e/s.components*s.byteLength;case ic:return n*e/s.components*s.byteLength;case K_:return n*e*2/s.components*s.byteLength;case xh:return n*e*2/s.components*s.byteLength;case X_:return n*e*3/s.components*s.byteLength;case Vn:return n*e*4/s.components*s.byteLength;case wh:return n*e*4/s.components*s.byteLength;case Tl:case Ml:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case El:case Cl:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case vd:case xd:return Math.max(n,16)*Math.max(e,8)/4;case yd:case bd:return Math.max(n,8)*Math.max(e,8)/2;case wd:case Sd:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case Td:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case Md:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case Ed:return Math.floor((n+4)/5)*Math.floor((e+3)/4)*16;case Cd:return Math.floor((n+4)/5)*Math.floor((e+4)/5)*16;case Ad:return Math.floor((n+5)/6)*Math.floor((e+4)/5)*16;case Rd:return Math.floor((n+5)/6)*Math.floor((e+5)/6)*16;case Pd:return Math.floor((n+7)/8)*Math.floor((e+4)/5)*16;case Id:return Math.floor((n+7)/8)*Math.floor((e+5)/6)*16;case Ld:return Math.floor((n+7)/8)*Math.floor((e+7)/8)*16;case Dd:return Math.floor((n+9)/10)*Math.floor((e+4)/5)*16;case kd:return Math.floor((n+9)/10)*Math.floor((e+5)/6)*16;case Od:return Math.floor((n+9)/10)*Math.floor((e+7)/8)*16;case Fd:return Math.floor((n+9)/10)*Math.floor((e+9)/10)*16;case Nd:return Math.floor((n+11)/12)*Math.floor((e+9)/10)*16;case Ud:return Math.floor((n+11)/12)*Math.floor((e+11)/12)*16;case Bd:case zd:case Hd:return Math.ceil(n/4)*Math.ceil(e/4)*16;case Vd:case Gd:return Math.ceil(n/4)*Math.ceil(e/4)*8;case $d:case Wd:return Math.ceil(n/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function mP(n){switch(n){case Yi:case H_:return{byteLength:1,components:1};case yo:case V_:case ls:return{byteLength:2,components:1};case yh:case vh:return{byteLength:2,components:4};case zs:case gh:case Sn:return{byteLength:4,components:1};case G_:case $_:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${n}.`)}class _P{static contain(e,t){return hP(e,t)}static cover(e,t){return fP(e,t)}static fill(e){return pP(e)}static getByteLength(e,t,i,s){return Rm(e,t,i,s)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:ph}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=ph);function nT(){let n=null,e=!1,t=null,i=null;function s(a,r){t(a,r),i=n.requestAnimationFrame(s)}return{start:function(){e!==!0&&t!==null&&(i=n.requestAnimationFrame(s),e=!0)},stop:function(){n.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(a){t=a},setContext:function(a){n=a}}}function gP(n){const e=new WeakMap;function t(o,l){const c=o.array,u=o.usage,d=c.byteLength,h=n.createBuffer();n.bindBuffer(l,h),n.bufferData(l,c,u),o.onUploadCallback();let f;if(c instanceof Float32Array)f=n.FLOAT;else if(typeof Float16Array<"u"&&c instanceof Float16Array)f=n.HALF_FLOAT;else if(c instanceof Uint16Array)o.isFloat16BufferAttribute?f=n.HALF_FLOAT:f=n.UNSIGNED_SHORT;else if(c instanceof Int16Array)f=n.SHORT;else if(c instanceof Uint32Array)f=n.UNSIGNED_INT;else if(c instanceof Int32Array)f=n.INT;else if(c instanceof Int8Array)f=n.BYTE;else if(c instanceof Uint8Array)f=n.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)f=n.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:h,type:f,bytesPerElement:c.BYTES_PER_ELEMENT,version:o.version,size:d}}function i(o,l,c){const u=l.array,d=l.updateRanges;if(n.bindBuffer(c,o),d.length===0)n.bufferSubData(c,0,u);else{d.sort((f,p)=>f.start-p.start);let h=0;for(let f=1;ff+p?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&h<=f-p&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(a=t.getPose(e.gripSpace,i),a!==null&&(l.matrix.fromArray(a.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,a.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(a.linearVelocity)):l.hasLinearVelocity=!1,a.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(a.angularVelocity)):l.hasAngularVelocity=!1));o!==null&&(s=t.getPose(e.targetRaySpace,i),s===null&&a!==null&&(s=a),s!==null&&(o.matrix.fromArray(s.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,s.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(s.linearVelocity)):o.hasLinearVelocity=!1,s.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(s.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(EA)))}return o!==null&&(o.visible=s!==null),l!==null&&(l.visible=a!==null),c!==null&&(c.visible=r!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const i=new Mt;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}class Oh{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new ue(e),this.density=t}clone(){return new Oh(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class Fh{constructor(e,t=1,i=1e3){this.isFog=!0,this.name="",this.color=new ue(e),this.near=t,this.far=i}clone(){return new Fh(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class cc extends Qe{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new an,this.environmentIntensity=1,this.environmentRotation=new an,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class uc{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=$l,this.updateRanges=[],this.version=0,this.uuid=pi()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,i){e*=this.stride,i*=t.stride;for(let s=0,a=this.stride;se.far||t.push({distance:l,point:Ko.clone(),uv:Qn.getInterpolation(Ko,Nc,Yo,Uc,Fy,zf,Ny,new te),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}}function Bc(n,e,t,i,s,a){Dr.subVectors(n,t).addScalar(.5).multiply(i),s!==void 0?(qo.x=a*Dr.x-s*Dr.y,qo.y=s*Dr.x+a*Dr.y):qo.copy(Dr),n.copy(e),n.x+=qo.x,n.y+=qo.y,n.applyMatrix4(MS)}const zc=new S,Uy=new S;class ES extends Qe{constructor(){super(),this.isLOD=!0,this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);const t=e.levels;for(let i=0,s=t.length;i0){let i,s;for(i=1,s=t.length;i0){zc.setFromMatrixPosition(this.matrixWorld);const s=e.ray.origin.distanceTo(zc);this.getObjectForDistance(s).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){zc.setFromMatrixPosition(e.matrixWorld),Uy.setFromMatrixPosition(this.matrixWorld);const i=zc.distanceTo(Uy)/e.zoom;t[0].object.visible=!0;let s,a;for(s=1,a=t.length;s=r)t[s-1].object.visible=!1,t[s].object.visible=!0;else break}for(this._currentLevel=s-1;s1?null:t.copy(e.start).addScaledVector(i,a)}intersectsLine(e){const t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const i=t||IA.getNormalMatrix(e),s=this.coplanarPoint(Gf).applyMatrix4(e),a=this.normal.applyMatrix3(i).normalize();return this.constant=-s.dot(a),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const xa=new bn,LA=new te(.5,.5),Gc=new S;class ko{constructor(e=new Ps,t=new Ps,i=new Ps,s=new Ps,a=new Ps,r=new Ps){this.planes=[e,t,i,s,a,r]}set(e,t,i,s,a,r){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(i),o[3].copy(s),o[4].copy(a),o[5].copy(r),this}copy(e){const t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=hi,i=!1){const s=this.planes,a=e.elements,r=a[0],o=a[1],l=a[2],c=a[3],u=a[4],d=a[5],h=a[6],f=a[7],p=a[8],g=a[9],_=a[10],m=a[11],v=a[12],y=a[13],b=a[14],T=a[15];if(s[0].setComponents(c-r,f-u,m-p,T-v).normalize(),s[1].setComponents(c+r,f+u,m+p,T+v).normalize(),s[2].setComponents(c+o,f+d,m+g,T+y).normalize(),s[3].setComponents(c-o,f-d,m-g,T-y).normalize(),i)s[4].setComponents(l,h,_,b).normalize(),s[5].setComponents(c-l,f-h,m-_,T-b).normalize();else if(s[4].setComponents(c-l,f-h,m-_,T-b).normalize(),t===hi)s[5].setComponents(c+l,f+h,m+_,T+b).normalize();else if(t===Eo)s[5].setComponents(l,h,_,b).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),xa.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),xa.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(xa)}intersectsSprite(e){xa.center.set(0,0,0);const t=LA.distanceTo(e.center);return xa.radius=.7071067811865476+t,xa.applyMatrix4(e.matrixWorld),this.intersectsSphere(xa)}intersectsSphere(e){const t=this.planes,i=e.center,s=-e.radius;for(let a=0;a<6;a++)if(t[a].distanceToPoint(i)0?e.max.x:e.min.x,Gc.y=s.normal.y>0?e.max.y:e.min.y,Gc.z=s.normal.z>0?e.max.z:e.min.z,s.distanceToPoint(Gc)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}const Qi=new Me,es=new ko;class Hh{constructor(){this.coordinateSystem=hi}intersectsObject(e,t){if(!t.isArrayCamera||t.cameras.length===0)return!1;for(let i=0;i=a.length&&a.push({start:-1,count:-1,z:-1,index:-1});const o=a[this.index];r.push(o),this.index++,o.start=e,o.count=t,o.z=i,o.index=s}reset(){this.list.length=0,this.index=0}}const Wn=new Me,FA=new ue(1,1,1),Ky=new ko,NA=new Hh,$c=new vn,wa=new bn,Jo=new S,qy=new S,UA=new S,Wf=new OA,Cn=new we,Wc=[];function BA(n,e,t=0){const i=e.itemSize;if(n.isInterleavedBufferAttribute||n.array.constructor!==e.array.constructor){const s=n.count;for(let a=0;a65535?new Uint32Array(s):new Uint16Array(s);t.setIndex(new ot(a,1))}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;if(!!e.getIndex()!=!!t.getIndex())throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');for(const i in t.attributes){if(!e.hasAttribute(i))throw new Error(`THREE.BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`);const s=e.getAttribute(i),a=t.getAttribute(i);if(s.itemSize!==a.itemSize||s.normalized!==a.normalized)throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}validateInstanceId(e){const t=this._instanceInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid instanceId ${e}. Instance is either out of range or has been deleted.`)}validateGeometryId(e){const t=this._geometryInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`)}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new vn);const e=this.boundingBox,t=this._instanceInfo;e.makeEmpty();for(let i=0,s=t.length;i=this.maxInstanceCount&&this._availableInstanceIds.length===0)throw new Error("THREE.BatchedMesh: Maximum item count reached.");const i={visible:!0,active:!0,geometryIndex:e};let s=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort($f),s=this._availableInstanceIds.shift(),this._instanceInfo[s]=i):(s=this._instanceInfo.length,this._instanceInfo.push(i));const a=this._matricesTexture;Wn.identity().toArray(a.image.data,s*16),a.needsUpdate=!0;const r=this._colorsTexture;return r&&(FA.toArray(r.image.data,s*4),r.needsUpdate=!0),this._visibilityChanged=!0,s}addGeometry(e,t=-1,i=-1){this._initializeGeometry(e),this._validateGeometry(e);const s={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},a=this._geometryInfo;s.vertexStart=this._nextVertexStart,s.reservedVertexCount=t===-1?e.getAttribute("position").count:t;const r=e.getIndex();if(r!==null&&(s.indexStart=this._nextIndexStart,s.reservedIndexCount=i===-1?r.count:i),s.indexStart!==-1&&s.indexStart+s.reservedIndexCount>this._maxIndexCount||s.vertexStart+s.reservedVertexCount>this._maxVertexCount)throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");let l;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort($f),l=this._availableGeometryIds.shift(),a[l]=s):(l=this._geometryCount,this._geometryCount++,a.push(s)),this.setGeometryAt(l,e),this._nextIndexStart=s.indexStart+s.reservedIndexCount,this._nextVertexStart=s.vertexStart+s.reservedVertexCount,l}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,s=i.getIndex()!==null,a=i.getIndex(),r=t.getIndex(),o=this._geometryInfo[e];if(s&&r.count>o.reservedIndexCount||t.attributes.position.count>o.reservedVertexCount)throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");const l=o.vertexStart,c=o.reservedVertexCount;o.vertexCount=t.getAttribute("position").count;for(const u in i.attributes){const d=t.getAttribute(u),h=i.getAttribute(u);BA(d,h,l);const f=d.itemSize;for(let p=d.count,g=c;p=t.length||t[e].active===!1)return this;const i=this._instanceInfo;for(let s=0,a=i.length;so).sort((r,o)=>i[r].vertexStart-i[o].vertexStart),a=this.geometry;for(let r=0,o=i.length;r=this._geometryCount)return null;const i=this.geometry,s=this._geometryInfo[e];if(s.boundingBox===null){const a=new vn,r=i.index,o=i.attributes.position;for(let l=s.start,c=s.start+s.count;l=this._geometryCount)return null;const i=this.geometry,s=this._geometryInfo[e];if(s.boundingSphere===null){const a=new bn;this.getBoundingBoxAt(e,$c),$c.getCenter(a.center);const r=i.index,o=i.attributes.position;let l=0;for(let c=s.start,u=s.start+s.count;co.active);if(Math.max(...i.map(o=>o.vertexStart+o.reservedVertexCount))>e)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${t}. Cannot shrink further.`);if(this.geometry.index&&Math.max(...i.map(l=>l.indexStart+l.reservedIndexCount))>t)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${t}. Cannot shrink further.`);const a=this.geometry;a.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new Ge,this._initializeGeometry(a));const r=this.geometry;a.index&&Sa(a.index.array,r.index.array);for(const o in a.attributes)Sa(a.attributes[o].array,r.attributes[o].array)}raycast(e,t){const i=this._instanceInfo,s=this._geometryInfo,a=this.matrixWorld,r=this.geometry;Cn.material=this.material,Cn.geometry.index=r.index,Cn.geometry.attributes=r.attributes,Cn.geometry.boundingBox===null&&(Cn.geometry.boundingBox=new vn),Cn.geometry.boundingSphere===null&&(Cn.geometry.boundingSphere=new bn);for(let o=0,l=i.length;o({...t,boundingBox:t.boundingBox!==null?t.boundingBox.clone():null,boundingSphere:t.boundingSphere!==null?t.boundingSphere.clone():null})),this._instanceInfo=e._instanceInfo.map(t=>({...t})),this._availableInstanceIds=e._availableInstanceIds.slice(),this._availableGeometryIds=e._availableGeometryIds.slice(),this._nextIndexStart=e._nextIndexStart,this._nextVertexStart=e._nextVertexStart,this._geometryCount=e._geometryCount,this._maxInstanceCount=e._maxInstanceCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._indirectTexture=e._indirectTexture.clone(),this._indirectTexture.image.data=this._indirectTexture.image.data.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),this._colorsTexture!==null&&(this._colorsTexture=e._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,this._colorsTexture!==null&&(this._colorsTexture.dispose(),this._colorsTexture=null)}onBeforeRender(e,t,i,s,a){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const r=s.getIndex(),o=r===null?1:r.array.BYTES_PER_ELEMENT,l=this._instanceInfo,c=this._multiDrawStarts,u=this._multiDrawCounts,d=this._geometryInfo,h=this.perObjectFrustumCulled,f=this._indirectTexture,p=f.image.data,g=i.isArrayCamera?NA:Ky;h&&!i.isArrayCamera&&(Wn.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse).multiply(this.matrixWorld),Ky.setFromProjectionMatrix(Wn,i.coordinateSystem,i.reversedDepth));let _=0;if(this.sortObjects){Wn.copy(this.matrixWorld).invert(),Jo.setFromMatrixPosition(i.matrixWorld).applyMatrix4(Wn),qy.set(0,0,-1).transformDirection(i.matrixWorld).transformDirection(Wn);for(let y=0,b=l.length;y0){const s=t[i[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,r=s.length;ai)return;Xf.applyMatrix4(n.matrixWorld);const c=e.ray.origin.distanceTo(Xf);if(!(ce.far))return{distance:c,point:jy.clone().applyMatrix4(n.matrixWorld),index:r,face:null,faceIndex:null,barycoord:null,object:n}}const Zy=new S,Jy=new S;class Ln extends In{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,i=[];for(let s=0,a=t.count;s0){const s=t[i[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,r=s.length;as.far)return;a.push({distance:c,distanceToRay:Math.sqrt(o),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:r})}}class AS extends Bt{constructor(e,t,i,s,a=Vt,r=Vt,o,l,c){super(e,t,i,s,a,r,o,l,c),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;const u=this;function d(){u.needsUpdate=!0,u._requestVideoFrameCallbackId=e.requestVideoFrameCallback(d)}"requestVideoFrameCallback"in e&&(this._requestVideoFrameCallbackId=e.requestVideoFrameCallback(d))}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;"requestVideoFrameCallback"in e===!1&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),super.dispose()}}class zA extends AS{constructor(e,t,i,s,a,r,o,l){super({},e,t,i,s,a,r,o,l),this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(e){this.image=e,this.needsUpdate=!0}}class HA extends Bt{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=dn,this.minFilter=dn,this.generateMipmaps=!1,this.needsUpdate=!0}}class Vh extends Bt{constructor(e,t,i,s,a,r,o,l,c,u,d,h){super(null,r,o,l,c,u,s,a,d,h),this.isCompressedTexture=!0,this.image={width:t,height:i},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class VA extends Vh{constructor(e,t,i,s,a,r){super(e,t,i,a,r),this.isCompressedArrayTexture=!0,this.image.depth=s,this.wrapR=Hn,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class GA extends Vh{constructor(e,t,i){super(void 0,e[0].width,e[0].height,t,i,Bs),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class dc extends Bt{constructor(e,t,i,s,a,r,o,l,c){super(e,t,i,s,a,r,o,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}}class lg extends Bt{constructor(e,t,i=zs,s,a,r,o=dn,l=dn,c,u=So,d=1){if(u!==So&&u!==To)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const h={width:e,height:t,depth:d};super(h,s,a,r,o,l,u,i,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new sa(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class cg extends Bt{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class Gh extends Ge{constructor(e=1,t=1,i=4,s=8,a=1){super(),this.type="CapsuleGeometry",this.parameters={radius:e,height:t,capSegments:i,radialSegments:s,heightSegments:a},t=Math.max(0,t),i=Math.max(1,Math.floor(i)),s=Math.max(3,Math.floor(s)),a=Math.max(1,Math.floor(a));const r=[],o=[],l=[],c=[],u=t/2,d=Math.PI/2*e,h=t,f=2*d+h,p=i*2+a,g=s+1,_=new S,m=new S;for(let v=0;v<=p;v++){let y=0,b=0,T=0,x=0;if(v<=i){const w=v/i,E=w*Math.PI/2;b=-u-e*Math.cos(E),T=e*Math.sin(E),x=-e*Math.cos(E),y=w*d}else if(v<=i+a){const w=(v-i)/a;b=-u+w*t,T=e,x=0,y=d+w*h}else{const w=(v-i-a)/i,E=w*Math.PI/2;b=u+e*Math.sin(E),T=e*Math.cos(E),x=e*Math.sin(E),y=d+h+w*d}const M=Math.max(0,Math.min(1,y/f));let C=0;v===0?C=.5/s:v===p&&(C=-.5/s);for(let w=0;w<=s;w++){const E=w/s,R=E*Math.PI*2,k=Math.sin(R),O=Math.cos(R);m.x=-T*O,m.y=b,m.z=T*k,o.push(m.x,m.y,m.z),_.set(-T*O,x,T*k),_.normalize(),l.push(_.x,_.y,_.z),c.push(E+C,M)}if(v>0){const w=(v-1)*g;for(let E=0;E0&&y(!0),t>0&&y(!1)),this.setIndex(u),this.setAttribute("position",new Ee(d,3)),this.setAttribute("normal",new Ee(h,3)),this.setAttribute("uv",new Ee(f,2));function v(){const b=new S,T=new S;let x=0;const M=(t-e)/i;for(let C=0;C<=a;C++){const w=[],E=C/a,R=E*(t-e)+e;for(let k=0;k<=s;k++){const O=k/s,D=O*l+o,U=Math.sin(D),F=Math.cos(D);T.x=R*U,T.y=-E*i+_,T.z=R*F,d.push(T.x,T.y,T.z),b.set(U,M,F).normalize(),h.push(b.x,b.y,b.z),f.push(O,1-E),w.push(p++)}g.push(w)}for(let C=0;C0||w!==0)&&(u.push(E,R,O),x+=3),(t>0||w!==a-1)&&(u.push(R,k,O),x+=3)}c.addGroup(m,x,0),m+=x}function y(b){const T=p,x=new te,M=new S;let C=0;const w=b===!0?e:t,E=b===!0?1:-1;for(let k=1;k<=s;k++)d.push(0,_*E,0),h.push(0,E,0),f.push(.5,.5),p++;const R=p;for(let k=0;k<=s;k++){const D=k/s*l+o,U=Math.cos(D),F=Math.sin(D);M.x=w*F,M.y=_*E,M.z=w*U,d.push(M.x,M.y,M.z),h.push(0,E,0),x.x=U*.5+.5,x.y=F*.5*E+.5,f.push(x.x,x.y),p++}for(let k=0;k.9&&M<.1&&(y<.2&&(r[v+0]+=1),b<.2&&(r[v+2]+=1),T<.2&&(r[v+4]+=1))}}function h(v){a.push(v.x,v.y,v.z)}function f(v,y){const b=v*3;y.x=e[b+0],y.y=e[b+1],y.z=e[b+2]}function p(){const v=new S,y=new S,b=new S,T=new S,x=new te,M=new te,C=new te;for(let w=0,E=0;w0)l=s-1;else{l=s;break}if(s=l,i[s]===r)return s/(a-1);const u=i[s],h=i[s+1]-u,f=(r-u)/h;return(s+f)/(a-1)}getTangent(e,t){let s=e-1e-4,a=e+1e-4;s<0&&(s=0),a>1&&(a=1);const r=this.getPoint(s),o=this.getPoint(a),l=t||(r.isVector2?new te:new S);return l.copy(o).sub(r).normalize(),l}getTangentAt(e,t){const i=this.getUtoTmapping(e);return this.getTangent(i,t)}computeFrenetFrames(e,t=!1){const i=new S,s=[],a=[],r=[],o=new S,l=new Me;for(let f=0;f<=e;f++){const p=f/e;s[f]=this.getTangentAt(p,new S)}a[0]=new S,r[0]=new S;let c=Number.MAX_VALUE;const u=Math.abs(s[0].x),d=Math.abs(s[0].y),h=Math.abs(s[0].z);u<=c&&(c=u,i.set(1,0,0)),d<=c&&(c=d,i.set(0,1,0)),h<=c&&i.set(0,0,1),o.crossVectors(s[0],i).normalize(),a[0].crossVectors(s[0],o),r[0].crossVectors(s[0],a[0]);for(let f=1;f<=e;f++){if(a[f]=a[f-1].clone(),r[f]=r[f-1].clone(),o.crossVectors(s[f-1],s[f]),o.length()>Number.EPSILON){o.normalize();const p=Math.acos(Ze(s[f-1].dot(s[f]),-1,1));a[f].applyMatrix4(l.makeRotationAxis(o,p))}r[f].crossVectors(s[f],a[f])}if(t===!0){let f=Math.acos(Ze(a[0].dot(a[e]),-1,1));f/=e,s[0].dot(o.crossVectors(a[0],a[e]))>0&&(f=-f);for(let p=1;p<=e;p++)a[p].applyMatrix4(l.makeRotationAxis(s[p],f*p)),r[p].crossVectors(s[p],a[p])}return{tangents:s,normals:a,binormals:r}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class Xh extends Pi{constructor(e=0,t=0,i=1,s=1,a=0,r=Math.PI*2,o=!1,l=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=i,this.yRadius=s,this.aStartAngle=a,this.aEndAngle=r,this.aClockwise=o,this.aRotation=l}getPoint(e,t=new te){const i=t,s=Math.PI*2;let a=this.aEndAngle-this.aStartAngle;const r=Math.abs(a)s;)a-=s;a0?0:(Math.floor(Math.abs(o)/a)+1)*a:l===0&&o===a-1&&(o=a-2,l=1);let c,u;this.closed||o>0?c=s[(o-1)%a]:(Qc.subVectors(s[0],s[1]).add(s[0]),c=Qc);const d=s[o%a],h=s[(o+1)%a];if(this.closed||o+2s.length-2?s.length-1:r+1],d=s[r>s.length-3?s.length-1:r+2];return i.set(t0(o,l.x,c.x,u.x,d.x),t0(o,l.y,c.y,u.y,d.y)),i}copy(e){super.copy(e),this.points=[];for(let t=0,i=e.points.length;t=i){const r=s[a]-i,o=this.curves[a],l=o.getLength(),c=l===0?0:1-r/l;return o.getPointAt(c,t)}a++}return null}getLength(){const e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const e=[];let t=0;for(let i=0,s=this.curves.length;i1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,i=e.curves.length;t0){const d=c.getPoint(0);d.equals(this.currentPoint)||this.lineTo(d.x,d.y)}this.curves.push(c);const u=c.getPoint(1);return this.currentPoint.copy(u),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class Ns extends ih{constructor(e){super(e),this.uuid=pi(),this.type="Shape",this.holes=[]}getPointsHoles(e){const t=[];for(let i=0,s=this.holes.length;i80*t){o=1/0,l=1/0;let u=-1/0,d=-1/0;for(let h=t;hu&&(u=f),p>d&&(d=p)}c=Math.max(u-o,d-l),c=c!==0?32767/c:0}return Kl(a,r,t,o,l,c,0),r}function kS(n,e,t,i,s){let a;if(s===fR(n,e,t,i)>0)for(let r=e;r=e;r-=i)a=n0(r/i|0,n[r],n[r+1],a);return a&&Po(a,a.next)&&(Yl(a),a=a.next),a}function ur(n,e){if(!n)return n;e||(e=n);let t=n,i;do if(i=!1,!t.steiner&&(Po(t,t.next)||Kt(t.prev,t,t.next)===0)){if(Yl(t),t=e=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==e);return e}function Kl(n,e,t,i,s,a,r){if(!n)return;!r&&a&&oR(n,i,s,a);let o=n;for(;n.prev!==n.next;){const l=n.prev,c=n.next;if(a?QA(n,i,s,a):JA(n)){e.push(l.i,n.i,c.i),Yl(n),n=c.next,o=c.next;continue}if(n=c,n===o){r?r===1?(n=eR(ur(n),e),Kl(n,e,t,i,s,a,2)):r===2&&tR(n,e,t,i,s,a):Kl(ur(n),e,t,i,s,a,1);break}}}function JA(n){const e=n.prev,t=n,i=n.next;if(Kt(e,t,i)>=0)return!1;const s=e.x,a=t.x,r=i.x,o=e.y,l=t.y,c=i.y,u=Math.min(s,a,r),d=Math.min(o,l,c),h=Math.max(s,a,r),f=Math.max(o,l,c);let p=i.next;for(;p!==e;){if(p.x>=u&&p.x<=h&&p.y>=d&&p.y<=f&&ml(s,o,a,l,r,c,p.x,p.y)&&Kt(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function QA(n,e,t,i){const s=n.prev,a=n,r=n.next;if(Kt(s,a,r)>=0)return!1;const o=s.x,l=a.x,c=r.x,u=s.y,d=a.y,h=r.y,f=Math.min(o,l,c),p=Math.min(u,d,h),g=Math.max(o,l,c),_=Math.max(u,d,h),m=Im(f,p,e,t,i),v=Im(g,_,e,t,i);let y=n.prevZ,b=n.nextZ;for(;y&&y.z>=m&&b&&b.z<=v;){if(y.x>=f&&y.x<=g&&y.y>=p&&y.y<=_&&y!==s&&y!==r&&ml(o,u,l,d,c,h,y.x,y.y)&&Kt(y.prev,y,y.next)>=0||(y=y.prevZ,b.x>=f&&b.x<=g&&b.y>=p&&b.y<=_&&b!==s&&b!==r&&ml(o,u,l,d,c,h,b.x,b.y)&&Kt(b.prev,b,b.next)>=0))return!1;b=b.nextZ}for(;y&&y.z>=m;){if(y.x>=f&&y.x<=g&&y.y>=p&&y.y<=_&&y!==s&&y!==r&&ml(o,u,l,d,c,h,y.x,y.y)&&Kt(y.prev,y,y.next)>=0)return!1;y=y.prevZ}for(;b&&b.z<=v;){if(b.x>=f&&b.x<=g&&b.y>=p&&b.y<=_&&b!==s&&b!==r&&ml(o,u,l,d,c,h,b.x,b.y)&&Kt(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function eR(n,e){let t=n;do{const i=t.prev,s=t.next.next;!Po(i,s)&&OS(i,t,t.next,s)&&ql(i,s)&&ql(s,i)&&(e.push(i.i,t.i,s.i),Yl(t),Yl(t.next),t=n=s),t=t.next}while(t!==n);return ur(t)}function tR(n,e,t,i,s,a){let r=n;do{let o=r.next.next;for(;o!==r.prev;){if(r.i!==o.i&&uR(r,o)){let l=FS(r,o);r=ur(r,r.next),l=ur(l,l.next),Kl(r,e,t,i,s,a,0),Kl(l,e,t,i,s,a,0);return}o=o.next}r=r.next}while(r!==n)}function nR(n,e,t,i){const s=[];for(let a=0,r=e.length;a=t.next.y&&t.next.y!==t.y){const d=t.x+(s-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(d<=i&&d>a&&(a=d,r=t.x=t.x&&t.x>=l&&i!==t.x&&DS(sr.x||t.x===r.x&&rR(r,t)))&&(r=t,u=d)}t=t.next}while(t!==o);return r}function rR(n,e){return Kt(n.prev,n,e.prev)<0&&Kt(e.next,n,n.next)<0}function oR(n,e,t,i){let s=n;do s.z===0&&(s.z=Im(s.x,s.y,e,t,i)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next;while(s!==n);s.prevZ.nextZ=null,s.prevZ=null,lR(s)}function lR(n){let e,t=1;do{let i=n,s;n=null;let a=null;for(e=0;i;){e++;let r=i,o=0;for(let c=0;c0||l>0&&r;)o!==0&&(l===0||!r||i.z<=r.z)?(s=i,i=i.nextZ,o--):(s=r,r=r.nextZ,l--),a?a.nextZ=s:n=s,s.prevZ=a,a=s;i=r}a.nextZ=null,t*=2}while(e>1);return n}function Im(n,e,t,i,s){return n=(n-t)*s|0,e=(e-i)*s|0,n=(n|n<<8)&16711935,n=(n|n<<4)&252645135,n=(n|n<<2)&858993459,n=(n|n<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,n|e<<1}function cR(n){let e=n,t=n;do(e.x=(n-r)*(a-o)&&(n-r)*(i-o)>=(t-r)*(e-o)&&(t-r)*(a-o)>=(s-r)*(i-o)}function ml(n,e,t,i,s,a,r,o){return!(n===r&&e===o)&&DS(n,e,t,i,s,a,r,o)}function uR(n,e){return n.next.i!==e.i&&n.prev.i!==e.i&&!dR(n,e)&&(ql(n,e)&&ql(e,n)&&hR(n,e)&&(Kt(n.prev,n,e.prev)||Kt(n,e.prev,e))||Po(n,e)&&Kt(n.prev,n,n.next)>0&&Kt(e.prev,e,e.next)>0)}function Kt(n,e,t){return(e.y-n.y)*(t.x-e.x)-(e.x-n.x)*(t.y-e.y)}function Po(n,e){return n.x===e.x&&n.y===e.y}function OS(n,e,t,i){const s=tu(Kt(n,e,t)),a=tu(Kt(n,e,i)),r=tu(Kt(t,i,n)),o=tu(Kt(t,i,e));return!!(s!==a&&r!==o||s===0&&eu(n,t,e)||a===0&&eu(n,i,e)||r===0&&eu(t,n,i)||o===0&&eu(t,e,i))}function eu(n,e,t){return e.x<=Math.max(n.x,t.x)&&e.x>=Math.min(n.x,t.x)&&e.y<=Math.max(n.y,t.y)&&e.y>=Math.min(n.y,t.y)}function tu(n){return n>0?1:n<0?-1:0}function dR(n,e){let t=n;do{if(t.i!==n.i&&t.next.i!==n.i&&t.i!==e.i&&t.next.i!==e.i&&OS(t,t.next,n,e))return!0;t=t.next}while(t!==n);return!1}function ql(n,e){return Kt(n.prev,n,n.next)<0?Kt(n,e,n.next)>=0&&Kt(n,n.prev,e)>=0:Kt(n,e,n.prev)<0||Kt(n,n.next,e)<0}function hR(n,e){let t=n,i=!1;const s=(n.x+e.x)/2,a=(n.y+e.y)/2;do t.y>a!=t.next.y>a&&t.next.y!==t.y&&s<(t.next.x-t.x)*(a-t.y)/(t.next.y-t.y)+t.x&&(i=!i),t=t.next;while(t!==n);return i}function FS(n,e){const t=Lm(n.i,n.x,n.y),i=Lm(e.i,e.x,e.y),s=n.next,a=e.prev;return n.next=e,e.prev=n,t.next=s,s.prev=t,i.next=t,t.prev=i,a.next=i,i.prev=a,i}function n0(n,e,t,i){const s=Lm(n,e,t);return i?(s.next=i.next,s.prev=i,i.next.prev=s,i.next=s):(s.prev=s,s.next=s),s}function Yl(n){n.next.prev=n.prev,n.prev.next=n.next,n.prevZ&&(n.prevZ.nextZ=n.nextZ),n.nextZ&&(n.nextZ.prevZ=n.prevZ)}function Lm(n,e,t){return{i:n,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function fR(n,e,t,i){let s=0;for(let a=e,r=t-i;a2&&n[e-1].equals(n[0])&&n.pop()}function s0(n,e){for(let t=0;tNumber.EPSILON){const J=Math.sqrt(A),le=Math.sqrt(it*it+I*I),ee=j.x-$e/J,He=j.y+ge/J,ye=Y.x-I/le,Ue=Y.y+it/le,Be=((ye-ee)*I-(Ue-He)*it)/(ge*I-$e*it);Q=ee+ge*Be-G.x,_e=He+$e*Be-G.y;const de=Q*Q+_e*_e;if(de<=2)return new te(Q,_e);ce=Math.sqrt(de/2)}else{let J=!1;ge>Number.EPSILON?it>Number.EPSILON&&(J=!0):ge<-Number.EPSILON?it<-Number.EPSILON&&(J=!0):Math.sign($e)===Math.sign(I)&&(J=!0),J?(Q=-$e,_e=ge,ce=Math.sqrt(A)):(Q=ge,_e=$e,ce=Math.sqrt(A/2))}return new te(Q/ce,_e/ce)}const ne=[];for(let G=0,j=U.length,Y=j-1,Q=G+1;G=0;G--){const j=G/_,Y=f*Math.cos(j*Math.PI/2),Q=p*Math.sin(j*Math.PI/2)+g;for(let _e=0,ce=U.length;_e=0;){const Q=Y;let _e=Y-1;_e<0&&(_e=G.length-1);for(let ce=0,ge=u+_*2;ce0)&&f.push(y,b,x),(m!==i-1||l0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class ja extends Qt{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new ue(16777215),this.specular=new ue(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ue(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=fa,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new an,this.combine=rc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class BS extends Qt{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new ue(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ue(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=fa,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class zS extends Qt{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=fa,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class ef extends Qt{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new ue(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ue(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=fa,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new an,this.combine=rc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class yg extends Qt{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=oS,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class vg extends Qt{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class HS extends Qt{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new ue(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=fa,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}class VS extends Rt{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}function Za(n,e){return!n||n.constructor===e?n:typeof e.BYTES_PER_ELEMENT=="number"?new e(n):Array.prototype.slice.call(n)}function GS(n){return ArrayBuffer.isView(n)&&!(n instanceof DataView)}function $S(n){function e(s,a){return n[s]-n[a]}const t=n.length,i=new Array(t);for(let s=0;s!==t;++s)i[s]=s;return i.sort(e),i}function km(n,e,t){const i=n.length,s=new n.constructor(i);for(let a=0,r=0;r!==i;++a){const o=t[a]*e;for(let l=0;l!==e;++l)s[r++]=n[o+l]}return s}function bg(n,e,t,i){let s=1,a=n[0];for(;a!==void 0&&a[i]===void 0;)a=n[s++];if(a===void 0)return;let r=a[i];if(r!==void 0)if(Array.isArray(r))do r=a[i],r!==void 0&&(e.push(a.time),t.push(...r)),a=n[s++];while(a!==void 0);else if(r.toArray!==void 0)do r=a[i],r!==void 0&&(e.push(a.time),r.toArray(t,t.length)),a=n[s++];while(a!==void 0);else do r=a[i],r!==void 0&&(e.push(a.time),t.push(r)),a=n[s++];while(a!==void 0)}function yR(n,e,t,i,s=30){const a=n.clone();a.name=e;const r=[];for(let l=0;l=i)){d.push(c.times[f]);for(let g=0;ga.tracks[l].times[0]&&(o=a.tracks[l].times[0]);for(let l=0;l=o.times[p]){const m=p*d+u,v=m+d-u;g=o.values.slice(m,v)}else{const m=o.createInterpolant(),v=u,y=d-u;m.evaluate(a),g=m.resultBuffer.slice(v,y)}l==="quaternion"&&new dt().fromArray(g).normalize().conjugate().toArray(g);const _=c.times.length;for(let m=0;m<_;++m){const v=m*f+h;if(l==="quaternion")dt.multiplyQuaternionsFlat(c.values,v,g,0,c.values,v);else{const y=f-h*2;for(let b=0;b=a)){const o=t[1];e=a)break t}r=i,i=0;break n}break e}for(;i>>1;et;)--r;if(++r,a!==0||r!==s){a>=r&&(r=Math.max(r,1),a=r-1);const o=this.getValueSize();this.times=i.slice(a,r),this.values=this.values.slice(a*o,r*o)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const i=this.times,s=this.values,a=i.length;a===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let r=null;for(let o=0;o!==a;o++){const l=i[o];if(typeof l=="number"&&isNaN(l)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,o,l),e=!1;break}if(r!==null&&r>l){console.error("THREE.KeyframeTrack: Out of order keys.",this,o,l,r),e=!1;break}r=l}if(s!==void 0&&GS(s))for(let o=0,l=s.length;o!==l;++o){const c=s[o];if(isNaN(c)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,o,c),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),i=this.getValueSize(),s=this.getInterpolation()===Xu,a=e.length-1;let r=1;for(let o=1;o0){e[r]=e[a];for(let o=a*i,l=r*i,c=0;c!==i;++c)t[l+c]=t[o+c];++r}return r!==e.length?(this.times=e.slice(0,r),this.values=t.slice(0,r*i)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),i=this.constructor,s=new i(this.name,e,t);return s.createInterpolant=this.createInterpolant,s}}Ii.prototype.ValueTypeName="";Ii.prototype.TimeBufferType=Float32Array;Ii.prototype.ValueBufferType=Float32Array;Ii.prototype.DefaultInterpolation=or;class mr extends Ii{constructor(e,t,i){super(e,t,i)}}mr.prototype.ValueTypeName="bool";mr.prototype.ValueBufferType=Array;mr.prototype.DefaultInterpolation=Mo;mr.prototype.InterpolantFactoryMethodLinear=void 0;mr.prototype.InterpolantFactoryMethodSmooth=void 0;class wg extends Ii{constructor(e,t,i,s){super(e,t,i,s)}}wg.prototype.ValueTypeName="color";class ua extends Ii{constructor(e,t,i,s){super(e,t,i,s)}}ua.prototype.ValueTypeName="number";class KS extends Oo{constructor(e,t,i,s){super(e,t,i,s)}interpolate_(e,t,i,s){const a=this.resultBuffer,r=this.sampleValues,o=this.valueSize,l=(i-t)/(s-t);let c=e*o;for(let u=c+o;c!==u;c+=4)dt.slerpFlat(a,0,r,c-o,r,c,l);return a}}class _s extends Ii{constructor(e,t,i,s){super(e,t,i,s)}InterpolantFactoryMethodLinear(e){return new KS(this.times,this.values,this.getValueSize(),e)}}_s.prototype.ValueTypeName="quaternion";_s.prototype.InterpolantFactoryMethodSmooth=void 0;class _r extends Ii{constructor(e,t,i){super(e,t,i)}}_r.prototype.ValueTypeName="string";_r.prototype.ValueBufferType=Array;_r.prototype.DefaultInterpolation=Mo;_r.prototype.InterpolantFactoryMethodLinear=void 0;_r.prototype.InterpolantFactoryMethodSmooth=void 0;class Hs extends Ii{constructor(e,t,i,s){super(e,t,i,s)}}Hs.prototype.ValueTypeName="vector";class da{constructor(e="",t=-1,i=[],s=Rh){this.name=e,this.tracks=i,this.duration=t,this.blendMode=s,this.uuid=pi(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){const t=[],i=e.tracks,s=1/(e.fps||1);for(let r=0,o=i.length;r!==o;++r)t.push(wR(i[r]).scale(s));const a=new this(e.name,e.duration,t,e.blendMode);return a.uuid=e.uuid,a.userData=JSON.parse(e.userData||"{}"),a}static toJSON(e){const t=[],i=e.tracks,s={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let a=0,r=i.length;a!==r;++a)t.push(Ii.toJSON(i[a]));return s}static CreateFromMorphTargetSequence(e,t,i,s){const a=t.length,r=[];for(let o=0;o1){const d=u[1];let h=s[d];h||(s[d]=h=[]),h.push(c)}}const r=[];for(const o in s)r.push(this.CreateFromMorphTargetSequence(o,s[o],t,i));return r}static parseAnimation(e,t){if(console.warn("THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const i=function(d,h,f,p,g){if(f.length!==0){const _=[],m=[];bg(f,_,m,p),_.length!==0&&g.push(new d(h,_,m))}},s=[],a=e.name||"default",r=e.fps||30,o=e.blendMode;let l=e.length||-1;const c=e.hierarchy||[];for(let d=0;d{t&&t(a),this.manager.itemEnd(e)},0),a;if(Ts[e]!==void 0){Ts[e].push({onLoad:t,onProgress:i,onError:s});return}Ts[e]=[],Ts[e].push({onLoad:t,onProgress:i,onError:s});const r=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,l=this.responseType;fetch(r).then(c=>{if(c.status===200||c.status===0){if(c.status===0&&console.warn("THREE.FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||c.body===void 0||c.body.getReader===void 0)return c;const u=Ts[e],d=c.body.getReader(),h=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),f=h?parseInt(h):0,p=f!==0;let g=0;const _=new ReadableStream({start(m){v();function v(){d.read().then(({done:y,value:b})=>{if(y)m.close();else{g+=b.byteLength;const T=new ProgressEvent("progress",{lengthComputable:p,loaded:g,total:f});for(let x=0,M=u.length;x{m.error(y)})}}});return new Response(_)}else throw new SR(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`,c)}).then(c=>{switch(l){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then(u=>new DOMParser().parseFromString(u,o));case"json":return c.json();default:if(o==="")return c.text();{const d=/charset="?([^;"\s]*)"?/i.exec(o),h=d&&d[1]?d[1].toLowerCase():void 0,f=new TextDecoder(h);return c.arrayBuffer().then(p=>f.decode(p))}}}).then(c=>{cs.add(`file:${e}`,c);const u=Ts[e];delete Ts[e];for(let d=0,h=u.length;d{const u=Ts[e];if(u===void 0)throw this.manager.itemError(e),c;delete Ts[e];for(let d=0,h=u.length;d{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}class TR extends on{constructor(e){super(e)}load(e,t,i,s){const a=this,r=new Gn(this.manager);r.setPath(this.path),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,function(o){try{t(a.parse(JSON.parse(o)))}catch(l){s?s(l):console.error(l),a.manager.itemError(e)}},i,s)}parse(e){const t=[];for(let i=0;i0:s.vertexColors=e.vertexColors),e.uniforms!==void 0)for(const a in e.uniforms){const r=e.uniforms[a];switch(s.uniforms[a]={},r.type){case"t":s.uniforms[a].value=i(r.value);break;case"c":s.uniforms[a].value=new ue().setHex(r.value);break;case"v2":s.uniforms[a].value=new te().fromArray(r.value);break;case"v3":s.uniforms[a].value=new S().fromArray(r.value);break;case"v4":s.uniforms[a].value=new qe().fromArray(r.value);break;case"m3":s.uniforms[a].value=new at().fromArray(r.value);break;case"m4":s.uniforms[a].value=new Me().fromArray(r.value);break;default:s.uniforms[a].value=r.value}}if(e.defines!==void 0&&(s.defines=e.defines),e.vertexShader!==void 0&&(s.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(s.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(s.glslVersion=e.glslVersion),e.extensions!==void 0)for(const a in e.extensions)s.extensions[a]=e.extensions[a];if(e.lights!==void 0&&(s.lights=e.lights),e.clipping!==void 0&&(s.clipping=e.clipping),e.size!==void 0&&(s.size=e.size),e.sizeAttenuation!==void 0&&(s.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(s.map=i(e.map)),e.matcap!==void 0&&(s.matcap=i(e.matcap)),e.alphaMap!==void 0&&(s.alphaMap=i(e.alphaMap)),e.bumpMap!==void 0&&(s.bumpMap=i(e.bumpMap)),e.bumpScale!==void 0&&(s.bumpScale=e.bumpScale),e.normalMap!==void 0&&(s.normalMap=i(e.normalMap)),e.normalMapType!==void 0&&(s.normalMapType=e.normalMapType),e.normalScale!==void 0){let a=e.normalScale;Array.isArray(a)===!1&&(a=[a,a]),s.normalScale=new te().fromArray(a)}return e.displacementMap!==void 0&&(s.displacementMap=i(e.displacementMap)),e.displacementScale!==void 0&&(s.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(s.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(s.roughnessMap=i(e.roughnessMap)),e.metalnessMap!==void 0&&(s.metalnessMap=i(e.metalnessMap)),e.emissiveMap!==void 0&&(s.emissiveMap=i(e.emissiveMap)),e.emissiveIntensity!==void 0&&(s.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(s.specularMap=i(e.specularMap)),e.specularIntensityMap!==void 0&&(s.specularIntensityMap=i(e.specularIntensityMap)),e.specularColorMap!==void 0&&(s.specularColorMap=i(e.specularColorMap)),e.envMap!==void 0&&(s.envMap=i(e.envMap)),e.envMapRotation!==void 0&&s.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(s.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(s.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(s.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(s.lightMap=i(e.lightMap)),e.lightMapIntensity!==void 0&&(s.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(s.aoMap=i(e.aoMap)),e.aoMapIntensity!==void 0&&(s.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(s.gradientMap=i(e.gradientMap)),e.clearcoatMap!==void 0&&(s.clearcoatMap=i(e.clearcoatMap)),e.clearcoatRoughnessMap!==void 0&&(s.clearcoatRoughnessMap=i(e.clearcoatRoughnessMap)),e.clearcoatNormalMap!==void 0&&(s.clearcoatNormalMap=i(e.clearcoatNormalMap)),e.clearcoatNormalScale!==void 0&&(s.clearcoatNormalScale=new te().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(s.iridescenceMap=i(e.iridescenceMap)),e.iridescenceThicknessMap!==void 0&&(s.iridescenceThicknessMap=i(e.iridescenceThicknessMap)),e.transmissionMap!==void 0&&(s.transmissionMap=i(e.transmissionMap)),e.thicknessMap!==void 0&&(s.thicknessMap=i(e.thicknessMap)),e.anisotropyMap!==void 0&&(s.anisotropyMap=i(e.anisotropyMap)),e.sheenColorMap!==void 0&&(s.sheenColorMap=i(e.sheenColorMap)),e.sheenRoughnessMap!==void 0&&(s.sheenRoughnessMap=i(e.sheenRoughnessMap)),s}setTextures(e){return this.textures=e,this}createMaterialFromType(e){return sf.createMaterialFromType(e)}static createMaterialFromType(e){const t={ShadowMaterial:NS,SpriteMaterial:Nh,RawShaderMaterial:US,ShaderMaterial:ti,PointsMaterial:aa,MeshPhysicalMaterial:ii,MeshStandardMaterial:Pn,MeshPhongMaterial:ja,MeshToonMaterial:BS,MeshNormalMaterial:zS,MeshLambertMaterial:ef,MeshDepthMaterial:yg,MeshDistanceMaterial:vg,MeshBasicMaterial:Ye,MeshMatcapMaterial:HS,LineDashedMaterial:VS,LineBasicMaterial:Rt,Material:Qt};return new t[e]}}class Us{static extractUrlBase(e){const t=e.lastIndexOf("/");return t===-1?"./":e.slice(0,t+1)}static resolveURL(e,t){return typeof e!="string"||e===""?"":(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}}class eT extends Ge{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){const e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}}class tT extends on{constructor(e){super(e)}load(e,t,i,s){const a=this,r=new Gn(a.manager);r.setPath(a.path),r.setRequestHeader(a.requestHeader),r.setWithCredentials(a.withCredentials),r.load(e,function(o){try{t(a.parse(JSON.parse(o)))}catch(l){s?s(l):console.error(l),a.manager.itemError(e)}},i,s)}parse(e){const t={},i={};function s(f,p){if(t[p]!==void 0)return t[p];const _=f.interleavedBuffers[p],m=a(f,_.buffer),v=Zr(_.type,m),y=new uc(v,_.stride);return y.uuid=_.uuid,t[p]=y,y}function a(f,p){if(i[p]!==void 0)return i[p];const _=f.arrayBuffers[p],m=new Uint32Array(_).buffer;return i[p]=m,m}const r=e.isInstancedBufferGeometry?new eT:new Ge,o=e.data.index;if(o!==void 0){const f=Zr(o.type,o.array);r.setIndex(new ot(f,1))}const l=e.data.attributes;for(const f in l){const p=l[f];let g;if(p.isInterleavedBufferAttribute){const _=s(e.data,p.data);g=new ca(_,p.itemSize,p.offset,p.normalized)}else{const _=Zr(p.type,p.array),m=p.isInstancedBufferAttribute?lr:ot;g=new m(_,p.itemSize,p.normalized)}p.name!==void 0&&(g.name=p.name),p.usage!==void 0&&g.setUsage(p.usage),r.setAttribute(f,g)}const c=e.data.morphAttributes;if(c)for(const f in c){const p=c[f],g=[];for(let _=0,m=p.length;_0){const l=new Sg(t);a=new jl(l),a.setCrossOrigin(this.crossOrigin);for(let c=0,u=e.length;c0){s=new jl(this.manager),s.setCrossOrigin(this.crossOrigin);for(let r=0,o=e.length;r{let _=null,m=null;return g.boundingBox!==void 0&&(_=new vn().fromJSON(g.boundingBox)),g.boundingSphere!==void 0&&(m=new bn().fromJSON(g.boundingSphere)),{...g,boundingBox:_,boundingSphere:m}}),r._instanceInfo=e.instanceInfo,r._availableInstanceIds=e._availableInstanceIds,r._availableGeometryIds=e._availableGeometryIds,r._nextIndexStart=e.nextIndexStart,r._nextVertexStart=e.nextVertexStart,r._geometryCount=e.geometryCount,r._maxInstanceCount=e.maxInstanceCount,r._maxVertexCount=e.maxVertexCount,r._maxIndexCount=e.maxIndexCount,r._geometryInitialized=e.geometryInitialized,r._matricesTexture=c(e.matricesTexture.uuid),r._indirectTexture=c(e.indirectTexture.uuid),e.colorsTexture!==void 0&&(r._colorsTexture=c(e.colorsTexture.uuid)),e.boundingSphere!==void 0&&(r.boundingSphere=new bn().fromJSON(e.boundingSphere)),e.boundingBox!==void 0&&(r.boundingBox=new vn().fromJSON(e.boundingBox));break;case"LOD":r=new ES;break;case"Line":r=new In(o(e.geometry),l(e.material));break;case"LineLoop":r=new og(o(e.geometry),l(e.material));break;case"LineSegments":r=new Ln(o(e.geometry),l(e.material));break;case"PointCloud":case"Points":r=new sr(o(e.geometry),l(e.material));break;case"Sprite":r=new Uh(l(e.material));break;case"Group":r=new Mt;break;case"Bone":r=new Ro;break;default:r=new Qe}if(r.uuid=e.uuid,e.name!==void 0&&(r.name=e.name),e.matrix!==void 0?(r.matrix.fromArray(e.matrix),e.matrixAutoUpdate!==void 0&&(r.matrixAutoUpdate=e.matrixAutoUpdate),r.matrixAutoUpdate&&r.matrix.decompose(r.position,r.quaternion,r.scale)):(e.position!==void 0&&r.position.fromArray(e.position),e.rotation!==void 0&&r.rotation.fromArray(e.rotation),e.quaternion!==void 0&&r.quaternion.fromArray(e.quaternion),e.scale!==void 0&&r.scale.fromArray(e.scale)),e.up!==void 0&&r.up.fromArray(e.up),e.castShadow!==void 0&&(r.castShadow=e.castShadow),e.receiveShadow!==void 0&&(r.receiveShadow=e.receiveShadow),e.shadow&&(e.shadow.intensity!==void 0&&(r.shadow.intensity=e.shadow.intensity),e.shadow.bias!==void 0&&(r.shadow.bias=e.shadow.bias),e.shadow.normalBias!==void 0&&(r.shadow.normalBias=e.shadow.normalBias),e.shadow.radius!==void 0&&(r.shadow.radius=e.shadow.radius),e.shadow.mapSize!==void 0&&r.shadow.mapSize.fromArray(e.shadow.mapSize),e.shadow.camera!==void 0&&(r.shadow.camera=this.parseObject(e.shadow.camera))),e.visible!==void 0&&(r.visible=e.visible),e.frustumCulled!==void 0&&(r.frustumCulled=e.frustumCulled),e.renderOrder!==void 0&&(r.renderOrder=e.renderOrder),e.userData!==void 0&&(r.userData=e.userData),e.layers!==void 0&&(r.layers.mask=e.layers),e.children!==void 0){const h=e.children;for(let f=0;f"u"&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,i,s){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const a=this,r=cs.get(`image-bitmap:${e}`);if(r!==void 0){if(a.manager.itemStart(e),r.then){r.then(c=>{if(Qf.has(r)===!0)s&&s(Qf.get(r)),a.manager.itemError(e),a.manager.itemEnd(e);else return t&&t(c),a.manager.itemEnd(e),c});return}return setTimeout(function(){t&&t(r),a.manager.itemEnd(e)},0),r}const o={};o.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",o.headers=this.requestHeader,o.signal=typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;const l=fetch(e,o).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign(a.options,{colorSpaceConversion:"none"}))}).then(function(c){return cs.add(`image-bitmap:${e}`,c),t&&t(c),a.manager.itemEnd(e),c}).catch(function(c){s&&s(c),Qf.set(l,c),cs.remove(`image-bitmap:${e}`),a.manager.itemError(e),a.manager.itemEnd(e)});cs.add(`image-bitmap:${e}`,l),a.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}let nu;class Mg{static getContext(){return nu===void 0&&(nu=new(window.AudioContext||window.webkitAudioContext)),nu}static setContext(e){nu=e}}class LR extends on{constructor(e){super(e)}load(e,t,i,s){const a=this,r=new Gn(this.manager);r.setResponseType("arraybuffer"),r.setPath(this.path),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,function(l){try{const c=l.slice(0);Mg.getContext().decodeAudioData(c,function(d){t(d)}).catch(o)}catch(c){o(c)}},i,s);function o(l){s?s(l):console.error(l),a.manager.itemError(e)}}}const h0=new Me,f0=new Me,Ta=new Me;class kR{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new Jt,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Jt,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){const t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,Ta.copy(e.projectionMatrix);const s=t.eyeSep/2,a=s*t.near/t.focus,r=t.near*Math.tan(ir*t.fov*.5)/t.zoom;let o,l;f0.elements[12]=-s,h0.elements[12]=s,o=-r*t.aspect+a,l=r*t.aspect+a,Ta.elements[0]=2*t.near/(l-o),Ta.elements[8]=(l+o)/(l-o),this.cameraL.projectionMatrix.copy(Ta),o=-r*t.aspect-a,l=r*t.aspect-a,Ta.elements[0]=2*t.near/(l-o),Ta.elements[8]=(l+o)/(l-o),this.cameraR.projectionMatrix.copy(Ta)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(f0),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(h0)}}class iT extends Jt{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class Eg{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}const Ma=new S,ep=new dt,DR=new S,Ea=new S,Ca=new S;class OR extends Qe{constructor(){super(),this.type="AudioListener",this.context=Mg.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new Eg}getInput(){return this.gain}removeFilter(){return this.filter!==null&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return this.filter!==null?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e);const t=this.context.listener;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(Ma,ep,DR),Ea.set(0,0,-1).applyQuaternion(ep),Ca.set(0,1,0).applyQuaternion(ep),t.positionX){const i=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(Ma.x,i),t.positionY.linearRampToValueAtTime(Ma.y,i),t.positionZ.linearRampToValueAtTime(Ma.z,i),t.forwardX.linearRampToValueAtTime(Ea.x,i),t.forwardY.linearRampToValueAtTime(Ea.y,i),t.forwardZ.linearRampToValueAtTime(Ea.z,i),t.upX.linearRampToValueAtTime(Ca.x,i),t.upY.linearRampToValueAtTime(Ca.y,i),t.upZ.linearRampToValueAtTime(Ca.z,i)}else t.setPosition(Ma.x,Ma.y,Ma.z),t.setOrientation(Ea.x,Ea.y,Ea.z,Ca.x,Ca.y,Ca.z)}}class sT extends Qe{constructor(e){super(),this.type="Audio",this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType="buffer",this.autoplay&&this.play(),this}play(e=0){if(this.isPlaying===!0){console.warn("THREE.Audio: Audio is already playing.");return}if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}this._startedAt=this.context.currentTime+e;const t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.isPlaying===!0&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this}stop(e=0){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this._progress=0,this.source!==null&&(this.source.stop(this.context.currentTime+e),this.source.onended=null),this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(i,s,this._addIndex*t,1,t);for(let l=t,c=t+t;l!==c;++l)if(i[l]!==i[l+t]){o.setValue(i,s);break}}saveOriginalState(){const e=this.binding,t=this.buffer,i=this.valueSize,s=i*this._origIndex;e.getValue(t,s);for(let a=i,r=s;a!==r;++a)t[a]=t[s+a%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let i=e;i=.5)for(let r=0;r!==a;++r)e[t+r]=e[i+r]}_slerp(e,t,i,s){dt.slerpFlat(e,t,e,t,e,i,s)}_slerpAdditive(e,t,i,s,a){const r=this._workIndex*a;dt.multiplyQuaternionsFlat(e,r,e,t,e,i),dt.slerpFlat(e,t,e,t,e,r,s)}_lerp(e,t,i,s,a){const r=1-s;for(let o=0;o!==a;++o){const l=t+o;e[l]=e[l]*r+e[i+o]*s}}_lerpAdditive(e,t,i,s,a){for(let r=0;r!==a;++r){const o=t+r;e[o]=e[o]+e[i+r]*s}}}const Cg="\\[\\]\\.:\\/",BR=new RegExp("["+Cg+"]","g"),Ag="[^"+Cg+"]",zR="[^"+Cg.replace("\\.","")+"]",HR=/((?:WC+[\/:])*)/.source.replace("WC",Ag),VR=/(WCOD+)?/.source.replace("WCOD",zR),GR=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Ag),$R=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Ag),WR=new RegExp("^"+HR+VR+GR+$R+"$"),XR=["material","materials","bones","map"];class KR{constructor(e,t,i){const s=i||yt.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,s)}getValue(e,t){this.bind();const i=this._targetGroup.nCachedObjects_,s=this._bindings[i];s!==void 0&&s.getValue(e,t)}setValue(e,t){const i=this._bindings;for(let s=this._targetGroup.nCachedObjects_,a=i.length;s!==a;++s)i[s].setValue(e,t)}bind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].bind()}unbind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].unbind()}}class yt{constructor(e,t,i){this.path=t,this.parsedPath=i||yt.parseTrackName(t),this.node=yt.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,i){return e&&e.isAnimationObjectGroup?new yt.Composite(e,t,i):new yt(e,t,i)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(BR,"")}static parseTrackName(e){const t=WR.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const i={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},s=i.nodeName&&i.nodeName.lastIndexOf(".");if(s!==void 0&&s!==-1){const a=i.nodeName.substring(s+1);XR.indexOf(a)!==-1&&(i.nodeName=i.nodeName.substring(0,s),i.objectName=a)}if(i.propertyName===null||i.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return i}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){const i=e.skeleton.getBoneByName(t);if(i!==void 0)return i}if(e.children){const i=function(a){for(let r=0;r=a){const d=a++,h=e[d];t[h.uuid]=u,e[u]=h,t[c]=d,e[d]=l;for(let f=0,p=s;f!==p;++f){const g=i[f],_=g[d],m=g[u];g[u]=_,g[d]=m}}}this.nCachedObjects_=a}uncache(){const e=this._objects,t=this._indicesByUUID,i=this._bindings,s=i.length;let a=this.nCachedObjects_,r=e.length;for(let o=0,l=arguments.length;o!==l;++o){const c=arguments[o],u=c.uuid,d=t[u];if(d!==void 0)if(delete t[u],d0&&(t[f.uuid]=d),e[d]=f,e.pop();for(let p=0,g=s;p!==g;++p){const _=i[p];_[d]=_[h],_.pop()}}}this.nCachedObjects_=a}subscribe_(e,t){const i=this._bindingsIndicesByPath;let s=i[e];const a=this._bindings;if(s!==void 0)return a[s];const r=this._paths,o=this._parsedPaths,l=this._objects,c=l.length,u=this.nCachedObjects_,d=new Array(c);s=a.length,i[e]=s,r.push(e),o.push(t),a.push(d);for(let h=u,f=l.length;h!==f;++h){const p=l[h];d[h]=new yt(p,e,t)}return d}unsubscribe_(e){const t=this._bindingsIndicesByPath,i=t[e];if(i!==void 0){const s=this._paths,a=this._parsedPaths,r=this._bindings,o=r.length-1,l=r[o],c=e[o];t[c]=i,r[i]=l,r.pop(),a[i]=a[o],a.pop(),s[i]=s[o],s.pop()}}}class rT{constructor(e,t,i=null,s=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=i,this.blendMode=s;const a=t.tracks,r=a.length,o=new Array(r),l={endingStart:qa,endingEnd:qa};for(let c=0;c!==r;++c){const u=a[c].createInterpolant(null);o[c]=u,u.settings=l}this._interpolantSettings=l,this._interpolants=o,this._propertyBindings=new Array(r),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=sS,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,i=!1){if(e.fadeOut(t),this.fadeIn(t),i===!0){const s=this._clip.duration,a=e._clip.duration,r=a/s,o=s/a;e.warp(1,r,t),this.warp(o,1,t)}return this}crossFadeTo(e,t,i=!1){return e.crossFadeFrom(this,t,i)}stopFading(){const e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,i){const s=this._mixer,a=s.time,r=this.timeScale;let o=this._timeScaleInterpolant;o===null&&(o=s._lendControlInterpolant(),this._timeScaleInterpolant=o);const l=o.parameterPositions,c=o.sampleValues;return l[0]=a,l[1]=a+i,c[0]=e/r,c[1]=t/r,this}stopWarping(){const e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,i,s){if(!this.enabled){this._updateWeight(e);return}const a=this._startTime;if(a!==null){const l=(e-a)*i;l<0||i===0?t=0:(this._startTime=null,t=i*l)}t*=this._updateTimeScale(e);const r=this._updateTime(t),o=this._updateWeight(e);if(o>0){const l=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case tg:for(let u=0,d=l.length;u!==d;++u)l[u].evaluate(r),c[u].accumulateAdditive(o);break;case Rh:default:for(let u=0,d=l.length;u!==d;++u)l[u].evaluate(r),c[u].accumulate(s,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const i=this._weightInterpolant;if(i!==null){const s=i.evaluate(e)[0];t*=s,e>i.parameterPositions[1]&&(this.stopFading(),s===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const i=this._timeScaleInterpolant;if(i!==null){const s=i.evaluate(e)[0];t*=s,e>i.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,i=this.loop;let s=this.time+e,a=this._loopCount;const r=i===aS;if(e===0)return a===-1?s:r&&(a&1)===1?t-s:s;if(i===Jd){a===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(s>=t)s=t;else if(s<0)s=0;else{this.time=s;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(a===-1&&(e>=0?(a=0,this._setEndings(!0,this.repetitions===0,r)):this._setEndings(this.repetitions===0,!0,r)),s>=t||s<0){const o=Math.floor(s/t);s-=t*o,a+=Math.abs(o);const l=this.repetitions-a;if(l<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,s=e>0?t:0,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(l===1){const c=e<0;this._setEndings(c,!c,r)}else this._setEndings(!1,!1,r);this._loopCount=a,this.time=s,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this.time=s;if(r&&(a&1)===1)return t-s}return s}_setEndings(e,t,i){const s=this._interpolantSettings;i?(s.endingStart=Ya,s.endingEnd=Ya):(e?s.endingStart=this.zeroSlopeAtStart?Ya:qa:s.endingStart=Vl,t?s.endingEnd=this.zeroSlopeAtEnd?Ya:qa:s.endingEnd=Vl)}_scheduleFading(e,t,i){const s=this._mixer,a=s.time;let r=this._weightInterpolant;r===null&&(r=s._lendControlInterpolant(),this._weightInterpolant=r);const o=r.parameterPositions,l=r.sampleValues;return o[0]=a,l[0]=t,o[1]=a+e,l[1]=i,this}}const YR=new Float32Array(1);class oT extends gs{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const i=e._localRoot||this._root,s=e._clip.tracks,a=s.length,r=e._propertyBindings,o=e._interpolants,l=i.uuid,c=this._bindingsByRootAndName;let u=c[l];u===void 0&&(u={},c[l]=u);for(let d=0;d!==a;++d){const h=s[d],f=h.name;let p=u[f];if(p!==void 0)++p.referenceCount,r[d]=p;else{if(p=r[d],p!==void 0){p._cacheIndex===null&&(++p.referenceCount,this._addInactiveBinding(p,l,f));continue}const g=t&&t._propertyBindings[d].binding.parsedPath;p=new aT(yt.create(i,f,g),h.ValueTypeName,h.getValueSize()),++p.referenceCount,this._addInactiveBinding(p,l,f),r[d]=p}o[d].resultBuffer=p.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){const i=(e._localRoot||this._root).uuid,s=e._clip.uuid,a=this._actionsByClip[s];this._bindAction(e,a&&a.knownActions[0]),this._addInactiveAction(e,s,i)}const t=e._propertyBindings;for(let i=0,s=t.length;i!==s;++i){const a=t[i];a.useCount++===0&&(this._lendBinding(a),a.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let i=0,s=t.length;i!==s;++i){const a=t[i];--a.useCount===0&&(a.restoreOriginalState(),this._takeBackBinding(a))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return t!==null&&t=0;--i)e[i].stop();return this}update(e){e*=this.timeScale;const t=this._actions,i=this._nActiveActions,s=this.time+=e,a=Math.sign(e),r=this._accuIndex^=1;for(let c=0;c!==i;++c)t[c]._update(s,e,a,r);const o=this._bindings,l=this._nActiveBindings;for(let c=0;c!==l;++c)o[c].apply(r);return this}setTime(e){this.time=0;for(let t=0;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,g0).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const y0=new S,iu=new S,Nr=new S,Ur=new S,tp=new S,rP=new S,oP=new S;class lP{constructor(e=new S,t=new S){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){y0.subVectors(e,this.start),iu.subVectors(this.end,this.start);const i=iu.dot(iu);let a=iu.dot(y0)/i;return t&&(a=Ze(a,0,1)),a}closestPointToPoint(e,t,i){const s=this.closestPointToPointParameter(e,t);return this.delta(i).multiplyScalar(s).add(this.start)}distanceSqToLine3(e,t=rP,i=oP){const s=10000000000000001e-32;let a,r;const o=this.start,l=e.start,c=this.end,u=e.end;Nr.subVectors(c,o),Ur.subVectors(u,l),tp.subVectors(o,l);const d=Nr.dot(Nr),h=Ur.dot(Ur),f=Ur.dot(tp);if(d<=s&&h<=s)return t.copy(o),i.copy(l),t.sub(i),t.dot(t);if(d<=s)a=0,r=f/h,r=Ze(r,0,1);else{const p=Nr.dot(tp);if(h<=s)r=0,a=Ze(-p/d,0,1);else{const g=Nr.dot(Ur),_=d*h-g*g;_!==0?a=Ze((g*f-p*h)/_,0,1):a=0,r=(g*a+f)/h,r<0?(r=0,a=Ze(-p/d,0,1)):r>1&&(r=1,a=Ze((g-p)/d,0,1))}}return t.copy(o).add(Nr.multiplyScalar(a)),i.copy(l).add(Ur.multiplyScalar(r)),t.sub(i),t.dot(t)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}const v0=new S;class cP extends Qe{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const i=new Ge,s=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let r=0,o=1,l=32;r1)for(let d=0;d.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{T0.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(T0,t)}}setLength(e,t=e*.2,i=t*.2){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(i,t,i),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class xP extends Ln{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],i=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],s=new Ge;s.setAttribute("position",new Ee(t,3)),s.setAttribute("color",new Ee(i,3));const a=new Rt({vertexColors:!0,toneMapped:!1});super(s,a),this.type="AxesHelper"}setColors(e,t,i){const s=new ue,a=this.geometry.attributes.color.array;return s.set(e),s.toArray(a,0),s.toArray(a,3),s.set(t),s.toArray(a,6),s.toArray(a,9),s.set(i),s.toArray(a,12),s.toArray(a,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class wP{constructor(){this.type="ShapePath",this.color=new ue,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new ih,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,i,s){return this.currentPath.quadraticCurveTo(e,t,i,s),this}bezierCurveTo(e,t,i,s,a,r){return this.currentPath.bezierCurveTo(e,t,i,s,a,r),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(m){const v=[];for(let y=0,b=m.length;yNumber.EPSILON){if(E<0&&(M=v[x],w=-w,C=v[T],E=-E),m.yC.y)continue;if(m.y===M.y){if(m.x===M.x)return!0}else{const R=E*(m.x-M.x)-w*(m.y-M.y);if(R===0)return!0;if(R<0)continue;b=!b}}else{if(m.y!==M.y)continue;if(C.x<=m.x&&m.x<=M.x||M.x<=m.x&&m.x<=C.x)return!0}}return b}const s=Ei.isClockWise,a=this.subPaths;if(a.length===0)return[];let r,o,l;const c=[];if(a.length===1)return o=a[0],l=new Ns,l.curves=o.curves,c.push(l),c;let u=!s(a[0].getPoints());u=e?!u:u;const d=[],h=[];let f=[],p=0,g;h[p]=void 0,f[p]=[];for(let m=0,v=a.length;m1){let m=!1,v=0;for(let y=0,b=h.length;y0&&m===!1&&(f=d)}let _;for(let m=0,v=h.length;me?(n.repeat.x=1,n.repeat.y=t/e,n.offset.x=0,n.offset.y=(1-n.repeat.y)/2):(n.repeat.x=e/t,n.repeat.y=1,n.offset.x=(1-n.repeat.x)/2,n.offset.y=0),n}function TP(n,e){const t=n.image&&n.image.width?n.image.width/n.image.height:1;return t>e?(n.repeat.x=e/t,n.repeat.y=1,n.offset.x=(1-n.repeat.x)/2,n.offset.y=0):(n.repeat.x=1,n.repeat.y=t/e,n.offset.x=0,n.offset.y=(1-n.repeat.y)/2),n}function MP(n){return n.repeat.x=1,n.repeat.y=1,n.offset.x=0,n.offset.y=0,n}function Fm(n,e,t,i){const s=EP(i);switch(t){case J_:return n*e;case Eh:return n*e/s.components*s.byteLength;case oc:return n*e/s.components*s.byteLength;case eg:return n*e*2/s.components*s.byteLength;case Ch:return n*e*2/s.components*s.byteLength;case Q_:return n*e*3/s.components*s.byteLength;case Vn:return n*e*4/s.components*s.byteLength;case Ah:return n*e*4/s.components*s.byteLength;case Cl:case Al:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case Rl:case Pl:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case Md:case Cd:return Math.max(n,16)*Math.max(e,8)/4;case Td:case Ed:return Math.max(n,8)*Math.max(e,8)/2;case Ad:case Rd:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case Pd:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case Id:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case Ld:return Math.floor((n+4)/5)*Math.floor((e+3)/4)*16;case kd:return Math.floor((n+4)/5)*Math.floor((e+4)/5)*16;case Dd:return Math.floor((n+5)/6)*Math.floor((e+4)/5)*16;case Od:return Math.floor((n+5)/6)*Math.floor((e+5)/6)*16;case Fd:return Math.floor((n+7)/8)*Math.floor((e+4)/5)*16;case Nd:return Math.floor((n+7)/8)*Math.floor((e+5)/6)*16;case Ud:return Math.floor((n+7)/8)*Math.floor((e+7)/8)*16;case Bd:return Math.floor((n+9)/10)*Math.floor((e+4)/5)*16;case zd:return Math.floor((n+9)/10)*Math.floor((e+5)/6)*16;case Hd:return Math.floor((n+9)/10)*Math.floor((e+7)/8)*16;case Vd:return Math.floor((n+9)/10)*Math.floor((e+9)/10)*16;case Gd:return Math.floor((n+11)/12)*Math.floor((e+9)/10)*16;case $d:return Math.floor((n+11)/12)*Math.floor((e+11)/12)*16;case Wd:case Xd:case Kd:return Math.ceil(n/4)*Math.ceil(e/4)*16;case qd:case Yd:return Math.ceil(n/4)*Math.ceil(e/4)*8;case jd:case Zd:return Math.ceil(n/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function EP(n){switch(n){case ji:case q_:return{byteLength:1,components:1};case xo:case Y_:case ls:return{byteLength:2,components:1};case Th:case Mh:return{byteLength:2,components:4};case zs:case Sh:case Sn:return{byteLength:4,components:1};case j_:case Z_:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${n}.`)}class CP{static contain(e,t){return SP(e,t)}static cover(e,t){return TP(e,t)}static fill(e){return MP(e)}static getByteLength(e,t,i,s){return Fm(e,t,i,s)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:bh}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=bh);function uT(){let n=null,e=!1,t=null,i=null;function s(a,r){t(a,r),i=n.requestAnimationFrame(s)}return{start:function(){e!==!0&&t!==null&&(i=n.requestAnimationFrame(s),e=!0)},stop:function(){n.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(a){t=a},setContext:function(a){n=a}}}function AP(n){const e=new WeakMap;function t(o,l){const c=o.array,u=o.usage,d=c.byteLength,h=n.createBuffer();n.bindBuffer(l,h),n.bufferData(l,c,u),o.onUploadCallback();let f;if(c instanceof Float32Array)f=n.FLOAT;else if(typeof Float16Array<"u"&&c instanceof Float16Array)f=n.HALF_FLOAT;else if(c instanceof Uint16Array)o.isFloat16BufferAttribute?f=n.HALF_FLOAT:f=n.UNSIGNED_SHORT;else if(c instanceof Int16Array)f=n.SHORT;else if(c instanceof Uint32Array)f=n.UNSIGNED_INT;else if(c instanceof Int32Array)f=n.INT;else if(c instanceof Int8Array)f=n.BYTE;else if(c instanceof Uint8Array)f=n.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)f=n.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:h,type:f,bytesPerElement:c.BYTES_PER_ELEMENT,version:o.version,size:d}}function i(o,l,c){const u=l.array,d=l.updateRanges;if(n.bindBuffer(c,o),d.length===0)n.bufferSubData(c,0,u);else{d.sort((f,p)=>f.start-p.start);let h=0;for(let f=1;f 0 +#endif`,$P=`#if NUM_CLIPPING_PLANES > 0 vec4 plane; #ifdef ALPHA_TO_COVERAGE float distanceToPlane, distanceGradient; @@ -289,26 +289,26 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve if ( clipped ) discard; #endif #endif -#endif`,kP=`#if NUM_CLIPPING_PLANES > 0 +#endif`,WP=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; -#endif`,OP=`#if NUM_CLIPPING_PLANES > 0 +#endif`,XP=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; -#endif`,FP=`#if NUM_CLIPPING_PLANES > 0 +#endif`,KP=`#if NUM_CLIPPING_PLANES > 0 vClipPosition = - mvPosition.xyz; -#endif`,NP=`#if defined( USE_COLOR_ALPHA ) +#endif`,qP=`#if defined( USE_COLOR_ALPHA ) diffuseColor *= vColor; #elif defined( USE_COLOR ) diffuseColor.rgb *= vColor; -#endif`,UP=`#if defined( USE_COLOR_ALPHA ) +#endif`,YP=`#if defined( USE_COLOR_ALPHA ) varying vec4 vColor; #elif defined( USE_COLOR ) varying vec3 vColor; -#endif`,BP=`#if defined( USE_COLOR_ALPHA ) +#endif`,jP=`#if defined( USE_COLOR_ALPHA ) varying vec4 vColor; #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) varying vec3 vColor; -#endif`,zP=`#if defined( USE_COLOR_ALPHA ) +#endif`,ZP=`#if defined( USE_COLOR_ALPHA ) vColor = vec4( 1.0 ); #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) vColor = vec3( 1.0 ); @@ -322,7 +322,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve #ifdef USE_BATCHING_COLOR vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); vColor.xyz *= batchingColor.xyz; -#endif`,HP=`#define PI 3.141592653589793 +#endif`,JP=`#define PI 3.141592653589793 #define PI2 6.283185307179586 #define PI_HALF 1.5707963267948966 #define RECIPROCAL_PI 0.3183098861837907 @@ -396,7 +396,7 @@ vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); -} // validated`,VP=`#ifdef ENVMAP_TYPE_CUBE_UV +} // validated`,QP=`#ifdef ENVMAP_TYPE_CUBE_UV #define cubeUV_minMipLevel 4.0 #define cubeUV_minTileSize 16.0 float getFace( vec3 direction ) { @@ -489,7 +489,7 @@ float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { return vec4( mix( color0, color1, mipF ), 1.0 ); } } -#endif`,GP=`vec3 transformedNormal = objectNormal; +#endif`,eI=`vec3 transformedNormal = objectNormal; #ifdef USE_TANGENT vec3 transformedTangent = objectTangent; #endif @@ -518,21 +518,21 @@ transformedNormal = normalMatrix * transformedNormal; #ifdef FLIP_SIDED transformedTangent = - transformedTangent; #endif -#endif`,$P=`#ifdef USE_DISPLACEMENTMAP +#endif`,tI=`#ifdef USE_DISPLACEMENTMAP uniform sampler2D displacementMap; uniform float displacementScale; uniform float displacementBias; -#endif`,WP=`#ifdef USE_DISPLACEMENTMAP +#endif`,nI=`#ifdef USE_DISPLACEMENTMAP transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); -#endif`,XP=`#ifdef USE_EMISSIVEMAP +#endif`,iI=`#ifdef USE_EMISSIVEMAP vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE emissiveColor = sRGBTransferEOTF( emissiveColor ); #endif totalEmissiveRadiance *= emissiveColor.rgb; -#endif`,KP=`#ifdef USE_EMISSIVEMAP +#endif`,sI=`#ifdef USE_EMISSIVEMAP uniform sampler2D emissiveMap; -#endif`,qP="gl_FragColor = linearToOutputTexel( gl_FragColor );",YP=`vec4 LinearTransferOETF( in vec4 value ) { +#endif`,aI="gl_FragColor = linearToOutputTexel( gl_FragColor );",rI=`vec4 LinearTransferOETF( in vec4 value ) { return value; } vec4 sRGBTransferEOTF( in vec4 value ) { @@ -540,7 +540,7 @@ vec4 sRGBTransferEOTF( in vec4 value ) { } vec4 sRGBTransferOETF( in vec4 value ) { return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); -}`,jP=`#ifdef USE_ENVMAP +}`,oI=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vec3 cameraToFrag; if ( isOrthographic ) { @@ -569,7 +569,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { #elif defined( ENVMAP_BLENDING_ADD ) outgoingLight += envColor.xyz * specularStrength * reflectivity; #endif -#endif`,ZP=`#ifdef USE_ENVMAP +#endif`,lI=`#ifdef USE_ENVMAP uniform float envMapIntensity; uniform float flipEnvMap; uniform mat3 envMapRotation; @@ -579,7 +579,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { uniform sampler2D envMap; #endif -#endif`,JP=`#ifdef USE_ENVMAP +#endif`,cI=`#ifdef USE_ENVMAP uniform float reflectivity; #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS @@ -590,7 +590,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { #else varying vec3 vReflect; #endif -#endif`,QP=`#ifdef USE_ENVMAP +#endif`,uI=`#ifdef USE_ENVMAP #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif @@ -601,7 +601,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { varying vec3 vReflect; uniform float refractionRatio; #endif -#endif`,eI=`#ifdef USE_ENVMAP +#endif`,dI=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vWorldPosition = worldPosition.xyz; #else @@ -618,18 +618,18 @@ vec4 sRGBTransferOETF( in vec4 value ) { vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); #endif #endif -#endif`,tI=`#ifdef USE_FOG +#endif`,hI=`#ifdef USE_FOG vFogDepth = - mvPosition.z; -#endif`,nI=`#ifdef USE_FOG +#endif`,fI=`#ifdef USE_FOG varying float vFogDepth; -#endif`,iI=`#ifdef USE_FOG +#endif`,pI=`#ifdef USE_FOG #ifdef FOG_EXP2 float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); #else float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); #endif gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); -#endif`,sI=`#ifdef USE_FOG +#endif`,mI=`#ifdef USE_FOG uniform vec3 fogColor; varying float vFogDepth; #ifdef FOG_EXP2 @@ -638,7 +638,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { uniform float fogNear; uniform float fogFar; #endif -#endif`,aI=`#ifdef USE_GRADIENTMAP +#endif`,_I=`#ifdef USE_GRADIENTMAP uniform sampler2D gradientMap; #endif vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { @@ -650,12 +650,12 @@ vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { vec2 fw = fwidth( coord ) * 0.5; return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); #endif -}`,rI=`#ifdef USE_LIGHTMAP +}`,gI=`#ifdef USE_LIGHTMAP uniform sampler2D lightMap; uniform float lightMapIntensity; -#endif`,oI=`LambertMaterial material; +#endif`,yI=`LambertMaterial material; material.diffuseColor = diffuseColor.rgb; -material.specularStrength = specularStrength;`,lI=`varying vec3 vViewPosition; +material.specularStrength = specularStrength;`,vI=`varying vec3 vViewPosition; struct LambertMaterial { vec3 diffuseColor; float specularStrength; @@ -669,7 +669,7 @@ void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometr reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Lambert -#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,cI=`uniform bool receiveShadow; +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,bI=`uniform bool receiveShadow; uniform vec3 ambientLightColor; #if defined( USE_LIGHT_PROBES ) uniform vec3 lightProbe[ 9 ]; @@ -785,7 +785,7 @@ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosi vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); return irradiance; } -#endif`,uI=`#ifdef USE_ENVMAP +#endif`,xI=`#ifdef USE_ENVMAP vec3 getIBLIrradiance( const in vec3 normal ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); @@ -818,8 +818,8 @@ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosi #endif } #endif -#endif`,dI=`ToonMaterial material; -material.diffuseColor = diffuseColor.rgb;`,hI=`varying vec3 vViewPosition; +#endif`,wI=`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,SI=`varying vec3 vViewPosition; struct ToonMaterial { vec3 diffuseColor; }; @@ -831,11 +831,11 @@ void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPo reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Toon -#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,fI=`BlinnPhongMaterial material; +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,TI=`BlinnPhongMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularColor = specular; material.specularShininess = shininess; -material.specularStrength = specularStrength;`,pI=`varying vec3 vViewPosition; +material.specularStrength = specularStrength;`,MI=`varying vec3 vViewPosition; struct BlinnPhongMaterial { vec3 diffuseColor; vec3 specularColor; @@ -852,7 +852,7 @@ void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geom reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_BlinnPhong -#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,mI=`PhysicalMaterial material; +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,EI=`PhysicalMaterial material; material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); @@ -938,7 +938,7 @@ material.roughness = min( material.roughness, 1.0 ); material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; -#endif`,_I=`struct PhysicalMaterial { +#endif`,CI=`struct PhysicalMaterial { vec3 diffuseColor; float roughness; vec3 specularColor; @@ -1239,7 +1239,7 @@ void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradia #define RE_IndirectSpecular RE_IndirectSpecular_Physical float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); -}`,gI=` +}`,AI=` vec3 geometryPosition = - vViewPosition; vec3 geometryNormal = normal; vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); @@ -1354,7 +1354,7 @@ IncidentLight directLight; #if defined( RE_IndirectSpecular ) vec3 radiance = vec3( 0.0 ); vec3 clearcoatRadiance = vec3( 0.0 ); -#endif`,yI=`#if defined( RE_IndirectDiffuse ) +#endif`,RI=`#if defined( RE_IndirectDiffuse ) #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; @@ -1373,32 +1373,32 @@ IncidentLight directLight; #ifdef USE_CLEARCOAT clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); #endif -#endif`,vI=`#if defined( RE_IndirectDiffuse ) +#endif`,PI=`#if defined( RE_IndirectDiffuse ) RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); #endif #if defined( RE_IndirectSpecular ) RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); -#endif`,bI=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) +#endif`,II=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; -#endif`,xI=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) +#endif`,LI=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) uniform float logDepthBufFC; varying float vFragDepth; varying float vIsPerspective; -#endif`,wI=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER +#endif`,kI=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER varying float vFragDepth; varying float vIsPerspective; -#endif`,SI=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER +#endif`,DI=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER vFragDepth = 1.0 + gl_Position.w; vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); -#endif`,TI=`#ifdef USE_MAP +#endif`,OI=`#ifdef USE_MAP vec4 sampledDiffuseColor = texture2D( map, vMapUv ); #ifdef DECODE_VIDEO_TEXTURE sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); #endif diffuseColor *= sampledDiffuseColor; -#endif`,MI=`#ifdef USE_MAP +#endif`,FI=`#ifdef USE_MAP uniform sampler2D map; -#endif`,EI=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) +#endif`,NI=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) #if defined( USE_POINTS_UV ) vec2 uv = vUv; #else @@ -1410,7 +1410,7 @@ IncidentLight directLight; #endif #ifdef USE_ALPHAMAP diffuseColor.a *= texture2D( alphaMap, uv ).g; -#endif`,CI=`#if defined( USE_POINTS_UV ) +#endif`,UI=`#if defined( USE_POINTS_UV ) varying vec2 vUv; #else #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) @@ -1422,19 +1422,19 @@ IncidentLight directLight; #endif #ifdef USE_ALPHAMAP uniform sampler2D alphaMap; -#endif`,AI=`float metalnessFactor = metalness; +#endif`,BI=`float metalnessFactor = metalness; #ifdef USE_METALNESSMAP vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); metalnessFactor *= texelMetalness.b; -#endif`,RI=`#ifdef USE_METALNESSMAP +#endif`,zI=`#ifdef USE_METALNESSMAP uniform sampler2D metalnessMap; -#endif`,PI=`#ifdef USE_INSTANCING_MORPH +#endif`,HI=`#ifdef USE_INSTANCING_MORPH float morphTargetInfluences[ MORPHTARGETS_COUNT ]; float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; } -#endif`,II=`#if defined( USE_MORPHCOLORS ) +#endif`,VI=`#if defined( USE_MORPHCOLORS ) vColor *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { #if defined( USE_COLOR_ALPHA ) @@ -1443,12 +1443,12 @@ IncidentLight directLight; if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; #endif } -#endif`,LI=`#ifdef USE_MORPHNORMALS +#endif`,GI=`#ifdef USE_MORPHNORMALS objectNormal *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; } -#endif`,DI=`#ifdef USE_MORPHTARGETS +#endif`,$I=`#ifdef USE_MORPHTARGETS #ifndef USE_INSTANCING_MORPH uniform float morphTargetBaseInfluence; uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; @@ -1462,12 +1462,12 @@ IncidentLight directLight; ivec3 morphUV = ivec3( x, y, morphTargetIndex ); return texelFetch( morphTargetsTexture, morphUV, 0 ); } -#endif`,kI=`#ifdef USE_MORPHTARGETS +#endif`,WI=`#ifdef USE_MORPHTARGETS transformed *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; } -#endif`,OI=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#endif`,XI=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; #ifdef FLAT_SHADED vec3 fdx = dFdx( vViewPosition ); vec3 fdy = dFdy( vViewPosition ); @@ -1508,7 +1508,7 @@ IncidentLight directLight; tbn2[1] *= faceDirection; #endif #endif -vec3 nonPerturbedNormal = normal;`,FI=`#ifdef USE_NORMALMAP_OBJECTSPACE +vec3 nonPerturbedNormal = normal;`,KI=`#ifdef USE_NORMALMAP_OBJECTSPACE normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; #ifdef FLIP_SIDED normal = - normal; @@ -1523,25 +1523,25 @@ vec3 nonPerturbedNormal = normal;`,FI=`#ifdef USE_NORMALMAP_OBJECTSPACE normal = normalize( tbn * mapN ); #elif defined( USE_BUMPMAP ) normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); -#endif`,NI=`#ifndef FLAT_SHADED +#endif`,qI=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif -#endif`,UI=`#ifndef FLAT_SHADED +#endif`,YI=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif -#endif`,BI=`#ifndef FLAT_SHADED +#endif`,jI=`#ifndef FLAT_SHADED vNormal = normalize( transformedNormal ); #ifdef USE_TANGENT vTangent = normalize( transformedTangent ); vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); #endif -#endif`,zI=`#ifdef USE_NORMALMAP +#endif`,ZI=`#ifdef USE_NORMALMAP uniform sampler2D normalMap; uniform vec2 normalScale; #endif @@ -1563,13 +1563,13 @@ vec3 nonPerturbedNormal = normal;`,FI=`#ifdef USE_NORMALMAP_OBJECTSPACE float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); return mat3( T * scale, B * scale, N ); } -#endif`,HI=`#ifdef USE_CLEARCOAT +#endif`,JI=`#ifdef USE_CLEARCOAT vec3 clearcoatNormal = nonPerturbedNormal; -#endif`,VI=`#ifdef USE_CLEARCOAT_NORMALMAP +#endif`,QI=`#ifdef USE_CLEARCOAT_NORMALMAP vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; clearcoatMapN.xy *= clearcoatNormalScale; clearcoatNormal = normalize( tbn2 * clearcoatMapN ); -#endif`,GI=`#ifdef USE_CLEARCOATMAP +#endif`,eL=`#ifdef USE_CLEARCOATMAP uniform sampler2D clearcoatMap; #endif #ifdef USE_CLEARCOAT_NORMALMAP @@ -1578,18 +1578,18 @@ vec3 nonPerturbedNormal = normal;`,FI=`#ifdef USE_NORMALMAP_OBJECTSPACE #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform sampler2D clearcoatRoughnessMap; -#endif`,$I=`#ifdef USE_IRIDESCENCEMAP +#endif`,tL=`#ifdef USE_IRIDESCENCEMAP uniform sampler2D iridescenceMap; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform sampler2D iridescenceThicknessMap; -#endif`,WI=`#ifdef OPAQUE +#endif`,nL=`#ifdef OPAQUE diffuseColor.a = 1.0; #endif #ifdef USE_TRANSMISSION diffuseColor.a *= material.transmissionAlpha; #endif -gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,XI=`vec3 packNormalToRGB( const in vec3 normal ) { +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,iL=`vec3 packNormalToRGB( const in vec3 normal ) { return normalize( normal ) * 0.5 + 0.5; } vec3 unpackRGBToNormal( const in vec3 rgb ) { @@ -1658,9 +1658,9 @@ float viewZToPerspectiveDepth( const in float viewZ, const in float near, const } float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { return ( near * far ) / ( ( far - near ) * depth - far ); -}`,KI=`#ifdef PREMULTIPLIED_ALPHA +}`,sL=`#ifdef PREMULTIPLIED_ALPHA gl_FragColor.rgb *= gl_FragColor.a; -#endif`,qI=`vec4 mvPosition = vec4( transformed, 1.0 ); +#endif`,aL=`vec4 mvPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING mvPosition = batchingMatrix * mvPosition; #endif @@ -1668,22 +1668,22 @@ float perspectiveDepthToViewZ( const in float depth, const in float near, const mvPosition = instanceMatrix * mvPosition; #endif mvPosition = modelViewMatrix * mvPosition; -gl_Position = projectionMatrix * mvPosition;`,YI=`#ifdef DITHERING +gl_Position = projectionMatrix * mvPosition;`,rL=`#ifdef DITHERING gl_FragColor.rgb = dithering( gl_FragColor.rgb ); -#endif`,jI=`#ifdef DITHERING +#endif`,oL=`#ifdef DITHERING vec3 dithering( vec3 color ) { float grid_position = rand( gl_FragCoord.xy ); vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); return color + dither_shift_RGB; } -#endif`,ZI=`float roughnessFactor = roughness; +#endif`,lL=`float roughnessFactor = roughness; #ifdef USE_ROUGHNESSMAP vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); roughnessFactor *= texelRoughness.g; -#endif`,JI=`#ifdef USE_ROUGHNESSMAP +#endif`,cL=`#ifdef USE_ROUGHNESSMAP uniform sampler2D roughnessMap; -#endif`,QI=`#if NUM_SPOT_LIGHT_COORDS > 0 +#endif`,uL=`#if NUM_SPOT_LIGHT_COORDS > 0 varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #if NUM_SPOT_LIGHT_MAPS > 0 @@ -1878,7 +1878,7 @@ gl_Position = projectionMatrix * mvPosition;`,YI=`#ifdef DITHERING } return mix( 1.0, shadow, shadowIntensity ); } -#endif`,eL=`#if NUM_SPOT_LIGHT_COORDS > 0 +#endif`,dL=`#if NUM_SPOT_LIGHT_COORDS > 0 uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif @@ -1919,7 +1919,7 @@ gl_Position = projectionMatrix * mvPosition;`,YI=`#ifdef DITHERING }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif -#endif`,tL=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) +#endif`,hL=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); vec4 shadowWorldPosition; #endif @@ -1951,7 +1951,7 @@ gl_Position = projectionMatrix * mvPosition;`,YI=`#ifdef DITHERING vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end -#endif`,nL=`float getShadowMask() { +#endif`,fL=`float getShadowMask() { float shadow = 1.0; #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 @@ -1983,12 +1983,12 @@ gl_Position = projectionMatrix * mvPosition;`,YI=`#ifdef DITHERING #endif #endif return shadow; -}`,iL=`#ifdef USE_SKINNING +}`,pL=`#ifdef USE_SKINNING mat4 boneMatX = getBoneMatrix( skinIndex.x ); mat4 boneMatY = getBoneMatrix( skinIndex.y ); mat4 boneMatZ = getBoneMatrix( skinIndex.z ); mat4 boneMatW = getBoneMatrix( skinIndex.w ); -#endif`,sL=`#ifdef USE_SKINNING +#endif`,mL=`#ifdef USE_SKINNING uniform mat4 bindMatrix; uniform mat4 bindMatrixInverse; uniform highp sampler2D boneTexture; @@ -2003,7 +2003,7 @@ gl_Position = projectionMatrix * mvPosition;`,YI=`#ifdef DITHERING vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); return mat4( v1, v2, v3, v4 ); } -#endif`,aL=`#ifdef USE_SKINNING +#endif`,_L=`#ifdef USE_SKINNING vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); vec4 skinned = vec4( 0.0 ); skinned += boneMatX * skinVertex * skinWeight.x; @@ -2011,7 +2011,7 @@ gl_Position = projectionMatrix * mvPosition;`,YI=`#ifdef DITHERING skinned += boneMatZ * skinVertex * skinWeight.z; skinned += boneMatW * skinVertex * skinWeight.w; transformed = ( bindMatrixInverse * skinned ).xyz; -#endif`,rL=`#ifdef USE_SKINNING +#endif`,gL=`#ifdef USE_SKINNING mat4 skinMatrix = mat4( 0.0 ); skinMatrix += skinWeight.x * boneMatX; skinMatrix += skinWeight.y * boneMatY; @@ -2022,17 +2022,17 @@ gl_Position = projectionMatrix * mvPosition;`,YI=`#ifdef DITHERING #ifdef USE_TANGENT objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; #endif -#endif`,oL=`float specularStrength; +#endif`,yL=`float specularStrength; #ifdef USE_SPECULARMAP vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); specularStrength = texelSpecular.r; #else specularStrength = 1.0; -#endif`,lL=`#ifdef USE_SPECULARMAP +#endif`,vL=`#ifdef USE_SPECULARMAP uniform sampler2D specularMap; -#endif`,cL=`#if defined( TONE_MAPPING ) +#endif`,bL=`#if defined( TONE_MAPPING ) gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); -#endif`,uL=`#ifndef saturate +#endif`,xL=`#ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif uniform float toneMappingExposure; @@ -2129,7 +2129,7 @@ vec3 NeutralToneMapping( vec3 color ) { float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); return mix( color, vec3( newPeak ), g ); } -vec3 CustomToneMapping( vec3 color ) { return color; }`,dL=`#ifdef USE_TRANSMISSION +vec3 CustomToneMapping( vec3 color ) { return color; }`,wL=`#ifdef USE_TRANSMISSION material.transmission = transmission; material.transmissionAlpha = 1.0; material.thickness = thickness; @@ -2150,7 +2150,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,dL=`#ifdef USE_TRANSMISS material.attenuationColor, material.attenuationDistance ); material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); -#endif`,hL=`#ifdef USE_TRANSMISSION +#endif`,SL=`#ifdef USE_TRANSMISSION uniform float transmission; uniform float thickness; uniform float attenuationDistance; @@ -2276,7 +2276,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,dL=`#ifdef USE_TRANSMISS float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); } -#endif`,fL=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) +#endif`,TL=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP @@ -2346,7 +2346,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,dL=`#ifdef USE_TRANSMISS #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; -#endif`,pL=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) +#endif`,ML=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP @@ -2440,7 +2440,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,dL=`#ifdef USE_TRANSMISS #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; -#endif`,mL=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) +#endif`,EL=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) vUv = vec3( uv, 1 ).xy; #endif #ifdef USE_MAP @@ -2511,7 +2511,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,dL=`#ifdef USE_TRANSMISS #endif #ifdef USE_THICKNESSMAP vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; -#endif`,_L=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 +#endif`,CL=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 vec4 worldPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING worldPosition = batchingMatrix * worldPosition; @@ -2520,12 +2520,12 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,dL=`#ifdef USE_TRANSMISS worldPosition = instanceMatrix * worldPosition; #endif worldPosition = modelMatrix * worldPosition; -#endif`;const gL=`varying vec2 vUv; +#endif`;const AL=`varying vec2 vUv; uniform mat3 uvTransform; void main() { vUv = ( uvTransform * vec3( uv, 1 ) ).xy; gl_Position = vec4( position.xy, 1.0, 1.0 ); -}`,yL=`uniform sampler2D t2D; +}`,RL=`uniform sampler2D t2D; uniform float backgroundIntensity; varying vec2 vUv; void main() { @@ -2537,14 +2537,14 @@ void main() { gl_FragColor = texColor; #include #include -}`,vL=`varying vec3 vWorldDirection; +}`,PL=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; -}`,bL=`#ifdef ENVMAP_TYPE_CUBE +}`,IL=`#ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #elif defined( ENVMAP_TYPE_CUBE_UV ) uniform sampler2D envMap; @@ -2567,14 +2567,14 @@ void main() { gl_FragColor = texColor; #include #include -}`,xL=`varying vec3 vWorldDirection; +}`,LL=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; -}`,wL=`uniform samplerCube tCube; +}`,kL=`uniform samplerCube tCube; uniform float tFlip; uniform float opacity; varying vec3 vWorldDirection; @@ -2584,7 +2584,7 @@ void main() { gl_FragColor.a *= opacity; #include #include -}`,SL=`#include +}`,DL=`#include #include #include #include @@ -2611,7 +2611,7 @@ void main() { #include #include vHighPrecisionZW = gl_Position.zw; -}`,TL=`#if DEPTH_PACKING == 3200 +}`,OL=`#if DEPTH_PACKING == 3200 uniform float opacity; #endif #include @@ -2649,7 +2649,7 @@ void main() { #elif DEPTH_PACKING == 3203 gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); #endif -}`,ML=`#define DISTANCE +}`,FL=`#define DISTANCE varying vec3 vWorldPosition; #include #include @@ -2676,7 +2676,7 @@ void main() { #include #include vWorldPosition = worldPosition.xyz; -}`,EL=`#define DISTANCE +}`,NL=`#define DISTANCE uniform vec3 referencePosition; uniform float nearDistance; uniform float farDistance; @@ -2700,13 +2700,13 @@ void main () { dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); dist = saturate( dist ); gl_FragColor = packDepthToRGBA( dist ); -}`,CL=`varying vec3 vWorldDirection; +}`,UL=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include -}`,AL=`uniform sampler2D tEquirect; +}`,BL=`uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { @@ -2715,7 +2715,7 @@ void main() { gl_FragColor = texture2D( tEquirect, sampleUV ); #include #include -}`,RL=`uniform float scale; +}`,zL=`uniform float scale; attribute float lineDistance; varying float vLineDistance; #include @@ -2737,7 +2737,7 @@ void main() { #include #include #include -}`,PL=`uniform vec3 diffuse; +}`,HL=`uniform vec3 diffuse; uniform float opacity; uniform float dashSize; uniform float totalSize; @@ -2765,7 +2765,7 @@ void main() { #include #include #include -}`,IL=`#include +}`,VL=`#include #include #include #include @@ -2797,7 +2797,7 @@ void main() { #include #include #include -}`,LL=`uniform vec3 diffuse; +}`,GL=`uniform vec3 diffuse; uniform float opacity; #ifndef FLAT_SHADED varying vec3 vNormal; @@ -2845,7 +2845,7 @@ void main() { #include #include #include -}`,DL=`#define LAMBERT +}`,$L=`#define LAMBERT varying vec3 vViewPosition; #include #include @@ -2884,7 +2884,7 @@ void main() { #include #include #include -}`,kL=`#define LAMBERT +}`,WL=`#define LAMBERT uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; @@ -2941,7 +2941,7 @@ void main() { #include #include #include -}`,OL=`#define MATCAP +}`,XL=`#define MATCAP varying vec3 vViewPosition; #include #include @@ -2975,7 +2975,7 @@ void main() { #include #include vViewPosition = - mvPosition.xyz; -}`,FL=`#define MATCAP +}`,KL=`#define MATCAP uniform vec3 diffuse; uniform float opacity; uniform sampler2D matcap; @@ -3021,7 +3021,7 @@ void main() { #include #include #include -}`,NL=`#define NORMAL +}`,qL=`#define NORMAL #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif @@ -3054,7 +3054,7 @@ void main() { #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) vViewPosition = - mvPosition.xyz; #endif -}`,UL=`#define NORMAL +}`,YL=`#define NORMAL uniform float opacity; #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; @@ -3076,7 +3076,7 @@ void main() { #ifdef OPAQUE gl_FragColor.a = 1.0; #endif -}`,BL=`#define PHONG +}`,jL=`#define PHONG varying vec3 vViewPosition; #include #include @@ -3115,7 +3115,7 @@ void main() { #include #include #include -}`,zL=`#define PHONG +}`,ZL=`#define PHONG uniform vec3 diffuse; uniform vec3 emissive; uniform vec3 specular; @@ -3174,7 +3174,7 @@ void main() { #include #include #include -}`,HL=`#define STANDARD +}`,JL=`#define STANDARD varying vec3 vViewPosition; #ifdef USE_TRANSMISSION varying vec3 vWorldPosition; @@ -3217,7 +3217,7 @@ void main() { #ifdef USE_TRANSMISSION vWorldPosition = worldPosition.xyz; #endif -}`,VL=`#define STANDARD +}`,QL=`#define STANDARD #ifdef PHYSICAL #define IOR #define USE_SPECULAR @@ -3342,7 +3342,7 @@ void main() { #include #include #include -}`,GL=`#define TOON +}`,e2=`#define TOON varying vec3 vViewPosition; #include #include @@ -3379,7 +3379,7 @@ void main() { #include #include #include -}`,$L=`#define TOON +}`,t2=`#define TOON uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; @@ -3432,7 +3432,7 @@ void main() { #include #include #include -}`,WL=`uniform float size; +}`,n2=`uniform float size; uniform float scale; #include #include @@ -3463,7 +3463,7 @@ void main() { #include #include #include -}`,XL=`uniform vec3 diffuse; +}`,i2=`uniform vec3 diffuse; uniform float opacity; #include #include @@ -3488,7 +3488,7 @@ void main() { #include #include #include -}`,KL=`#include +}`,s2=`#include #include #include #include @@ -3511,7 +3511,7 @@ void main() { #include #include #include -}`,qL=`uniform vec3 color; +}`,a2=`uniform vec3 color; uniform float opacity; #include #include @@ -3527,7 +3527,7 @@ void main() { #include #include #include -}`,YL=`uniform float rotation; +}`,r2=`uniform float rotation; uniform vec2 center; #include #include @@ -3551,7 +3551,7 @@ void main() { #include #include #include -}`,jL=`uniform vec3 diffuse; +}`,o2=`uniform vec3 diffuse; uniform float opacity; #include #include @@ -3576,7 +3576,7 @@ void main() { #include #include #include -}`,mt={alphahash_fragment:yP,alphahash_pars_fragment:vP,alphamap_fragment:bP,alphamap_pars_fragment:xP,alphatest_fragment:wP,alphatest_pars_fragment:SP,aomap_fragment:TP,aomap_pars_fragment:MP,batching_pars_vertex:EP,batching_vertex:CP,begin_vertex:AP,beginnormal_vertex:RP,bsdfs:PP,iridescence_fragment:IP,bumpmap_pars_fragment:LP,clipping_planes_fragment:DP,clipping_planes_pars_fragment:kP,clipping_planes_pars_vertex:OP,clipping_planes_vertex:FP,color_fragment:NP,color_pars_fragment:UP,color_pars_vertex:BP,color_vertex:zP,common:HP,cube_uv_reflection_fragment:VP,defaultnormal_vertex:GP,displacementmap_pars_vertex:$P,displacementmap_vertex:WP,emissivemap_fragment:XP,emissivemap_pars_fragment:KP,colorspace_fragment:qP,colorspace_pars_fragment:YP,envmap_fragment:jP,envmap_common_pars_fragment:ZP,envmap_pars_fragment:JP,envmap_pars_vertex:QP,envmap_physical_pars_fragment:uI,envmap_vertex:eI,fog_vertex:tI,fog_pars_vertex:nI,fog_fragment:iI,fog_pars_fragment:sI,gradientmap_pars_fragment:aI,lightmap_pars_fragment:rI,lights_lambert_fragment:oI,lights_lambert_pars_fragment:lI,lights_pars_begin:cI,lights_toon_fragment:dI,lights_toon_pars_fragment:hI,lights_phong_fragment:fI,lights_phong_pars_fragment:pI,lights_physical_fragment:mI,lights_physical_pars_fragment:_I,lights_fragment_begin:gI,lights_fragment_maps:yI,lights_fragment_end:vI,logdepthbuf_fragment:bI,logdepthbuf_pars_fragment:xI,logdepthbuf_pars_vertex:wI,logdepthbuf_vertex:SI,map_fragment:TI,map_pars_fragment:MI,map_particle_fragment:EI,map_particle_pars_fragment:CI,metalnessmap_fragment:AI,metalnessmap_pars_fragment:RI,morphinstance_vertex:PI,morphcolor_vertex:II,morphnormal_vertex:LI,morphtarget_pars_vertex:DI,morphtarget_vertex:kI,normal_fragment_begin:OI,normal_fragment_maps:FI,normal_pars_fragment:NI,normal_pars_vertex:UI,normal_vertex:BI,normalmap_pars_fragment:zI,clearcoat_normal_fragment_begin:HI,clearcoat_normal_fragment_maps:VI,clearcoat_pars_fragment:GI,iridescence_pars_fragment:$I,opaque_fragment:WI,packing:XI,premultiplied_alpha_fragment:KI,project_vertex:qI,dithering_fragment:YI,dithering_pars_fragment:jI,roughnessmap_fragment:ZI,roughnessmap_pars_fragment:JI,shadowmap_pars_fragment:QI,shadowmap_pars_vertex:eL,shadowmap_vertex:tL,shadowmask_pars_fragment:nL,skinbase_vertex:iL,skinning_pars_vertex:sL,skinning_vertex:aL,skinnormal_vertex:rL,specularmap_fragment:oL,specularmap_pars_fragment:lL,tonemapping_fragment:cL,tonemapping_pars_fragment:uL,transmission_fragment:dL,transmission_pars_fragment:hL,uv_pars_fragment:fL,uv_pars_vertex:pL,uv_vertex:mL,worldpos_vertex:_L,background_vert:gL,background_frag:yL,backgroundCube_vert:vL,backgroundCube_frag:bL,cube_vert:xL,cube_frag:wL,depth_vert:SL,depth_frag:TL,distanceRGBA_vert:ML,distanceRGBA_frag:EL,equirect_vert:CL,equirect_frag:AL,linedashed_vert:RL,linedashed_frag:PL,meshbasic_vert:IL,meshbasic_frag:LL,meshlambert_vert:DL,meshlambert_frag:kL,meshmatcap_vert:OL,meshmatcap_frag:FL,meshnormal_vert:NL,meshnormal_frag:UL,meshphong_vert:BL,meshphong_frag:zL,meshphysical_vert:HL,meshphysical_frag:VL,meshtoon_vert:GL,meshtoon_frag:$L,points_vert:WL,points_frag:XL,shadow_vert:KL,shadow_frag:qL,sprite_vert:YL,sprite_frag:jL},Te={common:{diffuse:{value:new ue(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new st},alphaMap:{value:null},alphaMapTransform:{value:new st},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new st}},envmap:{envMap:{value:null},envMapRotation:{value:new st},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new st}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new st}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new st},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new st},normalScale:{value:new te(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new st},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new st}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new st}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new st}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new ue(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new ue(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new st},alphaTest:{value:0},uvTransform:{value:new st}},sprite:{diffuse:{value:new ue(16777215)},opacity:{value:1},center:{value:new te(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new st},alphaMap:{value:null},alphaMapTransform:{value:new st},alphaTest:{value:0}}},Wi={basic:{uniforms:Nn([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.fog]),vertexShader:mt.meshbasic_vert,fragmentShader:mt.meshbasic_frag},lambert:{uniforms:Nn([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,Te.lights,{emissive:{value:new ue(0)}}]),vertexShader:mt.meshlambert_vert,fragmentShader:mt.meshlambert_frag},phong:{uniforms:Nn([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,Te.lights,{emissive:{value:new ue(0)},specular:{value:new ue(1118481)},shininess:{value:30}}]),vertexShader:mt.meshphong_vert,fragmentShader:mt.meshphong_frag},standard:{uniforms:Nn([Te.common,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.roughnessmap,Te.metalnessmap,Te.fog,Te.lights,{emissive:{value:new ue(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:mt.meshphysical_vert,fragmentShader:mt.meshphysical_frag},toon:{uniforms:Nn([Te.common,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.gradientmap,Te.fog,Te.lights,{emissive:{value:new ue(0)}}]),vertexShader:mt.meshtoon_vert,fragmentShader:mt.meshtoon_frag},matcap:{uniforms:Nn([Te.common,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,{matcap:{value:null}}]),vertexShader:mt.meshmatcap_vert,fragmentShader:mt.meshmatcap_frag},points:{uniforms:Nn([Te.points,Te.fog]),vertexShader:mt.points_vert,fragmentShader:mt.points_frag},dashed:{uniforms:Nn([Te.common,Te.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:mt.linedashed_vert,fragmentShader:mt.linedashed_frag},depth:{uniforms:Nn([Te.common,Te.displacementmap]),vertexShader:mt.depth_vert,fragmentShader:mt.depth_frag},normal:{uniforms:Nn([Te.common,Te.bumpmap,Te.normalmap,Te.displacementmap,{opacity:{value:1}}]),vertexShader:mt.meshnormal_vert,fragmentShader:mt.meshnormal_frag},sprite:{uniforms:Nn([Te.sprite,Te.fog]),vertexShader:mt.sprite_vert,fragmentShader:mt.sprite_frag},background:{uniforms:{uvTransform:{value:new st},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:mt.background_vert,fragmentShader:mt.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new st}},vertexShader:mt.backgroundCube_vert,fragmentShader:mt.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:mt.cube_vert,fragmentShader:mt.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:mt.equirect_vert,fragmentShader:mt.equirect_frag},distanceRGBA:{uniforms:Nn([Te.common,Te.displacementmap,{referencePosition:{value:new S},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:mt.distanceRGBA_vert,fragmentShader:mt.distanceRGBA_frag},shadow:{uniforms:Nn([Te.lights,Te.fog,{color:{value:new ue(0)},opacity:{value:1}}]),vertexShader:mt.shadow_vert,fragmentShader:mt.shadow_frag}};Wi.physical={uniforms:Nn([Wi.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new st},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new st},clearcoatNormalScale:{value:new te(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new st},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new st},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new st},sheen:{value:0},sheenColor:{value:new ue(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new st},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new st},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new st},transmissionSamplerSize:{value:new te},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new st},attenuationDistance:{value:0},attenuationColor:{value:new ue(0)},specularColor:{value:new ue(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new st},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new st},anisotropyVector:{value:new te},anisotropyMap:{value:null},anisotropyMapTransform:{value:new st}}]),vertexShader:mt.meshphysical_vert,fragmentShader:mt.meshphysical_frag};const au={r:0,b:0,g:0},Ra=new an,ZL=new Me;function JL(n,e,t,i,s,a,r){const o=new ue(0);let l=a===!0?0:1,c,u,d=null,h=0,f=null;function p(y){let b=y.isScene===!0?y.background:null;return b&&b.isTexture&&(b=(y.backgroundBlurriness>0?t:e).get(b)),b}function g(y){let b=!1;const T=p(y);T===null?m(o,l):T&&T.isColor&&(m(T,1),b=!0);const x=n.xr.getEnvironmentBlendMode();x==="additive"?i.buffers.color.setClear(0,0,0,1,r):x==="alpha-blend"&&i.buffers.color.setClear(0,0,0,0,r),(n.autoClear||b)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),n.clear(n.autoClearColor,n.autoClearDepth,n.autoClearStencil))}function _(y,b){const T=p(b);T&&(T.isCubeTexture||T.mapping===Ao)?(u===void 0&&(u=new we(new Ei(1,1,1),new ti({name:"BackgroundCubeMaterial",uniforms:Mo(Wi.backgroundCube.uniforms),vertexShader:Wi.backgroundCube.vertexShader,fragmentShader:Wi.backgroundCube.fragmentShader,side:un,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(x,M,C){this.matrixWorld.copyPosition(C.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),s.update(u)),Ra.copy(b.backgroundRotation),Ra.x*=-1,Ra.y*=-1,Ra.z*=-1,T.isCubeTexture&&T.isRenderTargetTexture===!1&&(Ra.y*=-1,Ra.z*=-1),u.material.uniforms.envMap.value=T,u.material.uniforms.flipEnvMap.value=T.isCubeTexture&&T.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=b.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(ZL.makeRotationFromEuler(Ra)),u.material.toneMapped=at.getTransfer(T.colorSpace)!==Pt,(d!==T||h!==T.version||f!==n.toneMapping)&&(u.material.needsUpdate=!0,d=T,h=T.version,f=n.toneMapping),u.layers.enableAll(),y.unshift(u,u.geometry,u.material,0,0,null)):T&&T.isTexture&&(c===void 0&&(c=new we(new Dn(2,2),new ti({name:"BackgroundMaterial",uniforms:Mo(Wi.background.uniforms),vertexShader:Wi.background.vertexShader,fragmentShader:Wi.background.fragmentShader,side:fs,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),s.update(c)),c.material.uniforms.t2D.value=T,c.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,c.material.toneMapped=at.getTransfer(T.colorSpace)!==Pt,T.matrixAutoUpdate===!0&&T.updateMatrix(),c.material.uniforms.uvTransform.value.copy(T.matrix),(d!==T||h!==T.version||f!==n.toneMapping)&&(c.material.needsUpdate=!0,d=T,h=T.version,f=n.toneMapping),c.layers.enableAll(),y.unshift(c,c.geometry,c.material,0,0,null))}function m(y,b){y.getRGB(au,fS(n)),i.buffers.color.setClear(au.r,au.g,au.b,b,r)}function v(){u!==void 0&&(u.geometry.dispose(),u.material.dispose(),u=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return o},setClearColor:function(y,b=1){o.set(y),l=b,m(o,l)},getClearAlpha:function(){return l},setClearAlpha:function(y){l=y,m(o,l)},render:g,addToRenderList:_,dispose:v}}function QL(n,e){const t=n.getParameter(n.MAX_VERTEX_ATTRIBS),i={},s=h(null);let a=s,r=!1;function o(E,R,D,O,k){let U=!1;const F=d(O,D,R);a!==F&&(a=F,c(a.object)),U=f(E,O,D,k),U&&p(E,O,D,k),k!==null&&e.update(k,n.ELEMENT_ARRAY_BUFFER),(U||r)&&(r=!1,b(E,R,D,O),k!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e.get(k).buffer))}function l(){return n.createVertexArray()}function c(E){return n.bindVertexArray(E)}function u(E){return n.deleteVertexArray(E)}function d(E,R,D){const O=D.wireframe===!0;let k=i[E.id];k===void 0&&(k={},i[E.id]=k);let U=k[R.id];U===void 0&&(U={},k[R.id]=U);let F=U[O];return F===void 0&&(F=h(l()),U[O]=F),F}function h(E){const R=[],D=[],O=[];for(let k=0;k=0){const oe=k[H];let pe=U[H];if(pe===void 0&&(H==="instanceMatrix"&&E.instanceMatrix&&(pe=E.instanceMatrix),H==="instanceColor"&&E.instanceColor&&(pe=E.instanceColor)),oe===void 0||oe.attribute!==pe||pe&&oe.data!==pe.data)return!0;F++}return a.attributesNum!==F||a.index!==O}function p(E,R,D,O){const k={},U=R.attributes;let F=0;const W=D.getAttributes();for(const H in W)if(W[H].location>=0){let oe=U[H];oe===void 0&&(H==="instanceMatrix"&&E.instanceMatrix&&(oe=E.instanceMatrix),H==="instanceColor"&&E.instanceColor&&(oe=E.instanceColor));const pe={};pe.attribute=oe,oe&&oe.data&&(pe.data=oe.data),k[H]=pe,F++}a.attributes=k,a.attributesNum=F,a.index=O}function g(){const E=a.newAttributes;for(let R=0,D=E.length;R=0){let ne=k[W];if(ne===void 0&&(W==="instanceMatrix"&&E.instanceMatrix&&(ne=E.instanceMatrix),W==="instanceColor"&&E.instanceColor&&(ne=E.instanceColor)),ne!==void 0){const oe=ne.normalized,pe=ne.itemSize,Ie=e.get(ne);if(Ie===void 0)continue;const De=Ie.buffer,Xe=Ie.type,ke=Ie.bytesPerElement,Z=Xe===n.INT||Xe===n.UNSIGNED_INT||ne.gpuType===gh;if(ne.isInterleavedBufferAttribute){const se=ne.data,Se=se.stride,X=ne.offset;if(se.isInstancedInterleavedBuffer){for(let ie=0;ie0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision>0)return"highp";M="mediump"}return M==="mediump"&&n.getShaderPrecisionFormat(n.VERTEX_SHADER,n.MEDIUM_FLOAT).precision>0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=t.precision!==void 0?t.precision:"highp";const u=l(c);u!==c&&(console.warn("THREE.WebGLRenderer:",c,"not supported, using",u,"instead."),c=u);const d=t.logarithmicDepthBuffer===!0,h=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),f=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),p=n.getParameter(n.MAX_VERTEX_TEXTURE_IMAGE_UNITS),g=n.getParameter(n.MAX_TEXTURE_SIZE),_=n.getParameter(n.MAX_CUBE_MAP_TEXTURE_SIZE),m=n.getParameter(n.MAX_VERTEX_ATTRIBS),v=n.getParameter(n.MAX_VERTEX_UNIFORM_VECTORS),y=n.getParameter(n.MAX_VARYING_VECTORS),b=n.getParameter(n.MAX_FRAGMENT_UNIFORM_VECTORS),T=p>0,x=n.getParameter(n.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:l,textureFormatReadable:r,textureTypeReadable:o,precision:c,logarithmicDepthBuffer:d,reversedDepthBuffer:h,maxTextures:f,maxVertexTextures:p,maxTextureSize:g,maxCubemapSize:_,maxAttributes:m,maxVertexUniforms:v,maxVaryings:y,maxFragmentUniforms:b,vertexTextures:T,maxSamples:x}}function n2(n){const e=this;let t=null,i=0,s=!1,a=!1;const r=new Ps,o=new st,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(d,h){const f=d.length!==0||h||i!==0||s;return s=h,i=d.length,f},this.beginShadows=function(){a=!0,u(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(d,h){t=u(d,h,0)},this.setState=function(d,h,f){const p=d.clippingPlanes,g=d.clipIntersection,_=d.clipShadows,m=n.get(d);if(!s||p===null||p.length===0||a&&!_)a?u(null):c();else{const v=a?0:i,y=v*4;let b=m.clippingState||null;l.value=b,b=u(p,h,y,f);for(let T=0;T!==y;++T)b[T]=t[T];m.clippingState=b,this.numIntersection=g?this.numPlanes:0,this.numPlanes+=v}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function u(d,h,f,p){const g=d!==null?d.length:0;let _=null;if(g!==0){if(_=l.value,p!==!0||_===null){const m=f+g*4,v=h.matrixWorldInverse;o.getNormalMatrix(v),(_===null||_.length0){const c=new _S(l.height);return c.fromEquirectangularTexture(n,r),e.set(r,c),r.addEventListener("dispose",s),t(c.texture,r.mapping)}else return null}}return r}function s(r){const o=r.target;o.removeEventListener("dispose",s);const l=e.get(o);l!==void 0&&(e.delete(o),l.dispose())}function a(){e=new WeakMap}return{get:i,dispose:a}}const jr=4,y0=[.125,.215,.35,.446,.526,.582],Ha=20,Jf=new uc,v0=new ue;let Qf=null,ep=0,tp=0,np=!1;const Ba=(1+Math.sqrt(5))/2,Ur=1/Ba,b0=[new S(-Ba,Ur,0),new S(Ba,Ur,0),new S(-Ur,0,Ba),new S(Ur,0,Ba),new S(0,Ba,-Ur),new S(0,Ba,Ur),new S(-1,1,-1),new S(1,1,-1),new S(-1,1,1),new S(1,1,1)],s2=new S;class Jd{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,i=.1,s=100,a={}){const{size:r=256,position:o=s2}=a;Qf=this._renderer.getRenderTarget(),ep=this._renderer.getActiveCubeFace(),tp=this._renderer.getActiveMipmapLevel(),np=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(r);const l=this._allocateTargets();return l.depthBuffer=!0,this._sceneToCubeUV(e,i,s,l,o),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=S0(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=w0(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?T:0,T,T),d.setRenderTarget(s),m&&d.render(_,l),d.render(e,l)}_.geometry.dispose(),_.material.dispose(),d.toneMapping=f,d.autoClear=h,e.background=v}_textureToCubeUV(e,t){const i=this._renderer,s=e.mapping===Bs||e.mapping===oa;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=S0()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=w0());const a=s?this._cubemapMaterial:this._equirectMaterial,r=new we(this._lodPlanes[0],a),o=a.uniforms;o.envMap.value=e;const l=this._cubeSize;ru(t,0,0,3*l,2*l),i.setRenderTarget(t),i.render(r,Jf)}_applyPMREM(e){const t=this._renderer,i=t.autoClear;t.autoClear=!1;const s=this._lodPlanes.length;for(let a=1;aHa&&console.warn(`sigmaRadians, ${a}, is too large and will clip, as it requested ${_} samples when the maximum is set to ${Ha}`);const m=[];let v=0;for(let M=0;My-jr?s-y+jr:0),x=4*(this._cubeSize-b);ru(t,T,x,3*b,2*b),l.setRenderTarget(t),l.render(d,Jf)}}function a2(n){const e=[],t=[],i=[];let s=n;const a=n-jr+1+y0.length;for(let r=0;rn-jr?l=y0[r-n+jr-1]:r===0&&(l=0),i.push(l);const c=1/(o-2),u=-c,d=1+c,h=[u,u,d,u,d,d,u,u,d,d,u,d],f=6,p=6,g=3,_=2,m=1,v=new Float32Array(g*p*f),y=new Float32Array(_*p*f),b=new Float32Array(m*p*f);for(let x=0;x2?0:-1,w=[M,C,0,M+2/3,C,0,M+2/3,C+1,0,M,C,0,M+2/3,C+1,0,M,C+1,0];v.set(w,g*p*x),y.set(h,_*p*x);const E=[x,x,x,x,x,x];b.set(E,m*p*x)}const T=new Ge;T.setAttribute("position",new rt(v,g)),T.setAttribute("uv",new rt(y,_)),T.setAttribute("faceIndex",new rt(b,m)),e.push(T),s>jr&&s--}return{lodPlanes:e,sizeLods:t,sigmas:i}}function x0(n,e,t){const i=new ms(n,e,t);return i.texture.mapping=Ao,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function ru(n,e,t,i,s){n.viewport.set(e,t,i,s),n.scissor.set(e,t,i,s)}function r2(n,e,t){const i=new Float32Array(Ha),s=new S(0,1,0);return new ti({name:"SphericalGaussianBlur",defines:{n:Ha,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:s}},vertexShader:Mg(),fragmentShader:` +}`,mt={alphahash_fragment:RP,alphahash_pars_fragment:PP,alphamap_fragment:IP,alphamap_pars_fragment:LP,alphatest_fragment:kP,alphatest_pars_fragment:DP,aomap_fragment:OP,aomap_pars_fragment:FP,batching_pars_vertex:NP,batching_vertex:UP,begin_vertex:BP,beginnormal_vertex:zP,bsdfs:HP,iridescence_fragment:VP,bumpmap_pars_fragment:GP,clipping_planes_fragment:$P,clipping_planes_pars_fragment:WP,clipping_planes_pars_vertex:XP,clipping_planes_vertex:KP,color_fragment:qP,color_pars_fragment:YP,color_pars_vertex:jP,color_vertex:ZP,common:JP,cube_uv_reflection_fragment:QP,defaultnormal_vertex:eI,displacementmap_pars_vertex:tI,displacementmap_vertex:nI,emissivemap_fragment:iI,emissivemap_pars_fragment:sI,colorspace_fragment:aI,colorspace_pars_fragment:rI,envmap_fragment:oI,envmap_common_pars_fragment:lI,envmap_pars_fragment:cI,envmap_pars_vertex:uI,envmap_physical_pars_fragment:xI,envmap_vertex:dI,fog_vertex:hI,fog_pars_vertex:fI,fog_fragment:pI,fog_pars_fragment:mI,gradientmap_pars_fragment:_I,lightmap_pars_fragment:gI,lights_lambert_fragment:yI,lights_lambert_pars_fragment:vI,lights_pars_begin:bI,lights_toon_fragment:wI,lights_toon_pars_fragment:SI,lights_phong_fragment:TI,lights_phong_pars_fragment:MI,lights_physical_fragment:EI,lights_physical_pars_fragment:CI,lights_fragment_begin:AI,lights_fragment_maps:RI,lights_fragment_end:PI,logdepthbuf_fragment:II,logdepthbuf_pars_fragment:LI,logdepthbuf_pars_vertex:kI,logdepthbuf_vertex:DI,map_fragment:OI,map_pars_fragment:FI,map_particle_fragment:NI,map_particle_pars_fragment:UI,metalnessmap_fragment:BI,metalnessmap_pars_fragment:zI,morphinstance_vertex:HI,morphcolor_vertex:VI,morphnormal_vertex:GI,morphtarget_pars_vertex:$I,morphtarget_vertex:WI,normal_fragment_begin:XI,normal_fragment_maps:KI,normal_pars_fragment:qI,normal_pars_vertex:YI,normal_vertex:jI,normalmap_pars_fragment:ZI,clearcoat_normal_fragment_begin:JI,clearcoat_normal_fragment_maps:QI,clearcoat_pars_fragment:eL,iridescence_pars_fragment:tL,opaque_fragment:nL,packing:iL,premultiplied_alpha_fragment:sL,project_vertex:aL,dithering_fragment:rL,dithering_pars_fragment:oL,roughnessmap_fragment:lL,roughnessmap_pars_fragment:cL,shadowmap_pars_fragment:uL,shadowmap_pars_vertex:dL,shadowmap_vertex:hL,shadowmask_pars_fragment:fL,skinbase_vertex:pL,skinning_pars_vertex:mL,skinning_vertex:_L,skinnormal_vertex:gL,specularmap_fragment:yL,specularmap_pars_fragment:vL,tonemapping_fragment:bL,tonemapping_pars_fragment:xL,transmission_fragment:wL,transmission_pars_fragment:SL,uv_pars_fragment:TL,uv_pars_vertex:ML,uv_vertex:EL,worldpos_vertex:CL,background_vert:AL,background_frag:RL,backgroundCube_vert:PL,backgroundCube_frag:IL,cube_vert:LL,cube_frag:kL,depth_vert:DL,depth_frag:OL,distanceRGBA_vert:FL,distanceRGBA_frag:NL,equirect_vert:UL,equirect_frag:BL,linedashed_vert:zL,linedashed_frag:HL,meshbasic_vert:VL,meshbasic_frag:GL,meshlambert_vert:$L,meshlambert_frag:WL,meshmatcap_vert:XL,meshmatcap_frag:KL,meshnormal_vert:qL,meshnormal_frag:YL,meshphong_vert:jL,meshphong_frag:ZL,meshphysical_vert:JL,meshphysical_frag:QL,meshtoon_vert:e2,meshtoon_frag:t2,points_vert:n2,points_frag:i2,shadow_vert:s2,shadow_frag:a2,sprite_vert:r2,sprite_frag:o2},Te={common:{diffuse:{value:new ue(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new at},alphaMap:{value:null},alphaMapTransform:{value:new at},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new at}},envmap:{envMap:{value:null},envMapRotation:{value:new at},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new at}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new at}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new at},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new at},normalScale:{value:new te(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new at},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new at}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new at}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new at}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new ue(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new ue(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new at},alphaTest:{value:0},uvTransform:{value:new at}},sprite:{diffuse:{value:new ue(16777215)},opacity:{value:1},center:{value:new te(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new at},alphaMap:{value:null},alphaMapTransform:{value:new at},alphaTest:{value:0}}},Xi={basic:{uniforms:Nn([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.fog]),vertexShader:mt.meshbasic_vert,fragmentShader:mt.meshbasic_frag},lambert:{uniforms:Nn([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,Te.lights,{emissive:{value:new ue(0)}}]),vertexShader:mt.meshlambert_vert,fragmentShader:mt.meshlambert_frag},phong:{uniforms:Nn([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,Te.lights,{emissive:{value:new ue(0)},specular:{value:new ue(1118481)},shininess:{value:30}}]),vertexShader:mt.meshphong_vert,fragmentShader:mt.meshphong_frag},standard:{uniforms:Nn([Te.common,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.roughnessmap,Te.metalnessmap,Te.fog,Te.lights,{emissive:{value:new ue(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:mt.meshphysical_vert,fragmentShader:mt.meshphysical_frag},toon:{uniforms:Nn([Te.common,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.gradientmap,Te.fog,Te.lights,{emissive:{value:new ue(0)}}]),vertexShader:mt.meshtoon_vert,fragmentShader:mt.meshtoon_frag},matcap:{uniforms:Nn([Te.common,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,{matcap:{value:null}}]),vertexShader:mt.meshmatcap_vert,fragmentShader:mt.meshmatcap_frag},points:{uniforms:Nn([Te.points,Te.fog]),vertexShader:mt.points_vert,fragmentShader:mt.points_frag},dashed:{uniforms:Nn([Te.common,Te.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:mt.linedashed_vert,fragmentShader:mt.linedashed_frag},depth:{uniforms:Nn([Te.common,Te.displacementmap]),vertexShader:mt.depth_vert,fragmentShader:mt.depth_frag},normal:{uniforms:Nn([Te.common,Te.bumpmap,Te.normalmap,Te.displacementmap,{opacity:{value:1}}]),vertexShader:mt.meshnormal_vert,fragmentShader:mt.meshnormal_frag},sprite:{uniforms:Nn([Te.sprite,Te.fog]),vertexShader:mt.sprite_vert,fragmentShader:mt.sprite_frag},background:{uniforms:{uvTransform:{value:new at},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:mt.background_vert,fragmentShader:mt.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new at}},vertexShader:mt.backgroundCube_vert,fragmentShader:mt.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:mt.cube_vert,fragmentShader:mt.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:mt.equirect_vert,fragmentShader:mt.equirect_frag},distanceRGBA:{uniforms:Nn([Te.common,Te.displacementmap,{referencePosition:{value:new S},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:mt.distanceRGBA_vert,fragmentShader:mt.distanceRGBA_frag},shadow:{uniforms:Nn([Te.lights,Te.fog,{color:{value:new ue(0)},opacity:{value:1}}]),vertexShader:mt.shadow_vert,fragmentShader:mt.shadow_frag}};Xi.physical={uniforms:Nn([Xi.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new at},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new at},clearcoatNormalScale:{value:new te(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new at},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new at},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new at},sheen:{value:0},sheenColor:{value:new ue(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new at},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new at},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new at},transmissionSamplerSize:{value:new te},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new at},attenuationDistance:{value:0},attenuationColor:{value:new ue(0)},specularColor:{value:new ue(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new at},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new at},anisotropyVector:{value:new te},anisotropyMap:{value:null},anisotropyMapTransform:{value:new at}}]),vertexShader:mt.meshphysical_vert,fragmentShader:mt.meshphysical_frag};const cu={r:0,b:0,g:0},Pa=new an,l2=new Me;function c2(n,e,t,i,s,a,r){const o=new ue(0);let l=a===!0?0:1,c,u,d=null,h=0,f=null;function p(y){let b=y.isScene===!0?y.background:null;return b&&b.isTexture&&(b=(y.backgroundBlurriness>0?t:e).get(b)),b}function g(y){let b=!1;const T=p(y);T===null?m(o,l):T&&T.isColor&&(m(T,1),b=!0);const x=n.xr.getEnvironmentBlendMode();x==="additive"?i.buffers.color.setClear(0,0,0,1,r):x==="alpha-blend"&&i.buffers.color.setClear(0,0,0,0,r),(n.autoClear||b)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),n.clear(n.autoClearColor,n.autoClearDepth,n.autoClearStencil))}function _(y,b){const T=p(b);T&&(T.isCubeTexture||T.mapping===Io)?(u===void 0&&(u=new we(new Ci(1,1,1),new ti({name:"BackgroundCubeMaterial",uniforms:Ao(Xi.backgroundCube.uniforms),vertexShader:Xi.backgroundCube.vertexShader,fragmentShader:Xi.backgroundCube.fragmentShader,side:un,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(x,M,C){this.matrixWorld.copyPosition(C.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),s.update(u)),Pa.copy(b.backgroundRotation),Pa.x*=-1,Pa.y*=-1,Pa.z*=-1,T.isCubeTexture&&T.isRenderTargetTexture===!1&&(Pa.y*=-1,Pa.z*=-1),u.material.uniforms.envMap.value=T,u.material.uniforms.flipEnvMap.value=T.isCubeTexture&&T.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=b.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(l2.makeRotationFromEuler(Pa)),u.material.toneMapped=rt.getTransfer(T.colorSpace)!==Pt,(d!==T||h!==T.version||f!==n.toneMapping)&&(u.material.needsUpdate=!0,d=T,h=T.version,f=n.toneMapping),u.layers.enableAll(),y.unshift(u,u.geometry,u.material,0,0,null)):T&&T.isTexture&&(c===void 0&&(c=new we(new kn(2,2),new ti({name:"BackgroundMaterial",uniforms:Ao(Xi.background.uniforms),vertexShader:Xi.background.vertexShader,fragmentShader:Xi.background.fragmentShader,side:fs,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),s.update(c)),c.material.uniforms.t2D.value=T,c.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,c.material.toneMapped=rt.getTransfer(T.colorSpace)!==Pt,T.matrixAutoUpdate===!0&&T.updateMatrix(),c.material.uniforms.uvTransform.value.copy(T.matrix),(d!==T||h!==T.version||f!==n.toneMapping)&&(c.material.needsUpdate=!0,d=T,h=T.version,f=n.toneMapping),c.layers.enableAll(),y.unshift(c,c.geometry,c.material,0,0,null))}function m(y,b){y.getRGB(cu,xS(n)),i.buffers.color.setClear(cu.r,cu.g,cu.b,b,r)}function v(){u!==void 0&&(u.geometry.dispose(),u.material.dispose(),u=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return o},setClearColor:function(y,b=1){o.set(y),l=b,m(o,l)},getClearAlpha:function(){return l},setClearAlpha:function(y){l=y,m(o,l)},render:g,addToRenderList:_,dispose:v}}function u2(n,e){const t=n.getParameter(n.MAX_VERTEX_ATTRIBS),i={},s=h(null);let a=s,r=!1;function o(E,R,k,O,D){let U=!1;const F=d(O,k,R);a!==F&&(a=F,c(a.object)),U=f(E,O,k,D),U&&p(E,O,k,D),D!==null&&e.update(D,n.ELEMENT_ARRAY_BUFFER),(U||r)&&(r=!1,b(E,R,k,O),D!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e.get(D).buffer))}function l(){return n.createVertexArray()}function c(E){return n.bindVertexArray(E)}function u(E){return n.deleteVertexArray(E)}function d(E,R,k){const O=k.wireframe===!0;let D=i[E.id];D===void 0&&(D={},i[E.id]=D);let U=D[R.id];U===void 0&&(U={},D[R.id]=U);let F=U[O];return F===void 0&&(F=h(l()),U[O]=F),F}function h(E){const R=[],k=[],O=[];for(let D=0;D=0){const oe=D[H];let pe=U[H];if(pe===void 0&&(H==="instanceMatrix"&&E.instanceMatrix&&(pe=E.instanceMatrix),H==="instanceColor"&&E.instanceColor&&(pe=E.instanceColor)),oe===void 0||oe.attribute!==pe||pe&&oe.data!==pe.data)return!0;F++}return a.attributesNum!==F||a.index!==O}function p(E,R,k,O){const D={},U=R.attributes;let F=0;const W=k.getAttributes();for(const H in W)if(W[H].location>=0){let oe=U[H];oe===void 0&&(H==="instanceMatrix"&&E.instanceMatrix&&(oe=E.instanceMatrix),H==="instanceColor"&&E.instanceColor&&(oe=E.instanceColor));const pe={};pe.attribute=oe,oe&&oe.data&&(pe.data=oe.data),D[H]=pe,F++}a.attributes=D,a.attributesNum=F,a.index=O}function g(){const E=a.newAttributes;for(let R=0,k=E.length;R=0){let ne=D[W];if(ne===void 0&&(W==="instanceMatrix"&&E.instanceMatrix&&(ne=E.instanceMatrix),W==="instanceColor"&&E.instanceColor&&(ne=E.instanceColor)),ne!==void 0){const oe=ne.normalized,pe=ne.itemSize,Ie=e.get(ne);if(Ie===void 0)continue;const ke=Ie.buffer,Xe=Ie.type,De=Ie.bytesPerElement,Z=Xe===n.INT||Xe===n.UNSIGNED_INT||ne.gpuType===Sh;if(ne.isInterleavedBufferAttribute){const ae=ne.data,Se=ae.stride,X=ne.offset;if(ae.isInstancedInterleavedBuffer){for(let ie=0;ie0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision>0)return"highp";M="mediump"}return M==="mediump"&&n.getShaderPrecisionFormat(n.VERTEX_SHADER,n.MEDIUM_FLOAT).precision>0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=t.precision!==void 0?t.precision:"highp";const u=l(c);u!==c&&(console.warn("THREE.WebGLRenderer:",c,"not supported, using",u,"instead."),c=u);const d=t.logarithmicDepthBuffer===!0,h=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),f=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),p=n.getParameter(n.MAX_VERTEX_TEXTURE_IMAGE_UNITS),g=n.getParameter(n.MAX_TEXTURE_SIZE),_=n.getParameter(n.MAX_CUBE_MAP_TEXTURE_SIZE),m=n.getParameter(n.MAX_VERTEX_ATTRIBS),v=n.getParameter(n.MAX_VERTEX_UNIFORM_VECTORS),y=n.getParameter(n.MAX_VARYING_VECTORS),b=n.getParameter(n.MAX_FRAGMENT_UNIFORM_VECTORS),T=p>0,x=n.getParameter(n.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:l,textureFormatReadable:r,textureTypeReadable:o,precision:c,logarithmicDepthBuffer:d,reversedDepthBuffer:h,maxTextures:f,maxVertexTextures:p,maxTextureSize:g,maxCubemapSize:_,maxAttributes:m,maxVertexUniforms:v,maxVaryings:y,maxFragmentUniforms:b,vertexTextures:T,maxSamples:x}}function f2(n){const e=this;let t=null,i=0,s=!1,a=!1;const r=new Ps,o=new at,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(d,h){const f=d.length!==0||h||i!==0||s;return s=h,i=d.length,f},this.beginShadows=function(){a=!0,u(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(d,h){t=u(d,h,0)},this.setState=function(d,h,f){const p=d.clippingPlanes,g=d.clipIntersection,_=d.clipShadows,m=n.get(d);if(!s||p===null||p.length===0||a&&!_)a?u(null):c();else{const v=a?0:i,y=v*4;let b=m.clippingState||null;l.value=b,b=u(p,h,y,f);for(let T=0;T!==y;++T)b[T]=t[T];m.clippingState=b,this.numIntersection=g?this.numPlanes:0,this.numPlanes+=v}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function u(d,h,f,p){const g=d!==null?d.length:0;let _=null;if(g!==0){if(_=l.value,p!==!0||_===null){const m=f+g*4,v=h.matrixWorldInverse;o.getNormalMatrix(v),(_===null||_.length0){const c=new TS(l.height);return c.fromEquirectangularTexture(n,r),e.set(r,c),r.addEventListener("dispose",s),t(c.texture,r.mapping)}else return null}}return r}function s(r){const o=r.target;o.removeEventListener("dispose",s);const l=e.get(o);l!==void 0&&(e.delete(o),l.dispose())}function a(){e=new WeakMap}return{get:i,dispose:a}}const Jr=4,M0=[.125,.215,.35,.446,.526,.582],Va=20,sp=new pc,E0=new ue;let ap=null,rp=0,op=0,lp=!1;const za=(1+Math.sqrt(5))/2,Br=1/za,C0=[new S(-za,Br,0),new S(za,Br,0),new S(-Br,0,za),new S(Br,0,za),new S(0,za,-Br),new S(0,za,Br),new S(-1,1,-1),new S(1,1,-1),new S(-1,1,1),new S(1,1,1)],m2=new S;class sh{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,i=.1,s=100,a={}){const{size:r=256,position:o=m2}=a;ap=this._renderer.getRenderTarget(),rp=this._renderer.getActiveCubeFace(),op=this._renderer.getActiveMipmapLevel(),lp=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(r);const l=this._allocateTargets();return l.depthBuffer=!0,this._sceneToCubeUV(e,i,s,l,o),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=P0(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=R0(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?T:0,T,T),d.setRenderTarget(s),m&&d.render(_,l),d.render(e,l)}_.geometry.dispose(),_.material.dispose(),d.toneMapping=f,d.autoClear=h,e.background=v}_textureToCubeUV(e,t){const i=this._renderer,s=e.mapping===Bs||e.mapping===la;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=P0()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=R0());const a=s?this._cubemapMaterial:this._equirectMaterial,r=new we(this._lodPlanes[0],a),o=a.uniforms;o.envMap.value=e;const l=this._cubeSize;uu(t,0,0,3*l,2*l),i.setRenderTarget(t),i.render(r,sp)}_applyPMREM(e){const t=this._renderer,i=t.autoClear;t.autoClear=!1;const s=this._lodPlanes.length;for(let a=1;aVa&&console.warn(`sigmaRadians, ${a}, is too large and will clip, as it requested ${_} samples when the maximum is set to ${Va}`);const m=[];let v=0;for(let M=0;My-Jr?s-y+Jr:0),x=4*(this._cubeSize-b);uu(t,T,x,3*b,2*b),l.setRenderTarget(t),l.render(d,sp)}}function _2(n){const e=[],t=[],i=[];let s=n;const a=n-Jr+1+M0.length;for(let r=0;rn-Jr?l=M0[r-n+Jr-1]:r===0&&(l=0),i.push(l);const c=1/(o-2),u=-c,d=1+c,h=[u,u,d,u,d,d,u,u,d,d,u,d],f=6,p=6,g=3,_=2,m=1,v=new Float32Array(g*p*f),y=new Float32Array(_*p*f),b=new Float32Array(m*p*f);for(let x=0;x2?0:-1,w=[M,C,0,M+2/3,C,0,M+2/3,C+1,0,M,C,0,M+2/3,C+1,0,M,C+1,0];v.set(w,g*p*x),y.set(h,_*p*x);const E=[x,x,x,x,x,x];b.set(E,m*p*x)}const T=new Ge;T.setAttribute("position",new ot(v,g)),T.setAttribute("uv",new ot(y,_)),T.setAttribute("faceIndex",new ot(b,m)),e.push(T),s>Jr&&s--}return{lodPlanes:e,sizeLods:t,sigmas:i}}function A0(n,e,t){const i=new ms(n,e,t);return i.texture.mapping=Io,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function uu(n,e,t,i,s){n.viewport.set(e,t,i,s),n.scissor.set(e,t,i,s)}function g2(n,e,t){const i=new Float32Array(Va),s=new S(0,1,0);return new ti({name:"SphericalGaussianBlur",defines:{n:Va,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:s}},vertexShader:Lg(),fragmentShader:` precision mediump float; precision mediump int; @@ -3636,7 +3636,7 @@ void main() { } } - `,blending:ks,depthTest:!1,depthWrite:!1})}function w0(){return new ti({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Mg(),fragmentShader:` + `,blending:Ds,depthTest:!1,depthWrite:!1})}function R0(){return new ti({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Lg(),fragmentShader:` precision mediump float; precision mediump int; @@ -3655,7 +3655,7 @@ void main() { gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); } - `,blending:ks,depthTest:!1,depthWrite:!1})}function S0(){return new ti({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Mg(),fragmentShader:` + `,blending:Ds,depthTest:!1,depthWrite:!1})}function P0(){return new ti({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Lg(),fragmentShader:` precision mediump float; precision mediump int; @@ -3671,7 +3671,7 @@ void main() { gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); } - `,blending:ks,depthTest:!1,depthWrite:!1})}function Mg(){return` + `,blending:Ds,depthTest:!1,depthWrite:!1})}function Lg(){return` precision mediump float; precision mediump int; @@ -3726,17 +3726,17 @@ void main() { gl_Position = vec4( position, 1.0 ); } - `}function o2(n){let e=new WeakMap,t=null;function i(o){if(o&&o.isTexture){const l=o.mapping,c=l===ar||l===Nl,u=l===Bs||l===oa;if(c||u){let d=e.get(o);const h=d!==void 0?d.texture.pmremVersion:0;if(o.isRenderTargetTexture&&o.pmremVersion!==h)return t===null&&(t=new Jd(n)),d=c?t.fromEquirectangular(o,d):t.fromCubemap(o,d),d.texture.pmremVersion=o.pmremVersion,e.set(o,d),d.texture;if(d!==void 0)return d.texture;{const f=o.image;return c&&f&&f.height>0||u&&f&&s(f)?(t===null&&(t=new Jd(n)),d=c?t.fromEquirectangular(o):t.fromCubemap(o),d.texture.pmremVersion=o.pmremVersion,e.set(o,d),o.addEventListener("dispose",a),d.texture):null}}}return o}function s(o){let l=0;const c=6;for(let u=0;ue.maxTextureSize&&(T=Math.ceil(b/e.maxTextureSize),b=e.maxTextureSize);const x=new Float32Array(b*T*4*d),M=new Th(x,b,T,d);M.type=Sn,M.needsUpdate=!0;const C=y*4;for(let E=0;E0)return n;const s=e*t;let a=M0[s];if(a===void 0&&(a=new Float32Array(s),M0[s]=a),e!==0){i.toArray(a,0);for(let r=1,o=0;r!==e;++r)o+=t,n[r].toArray(a,o)}return a}function hn(n,e){if(n.length!==e.length)return!1;for(let t=0,i=n.length;t0||u&&f&&s(f)?(t===null&&(t=new sh(n)),d=c?t.fromEquirectangular(o):t.fromCubemap(o),d.texture.pmremVersion=o.pmremVersion,e.set(o,d),o.addEventListener("dispose",a),d.texture):null}}}return o}function s(o){let l=0;const c=6;for(let u=0;ue.maxTextureSize&&(T=Math.ceil(b/e.maxTextureSize),b=e.maxTextureSize);const x=new Float32Array(b*T*4*d),M=new Ph(x,b,T,d);M.type=Sn,M.needsUpdate=!0;const C=y*4;for(let E=0;E0)return n;const s=e*t;let a=L0[s];if(a===void 0&&(a=new Float32Array(s),L0[s]=a),e!==0){i.toArray(a,0);for(let r=1,o=0;r!==e;++r)o+=t,n[r].toArray(a,o)}return a}function hn(n,e){if(n.length!==e.length)return!1;for(let t=0,i=n.length;t":" "} ${o}: ${t[r]}`)}return i.join(` -`)}const L0=new st;function oD(n){at._getMatrix(L0,at.workingColorSpace,n);const e=`mat3( ${L0.elements.map(t=>t.toFixed(4))} )`;switch(at.getTransfer(n)){case Bl:return[e,"LinearTransferOETF"];case Pt:return[e,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",n),[e,"LinearTransferOETF"]}}function D0(n,e,t){const i=n.getShaderParameter(e,n.COMPILE_STATUS),a=(n.getShaderInfoLog(e)||"").trim();if(i&&a==="")return"";const r=/ERROR: 0:(\d+)/.exec(a);if(r){const o=parseInt(r[1]);return t.toUpperCase()+` +`)}const B0=new at;function yk(n){rt._getMatrix(B0,rt.workingColorSpace,n);const e=`mat3( ${B0.elements.map(t=>t.toFixed(4))} )`;switch(rt.getTransfer(n)){case Gl:return[e,"LinearTransferOETF"];case Pt:return[e,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",n),[e,"LinearTransferOETF"]}}function z0(n,e,t){const i=n.getShaderParameter(e,n.COMPILE_STATUS),a=(n.getShaderInfoLog(e)||"").trim();if(i&&a==="")return"";const r=/ERROR: 0:(\d+)/.exec(a);if(r){const o=parseInt(r[1]);return t.toUpperCase()+` `+a+` -`+rD(n.getShaderSource(e),o)}else return a}function lD(n,e){const t=oD(e);return[`vec4 ${n}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(` -`)}function cD(n,e){let t;switch(e){case Gw:t="Linear";break;case $w:t="Reinhard";break;case Ww:t="Cineon";break;case z_:t="ACESFilmic";break;case Kw:t="AgX";break;case qw:t="Neutral";break;case Xw:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+n+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const ou=new S;function uD(){at.getLuminanceCoefficients(ou);const n=ou.x.toFixed(4),e=ou.y.toFixed(4),t=ou.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${n}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(` -`)}function dD(n){return[n.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",n.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(fl).join(` -`)}function hD(n){const e=[];for(const t in n){const i=n[t];i!==!1&&e.push("#define "+t+" "+i)}return e.join(` -`)}function fD(n,e){const t={},i=n.getProgramParameter(e,n.ACTIVE_ATTRIBUTES);for(let s=0;s/gm;function Pm(n){return n.replace(pD,_D)}const mD=new Map;function _D(n,e){let t=mt[e];if(t===void 0){const i=mD.get(e);if(i!==void 0)t=mt[i],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,i);else throw new Error("Can not resolve #include <"+e+">")}return Pm(t)}const gD=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function F0(n){return n.replace(gD,yD)}function yD(n,e,t,i){let s="";for(let a=parseInt(e);a/gm;function Nm(n){return n.replace(Mk,Ck)}const Ek=new Map;function Ck(n,e){let t=mt[e];if(t===void 0){const i=Ek.get(e);if(i!==void 0)t=mt[i],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,i);else throw new Error("Can not resolve #include <"+e+">")}return Nm(t)}const Ak=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function G0(n){return n.replace(Ak,Rk)}function Rk(n,e,t,i){let s="";for(let a=parseInt(e);a0&&(_+=` -`),m=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p].filter(fl).join(` +`),m=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p].filter(_l).join(` `),m.length>0&&(m+=` -`)):(_=[N0(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+u:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` -`].filter(fl).join(` -`),m=[N0(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+u:"",t.envMap?"#define "+d:"",h?"#define CUBEUV_TEXEL_WIDTH "+h.texelWidth:"",h?"#define CUBEUV_TEXEL_HEIGHT "+h.texelHeight:"",h?"#define CUBEUV_MAX_MIP "+h.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==Os?"#define TONE_MAPPING":"",t.toneMapping!==Os?mt.tonemapping_pars_fragment:"",t.toneMapping!==Os?cD("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",mt.colorspace_pars_fragment,lD("linearToOutputTexel",t.outputColorSpace),uD(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` -`].filter(fl).join(` -`)),r=Pm(r),r=k0(r,t),r=O0(r,t),o=Pm(o),o=k0(o,t),o=O0(o,t),r=F0(r),o=F0(o),t.isRawShaderMaterial!==!0&&(v=`#version 300 es +`)):(_=[$0(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+u:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` +`].filter(_l).join(` +`),m=[$0(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+u:"",t.envMap?"#define "+d:"",h?"#define CUBEUV_TEXEL_WIDTH "+h.texelWidth:"",h?"#define CUBEUV_TEXEL_HEIGHT "+h.texelHeight:"",h?"#define CUBEUV_MAX_MIP "+h.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==Os?"#define TONE_MAPPING":"",t.toneMapping!==Os?mt.tonemapping_pars_fragment:"",t.toneMapping!==Os?bk("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",mt.colorspace_pars_fragment,vk("linearToOutputTexel",t.outputColorSpace),xk(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` +`].filter(_l).join(` +`)),r=Nm(r),r=H0(r,t),r=V0(r,t),o=Nm(o),o=H0(o,t),o=V0(o,t),r=G0(r),o=G0(o),t.isRawShaderMaterial!==!0&&(v=`#version 300 es `,_=[f,"#define attribute in","#define varying out","#define texture2D texture"].join(` `)+` -`+_,m=["#define varying in",t.glslVersion===wm?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===wm?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` +`+_,m=["#define varying in",t.glslVersion===Rm?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===Rm?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` `)+` -`+m);const y=v+_+r,b=v+m+o,T=I0(s,s.VERTEX_SHADER,y),x=I0(s,s.FRAGMENT_SHADER,b);s.attachShader(g,T),s.attachShader(g,x),t.index0AttributeName!==void 0?s.bindAttribLocation(g,0,t.index0AttributeName):t.morphTargets===!0&&s.bindAttribLocation(g,0,"position"),s.linkProgram(g);function M(R){if(n.debug.checkShaderErrors){const D=s.getProgramInfoLog(g)||"",O=s.getShaderInfoLog(T)||"",k=s.getShaderInfoLog(x)||"",U=D.trim(),F=O.trim(),W=k.trim();let H=!0,ne=!0;if(s.getProgramParameter(g,s.LINK_STATUS)===!1)if(H=!1,typeof n.debug.onShaderError=="function")n.debug.onShaderError(s,g,T,x);else{const oe=D0(s,T,"vertex"),pe=D0(s,x,"fragment");console.error("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(g,s.VALIDATE_STATUS)+` +`+m);const y=v+_+r,b=v+m+o,T=U0(s,s.VERTEX_SHADER,y),x=U0(s,s.FRAGMENT_SHADER,b);s.attachShader(g,T),s.attachShader(g,x),t.index0AttributeName!==void 0?s.bindAttribLocation(g,0,t.index0AttributeName):t.morphTargets===!0&&s.bindAttribLocation(g,0,"position"),s.linkProgram(g);function M(R){if(n.debug.checkShaderErrors){const k=s.getProgramInfoLog(g)||"",O=s.getShaderInfoLog(T)||"",D=s.getShaderInfoLog(x)||"",U=k.trim(),F=O.trim(),W=D.trim();let H=!0,ne=!0;if(s.getProgramParameter(g,s.LINK_STATUS)===!1)if(H=!1,typeof n.debug.onShaderError=="function")n.debug.onShaderError(s,g,T,x);else{const oe=z0(s,T,"vertex"),pe=z0(s,x,"fragment");console.error("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(g,s.VALIDATE_STATUS)+` Material Name: `+R.name+` Material Type: `+R.type+` Program Info Log: `+U+` `+oe+` -`+pe)}else U!==""?console.warn("THREE.WebGLProgram: Program Info Log:",U):(F===""||W==="")&&(ne=!1);ne&&(R.diagnostics={runnable:H,programLog:U,vertexShader:{log:F,prefix:_},fragmentShader:{log:W,prefix:m}})}s.deleteShader(T),s.deleteShader(x),C=new $u(s,g),w=fD(s,g)}let C;this.getUniforms=function(){return C===void 0&&M(this),C};let w;this.getAttributes=function(){return w===void 0&&M(this),w};let E=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=s.getProgramParameter(g,sD)),E},this.destroy=function(){i.releaseStatesOfProgram(this),s.deleteProgram(g),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=aD++,this.cacheKey=e,this.usedTimes=1,this.program=g,this.vertexShader=T,this.fragmentShader=x,this}let MD=0;class ED{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,i=e.fragmentShader,s=this._getShaderStage(t),a=this._getShaderStage(i),r=this._getShaderCacheForMaterial(e);return r.has(s)===!1&&(r.add(s),s.usedTimes++),r.has(a)===!1&&(r.add(a),a.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return i===void 0&&(i=new CD(e),t.set(e,i)),i}}class CD{constructor(e){this.id=MD++,this.code=e,this.usedTimes=0}}function AD(n,e,t,i,s,a,r){const o=new Eh,l=new ED,c=new Set,u=[],d=s.logarithmicDepthBuffer,h=s.vertexTextures;let f=s.precision;const p={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function g(w){return c.add(w),w===0?"uv":`uv${w}`}function _(w,E,R,D,O){const k=D.fog,U=O.geometry,F=w.isMeshStandardMaterial?D.environment:null,W=(w.isMeshStandardMaterial?t:e).get(w.envMap||F),H=W&&W.mapping===Ao?W.image.height:null,ne=p[w.type];w.precision!==null&&(f=s.getMaxPrecision(w.precision),f!==w.precision&&console.warn("THREE.WebGLProgram.getParameters:",w.precision,"not supported, using",f,"instead."));const oe=U.morphAttributes.position||U.morphAttributes.normal||U.morphAttributes.color,pe=oe!==void 0?oe.length:0;let Ie=0;U.morphAttributes.position!==void 0&&(Ie=1),U.morphAttributes.normal!==void 0&&(Ie=2),U.morphAttributes.color!==void 0&&(Ie=3);let De,Xe,ke,Z;if(ne){const Et=Wi[ne];De=Et.vertexShader,Xe=Et.fragmentShader}else De=w.vertexShader,Xe=w.fragmentShader,l.update(w),ke=l.getVertexShaderID(w),Z=l.getFragmentShaderID(w);const se=n.getRenderTarget(),Se=n.state.buffers.depth.getReversed(),X=O.isInstancedMesh===!0,ie=O.isBatchedMesh===!0,xe=!!w.map,Ae=!!w.matcap,L=!!W,G=!!w.aoMap,j=!!w.lightMap,Y=!!w.bumpMap,Q=!!w.normalMap,_e=!!w.displacementMap,ce=!!w.emissiveMap,ge=!!w.metalnessMap,$e=!!w.roughnessMap,it=w.anisotropy>0,I=w.clearcoat>0,A=w.dispersion>0,V=w.iridescence>0,J=w.sheen>0,le=w.transmission>0,ee=it&&!!w.anisotropyMap,He=I&&!!w.clearcoatMap,ye=I&&!!w.clearcoatNormalMap,Ue=I&&!!w.clearcoatRoughnessMap,Be=V&&!!w.iridescenceMap,de=V&&!!w.iridescenceThicknessMap,Pe=J&&!!w.sheenColorMap,Je=J&&!!w.sheenRoughnessMap,Ve=!!w.specularMap,Ce=!!w.specularColorMap,ht=!!w.specularIntensityMap,N=le&&!!w.transmissionMap,me=le&&!!w.thicknessMap,be=!!w.gradientMap,Fe=!!w.alphaMap,he=w.alphaTest>0,re=!!w.alphaHash,ze=!!w.extensions;let lt=Os;w.toneMapped&&(se===null||se.isXRRenderTarget===!0)&&(lt=n.toneMapping);const kt={shaderID:ne,shaderType:w.type,shaderName:w.name,vertexShader:De,fragmentShader:Xe,defines:w.defines,customVertexShaderID:ke,customFragmentShaderID:Z,isRawShaderMaterial:w.isRawShaderMaterial===!0,glslVersion:w.glslVersion,precision:f,batching:ie,batchingColor:ie&&O._colorsTexture!==null,instancing:X,instancingColor:X&&O.instanceColor!==null,instancingMorph:X&&O.morphTexture!==null,supportsVertexTextures:h,outputColorSpace:se===null?n.outputColorSpace:se.isXRRenderTarget===!0?se.texture.colorSpace:xn,alphaToCoverage:!!w.alphaToCoverage,map:xe,matcap:Ae,envMap:L,envMapMode:L&&W.mapping,envMapCubeUVHeight:H,aoMap:G,lightMap:j,bumpMap:Y,normalMap:Q,displacementMap:h&&_e,emissiveMap:ce,normalMapObjectSpace:Q&&w.normalMapType===tS,normalMapTangentSpace:Q&&w.normalMapType===ha,metalnessMap:ge,roughnessMap:$e,anisotropy:it,anisotropyMap:ee,clearcoat:I,clearcoatMap:He,clearcoatNormalMap:ye,clearcoatRoughnessMap:Ue,dispersion:A,iridescence:V,iridescenceMap:Be,iridescenceThicknessMap:de,sheen:J,sheenColorMap:Pe,sheenRoughnessMap:Je,specularMap:Ve,specularColorMap:Ce,specularIntensityMap:ht,transmission:le,transmissionMap:N,thicknessMap:me,gradientMap:be,opaque:w.transparent===!1&&w.blending===tr&&w.alphaToCoverage===!1,alphaMap:Fe,alphaTest:he,alphaHash:re,combine:w.combine,mapUv:xe&&g(w.map.channel),aoMapUv:G&&g(w.aoMap.channel),lightMapUv:j&&g(w.lightMap.channel),bumpMapUv:Y&&g(w.bumpMap.channel),normalMapUv:Q&&g(w.normalMap.channel),displacementMapUv:_e&&g(w.displacementMap.channel),emissiveMapUv:ce&&g(w.emissiveMap.channel),metalnessMapUv:ge&&g(w.metalnessMap.channel),roughnessMapUv:$e&&g(w.roughnessMap.channel),anisotropyMapUv:ee&&g(w.anisotropyMap.channel),clearcoatMapUv:He&&g(w.clearcoatMap.channel),clearcoatNormalMapUv:ye&&g(w.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ue&&g(w.clearcoatRoughnessMap.channel),iridescenceMapUv:Be&&g(w.iridescenceMap.channel),iridescenceThicknessMapUv:de&&g(w.iridescenceThicknessMap.channel),sheenColorMapUv:Pe&&g(w.sheenColorMap.channel),sheenRoughnessMapUv:Je&&g(w.sheenRoughnessMap.channel),specularMapUv:Ve&&g(w.specularMap.channel),specularColorMapUv:Ce&&g(w.specularColorMap.channel),specularIntensityMapUv:ht&&g(w.specularIntensityMap.channel),transmissionMapUv:N&&g(w.transmissionMap.channel),thicknessMapUv:me&&g(w.thicknessMap.channel),alphaMapUv:Fe&&g(w.alphaMap.channel),vertexTangents:!!U.attributes.tangent&&(Q||it),vertexColors:w.vertexColors,vertexAlphas:w.vertexColors===!0&&!!U.attributes.color&&U.attributes.color.itemSize===4,pointsUvs:O.isPoints===!0&&!!U.attributes.uv&&(xe||Fe),fog:!!k,useFog:w.fog===!0,fogExp2:!!k&&k.isFogExp2,flatShading:w.flatShading===!0&&w.wireframe===!1,sizeAttenuation:w.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:Se,skinning:O.isSkinnedMesh===!0,morphTargets:U.morphAttributes.position!==void 0,morphNormals:U.morphAttributes.normal!==void 0,morphColors:U.morphAttributes.color!==void 0,morphTargetsCount:pe,morphTextureStride:Ie,numDirLights:E.directional.length,numPointLights:E.point.length,numSpotLights:E.spot.length,numSpotLightMaps:E.spotLightMap.length,numRectAreaLights:E.rectArea.length,numHemiLights:E.hemi.length,numDirLightShadows:E.directionalShadowMap.length,numPointLightShadows:E.pointShadowMap.length,numSpotLightShadows:E.spotShadowMap.length,numSpotLightShadowsWithMaps:E.numSpotLightShadowsWithMaps,numLightProbes:E.numLightProbes,numClippingPlanes:r.numPlanes,numClipIntersection:r.numIntersection,dithering:w.dithering,shadowMapEnabled:n.shadowMap.enabled&&R.length>0,shadowMapType:n.shadowMap.type,toneMapping:lt,decodeVideoTexture:xe&&w.map.isVideoTexture===!0&&at.getTransfer(w.map.colorSpace)===Pt,decodeVideoTextureEmissive:ce&&w.emissiveMap.isVideoTexture===!0&&at.getTransfer(w.emissiveMap.colorSpace)===Pt,premultipliedAlpha:w.premultipliedAlpha,doubleSided:w.side===ct,flipSided:w.side===un,useDepthPacking:w.depthPacking>=0,depthPacking:w.depthPacking||0,index0AttributeName:w.index0AttributeName,extensionClipCullDistance:ze&&w.extensions.clipCullDistance===!0&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ze&&w.extensions.multiDraw===!0||ie)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:w.customProgramCacheKey()};return kt.vertexUv1s=c.has(1),kt.vertexUv2s=c.has(2),kt.vertexUv3s=c.has(3),c.clear(),kt}function m(w){const E=[];if(w.shaderID?E.push(w.shaderID):(E.push(w.customVertexShaderID),E.push(w.customFragmentShaderID)),w.defines!==void 0)for(const R in w.defines)E.push(R),E.push(w.defines[R]);return w.isRawShaderMaterial===!1&&(v(E,w),y(E,w),E.push(n.outputColorSpace)),E.push(w.customProgramCacheKey),E.join()}function v(w,E){w.push(E.precision),w.push(E.outputColorSpace),w.push(E.envMapMode),w.push(E.envMapCubeUVHeight),w.push(E.mapUv),w.push(E.alphaMapUv),w.push(E.lightMapUv),w.push(E.aoMapUv),w.push(E.bumpMapUv),w.push(E.normalMapUv),w.push(E.displacementMapUv),w.push(E.emissiveMapUv),w.push(E.metalnessMapUv),w.push(E.roughnessMapUv),w.push(E.anisotropyMapUv),w.push(E.clearcoatMapUv),w.push(E.clearcoatNormalMapUv),w.push(E.clearcoatRoughnessMapUv),w.push(E.iridescenceMapUv),w.push(E.iridescenceThicknessMapUv),w.push(E.sheenColorMapUv),w.push(E.sheenRoughnessMapUv),w.push(E.specularMapUv),w.push(E.specularColorMapUv),w.push(E.specularIntensityMapUv),w.push(E.transmissionMapUv),w.push(E.thicknessMapUv),w.push(E.combine),w.push(E.fogExp2),w.push(E.sizeAttenuation),w.push(E.morphTargetsCount),w.push(E.morphAttributeCount),w.push(E.numDirLights),w.push(E.numPointLights),w.push(E.numSpotLights),w.push(E.numSpotLightMaps),w.push(E.numHemiLights),w.push(E.numRectAreaLights),w.push(E.numDirLightShadows),w.push(E.numPointLightShadows),w.push(E.numSpotLightShadows),w.push(E.numSpotLightShadowsWithMaps),w.push(E.numLightProbes),w.push(E.shadowMapType),w.push(E.toneMapping),w.push(E.numClippingPlanes),w.push(E.numClipIntersection),w.push(E.depthPacking)}function y(w,E){o.disableAll(),E.supportsVertexTextures&&o.enable(0),E.instancing&&o.enable(1),E.instancingColor&&o.enable(2),E.instancingMorph&&o.enable(3),E.matcap&&o.enable(4),E.envMap&&o.enable(5),E.normalMapObjectSpace&&o.enable(6),E.normalMapTangentSpace&&o.enable(7),E.clearcoat&&o.enable(8),E.iridescence&&o.enable(9),E.alphaTest&&o.enable(10),E.vertexColors&&o.enable(11),E.vertexAlphas&&o.enable(12),E.vertexUv1s&&o.enable(13),E.vertexUv2s&&o.enable(14),E.vertexUv3s&&o.enable(15),E.vertexTangents&&o.enable(16),E.anisotropy&&o.enable(17),E.alphaHash&&o.enable(18),E.batching&&o.enable(19),E.dispersion&&o.enable(20),E.batchingColor&&o.enable(21),E.gradientMap&&o.enable(22),w.push(o.mask),o.disableAll(),E.fog&&o.enable(0),E.useFog&&o.enable(1),E.flatShading&&o.enable(2),E.logarithmicDepthBuffer&&o.enable(3),E.reversedDepthBuffer&&o.enable(4),E.skinning&&o.enable(5),E.morphTargets&&o.enable(6),E.morphNormals&&o.enable(7),E.morphColors&&o.enable(8),E.premultipliedAlpha&&o.enable(9),E.shadowMapEnabled&&o.enable(10),E.doubleSided&&o.enable(11),E.flipSided&&o.enable(12),E.useDepthPacking&&o.enable(13),E.dithering&&o.enable(14),E.transmission&&o.enable(15),E.sheen&&o.enable(16),E.opaque&&o.enable(17),E.pointsUvs&&o.enable(18),E.decodeVideoTexture&&o.enable(19),E.decodeVideoTextureEmissive&&o.enable(20),E.alphaToCoverage&&o.enable(21),w.push(o.mask)}function b(w){const E=p[w.type];let R;if(E){const D=Wi[E];R=pS.clone(D.uniforms)}else R=w.uniforms;return R}function T(w,E){let R;for(let D=0,O=u.length;D0?i.push(m):f.transparent===!0?s.push(m):t.push(m)}function l(d,h,f,p,g,_){const m=r(d,h,f,p,g,_);f.transmission>0?i.unshift(m):f.transparent===!0?s.unshift(m):t.unshift(m)}function c(d,h){t.length>1&&t.sort(d||PD),i.length>1&&i.sort(h||U0),s.length>1&&s.sort(h||U0)}function u(){for(let d=e,h=n.length;d=a.length?(r=new B0,a.push(r)):r=a[s],r}function t(){n=new WeakMap}return{get:e,dispose:t}}function LD(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new S,color:new ue};break;case"SpotLight":t={position:new S,direction:new S,color:new ue,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new S,color:new ue,distance:0,decay:0};break;case"HemisphereLight":t={direction:new S,skyColor:new ue,groundColor:new ue};break;case"RectAreaLight":t={color:new ue,position:new S,halfWidth:new S,halfHeight:new S};break}return n[e.id]=t,t}}}function DD(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new te};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new te};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new te,shadowCameraNear:1,shadowCameraFar:1e3};break}return n[e.id]=t,t}}}let kD=0;function OD(n,e){return(e.castShadow?2:0)-(n.castShadow?2:0)+(e.map?1:0)-(n.map?1:0)}function FD(n){const e=new LD,t=DD(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)i.probe.push(new S);const s=new S,a=new Me,r=new Me;function o(c){let u=0,d=0,h=0;for(let w=0;w<9;w++)i.probe[w].set(0,0,0);let f=0,p=0,g=0,_=0,m=0,v=0,y=0,b=0,T=0,x=0,M=0;c.sort(OD);for(let w=0,E=c.length;w0&&(n.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Te.LTC_FLOAT_1,i.rectAreaLTC2=Te.LTC_FLOAT_2):(i.rectAreaLTC1=Te.LTC_HALF_1,i.rectAreaLTC2=Te.LTC_HALF_2)),i.ambient[0]=u,i.ambient[1]=d,i.ambient[2]=h;const C=i.hash;(C.directionalLength!==f||C.pointLength!==p||C.spotLength!==g||C.rectAreaLength!==_||C.hemiLength!==m||C.numDirectionalShadows!==v||C.numPointShadows!==y||C.numSpotShadows!==b||C.numSpotMaps!==T||C.numLightProbes!==M)&&(i.directional.length=f,i.spot.length=g,i.rectArea.length=_,i.point.length=p,i.hemi.length=m,i.directionalShadow.length=v,i.directionalShadowMap.length=v,i.pointShadow.length=y,i.pointShadowMap.length=y,i.spotShadow.length=b,i.spotShadowMap.length=b,i.directionalShadowMatrix.length=v,i.pointShadowMatrix.length=y,i.spotLightMatrix.length=b+T-x,i.spotLightMap.length=T,i.numSpotLightShadowsWithMaps=x,i.numLightProbes=M,C.directionalLength=f,C.pointLength=p,C.spotLength=g,C.rectAreaLength=_,C.hemiLength=m,C.numDirectionalShadows=v,C.numPointShadows=y,C.numSpotShadows=b,C.numSpotMaps=T,C.numLightProbes=M,i.version=kD++)}function l(c,u){let d=0,h=0,f=0,p=0,g=0;const _=u.matrixWorldInverse;for(let m=0,v=c.length;m=r.length?(o=new z0(n),r.push(o)):o=r[a],o}function i(){e=new WeakMap}return{get:t,dispose:i}}const UD=`void main() { +`+pe)}else U!==""?console.warn("THREE.WebGLProgram: Program Info Log:",U):(F===""||W==="")&&(ne=!1);ne&&(R.diagnostics={runnable:H,programLog:U,vertexShader:{log:F,prefix:_},fragmentShader:{log:W,prefix:m}})}s.deleteShader(T),s.deleteShader(x),C=new qu(s,g),w=Tk(s,g)}let C;this.getUniforms=function(){return C===void 0&&M(this),C};let w;this.getAttributes=function(){return w===void 0&&M(this),w};let E=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=s.getProgramParameter(g,mk)),E},this.destroy=function(){i.releaseStatesOfProgram(this),s.deleteProgram(g),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=_k++,this.cacheKey=e,this.usedTimes=1,this.program=g,this.vertexShader=T,this.fragmentShader=x,this}let Fk=0;class Nk{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,i=e.fragmentShader,s=this._getShaderStage(t),a=this._getShaderStage(i),r=this._getShaderCacheForMaterial(e);return r.has(s)===!1&&(r.add(s),s.usedTimes++),r.has(a)===!1&&(r.add(a),a.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return i===void 0&&(i=new Uk(e),t.set(e,i)),i}}class Uk{constructor(e){this.id=Fk++,this.code=e,this.usedTimes=0}}function Bk(n,e,t,i,s,a,r){const o=new Lh,l=new Nk,c=new Set,u=[],d=s.logarithmicDepthBuffer,h=s.vertexTextures;let f=s.precision;const p={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function g(w){return c.add(w),w===0?"uv":`uv${w}`}function _(w,E,R,k,O){const D=k.fog,U=O.geometry,F=w.isMeshStandardMaterial?k.environment:null,W=(w.isMeshStandardMaterial?t:e).get(w.envMap||F),H=W&&W.mapping===Io?W.image.height:null,ne=p[w.type];w.precision!==null&&(f=s.getMaxPrecision(w.precision),f!==w.precision&&console.warn("THREE.WebGLProgram.getParameters:",w.precision,"not supported, using",f,"instead."));const oe=U.morphAttributes.position||U.morphAttributes.normal||U.morphAttributes.color,pe=oe!==void 0?oe.length:0;let Ie=0;U.morphAttributes.position!==void 0&&(Ie=1),U.morphAttributes.normal!==void 0&&(Ie=2),U.morphAttributes.color!==void 0&&(Ie=3);let ke,Xe,De,Z;if(ne){const Et=Xi[ne];ke=Et.vertexShader,Xe=Et.fragmentShader}else ke=w.vertexShader,Xe=w.fragmentShader,l.update(w),De=l.getVertexShaderID(w),Z=l.getFragmentShaderID(w);const ae=n.getRenderTarget(),Se=n.state.buffers.depth.getReversed(),X=O.isInstancedMesh===!0,ie=O.isBatchedMesh===!0,xe=!!w.map,Ae=!!w.matcap,L=!!W,G=!!w.aoMap,j=!!w.lightMap,Y=!!w.bumpMap,Q=!!w.normalMap,_e=!!w.displacementMap,ce=!!w.emissiveMap,ge=!!w.metalnessMap,$e=!!w.roughnessMap,it=w.anisotropy>0,I=w.clearcoat>0,A=w.dispersion>0,V=w.iridescence>0,J=w.sheen>0,le=w.transmission>0,ee=it&&!!w.anisotropyMap,He=I&&!!w.clearcoatMap,ye=I&&!!w.clearcoatNormalMap,Ue=I&&!!w.clearcoatRoughnessMap,Be=V&&!!w.iridescenceMap,de=V&&!!w.iridescenceThicknessMap,Pe=J&&!!w.sheenColorMap,Je=J&&!!w.sheenRoughnessMap,Ve=!!w.specularMap,Ce=!!w.specularColorMap,ht=!!w.specularIntensityMap,N=le&&!!w.transmissionMap,me=le&&!!w.thicknessMap,be=!!w.gradientMap,Fe=!!w.alphaMap,he=w.alphaTest>0,re=!!w.alphaHash,ze=!!w.extensions;let lt=Os;w.toneMapped&&(ae===null||ae.isXRRenderTarget===!0)&&(lt=n.toneMapping);const Dt={shaderID:ne,shaderType:w.type,shaderName:w.name,vertexShader:ke,fragmentShader:Xe,defines:w.defines,customVertexShaderID:De,customFragmentShaderID:Z,isRawShaderMaterial:w.isRawShaderMaterial===!0,glslVersion:w.glslVersion,precision:f,batching:ie,batchingColor:ie&&O._colorsTexture!==null,instancing:X,instancingColor:X&&O.instanceColor!==null,instancingMorph:X&&O.morphTexture!==null,supportsVertexTextures:h,outputColorSpace:ae===null?n.outputColorSpace:ae.isXRRenderTarget===!0?ae.texture.colorSpace:xn,alphaToCoverage:!!w.alphaToCoverage,map:xe,matcap:Ae,envMap:L,envMapMode:L&&W.mapping,envMapCubeUVHeight:H,aoMap:G,lightMap:j,bumpMap:Y,normalMap:Q,displacementMap:h&&_e,emissiveMap:ce,normalMapObjectSpace:Q&&w.normalMapType===cS,normalMapTangentSpace:Q&&w.normalMapType===fa,metalnessMap:ge,roughnessMap:$e,anisotropy:it,anisotropyMap:ee,clearcoat:I,clearcoatMap:He,clearcoatNormalMap:ye,clearcoatRoughnessMap:Ue,dispersion:A,iridescence:V,iridescenceMap:Be,iridescenceThicknessMap:de,sheen:J,sheenColorMap:Pe,sheenRoughnessMap:Je,specularMap:Ve,specularColorMap:Ce,specularIntensityMap:ht,transmission:le,transmissionMap:N,thicknessMap:me,gradientMap:be,opaque:w.transparent===!1&&w.blending===nr&&w.alphaToCoverage===!1,alphaMap:Fe,alphaTest:he,alphaHash:re,combine:w.combine,mapUv:xe&&g(w.map.channel),aoMapUv:G&&g(w.aoMap.channel),lightMapUv:j&&g(w.lightMap.channel),bumpMapUv:Y&&g(w.bumpMap.channel),normalMapUv:Q&&g(w.normalMap.channel),displacementMapUv:_e&&g(w.displacementMap.channel),emissiveMapUv:ce&&g(w.emissiveMap.channel),metalnessMapUv:ge&&g(w.metalnessMap.channel),roughnessMapUv:$e&&g(w.roughnessMap.channel),anisotropyMapUv:ee&&g(w.anisotropyMap.channel),clearcoatMapUv:He&&g(w.clearcoatMap.channel),clearcoatNormalMapUv:ye&&g(w.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ue&&g(w.clearcoatRoughnessMap.channel),iridescenceMapUv:Be&&g(w.iridescenceMap.channel),iridescenceThicknessMapUv:de&&g(w.iridescenceThicknessMap.channel),sheenColorMapUv:Pe&&g(w.sheenColorMap.channel),sheenRoughnessMapUv:Je&&g(w.sheenRoughnessMap.channel),specularMapUv:Ve&&g(w.specularMap.channel),specularColorMapUv:Ce&&g(w.specularColorMap.channel),specularIntensityMapUv:ht&&g(w.specularIntensityMap.channel),transmissionMapUv:N&&g(w.transmissionMap.channel),thicknessMapUv:me&&g(w.thicknessMap.channel),alphaMapUv:Fe&&g(w.alphaMap.channel),vertexTangents:!!U.attributes.tangent&&(Q||it),vertexColors:w.vertexColors,vertexAlphas:w.vertexColors===!0&&!!U.attributes.color&&U.attributes.color.itemSize===4,pointsUvs:O.isPoints===!0&&!!U.attributes.uv&&(xe||Fe),fog:!!D,useFog:w.fog===!0,fogExp2:!!D&&D.isFogExp2,flatShading:w.flatShading===!0&&w.wireframe===!1,sizeAttenuation:w.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:Se,skinning:O.isSkinnedMesh===!0,morphTargets:U.morphAttributes.position!==void 0,morphNormals:U.morphAttributes.normal!==void 0,morphColors:U.morphAttributes.color!==void 0,morphTargetsCount:pe,morphTextureStride:Ie,numDirLights:E.directional.length,numPointLights:E.point.length,numSpotLights:E.spot.length,numSpotLightMaps:E.spotLightMap.length,numRectAreaLights:E.rectArea.length,numHemiLights:E.hemi.length,numDirLightShadows:E.directionalShadowMap.length,numPointLightShadows:E.pointShadowMap.length,numSpotLightShadows:E.spotShadowMap.length,numSpotLightShadowsWithMaps:E.numSpotLightShadowsWithMaps,numLightProbes:E.numLightProbes,numClippingPlanes:r.numPlanes,numClipIntersection:r.numIntersection,dithering:w.dithering,shadowMapEnabled:n.shadowMap.enabled&&R.length>0,shadowMapType:n.shadowMap.type,toneMapping:lt,decodeVideoTexture:xe&&w.map.isVideoTexture===!0&&rt.getTransfer(w.map.colorSpace)===Pt,decodeVideoTextureEmissive:ce&&w.emissiveMap.isVideoTexture===!0&&rt.getTransfer(w.emissiveMap.colorSpace)===Pt,premultipliedAlpha:w.premultipliedAlpha,doubleSided:w.side===ct,flipSided:w.side===un,useDepthPacking:w.depthPacking>=0,depthPacking:w.depthPacking||0,index0AttributeName:w.index0AttributeName,extensionClipCullDistance:ze&&w.extensions.clipCullDistance===!0&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ze&&w.extensions.multiDraw===!0||ie)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:w.customProgramCacheKey()};return Dt.vertexUv1s=c.has(1),Dt.vertexUv2s=c.has(2),Dt.vertexUv3s=c.has(3),c.clear(),Dt}function m(w){const E=[];if(w.shaderID?E.push(w.shaderID):(E.push(w.customVertexShaderID),E.push(w.customFragmentShaderID)),w.defines!==void 0)for(const R in w.defines)E.push(R),E.push(w.defines[R]);return w.isRawShaderMaterial===!1&&(v(E,w),y(E,w),E.push(n.outputColorSpace)),E.push(w.customProgramCacheKey),E.join()}function v(w,E){w.push(E.precision),w.push(E.outputColorSpace),w.push(E.envMapMode),w.push(E.envMapCubeUVHeight),w.push(E.mapUv),w.push(E.alphaMapUv),w.push(E.lightMapUv),w.push(E.aoMapUv),w.push(E.bumpMapUv),w.push(E.normalMapUv),w.push(E.displacementMapUv),w.push(E.emissiveMapUv),w.push(E.metalnessMapUv),w.push(E.roughnessMapUv),w.push(E.anisotropyMapUv),w.push(E.clearcoatMapUv),w.push(E.clearcoatNormalMapUv),w.push(E.clearcoatRoughnessMapUv),w.push(E.iridescenceMapUv),w.push(E.iridescenceThicknessMapUv),w.push(E.sheenColorMapUv),w.push(E.sheenRoughnessMapUv),w.push(E.specularMapUv),w.push(E.specularColorMapUv),w.push(E.specularIntensityMapUv),w.push(E.transmissionMapUv),w.push(E.thicknessMapUv),w.push(E.combine),w.push(E.fogExp2),w.push(E.sizeAttenuation),w.push(E.morphTargetsCount),w.push(E.morphAttributeCount),w.push(E.numDirLights),w.push(E.numPointLights),w.push(E.numSpotLights),w.push(E.numSpotLightMaps),w.push(E.numHemiLights),w.push(E.numRectAreaLights),w.push(E.numDirLightShadows),w.push(E.numPointLightShadows),w.push(E.numSpotLightShadows),w.push(E.numSpotLightShadowsWithMaps),w.push(E.numLightProbes),w.push(E.shadowMapType),w.push(E.toneMapping),w.push(E.numClippingPlanes),w.push(E.numClipIntersection),w.push(E.depthPacking)}function y(w,E){o.disableAll(),E.supportsVertexTextures&&o.enable(0),E.instancing&&o.enable(1),E.instancingColor&&o.enable(2),E.instancingMorph&&o.enable(3),E.matcap&&o.enable(4),E.envMap&&o.enable(5),E.normalMapObjectSpace&&o.enable(6),E.normalMapTangentSpace&&o.enable(7),E.clearcoat&&o.enable(8),E.iridescence&&o.enable(9),E.alphaTest&&o.enable(10),E.vertexColors&&o.enable(11),E.vertexAlphas&&o.enable(12),E.vertexUv1s&&o.enable(13),E.vertexUv2s&&o.enable(14),E.vertexUv3s&&o.enable(15),E.vertexTangents&&o.enable(16),E.anisotropy&&o.enable(17),E.alphaHash&&o.enable(18),E.batching&&o.enable(19),E.dispersion&&o.enable(20),E.batchingColor&&o.enable(21),E.gradientMap&&o.enable(22),w.push(o.mask),o.disableAll(),E.fog&&o.enable(0),E.useFog&&o.enable(1),E.flatShading&&o.enable(2),E.logarithmicDepthBuffer&&o.enable(3),E.reversedDepthBuffer&&o.enable(4),E.skinning&&o.enable(5),E.morphTargets&&o.enable(6),E.morphNormals&&o.enable(7),E.morphColors&&o.enable(8),E.premultipliedAlpha&&o.enable(9),E.shadowMapEnabled&&o.enable(10),E.doubleSided&&o.enable(11),E.flipSided&&o.enable(12),E.useDepthPacking&&o.enable(13),E.dithering&&o.enable(14),E.transmission&&o.enable(15),E.sheen&&o.enable(16),E.opaque&&o.enable(17),E.pointsUvs&&o.enable(18),E.decodeVideoTexture&&o.enable(19),E.decodeVideoTextureEmissive&&o.enable(20),E.alphaToCoverage&&o.enable(21),w.push(o.mask)}function b(w){const E=p[w.type];let R;if(E){const k=Xi[E];R=wS.clone(k.uniforms)}else R=w.uniforms;return R}function T(w,E){let R;for(let k=0,O=u.length;k0?i.push(m):f.transparent===!0?s.push(m):t.push(m)}function l(d,h,f,p,g,_){const m=r(d,h,f,p,g,_);f.transmission>0?i.unshift(m):f.transparent===!0?s.unshift(m):t.unshift(m)}function c(d,h){t.length>1&&t.sort(d||Hk),i.length>1&&i.sort(h||W0),s.length>1&&s.sort(h||W0)}function u(){for(let d=e,h=n.length;d=a.length?(r=new X0,a.push(r)):r=a[s],r}function t(){n=new WeakMap}return{get:e,dispose:t}}function Gk(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new S,color:new ue};break;case"SpotLight":t={position:new S,direction:new S,color:new ue,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new S,color:new ue,distance:0,decay:0};break;case"HemisphereLight":t={direction:new S,skyColor:new ue,groundColor:new ue};break;case"RectAreaLight":t={color:new ue,position:new S,halfWidth:new S,halfHeight:new S};break}return n[e.id]=t,t}}}function $k(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new te};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new te};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new te,shadowCameraNear:1,shadowCameraFar:1e3};break}return n[e.id]=t,t}}}let Wk=0;function Xk(n,e){return(e.castShadow?2:0)-(n.castShadow?2:0)+(e.map?1:0)-(n.map?1:0)}function Kk(n){const e=new Gk,t=$k(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)i.probe.push(new S);const s=new S,a=new Me,r=new Me;function o(c){let u=0,d=0,h=0;for(let w=0;w<9;w++)i.probe[w].set(0,0,0);let f=0,p=0,g=0,_=0,m=0,v=0,y=0,b=0,T=0,x=0,M=0;c.sort(Xk);for(let w=0,E=c.length;w0&&(n.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Te.LTC_FLOAT_1,i.rectAreaLTC2=Te.LTC_FLOAT_2):(i.rectAreaLTC1=Te.LTC_HALF_1,i.rectAreaLTC2=Te.LTC_HALF_2)),i.ambient[0]=u,i.ambient[1]=d,i.ambient[2]=h;const C=i.hash;(C.directionalLength!==f||C.pointLength!==p||C.spotLength!==g||C.rectAreaLength!==_||C.hemiLength!==m||C.numDirectionalShadows!==v||C.numPointShadows!==y||C.numSpotShadows!==b||C.numSpotMaps!==T||C.numLightProbes!==M)&&(i.directional.length=f,i.spot.length=g,i.rectArea.length=_,i.point.length=p,i.hemi.length=m,i.directionalShadow.length=v,i.directionalShadowMap.length=v,i.pointShadow.length=y,i.pointShadowMap.length=y,i.spotShadow.length=b,i.spotShadowMap.length=b,i.directionalShadowMatrix.length=v,i.pointShadowMatrix.length=y,i.spotLightMatrix.length=b+T-x,i.spotLightMap.length=T,i.numSpotLightShadowsWithMaps=x,i.numLightProbes=M,C.directionalLength=f,C.pointLength=p,C.spotLength=g,C.rectAreaLength=_,C.hemiLength=m,C.numDirectionalShadows=v,C.numPointShadows=y,C.numSpotShadows=b,C.numSpotMaps=T,C.numLightProbes=M,i.version=Wk++)}function l(c,u){let d=0,h=0,f=0,p=0,g=0;const _=u.matrixWorldInverse;for(let m=0,v=c.length;m=r.length?(o=new K0(n),r.push(o)):o=r[a],o}function i(){e=new WeakMap}return{get:t,dispose:i}}const Yk=`void main() { gl_Position = vec4( position, 1.0 ); -}`,BD=`uniform sampler2D shadow_pass; +}`,jk=`uniform sampler2D shadow_pass; uniform vec2 resolution; uniform float radius; #include @@ -3805,12 +3805,12 @@ void main() { squared_mean = squared_mean / samples; float std_dev = sqrt( squared_mean - mean * mean ); gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); -}`;function zD(n,e,t){let i=new Po;const s=new te,a=new te,r=new qe,o=new dg({depthPacking:eS}),l=new hg,c={},u=t.maxTextureSize,d={[fs]:un,[un]:fs,[ct]:ct},h=new ti({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new te},radius:{value:4}},vertexShader:UD,fragmentShader:BD}),f=h.clone();f.defines.HORIZONTAL_PASS=1;const p=new Ge;p.setAttribute("position",new rt(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const g=new we(p,h),_=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=N_;let m=this.type;this.render=function(x,M,C){if(_.enabled===!1||_.autoUpdate===!1&&_.needsUpdate===!1||x.length===0)return;const w=n.getRenderTarget(),E=n.getActiveCubeFace(),R=n.getActiveMipmapLevel(),D=n.state;D.setBlending(ks),D.buffers.depth.getReversed()===!0?D.buffers.color.setClear(0,0,0,0):D.buffers.color.setClear(1,1,1,1),D.buffers.depth.setTest(!0),D.setScissorTest(!1);const O=m!==as&&this.type===as,k=m===as&&this.type!==as;for(let U=0,F=x.length;Uu||s.y>u)&&(s.x>u&&(a.x=Math.floor(u/ne.x),s.x=a.x*ne.x,H.mapSize.x=a.x),s.y>u&&(a.y=Math.floor(u/ne.y),s.y=a.y*ne.y,H.mapSize.y=a.y)),H.map===null||O===!0||k===!0){const pe=this.type!==as?{minFilter:dn,magFilter:dn}:{};H.map!==null&&H.map.dispose(),H.map=new ms(s.x,s.y,pe),H.map.texture.name=W.name+".shadowMap",H.camera.updateProjectionMatrix()}n.setRenderTarget(H.map),n.clear();const oe=H.getViewportCount();for(let pe=0;pe0||M.map&&M.alphaTest>0||M.alphaToCoverage===!0){const D=E.uuid,O=M.uuid;let k=c[D];k===void 0&&(k={},c[D]=k);let U=k[O];U===void 0&&(U=E.clone(),k[O]=U,M.addEventListener("dispose",T)),E=U}if(E.visible=M.visible,E.wireframe=M.wireframe,w===as?E.side=M.shadowSide!==null?M.shadowSide:M.side:E.side=M.shadowSide!==null?M.shadowSide:d[M.side],E.alphaMap=M.alphaMap,E.alphaTest=M.alphaToCoverage===!0?.5:M.alphaTest,E.map=M.map,E.clipShadows=M.clipShadows,E.clippingPlanes=M.clippingPlanes,E.clipIntersection=M.clipIntersection,E.displacementMap=M.displacementMap,E.displacementScale=M.displacementScale,E.displacementBias=M.displacementBias,E.wireframeLinewidth=M.wireframeLinewidth,E.linewidth=M.linewidth,C.isPointLight===!0&&E.isMeshDistanceMaterial===!0){const D=n.properties.get(E);D.light=C}return E}function b(x,M,C,w,E){if(x.visible===!1)return;if(x.layers.test(M.layers)&&(x.isMesh||x.isLine||x.isPoints)&&(x.castShadow||x.receiveShadow&&E===as)&&(!x.frustumCulled||i.intersectsObject(x))){x.modelViewMatrix.multiplyMatrices(C.matrixWorldInverse,x.matrixWorld);const O=e.update(x),k=x.material;if(Array.isArray(k)){const U=O.groups;for(let F=0,W=U.length;F=1):H.indexOf("OpenGL ES")!==-1&&(W=parseFloat(/^OpenGL ES (\d)/.exec(H)[1]),F=W>=2);let ne=null,oe={};const pe=n.getParameter(n.SCISSOR_BOX),Ie=n.getParameter(n.VIEWPORT),De=new qe().fromArray(pe),Xe=new qe().fromArray(Ie);function ke(N,me,be,Fe){const he=new Uint8Array(4),re=n.createTexture();n.bindTexture(N,re),n.texParameteri(N,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(N,n.TEXTURE_MAG_FILTER,n.NEAREST);for(let ze=0;ze"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new te,u=new WeakMap;let d;const h=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function p(I,A){return f?new OffscreenCanvas(I,A):Hl("canvas")}function g(I,A,V){let J=1;const le=it(I);if((le.width>V||le.height>V)&&(J=V/Math.max(le.width,le.height)),J<1)if(typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&I instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&I instanceof ImageBitmap||typeof VideoFrame<"u"&&I instanceof VideoFrame){const ee=Math.floor(J*le.width),He=Math.floor(J*le.height);d===void 0&&(d=p(ee,He));const ye=A?p(ee,He):d;return ye.width=ee,ye.height=He,ye.getContext("2d").drawImage(I,0,0,ee,He),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+le.width+"x"+le.height+") to ("+ee+"x"+He+")."),ye}else return"data"in I&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+le.width+"x"+le.height+")."),I;return I}function _(I){return I.generateMipmaps}function m(I){n.generateMipmap(I)}function v(I){return I.isWebGLCubeRenderTarget?n.TEXTURE_CUBE_MAP:I.isWebGL3DRenderTarget?n.TEXTURE_3D:I.isWebGLArrayRenderTarget||I.isCompressedArrayTexture?n.TEXTURE_2D_ARRAY:n.TEXTURE_2D}function y(I,A,V,J,le=!1){if(I!==null){if(n[I]!==void 0)return n[I];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+I+"'")}let ee=A;if(A===n.RED&&(V===n.FLOAT&&(ee=n.R32F),V===n.HALF_FLOAT&&(ee=n.R16F),V===n.UNSIGNED_BYTE&&(ee=n.R8)),A===n.RED_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.R8UI),V===n.UNSIGNED_SHORT&&(ee=n.R16UI),V===n.UNSIGNED_INT&&(ee=n.R32UI),V===n.BYTE&&(ee=n.R8I),V===n.SHORT&&(ee=n.R16I),V===n.INT&&(ee=n.R32I)),A===n.RG&&(V===n.FLOAT&&(ee=n.RG32F),V===n.HALF_FLOAT&&(ee=n.RG16F),V===n.UNSIGNED_BYTE&&(ee=n.RG8)),A===n.RG_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.RG8UI),V===n.UNSIGNED_SHORT&&(ee=n.RG16UI),V===n.UNSIGNED_INT&&(ee=n.RG32UI),V===n.BYTE&&(ee=n.RG8I),V===n.SHORT&&(ee=n.RG16I),V===n.INT&&(ee=n.RG32I)),A===n.RGB_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.RGB8UI),V===n.UNSIGNED_SHORT&&(ee=n.RGB16UI),V===n.UNSIGNED_INT&&(ee=n.RGB32UI),V===n.BYTE&&(ee=n.RGB8I),V===n.SHORT&&(ee=n.RGB16I),V===n.INT&&(ee=n.RGB32I)),A===n.RGBA_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.RGBA8UI),V===n.UNSIGNED_SHORT&&(ee=n.RGBA16UI),V===n.UNSIGNED_INT&&(ee=n.RGBA32UI),V===n.BYTE&&(ee=n.RGBA8I),V===n.SHORT&&(ee=n.RGBA16I),V===n.INT&&(ee=n.RGBA32I)),A===n.RGB&&(V===n.UNSIGNED_INT_5_9_9_9_REV&&(ee=n.RGB9_E5),V===n.UNSIGNED_INT_10F_11F_11F_REV&&(ee=n.R11F_G11F_B10F)),A===n.RGBA){const He=le?Bl:at.getTransfer(J);V===n.FLOAT&&(ee=n.RGBA32F),V===n.HALF_FLOAT&&(ee=n.RGBA16F),V===n.UNSIGNED_BYTE&&(ee=He===Pt?n.SRGB8_ALPHA8:n.RGBA8),V===n.UNSIGNED_SHORT_4_4_4_4&&(ee=n.RGBA4),V===n.UNSIGNED_SHORT_5_5_5_1&&(ee=n.RGB5_A1)}return(ee===n.R16F||ee===n.R32F||ee===n.RG16F||ee===n.RG32F||ee===n.RGBA16F||ee===n.RGBA32F)&&e.get("EXT_color_buffer_float"),ee}function b(I,A){let V;return I?A===null||A===zs||A===vo?V=n.DEPTH24_STENCIL8:A===Sn?V=n.DEPTH32F_STENCIL8:A===yo&&(V=n.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):A===null||A===zs||A===vo?V=n.DEPTH_COMPONENT24:A===Sn?V=n.DEPTH_COMPONENT32F:A===yo&&(V=n.DEPTH_COMPONENT16),V}function T(I,A){return _(I)===!0||I.isFramebufferTexture&&I.minFilter!==dn&&I.minFilter!==Vt?Math.log2(Math.max(A.width,A.height))+1:I.mipmaps!==void 0&&I.mipmaps.length>0?I.mipmaps.length:I.isCompressedTexture&&Array.isArray(I.image)?A.mipmaps.length:1}function x(I){const A=I.target;A.removeEventListener("dispose",x),C(A),A.isVideoTexture&&u.delete(A)}function M(I){const A=I.target;A.removeEventListener("dispose",M),E(A)}function C(I){const A=i.get(I);if(A.__webglInit===void 0)return;const V=I.source,J=h.get(V);if(J){const le=J[A.__cacheKey];le.usedTimes--,le.usedTimes===0&&w(I),Object.keys(J).length===0&&h.delete(V)}i.remove(I)}function w(I){const A=i.get(I);n.deleteTexture(A.__webglTexture);const V=I.source,J=h.get(V);delete J[A.__cacheKey],r.memory.textures--}function E(I){const A=i.get(I);if(I.depthTexture&&(I.depthTexture.dispose(),i.remove(I.depthTexture)),I.isWebGLCubeRenderTarget)for(let J=0;J<6;J++){if(Array.isArray(A.__webglFramebuffer[J]))for(let le=0;le=s.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+I+" texture units while this GPU supports only "+s.maxTextures),R+=1,I}function k(I){const A=[];return A.push(I.wrapS),A.push(I.wrapT),A.push(I.wrapR||0),A.push(I.magFilter),A.push(I.minFilter),A.push(I.anisotropy),A.push(I.internalFormat),A.push(I.format),A.push(I.type),A.push(I.generateMipmaps),A.push(I.premultiplyAlpha),A.push(I.flipY),A.push(I.unpackAlignment),A.push(I.colorSpace),A.join()}function U(I,A){const V=i.get(I);if(I.isVideoTexture&&ge(I),I.isRenderTargetTexture===!1&&I.isExternalTexture!==!0&&I.version>0&&V.__version!==I.version){const J=I.image;if(J===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(J.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{Z(V,I,A);return}}else I.isExternalTexture&&(V.__webglTexture=I.sourceTexture?I.sourceTexture:null);t.bindTexture(n.TEXTURE_2D,V.__webglTexture,n.TEXTURE0+A)}function F(I,A){const V=i.get(I);if(I.isRenderTargetTexture===!1&&I.version>0&&V.__version!==I.version){Z(V,I,A);return}t.bindTexture(n.TEXTURE_2D_ARRAY,V.__webglTexture,n.TEXTURE0+A)}function W(I,A){const V=i.get(I);if(I.isRenderTargetTexture===!1&&I.version>0&&V.__version!==I.version){Z(V,I,A);return}t.bindTexture(n.TEXTURE_3D,V.__webglTexture,n.TEXTURE0+A)}function H(I,A){const V=i.get(I);if(I.version>0&&V.__version!==I.version){se(V,I,A);return}t.bindTexture(n.TEXTURE_CUBE_MAP,V.__webglTexture,n.TEXTURE0+A)}const ne={[ps]:n.REPEAT,[Hn]:n.CLAMP_TO_EDGE,[go]:n.MIRRORED_REPEAT},oe={[dn]:n.NEAREST,[_h]:n.NEAREST_MIPMAP_NEAREST,[Xa]:n.NEAREST_MIPMAP_LINEAR,[Vt]:n.LINEAR,[eo]:n.LINEAR_MIPMAP_NEAREST,[Ti]:n.LINEAR_MIPMAP_LINEAR},pe={[nS]:n.NEVER,[lS]:n.ALWAYS,[iS]:n.LESS,[j_]:n.LEQUAL,[sS]:n.EQUAL,[oS]:n.GEQUAL,[aS]:n.GREATER,[rS]:n.NOTEQUAL};function Ie(I,A){if(A.type===Sn&&e.has("OES_texture_float_linear")===!1&&(A.magFilter===Vt||A.magFilter===eo||A.magFilter===Xa||A.magFilter===Ti||A.minFilter===Vt||A.minFilter===eo||A.minFilter===Xa||A.minFilter===Ti)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),n.texParameteri(I,n.TEXTURE_WRAP_S,ne[A.wrapS]),n.texParameteri(I,n.TEXTURE_WRAP_T,ne[A.wrapT]),(I===n.TEXTURE_3D||I===n.TEXTURE_2D_ARRAY)&&n.texParameteri(I,n.TEXTURE_WRAP_R,ne[A.wrapR]),n.texParameteri(I,n.TEXTURE_MAG_FILTER,oe[A.magFilter]),n.texParameteri(I,n.TEXTURE_MIN_FILTER,oe[A.minFilter]),A.compareFunction&&(n.texParameteri(I,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(I,n.TEXTURE_COMPARE_FUNC,pe[A.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(A.magFilter===dn||A.minFilter!==Xa&&A.minFilter!==Ti||A.type===Sn&&e.has("OES_texture_float_linear")===!1)return;if(A.anisotropy>1||i.get(A).__currentAnisotropy){const V=e.get("EXT_texture_filter_anisotropic");n.texParameterf(I,V.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(A.anisotropy,s.getMaxAnisotropy())),i.get(A).__currentAnisotropy=A.anisotropy}}}function De(I,A){let V=!1;I.__webglInit===void 0&&(I.__webglInit=!0,A.addEventListener("dispose",x));const J=A.source;let le=h.get(J);le===void 0&&(le={},h.set(J,le));const ee=k(A);if(ee!==I.__cacheKey){le[ee]===void 0&&(le[ee]={texture:n.createTexture(),usedTimes:0},r.memory.textures++,V=!0),le[ee].usedTimes++;const He=le[I.__cacheKey];He!==void 0&&(le[I.__cacheKey].usedTimes--,He.usedTimes===0&&w(A)),I.__cacheKey=ee,I.__webglTexture=le[ee].texture}return V}function Xe(I,A,V){return Math.floor(Math.floor(I/V)/A)}function ke(I,A,V,J){const ee=I.updateRanges;if(ee.length===0)t.texSubImage2D(n.TEXTURE_2D,0,0,0,A.width,A.height,V,J,A.data);else{ee.sort((de,Pe)=>de.start-Pe.start);let He=0;for(let de=1;de0){N&&me&&t.texStorage2D(n.TEXTURE_2D,Fe,Ve,ht[0].width,ht[0].height);for(let he=0,re=ht.length;he0){const ze=Rm(Ce.width,Ce.height,A.format,A.type);for(const lt of A.layerUpdates){const kt=Ce.data.subarray(lt*ze/Ce.data.BYTES_PER_ELEMENT,(lt+1)*ze/Ce.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,he,0,0,lt,Ce.width,Ce.height,1,Pe,kt)}A.clearLayerUpdates()}else t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,he,0,0,0,Ce.width,Ce.height,de.depth,Pe,Ce.data)}else t.compressedTexImage3D(n.TEXTURE_2D_ARRAY,he,Ve,Ce.width,Ce.height,de.depth,0,Ce.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else N?be&&t.texSubImage3D(n.TEXTURE_2D_ARRAY,he,0,0,0,Ce.width,Ce.height,de.depth,Pe,Je,Ce.data):t.texImage3D(n.TEXTURE_2D_ARRAY,he,Ve,Ce.width,Ce.height,de.depth,0,Pe,Je,Ce.data)}else{N&&me&&t.texStorage2D(n.TEXTURE_2D,Fe,Ve,ht[0].width,ht[0].height);for(let he=0,re=ht.length;he0){const he=Rm(de.width,de.height,A.format,A.type);for(const re of A.layerUpdates){const ze=de.data.subarray(re*he/de.data.BYTES_PER_ELEMENT,(re+1)*he/de.data.BYTES_PER_ELEMENT);t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,re,de.width,de.height,1,Pe,Je,ze)}A.clearLayerUpdates()}else t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,de.width,de.height,de.depth,Pe,Je,de.data)}else t.texImage3D(n.TEXTURE_2D_ARRAY,0,Ve,de.width,de.height,de.depth,0,Pe,Je,de.data);else if(A.isData3DTexture)N?(me&&t.texStorage3D(n.TEXTURE_3D,Fe,Ve,de.width,de.height,de.depth),be&&t.texSubImage3D(n.TEXTURE_3D,0,0,0,0,de.width,de.height,de.depth,Pe,Je,de.data)):t.texImage3D(n.TEXTURE_3D,0,Ve,de.width,de.height,de.depth,0,Pe,Je,de.data);else if(A.isFramebufferTexture){if(me)if(N)t.texStorage2D(n.TEXTURE_2D,Fe,Ve,de.width,de.height);else{let he=de.width,re=de.height;for(let ze=0;ze>=1,re>>=1}}else if(ht.length>0){if(N&&me){const he=it(ht[0]);t.texStorage2D(n.TEXTURE_2D,Fe,Ve,he.width,he.height)}for(let he=0,re=ht.length;he0&&Fe++;const re=it(Pe[0]);t.texStorage2D(n.TEXTURE_CUBE_MAP,Fe,ht,re.width,re.height)}for(let re=0;re<6;re++)if(de){N?be&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+re,0,0,0,Pe[re].width,Pe[re].height,Ve,Ce,Pe[re].data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+re,0,ht,Pe[re].width,Pe[re].height,0,Ve,Ce,Pe[re].data);for(let ze=0;ze>ee),Je=Math.max(1,A.height>>ee);le===n.TEXTURE_3D||le===n.TEXTURE_2D_ARRAY?t.texImage3D(le,ee,Ue,Pe,Je,A.depth,0,He,ye,null):t.texImage2D(le,ee,Ue,Pe,Je,0,He,ye,null)}t.bindFramebuffer(n.FRAMEBUFFER,I),ce(A)?o.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,J,le,de.__webglTexture,0,_e(A)):(le===n.TEXTURE_2D||le>=n.TEXTURE_CUBE_MAP_POSITIVE_X&&le<=n.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&n.framebufferTexture2D(n.FRAMEBUFFER,J,le,de.__webglTexture,ee),t.bindFramebuffer(n.FRAMEBUFFER,null)}function X(I,A,V){if(n.bindRenderbuffer(n.RENDERBUFFER,I),A.depthBuffer){const J=A.depthTexture,le=J&&J.isDepthTexture?J.type:null,ee=b(A.stencilBuffer,le),He=A.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ye=_e(A);ce(A)?o.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,ye,ee,A.width,A.height):V?n.renderbufferStorageMultisample(n.RENDERBUFFER,ye,ee,A.width,A.height):n.renderbufferStorage(n.RENDERBUFFER,ee,A.width,A.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,He,n.RENDERBUFFER,I)}else{const J=A.textures;for(let le=0;le{delete A.__boundDepthTexture,delete A.__depthDisposeCallback,J.removeEventListener("dispose",le)};J.addEventListener("dispose",le),A.__depthDisposeCallback=le}A.__boundDepthTexture=J}if(I.depthTexture&&!A.__autoAllocateDepthBuffer){if(V)throw new Error("target.depthTexture not supported in Cube render targets");const J=I.texture.mipmaps;J&&J.length>0?ie(A.__webglFramebuffer[0],I):ie(A.__webglFramebuffer,I)}else if(V){A.__webglDepthbuffer=[];for(let J=0;J<6;J++)if(t.bindFramebuffer(n.FRAMEBUFFER,A.__webglFramebuffer[J]),A.__webglDepthbuffer[J]===void 0)A.__webglDepthbuffer[J]=n.createRenderbuffer(),X(A.__webglDepthbuffer[J],I,!1);else{const le=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ee=A.__webglDepthbuffer[J];n.bindRenderbuffer(n.RENDERBUFFER,ee),n.framebufferRenderbuffer(n.FRAMEBUFFER,le,n.RENDERBUFFER,ee)}}else{const J=I.texture.mipmaps;if(J&&J.length>0?t.bindFramebuffer(n.FRAMEBUFFER,A.__webglFramebuffer[0]):t.bindFramebuffer(n.FRAMEBUFFER,A.__webglFramebuffer),A.__webglDepthbuffer===void 0)A.__webglDepthbuffer=n.createRenderbuffer(),X(A.__webglDepthbuffer,I,!1);else{const le=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ee=A.__webglDepthbuffer;n.bindRenderbuffer(n.RENDERBUFFER,ee),n.framebufferRenderbuffer(n.FRAMEBUFFER,le,n.RENDERBUFFER,ee)}}t.bindFramebuffer(n.FRAMEBUFFER,null)}function Ae(I,A,V){const J=i.get(I);A!==void 0&&Se(J.__webglFramebuffer,I,I.texture,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,0),V!==void 0&&xe(I)}function L(I){const A=I.texture,V=i.get(I),J=i.get(A);I.addEventListener("dispose",M);const le=I.textures,ee=I.isWebGLCubeRenderTarget===!0,He=le.length>1;if(He||(J.__webglTexture===void 0&&(J.__webglTexture=n.createTexture()),J.__version=A.version,r.memory.textures++),ee){V.__webglFramebuffer=[];for(let ye=0;ye<6;ye++)if(A.mipmaps&&A.mipmaps.length>0){V.__webglFramebuffer[ye]=[];for(let Ue=0;Ue0){V.__webglFramebuffer=[];for(let ye=0;ye0&&ce(I)===!1){V.__webglMultisampledFramebuffer=n.createFramebuffer(),V.__webglColorRenderbuffer=[],t.bindFramebuffer(n.FRAMEBUFFER,V.__webglMultisampledFramebuffer);for(let ye=0;ye0)for(let Ue=0;Ue0)for(let Ue=0;Ue0){if(ce(I)===!1){const A=I.textures,V=I.width,J=I.height;let le=n.COLOR_BUFFER_BIT;const ee=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,He=i.get(I),ye=A.length>1;if(ye)for(let Be=0;Be0?t.bindFramebuffer(n.DRAW_FRAMEBUFFER,He.__webglFramebuffer[0]):t.bindFramebuffer(n.DRAW_FRAMEBUFFER,He.__webglFramebuffer);for(let Be=0;Be0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&A.__useRenderToTexture!==!1}function ge(I){const A=r.render.frame;u.get(I)!==A&&(u.set(I,A),I.update())}function $e(I,A){const V=I.colorSpace,J=I.format,le=I.type;return I.isCompressedTexture===!0||I.isVideoTexture===!0||V!==xn&&V!==Ls&&(at.getTransfer(V)===Pt?(J!==Vn||le!==Yi)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",V)),A}function it(I){return typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement?(c.width=I.naturalWidth||I.width,c.height=I.naturalHeight||I.height):typeof VideoFrame<"u"&&I instanceof VideoFrame?(c.width=I.displayWidth,c.height=I.displayHeight):(c.width=I.width,c.height=I.height),c}this.allocateTextureUnit=O,this.resetTextureUnits=D,this.setTexture2D=U,this.setTexture2DArray=F,this.setTexture3D=W,this.setTextureCube=H,this.rebindTextures=Ae,this.setupRenderTarget=L,this.updateRenderTargetMipmap=G,this.updateMultisampleRenderTarget=Q,this.setupDepthRenderbuffer=xe,this.setupFrameBufferTexture=Se,this.useMultisampledRTT=ce}function oT(n,e){function t(i,s=Ls){let a;const r=at.getTransfer(s);if(i===Yi)return n.UNSIGNED_BYTE;if(i===yh)return n.UNSIGNED_SHORT_4_4_4_4;if(i===vh)return n.UNSIGNED_SHORT_5_5_5_1;if(i===G_)return n.UNSIGNED_INT_5_9_9_9_REV;if(i===$_)return n.UNSIGNED_INT_10F_11F_11F_REV;if(i===H_)return n.BYTE;if(i===V_)return n.SHORT;if(i===yo)return n.UNSIGNED_SHORT;if(i===gh)return n.INT;if(i===zs)return n.UNSIGNED_INT;if(i===Sn)return n.FLOAT;if(i===ls)return n.HALF_FLOAT;if(i===W_)return n.ALPHA;if(i===X_)return n.RGB;if(i===Vn)return n.RGBA;if(i===bo)return n.DEPTH_COMPONENT;if(i===xo)return n.DEPTH_STENCIL;if(i===bh)return n.RED;if(i===ic)return n.RED_INTEGER;if(i===K_)return n.RG;if(i===xh)return n.RG_INTEGER;if(i===wh)return n.RGBA_INTEGER;if(i===Tl||i===Ml||i===El||i===Cl)if(r===Pt)if(a=e.get("WEBGL_compressed_texture_s3tc_srgb"),a!==null){if(i===Tl)return a.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===Ml)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===El)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===Cl)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(a=e.get("WEBGL_compressed_texture_s3tc"),a!==null){if(i===Tl)return a.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===Ml)return a.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===El)return a.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===Cl)return a.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===yd||i===vd||i===bd||i===xd)if(a=e.get("WEBGL_compressed_texture_pvrtc"),a!==null){if(i===yd)return a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===vd)return a.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===bd)return a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===xd)return a.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===wd||i===Sd||i===Td)if(a=e.get("WEBGL_compressed_texture_etc"),a!==null){if(i===wd||i===Sd)return r===Pt?a.COMPRESSED_SRGB8_ETC2:a.COMPRESSED_RGB8_ETC2;if(i===Td)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:a.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(i===Md||i===Ed||i===Cd||i===Ad||i===Rd||i===Pd||i===Id||i===Ld||i===Dd||i===kd||i===Od||i===Fd||i===Nd||i===Ud)if(a=e.get("WEBGL_compressed_texture_astc"),a!==null){if(i===Md)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:a.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===Ed)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:a.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===Cd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:a.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===Ad)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:a.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===Rd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:a.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===Pd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:a.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===Id)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:a.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===Ld)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:a.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===Dd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:a.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===kd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:a.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===Od)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:a.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===Fd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:a.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===Nd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:a.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===Ud)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:a.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===Bd||i===zd||i===Hd)if(a=e.get("EXT_texture_compression_bptc"),a!==null){if(i===Bd)return r===Pt?a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:a.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===zd)return a.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===Hd)return a.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===Vd||i===Gd||i===$d||i===Wd)if(a=e.get("EXT_texture_compression_rgtc"),a!==null){if(i===Vd)return a.COMPRESSED_RED_RGTC1_EXT;if(i===Gd)return a.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===$d)return a.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===Wd)return a.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===vo?n.UNSIGNED_INT_24_8:n[i]!==void 0?n[i]:null}return{convert:t}}const $D=` +}`;function Zk(n,e,t){let i=new ko;const s=new te,a=new te,r=new qe,o=new yg({depthPacking:lS}),l=new vg,c={},u=t.maxTextureSize,d={[fs]:un,[un]:fs,[ct]:ct},h=new ti({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new te},radius:{value:4}},vertexShader:Yk,fragmentShader:jk}),f=h.clone();f.defines.HORIZONTAL_PASS=1;const p=new Ge;p.setAttribute("position",new ot(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const g=new we(p,h),_=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=$_;let m=this.type;this.render=function(x,M,C){if(_.enabled===!1||_.autoUpdate===!1&&_.needsUpdate===!1||x.length===0)return;const w=n.getRenderTarget(),E=n.getActiveCubeFace(),R=n.getActiveMipmapLevel(),k=n.state;k.setBlending(Ds),k.buffers.depth.getReversed()===!0?k.buffers.color.setClear(0,0,0,0):k.buffers.color.setClear(1,1,1,1),k.buffers.depth.setTest(!0),k.setScissorTest(!1);const O=m!==as&&this.type===as,D=m===as&&this.type!==as;for(let U=0,F=x.length;Uu||s.y>u)&&(s.x>u&&(a.x=Math.floor(u/ne.x),s.x=a.x*ne.x,H.mapSize.x=a.x),s.y>u&&(a.y=Math.floor(u/ne.y),s.y=a.y*ne.y,H.mapSize.y=a.y)),H.map===null||O===!0||D===!0){const pe=this.type!==as?{minFilter:dn,magFilter:dn}:{};H.map!==null&&H.map.dispose(),H.map=new ms(s.x,s.y,pe),H.map.texture.name=W.name+".shadowMap",H.camera.updateProjectionMatrix()}n.setRenderTarget(H.map),n.clear();const oe=H.getViewportCount();for(let pe=0;pe0||M.map&&M.alphaTest>0||M.alphaToCoverage===!0){const k=E.uuid,O=M.uuid;let D=c[k];D===void 0&&(D={},c[k]=D);let U=D[O];U===void 0&&(U=E.clone(),D[O]=U,M.addEventListener("dispose",T)),E=U}if(E.visible=M.visible,E.wireframe=M.wireframe,w===as?E.side=M.shadowSide!==null?M.shadowSide:M.side:E.side=M.shadowSide!==null?M.shadowSide:d[M.side],E.alphaMap=M.alphaMap,E.alphaTest=M.alphaToCoverage===!0?.5:M.alphaTest,E.map=M.map,E.clipShadows=M.clipShadows,E.clippingPlanes=M.clippingPlanes,E.clipIntersection=M.clipIntersection,E.displacementMap=M.displacementMap,E.displacementScale=M.displacementScale,E.displacementBias=M.displacementBias,E.wireframeLinewidth=M.wireframeLinewidth,E.linewidth=M.linewidth,C.isPointLight===!0&&E.isMeshDistanceMaterial===!0){const k=n.properties.get(E);k.light=C}return E}function b(x,M,C,w,E){if(x.visible===!1)return;if(x.layers.test(M.layers)&&(x.isMesh||x.isLine||x.isPoints)&&(x.castShadow||x.receiveShadow&&E===as)&&(!x.frustumCulled||i.intersectsObject(x))){x.modelViewMatrix.multiplyMatrices(C.matrixWorldInverse,x.matrixWorld);const O=e.update(x),D=x.material;if(Array.isArray(D)){const U=O.groups;for(let F=0,W=U.length;F=1):H.indexOf("OpenGL ES")!==-1&&(W=parseFloat(/^OpenGL ES (\d)/.exec(H)[1]),F=W>=2);let ne=null,oe={};const pe=n.getParameter(n.SCISSOR_BOX),Ie=n.getParameter(n.VIEWPORT),ke=new qe().fromArray(pe),Xe=new qe().fromArray(Ie);function De(N,me,be,Fe){const he=new Uint8Array(4),re=n.createTexture();n.bindTexture(N,re),n.texParameteri(N,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(N,n.TEXTURE_MAG_FILTER,n.NEAREST);for(let ze=0;ze"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new te,u=new WeakMap;let d;const h=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function p(I,A){return f?new OffscreenCanvas(I,A):Wl("canvas")}function g(I,A,V){let J=1;const le=it(I);if((le.width>V||le.height>V)&&(J=V/Math.max(le.width,le.height)),J<1)if(typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&I instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&I instanceof ImageBitmap||typeof VideoFrame<"u"&&I instanceof VideoFrame){const ee=Math.floor(J*le.width),He=Math.floor(J*le.height);d===void 0&&(d=p(ee,He));const ye=A?p(ee,He):d;return ye.width=ee,ye.height=He,ye.getContext("2d").drawImage(I,0,0,ee,He),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+le.width+"x"+le.height+") to ("+ee+"x"+He+")."),ye}else return"data"in I&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+le.width+"x"+le.height+")."),I;return I}function _(I){return I.generateMipmaps}function m(I){n.generateMipmap(I)}function v(I){return I.isWebGLCubeRenderTarget?n.TEXTURE_CUBE_MAP:I.isWebGL3DRenderTarget?n.TEXTURE_3D:I.isWebGLArrayRenderTarget||I.isCompressedArrayTexture?n.TEXTURE_2D_ARRAY:n.TEXTURE_2D}function y(I,A,V,J,le=!1){if(I!==null){if(n[I]!==void 0)return n[I];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+I+"'")}let ee=A;if(A===n.RED&&(V===n.FLOAT&&(ee=n.R32F),V===n.HALF_FLOAT&&(ee=n.R16F),V===n.UNSIGNED_BYTE&&(ee=n.R8)),A===n.RED_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.R8UI),V===n.UNSIGNED_SHORT&&(ee=n.R16UI),V===n.UNSIGNED_INT&&(ee=n.R32UI),V===n.BYTE&&(ee=n.R8I),V===n.SHORT&&(ee=n.R16I),V===n.INT&&(ee=n.R32I)),A===n.RG&&(V===n.FLOAT&&(ee=n.RG32F),V===n.HALF_FLOAT&&(ee=n.RG16F),V===n.UNSIGNED_BYTE&&(ee=n.RG8)),A===n.RG_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.RG8UI),V===n.UNSIGNED_SHORT&&(ee=n.RG16UI),V===n.UNSIGNED_INT&&(ee=n.RG32UI),V===n.BYTE&&(ee=n.RG8I),V===n.SHORT&&(ee=n.RG16I),V===n.INT&&(ee=n.RG32I)),A===n.RGB_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.RGB8UI),V===n.UNSIGNED_SHORT&&(ee=n.RGB16UI),V===n.UNSIGNED_INT&&(ee=n.RGB32UI),V===n.BYTE&&(ee=n.RGB8I),V===n.SHORT&&(ee=n.RGB16I),V===n.INT&&(ee=n.RGB32I)),A===n.RGBA_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.RGBA8UI),V===n.UNSIGNED_SHORT&&(ee=n.RGBA16UI),V===n.UNSIGNED_INT&&(ee=n.RGBA32UI),V===n.BYTE&&(ee=n.RGBA8I),V===n.SHORT&&(ee=n.RGBA16I),V===n.INT&&(ee=n.RGBA32I)),A===n.RGB&&(V===n.UNSIGNED_INT_5_9_9_9_REV&&(ee=n.RGB9_E5),V===n.UNSIGNED_INT_10F_11F_11F_REV&&(ee=n.R11F_G11F_B10F)),A===n.RGBA){const He=le?Gl:rt.getTransfer(J);V===n.FLOAT&&(ee=n.RGBA32F),V===n.HALF_FLOAT&&(ee=n.RGBA16F),V===n.UNSIGNED_BYTE&&(ee=He===Pt?n.SRGB8_ALPHA8:n.RGBA8),V===n.UNSIGNED_SHORT_4_4_4_4&&(ee=n.RGBA4),V===n.UNSIGNED_SHORT_5_5_5_1&&(ee=n.RGB5_A1)}return(ee===n.R16F||ee===n.R32F||ee===n.RG16F||ee===n.RG32F||ee===n.RGBA16F||ee===n.RGBA32F)&&e.get("EXT_color_buffer_float"),ee}function b(I,A){let V;return I?A===null||A===zs||A===wo?V=n.DEPTH24_STENCIL8:A===Sn?V=n.DEPTH32F_STENCIL8:A===xo&&(V=n.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):A===null||A===zs||A===wo?V=n.DEPTH_COMPONENT24:A===Sn?V=n.DEPTH_COMPONENT32F:A===xo&&(V=n.DEPTH_COMPONENT16),V}function T(I,A){return _(I)===!0||I.isFramebufferTexture&&I.minFilter!==dn&&I.minFilter!==Vt?Math.log2(Math.max(A.width,A.height))+1:I.mipmaps!==void 0&&I.mipmaps.length>0?I.mipmaps.length:I.isCompressedTexture&&Array.isArray(I.image)?A.mipmaps.length:1}function x(I){const A=I.target;A.removeEventListener("dispose",x),C(A),A.isVideoTexture&&u.delete(A)}function M(I){const A=I.target;A.removeEventListener("dispose",M),E(A)}function C(I){const A=i.get(I);if(A.__webglInit===void 0)return;const V=I.source,J=h.get(V);if(J){const le=J[A.__cacheKey];le.usedTimes--,le.usedTimes===0&&w(I),Object.keys(J).length===0&&h.delete(V)}i.remove(I)}function w(I){const A=i.get(I);n.deleteTexture(A.__webglTexture);const V=I.source,J=h.get(V);delete J[A.__cacheKey],r.memory.textures--}function E(I){const A=i.get(I);if(I.depthTexture&&(I.depthTexture.dispose(),i.remove(I.depthTexture)),I.isWebGLCubeRenderTarget)for(let J=0;J<6;J++){if(Array.isArray(A.__webglFramebuffer[J]))for(let le=0;le=s.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+I+" texture units while this GPU supports only "+s.maxTextures),R+=1,I}function D(I){const A=[];return A.push(I.wrapS),A.push(I.wrapT),A.push(I.wrapR||0),A.push(I.magFilter),A.push(I.minFilter),A.push(I.anisotropy),A.push(I.internalFormat),A.push(I.format),A.push(I.type),A.push(I.generateMipmaps),A.push(I.premultiplyAlpha),A.push(I.flipY),A.push(I.unpackAlignment),A.push(I.colorSpace),A.join()}function U(I,A){const V=i.get(I);if(I.isVideoTexture&&ge(I),I.isRenderTargetTexture===!1&&I.isExternalTexture!==!0&&I.version>0&&V.__version!==I.version){const J=I.image;if(J===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(J.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{Z(V,I,A);return}}else I.isExternalTexture&&(V.__webglTexture=I.sourceTexture?I.sourceTexture:null);t.bindTexture(n.TEXTURE_2D,V.__webglTexture,n.TEXTURE0+A)}function F(I,A){const V=i.get(I);if(I.isRenderTargetTexture===!1&&I.version>0&&V.__version!==I.version){Z(V,I,A);return}t.bindTexture(n.TEXTURE_2D_ARRAY,V.__webglTexture,n.TEXTURE0+A)}function W(I,A){const V=i.get(I);if(I.isRenderTargetTexture===!1&&I.version>0&&V.__version!==I.version){Z(V,I,A);return}t.bindTexture(n.TEXTURE_3D,V.__webglTexture,n.TEXTURE0+A)}function H(I,A){const V=i.get(I);if(I.version>0&&V.__version!==I.version){ae(V,I,A);return}t.bindTexture(n.TEXTURE_CUBE_MAP,V.__webglTexture,n.TEXTURE0+A)}const ne={[ps]:n.REPEAT,[Hn]:n.CLAMP_TO_EDGE,[bo]:n.MIRRORED_REPEAT},oe={[dn]:n.NEAREST,[wh]:n.NEAREST_MIPMAP_NEAREST,[Ka]:n.NEAREST_MIPMAP_LINEAR,[Vt]:n.LINEAR,[no]:n.LINEAR_MIPMAP_NEAREST,[Mi]:n.LINEAR_MIPMAP_LINEAR},pe={[uS]:n.NEVER,[_S]:n.ALWAYS,[dS]:n.LESS,[ig]:n.LEQUAL,[hS]:n.EQUAL,[mS]:n.GEQUAL,[fS]:n.GREATER,[pS]:n.NOTEQUAL};function Ie(I,A){if(A.type===Sn&&e.has("OES_texture_float_linear")===!1&&(A.magFilter===Vt||A.magFilter===no||A.magFilter===Ka||A.magFilter===Mi||A.minFilter===Vt||A.minFilter===no||A.minFilter===Ka||A.minFilter===Mi)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),n.texParameteri(I,n.TEXTURE_WRAP_S,ne[A.wrapS]),n.texParameteri(I,n.TEXTURE_WRAP_T,ne[A.wrapT]),(I===n.TEXTURE_3D||I===n.TEXTURE_2D_ARRAY)&&n.texParameteri(I,n.TEXTURE_WRAP_R,ne[A.wrapR]),n.texParameteri(I,n.TEXTURE_MAG_FILTER,oe[A.magFilter]),n.texParameteri(I,n.TEXTURE_MIN_FILTER,oe[A.minFilter]),A.compareFunction&&(n.texParameteri(I,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(I,n.TEXTURE_COMPARE_FUNC,pe[A.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(A.magFilter===dn||A.minFilter!==Ka&&A.minFilter!==Mi||A.type===Sn&&e.has("OES_texture_float_linear")===!1)return;if(A.anisotropy>1||i.get(A).__currentAnisotropy){const V=e.get("EXT_texture_filter_anisotropic");n.texParameterf(I,V.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(A.anisotropy,s.getMaxAnisotropy())),i.get(A).__currentAnisotropy=A.anisotropy}}}function ke(I,A){let V=!1;I.__webglInit===void 0&&(I.__webglInit=!0,A.addEventListener("dispose",x));const J=A.source;let le=h.get(J);le===void 0&&(le={},h.set(J,le));const ee=D(A);if(ee!==I.__cacheKey){le[ee]===void 0&&(le[ee]={texture:n.createTexture(),usedTimes:0},r.memory.textures++,V=!0),le[ee].usedTimes++;const He=le[I.__cacheKey];He!==void 0&&(le[I.__cacheKey].usedTimes--,He.usedTimes===0&&w(A)),I.__cacheKey=ee,I.__webglTexture=le[ee].texture}return V}function Xe(I,A,V){return Math.floor(Math.floor(I/V)/A)}function De(I,A,V,J){const ee=I.updateRanges;if(ee.length===0)t.texSubImage2D(n.TEXTURE_2D,0,0,0,A.width,A.height,V,J,A.data);else{ee.sort((de,Pe)=>de.start-Pe.start);let He=0;for(let de=1;de0){N&&me&&t.texStorage2D(n.TEXTURE_2D,Fe,Ve,ht[0].width,ht[0].height);for(let he=0,re=ht.length;he0){const ze=Fm(Ce.width,Ce.height,A.format,A.type);for(const lt of A.layerUpdates){const Dt=Ce.data.subarray(lt*ze/Ce.data.BYTES_PER_ELEMENT,(lt+1)*ze/Ce.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,he,0,0,lt,Ce.width,Ce.height,1,Pe,Dt)}A.clearLayerUpdates()}else t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,he,0,0,0,Ce.width,Ce.height,de.depth,Pe,Ce.data)}else t.compressedTexImage3D(n.TEXTURE_2D_ARRAY,he,Ve,Ce.width,Ce.height,de.depth,0,Ce.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else N?be&&t.texSubImage3D(n.TEXTURE_2D_ARRAY,he,0,0,0,Ce.width,Ce.height,de.depth,Pe,Je,Ce.data):t.texImage3D(n.TEXTURE_2D_ARRAY,he,Ve,Ce.width,Ce.height,de.depth,0,Pe,Je,Ce.data)}else{N&&me&&t.texStorage2D(n.TEXTURE_2D,Fe,Ve,ht[0].width,ht[0].height);for(let he=0,re=ht.length;he0){const he=Fm(de.width,de.height,A.format,A.type);for(const re of A.layerUpdates){const ze=de.data.subarray(re*he/de.data.BYTES_PER_ELEMENT,(re+1)*he/de.data.BYTES_PER_ELEMENT);t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,re,de.width,de.height,1,Pe,Je,ze)}A.clearLayerUpdates()}else t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,de.width,de.height,de.depth,Pe,Je,de.data)}else t.texImage3D(n.TEXTURE_2D_ARRAY,0,Ve,de.width,de.height,de.depth,0,Pe,Je,de.data);else if(A.isData3DTexture)N?(me&&t.texStorage3D(n.TEXTURE_3D,Fe,Ve,de.width,de.height,de.depth),be&&t.texSubImage3D(n.TEXTURE_3D,0,0,0,0,de.width,de.height,de.depth,Pe,Je,de.data)):t.texImage3D(n.TEXTURE_3D,0,Ve,de.width,de.height,de.depth,0,Pe,Je,de.data);else if(A.isFramebufferTexture){if(me)if(N)t.texStorage2D(n.TEXTURE_2D,Fe,Ve,de.width,de.height);else{let he=de.width,re=de.height;for(let ze=0;ze>=1,re>>=1}}else if(ht.length>0){if(N&&me){const he=it(ht[0]);t.texStorage2D(n.TEXTURE_2D,Fe,Ve,he.width,he.height)}for(let he=0,re=ht.length;he0&&Fe++;const re=it(Pe[0]);t.texStorage2D(n.TEXTURE_CUBE_MAP,Fe,ht,re.width,re.height)}for(let re=0;re<6;re++)if(de){N?be&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+re,0,0,0,Pe[re].width,Pe[re].height,Ve,Ce,Pe[re].data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+re,0,ht,Pe[re].width,Pe[re].height,0,Ve,Ce,Pe[re].data);for(let ze=0;ze>ee),Je=Math.max(1,A.height>>ee);le===n.TEXTURE_3D||le===n.TEXTURE_2D_ARRAY?t.texImage3D(le,ee,Ue,Pe,Je,A.depth,0,He,ye,null):t.texImage2D(le,ee,Ue,Pe,Je,0,He,ye,null)}t.bindFramebuffer(n.FRAMEBUFFER,I),ce(A)?o.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,J,le,de.__webglTexture,0,_e(A)):(le===n.TEXTURE_2D||le>=n.TEXTURE_CUBE_MAP_POSITIVE_X&&le<=n.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&n.framebufferTexture2D(n.FRAMEBUFFER,J,le,de.__webglTexture,ee),t.bindFramebuffer(n.FRAMEBUFFER,null)}function X(I,A,V){if(n.bindRenderbuffer(n.RENDERBUFFER,I),A.depthBuffer){const J=A.depthTexture,le=J&&J.isDepthTexture?J.type:null,ee=b(A.stencilBuffer,le),He=A.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ye=_e(A);ce(A)?o.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,ye,ee,A.width,A.height):V?n.renderbufferStorageMultisample(n.RENDERBUFFER,ye,ee,A.width,A.height):n.renderbufferStorage(n.RENDERBUFFER,ee,A.width,A.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,He,n.RENDERBUFFER,I)}else{const J=A.textures;for(let le=0;le{delete A.__boundDepthTexture,delete A.__depthDisposeCallback,J.removeEventListener("dispose",le)};J.addEventListener("dispose",le),A.__depthDisposeCallback=le}A.__boundDepthTexture=J}if(I.depthTexture&&!A.__autoAllocateDepthBuffer){if(V)throw new Error("target.depthTexture not supported in Cube render targets");const J=I.texture.mipmaps;J&&J.length>0?ie(A.__webglFramebuffer[0],I):ie(A.__webglFramebuffer,I)}else if(V){A.__webglDepthbuffer=[];for(let J=0;J<6;J++)if(t.bindFramebuffer(n.FRAMEBUFFER,A.__webglFramebuffer[J]),A.__webglDepthbuffer[J]===void 0)A.__webglDepthbuffer[J]=n.createRenderbuffer(),X(A.__webglDepthbuffer[J],I,!1);else{const le=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ee=A.__webglDepthbuffer[J];n.bindRenderbuffer(n.RENDERBUFFER,ee),n.framebufferRenderbuffer(n.FRAMEBUFFER,le,n.RENDERBUFFER,ee)}}else{const J=I.texture.mipmaps;if(J&&J.length>0?t.bindFramebuffer(n.FRAMEBUFFER,A.__webglFramebuffer[0]):t.bindFramebuffer(n.FRAMEBUFFER,A.__webglFramebuffer),A.__webglDepthbuffer===void 0)A.__webglDepthbuffer=n.createRenderbuffer(),X(A.__webglDepthbuffer,I,!1);else{const le=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ee=A.__webglDepthbuffer;n.bindRenderbuffer(n.RENDERBUFFER,ee),n.framebufferRenderbuffer(n.FRAMEBUFFER,le,n.RENDERBUFFER,ee)}}t.bindFramebuffer(n.FRAMEBUFFER,null)}function Ae(I,A,V){const J=i.get(I);A!==void 0&&Se(J.__webglFramebuffer,I,I.texture,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,0),V!==void 0&&xe(I)}function L(I){const A=I.texture,V=i.get(I),J=i.get(A);I.addEventListener("dispose",M);const le=I.textures,ee=I.isWebGLCubeRenderTarget===!0,He=le.length>1;if(He||(J.__webglTexture===void 0&&(J.__webglTexture=n.createTexture()),J.__version=A.version,r.memory.textures++),ee){V.__webglFramebuffer=[];for(let ye=0;ye<6;ye++)if(A.mipmaps&&A.mipmaps.length>0){V.__webglFramebuffer[ye]=[];for(let Ue=0;Ue0){V.__webglFramebuffer=[];for(let ye=0;ye0&&ce(I)===!1){V.__webglMultisampledFramebuffer=n.createFramebuffer(),V.__webglColorRenderbuffer=[],t.bindFramebuffer(n.FRAMEBUFFER,V.__webglMultisampledFramebuffer);for(let ye=0;ye0)for(let Ue=0;Ue0)for(let Ue=0;Ue0){if(ce(I)===!1){const A=I.textures,V=I.width,J=I.height;let le=n.COLOR_BUFFER_BIT;const ee=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,He=i.get(I),ye=A.length>1;if(ye)for(let Be=0;Be0?t.bindFramebuffer(n.DRAW_FRAMEBUFFER,He.__webglFramebuffer[0]):t.bindFramebuffer(n.DRAW_FRAMEBUFFER,He.__webglFramebuffer);for(let Be=0;Be0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&A.__useRenderToTexture!==!1}function ge(I){const A=r.render.frame;u.get(I)!==A&&(u.set(I,A),I.update())}function $e(I,A){const V=I.colorSpace,J=I.format,le=I.type;return I.isCompressedTexture===!0||I.isVideoTexture===!0||V!==xn&&V!==Ls&&(rt.getTransfer(V)===Pt?(J!==Vn||le!==ji)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",V)),A}function it(I){return typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement?(c.width=I.naturalWidth||I.width,c.height=I.naturalHeight||I.height):typeof VideoFrame<"u"&&I instanceof VideoFrame?(c.width=I.displayWidth,c.height=I.displayHeight):(c.width=I.width,c.height=I.height),c}this.allocateTextureUnit=O,this.resetTextureUnits=k,this.setTexture2D=U,this.setTexture2DArray=F,this.setTexture3D=W,this.setTextureCube=H,this.rebindTextures=Ae,this.setupRenderTarget=L,this.updateRenderTargetMipmap=G,this.updateMultisampleRenderTarget=Q,this.setupDepthRenderbuffer=xe,this.setupFrameBufferTexture=Se,this.useMultisampledRTT=ce}function mT(n,e){function t(i,s=Ls){let a;const r=rt.getTransfer(s);if(i===ji)return n.UNSIGNED_BYTE;if(i===Th)return n.UNSIGNED_SHORT_4_4_4_4;if(i===Mh)return n.UNSIGNED_SHORT_5_5_5_1;if(i===j_)return n.UNSIGNED_INT_5_9_9_9_REV;if(i===Z_)return n.UNSIGNED_INT_10F_11F_11F_REV;if(i===q_)return n.BYTE;if(i===Y_)return n.SHORT;if(i===xo)return n.UNSIGNED_SHORT;if(i===Sh)return n.INT;if(i===zs)return n.UNSIGNED_INT;if(i===Sn)return n.FLOAT;if(i===ls)return n.HALF_FLOAT;if(i===J_)return n.ALPHA;if(i===Q_)return n.RGB;if(i===Vn)return n.RGBA;if(i===So)return n.DEPTH_COMPONENT;if(i===To)return n.DEPTH_STENCIL;if(i===Eh)return n.RED;if(i===oc)return n.RED_INTEGER;if(i===eg)return n.RG;if(i===Ch)return n.RG_INTEGER;if(i===Ah)return n.RGBA_INTEGER;if(i===Cl||i===Al||i===Rl||i===Pl)if(r===Pt)if(a=e.get("WEBGL_compressed_texture_s3tc_srgb"),a!==null){if(i===Cl)return a.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===Al)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===Rl)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===Pl)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(a=e.get("WEBGL_compressed_texture_s3tc"),a!==null){if(i===Cl)return a.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===Al)return a.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===Rl)return a.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===Pl)return a.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===Td||i===Md||i===Ed||i===Cd)if(a=e.get("WEBGL_compressed_texture_pvrtc"),a!==null){if(i===Td)return a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===Md)return a.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===Ed)return a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===Cd)return a.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===Ad||i===Rd||i===Pd)if(a=e.get("WEBGL_compressed_texture_etc"),a!==null){if(i===Ad||i===Rd)return r===Pt?a.COMPRESSED_SRGB8_ETC2:a.COMPRESSED_RGB8_ETC2;if(i===Pd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:a.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(i===Id||i===Ld||i===kd||i===Dd||i===Od||i===Fd||i===Nd||i===Ud||i===Bd||i===zd||i===Hd||i===Vd||i===Gd||i===$d)if(a=e.get("WEBGL_compressed_texture_astc"),a!==null){if(i===Id)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:a.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===Ld)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:a.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===kd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:a.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===Dd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:a.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===Od)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:a.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===Fd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:a.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===Nd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:a.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===Ud)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:a.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===Bd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:a.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===zd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:a.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===Hd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:a.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===Vd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:a.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===Gd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:a.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===$d)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:a.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===Wd||i===Xd||i===Kd)if(a=e.get("EXT_texture_compression_bptc"),a!==null){if(i===Wd)return r===Pt?a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:a.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===Xd)return a.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===Kd)return a.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===qd||i===Yd||i===jd||i===Zd)if(a=e.get("EXT_texture_compression_rgtc"),a!==null){if(i===qd)return a.COMPRESSED_RED_RGTC1_EXT;if(i===Yd)return a.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===jd)return a.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===Zd)return a.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===wo?n.UNSIGNED_INT_24_8:n[i]!==void 0?n[i]:null}return{convert:t}}const tD=` void main() { gl_Position = vec4( position, 1.0 ); -}`,WD=` +}`,nD=` uniform sampler2DArray depthColor; uniform float depthWidth; uniform float depthHeight; @@ -3829,16 +3829,16 @@ void main() { } -}`;class XD{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const i=new ng(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,i=new ti({vertexShader:$D,fragmentShader:WD,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new we(new Dn(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class KD extends gs{constructor(e,t){super();const i=this;let s=null,a=1,r=null,o="local-floor",l=1,c=null,u=null,d=null,h=null,f=null,p=null;const g=typeof XRWebGLBinding<"u",_=new XD,m={},v=t.getContextAttributes();let y=null,b=null;const T=[],x=[],M=new te;let C=null;const w=new Jt;w.viewport=new qe;const E=new Jt;E.viewport=new qe;const R=[w,E],D=new YS;let O=null,k=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Z){let se=T[Z];return se===void 0&&(se=new Gu,T[Z]=se),se.getTargetRaySpace()},this.getControllerGrip=function(Z){let se=T[Z];return se===void 0&&(se=new Gu,T[Z]=se),se.getGripSpace()},this.getHand=function(Z){let se=T[Z];return se===void 0&&(se=new Gu,T[Z]=se),se.getHandSpace()};function U(Z){const se=x.indexOf(Z.inputSource);if(se===-1)return;const Se=T[se];Se!==void 0&&(Se.update(Z.inputSource,Z.frame,c||r),Se.dispatchEvent({type:Z.type,data:Z.inputSource}))}function F(){s.removeEventListener("select",U),s.removeEventListener("selectstart",U),s.removeEventListener("selectend",U),s.removeEventListener("squeeze",U),s.removeEventListener("squeezestart",U),s.removeEventListener("squeezeend",U),s.removeEventListener("end",F),s.removeEventListener("inputsourceschange",W);for(let Z=0;Z=0&&(x[X]=null,T[X].disconnect(Se))}for(let se=0;se=x.length){x.push(Se),X=xe;break}else if(x[xe]===null){x[xe]=Se,X=xe;break}if(X===-1)break}const ie=T[X];ie&&ie.connect(Se)}}const H=new S,ne=new S;function oe(Z,se,Se){H.setFromMatrixPosition(se.matrixWorld),ne.setFromMatrixPosition(Se.matrixWorld);const X=H.distanceTo(ne),ie=se.projectionMatrix.elements,xe=Se.projectionMatrix.elements,Ae=ie[14]/(ie[10]-1),L=ie[14]/(ie[10]+1),G=(ie[9]+1)/ie[5],j=(ie[9]-1)/ie[5],Y=(ie[8]-1)/ie[0],Q=(xe[8]+1)/xe[0],_e=Ae*Y,ce=Ae*Q,ge=X/(-Y+Q),$e=ge*-Y;if(se.matrixWorld.decompose(Z.position,Z.quaternion,Z.scale),Z.translateX($e),Z.translateZ(ge),Z.matrixWorld.compose(Z.position,Z.quaternion,Z.scale),Z.matrixWorldInverse.copy(Z.matrixWorld).invert(),ie[10]===-1)Z.projectionMatrix.copy(se.projectionMatrix),Z.projectionMatrixInverse.copy(se.projectionMatrixInverse);else{const it=Ae+ge,I=L+ge,A=_e-$e,V=ce+(X-$e),J=G*L/I*it,le=j*L/I*it;Z.projectionMatrix.makePerspective(A,V,J,le,it,I),Z.projectionMatrixInverse.copy(Z.projectionMatrix).invert()}}function pe(Z,se){se===null?Z.matrixWorld.copy(Z.matrix):Z.matrixWorld.multiplyMatrices(se.matrixWorld,Z.matrix),Z.matrixWorldInverse.copy(Z.matrixWorld).invert()}this.updateCamera=function(Z){if(s===null)return;let se=Z.near,Se=Z.far;_.texture!==null&&(_.depthNear>0&&(se=_.depthNear),_.depthFar>0&&(Se=_.depthFar)),D.near=E.near=w.near=se,D.far=E.far=w.far=Se,(O!==D.near||k!==D.far)&&(s.updateRenderState({depthNear:D.near,depthFar:D.far}),O=D.near,k=D.far),D.layers.mask=Z.layers.mask|6,w.layers.mask=D.layers.mask&3,E.layers.mask=D.layers.mask&5;const X=Z.parent,ie=D.cameras;pe(D,X);for(let xe=0;xe0&&(_.alphaTest.value=m.alphaTest);const v=e.get(m),y=v.envMap,b=v.envMapRotation;y&&(_.envMap.value=y,Pa.copy(b),Pa.x*=-1,Pa.y*=-1,Pa.z*=-1,y.isCubeTexture&&y.isRenderTargetTexture===!1&&(Pa.y*=-1,Pa.z*=-1),_.envMapRotation.value.setFromMatrix4(qD.makeRotationFromEuler(Pa)),_.flipEnvMap.value=y.isCubeTexture&&y.isRenderTargetTexture===!1?-1:1,_.reflectivity.value=m.reflectivity,_.ior.value=m.ior,_.refractionRatio.value=m.refractionRatio),m.lightMap&&(_.lightMap.value=m.lightMap,_.lightMapIntensity.value=m.lightMapIntensity,t(m.lightMap,_.lightMapTransform)),m.aoMap&&(_.aoMap.value=m.aoMap,_.aoMapIntensity.value=m.aoMapIntensity,t(m.aoMap,_.aoMapTransform))}function r(_,m){_.diffuse.value.copy(m.color),_.opacity.value=m.opacity,m.map&&(_.map.value=m.map,t(m.map,_.mapTransform))}function o(_,m){_.dashSize.value=m.dashSize,_.totalSize.value=m.dashSize+m.gapSize,_.scale.value=m.scale}function l(_,m,v,y){_.diffuse.value.copy(m.color),_.opacity.value=m.opacity,_.size.value=m.size*v,_.scale.value=y*.5,m.map&&(_.map.value=m.map,t(m.map,_.uvTransform)),m.alphaMap&&(_.alphaMap.value=m.alphaMap,t(m.alphaMap,_.alphaMapTransform)),m.alphaTest>0&&(_.alphaTest.value=m.alphaTest)}function c(_,m){_.diffuse.value.copy(m.color),_.opacity.value=m.opacity,_.rotation.value=m.rotation,m.map&&(_.map.value=m.map,t(m.map,_.mapTransform)),m.alphaMap&&(_.alphaMap.value=m.alphaMap,t(m.alphaMap,_.alphaMapTransform)),m.alphaTest>0&&(_.alphaTest.value=m.alphaTest)}function u(_,m){_.specular.value.copy(m.specular),_.shininess.value=Math.max(m.shininess,1e-4)}function d(_,m){m.gradientMap&&(_.gradientMap.value=m.gradientMap)}function h(_,m){_.metalness.value=m.metalness,m.metalnessMap&&(_.metalnessMap.value=m.metalnessMap,t(m.metalnessMap,_.metalnessMapTransform)),_.roughness.value=m.roughness,m.roughnessMap&&(_.roughnessMap.value=m.roughnessMap,t(m.roughnessMap,_.roughnessMapTransform)),m.envMap&&(_.envMapIntensity.value=m.envMapIntensity)}function f(_,m,v){_.ior.value=m.ior,m.sheen>0&&(_.sheenColor.value.copy(m.sheenColor).multiplyScalar(m.sheen),_.sheenRoughness.value=m.sheenRoughness,m.sheenColorMap&&(_.sheenColorMap.value=m.sheenColorMap,t(m.sheenColorMap,_.sheenColorMapTransform)),m.sheenRoughnessMap&&(_.sheenRoughnessMap.value=m.sheenRoughnessMap,t(m.sheenRoughnessMap,_.sheenRoughnessMapTransform))),m.clearcoat>0&&(_.clearcoat.value=m.clearcoat,_.clearcoatRoughness.value=m.clearcoatRoughness,m.clearcoatMap&&(_.clearcoatMap.value=m.clearcoatMap,t(m.clearcoatMap,_.clearcoatMapTransform)),m.clearcoatRoughnessMap&&(_.clearcoatRoughnessMap.value=m.clearcoatRoughnessMap,t(m.clearcoatRoughnessMap,_.clearcoatRoughnessMapTransform)),m.clearcoatNormalMap&&(_.clearcoatNormalMap.value=m.clearcoatNormalMap,t(m.clearcoatNormalMap,_.clearcoatNormalMapTransform),_.clearcoatNormalScale.value.copy(m.clearcoatNormalScale),m.side===un&&_.clearcoatNormalScale.value.negate())),m.dispersion>0&&(_.dispersion.value=m.dispersion),m.iridescence>0&&(_.iridescence.value=m.iridescence,_.iridescenceIOR.value=m.iridescenceIOR,_.iridescenceThicknessMinimum.value=m.iridescenceThicknessRange[0],_.iridescenceThicknessMaximum.value=m.iridescenceThicknessRange[1],m.iridescenceMap&&(_.iridescenceMap.value=m.iridescenceMap,t(m.iridescenceMap,_.iridescenceMapTransform)),m.iridescenceThicknessMap&&(_.iridescenceThicknessMap.value=m.iridescenceThicknessMap,t(m.iridescenceThicknessMap,_.iridescenceThicknessMapTransform))),m.transmission>0&&(_.transmission.value=m.transmission,_.transmissionSamplerMap.value=v.texture,_.transmissionSamplerSize.value.set(v.width,v.height),m.transmissionMap&&(_.transmissionMap.value=m.transmissionMap,t(m.transmissionMap,_.transmissionMapTransform)),_.thickness.value=m.thickness,m.thicknessMap&&(_.thicknessMap.value=m.thicknessMap,t(m.thicknessMap,_.thicknessMapTransform)),_.attenuationDistance.value=m.attenuationDistance,_.attenuationColor.value.copy(m.attenuationColor)),m.anisotropy>0&&(_.anisotropyVector.value.set(m.anisotropy*Math.cos(m.anisotropyRotation),m.anisotropy*Math.sin(m.anisotropyRotation)),m.anisotropyMap&&(_.anisotropyMap.value=m.anisotropyMap,t(m.anisotropyMap,_.anisotropyMapTransform))),_.specularIntensity.value=m.specularIntensity,_.specularColor.value.copy(m.specularColor),m.specularColorMap&&(_.specularColorMap.value=m.specularColorMap,t(m.specularColorMap,_.specularColorMapTransform)),m.specularIntensityMap&&(_.specularIntensityMap.value=m.specularIntensityMap,t(m.specularIntensityMap,_.specularIntensityMapTransform))}function p(_,m){m.matcap&&(_.matcap.value=m.matcap)}function g(_,m){const v=e.get(m).light;_.referencePosition.value.setFromMatrixPosition(v.matrixWorld),_.nearDistance.value=v.shadow.camera.near,_.farDistance.value=v.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:s}}function jD(n,e,t,i){let s={},a={},r=[];const o=n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS);function l(v,y){const b=y.program;i.uniformBlockBinding(v,b)}function c(v,y){let b=s[v.id];b===void 0&&(p(v),b=u(v),s[v.id]=b,v.addEventListener("dispose",_));const T=y.program;i.updateUBOMapping(v,T);const x=e.render.frame;a[v.id]!==x&&(h(v),a[v.id]=x)}function u(v){const y=d();v.__bindingPointIndex=y;const b=n.createBuffer(),T=v.__size,x=v.usage;return n.bindBuffer(n.UNIFORM_BUFFER,b),n.bufferData(n.UNIFORM_BUFFER,T,x),n.bindBuffer(n.UNIFORM_BUFFER,null),n.bindBufferBase(n.UNIFORM_BUFFER,y,b),b}function d(){for(let v=0;v0&&(b+=T-x),v.__size=b,v.__cache={},this}function g(v){const y={boundary:0,storage:0};return typeof v=="number"||typeof v=="boolean"?(y.boundary=4,y.storage=4):v.isVector2?(y.boundary=8,y.storage=8):v.isVector3||v.isColor?(y.boundary=16,y.storage=12):v.isVector4?(y.boundary=16,y.storage=16):v.isMatrix3?(y.boundary=48,y.storage=48):v.isMatrix4?(y.boundary=64,y.storage=64):v.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",v),y}function _(v){const y=v.target;y.removeEventListener("dispose",_);const b=r.indexOf(y.__bindingPointIndex);r.splice(b,1),n.deleteBuffer(s[y.id]),delete s[y.id],delete a[y.id]}function m(){for(const v in s)n.deleteBuffer(s[v]);r=[],s={},a={}}return{bind:l,update:c,dispose:m}}class Eg{constructor(e={}){const{canvas:t=uS(),context:i=null,depth:s=!0,stencil:a=!1,alpha:r=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:d=!1,reversedDepthBuffer:h=!1}=e;this.isWebGLRenderer=!0;let f;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=i.getContextAttributes().alpha}else f=r;const p=new Uint32Array(4),g=new Int32Array(4);let _=null,m=null;const v=[],y=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Os,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const b=this;let T=!1;this._outputColorSpace=gt;let x=0,M=0,C=null,w=-1,E=null;const R=new qe,D=new qe;let O=null;const k=new ue(0);let U=0,F=t.width,W=t.height,H=1,ne=null,oe=null;const pe=new qe(0,0,F,W),Ie=new qe(0,0,F,W);let De=!1;const Xe=new Po;let ke=!1,Z=!1;const se=new Me,Se=new S,X=new qe,ie={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let xe=!1;function Ae(){return C===null?H:1}let L=i;function G(P,B){return t.getContext(P,B)}try{const P={alpha:!0,depth:s,stencil:a,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:u,failIfMajorPerformanceCaveat:d};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${ph}`),t.addEventListener("webglcontextlost",be,!1),t.addEventListener("webglcontextrestored",Fe,!1),t.addEventListener("webglcontextcreationerror",he,!1),L===null){const B="webgl2";if(L=G(B,P),L===null)throw G(B)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(P){throw console.error("THREE.WebGLRenderer: "+P.message),P}let j,Y,Q,_e,ce,ge,$e,it,I,A,V,J,le,ee,He,ye,Ue,Be,de,Pe,Je,Ve,Ce,ht;function N(){j=new l2(L),j.init(),Ve=new oT(L,j),Y=new t2(L,j,e,Ve),Q=new VD(L,j),Y.reversedDepthBuffer&&h&&Q.buffers.depth.setReversed(!0),_e=new d2(L),ce=new RD,ge=new GD(L,j,Q,ce,Y,Ve,_e),$e=new i2(b),it=new o2(b),I=new gP(L),Ce=new QL(L,I),A=new c2(L,I,_e,Ce),V=new f2(L,A,I,_e),de=new h2(L,Y,ge),ye=new n2(ce),J=new AD(b,$e,it,j,Y,Ce,ye),le=new YD(b,ce),ee=new ID,He=new ND(j),Be=new JL(b,$e,it,Q,V,f,l),Ue=new zD(b,V,Y),ht=new jD(L,_e,Y,Q),Pe=new e2(L,j,_e),Je=new u2(L,j,_e),_e.programs=J.programs,b.capabilities=Y,b.extensions=j,b.properties=ce,b.renderLists=ee,b.shadowMap=Ue,b.state=Q,b.info=_e}N();const me=new KD(b,L);this.xr=me,this.getContext=function(){return L},this.getContextAttributes=function(){return L.getContextAttributes()},this.forceContextLoss=function(){const P=j.get("WEBGL_lose_context");P&&P.loseContext()},this.forceContextRestore=function(){const P=j.get("WEBGL_lose_context");P&&P.restoreContext()},this.getPixelRatio=function(){return H},this.setPixelRatio=function(P){P!==void 0&&(H=P,this.setSize(F,W,!1))},this.getSize=function(P){return P.set(F,W)},this.setSize=function(P,B,K=!0){if(me.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}F=P,W=B,t.width=Math.floor(P*H),t.height=Math.floor(B*H),K===!0&&(t.style.width=P+"px",t.style.height=B+"px"),this.setViewport(0,0,P,B)},this.getDrawingBufferSize=function(P){return P.set(F*H,W*H).floor()},this.setDrawingBufferSize=function(P,B,K){F=P,W=B,H=K,t.width=Math.floor(P*K),t.height=Math.floor(B*K),this.setViewport(0,0,P,B)},this.getCurrentViewport=function(P){return P.copy(R)},this.getViewport=function(P){return P.copy(pe)},this.setViewport=function(P,B,K,q){P.isVector4?pe.set(P.x,P.y,P.z,P.w):pe.set(P,B,K,q),Q.viewport(R.copy(pe).multiplyScalar(H).round())},this.getScissor=function(P){return P.copy(Ie)},this.setScissor=function(P,B,K,q){P.isVector4?Ie.set(P.x,P.y,P.z,P.w):Ie.set(P,B,K,q),Q.scissor(D.copy(Ie).multiplyScalar(H).round())},this.getScissorTest=function(){return De},this.setScissorTest=function(P){Q.setScissorTest(De=P)},this.setOpaqueSort=function(P){ne=P},this.setTransparentSort=function(P){oe=P},this.getClearColor=function(P){return P.copy(Be.getClearColor())},this.setClearColor=function(){Be.setClearColor(...arguments)},this.getClearAlpha=function(){return Be.getClearAlpha()},this.setClearAlpha=function(){Be.setClearAlpha(...arguments)},this.clear=function(P=!0,B=!0,K=!0){let q=0;if(P){let z=!1;if(C!==null){const fe=C.texture.format;z=fe===wh||fe===xh||fe===ic}if(z){const fe=C.texture.type,Re=fe===Yi||fe===zs||fe===yo||fe===vo||fe===yh||fe===vh,Ne=Be.getClearColor(),Oe=Be.getClearAlpha(),je=Ne.r,et=Ne.g,We=Ne.b;Re?(p[0]=je,p[1]=et,p[2]=We,p[3]=Oe,L.clearBufferuiv(L.COLOR,0,p)):(g[0]=je,g[1]=et,g[2]=We,g[3]=Oe,L.clearBufferiv(L.COLOR,0,g))}else q|=L.COLOR_BUFFER_BIT}B&&(q|=L.DEPTH_BUFFER_BIT),K&&(q|=L.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),L.clear(q)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",be,!1),t.removeEventListener("webglcontextrestored",Fe,!1),t.removeEventListener("webglcontextcreationerror",he,!1),Be.dispose(),ee.dispose(),He.dispose(),ce.dispose(),$e.dispose(),it.dispose(),V.dispose(),Ce.dispose(),ht.dispose(),J.dispose(),me.dispose(),me.removeEventListener("sessionstart",Zi),me.removeEventListener("sessionend",ty),ma.stop()};function be(P){P.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),T=!0}function Fe(){console.log("THREE.WebGLRenderer: Context Restored."),T=!1;const P=_e.autoReset,B=Ue.enabled,K=Ue.autoUpdate,q=Ue.needsUpdate,z=Ue.type;N(),_e.autoReset=P,Ue.enabled=B,Ue.autoUpdate=K,Ue.needsUpdate=q,Ue.type=z}function he(P){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",P.statusMessage)}function re(P){const B=P.target;B.removeEventListener("dispose",re),ze(B)}function ze(P){lt(P),ce.remove(P)}function lt(P){const B=ce.get(P).programs;B!==void 0&&(B.forEach(function(K){J.releaseProgram(K)}),P.isShaderMaterial&&J.releaseShaderCache(P))}this.renderBufferDirect=function(P,B,K,q,z,fe){B===null&&(B=ie);const Re=z.isMesh&&z.matrixWorld.determinant()<0,Ne=b1(P,B,K,q,z);Q.setMaterial(q,Re);let Oe=K.index,je=1;if(q.wireframe===!0){if(Oe=A.getWireframeAttribute(K),Oe===void 0)return;je=2}const et=K.drawRange,We=K.attributes.position;let wt=et.start*je,It=(et.start+et.count)*je;fe!==null&&(wt=Math.max(wt,fe.start*je),It=Math.min(It,(fe.start+fe.count)*je)),Oe!==null?(wt=Math.max(wt,0),It=Math.min(It,Oe.count)):We!=null&&(wt=Math.max(wt,0),It=Math.min(It,We.count));const qt=It-wt;if(qt<0||qt===1/0)return;Ce.setup(z,q,Ne,K,Oe);let Ft,Dt=Pe;if(Oe!==null&&(Ft=I.get(Oe),Dt=Je,Dt.setIndex(Ft)),z.isMesh)q.wireframe===!0?(Q.setLineWidth(q.wireframeLinewidth*Ae()),Dt.setMode(L.LINES)):Dt.setMode(L.TRIANGLES);else if(z.isLine){let Ke=q.linewidth;Ke===void 0&&(Ke=1),Q.setLineWidth(Ke*Ae()),z.isLineSegments?Dt.setMode(L.LINES):z.isLineLoop?Dt.setMode(L.LINE_LOOP):Dt.setMode(L.LINE_STRIP)}else z.isPoints?Dt.setMode(L.POINTS):z.isSprite&&Dt.setMode(L.TRIANGLES);if(z.isBatchedMesh)if(z._multiDrawInstances!==null)Vl("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),Dt.renderMultiDrawInstances(z._multiDrawStarts,z._multiDrawCounts,z._multiDrawCount,z._multiDrawInstances);else if(j.get("WEBGL_multi_draw"))Dt.renderMultiDraw(z._multiDrawStarts,z._multiDrawCounts,z._multiDrawCount);else{const Ke=z._multiDrawStarts,Gt=z._multiDrawCounts,St=z._multiDrawCount,ri=Oe?I.get(Oe).bytesPerElement:1,gr=ce.get(q).currentProgram.getUniforms();for(let oi=0;oi{function fe(){if(q.forEach(function(Re){ce.get(Re).currentProgram.isReady()&&q.delete(Re)}),q.size===0){z(P);return}setTimeout(fe,10)}j.get("KHR_parallel_shader_compile")!==null?fe():setTimeout(fe,10)})};let Et=null;function ys(P){Et&&Et(P)}function Zi(){ma.stop()}function ty(){ma.start()}const ma=new nT;ma.setAnimationLoop(ys),typeof self<"u"&&ma.setContext(self),this.setAnimationLoop=function(P){Et=P,me.setAnimationLoop(P),P===null?ma.stop():ma.start()},me.addEventListener("sessionstart",Zi),me.addEventListener("sessionend",ty),this.render=function(P,B){if(B!==void 0&&B.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(T===!0)return;if(P.matrixWorldAutoUpdate===!0&&P.updateMatrixWorld(),B.parent===null&&B.matrixWorldAutoUpdate===!0&&B.updateMatrixWorld(),me.enabled===!0&&me.isPresenting===!0&&(me.cameraAutoUpdate===!0&&me.updateCamera(B),B=me.getCamera()),P.isScene===!0&&P.onBeforeRender(b,P,B,C),m=He.get(P,y.length),m.init(B),y.push(m),se.multiplyMatrices(B.projectionMatrix,B.matrixWorldInverse),Xe.setFromProjectionMatrix(se,hi,B.reversedDepth),Z=this.localClippingEnabled,ke=ye.init(this.clippingPlanes,Z),_=ee.get(P,v.length),_.init(),v.push(_),me.enabled===!0&&me.isPresenting===!0){const fe=b.xr.getDepthSensingMesh();fe!==null&&df(fe,B,-1/0,b.sortObjects)}df(P,B,0,b.sortObjects),_.finish(),b.sortObjects===!0&&_.sort(ne,oe),xe=me.enabled===!1||me.isPresenting===!1||me.hasDepthSensing()===!1,xe&&Be.addToRenderList(_,P),this.info.render.frame++,ke===!0&&ye.beginShadows();const K=m.state.shadowsArray;Ue.render(K,P,B),ke===!0&&ye.endShadows(),this.info.autoReset===!0&&this.info.reset();const q=_.opaque,z=_.transmissive;if(m.setupLights(),B.isArrayCamera){const fe=B.cameras;if(z.length>0)for(let Re=0,Ne=fe.length;Re0&&iy(q,z,P,B),xe&&Be.render(P),ny(_,P,B);C!==null&&M===0&&(ge.updateMultisampleRenderTarget(C),ge.updateRenderTargetMipmap(C)),P.isScene===!0&&P.onAfterRender(b,P,B),Ce.resetDefaultState(),w=-1,E=null,y.pop(),y.length>0?(m=y[y.length-1],ke===!0&&ye.setGlobalState(b.clippingPlanes,m.state.camera)):m=null,v.pop(),v.length>0?_=v[v.length-1]:_=null};function df(P,B,K,q){if(P.visible===!1)return;if(P.layers.test(B.layers)){if(P.isGroup)K=P.renderOrder;else if(P.isLOD)P.autoUpdate===!0&&P.update(B);else if(P.isLight)m.pushLight(P),P.castShadow&&m.pushShadow(P);else if(P.isSprite){if(!P.frustumCulled||Xe.intersectsSprite(P)){q&&X.setFromMatrixPosition(P.matrixWorld).applyMatrix4(se);const Re=V.update(P),Ne=P.material;Ne.visible&&_.push(P,Re,Ne,K,X.z,null)}}else if((P.isMesh||P.isLine||P.isPoints)&&(!P.frustumCulled||Xe.intersectsObject(P))){const Re=V.update(P),Ne=P.material;if(q&&(P.boundingSphere!==void 0?(P.boundingSphere===null&&P.computeBoundingSphere(),X.copy(P.boundingSphere.center)):(Re.boundingSphere===null&&Re.computeBoundingSphere(),X.copy(Re.boundingSphere.center)),X.applyMatrix4(P.matrixWorld).applyMatrix4(se)),Array.isArray(Ne)){const Oe=Re.groups;for(let je=0,et=Oe.length;je0&&mc(z,B,K),fe.length>0&&mc(fe,B,K),Re.length>0&&mc(Re,B,K),Q.buffers.depth.setTest(!0),Q.buffers.depth.setMask(!0),Q.buffers.color.setMask(!0),Q.setPolygonOffset(!1)}function iy(P,B,K,q){if((K.isScene===!0?K.overrideMaterial:null)!==null)return;m.state.transmissionRenderTarget[q.id]===void 0&&(m.state.transmissionRenderTarget[q.id]=new ms(1,1,{generateMipmaps:!0,type:j.has("EXT_color_buffer_half_float")||j.has("EXT_color_buffer_float")?ls:Yi,minFilter:Ti,samples:4,stencilBuffer:a,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:at.workingColorSpace}));const fe=m.state.transmissionRenderTarget[q.id],Re=q.viewport||R;fe.setSize(Re.z*b.transmissionResolutionScale,Re.w*b.transmissionResolutionScale);const Ne=b.getRenderTarget(),Oe=b.getActiveCubeFace(),je=b.getActiveMipmapLevel();b.setRenderTarget(fe),b.getClearColor(k),U=b.getClearAlpha(),U<1&&b.setClearColor(16777215,.5),b.clear(),xe&&Be.render(K);const et=b.toneMapping;b.toneMapping=Os;const We=q.viewport;if(q.viewport!==void 0&&(q.viewport=void 0),m.setupLightsView(q),ke===!0&&ye.setGlobalState(b.clippingPlanes,q),mc(P,K,q),ge.updateMultisampleRenderTarget(fe),ge.updateRenderTargetMipmap(fe),j.has("WEBGL_multisampled_render_to_texture")===!1){let wt=!1;for(let It=0,qt=B.length;It0),We=!!K.morphAttributes.position,wt=!!K.morphAttributes.normal,It=!!K.morphAttributes.color;let qt=Os;q.toneMapped&&(C===null||C.isXRRenderTarget===!0)&&(qt=b.toneMapping);const Ft=K.morphAttributes.position||K.morphAttributes.normal||K.morphAttributes.color,Dt=Ft!==void 0?Ft.length:0,Ke=ce.get(q),Gt=m.state.lights;if(ke===!0&&(Z===!0||P!==E)){const On=P===E&&q.id===w;ye.setState(q,P,On)}let St=!1;q.version===Ke.__version?(Ke.needsLights&&Ke.lightsStateVersion!==Gt.state.version||Ke.outputColorSpace!==Ne||z.isBatchedMesh&&Ke.batching===!1||!z.isBatchedMesh&&Ke.batching===!0||z.isBatchedMesh&&Ke.batchingColor===!0&&z.colorTexture===null||z.isBatchedMesh&&Ke.batchingColor===!1&&z.colorTexture!==null||z.isInstancedMesh&&Ke.instancing===!1||!z.isInstancedMesh&&Ke.instancing===!0||z.isSkinnedMesh&&Ke.skinning===!1||!z.isSkinnedMesh&&Ke.skinning===!0||z.isInstancedMesh&&Ke.instancingColor===!0&&z.instanceColor===null||z.isInstancedMesh&&Ke.instancingColor===!1&&z.instanceColor!==null||z.isInstancedMesh&&Ke.instancingMorph===!0&&z.morphTexture===null||z.isInstancedMesh&&Ke.instancingMorph===!1&&z.morphTexture!==null||Ke.envMap!==Oe||q.fog===!0&&Ke.fog!==fe||Ke.numClippingPlanes!==void 0&&(Ke.numClippingPlanes!==ye.numPlanes||Ke.numIntersection!==ye.numIntersection)||Ke.vertexAlphas!==je||Ke.vertexTangents!==et||Ke.morphTargets!==We||Ke.morphNormals!==wt||Ke.morphColors!==It||Ke.toneMapping!==qt||Ke.morphTargetsCount!==Dt)&&(St=!0):(St=!0,Ke.__version=q.version);let ri=Ke.currentProgram;St===!0&&(ri=_c(q,B,z));let gr=!1,oi=!1,No=!1;const $t=ri.getUniforms(),mi=Ke.uniforms;if(Q.useProgram(ri.program)&&(gr=!0,oi=!0,No=!0),q.id!==w&&(w=q.id,oi=!0),gr||E!==P){Q.buffers.depth.getReversed()&&P.reversedDepth!==!0&&(P._reversedDepth=!0,P.updateProjectionMatrix()),$t.setValue(L,"projectionMatrix",P.projectionMatrix),$t.setValue(L,"viewMatrix",P.matrixWorldInverse);const $n=$t.map.cameraPosition;$n!==void 0&&$n.setValue(L,Se.setFromMatrixPosition(P.matrixWorld)),Y.logarithmicDepthBuffer&&$t.setValue(L,"logDepthBufFC",2/(Math.log(P.far+1)/Math.LN2)),(q.isMeshPhongMaterial||q.isMeshToonMaterial||q.isMeshLambertMaterial||q.isMeshBasicMaterial||q.isMeshStandardMaterial||q.isShaderMaterial)&&$t.setValue(L,"isOrthographic",P.isOrthographicCamera===!0),E!==P&&(E=P,oi=!0,No=!0)}if(z.isSkinnedMesh){$t.setOptional(L,z,"bindMatrix"),$t.setOptional(L,z,"bindMatrixInverse");const On=z.skeleton;On&&(On.boneTexture===null&&On.computeBoneTexture(),$t.setValue(L,"boneTexture",On.boneTexture,ge))}z.isBatchedMesh&&($t.setOptional(L,z,"batchingTexture"),$t.setValue(L,"batchingTexture",z._matricesTexture,ge),$t.setOptional(L,z,"batchingIdTexture"),$t.setValue(L,"batchingIdTexture",z._indirectTexture,ge),$t.setOptional(L,z,"batchingColorTexture"),z._colorsTexture!==null&&$t.setValue(L,"batchingColorTexture",z._colorsTexture,ge));const _i=K.morphAttributes;if((_i.position!==void 0||_i.normal!==void 0||_i.color!==void 0)&&de.update(z,K,ri),(oi||Ke.receiveShadow!==z.receiveShadow)&&(Ke.receiveShadow=z.receiveShadow,$t.setValue(L,"receiveShadow",z.receiveShadow)),q.isMeshGouraudMaterial&&q.envMap!==null&&(mi.envMap.value=Oe,mi.flipEnvMap.value=Oe.isCubeTexture&&Oe.isRenderTargetTexture===!1?-1:1),q.isMeshStandardMaterial&&q.envMap===null&&B.environment!==null&&(mi.envMapIntensity.value=B.environmentIntensity),oi&&($t.setValue(L,"toneMappingExposure",b.toneMappingExposure),Ke.needsLights&&x1(mi,No),fe&&q.fog===!0&&le.refreshFogUniforms(mi,fe),le.refreshMaterialUniforms(mi,q,H,W,m.state.transmissionRenderTarget[P.id]),$u.upload(L,ay(Ke),mi,ge)),q.isShaderMaterial&&q.uniformsNeedUpdate===!0&&($u.upload(L,ay(Ke),mi,ge),q.uniformsNeedUpdate=!1),q.isSpriteMaterial&&$t.setValue(L,"center",z.center),$t.setValue(L,"modelViewMatrix",z.modelViewMatrix),$t.setValue(L,"normalMatrix",z.normalMatrix),$t.setValue(L,"modelMatrix",z.matrixWorld),q.isShaderMaterial||q.isRawShaderMaterial){const On=q.uniformsGroups;for(let $n=0,hf=On.length;$n0&&ge.useMultisampledRTT(P)===!1?z=ce.get(P).__webglMultisampledFramebuffer:Array.isArray(et)?z=et[K]:z=et,R.copy(P.viewport),D.copy(P.scissor),O=P.scissorTest}else R.copy(pe).multiplyScalar(H).floor(),D.copy(Ie).multiplyScalar(H).floor(),O=De;if(K!==0&&(z=S1),Q.bindFramebuffer(L.FRAMEBUFFER,z)&&q&&Q.drawBuffers(P,z),Q.viewport(R),Q.scissor(D),Q.setScissorTest(O),fe){const Oe=ce.get(P.texture);L.framebufferTexture2D(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_CUBE_MAP_POSITIVE_X+B,Oe.__webglTexture,K)}else if(Re){const Oe=B;for(let je=0;je=0&&B<=P.width-q&&K>=0&&K<=P.height-z&&(P.textures.length>1&&L.readBuffer(L.COLOR_ATTACHMENT0+Ne),L.readPixels(B,K,q,z,Ve.convert(et),Ve.convert(We),fe))}finally{const je=C!==null?ce.get(C).__webglFramebuffer:null;Q.bindFramebuffer(L.FRAMEBUFFER,je)}}},this.readRenderTargetPixelsAsync=async function(P,B,K,q,z,fe,Re,Ne=0){if(!(P&&P.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Oe=ce.get(P).__webglFramebuffer;if(P.isWebGLCubeRenderTarget&&Re!==void 0&&(Oe=Oe[Re]),Oe)if(B>=0&&B<=P.width-q&&K>=0&&K<=P.height-z){Q.bindFramebuffer(L.FRAMEBUFFER,Oe);const je=P.textures[Ne],et=je.format,We=je.type;if(!Y.textureFormatReadable(et))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Y.textureTypeReadable(We))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const wt=L.createBuffer();L.bindBuffer(L.PIXEL_PACK_BUFFER,wt),L.bufferData(L.PIXEL_PACK_BUFFER,fe.byteLength,L.STREAM_READ),P.textures.length>1&&L.readBuffer(L.COLOR_ATTACHMENT0+Ne),L.readPixels(B,K,q,z,Ve.convert(et),Ve.convert(We),0);const It=C!==null?ce.get(C).__webglFramebuffer:null;Q.bindFramebuffer(L.FRAMEBUFFER,It);const qt=L.fenceSync(L.SYNC_GPU_COMMANDS_COMPLETE,0);return L.flush(),await VC(L,qt,4),L.bindBuffer(L.PIXEL_PACK_BUFFER,wt),L.getBufferSubData(L.PIXEL_PACK_BUFFER,0,fe),L.deleteBuffer(wt),L.deleteSync(qt),fe}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(P,B=null,K=0){const q=Math.pow(2,-K),z=Math.floor(P.image.width*q),fe=Math.floor(P.image.height*q),Re=B!==null?B.x:0,Ne=B!==null?B.y:0;ge.setTexture2D(P,0),L.copyTexSubImage2D(L.TEXTURE_2D,K,0,0,Re,Ne,z,fe),Q.unbindTexture()};const T1=L.createFramebuffer(),M1=L.createFramebuffer();this.copyTextureToTexture=function(P,B,K=null,q=null,z=0,fe=null){fe===null&&(z!==0?(Vl("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),fe=z,z=0):fe=0);let Re,Ne,Oe,je,et,We,wt,It,qt;const Ft=P.isCompressedTexture?P.mipmaps[fe]:P.image;if(K!==null)Re=K.max.x-K.min.x,Ne=K.max.y-K.min.y,Oe=K.isBox3?K.max.z-K.min.z:1,je=K.min.x,et=K.min.y,We=K.isBox3?K.min.z:0;else{const _i=Math.pow(2,-z);Re=Math.floor(Ft.width*_i),Ne=Math.floor(Ft.height*_i),P.isDataArrayTexture?Oe=Ft.depth:P.isData3DTexture?Oe=Math.floor(Ft.depth*_i):Oe=1,je=0,et=0,We=0}q!==null?(wt=q.x,It=q.y,qt=q.z):(wt=0,It=0,qt=0);const Dt=Ve.convert(B.format),Ke=Ve.convert(B.type);let Gt;B.isData3DTexture?(ge.setTexture3D(B,0),Gt=L.TEXTURE_3D):B.isDataArrayTexture||B.isCompressedArrayTexture?(ge.setTexture2DArray(B,0),Gt=L.TEXTURE_2D_ARRAY):(ge.setTexture2D(B,0),Gt=L.TEXTURE_2D),L.pixelStorei(L.UNPACK_FLIP_Y_WEBGL,B.flipY),L.pixelStorei(L.UNPACK_PREMULTIPLY_ALPHA_WEBGL,B.premultiplyAlpha),L.pixelStorei(L.UNPACK_ALIGNMENT,B.unpackAlignment);const St=L.getParameter(L.UNPACK_ROW_LENGTH),ri=L.getParameter(L.UNPACK_IMAGE_HEIGHT),gr=L.getParameter(L.UNPACK_SKIP_PIXELS),oi=L.getParameter(L.UNPACK_SKIP_ROWS),No=L.getParameter(L.UNPACK_SKIP_IMAGES);L.pixelStorei(L.UNPACK_ROW_LENGTH,Ft.width),L.pixelStorei(L.UNPACK_IMAGE_HEIGHT,Ft.height),L.pixelStorei(L.UNPACK_SKIP_PIXELS,je),L.pixelStorei(L.UNPACK_SKIP_ROWS,et),L.pixelStorei(L.UNPACK_SKIP_IMAGES,We);const $t=P.isDataArrayTexture||P.isData3DTexture,mi=B.isDataArrayTexture||B.isData3DTexture;if(P.isDepthTexture){const _i=ce.get(P),On=ce.get(B),$n=ce.get(_i.__renderTarget),hf=ce.get(On.__renderTarget);Q.bindFramebuffer(L.READ_FRAMEBUFFER,$n.__webglFramebuffer),Q.bindFramebuffer(L.DRAW_FRAMEBUFFER,hf.__webglFramebuffer);for(let _a=0;_aMath.PI&&(i-=Xn),s<-Math.PI?s+=Xn:s>Math.PI&&(s-=Xn),i<=s?this._spherical.theta=Math.max(i,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(i+s)/2?Math.max(i,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let a=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const r=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),a=r!=this._spherical.radius}if(ln.setFromSpherical(this._spherical),ln.applyQuaternion(this._quatInverse),t.copy(this.target).add(ln),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let r=null;if(this.object.isPerspectiveCamera){const o=ln.length();r=this._clampDistance(o*this._scale);const l=o-r;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),a=!!l}else if(this.object.isOrthographicCamera){const o=new S(this._mouse.x,this._mouse.y,0);o.unproject(this.object);const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),a=l!==this.object.zoom;const c=new S(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(o),this.object.updateMatrixWorld(),r=ln.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;r!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(r).add(this.object.position):(lu.origin.copy(this.object.position),lu.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(lu.direction))sp||8*(1-this._lastQuaternion.dot(this.object.quaternion))>sp||this._lastTargetPosition.distanceToSquared(this.target)>sp?(this.dispatchEvent(H0),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Xn/60*this.autoRotateSpeed*e:Xn/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){ln.setFromMatrixColumn(t,0),ln.multiplyScalar(-e),this._panOffset.add(ln)}_panUp(e,t){this.screenSpacePanning===!0?ln.setFromMatrixColumn(t,1):(ln.setFromMatrixColumn(t,0),ln.crossVectors(this.object.up,ln)),ln.multiplyScalar(e),this._panOffset.add(ln)}_pan(e,t){const i=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;ln.copy(s).sub(this.target);let a=ln.length();a*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*a/i.clientHeight,this.object.matrix),this._panUp(2*t*a/i.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/i.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/i.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const i=this.domElement.getBoundingClientRect(),s=e-i.left,a=t-i.top,r=i.width,o=i.height;this._mouse.x=s/r*2-1,this._mouse.y=-(a/o)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Xn*this._rotateDelta.x/t.clientHeight),this._rotateUp(Xn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(Xn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-Xn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(Xn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-Xn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(i,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(i,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,s=e.pageY-t.y,a=Math.sqrt(i*i+s*s);this._dollyStart.set(0,a)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const i=this._getSecondPointerPosition(e),s=.5*(e.pageX+i.x),a=.5*(e.pageY+i.y);this._rotateEnd.set(s,a)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Xn*this._rotateDelta.x/t.clientHeight),this._rotateUp(Xn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(i,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,s=e.pageY-t.y,a=Math.sqrt(i*i+s*s);this._dollyEnd.set(0,a),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const r=(e.pageX+t.x)*.5,o=(e.pageY+t.y)*.5;this._updateZoomParameters(r,o)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t(O=F.indexOf(` -`))&&k=C.byteLength||!(U=d(C)))&&r(1,"no header found"),(F=U.match(w))||r(3,"bad initial token"),k.valid|=1,k.programtype=F[1],k.string+=U+` -`;U=d(C),U!==!1;){if(k.string+=U+` -`,U.charAt(0)==="#"){k.comments+=U+` -`;continue}if((F=U.match(E))&&(k.gamma=parseFloat(F[1])),(F=U.match(R))&&(k.exposure=parseFloat(F[1])),(F=U.match(D))&&(k.valid|=2,k.format=F[1]),(F=U.match(O))&&(k.valid|=4,k.height=parseInt(F[1],10),k.width=parseInt(F[2],10)),k.valid&2&&k.valid&4)break}return k.valid&2||r(3,"missing format specifier"),k.valid&4||r(3,"missing image size specifier"),k},f=function(C,w,E){const R=w;if(R<8||R>32767||C[0]!==2||C[1]!==2||C[2]&128)return new Uint8Array(C);R!==(C[2]<<8|C[3])&&r(3,"wrong scanline width");const D=new Uint8Array(4*w*E);D.length||r(4,"unable to allocate buffer space");let O=0,k=0;const U=4*R,F=new Uint8Array(4),W=new Uint8Array(U);let H=E;for(;H>0&&kC.byteLength&&r(1),F[0]=C[k++],F[1]=C[k++],F[2]=C[k++],F[3]=C[k++],(F[0]!=2||F[1]!=2||(F[2]<<8|F[3])!=R)&&r(3,"bad rgbe scanline format");let ne=0,oe;for(;ne128;if(Ie&&(oe-=128),(oe===0||ne+oe>U)&&r(3,"bad scanline data"),Ie){const De=C[k++];for(let Xe=0;Xe{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(const t of e)t.dispose()}}function Br(n){return new qh({color:0,emissive:16777215,emissiveIntensity:n})}let cT=null;function pk(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof window<"u"&&window.location?.href?window.location.href:import.meta.url}function mk(){return"./"}function _k(n){return/^[a-z][a-z\d+\-.]*:/i.test(n)||n.startsWith("//")}function gk(n=cT){const e=n==null||n===""?mk():String(n);return new URL(e,pk()).href}function wi(n,e=cT){const t=String(n);return _k(t)?t:new URL(t.replace(/^\/+/,""),gk(e)).href}class yk{constructor(e,t={}){if(this.container=typeof e=="string"?document.getElementById(e):e,this.assetBase=t.assetBase,!this.container){console.error("Invalid container passed to SceneManager");return}this.scene=new ac,this.scene.background=new ue(8900331);const i=this.container.clientWidth,s=this.container.clientHeight;this.camera=new Jt(75,i/s,10,5e4),this.camera.position.set(0,2e3,5e3),this.renderer=new Eg({antialias:!0,preserveDrawingBuffer:t.preserveDrawingBuffer===!0}),this.renderer.setSize(i,s),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=U_,this.renderer.toneMapping=z_,this.renderer.toneMappingExposure=1,this.renderer.outputColorSpace=gt,this.container.appendChild(this.renderer.domElement),window.addEventListener("resize",()=>this.onWindowResize())}initDefaultEnvironment(){if(!this._neutralEnvTexture){const e=new Jd(this.renderer);this._neutralEnvTexture=e.fromScene(new fk,.04).texture,e.dispose()}if(this.scene.environment=this._neutralEnvTexture,!this._defaultLightsAdded){const e=new Do(16777215,1.5);e.position.set(3e3,8e3,4e3),this.scene.add(e);const t=new dc(16777215,.4);this.scene.add(t),this._defaultLightsAdded=!0}}applyEnvironment(e){return new Promise(t=>{const i=new hk,s=wi(e.skyboxUrl,this.assetBase);i.load(s,a=>{this.scene.background&&this.scene.background.dispose&&this.scene.background.dispose(),a.mapping=ar,this.scene.background=a,this.scene.environment=a,this.currentEnvironmentId=e.id;const r=e.rotation??{};this._skyboxBaseRotation={x:vt.degToRad(r.x??0),y:vt.degToRad(r.y??0),z:vt.degToRad(r.z??0)},this._skyboxAnimatedY=0,this._skyboxAnimation=e.animation??null,this._applySkyboxRotation(),typeof e.exposure=="number"&&(this.renderer.toneMappingExposure=e.exposure),console.log(`[SceneManager] environment applied: ${e.id}`),t(!0)},void 0,a=>{console.error(`[SceneManager] Failed to load environment "${e.id}":`,a),t(!1)})})}_applySkyboxRotation(){const e=this._skyboxBaseRotation;if(!e)return;const t=e.y+(this._skyboxAnimatedY??0);this.scene.backgroundRotation&&this.scene.backgroundRotation.set(e.x,t,e.z),this.scene.environmentRotation&&this.scene.environmentRotation.set(e.x,t,e.z)}updateSkyboxAnimation(e){const t=this._skyboxAnimation;!t||!t.enabled||!e||(this._skyboxAnimatedY=(this._skyboxAnimatedY??0)+vt.degToRad(t.speed*e),this._applySkyboxRotation())}setDefaultBackground(){this.scene.background&&this.scene.background.dispose&&this.scene.background.dispose(),this.scene.background=new ue(1710638),this.initDefaultEnvironment(),this.renderer.toneMappingExposure=1,this._skyboxAnimation=null,this._skyboxBaseRotation=null,this.currentEnvironmentId=null,console.log("[SceneManager] Using neutral default environment (no skybox)")}setExposure(e){this.renderer&&(this.renderer.toneMappingExposure=e)}onWindowResize(){if(!this.container||!this.renderer)return;const e=this.container.clientWidth,t=this.container.clientHeight;this.camera.aspect=e/t,this.camera.updateProjectionMatrix(),this.renderer.setSize(e,t)}render(){this.renderer&&this.renderer.render(this.scene,this.camera)}dispose(){this.renderer&&(this.renderer.dispose(),this.renderer.domElement&&this.renderer.domElement.parentNode&&this.renderer.domElement.parentNode.removeChild(this.renderer.domElement),this.renderer=null)}}function G0(n,e){if(e===Jw)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),n;if(e===Kd||e===Y_){let t=n.getIndex();if(t===null){const r=[],o=n.getAttribute("position");if(o!==void 0){for(let l=0;l=2.0 are supported."));return}const c=new Zk(a,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let u=0;u=0&&o[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}c.setExtensions(r),c.setPlugins(o),c.parse(i,s)}parseAsync(e,t){const i=this;return new Promise(function(s,a){i.parse(e,t,s,a)})}}function vk(){let n={};return{get:function(e){return n[e]},add:function(e,t){n[e]=t},remove:function(e){delete n[e]},removeAll:function(){n={}}}}const xt={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class bk{constructor(e){this.parser=e,this.name=xt.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let i=0,s=t.length;i=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,a.source,r)}}class kk{constructor(e){this.parser=e,this.name=xt.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,i=this.parser,s=i.json,a=s.textures[e];if(!a.extensions||!a.extensions[t])return null;const r=a.extensions[t],o=s.images[r.source];let l=i.textureLoader;if(o.uri){const c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,r.source,l)}}class Ok{constructor(e){this.parser=e,this.name=xt.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,i=this.parser,s=i.json,a=s.textures[e];if(!a.extensions||!a.extensions[t])return null;const r=a.extensions[t],o=s.images[r.source];let l=i.textureLoader;if(o.uri){const c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,r.source,l)}}class Fk{constructor(e){this.name=xt.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,i=t.bufferViews[e];if(i.extensions&&i.extensions[this.name]){const s=i.extensions[this.name],a=this.parser.getDependency("buffer",s.buffer),r=this.parser.options.meshoptDecoder;if(!r||!r.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return a.then(function(o){const l=s.byteOffset||0,c=s.byteLength||0,u=s.count,d=s.byteStride,h=new Uint8Array(o,l,c);return r.decodeGltfBufferAsync?r.decodeGltfBufferAsync(u,d,h,s.mode,s.filter).then(function(f){return f.buffer}):r.ready.then(function(){const f=new ArrayBuffer(u*d);return r.decodeGltfBuffer(new Uint8Array(f),u,d,h,s.mode,s.filter),f})})}else return null}}class Nk{constructor(e){this.name=xt.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,i=t.nodes[e];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;const s=t.meshes[i.mesh];for(const c of s.primitives)if(c.mode!==xi.TRIANGLES&&c.mode!==xi.TRIANGLE_STRIP&&c.mode!==xi.TRIANGLE_FAN&&c.mode!==void 0)return null;const r=i.extensions[this.name].attributes,o=[],l={};for(const c in r)o.push(this.parser.getDependency("accessor",r[c]).then(u=>(l[c]=u,l[c])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(c=>{const u=c.pop(),d=u.isGroup?u.children:[u],h=c[0].count,f=[];for(const p of d){const g=new Me,_=new S,m=new dt,v=new S(1,1,1),y=new kh(p.geometry,p.material,h);for(let b=0;b0||n.search(/^data\:image\/jpeg/)===0?"image/jpeg":n.search(/\.webp($|\?)/i)>0||n.search(/^data\:image\/webp/)===0?"image/webp":n.search(/\.ktx2($|\?)/i)>0||n.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const jk=new Me;class Zk{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new vk,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let i=!1,s=-1,a=!1,r=-1;if(typeof navigator<"u"){const o=navigator.userAgent;i=/^((?!chrome|android).)*safari/i.test(o)===!0;const l=o.match(/Version\/(\d+)/);s=i&&l?parseInt(l[1],10):-1,a=o.indexOf("Firefox")>-1,r=a?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||i&&s<17||a&&r<98?this.textureLoader=new Yh(this.options.manager):this.textureLoader=new qS(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Gn(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const i=this,s=this.json,a=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(r){return r._markDefs&&r._markDefs()}),Promise.all(this._invokeAll(function(r){return r.beforeRoot&&r.beforeRoot()})).then(function(){return Promise.all([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])}).then(function(r){const o={scene:r[0][s.scene||0],scenes:r[0],animations:r[1],cameras:r[2],asset:s.asset,parser:i,userData:{}};return Ia(a,o,s),rs(o,s),Promise.all(i._invokeAll(function(l){return l.afterRoot&&l.afterRoot(o)})).then(function(){for(const l of o.scenes)l.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let s=0,a=t.length;s{const l=this.associations.get(r);l!=null&&this.associations.set(o,l);for(const[c,u]of r.children.entries())a(u,o.children[c])};return a(i,s),s.name+="_instance_"+e.uses[t]++,s}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let i=0;i=2&&_.setY(w,x[M*l+1]),l>=3&&_.setZ(w,x[M*l+2]),l>=4&&_.setW(w,x[M*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}_.normalized=p}return _})}loadTexture(e){const t=this.json,i=this.options,a=t.textures[e].source,r=t.images[a];let o=this.textureLoader;if(r.uri){const l=i.manager.getHandler(r.uri);l!==null&&(o=l)}return this.loadTextureImage(e,a,o)}loadTextureImage(e,t,i){const s=this,a=this.json,r=a.textures[e],o=a.images[t],l=(o.uri||o.bufferView)+":"+r.sampler;if(this.textureCache[l])return this.textureCache[l];const c=this.loadImageSource(t,i).then(function(u){u.flipY=!1,u.name=r.name||o.name||"",u.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(u.name=o.uri);const h=(a.samplers||{})[r.sampler]||{};return u.magFilter=W0[h.magFilter]||Vt,u.minFilter=W0[h.minFilter]||Ti,u.wrapS=X0[h.wrapS]||ps,u.wrapT=X0[h.wrapT]||ps,u.generateMipmaps=!u.isCompressedTexture&&u.minFilter!==dn&&u.minFilter!==Vt,s.associations.set(u,{textures:e}),u}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){const i=this,s=this.json,a=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(d=>d.clone());const r=s.images[e],o=self.URL||self.webkitURL;let l=r.uri||"",c=!1;if(r.bufferView!==void 0)l=i.getDependency("bufferView",r.bufferView).then(function(d){c=!0;const h=new Blob([d],{type:r.mimeType});return l=o.createObjectURL(h),l});else if(r.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const u=Promise.resolve(l).then(function(d){return new Promise(function(h,f){let p=h;t.isImageBitmapLoader===!0&&(p=function(g){const _=new Bt(g);_.needsUpdate=!0,h(_)}),t.load(Us.resolveURL(d,a.path),p,void 0,f)})}).then(function(d){return c===!0&&o.revokeObjectURL(l),rs(d,r),d.userData.mimeType=r.mimeType||Yk(r.uri),d}).catch(function(d){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),d});return this.sourceCache[e]=u,u}assignTexture(e,t,i,s){const a=this;return this.getDependency("texture",i.index).then(function(r){if(!r)return null;if(i.texCoord!==void 0&&i.texCoord>0&&(r=r.clone(),r.channel=i.texCoord),a.extensions[xt.KHR_TEXTURE_TRANSFORM]){const o=i.extensions!==void 0?i.extensions[xt.KHR_TEXTURE_TRANSFORM]:void 0;if(o){const l=a.associations.get(r);r=a.extensions[xt.KHR_TEXTURE_TRANSFORM].extendTexture(r,o),a.associations.set(r,l)}}return s!==void 0&&(r.colorSpace=s),e[t]=r,r})}assignFinalMaterial(e){const t=e.geometry;let i=e.material;const s=t.attributes.tangent===void 0,a=t.attributes.color!==void 0,r=t.attributes.normal===void 0;if(e.isPoints){const o="PointsMaterial:"+i.uuid;let l=this.cache.get(o);l||(l=new sa,Qt.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,l.sizeAttenuation=!1,this.cache.add(o,l)),i=l}else if(e.isLine){const o="LineBasicMaterial:"+i.uuid;let l=this.cache.get(o);l||(l=new Rt,Qt.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,this.cache.add(o,l)),i=l}if(s||a||r){let o="ClonedMaterial:"+i.uuid+":";s&&(o+="derivative-tangents:"),a&&(o+="vertex-colors:"),r&&(o+="flat-shading:");let l=this.cache.get(o);l||(l=i.clone(),a&&(l.vertexColors=!0),r&&(l.flatShading=!0),s&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(o,l),this.associations.set(l,this.associations.get(i))),i=l}e.material=i}getMaterialType(){return Pn}loadMaterial(e){const t=this,i=this.json,s=this.extensions,a=i.materials[e];let r;const o={},l=a.extensions||{},c=[];if(l[xt.KHR_MATERIALS_UNLIT]){const d=s[xt.KHR_MATERIALS_UNLIT];r=d.getMaterialType(),c.push(d.extendParams(o,a,t))}else{const d=a.pbrMetallicRoughness||{};if(o.color=new ue(1,1,1),o.opacity=1,Array.isArray(d.baseColorFactor)){const h=d.baseColorFactor;o.color.setRGB(h[0],h[1],h[2],xn),o.opacity=h[3]}d.baseColorTexture!==void 0&&c.push(t.assignTexture(o,"map",d.baseColorTexture,gt)),o.metalness=d.metallicFactor!==void 0?d.metallicFactor:1,o.roughness=d.roughnessFactor!==void 0?d.roughnessFactor:1,d.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,"metalnessMap",d.metallicRoughnessTexture)),c.push(t.assignTexture(o,"roughnessMap",d.metallicRoughnessTexture))),r=this._invokeOne(function(h){return h.getMaterialType&&h.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(h){return h.extendMaterialParams&&h.extendMaterialParams(e,o)})))}a.doubleSided===!0&&(o.side=ct);const u=a.alphaMode||rp.OPAQUE;if(u===rp.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,u===rp.MASK&&(o.alphaTest=a.alphaCutoff!==void 0?a.alphaCutoff:.5)),a.normalTexture!==void 0&&r!==Ye&&(c.push(t.assignTexture(o,"normalMap",a.normalTexture)),o.normalScale=new te(1,1),a.normalTexture.scale!==void 0)){const d=a.normalTexture.scale;o.normalScale.set(d,d)}if(a.occlusionTexture!==void 0&&r!==Ye&&(c.push(t.assignTexture(o,"aoMap",a.occlusionTexture)),a.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=a.occlusionTexture.strength)),a.emissiveFactor!==void 0&&r!==Ye){const d=a.emissiveFactor;o.emissive=new ue().setRGB(d[0],d[1],d[2],xn)}return a.emissiveTexture!==void 0&&r!==Ye&&c.push(t.assignTexture(o,"emissiveMap",a.emissiveTexture,gt)),Promise.all(c).then(function(){const d=new r(o);return a.name&&(d.name=a.name),rs(d,a),t.associations.set(d,{materials:e}),a.extensions&&Ia(s,d,a),d})}createUniqueName(e){const t=yt.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,i=this.extensions,s=this.primitiveCache;function a(o){return i[xt.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(l){return K0(l,o,t)})}const r=[];for(let o=0,l=e.length;o0&&Kk(m,a),m.name=t.createUniqueName(a.name||"mesh_"+e),rs(m,a),_.extensions&&Ia(s,m,_),t.assignFinalMaterial(m),d.push(m)}for(let f=0,p=d.length;f1?u=new Mt:c.length===1?u=c[0]:u=new Qe,u!==c[0])for(let d=0,h=c.length;d1){const d=s.associations.get(u);s.associations.set(u,{...d})}return s.associations.get(u).nodes=e,u}),this.nodeCache[e]}loadScene(e){const t=this.extensions,i=this.json.scenes[e],s=this,a=new Mt;i.name&&(a.name=s.createUniqueName(i.name)),rs(a,i),i.extensions&&Ia(t,a,i);const r=i.nodes||[],o=[];for(let l=0,c=r.length;l{const d=new Map;for(const[h,f]of s.associations)(h instanceof Qt||h instanceof Bt)&&d.set(h,f);return u.traverse(h=>{const f=s.associations.get(h);f!=null&&d.set(h,f)}),d};return s.associations=c(a),a})}_createAnimationTracks(e,t,i,s,a){const r=[],o=e.name?e.name:e.uuid,l=[];Ys[a.path]===Ys.weights?e.traverse(function(h){h.morphTargetInfluences&&l.push(h.name?h.name:h.uuid)}):l.push(o);let c;switch(Ys[a.path]){case Ys.weights:c=ca;break;case Ys.rotation:c=_s;break;case Ys.translation:case Ys.scale:c=Hs;break;default:i.itemSize===1?c=ca:c=Hs;break}const u=s.interpolation!==void 0?$k[s.interpolation]:rr,d=this._getArrayFromAccessor(i);for(let h=0,f=l.length;h{this.parse(r,t,s)},i,s)}parse(e,t,i=()=>{}){this.decodeDracoFile(e,t,null,null,gt,i).catch(i)}decodeDracoFile(e,t,i,s,a=xn,r=()=>{}){const o={attributeIDs:i||this.defaultAttributeIDs,attributeTypes:s||this.defaultAttributeTypes,useUniqueIDs:!!i,vertexColorSpace:a};return this.decodeGeometry(e,o).then(t).catch(r)}decodeGeometry(e,t){const i=JSON.stringify(t);if(lp.has(e)){const l=lp.get(e);if(l.key===i)return l.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let s;const a=this.workerNextTaskID++,r=e.byteLength,o=this._getWorker(a,r).then(l=>(s=l,new Promise((c,u)=>{s._callbacks[a]={resolve:c,reject:u},s.postMessage({type:"decode",id:a,taskConfig:t,buffer:e},[e])}))).then(l=>this._createGeometry(l.geometry));return o.catch(()=>!0).then(()=>{s&&a&&this._releaseTask(s,a)}),lp.set(e,{key:i,promise:o}),o}_createGeometry(e){const t=new Ge;e.index&&t.setIndex(new rt(e.index.array,1));for(let i=0;i{i.load(e,s,void 0,a)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(i=>{const s=i[0];e||(this.decoderConfig.wasmBinary=i[1]);const a=Qk.toString(),r=["/* draco decoder */",s,"","/* worker */",a.substring(a.indexOf("{")+1,a.lastIndexOf("}"))].join(` -`);this.workerSourceURL=URL.createObjectURL(new Blob([r]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.lengtha._taskLoad?-1:1});const i=this.workerPool[this.workerPool.length-1];return i._taskCosts[e]=t,i._taskLoad+=t,i})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e{const d=u.draco,h=new d.Decoder;try{const f=t(d,h,new Int8Array(l),c),p=f.attributes.map(g=>g.array.buffer);f.index&&p.push(f.index.array.buffer),self.postMessage({type:"decode",id:o.id,geometry:f},p)}catch(f){console.error(f),self.postMessage({type:"error",id:o.id,error:f.message})}finally{d.destroy(h)}});break}};function t(r,o,l,c){const u=c.attributeIDs,d=c.attributeTypes;let h,f;const p=o.GetEncodedGeometryType(l);if(p===r.TRIANGULAR_MESH)h=new r.Mesh,f=o.DecodeArrayToMesh(l,l.byteLength,h);else if(p===r.POINT_CLOUD)h=new r.PointCloud,f=o.DecodeArrayToPointCloud(l,l.byteLength,h);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!f.ok()||h.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+f.error_msg());const g={index:null,attributes:[]};for(const _ in u){const m=self[d[_]];let v,y;if(c.useUniqueIDs)y=u[_],v=o.GetAttributeByUniqueId(h,y);else{if(y=o.GetAttributeId(h,r[u[_]]),y===-1)continue;v=o.GetAttribute(h,y)}const b=s(r,o,h,_,m,v);_==="color"&&(b.vertexColorSpace=c.vertexColorSpace),g.attributes.push(b)}return p===r.TRIANGULAR_MESH&&(g.index=i(r,o,h)),r.destroy(h),g}function i(r,o,l){const u=l.num_faces()*3,d=u*4,h=r._malloc(d);o.GetTrianglesUInt32Array(l,d,h);const f=new Uint32Array(r.HEAPF32.buffer,h,u).slice();return r._free(h),{array:f,itemSize:1}}function s(r,o,l,c,u,d){const h=d.num_components(),p=l.num_points()*h,g=p*u.BYTES_PER_ELEMENT,_=a(r,u),m=r._malloc(g);o.GetAttributeDataArrayForAllPoints(l,d,_,g,m);const v=new u(r.HEAPF32.buffer,m,p).slice();return r._free(m),{name:c,array:v,itemSize:h}}function a(r,o){switch(o){case Float32Array:return r.DT_FLOAT32;case Int8Array:return r.DT_INT8;case Int16Array:return r.DT_INT16;case Int32Array:return r.DT_INT32;case Uint8Array:return r.DT_UINT8;case Uint16Array:return r.DT_UINT16;case Uint32Array:return r.DT_UINT32}}}const eO=/^[og]\s*(.+)?/,tO=/^mtllib /,nO=/^usemtl /,iO=/^usemap /,q0=/\s+/,Y0=new S,cp=new S,j0=new S,Z0=new S,yi=new S,cu=new ue;function sO(){const n={objects:[],object:{},vertices:[],normals:[],colors:[],uvs:[],materials:{},materialLibraries:[],startObject:function(e,t){if(this.object&&this.object.fromDeclaration===!1){this.object.name=e,this.object.fromDeclaration=t!==!1;return}const i=this.object&&typeof this.object.currentMaterial=="function"?this.object.currentMaterial():void 0;if(this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0),this.object={name:e||"",fromDeclaration:t!==!1,geometry:{vertices:[],normals:[],colors:[],uvs:[],hasUVIndices:!1},materials:[],smooth:!0,startMaterial:function(s,a){const r=this._finalize(!1);r&&(r.inherited||r.groupCount<=0)&&this.materials.splice(r.index,1);const o={index:this.materials.length,name:s||"",mtllib:Array.isArray(a)&&a.length>0?a[a.length-1]:"",smooth:r!==void 0?r.smooth:this.smooth,groupStart:r!==void 0?r.groupEnd:0,groupEnd:-1,groupCount:-1,inherited:!1,clone:function(l){const c={index:typeof l=="number"?l:this.index,name:this.name,mtllib:this.mtllib,smooth:this.smooth,groupStart:0,groupEnd:-1,groupCount:-1,inherited:!1};return c.clone=this.clone.bind(c),c}};return this.materials.push(o),o},currentMaterial:function(){if(this.materials.length>0)return this.materials[this.materials.length-1]},_finalize:function(s){const a=this.currentMaterial();if(a&&a.groupEnd===-1&&(a.groupEnd=this.geometry.vertices.length/3,a.groupCount=a.groupEnd-a.groupStart,a.inherited=!1),s&&this.materials.length>1)for(let r=this.materials.length-1;r>=0;r--)this.materials[r].groupCount<=0&&this.materials.splice(r,1);return s&&this.materials.length===0&&this.materials.push({name:"",smooth:this.smooth}),a}},i&&i.name&&typeof i.clone=="function"){const s=i.clone(0);s.inherited=!0,this.object.materials.push(s)}this.objects.push(this.object)},finalize:function(){this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0)},parseVertexIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseNormalIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseUVIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/2)*2},addVertex:function(e,t,i){const s=this.vertices,a=this.object.geometry.vertices;a.push(s[e+0],s[e+1],s[e+2]),a.push(s[t+0],s[t+1],s[t+2]),a.push(s[i+0],s[i+1],s[i+2])},addVertexPoint:function(e){const t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addVertexLine:function(e){const t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addNormal:function(e,t,i){const s=this.normals,a=this.object.geometry.normals;a.push(s[e+0],s[e+1],s[e+2]),a.push(s[t+0],s[t+1],s[t+2]),a.push(s[i+0],s[i+1],s[i+2])},addFaceNormal:function(e,t,i){const s=this.vertices,a=this.object.geometry.normals;Y0.fromArray(s,e),cp.fromArray(s,t),j0.fromArray(s,i),yi.subVectors(j0,cp),Z0.subVectors(Y0,cp),yi.cross(Z0),yi.normalize(),a.push(yi.x,yi.y,yi.z),a.push(yi.x,yi.y,yi.z),a.push(yi.x,yi.y,yi.z)},addColor:function(e,t,i){const s=this.colors,a=this.object.geometry.colors;s[e]!==void 0&&a.push(s[e+0],s[e+1],s[e+2]),s[t]!==void 0&&a.push(s[t+0],s[t+1],s[t+2]),s[i]!==void 0&&a.push(s[i+0],s[i+1],s[i+2])},addUV:function(e,t,i){const s=this.uvs,a=this.object.geometry.uvs;a.push(s[e+0],s[e+1]),a.push(s[t+0],s[t+1]),a.push(s[i+0],s[i+1])},addDefaultUV:function(){const e=this.object.geometry.uvs;e.push(0,0),e.push(0,0),e.push(0,0)},addUVLine:function(e){const t=this.uvs;this.object.geometry.uvs.push(t[e+0],t[e+1])},addFace:function(e,t,i,s,a,r,o,l,c){const u=this.vertices.length;let d=this.parseVertexIndex(e,u),h=this.parseVertexIndex(t,u),f=this.parseVertexIndex(i,u);if(this.addVertex(d,h,f),this.addColor(d,h,f),o!==void 0&&o!==""){const p=this.normals.length;d=this.parseNormalIndex(o,p),h=this.parseNormalIndex(l,p),f=this.parseNormalIndex(c,p),this.addNormal(d,h,f)}else this.addFaceNormal(d,h,f);if(s!==void 0&&s!==""){const p=this.uvs.length;d=this.parseUVIndex(s,p),h=this.parseUVIndex(a,p),f=this.parseUVIndex(r,p),this.addUV(d,h,f),this.object.geometry.hasUVIndices=!0}else this.addDefaultUV()},addPointGeometry:function(e){this.object.geometry.type="Points";const t=this.vertices.length;for(let i=0,s=e.length;i=0&&(x[X]=null,T[X].disconnect(Se))}for(let ae=0;ae=x.length){x.push(Se),X=xe;break}else if(x[xe]===null){x[xe]=Se,X=xe;break}if(X===-1)break}const ie=T[X];ie&&ie.connect(Se)}}const H=new S,ne=new S;function oe(Z,ae,Se){H.setFromMatrixPosition(ae.matrixWorld),ne.setFromMatrixPosition(Se.matrixWorld);const X=H.distanceTo(ne),ie=ae.projectionMatrix.elements,xe=Se.projectionMatrix.elements,Ae=ie[14]/(ie[10]-1),L=ie[14]/(ie[10]+1),G=(ie[9]+1)/ie[5],j=(ie[9]-1)/ie[5],Y=(ie[8]-1)/ie[0],Q=(xe[8]+1)/xe[0],_e=Ae*Y,ce=Ae*Q,ge=X/(-Y+Q),$e=ge*-Y;if(ae.matrixWorld.decompose(Z.position,Z.quaternion,Z.scale),Z.translateX($e),Z.translateZ(ge),Z.matrixWorld.compose(Z.position,Z.quaternion,Z.scale),Z.matrixWorldInverse.copy(Z.matrixWorld).invert(),ie[10]===-1)Z.projectionMatrix.copy(ae.projectionMatrix),Z.projectionMatrixInverse.copy(ae.projectionMatrixInverse);else{const it=Ae+ge,I=L+ge,A=_e-$e,V=ce+(X-$e),J=G*L/I*it,le=j*L/I*it;Z.projectionMatrix.makePerspective(A,V,J,le,it,I),Z.projectionMatrixInverse.copy(Z.projectionMatrix).invert()}}function pe(Z,ae){ae===null?Z.matrixWorld.copy(Z.matrix):Z.matrixWorld.multiplyMatrices(ae.matrixWorld,Z.matrix),Z.matrixWorldInverse.copy(Z.matrixWorld).invert()}this.updateCamera=function(Z){if(s===null)return;let ae=Z.near,Se=Z.far;_.texture!==null&&(_.depthNear>0&&(ae=_.depthNear),_.depthFar>0&&(Se=_.depthFar)),k.near=E.near=w.near=ae,k.far=E.far=w.far=Se,(O!==k.near||D!==k.far)&&(s.updateRenderState({depthNear:k.near,depthFar:k.far}),O=k.near,D=k.far),k.layers.mask=Z.layers.mask|6,w.layers.mask=k.layers.mask&3,E.layers.mask=k.layers.mask&5;const X=Z.parent,ie=k.cameras;pe(k,X);for(let xe=0;xe0&&(_.alphaTest.value=m.alphaTest);const v=e.get(m),y=v.envMap,b=v.envMapRotation;y&&(_.envMap.value=y,Ia.copy(b),Ia.x*=-1,Ia.y*=-1,Ia.z*=-1,y.isCubeTexture&&y.isRenderTargetTexture===!1&&(Ia.y*=-1,Ia.z*=-1),_.envMapRotation.value.setFromMatrix4(aD.makeRotationFromEuler(Ia)),_.flipEnvMap.value=y.isCubeTexture&&y.isRenderTargetTexture===!1?-1:1,_.reflectivity.value=m.reflectivity,_.ior.value=m.ior,_.refractionRatio.value=m.refractionRatio),m.lightMap&&(_.lightMap.value=m.lightMap,_.lightMapIntensity.value=m.lightMapIntensity,t(m.lightMap,_.lightMapTransform)),m.aoMap&&(_.aoMap.value=m.aoMap,_.aoMapIntensity.value=m.aoMapIntensity,t(m.aoMap,_.aoMapTransform))}function r(_,m){_.diffuse.value.copy(m.color),_.opacity.value=m.opacity,m.map&&(_.map.value=m.map,t(m.map,_.mapTransform))}function o(_,m){_.dashSize.value=m.dashSize,_.totalSize.value=m.dashSize+m.gapSize,_.scale.value=m.scale}function l(_,m,v,y){_.diffuse.value.copy(m.color),_.opacity.value=m.opacity,_.size.value=m.size*v,_.scale.value=y*.5,m.map&&(_.map.value=m.map,t(m.map,_.uvTransform)),m.alphaMap&&(_.alphaMap.value=m.alphaMap,t(m.alphaMap,_.alphaMapTransform)),m.alphaTest>0&&(_.alphaTest.value=m.alphaTest)}function c(_,m){_.diffuse.value.copy(m.color),_.opacity.value=m.opacity,_.rotation.value=m.rotation,m.map&&(_.map.value=m.map,t(m.map,_.mapTransform)),m.alphaMap&&(_.alphaMap.value=m.alphaMap,t(m.alphaMap,_.alphaMapTransform)),m.alphaTest>0&&(_.alphaTest.value=m.alphaTest)}function u(_,m){_.specular.value.copy(m.specular),_.shininess.value=Math.max(m.shininess,1e-4)}function d(_,m){m.gradientMap&&(_.gradientMap.value=m.gradientMap)}function h(_,m){_.metalness.value=m.metalness,m.metalnessMap&&(_.metalnessMap.value=m.metalnessMap,t(m.metalnessMap,_.metalnessMapTransform)),_.roughness.value=m.roughness,m.roughnessMap&&(_.roughnessMap.value=m.roughnessMap,t(m.roughnessMap,_.roughnessMapTransform)),m.envMap&&(_.envMapIntensity.value=m.envMapIntensity)}function f(_,m,v){_.ior.value=m.ior,m.sheen>0&&(_.sheenColor.value.copy(m.sheenColor).multiplyScalar(m.sheen),_.sheenRoughness.value=m.sheenRoughness,m.sheenColorMap&&(_.sheenColorMap.value=m.sheenColorMap,t(m.sheenColorMap,_.sheenColorMapTransform)),m.sheenRoughnessMap&&(_.sheenRoughnessMap.value=m.sheenRoughnessMap,t(m.sheenRoughnessMap,_.sheenRoughnessMapTransform))),m.clearcoat>0&&(_.clearcoat.value=m.clearcoat,_.clearcoatRoughness.value=m.clearcoatRoughness,m.clearcoatMap&&(_.clearcoatMap.value=m.clearcoatMap,t(m.clearcoatMap,_.clearcoatMapTransform)),m.clearcoatRoughnessMap&&(_.clearcoatRoughnessMap.value=m.clearcoatRoughnessMap,t(m.clearcoatRoughnessMap,_.clearcoatRoughnessMapTransform)),m.clearcoatNormalMap&&(_.clearcoatNormalMap.value=m.clearcoatNormalMap,t(m.clearcoatNormalMap,_.clearcoatNormalMapTransform),_.clearcoatNormalScale.value.copy(m.clearcoatNormalScale),m.side===un&&_.clearcoatNormalScale.value.negate())),m.dispersion>0&&(_.dispersion.value=m.dispersion),m.iridescence>0&&(_.iridescence.value=m.iridescence,_.iridescenceIOR.value=m.iridescenceIOR,_.iridescenceThicknessMinimum.value=m.iridescenceThicknessRange[0],_.iridescenceThicknessMaximum.value=m.iridescenceThicknessRange[1],m.iridescenceMap&&(_.iridescenceMap.value=m.iridescenceMap,t(m.iridescenceMap,_.iridescenceMapTransform)),m.iridescenceThicknessMap&&(_.iridescenceThicknessMap.value=m.iridescenceThicknessMap,t(m.iridescenceThicknessMap,_.iridescenceThicknessMapTransform))),m.transmission>0&&(_.transmission.value=m.transmission,_.transmissionSamplerMap.value=v.texture,_.transmissionSamplerSize.value.set(v.width,v.height),m.transmissionMap&&(_.transmissionMap.value=m.transmissionMap,t(m.transmissionMap,_.transmissionMapTransform)),_.thickness.value=m.thickness,m.thicknessMap&&(_.thicknessMap.value=m.thicknessMap,t(m.thicknessMap,_.thicknessMapTransform)),_.attenuationDistance.value=m.attenuationDistance,_.attenuationColor.value.copy(m.attenuationColor)),m.anisotropy>0&&(_.anisotropyVector.value.set(m.anisotropy*Math.cos(m.anisotropyRotation),m.anisotropy*Math.sin(m.anisotropyRotation)),m.anisotropyMap&&(_.anisotropyMap.value=m.anisotropyMap,t(m.anisotropyMap,_.anisotropyMapTransform))),_.specularIntensity.value=m.specularIntensity,_.specularColor.value.copy(m.specularColor),m.specularColorMap&&(_.specularColorMap.value=m.specularColorMap,t(m.specularColorMap,_.specularColorMapTransform)),m.specularIntensityMap&&(_.specularIntensityMap.value=m.specularIntensityMap,t(m.specularIntensityMap,_.specularIntensityMapTransform))}function p(_,m){m.matcap&&(_.matcap.value=m.matcap)}function g(_,m){const v=e.get(m).light;_.referencePosition.value.setFromMatrixPosition(v.matrixWorld),_.nearDistance.value=v.shadow.camera.near,_.farDistance.value=v.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:s}}function oD(n,e,t,i){let s={},a={},r=[];const o=n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS);function l(v,y){const b=y.program;i.uniformBlockBinding(v,b)}function c(v,y){let b=s[v.id];b===void 0&&(p(v),b=u(v),s[v.id]=b,v.addEventListener("dispose",_));const T=y.program;i.updateUBOMapping(v,T);const x=e.render.frame;a[v.id]!==x&&(h(v),a[v.id]=x)}function u(v){const y=d();v.__bindingPointIndex=y;const b=n.createBuffer(),T=v.__size,x=v.usage;return n.bindBuffer(n.UNIFORM_BUFFER,b),n.bufferData(n.UNIFORM_BUFFER,T,x),n.bindBuffer(n.UNIFORM_BUFFER,null),n.bindBufferBase(n.UNIFORM_BUFFER,y,b),b}function d(){for(let v=0;v0&&(b+=T-x),v.__size=b,v.__cache={},this}function g(v){const y={boundary:0,storage:0};return typeof v=="number"||typeof v=="boolean"?(y.boundary=4,y.storage=4):v.isVector2?(y.boundary=8,y.storage=8):v.isVector3||v.isColor?(y.boundary=16,y.storage=12):v.isVector4?(y.boundary=16,y.storage=16):v.isMatrix3?(y.boundary=48,y.storage=48):v.isMatrix4?(y.boundary=64,y.storage=64):v.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",v),y}function _(v){const y=v.target;y.removeEventListener("dispose",_);const b=r.indexOf(y.__bindingPointIndex);r.splice(b,1),n.deleteBuffer(s[y.id]),delete s[y.id],delete a[y.id]}function m(){for(const v in s)n.deleteBuffer(s[v]);r=[],s={},a={}}return{bind:l,update:c,dispose:m}}class kg{constructor(e={}){const{canvas:t=yS(),context:i=null,depth:s=!0,stencil:a=!1,alpha:r=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:d=!1,reversedDepthBuffer:h=!1}=e;this.isWebGLRenderer=!0;let f;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=i.getContextAttributes().alpha}else f=r;const p=new Uint32Array(4),g=new Int32Array(4);let _=null,m=null;const v=[],y=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Os,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const b=this;let T=!1;this._outputColorSpace=gt;let x=0,M=0,C=null,w=-1,E=null;const R=new qe,k=new qe;let O=null;const D=new ue(0);let U=0,F=t.width,W=t.height,H=1,ne=null,oe=null;const pe=new qe(0,0,F,W),Ie=new qe(0,0,F,W);let ke=!1;const Xe=new ko;let De=!1,Z=!1;const ae=new Me,Se=new S,X=new qe,ie={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let xe=!1;function Ae(){return C===null?H:1}let L=i;function G(P,B){return t.getContext(P,B)}try{const P={alpha:!0,depth:s,stencil:a,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:u,failIfMajorPerformanceCaveat:d};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${bh}`),t.addEventListener("webglcontextlost",be,!1),t.addEventListener("webglcontextrestored",Fe,!1),t.addEventListener("webglcontextcreationerror",he,!1),L===null){const B="webgl2";if(L=G(B,P),L===null)throw G(B)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(P){throw console.error("THREE.WebGLRenderer: "+P.message),P}let j,Y,Q,_e,ce,ge,$e,it,I,A,V,J,le,ee,He,ye,Ue,Be,de,Pe,Je,Ve,Ce,ht;function N(){j=new v2(L),j.init(),Ve=new mT(L,j),Y=new h2(L,j,e,Ve),Q=new Qk(L,j),Y.reversedDepthBuffer&&h&&Q.buffers.depth.setReversed(!0),_e=new w2(L),ce=new zk,ge=new eD(L,j,Q,ce,Y,Ve,_e),$e=new p2(b),it=new y2(b),I=new AP(L),Ce=new u2(L,I),A=new b2(L,I,_e,Ce),V=new T2(L,A,I,_e),de=new S2(L,Y,ge),ye=new f2(ce),J=new Bk(b,$e,it,j,Y,Ce,ye),le=new rD(b,ce),ee=new Vk,He=new qk(j),Be=new c2(b,$e,it,Q,V,f,l),Ue=new Zk(b,V,Y),ht=new oD(L,_e,Y,Q),Pe=new d2(L,j,_e),Je=new x2(L,j,_e),_e.programs=J.programs,b.capabilities=Y,b.extensions=j,b.properties=ce,b.renderLists=ee,b.shadowMap=Ue,b.state=Q,b.info=_e}N();const me=new sD(b,L);this.xr=me,this.getContext=function(){return L},this.getContextAttributes=function(){return L.getContextAttributes()},this.forceContextLoss=function(){const P=j.get("WEBGL_lose_context");P&&P.loseContext()},this.forceContextRestore=function(){const P=j.get("WEBGL_lose_context");P&&P.restoreContext()},this.getPixelRatio=function(){return H},this.setPixelRatio=function(P){P!==void 0&&(H=P,this.setSize(F,W,!1))},this.getSize=function(P){return P.set(F,W)},this.setSize=function(P,B,K=!0){if(me.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}F=P,W=B,t.width=Math.floor(P*H),t.height=Math.floor(B*H),K===!0&&(t.style.width=P+"px",t.style.height=B+"px"),this.setViewport(0,0,P,B)},this.getDrawingBufferSize=function(P){return P.set(F*H,W*H).floor()},this.setDrawingBufferSize=function(P,B,K){F=P,W=B,H=K,t.width=Math.floor(P*K),t.height=Math.floor(B*K),this.setViewport(0,0,P,B)},this.getCurrentViewport=function(P){return P.copy(R)},this.getViewport=function(P){return P.copy(pe)},this.setViewport=function(P,B,K,q){P.isVector4?pe.set(P.x,P.y,P.z,P.w):pe.set(P,B,K,q),Q.viewport(R.copy(pe).multiplyScalar(H).round())},this.getScissor=function(P){return P.copy(Ie)},this.setScissor=function(P,B,K,q){P.isVector4?Ie.set(P.x,P.y,P.z,P.w):Ie.set(P,B,K,q),Q.scissor(k.copy(Ie).multiplyScalar(H).round())},this.getScissorTest=function(){return ke},this.setScissorTest=function(P){Q.setScissorTest(ke=P)},this.setOpaqueSort=function(P){ne=P},this.setTransparentSort=function(P){oe=P},this.getClearColor=function(P){return P.copy(Be.getClearColor())},this.setClearColor=function(){Be.setClearColor(...arguments)},this.getClearAlpha=function(){return Be.getClearAlpha()},this.setClearAlpha=function(){Be.setClearAlpha(...arguments)},this.clear=function(P=!0,B=!0,K=!0){let q=0;if(P){let z=!1;if(C!==null){const fe=C.texture.format;z=fe===Ah||fe===Ch||fe===oc}if(z){const fe=C.texture.type,Re=fe===ji||fe===zs||fe===xo||fe===wo||fe===Th||fe===Mh,Ne=Be.getClearColor(),Oe=Be.getClearAlpha(),je=Ne.r,et=Ne.g,We=Ne.b;Re?(p[0]=je,p[1]=et,p[2]=We,p[3]=Oe,L.clearBufferuiv(L.COLOR,0,p)):(g[0]=je,g[1]=et,g[2]=We,g[3]=Oe,L.clearBufferiv(L.COLOR,0,g))}else q|=L.COLOR_BUFFER_BIT}B&&(q|=L.DEPTH_BUFFER_BIT),K&&(q|=L.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),L.clear(q)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",be,!1),t.removeEventListener("webglcontextrestored",Fe,!1),t.removeEventListener("webglcontextcreationerror",he,!1),Be.dispose(),ee.dispose(),He.dispose(),ce.dispose(),$e.dispose(),it.dispose(),V.dispose(),Ce.dispose(),ht.dispose(),J.dispose(),me.dispose(),me.removeEventListener("sessionstart",Ji),me.removeEventListener("sessionend",ly),_a.stop()};function be(P){P.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),T=!0}function Fe(){console.log("THREE.WebGLRenderer: Context Restored."),T=!1;const P=_e.autoReset,B=Ue.enabled,K=Ue.autoUpdate,q=Ue.needsUpdate,z=Ue.type;N(),_e.autoReset=P,Ue.enabled=B,Ue.autoUpdate=K,Ue.needsUpdate=q,Ue.type=z}function he(P){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",P.statusMessage)}function re(P){const B=P.target;B.removeEventListener("dispose",re),ze(B)}function ze(P){lt(P),ce.remove(P)}function lt(P){const B=ce.get(P).programs;B!==void 0&&(B.forEach(function(K){J.releaseProgram(K)}),P.isShaderMaterial&&J.releaseShaderCache(P))}this.renderBufferDirect=function(P,B,K,q,z,fe){B===null&&(B=ie);const Re=z.isMesh&&z.matrixWorld.determinant()<0,Ne=P1(P,B,K,q,z);Q.setMaterial(q,Re);let Oe=K.index,je=1;if(q.wireframe===!0){if(Oe=A.getWireframeAttribute(K),Oe===void 0)return;je=2}const et=K.drawRange,We=K.attributes.position;let wt=et.start*je,It=(et.start+et.count)*je;fe!==null&&(wt=Math.max(wt,fe.start*je),It=Math.min(It,(fe.start+fe.count)*je)),Oe!==null?(wt=Math.max(wt,0),It=Math.min(It,Oe.count)):We!=null&&(wt=Math.max(wt,0),It=Math.min(It,We.count));const qt=It-wt;if(qt<0||qt===1/0)return;Ce.setup(z,q,Ne,K,Oe);let Ft,kt=Pe;if(Oe!==null&&(Ft=I.get(Oe),kt=Je,kt.setIndex(Ft)),z.isMesh)q.wireframe===!0?(Q.setLineWidth(q.wireframeLinewidth*Ae()),kt.setMode(L.LINES)):kt.setMode(L.TRIANGLES);else if(z.isLine){let Ke=q.linewidth;Ke===void 0&&(Ke=1),Q.setLineWidth(Ke*Ae()),z.isLineSegments?kt.setMode(L.LINES):z.isLineLoop?kt.setMode(L.LINE_LOOP):kt.setMode(L.LINE_STRIP)}else z.isPoints?kt.setMode(L.POINTS):z.isSprite&&kt.setMode(L.TRIANGLES);if(z.isBatchedMesh)if(z._multiDrawInstances!==null)Xl("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),kt.renderMultiDrawInstances(z._multiDrawStarts,z._multiDrawCounts,z._multiDrawCount,z._multiDrawInstances);else if(j.get("WEBGL_multi_draw"))kt.renderMultiDraw(z._multiDrawStarts,z._multiDrawCounts,z._multiDrawCount);else{const Ke=z._multiDrawStarts,Gt=z._multiDrawCounts,St=z._multiDrawCount,ri=Oe?I.get(Oe).bytesPerElement:1,yr=ce.get(q).currentProgram.getUniforms();for(let oi=0;oi{function fe(){if(q.forEach(function(Re){ce.get(Re).currentProgram.isReady()&&q.delete(Re)}),q.size===0){z(P);return}setTimeout(fe,10)}j.get("KHR_parallel_shader_compile")!==null?fe():setTimeout(fe,10)})};let Et=null;function ys(P){Et&&Et(P)}function Ji(){_a.stop()}function ly(){_a.start()}const _a=new uT;_a.setAnimationLoop(ys),typeof self<"u"&&_a.setContext(self),this.setAnimationLoop=function(P){Et=P,me.setAnimationLoop(P),P===null?_a.stop():_a.start()},me.addEventListener("sessionstart",Ji),me.addEventListener("sessionend",ly),this.render=function(P,B){if(B!==void 0&&B.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(T===!0)return;if(P.matrixWorldAutoUpdate===!0&&P.updateMatrixWorld(),B.parent===null&&B.matrixWorldAutoUpdate===!0&&B.updateMatrixWorld(),me.enabled===!0&&me.isPresenting===!0&&(me.cameraAutoUpdate===!0&&me.updateCamera(B),B=me.getCamera()),P.isScene===!0&&P.onBeforeRender(b,P,B,C),m=He.get(P,y.length),m.init(B),y.push(m),ae.multiplyMatrices(B.projectionMatrix,B.matrixWorldInverse),Xe.setFromProjectionMatrix(ae,hi,B.reversedDepth),Z=this.localClippingEnabled,De=ye.init(this.clippingPlanes,Z),_=ee.get(P,v.length),_.init(),v.push(_),me.enabled===!0&&me.isPresenting===!0){const fe=b.xr.getDepthSensingMesh();fe!==null&&gf(fe,B,-1/0,b.sortObjects)}gf(P,B,0,b.sortObjects),_.finish(),b.sortObjects===!0&&_.sort(ne,oe),xe=me.enabled===!1||me.isPresenting===!1||me.hasDepthSensing()===!1,xe&&Be.addToRenderList(_,P),this.info.render.frame++,De===!0&&ye.beginShadows();const K=m.state.shadowsArray;Ue.render(K,P,B),De===!0&&ye.endShadows(),this.info.autoReset===!0&&this.info.reset();const q=_.opaque,z=_.transmissive;if(m.setupLights(),B.isArrayCamera){const fe=B.cameras;if(z.length>0)for(let Re=0,Ne=fe.length;Re0&&uy(q,z,P,B),xe&&Be.render(P),cy(_,P,B);C!==null&&M===0&&(ge.updateMultisampleRenderTarget(C),ge.updateRenderTargetMipmap(C)),P.isScene===!0&&P.onAfterRender(b,P,B),Ce.resetDefaultState(),w=-1,E=null,y.pop(),y.length>0?(m=y[y.length-1],De===!0&&ye.setGlobalState(b.clippingPlanes,m.state.camera)):m=null,v.pop(),v.length>0?_=v[v.length-1]:_=null};function gf(P,B,K,q){if(P.visible===!1)return;if(P.layers.test(B.layers)){if(P.isGroup)K=P.renderOrder;else if(P.isLOD)P.autoUpdate===!0&&P.update(B);else if(P.isLight)m.pushLight(P),P.castShadow&&m.pushShadow(P);else if(P.isSprite){if(!P.frustumCulled||Xe.intersectsSprite(P)){q&&X.setFromMatrixPosition(P.matrixWorld).applyMatrix4(ae);const Re=V.update(P),Ne=P.material;Ne.visible&&_.push(P,Re,Ne,K,X.z,null)}}else if((P.isMesh||P.isLine||P.isPoints)&&(!P.frustumCulled||Xe.intersectsObject(P))){const Re=V.update(P),Ne=P.material;if(q&&(P.boundingSphere!==void 0?(P.boundingSphere===null&&P.computeBoundingSphere(),X.copy(P.boundingSphere.center)):(Re.boundingSphere===null&&Re.computeBoundingSphere(),X.copy(Re.boundingSphere.center)),X.applyMatrix4(P.matrixWorld).applyMatrix4(ae)),Array.isArray(Ne)){const Oe=Re.groups;for(let je=0,et=Oe.length;je0&&vc(z,B,K),fe.length>0&&vc(fe,B,K),Re.length>0&&vc(Re,B,K),Q.buffers.depth.setTest(!0),Q.buffers.depth.setMask(!0),Q.buffers.color.setMask(!0),Q.setPolygonOffset(!1)}function uy(P,B,K,q){if((K.isScene===!0?K.overrideMaterial:null)!==null)return;m.state.transmissionRenderTarget[q.id]===void 0&&(m.state.transmissionRenderTarget[q.id]=new ms(1,1,{generateMipmaps:!0,type:j.has("EXT_color_buffer_half_float")||j.has("EXT_color_buffer_float")?ls:ji,minFilter:Mi,samples:4,stencilBuffer:a,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:rt.workingColorSpace}));const fe=m.state.transmissionRenderTarget[q.id],Re=q.viewport||R;fe.setSize(Re.z*b.transmissionResolutionScale,Re.w*b.transmissionResolutionScale);const Ne=b.getRenderTarget(),Oe=b.getActiveCubeFace(),je=b.getActiveMipmapLevel();b.setRenderTarget(fe),b.getClearColor(D),U=b.getClearAlpha(),U<1&&b.setClearColor(16777215,.5),b.clear(),xe&&Be.render(K);const et=b.toneMapping;b.toneMapping=Os;const We=q.viewport;if(q.viewport!==void 0&&(q.viewport=void 0),m.setupLightsView(q),De===!0&&ye.setGlobalState(b.clippingPlanes,q),vc(P,K,q),ge.updateMultisampleRenderTarget(fe),ge.updateRenderTargetMipmap(fe),j.has("WEBGL_multisampled_render_to_texture")===!1){let wt=!1;for(let It=0,qt=B.length;It0),We=!!K.morphAttributes.position,wt=!!K.morphAttributes.normal,It=!!K.morphAttributes.color;let qt=Os;q.toneMapped&&(C===null||C.isXRRenderTarget===!0)&&(qt=b.toneMapping);const Ft=K.morphAttributes.position||K.morphAttributes.normal||K.morphAttributes.color,kt=Ft!==void 0?Ft.length:0,Ke=ce.get(q),Gt=m.state.lights;if(De===!0&&(Z===!0||P!==E)){const On=P===E&&q.id===w;ye.setState(q,P,On)}let St=!1;q.version===Ke.__version?(Ke.needsLights&&Ke.lightsStateVersion!==Gt.state.version||Ke.outputColorSpace!==Ne||z.isBatchedMesh&&Ke.batching===!1||!z.isBatchedMesh&&Ke.batching===!0||z.isBatchedMesh&&Ke.batchingColor===!0&&z.colorTexture===null||z.isBatchedMesh&&Ke.batchingColor===!1&&z.colorTexture!==null||z.isInstancedMesh&&Ke.instancing===!1||!z.isInstancedMesh&&Ke.instancing===!0||z.isSkinnedMesh&&Ke.skinning===!1||!z.isSkinnedMesh&&Ke.skinning===!0||z.isInstancedMesh&&Ke.instancingColor===!0&&z.instanceColor===null||z.isInstancedMesh&&Ke.instancingColor===!1&&z.instanceColor!==null||z.isInstancedMesh&&Ke.instancingMorph===!0&&z.morphTexture===null||z.isInstancedMesh&&Ke.instancingMorph===!1&&z.morphTexture!==null||Ke.envMap!==Oe||q.fog===!0&&Ke.fog!==fe||Ke.numClippingPlanes!==void 0&&(Ke.numClippingPlanes!==ye.numPlanes||Ke.numIntersection!==ye.numIntersection)||Ke.vertexAlphas!==je||Ke.vertexTangents!==et||Ke.morphTargets!==We||Ke.morphNormals!==wt||Ke.morphColors!==It||Ke.toneMapping!==qt||Ke.morphTargetsCount!==kt)&&(St=!0):(St=!0,Ke.__version=q.version);let ri=Ke.currentProgram;St===!0&&(ri=bc(q,B,z));let yr=!1,oi=!1,zo=!1;const $t=ri.getUniforms(),mi=Ke.uniforms;if(Q.useProgram(ri.program)&&(yr=!0,oi=!0,zo=!0),q.id!==w&&(w=q.id,oi=!0),yr||E!==P){Q.buffers.depth.getReversed()&&P.reversedDepth!==!0&&(P._reversedDepth=!0,P.updateProjectionMatrix()),$t.setValue(L,"projectionMatrix",P.projectionMatrix),$t.setValue(L,"viewMatrix",P.matrixWorldInverse);const $n=$t.map.cameraPosition;$n!==void 0&&$n.setValue(L,Se.setFromMatrixPosition(P.matrixWorld)),Y.logarithmicDepthBuffer&&$t.setValue(L,"logDepthBufFC",2/(Math.log(P.far+1)/Math.LN2)),(q.isMeshPhongMaterial||q.isMeshToonMaterial||q.isMeshLambertMaterial||q.isMeshBasicMaterial||q.isMeshStandardMaterial||q.isShaderMaterial)&&$t.setValue(L,"isOrthographic",P.isOrthographicCamera===!0),E!==P&&(E=P,oi=!0,zo=!0)}if(z.isSkinnedMesh){$t.setOptional(L,z,"bindMatrix"),$t.setOptional(L,z,"bindMatrixInverse");const On=z.skeleton;On&&(On.boneTexture===null&&On.computeBoneTexture(),$t.setValue(L,"boneTexture",On.boneTexture,ge))}z.isBatchedMesh&&($t.setOptional(L,z,"batchingTexture"),$t.setValue(L,"batchingTexture",z._matricesTexture,ge),$t.setOptional(L,z,"batchingIdTexture"),$t.setValue(L,"batchingIdTexture",z._indirectTexture,ge),$t.setOptional(L,z,"batchingColorTexture"),z._colorsTexture!==null&&$t.setValue(L,"batchingColorTexture",z._colorsTexture,ge));const _i=K.morphAttributes;if((_i.position!==void 0||_i.normal!==void 0||_i.color!==void 0)&&de.update(z,K,ri),(oi||Ke.receiveShadow!==z.receiveShadow)&&(Ke.receiveShadow=z.receiveShadow,$t.setValue(L,"receiveShadow",z.receiveShadow)),q.isMeshGouraudMaterial&&q.envMap!==null&&(mi.envMap.value=Oe,mi.flipEnvMap.value=Oe.isCubeTexture&&Oe.isRenderTargetTexture===!1?-1:1),q.isMeshStandardMaterial&&q.envMap===null&&B.environment!==null&&(mi.envMapIntensity.value=B.environmentIntensity),oi&&($t.setValue(L,"toneMappingExposure",b.toneMappingExposure),Ke.needsLights&&I1(mi,zo),fe&&q.fog===!0&&le.refreshFogUniforms(mi,fe),le.refreshMaterialUniforms(mi,q,H,W,m.state.transmissionRenderTarget[P.id]),qu.upload(L,hy(Ke),mi,ge)),q.isShaderMaterial&&q.uniformsNeedUpdate===!0&&(qu.upload(L,hy(Ke),mi,ge),q.uniformsNeedUpdate=!1),q.isSpriteMaterial&&$t.setValue(L,"center",z.center),$t.setValue(L,"modelViewMatrix",z.modelViewMatrix),$t.setValue(L,"normalMatrix",z.normalMatrix),$t.setValue(L,"modelMatrix",z.matrixWorld),q.isShaderMaterial||q.isRawShaderMaterial){const On=q.uniformsGroups;for(let $n=0,yf=On.length;$n0&&ge.useMultisampledRTT(P)===!1?z=ce.get(P).__webglMultisampledFramebuffer:Array.isArray(et)?z=et[K]:z=et,R.copy(P.viewport),k.copy(P.scissor),O=P.scissorTest}else R.copy(pe).multiplyScalar(H).floor(),k.copy(Ie).multiplyScalar(H).floor(),O=ke;if(K!==0&&(z=k1),Q.bindFramebuffer(L.FRAMEBUFFER,z)&&q&&Q.drawBuffers(P,z),Q.viewport(R),Q.scissor(k),Q.setScissorTest(O),fe){const Oe=ce.get(P.texture);L.framebufferTexture2D(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_CUBE_MAP_POSITIVE_X+B,Oe.__webglTexture,K)}else if(Re){const Oe=B;for(let je=0;je=0&&B<=P.width-q&&K>=0&&K<=P.height-z&&(P.textures.length>1&&L.readBuffer(L.COLOR_ATTACHMENT0+Ne),L.readPixels(B,K,q,z,Ve.convert(et),Ve.convert(We),fe))}finally{const je=C!==null?ce.get(C).__webglFramebuffer:null;Q.bindFramebuffer(L.FRAMEBUFFER,je)}}},this.readRenderTargetPixelsAsync=async function(P,B,K,q,z,fe,Re,Ne=0){if(!(P&&P.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Oe=ce.get(P).__webglFramebuffer;if(P.isWebGLCubeRenderTarget&&Re!==void 0&&(Oe=Oe[Re]),Oe)if(B>=0&&B<=P.width-q&&K>=0&&K<=P.height-z){Q.bindFramebuffer(L.FRAMEBUFFER,Oe);const je=P.textures[Ne],et=je.format,We=je.type;if(!Y.textureFormatReadable(et))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Y.textureTypeReadable(We))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const wt=L.createBuffer();L.bindBuffer(L.PIXEL_PACK_BUFFER,wt),L.bufferData(L.PIXEL_PACK_BUFFER,fe.byteLength,L.STREAM_READ),P.textures.length>1&&L.readBuffer(L.COLOR_ATTACHMENT0+Ne),L.readPixels(B,K,q,z,Ve.convert(et),Ve.convert(We),0);const It=C!==null?ce.get(C).__webglFramebuffer:null;Q.bindFramebuffer(L.FRAMEBUFFER,It);const qt=L.fenceSync(L.SYNC_GPU_COMMANDS_COMPLETE,0);return L.flush(),await QC(L,qt,4),L.bindBuffer(L.PIXEL_PACK_BUFFER,wt),L.getBufferSubData(L.PIXEL_PACK_BUFFER,0,fe),L.deleteBuffer(wt),L.deleteSync(qt),fe}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(P,B=null,K=0){const q=Math.pow(2,-K),z=Math.floor(P.image.width*q),fe=Math.floor(P.image.height*q),Re=B!==null?B.x:0,Ne=B!==null?B.y:0;ge.setTexture2D(P,0),L.copyTexSubImage2D(L.TEXTURE_2D,K,0,0,Re,Ne,z,fe),Q.unbindTexture()};const D1=L.createFramebuffer(),O1=L.createFramebuffer();this.copyTextureToTexture=function(P,B,K=null,q=null,z=0,fe=null){fe===null&&(z!==0?(Xl("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),fe=z,z=0):fe=0);let Re,Ne,Oe,je,et,We,wt,It,qt;const Ft=P.isCompressedTexture?P.mipmaps[fe]:P.image;if(K!==null)Re=K.max.x-K.min.x,Ne=K.max.y-K.min.y,Oe=K.isBox3?K.max.z-K.min.z:1,je=K.min.x,et=K.min.y,We=K.isBox3?K.min.z:0;else{const _i=Math.pow(2,-z);Re=Math.floor(Ft.width*_i),Ne=Math.floor(Ft.height*_i),P.isDataArrayTexture?Oe=Ft.depth:P.isData3DTexture?Oe=Math.floor(Ft.depth*_i):Oe=1,je=0,et=0,We=0}q!==null?(wt=q.x,It=q.y,qt=q.z):(wt=0,It=0,qt=0);const kt=Ve.convert(B.format),Ke=Ve.convert(B.type);let Gt;B.isData3DTexture?(ge.setTexture3D(B,0),Gt=L.TEXTURE_3D):B.isDataArrayTexture||B.isCompressedArrayTexture?(ge.setTexture2DArray(B,0),Gt=L.TEXTURE_2D_ARRAY):(ge.setTexture2D(B,0),Gt=L.TEXTURE_2D),L.pixelStorei(L.UNPACK_FLIP_Y_WEBGL,B.flipY),L.pixelStorei(L.UNPACK_PREMULTIPLY_ALPHA_WEBGL,B.premultiplyAlpha),L.pixelStorei(L.UNPACK_ALIGNMENT,B.unpackAlignment);const St=L.getParameter(L.UNPACK_ROW_LENGTH),ri=L.getParameter(L.UNPACK_IMAGE_HEIGHT),yr=L.getParameter(L.UNPACK_SKIP_PIXELS),oi=L.getParameter(L.UNPACK_SKIP_ROWS),zo=L.getParameter(L.UNPACK_SKIP_IMAGES);L.pixelStorei(L.UNPACK_ROW_LENGTH,Ft.width),L.pixelStorei(L.UNPACK_IMAGE_HEIGHT,Ft.height),L.pixelStorei(L.UNPACK_SKIP_PIXELS,je),L.pixelStorei(L.UNPACK_SKIP_ROWS,et),L.pixelStorei(L.UNPACK_SKIP_IMAGES,We);const $t=P.isDataArrayTexture||P.isData3DTexture,mi=B.isDataArrayTexture||B.isData3DTexture;if(P.isDepthTexture){const _i=ce.get(P),On=ce.get(B),$n=ce.get(_i.__renderTarget),yf=ce.get(On.__renderTarget);Q.bindFramebuffer(L.READ_FRAMEBUFFER,$n.__webglFramebuffer),Q.bindFramebuffer(L.DRAW_FRAMEBUFFER,yf.__webglFramebuffer);for(let ga=0;gaMath.PI&&(i-=Xn),s<-Math.PI?s+=Xn:s>Math.PI&&(s-=Xn),i<=s?this._spherical.theta=Math.max(i,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(i+s)/2?Math.max(i,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let a=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const r=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),a=r!=this._spherical.radius}if(ln.setFromSpherical(this._spherical),ln.applyQuaternion(this._quatInverse),t.copy(this.target).add(ln),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let r=null;if(this.object.isPerspectiveCamera){const o=ln.length();r=this._clampDistance(o*this._scale);const l=o-r;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),a=!!l}else if(this.object.isOrthographicCamera){const o=new S(this._mouse.x,this._mouse.y,0);o.unproject(this.object);const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),a=l!==this.object.zoom;const c=new S(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(o),this.object.updateMatrixWorld(),r=ln.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;r!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(r).add(this.object.position):(hu.origin.copy(this.object.position),hu.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(hu.direction))up||8*(1-this._lastQuaternion.dot(this.object.quaternion))>up||this._lastTargetPosition.distanceToSquared(this.target)>up?(this.dispatchEvent(q0),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Xn/60*this.autoRotateSpeed*e:Xn/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){ln.setFromMatrixColumn(t,0),ln.multiplyScalar(-e),this._panOffset.add(ln)}_panUp(e,t){this.screenSpacePanning===!0?ln.setFromMatrixColumn(t,1):(ln.setFromMatrixColumn(t,0),ln.crossVectors(this.object.up,ln)),ln.multiplyScalar(e),this._panOffset.add(ln)}_pan(e,t){const i=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;ln.copy(s).sub(this.target);let a=ln.length();a*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*a/i.clientHeight,this.object.matrix),this._panUp(2*t*a/i.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/i.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/i.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const i=this.domElement.getBoundingClientRect(),s=e-i.left,a=t-i.top,r=i.width,o=i.height;this._mouse.x=s/r*2-1,this._mouse.y=-(a/o)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Xn*this._rotateDelta.x/t.clientHeight),this._rotateUp(Xn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(Xn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-Xn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(Xn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-Xn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(i,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(i,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,s=e.pageY-t.y,a=Math.sqrt(i*i+s*s);this._dollyStart.set(0,a)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const i=this._getSecondPointerPosition(e),s=.5*(e.pageX+i.x),a=.5*(e.pageY+i.y);this._rotateEnd.set(s,a)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Xn*this._rotateDelta.x/t.clientHeight),this._rotateUp(Xn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(i,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,s=e.pageY-t.y,a=Math.sqrt(i*i+s*s);this._dollyEnd.set(0,a),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const r=(e.pageX+t.x)*.5,o=(e.pageY+t.y)*.5;this._updateZoomParameters(r,o)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t(O=F.indexOf(` +`))&&D=C.byteLength||!(U=d(C)))&&r(1,"no header found"),(F=U.match(w))||r(3,"bad initial token"),D.valid|=1,D.programtype=F[1],D.string+=U+` +`;U=d(C),U!==!1;){if(D.string+=U+` +`,U.charAt(0)==="#"){D.comments+=U+` +`;continue}if((F=U.match(E))&&(D.gamma=parseFloat(F[1])),(F=U.match(R))&&(D.exposure=parseFloat(F[1])),(F=U.match(k))&&(D.valid|=2,D.format=F[1]),(F=U.match(O))&&(D.valid|=4,D.height=parseInt(F[1],10),D.width=parseInt(F[2],10)),D.valid&2&&D.valid&4)break}return D.valid&2||r(3,"missing format specifier"),D.valid&4||r(3,"missing image size specifier"),D},f=function(C,w,E){const R=w;if(R<8||R>32767||C[0]!==2||C[1]!==2||C[2]&128)return new Uint8Array(C);R!==(C[2]<<8|C[3])&&r(3,"wrong scanline width");const k=new Uint8Array(4*w*E);k.length||r(4,"unable to allocate buffer space");let O=0,D=0;const U=4*R,F=new Uint8Array(4),W=new Uint8Array(U);let H=E;for(;H>0&&DC.byteLength&&r(1),F[0]=C[D++],F[1]=C[D++],F[2]=C[D++],F[3]=C[D++],(F[0]!=2||F[1]!=2||(F[2]<<8|F[3])!=R)&&r(3,"bad rgbe scanline format");let ne=0,oe;for(;ne128;if(Ie&&(oe-=128),(oe===0||ne+oe>U)&&r(3,"bad scanline data"),Ie){const ke=C[D++];for(let Xe=0;Xe{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(const t of e)t.dispose()}}function zr(n){return new ef({color:0,emissive:16777215,emissiveIntensity:n})}let gT=null;function MD(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof window<"u"&&window.location?.href?window.location.href:import.meta.url}function ED(){return"./"}function CD(n){return/^[a-z][a-z\d+\-.]*:/i.test(n)||n.startsWith("//")}function AD(n=gT){const e=n==null||n===""?ED():String(n);return new URL(e,MD()).href}function Si(n,e=gT){const t=String(n);return CD(t)?t:new URL(t.replace(/^\/+/,""),AD(e)).href}class RD{constructor(e,t={}){if(this.container=typeof e=="string"?document.getElementById(e):e,this.assetBase=t.assetBase,!this.container){console.error("Invalid container passed to SceneManager");return}this.scene=new cc,this.scene.background=new ue(8900331);const i=this.container.clientWidth,s=this.container.clientHeight;this.camera=new Jt(75,i/s,10,5e4),this.camera.position.set(0,2e3,5e3),this.renderer=new kg({antialias:!0,preserveDrawingBuffer:t.preserveDrawingBuffer===!0}),this.renderer.setSize(i,s),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=W_,this.renderer.toneMapping=K_,this.renderer.toneMappingExposure=1,this.renderer.outputColorSpace=gt,this.container.appendChild(this.renderer.domElement),window.addEventListener("resize",()=>this.onWindowResize())}initDefaultEnvironment(){if(!this._neutralEnvTexture){const e=new sh(this.renderer);this._neutralEnvTexture=e.fromScene(new TD,.04).texture,e.dispose()}if(this.scene.environment=this._neutralEnvTexture,!this._defaultLightsAdded){const e=new Fo(16777215,1.5);e.position.set(3e3,8e3,4e3),this.scene.add(e);const t=new mc(16777215,.4);this.scene.add(t),this._defaultLightsAdded=!0}}applyEnvironment(e){return new Promise(t=>{const i=new SD,s=Si(e.skyboxUrl,this.assetBase);i.load(s,a=>{this.scene.background&&this.scene.background.dispose&&this.scene.background.dispose(),a.mapping=rr,this.scene.background=a,this.scene.environment=a,this.currentEnvironmentId=e.id;const r=e.rotation??{};this._skyboxBaseRotation={x:vt.degToRad(r.x??0),y:vt.degToRad(r.y??0),z:vt.degToRad(r.z??0)},this._skyboxAnimatedY=0,this._skyboxAnimation=e.animation??null,this._applySkyboxRotation(),typeof e.exposure=="number"&&(this.renderer.toneMappingExposure=e.exposure),console.log(`[SceneManager] environment applied: ${e.id}`),t(!0)},void 0,a=>{console.error(`[SceneManager] Failed to load environment "${e.id}":`,a),t(!1)})})}_applySkyboxRotation(){const e=this._skyboxBaseRotation;if(!e)return;const t=e.y+(this._skyboxAnimatedY??0);this.scene.backgroundRotation&&this.scene.backgroundRotation.set(e.x,t,e.z),this.scene.environmentRotation&&this.scene.environmentRotation.set(e.x,t,e.z)}updateSkyboxAnimation(e){const t=this._skyboxAnimation;!t||!t.enabled||!e||(this._skyboxAnimatedY=(this._skyboxAnimatedY??0)+vt.degToRad(t.speed*e),this._applySkyboxRotation())}setDefaultBackground(){this.scene.background&&this.scene.background.dispose&&this.scene.background.dispose(),this.scene.background=new ue(1710638),this.initDefaultEnvironment(),this.renderer.toneMappingExposure=1,this._skyboxAnimation=null,this._skyboxBaseRotation=null,this.currentEnvironmentId=null,console.log("[SceneManager] Using neutral default environment (no skybox)")}setExposure(e){this.renderer&&(this.renderer.toneMappingExposure=e)}onWindowResize(){if(!this.container||!this.renderer)return;const e=this.container.clientWidth,t=this.container.clientHeight;this.camera.aspect=e/t,this.camera.updateProjectionMatrix(),this.renderer.setSize(e,t)}render(){this.renderer&&this.renderer.render(this.scene,this.camera)}dispose(){this.renderer&&(this.renderer.dispose(),this.renderer.domElement&&this.renderer.domElement.parentNode&&this.renderer.domElement.parentNode.removeChild(this.renderer.domElement),this.renderer=null)}}function j0(n,e){if(e===rS)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),n;if(e===Qd||e===ng){let t=n.getIndex();if(t===null){const r=[],o=n.getAttribute("position");if(o!==void 0){for(let l=0;l=2.0 are supported."));return}const c=new lO(a,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let u=0;u=0&&o[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}c.setExtensions(r),c.setPlugins(o),c.parse(i,s)}parseAsync(e,t){const i=this;return new Promise(function(s,a){i.parse(e,t,s,a)})}}function PD(){let n={};return{get:function(e){return n[e]},add:function(e,t){n[e]=t},remove:function(e){delete n[e]},removeAll:function(){n={}}}}const xt={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class ID{constructor(e){this.parser=e,this.name=xt.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let i=0,s=t.length;i=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,a.source,r)}}class WD{constructor(e){this.parser=e,this.name=xt.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,i=this.parser,s=i.json,a=s.textures[e];if(!a.extensions||!a.extensions[t])return null;const r=a.extensions[t],o=s.images[r.source];let l=i.textureLoader;if(o.uri){const c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,r.source,l)}}class XD{constructor(e){this.parser=e,this.name=xt.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,i=this.parser,s=i.json,a=s.textures[e];if(!a.extensions||!a.extensions[t])return null;const r=a.extensions[t],o=s.images[r.source];let l=i.textureLoader;if(o.uri){const c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,r.source,l)}}class KD{constructor(e){this.name=xt.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,i=t.bufferViews[e];if(i.extensions&&i.extensions[this.name]){const s=i.extensions[this.name],a=this.parser.getDependency("buffer",s.buffer),r=this.parser.options.meshoptDecoder;if(!r||!r.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return a.then(function(o){const l=s.byteOffset||0,c=s.byteLength||0,u=s.count,d=s.byteStride,h=new Uint8Array(o,l,c);return r.decodeGltfBufferAsync?r.decodeGltfBufferAsync(u,d,h,s.mode,s.filter).then(function(f){return f.buffer}):r.ready.then(function(){const f=new ArrayBuffer(u*d);return r.decodeGltfBuffer(new Uint8Array(f),u,d,h,s.mode,s.filter),f})})}else return null}}class qD{constructor(e){this.name=xt.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,i=t.nodes[e];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;const s=t.meshes[i.mesh];for(const c of s.primitives)if(c.mode!==xi.TRIANGLES&&c.mode!==xi.TRIANGLE_STRIP&&c.mode!==xi.TRIANGLE_FAN&&c.mode!==void 0)return null;const r=i.extensions[this.name].attributes,o=[],l={};for(const c in r)o.push(this.parser.getDependency("accessor",r[c]).then(u=>(l[c]=u,l[c])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(c=>{const u=c.pop(),d=u.isGroup?u.children:[u],h=c[0].count,f=[];for(const p of d){const g=new Me,_=new S,m=new dt,v=new S(1,1,1),y=new zh(p.geometry,p.material,h);for(let b=0;b0||n.search(/^data\:image\/jpeg/)===0?"image/jpeg":n.search(/\.webp($|\?)/i)>0||n.search(/^data\:image\/webp/)===0?"image/webp":n.search(/\.ktx2($|\?)/i)>0||n.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const oO=new Me;class lO{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new PD,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let i=!1,s=-1,a=!1,r=-1;if(typeof navigator<"u"){const o=navigator.userAgent;i=/^((?!chrome|android).)*safari/i.test(o)===!0;const l=o.match(/Version\/(\d+)/);s=i&&l?parseInt(l[1],10):-1,a=o.indexOf("Firefox")>-1,r=a?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||i&&s<17||a&&r<98?this.textureLoader=new tf(this.options.manager):this.textureLoader=new nT(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Gn(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const i=this,s=this.json,a=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(r){return r._markDefs&&r._markDefs()}),Promise.all(this._invokeAll(function(r){return r.beforeRoot&&r.beforeRoot()})).then(function(){return Promise.all([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])}).then(function(r){const o={scene:r[0][s.scene||0],scenes:r[0],animations:r[1],cameras:r[2],asset:s.asset,parser:i,userData:{}};return La(a,o,s),rs(o,s),Promise.all(i._invokeAll(function(l){return l.afterRoot&&l.afterRoot(o)})).then(function(){for(const l of o.scenes)l.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let s=0,a=t.length;s{const l=this.associations.get(r);l!=null&&this.associations.set(o,l);for(const[c,u]of r.children.entries())a(u,o.children[c])};return a(i,s),s.name+="_instance_"+e.uses[t]++,s}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let i=0;i=2&&_.setY(w,x[M*l+1]),l>=3&&_.setZ(w,x[M*l+2]),l>=4&&_.setW(w,x[M*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}_.normalized=p}return _})}loadTexture(e){const t=this.json,i=this.options,a=t.textures[e].source,r=t.images[a];let o=this.textureLoader;if(r.uri){const l=i.manager.getHandler(r.uri);l!==null&&(o=l)}return this.loadTextureImage(e,a,o)}loadTextureImage(e,t,i){const s=this,a=this.json,r=a.textures[e],o=a.images[t],l=(o.uri||o.bufferView)+":"+r.sampler;if(this.textureCache[l])return this.textureCache[l];const c=this.loadImageSource(t,i).then(function(u){u.flipY=!1,u.name=r.name||o.name||"",u.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(u.name=o.uri);const h=(a.samplers||{})[r.sampler]||{};return u.magFilter=J0[h.magFilter]||Vt,u.minFilter=J0[h.minFilter]||Mi,u.wrapS=Q0[h.wrapS]||ps,u.wrapT=Q0[h.wrapT]||ps,u.generateMipmaps=!u.isCompressedTexture&&u.minFilter!==dn&&u.minFilter!==Vt,s.associations.set(u,{textures:e}),u}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){const i=this,s=this.json,a=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(d=>d.clone());const r=s.images[e],o=self.URL||self.webkitURL;let l=r.uri||"",c=!1;if(r.bufferView!==void 0)l=i.getDependency("bufferView",r.bufferView).then(function(d){c=!0;const h=new Blob([d],{type:r.mimeType});return l=o.createObjectURL(h),l});else if(r.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const u=Promise.resolve(l).then(function(d){return new Promise(function(h,f){let p=h;t.isImageBitmapLoader===!0&&(p=function(g){const _=new Bt(g);_.needsUpdate=!0,h(_)}),t.load(Us.resolveURL(d,a.path),p,void 0,f)})}).then(function(d){return c===!0&&o.revokeObjectURL(l),rs(d,r),d.userData.mimeType=r.mimeType||rO(r.uri),d}).catch(function(d){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),d});return this.sourceCache[e]=u,u}assignTexture(e,t,i,s){const a=this;return this.getDependency("texture",i.index).then(function(r){if(!r)return null;if(i.texCoord!==void 0&&i.texCoord>0&&(r=r.clone(),r.channel=i.texCoord),a.extensions[xt.KHR_TEXTURE_TRANSFORM]){const o=i.extensions!==void 0?i.extensions[xt.KHR_TEXTURE_TRANSFORM]:void 0;if(o){const l=a.associations.get(r);r=a.extensions[xt.KHR_TEXTURE_TRANSFORM].extendTexture(r,o),a.associations.set(r,l)}}return s!==void 0&&(r.colorSpace=s),e[t]=r,r})}assignFinalMaterial(e){const t=e.geometry;let i=e.material;const s=t.attributes.tangent===void 0,a=t.attributes.color!==void 0,r=t.attributes.normal===void 0;if(e.isPoints){const o="PointsMaterial:"+i.uuid;let l=this.cache.get(o);l||(l=new aa,Qt.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,l.sizeAttenuation=!1,this.cache.add(o,l)),i=l}else if(e.isLine){const o="LineBasicMaterial:"+i.uuid;let l=this.cache.get(o);l||(l=new Rt,Qt.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,this.cache.add(o,l)),i=l}if(s||a||r){let o="ClonedMaterial:"+i.uuid+":";s&&(o+="derivative-tangents:"),a&&(o+="vertex-colors:"),r&&(o+="flat-shading:");let l=this.cache.get(o);l||(l=i.clone(),a&&(l.vertexColors=!0),r&&(l.flatShading=!0),s&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(o,l),this.associations.set(l,this.associations.get(i))),i=l}e.material=i}getMaterialType(){return Pn}loadMaterial(e){const t=this,i=this.json,s=this.extensions,a=i.materials[e];let r;const o={},l=a.extensions||{},c=[];if(l[xt.KHR_MATERIALS_UNLIT]){const d=s[xt.KHR_MATERIALS_UNLIT];r=d.getMaterialType(),c.push(d.extendParams(o,a,t))}else{const d=a.pbrMetallicRoughness||{};if(o.color=new ue(1,1,1),o.opacity=1,Array.isArray(d.baseColorFactor)){const h=d.baseColorFactor;o.color.setRGB(h[0],h[1],h[2],xn),o.opacity=h[3]}d.baseColorTexture!==void 0&&c.push(t.assignTexture(o,"map",d.baseColorTexture,gt)),o.metalness=d.metallicFactor!==void 0?d.metallicFactor:1,o.roughness=d.roughnessFactor!==void 0?d.roughnessFactor:1,d.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,"metalnessMap",d.metallicRoughnessTexture)),c.push(t.assignTexture(o,"roughnessMap",d.metallicRoughnessTexture))),r=this._invokeOne(function(h){return h.getMaterialType&&h.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(h){return h.extendMaterialParams&&h.extendMaterialParams(e,o)})))}a.doubleSided===!0&&(o.side=ct);const u=a.alphaMode||hp.OPAQUE;if(u===hp.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,u===hp.MASK&&(o.alphaTest=a.alphaCutoff!==void 0?a.alphaCutoff:.5)),a.normalTexture!==void 0&&r!==Ye&&(c.push(t.assignTexture(o,"normalMap",a.normalTexture)),o.normalScale=new te(1,1),a.normalTexture.scale!==void 0)){const d=a.normalTexture.scale;o.normalScale.set(d,d)}if(a.occlusionTexture!==void 0&&r!==Ye&&(c.push(t.assignTexture(o,"aoMap",a.occlusionTexture)),a.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=a.occlusionTexture.strength)),a.emissiveFactor!==void 0&&r!==Ye){const d=a.emissiveFactor;o.emissive=new ue().setRGB(d[0],d[1],d[2],xn)}return a.emissiveTexture!==void 0&&r!==Ye&&c.push(t.assignTexture(o,"emissiveMap",a.emissiveTexture,gt)),Promise.all(c).then(function(){const d=new r(o);return a.name&&(d.name=a.name),rs(d,a),t.associations.set(d,{materials:e}),a.extensions&&La(s,d,a),d})}createUniqueName(e){const t=yt.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,i=this.extensions,s=this.primitiveCache;function a(o){return i[xt.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(l){return ev(l,o,t)})}const r=[];for(let o=0,l=e.length;o0&&sO(m,a),m.name=t.createUniqueName(a.name||"mesh_"+e),rs(m,a),_.extensions&&La(s,m,_),t.assignFinalMaterial(m),d.push(m)}for(let f=0,p=d.length;f1?u=new Mt:c.length===1?u=c[0]:u=new Qe,u!==c[0])for(let d=0,h=c.length;d1){const d=s.associations.get(u);s.associations.set(u,{...d})}return s.associations.get(u).nodes=e,u}),this.nodeCache[e]}loadScene(e){const t=this.extensions,i=this.json.scenes[e],s=this,a=new Mt;i.name&&(a.name=s.createUniqueName(i.name)),rs(a,i),i.extensions&&La(t,a,i);const r=i.nodes||[],o=[];for(let l=0,c=r.length;l{const d=new Map;for(const[h,f]of s.associations)(h instanceof Qt||h instanceof Bt)&&d.set(h,f);return u.traverse(h=>{const f=s.associations.get(h);f!=null&&d.set(h,f)}),d};return s.associations=c(a),a})}_createAnimationTracks(e,t,i,s,a){const r=[],o=e.name?e.name:e.uuid,l=[];Ys[a.path]===Ys.weights?e.traverse(function(h){h.morphTargetInfluences&&l.push(h.name?h.name:h.uuid)}):l.push(o);let c;switch(Ys[a.path]){case Ys.weights:c=ua;break;case Ys.rotation:c=_s;break;case Ys.translation:case Ys.scale:c=Hs;break;default:i.itemSize===1?c=ua:c=Hs;break}const u=s.interpolation!==void 0?tO[s.interpolation]:or,d=this._getArrayFromAccessor(i);for(let h=0,f=l.length;h{this.parse(r,t,s)},i,s)}parse(e,t,i=()=>{}){this.decodeDracoFile(e,t,null,null,gt,i).catch(i)}decodeDracoFile(e,t,i,s,a=xn,r=()=>{}){const o={attributeIDs:i||this.defaultAttributeIDs,attributeTypes:s||this.defaultAttributeTypes,useUniqueIDs:!!i,vertexColorSpace:a};return this.decodeGeometry(e,o).then(t).catch(r)}decodeGeometry(e,t){const i=JSON.stringify(t);if(pp.has(e)){const l=pp.get(e);if(l.key===i)return l.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let s;const a=this.workerNextTaskID++,r=e.byteLength,o=this._getWorker(a,r).then(l=>(s=l,new Promise((c,u)=>{s._callbacks[a]={resolve:c,reject:u},s.postMessage({type:"decode",id:a,taskConfig:t,buffer:e},[e])}))).then(l=>this._createGeometry(l.geometry));return o.catch(()=>!0).then(()=>{s&&a&&this._releaseTask(s,a)}),pp.set(e,{key:i,promise:o}),o}_createGeometry(e){const t=new Ge;e.index&&t.setIndex(new ot(e.index.array,1));for(let i=0;i{i.load(e,s,void 0,a)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(i=>{const s=i[0];e||(this.decoderConfig.wasmBinary=i[1]);const a=uO.toString(),r=["/* draco decoder */",s,"","/* worker */",a.substring(a.indexOf("{")+1,a.lastIndexOf("}"))].join(` +`);this.workerSourceURL=URL.createObjectURL(new Blob([r]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.lengtha._taskLoad?-1:1});const i=this.workerPool[this.workerPool.length-1];return i._taskCosts[e]=t,i._taskLoad+=t,i})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e{const d=u.draco,h=new d.Decoder;try{const f=t(d,h,new Int8Array(l),c),p=f.attributes.map(g=>g.array.buffer);f.index&&p.push(f.index.array.buffer),self.postMessage({type:"decode",id:o.id,geometry:f},p)}catch(f){console.error(f),self.postMessage({type:"error",id:o.id,error:f.message})}finally{d.destroy(h)}});break}};function t(r,o,l,c){const u=c.attributeIDs,d=c.attributeTypes;let h,f;const p=o.GetEncodedGeometryType(l);if(p===r.TRIANGULAR_MESH)h=new r.Mesh,f=o.DecodeArrayToMesh(l,l.byteLength,h);else if(p===r.POINT_CLOUD)h=new r.PointCloud,f=o.DecodeArrayToPointCloud(l,l.byteLength,h);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!f.ok()||h.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+f.error_msg());const g={index:null,attributes:[]};for(const _ in u){const m=self[d[_]];let v,y;if(c.useUniqueIDs)y=u[_],v=o.GetAttributeByUniqueId(h,y);else{if(y=o.GetAttributeId(h,r[u[_]]),y===-1)continue;v=o.GetAttribute(h,y)}const b=s(r,o,h,_,m,v);_==="color"&&(b.vertexColorSpace=c.vertexColorSpace),g.attributes.push(b)}return p===r.TRIANGULAR_MESH&&(g.index=i(r,o,h)),r.destroy(h),g}function i(r,o,l){const u=l.num_faces()*3,d=u*4,h=r._malloc(d);o.GetTrianglesUInt32Array(l,d,h);const f=new Uint32Array(r.HEAPF32.buffer,h,u).slice();return r._free(h),{array:f,itemSize:1}}function s(r,o,l,c,u,d){const h=d.num_components(),p=l.num_points()*h,g=p*u.BYTES_PER_ELEMENT,_=a(r,u),m=r._malloc(g);o.GetAttributeDataArrayForAllPoints(l,d,_,g,m);const v=new u(r.HEAPF32.buffer,m,p).slice();return r._free(m),{name:c,array:v,itemSize:h}}function a(r,o){switch(o){case Float32Array:return r.DT_FLOAT32;case Int8Array:return r.DT_INT8;case Int16Array:return r.DT_INT16;case Int32Array:return r.DT_INT32;case Uint8Array:return r.DT_UINT8;case Uint16Array:return r.DT_UINT16;case Uint32Array:return r.DT_UINT32}}}const dO=/^[og]\s*(.+)?/,hO=/^mtllib /,fO=/^usemtl /,pO=/^usemap /,tv=/\s+/,nv=new S,mp=new S,iv=new S,sv=new S,yi=new S,fu=new ue;function mO(){const n={objects:[],object:{},vertices:[],normals:[],colors:[],uvs:[],materials:{},materialLibraries:[],startObject:function(e,t){if(this.object&&this.object.fromDeclaration===!1){this.object.name=e,this.object.fromDeclaration=t!==!1;return}const i=this.object&&typeof this.object.currentMaterial=="function"?this.object.currentMaterial():void 0;if(this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0),this.object={name:e||"",fromDeclaration:t!==!1,geometry:{vertices:[],normals:[],colors:[],uvs:[],hasUVIndices:!1},materials:[],smooth:!0,startMaterial:function(s,a){const r=this._finalize(!1);r&&(r.inherited||r.groupCount<=0)&&this.materials.splice(r.index,1);const o={index:this.materials.length,name:s||"",mtllib:Array.isArray(a)&&a.length>0?a[a.length-1]:"",smooth:r!==void 0?r.smooth:this.smooth,groupStart:r!==void 0?r.groupEnd:0,groupEnd:-1,groupCount:-1,inherited:!1,clone:function(l){const c={index:typeof l=="number"?l:this.index,name:this.name,mtllib:this.mtllib,smooth:this.smooth,groupStart:0,groupEnd:-1,groupCount:-1,inherited:!1};return c.clone=this.clone.bind(c),c}};return this.materials.push(o),o},currentMaterial:function(){if(this.materials.length>0)return this.materials[this.materials.length-1]},_finalize:function(s){const a=this.currentMaterial();if(a&&a.groupEnd===-1&&(a.groupEnd=this.geometry.vertices.length/3,a.groupCount=a.groupEnd-a.groupStart,a.inherited=!1),s&&this.materials.length>1)for(let r=this.materials.length-1;r>=0;r--)this.materials[r].groupCount<=0&&this.materials.splice(r,1);return s&&this.materials.length===0&&this.materials.push({name:"",smooth:this.smooth}),a}},i&&i.name&&typeof i.clone=="function"){const s=i.clone(0);s.inherited=!0,this.object.materials.push(s)}this.objects.push(this.object)},finalize:function(){this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0)},parseVertexIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseNormalIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseUVIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/2)*2},addVertex:function(e,t,i){const s=this.vertices,a=this.object.geometry.vertices;a.push(s[e+0],s[e+1],s[e+2]),a.push(s[t+0],s[t+1],s[t+2]),a.push(s[i+0],s[i+1],s[i+2])},addVertexPoint:function(e){const t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addVertexLine:function(e){const t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addNormal:function(e,t,i){const s=this.normals,a=this.object.geometry.normals;a.push(s[e+0],s[e+1],s[e+2]),a.push(s[t+0],s[t+1],s[t+2]),a.push(s[i+0],s[i+1],s[i+2])},addFaceNormal:function(e,t,i){const s=this.vertices,a=this.object.geometry.normals;nv.fromArray(s,e),mp.fromArray(s,t),iv.fromArray(s,i),yi.subVectors(iv,mp),sv.subVectors(nv,mp),yi.cross(sv),yi.normalize(),a.push(yi.x,yi.y,yi.z),a.push(yi.x,yi.y,yi.z),a.push(yi.x,yi.y,yi.z)},addColor:function(e,t,i){const s=this.colors,a=this.object.geometry.colors;s[e]!==void 0&&a.push(s[e+0],s[e+1],s[e+2]),s[t]!==void 0&&a.push(s[t+0],s[t+1],s[t+2]),s[i]!==void 0&&a.push(s[i+0],s[i+1],s[i+2])},addUV:function(e,t,i){const s=this.uvs,a=this.object.geometry.uvs;a.push(s[e+0],s[e+1]),a.push(s[t+0],s[t+1]),a.push(s[i+0],s[i+1])},addDefaultUV:function(){const e=this.object.geometry.uvs;e.push(0,0),e.push(0,0),e.push(0,0)},addUVLine:function(e){const t=this.uvs;this.object.geometry.uvs.push(t[e+0],t[e+1])},addFace:function(e,t,i,s,a,r,o,l,c){const u=this.vertices.length;let d=this.parseVertexIndex(e,u),h=this.parseVertexIndex(t,u),f=this.parseVertexIndex(i,u);if(this.addVertex(d,h,f),this.addColor(d,h,f),o!==void 0&&o!==""){const p=this.normals.length;d=this.parseNormalIndex(o,p),h=this.parseNormalIndex(l,p),f=this.parseNormalIndex(c,p),this.addNormal(d,h,f)}else this.addFaceNormal(d,h,f);if(s!==void 0&&s!==""){const p=this.uvs.length;d=this.parseUVIndex(s,p),h=this.parseUVIndex(a,p),f=this.parseUVIndex(r,p),this.addUV(d,h,f),this.object.geometry.hasUVIndices=!0}else this.addDefaultUV()},addPointGeometry:function(e){this.object.geometry.type="Points";const t=this.vertices.length;for(let i=0,s=e.length;i=7?(cu.setRGB(parseFloat(d[4]),parseFloat(d[5]),parseFloat(d[6]),gt),t.colors.push(cu.r,cu.g,cu.b)):t.colors.push(void 0,void 0,void 0);break;case"vn":t.normals.push(parseFloat(d[1]),parseFloat(d[2]),parseFloat(d[3]));break;case"vt":t.uvs.push(parseFloat(d[1]),parseFloat(d[2]));break}}else if(u==="f"){const h=c.slice(1).trim().split(q0),f=[];for(let g=0,_=h.length;g<_;g++){const m=h[g];if(m.length>0){const v=m.split("/");f.push(v)}}const p=f[0];for(let g=1,_=f.length-1;g<_;g++){const m=f[g],v=f[g+1];t.addFace(p[0],m[0],v[0],p[1],m[1],v[1],p[2],m[2],v[2])}}else if(u==="l"){const d=c.substring(1).trim().split(" ");let h=[];const f=[];if(c.indexOf("/")===-1)h=d;else for(let p=0,g=d.length;p1){const h=s[1].trim().toLowerCase();t.object.smooth=h!=="0"&&h!=="off"}else t.object.smooth=!0;const d=t.object.currentMaterial();d&&(d.smooth=t.object.smooth)}else{if(c==="\0")continue;console.warn('THREE.OBJLoader: Unexpected line: "'+c+'"')}}t.finalize();const a=new Mt;if(a.materialLibraries=[].concat(t.materialLibraries),!(t.objects.length===1&&t.objects[0].geometry.vertices.length===0)===!0)for(let o=0,l=t.objects.length;o0&&g.setAttribute("normal",new Ee(u.normals,3)),u.colors.length>0&&(p=!0,g.setAttribute("color",new Ee(u.colors,3))),u.hasUVIndices===!0&&g.setAttribute("uv",new Ee(u.uvs,2));const _=[];for(let v=0,y=d.length;v1){for(let v=0,y=d.length;v0){const o=new sa({size:1,sizeAttenuation:!1}),l=new Ge;l.setAttribute("position",new Ee(t.vertices,3)),t.colors.length>0&&t.colors[0]!==void 0&&(l.setAttribute("color",new Ee(t.colors,3)),o.vertexColors=!0);const c=new ir(l,o);a.add(c)}return a}}const up=new Map;async function rO(n,e){const t=wi("models/stadium/stadium.glb",e);let i=up.get(t);return i||(i=n.loadAsync(t).then(s=>{const a=s.scene;return oO(a),a}).catch(s=>{throw up.delete(t),s}),up.set(t,i)),i}function oO(n){const e=["Sol_Trait_T0","Sol_Trait_T1","Milieu_Forme","Milieu_Forme.001","cage_T0","cage_T1","Couleur_Hexagone_T0","Couleur_Hexagone_T1","wall_gradient_color_2","wall_gradient_color_2.001","Fond_BackBoard_Transparent","dégradé_transparent_T0","dégradé_transparent_T1","grid_transperant","Detail_Milieu","Detail_Milieu.001"],t=["Glow","Glass"],i=["Plafond_Hexagone_T0","Plafond_Hexagone_T1","Plafond_Transparent"];n.traverse(s=>{if(!s.isMesh)return;s.receiveShadow=!0,s.castShadow=!i.includes(s.name),t.some(r=>s.name.includes(r))&&(console.log(`[ArenaManager] Disabling frustum culling for: ${s.name}`),s.frustumCulled=!1),s.material&&/^Hexagone_T[01]$/.test(s.material.name??"")&&(s.material=s.material.clone(),s.material.transparent=!0,s.material.opacity=.18,s.material.depthWrite=!1,s.renderOrder=1),s.material&&s.material.name==="bannière_pub"&&(s.visible=!1),s.material&&s.material.name==="Sol_Hexagone"&&(s.material=s.material.clone(),s.material.color.setScalar(.35),s.material.metalness=0,s.material.roughness=1),s.material&&s.material.name&&e.includes(s.material.name)&&(console.log(`[ArenaManager] Fixing visibility for: ${s.name} (material: ${s.material.name})`),s.material=s.material.clone(),s.material.side=ct,s.material.depthWrite=!1,s.renderOrder=1,s.frustumCulled=!1)})}class lO{constructor(e,t={}){this.scene=e,this.assetBase=t.assetBase,this.arenaMeshes=[],this.drawingCollider=null,this.drawingColliderMeshes=[],this.arenaDecorMesh=null,this.showArenaDecor=!0,this.dracoLoader=new hT,this.dracoLoader.setDecoderPath(wi("draco/",this.assetBase)),this.gltfLoader=new Ag,this.gltfLoader.setDRACOLoader(this.dracoLoader)}async loadArenaMeshes(){try{console.log("Loading arena mesh...");const t=(await rO(this.gltfLoader,this.assetBase)).clone(!0);t.traverse(i=>{i.isMesh&&this.arenaMeshes.push(i)}),console.log(`[ArenaManager] Collected ${this.arenaMeshes.length} meshes for raycasting`),this.scene.add(t),console.log("Arena mesh loaded successfully with correct orientation")}catch(e){console.error("Error loading arena mesh:",e);const t=new Dn(10240,8192),i=new Pn({color:3355443,side:ct}),s=new we(t,i);s.rotation.x=-Math.PI/2,s.receiveShadow=!0,this.scene.add(s),this.arenaMeshes.push(s)}}getArenaMeshes(){return this.arenaMeshes}getDrawingColliderMeshes(){return this.drawingColliderMeshes}async loadDrawingCollider(e=!1){try{console.log("[ArenaManager] Loading drawing collider...");const i=await new aO().loadAsync(wi("models/stadium/DrawingArena.obj",this.assetBase));i.rotation.x=Math.PI/2,i.rotation.y=Math.PI,i.scale.setScalar(.99),i.position.y=20,i.traverse(s=>{s.isMesh&&(this.drawingColliderMeshes.push(s),s.castShadow=!1,s.receiveShadow=!1,e?s.material=new Ye({color:65280,transparent:!0,opacity:.7,side:ct}):s.material=new Ye({visible:!1}))}),this.drawingCollider=i,this.scene.add(i),console.log(`[ArenaManager] Drawing collider loaded with ${this.drawingColliderMeshes.length} meshes`)}catch(t){console.error("[ArenaManager] Failed to load drawing collider:",t)}}setDrawingColliderVisible(e){for(const t of this.drawingColliderMeshes)e?t.material=new Ye({color:65280,wireframe:!0,transparent:!0,opacity:.5}):t.material=new Ye({visible:!1})}async loadArenaDecor(e=!0){try{console.log("[ArenaManager] Loading arena decoration mesh...");const t=await this.gltfLoader.loadAsync(wi("models/stadium/arene.glb",this.assetBase));this.arenaDecorMesh=t.scene,this.showArenaDecor=e,this.arenaDecorMesh.traverse(i=>{i.isMesh&&(i.receiveShadow=!0,i.castShadow=!0)}),this.arenaDecorMesh.visible=e,this.scene.add(this.arenaDecorMesh),console.log(`[ArenaManager] Arena decoration loaded, visible: ${e}`)}catch(t){console.error("[ArenaManager] Failed to load arena decoration:",t)}}setArenaDecorVisible(e){this.showArenaDecor=e,this.arenaDecorMesh&&(this.arenaDecorMesh.visible=e,console.log(`[ArenaManager] Arena decoration visibility set to: ${e}`))}isArenaDecorVisible(){return this.showArenaDecor}}var Si=Uint8Array,Zr=Uint16Array,cO=Int32Array,fT=new Si([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),pT=new Si([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),uO=new Si([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),mT=function(n,e){for(var t=new Zr(31),i=0;i<31;++i)t[i]=e+=1<>1|(Nt&21845)<<1;js=(js&52428)>>2|(js&13107)<<2,js=(js&61680)>>4|(js&3855)<<4,Dm[Nt]=((js&65280)>>8|(js&255)<<8)>>1}var Il=(function(n,e,t){for(var i=n.length,s=0,a=new Zr(e);s>l]=c}else for(o=new Zr(i),s=0;s>15-n[s]);return o}),hc=new Si(288);for(var Nt=0;Nt<144;++Nt)hc[Nt]=8;for(var Nt=144;Nt<256;++Nt)hc[Nt]=9;for(var Nt=256;Nt<280;++Nt)hc[Nt]=7;for(var Nt=280;Nt<288;++Nt)hc[Nt]=8;var yT=new Si(32);for(var Nt=0;Nt<32;++Nt)yT[Nt]=5;var pO=Il(hc,9,1),mO=Il(yT,5,1),dp=function(n){for(var e=n[0],t=1;te&&(e=n[t]);return e},ki=function(n,e,t){var i=e/8|0;return(n[i]|n[i+1]<<8)>>(e&7)&t},hp=function(n,e){var t=e/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},_O=function(n){return(n+7)/8|0},gO=function(n,e,t){return(t==null||t>n.length)&&(t=n.length),new Si(n.subarray(e,t))},yO=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Hi=function(n,e,t){var i=new Error(e||yO[n]);if(i.code=n,Error.captureStackTrace&&Error.captureStackTrace(i,Hi),!t)throw i;return i},vO=function(n,e,t,i){var s=n.length,a=0;if(!s||e.f&&!e.l)return t||new Si(0);var r=!t,o=r||e.i!=2,l=e.i;r&&(t=new Si(s*3));var c=function(xe){var Ae=t.length;if(xe>Ae){var L=new Si(Math.max(Ae*2,xe));L.set(t),t=L}},u=e.f||0,d=e.p||0,h=e.b||0,f=e.l,p=e.d,g=e.m,_=e.n,m=s*8;do{if(!f){u=ki(n,d,1);var v=ki(n,d+1,3);if(d+=3,v)if(v==1)f=pO,p=mO,g=9,_=5;else if(v==2){var x=ki(n,d,31)+257,M=ki(n,d+10,15)+4,C=x+ki(n,d+5,31)+1;d+=14;for(var w=new Si(C),E=new Si(19),R=0;R>4;if(y<16)w[R++]=y;else{var F=0,W=0;for(y==16?(W=3+ki(n,d,3),d+=2,F=w[R-1]):y==17?(W=3+ki(n,d,7),d+=3):y==18&&(W=11+ki(n,d,127),d+=7);W--;)w[R++]=F}}var H=w.subarray(0,x),ne=w.subarray(x);g=dp(H),_=dp(ne),f=Il(H,g,1),p=Il(ne,_,1)}else Hi(1);else{var y=_O(d)+4,b=n[y-4]|n[y-3]<<8,T=y+b;if(T>s){l&&Hi(0);break}o&&c(h+b),t.set(n.subarray(y,T),h),e.b=h+=b,e.p=d=T*8,e.f=u;continue}if(d>m){l&&Hi(0);break}}o&&c(h+131072);for(var oe=(1<>4;if(d+=F&15,d>m){l&&Hi(0);break}if(F||Hi(2),De<256)t[h++]=De;else if(De==256){Ie=d,f=null;break}else{var Xe=De-254;if(De>264){var R=De-257,ke=fT[R];Xe=ki(n,d,(1<>4;Z||Hi(3),d+=Z&15;var ne=fO[se];if(se>3){var ke=pT[se];ne+=hp(n,d)&(1<m){l&&Hi(0);break}o&&c(h+131072);var Se=h+Xe;if(h>4>7||(n[0]<<8|n[1])%31)&&Hi(6,"invalid zlib data"),(n[1]>>5&1)==1&&Hi(6,"invalid zlib data: "+(n[1]&32?"need":"unexpected")+" dictionary"),(n[1]>>3&4)+2};function wO(n,e){return vO(n.subarray(xO(n),-4),{i:2},e,e)}var SO=typeof TextDecoder<"u"&&new TextDecoder,TO=0;try{SO.decode(bO,{stream:!0}),TO=1}catch{}function vT(n,e,t){const i=t.length-n-1;if(e>=t[i])return i-1;if(e<=t[n])return n;let s=n,a=i,r=Math.floor((s+a)/2);for(;e=t[r+1];)e=g&&(p[f][0]=p[h][0]/o[v+1][m],_=p[f][0]*o[m][v]);const y=m>=-1?1:-m,b=d-1<=v?g-1:t-d;for(let x=y;x<=b;++x)p[f][x]=(p[h][x]-p[h][x-1])/o[v+1][m+x],_+=p[f][x]*o[m+x][v];d<=v&&(p[f][g]=-p[h][g-1]/o[v+1][d],_+=p[f][g]*o[d][v]),r[g][d]=_;const T=h;h=f,f=T}}let u=t;for(let d=1;d<=i;++d){for(let h=0;h<=t;++h)r[d][h]*=u;u*=t-d}return r}function AO(n,e,t,i,s){const a=st.toArray()),e.startKnot=this.startKnot,e.endKnot=this.endKnot,e}fromJSON(e){return super.fromJSON(e),this.degree=e.degree,this.knots=[...e.knots],this.controlPoints=e.controlPoints.map(t=>new qe(t[0],t[1],t[2],t[3])),this.startKnot=e.startKnot,this.endKnot=e.endKnot,this}}let _t,Zt,Un;class DO extends on{constructor(e){super(e)}load(e,t,i,s){const a=this,r=a.path===""?Us.extractUrlBase(e):a.path,o=new Gn(this.manager);o.setPath(a.path),o.setResponseType("arraybuffer"),o.setRequestHeader(a.requestHeader),o.setWithCredentials(a.withCredentials),o.load(e,function(l){try{t(a.parse(l,r))}catch(c){s?s(c):console.error(c),a.manager.itemError(e)}},i,s)}parse(e,t){if(BO(e))_t=new UO().parse(e);else{const s=wT(e);if(!zO(s))throw new Error("THREE.FBXLoader: Unknown format.");if(Q0(s)<7e3)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+Q0(s));_t=new NO().parse(s)}const i=new Yh(this.manager).setPath(this.resourcePath||t).setCrossOrigin(this.crossOrigin);return new kO(i,this.manager).parse(_t)}}class kO{constructor(e,t){this.textureLoader=e,this.manager=t}parse(){Zt=this.parseConnections();const e=this.parseImages(),t=this.parseTextures(e),i=this.parseMaterials(t),s=this.parseDeformers(),a=new OO().parse(s);return this.parseScene(s,a,i),Un}parseConnections(){const e=new Map;return"Connections"in _t&&_t.Connections.connections.forEach(function(i){const s=i[0],a=i[1],r=i[2];e.has(s)||e.set(s,{parents:[],children:[]});const o={ID:a,relationship:r};e.get(s).parents.push(o),e.has(a)||e.set(a,{parents:[],children:[]});const l={ID:s,relationship:r};e.get(a).children.push(l)}),e}parseImages(){const e={},t={};if("Video"in _t.Objects){const i=_t.Objects.Video;for(const s in i){const a=i[s],r=parseInt(s);if(e[r]=a.RelativeFilename||a.Filename,"Content"in a){const o=a.Content instanceof ArrayBuffer&&a.Content.byteLength>0,l=typeof a.Content=="string"&&a.Content!=="";if(o||l){const c=this.parseImage(i[s]);t[a.RelativeFilename||a.Filename]=c}}}}for(const i in e){const s=e[i];t[s]!==void 0?e[i]=t[s]:e[i]=e[i].split("\\").pop()}return e}parseImage(e){const t=e.Content,i=e.RelativeFilename||e.Filename,s=i.slice(i.lastIndexOf(".")+1).toLowerCase();let a;switch(s){case"bmp":a="image/bmp";break;case"jpg":case"jpeg":a="image/jpeg";break;case"png":a="image/png";break;case"tif":a="image/tiff";break;case"tga":this.manager.getHandler(".tga")===null&&console.warn("FBXLoader: TGA loader not found, skipping ",i),a="image/tga";break;case"webp":a="image/webp";break;default:console.warn('FBXLoader: Image type "'+s+'" is not supported.');return}if(typeof t=="string")return"data:"+a+";base64,"+t;{const r=new Uint8Array(t);return window.URL.createObjectURL(new Blob([r],{type:a}))}}parseTextures(e){const t=new Map;if("Texture"in _t.Objects){const i=_t.Objects.Texture;for(const s in i){const a=this.parseTexture(i[s],e);t.set(parseInt(s),a)}}return t}parseTexture(e,t){const i=this.loadTexture(e,t);i.ID=e.id,i.name=e.attrName;const s=e.WrapModeU,a=e.WrapModeV,r=s!==void 0?s.value:0,o=a!==void 0?a.value:0;if(i.wrapS=r===0?ps:Hn,i.wrapT=o===0?ps:Hn,"Scaling"in e){const l=e.Scaling.value;i.repeat.x=l[0],i.repeat.y=l[1]}if("Translation"in e){const l=e.Translation.value;i.offset.x=l[0],i.offset.y=l[1]}return i}loadTexture(e,t){const i=e.FileName.split(".").pop().toLowerCase();let s=this.manager.getHandler(`.${i}`);s===null&&(s=this.textureLoader);const a=s.path;a||s.setPath(this.textureLoader.path);const r=Zt.get(e.id).children;let o;if(r!==void 0&&r.length>0&&t[r[0].ID]!==void 0&&(o=t[r[0].ID],(o.indexOf("blob:")===0||o.indexOf("data:")===0)&&s.setPath(void 0)),o===void 0)return console.warn("FBXLoader: Undefined filename, creating placeholder texture."),new Bt;const l=s.load(o);return s.setPath(a),l}parseMaterials(e){const t=new Map;if("Material"in _t.Objects){const i=_t.Objects.Material;for(const s in i){const a=this.parseMaterial(i[s],e);a!==null&&t.set(parseInt(s),a)}}return t}parseMaterial(e,t){const i=e.id,s=e.attrName;let a=e.ShadingModel;if(typeof a=="object"&&(a=a.value),!Zt.has(i))return null;const r=this.parseParameters(e,t,i);let o;switch(a.toLowerCase()){case"phong":o=new Ya;break;case"lambert":o=new qh;break;default:console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.',a),o=new Ya;break}return o.setValues(r),o.name=s,o}parseParameters(e,t,i){const s={};e.BumpFactor&&(s.bumpScale=e.BumpFactor.value),e.Diffuse?s.color=at.colorSpaceToWorking(new ue().fromArray(e.Diffuse.value),gt):e.DiffuseColor&&(e.DiffuseColor.type==="Color"||e.DiffuseColor.type==="ColorRGB")&&(s.color=at.colorSpaceToWorking(new ue().fromArray(e.DiffuseColor.value),gt)),e.DisplacementFactor&&(s.displacementScale=e.DisplacementFactor.value),e.Emissive?s.emissive=at.colorSpaceToWorking(new ue().fromArray(e.Emissive.value),gt):e.EmissiveColor&&(e.EmissiveColor.type==="Color"||e.EmissiveColor.type==="ColorRGB")&&(s.emissive=at.colorSpaceToWorking(new ue().fromArray(e.EmissiveColor.value),gt)),e.EmissiveFactor&&(s.emissiveIntensity=parseFloat(e.EmissiveFactor.value)),s.opacity=1-(e.TransparencyFactor?parseFloat(e.TransparencyFactor.value):0),(s.opacity===1||s.opacity===0)&&(s.opacity=e.Opacity?parseFloat(e.Opacity.value):null,s.opacity===null&&(s.opacity=1-(e.TransparentColor?parseFloat(e.TransparentColor.value[0]):0))),s.opacity<1&&(s.transparent=!0),e.ReflectionFactor&&(s.reflectivity=e.ReflectionFactor.value),e.Shininess&&(s.shininess=e.Shininess.value),e.Specular?s.specular=at.colorSpaceToWorking(new ue().fromArray(e.Specular.value),gt):e.SpecularColor&&e.SpecularColor.type==="Color"&&(s.specular=at.colorSpaceToWorking(new ue().fromArray(e.SpecularColor.value),gt));const a=this;return Zt.get(i).children.forEach(function(r){const o=r.relationship;switch(o){case"Bump":s.bumpMap=a.getTexture(t,r.ID);break;case"Maya|TEX_ao_map":s.aoMap=a.getTexture(t,r.ID);break;case"DiffuseColor":case"Maya|TEX_color_map":s.map=a.getTexture(t,r.ID),s.map!==void 0&&(s.map.colorSpace=gt);break;case"DisplacementColor":s.displacementMap=a.getTexture(t,r.ID);break;case"EmissiveColor":s.emissiveMap=a.getTexture(t,r.ID),s.emissiveMap!==void 0&&(s.emissiveMap.colorSpace=gt);break;case"NormalMap":case"Maya|TEX_normal_map":s.normalMap=a.getTexture(t,r.ID);break;case"ReflectionColor":s.envMap=a.getTexture(t,r.ID),s.envMap!==void 0&&(s.envMap.mapping=ar,s.envMap.colorSpace=gt);break;case"SpecularColor":s.specularMap=a.getTexture(t,r.ID),s.specularMap!==void 0&&(s.specularMap.colorSpace=gt);break;case"TransparentColor":case"TransparencyFactor":s.alphaMap=a.getTexture(t,r.ID),s.transparent=!0;break;default:console.warn("THREE.FBXLoader: %s map is not supported in three.js, skipping texture.",o);break}}),s}getTexture(e,t){return"LayeredTexture"in _t.Objects&&t in _t.Objects.LayeredTexture&&(console.warn("THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer."),t=Zt.get(t).children[0].ID),e.get(t)}parseDeformers(){const e={},t={};if("Deformer"in _t.Objects){const i=_t.Objects.Deformer;for(const s in i){const a=i[s],r=Zt.get(parseInt(s));if(a.attrType==="Skin"){const o=this.parseSkeleton(r,i);o.ID=s,r.parents.length>1&&console.warn("THREE.FBXLoader: skeleton attached to more than one geometry is not supported."),o.geometryID=r.parents[0].ID,e[s]=o}else if(a.attrType==="BlendShape"){const o={id:s};o.rawTargets=this.parseMorphTargets(r,i),o.id=s,r.parents.length>1&&console.warn("THREE.FBXLoader: morph target attached to more than one geometry is not supported."),t[s]=o}}}return{skeletons:e,morphTargets:t}}parseSkeleton(e,t){const i=[];return e.children.forEach(function(s){const a=t[s.ID];if(a.attrType!=="Cluster")return;const r={ID:s.ID,indices:[],weights:[],transformLink:new Me().fromArray(a.TransformLink.a)};"Indexes"in a&&(r.indices=a.Indexes.a,r.weights=a.Weights.a),i.push(r)}),{rawBones:i,bones:[]}}parseMorphTargets(e,t){const i=[];for(let s=0;s1?r=o:o.length>0?r=o[0]:(r=new Ya({name:on.DEFAULT_MATERIAL_NAME,color:13421772}),o.push(r)),"color"in a.attributes&&o.forEach(function(l){l.vertexColors=!0}),a.groups.length>0){let l=!1;for(let c=0,u=a.groups.length;c=o.length)&&(d.materialIndex=o.length,l=!0)}if(l){const c=new Ya;o.push(c)}}return a.FBX_Deformer?(s=new Dh(a,r),s.normalizeSkinWeights()):s=new we(a,r),s}createCurve(e,t){const i=e.children.reduce(function(a,r){return t.has(r.ID)&&(a=t.get(r.ID)),a},null),s=new Rt({name:on.DEFAULT_MATERIAL_NAME,color:3342591,linewidth:1});return new In(i,s)}getTransformData(e,t){const i={};"InheritType"in t&&(i.inheritType=parseInt(t.InheritType.value)),"RotationOrder"in t?i.eulerOrder=Kl(t.RotationOrder.value):i.eulerOrder=Kl(0),"Lcl_Translation"in t&&(i.translation=t.Lcl_Translation.value),"PreRotation"in t&&(i.preRotation=t.PreRotation.value),"Lcl_Rotation"in t&&(i.rotation=t.Lcl_Rotation.value),"PostRotation"in t&&(i.postRotation=t.PostRotation.value),"Lcl_Scaling"in t&&(i.scale=t.Lcl_Scaling.value),"ScalingOffset"in t&&(i.scalingOffset=t.ScalingOffset.value),"ScalingPivot"in t&&(i.scalingPivot=t.ScalingPivot.value),"RotationOffset"in t&&(i.rotationOffset=t.RotationOffset.value),"RotationPivot"in t&&(i.rotationPivot=t.RotationPivot.value),e.userData.transformData=i}setLookAtProperties(e,t){"LookAtProperty"in t&&Zt.get(e.ID).children.forEach(function(s){if(s.relationship==="LookAtProperty"){const a=_t.Objects.Model[s.ID];if("Lcl_Translation"in a){const r=a.Lcl_Translation.value;e.target!==void 0?(e.target.position.fromArray(r),Un.add(e.target)):e.lookAt(new S().fromArray(r))}}})}bindSkeleton(e,t,i){const s=this.parsePoseNodes();for(const a in e){const r=e[a];Zt.get(parseInt(r.ID)).parents.forEach(function(l){if(t.has(l.ID)){const c=l.ID;Zt.get(c).parents.forEach(function(d){i.has(d.ID)&&i.get(d.ID).bind(new Ro(r.bones),s[d.ID])})}})}}parsePoseNodes(){const e={};if("Pose"in _t.Objects){const t=_t.Objects.Pose;for(const i in t)if(t[i].attrType==="BindPose"&&t[i].NbPoseNodes>0){const s=t[i].PoseNode;Array.isArray(s)?s.forEach(function(a){e[a.Node]=new Me().fromArray(a.Matrix.a)}):e[s.Node]=new Me().fromArray(s.Matrix.a)}}return e}addGlobalSceneSettings(){if("GlobalSettings"in _t){if("AmbientColor"in _t.GlobalSettings){const e=_t.GlobalSettings.AmbientColor.value,t=e[0],i=e[1],s=e[2];if(t!==0||i!==0||s!==0){const a=new ue().setRGB(t,i,s,gt);Un.add(new dc(a,1))}}"UnitScaleFactor"in _t.GlobalSettings&&(Un.userData.unitScaleFactor=_t.GlobalSettings.UnitScaleFactor.value)}}}class OO{constructor(){this.negativeMaterialIndices=!1}parse(e){const t=new Map;if("Geometry"in _t.Objects){const i=_t.Objects.Geometry;for(const s in i){const a=Zt.get(parseInt(s)),r=this.parseGeometry(a,i[s],e);t.set(parseInt(s),r)}}return this.negativeMaterialIndices===!0&&console.warn("THREE.FBXLoader: The FBX file contains invalid (negative) material indices. The asset might not render as expected."),t}parseGeometry(e,t,i){switch(t.attrType){case"Mesh":return this.parseMeshGeometry(e,t,i);case"NurbsCurve":return this.parseNurbsGeometry(t)}}parseMeshGeometry(e,t,i){const s=i.skeletons,a=[],r=e.parents.map(function(d){return _t.Objects.Model[d.ID]});if(r.length===0)return;const o=e.children.reduce(function(d,h){return s[h.ID]!==void 0&&(d=s[h.ID]),d},null);e.children.forEach(function(d){i.morphTargets[d.ID]!==void 0&&a.push(i.morphTargets[d.ID])});const l=r[0],c={};"RotationOrder"in l&&(c.eulerOrder=Kl(l.RotationOrder.value)),"InheritType"in l&&(c.inheritType=parseInt(l.InheritType.value)),"GeometricTranslation"in l&&(c.translation=l.GeometricTranslation.value),"GeometricRotation"in l&&(c.rotation=l.GeometricRotation.value),"GeometricScaling"in l&&(c.scale=l.GeometricScaling.value);const u=xT(c);return this.genGeometry(t,o,a,u)}genGeometry(e,t,i,s){const a=new Ge;e.attrName&&(a.name=e.attrName);const r=this.parseGeoNode(e,t),o=this.genBuffers(r),l=new Ee(o.vertex,3);if(l.applyMatrix4(s),a.setAttribute("position",l),o.colors.length>0&&a.setAttribute("color",new Ee(o.colors,3)),t&&(a.setAttribute("skinIndex",new Ch(o.weightsIndices,4)),a.setAttribute("skinWeight",new Ee(o.vertexWeights,4)),a.FBX_Deformer=t),o.normal.length>0){const c=new st().getNormalMatrix(s),u=new Ee(o.normal,3);u.applyNormalMatrix(c),a.setAttribute("normal",u)}if(o.uvs.forEach(function(c,u){const d=u===0?"uv":`uv${u}`;a.setAttribute(d,new Ee(o.uvs[u],2))}),r.material&&r.material.mappingType!=="AllSame"){let c=o.materialIndex[0],u=0;if(o.materialIndex.forEach(function(d,h){d!==c&&(a.addGroup(u,h-u,c),c=d,u=h)}),a.groups.length>0){const d=a.groups[a.groups.length-1],h=d.start+d.count;h!==o.materialIndex.length&&a.addGroup(h,o.materialIndex.length-h,c)}a.groups.length===0&&a.addGroup(0,o.materialIndex.length,o.materialIndex[0])}return this.addMorphTargets(a,e,i,s),a}parseGeoNode(e,t){const i={};if(i.vertexPositions=e.Vertices!==void 0?e.Vertices.a:[],i.vertexIndices=e.PolygonVertexIndex!==void 0?e.PolygonVertexIndex.a:[],e.LayerElementColor&&e.LayerElementColor[0].Colors&&(i.color=this.parseVertexColors(e.LayerElementColor[0])),e.LayerElementMaterial&&(i.material=this.parseMaterialIndices(e.LayerElementMaterial[0])),e.LayerElementNormal&&(i.normal=this.parseNormals(e.LayerElementNormal[0])),e.LayerElementUV){i.uv=[];let s=0;for(;e.LayerElementUV[s];)e.LayerElementUV[s].UV&&i.uv.push(this.parseUVs(e.LayerElementUV[s])),s++}return i.weightTable={},t!==null&&(i.skeleton=t,t.rawBones.forEach(function(s,a){s.indices.forEach(function(r,o){i.weightTable[r]===void 0&&(i.weightTable[r]=[]),i.weightTable[r].push({id:a,weight:s.weights[o]})})})),i}genBuffers(e){const t={vertex:[],normal:[],colors:[],uvs:[],materialIndex:[],vertexWeights:[],weightsIndices:[]};let i=0,s=0,a=!1,r=[],o=[],l=[],c=[],u=[],d=[];const h=this;return e.vertexIndices.forEach(function(f,p){let g,_=!1;f<0&&(f=f^-1,_=!0);let m=[],v=[];if(r.push(f*3,f*3+1,f*3+2),e.color){const y=uu(p,i,f,e.color);l.push(y[0],y[1],y[2])}if(e.skeleton){if(e.weightTable[f]!==void 0&&e.weightTable[f].forEach(function(y){v.push(y.weight),m.push(y.id)}),v.length>4){a||(console.warn("THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights."),a=!0);const y=[0,0,0,0],b=[0,0,0,0];v.forEach(function(T,x){let M=T,C=m[x];b.forEach(function(w,E,R){if(M>w){R[E]=M,M=w;const D=y[E];y[E]=C,C=D}})}),m=y,v=b}for(;v.length<4;)v.push(0),m.push(0);for(let y=0;y<4;++y)u.push(v[y]),d.push(m[y])}if(e.normal){const y=uu(p,i,f,e.normal);o.push(y[0],y[1],y[2])}e.material&&e.material.mappingType!=="AllSame"&&(g=uu(p,i,f,e.material)[0],g<0&&(h.negativeMaterialIndices=!0,g=0)),e.uv&&e.uv.forEach(function(y,b){const T=uu(p,i,f,y);c[b]===void 0&&(c[b]=[]),c[b].push(T[0]),c[b].push(T[1])}),s++,_&&(h.genFace(t,e,r,g,o,l,c,u,d,s),i++,s=0,r=[],o=[],l=[],c=[],u=[],d=[])}),t}getNormalNewell(e){const t=new S(0,0,0);for(let i=0;i.5?new S(0,1,0):new S(0,0,1)).cross(t).normalize(),a=t.clone().cross(s).normalize();return{normal:t,tangent:s,bitangent:a}}flattenVertex(e,t,i){return new te(e.dot(t),e.dot(i))}genFace(e,t,i,s,a,r,o,l,c,u){let d;if(u>3){const h=[],f=t.baseVertexPositions||t.vertexPositions;for(let m=0;m1&&console.warn("THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.");const r=e.get(a[0].ID);i[s]={name:t[s].attrName,layer:r}}return i}addClip(e){let t=[];const i=this;return e.layer.forEach(function(s){t=t.concat(i.generateTracks(s))}),new ua(e.name,-1,t)}generateTracks(e){const t=[];let i=new S,s=new S;if(e.transform&&e.transform.decompose(i,new dt,s),i=i.toArray(),s=s.toArray(),e.T!==void 0&&Object.keys(e.T.curves).length>0){const a=this.generateVectorTrack(e.modelName,e.T.curves,i,"position");a!==void 0&&t.push(a)}if(e.R!==void 0&&Object.keys(e.R.curves).length>0){const a=this.generateRotationTrack(e.modelName,e.R.curves,e.preRotation,e.postRotation,e.eulerOrder);a!==void 0&&t.push(a)}if(e.S!==void 0&&Object.keys(e.S.curves).length>0){const a=this.generateVectorTrack(e.modelName,e.S.curves,s,"scale");a!==void 0&&t.push(a)}if(e.DeformPercent!==void 0){const a=this.generateMorphTrack(e);a!==void 0&&t.push(a)}return t}generateVectorTrack(e,t,i,s){const a=this.getTimesForAllAxes(t),r=this.getKeyframeTrackValues(a,t,i);return new Hs(e+"."+s,a,r)}generateRotationTrack(e,t,i,s,a){let r,o;if(t.x!==void 0&&t.y!==void 0&&t.z!==void 0){const h=this.interpolateRotations(t.x,t.y,t.z,a);r=h[0],o=h[1]}const l=Kl(0);i!==void 0&&(i=i.map(vt.degToRad),i.push(l),i=new an().fromArray(i),i=new dt().setFromEuler(i)),s!==void 0&&(s=s.map(vt.degToRad),s.push(l),s=new an().fromArray(s),s=new dt().setFromEuler(s).invert());const c=new dt,u=new an,d=[];if(!o||!r)return new _s(e+".quaternion",[0],[0]);for(let h=0;h2&&new dt().fromArray(d,(h-3)/3*4).dot(c)<0&&c.set(-c.x,-c.y,-c.z,-c.w),c.toArray(d,h/3*4);return new _s(e+".quaternion",r,d)}generateMorphTrack(e){const t=e.DeformPercent.curves.morph,i=t.values.map(function(a){return a/100}),s=Un.getObjectByName(e.modelName).morphTargetDictionary[e.morphName];return new ca(e.modelName+".morphTargetInfluences["+s+"]",t.times,i)}getTimesForAllAxes(e){let t=[];if(e.x!==void 0&&(t=t.concat(e.x.times)),e.y!==void 0&&(t=t.concat(e.y.times)),e.z!==void 0&&(t=t.concat(e.z.times)),t=t.sort(function(i,s){return i-s}),t.length>1){let i=1,s=t[0];for(let a=1;a=180||f[1]>=180||f[2]>=180){const g=Math.max(...f)/180,_=new an(...c,s),m=new an(...d,s),v=new dt().setFromEuler(_),y=new dt().setFromEuler(m);v.dot(y)&&y.set(-y.x,-y.y,-y.z,-y.w);const b=e.times[o-1],T=e.times[o]-b,x=new dt,M=new an;for(let C=0;C<1;C+=1/g)x.copy(v.clone().slerp(y.clone(),C)),a.push(b+C*T),M.setFromQuaternion(x,s),r.push(M.x),r.push(M.y),r.push(M.z)}else a.push(e.times[o]),r.push(vt.degToRad(e.values[o])),r.push(vt.degToRad(t.values[o])),r.push(vt.degToRad(i.values[o]))}return[a,r]}}class NO{getPrevNode(){return this.nodeStack[this.currentIndent-2]}getCurrentNode(){return this.nodeStack[this.currentIndent-1]}getCurrentProp(){return this.currentProp}pushStack(e){this.nodeStack.push(e),this.currentIndent+=1}popStack(){this.nodeStack.pop(),this.currentIndent-=1}setCurrentProp(e,t){this.currentProp=e,this.currentPropName=t}parse(e){this.currentIndent=0,this.allNodes=new bT,this.nodeStack=[],this.currentProp=[],this.currentPropName="";const t=this,i=e.split(/[\r\n]+/);return i.forEach(function(s,a){const r=s.match(/^[\s\t]*;/),o=s.match(/^[\s\t]*$/);if(r||o)return;const l=s.match("^\\t{"+t.currentIndent+"}(\\w+):(.*){",""),c=s.match("^\\t{"+t.currentIndent+"}(\\w+):[\\s\\t\\r\\n](.*)"),u=s.match("^\\t{"+(t.currentIndent-1)+"}}");l?t.parseNodeBegin(s,l):c?t.parseNodeProperty(s,c,i[++a]):u?t.popStack():s.match(/^[^\s\t}]/)&&t.parseNodePropertyContinued(s)}),this.allNodes}parseNodeBegin(e,t){const i=t[1].trim().replace(/^"/,"").replace(/"$/,""),s=t[2].split(",").map(function(l){return l.trim().replace(/^"/,"").replace(/"$/,"")}),a={name:i},r=this.parseNodeAttr(s),o=this.getCurrentNode();this.currentIndent===0?this.allNodes.add(i,a):i in o?(i==="PoseNode"?o.PoseNode.push(a):o[i].id!==void 0&&(o[i]={},o[i][o[i].id]=o[i]),r.id!==""&&(o[i][r.id]=a)):typeof r.id=="number"?(o[i]={},o[i][r.id]=a):i!=="Properties70"&&(i==="PoseNode"?o[i]=[a]:o[i]=a),typeof r.id=="number"&&(a.id=r.id),r.name!==""&&(a.attrName=r.name),r.type!==""&&(a.attrType=r.type),this.pushStack(a)}parseNodeAttr(e){let t=e[0];e[0]!==""&&(t=parseInt(e[0]),isNaN(t)&&(t=e[0]));let i="",s="";return e.length>1&&(i=e[1].replace(/^(\w+)::/,""),s=e[2]),{id:t,name:i,type:s}}parseNodeProperty(e,t,i){let s=t[1].replace(/^"/,"").replace(/"$/,"").trim(),a=t[2].replace(/^"/,"").replace(/"$/,"").trim();s==="Content"&&a===","&&(a=i.replace(/"/g,"").replace(/,$/,"").trim());const r=this.getCurrentNode();if(r.name==="Properties70"){this.parseNodeSpecialProperty(e,s,a);return}if(s==="C"){const l=a.split(",").slice(1),c=parseInt(l[0]),u=parseInt(l[1]);let d=a.split(",").slice(3);d=d.map(function(h){return h.trim().replace(/^"/,"")}),s="connections",a=[c,u],GO(a,d),r[s]===void 0&&(r[s]=[])}s==="Node"&&(r.id=a),s in r&&Array.isArray(r[s])?r[s].push(a):s!=="a"?r[s]=a:r.a=a,this.setCurrentProp(r,s),s==="a"&&a.slice(-1)!==","&&(r.a=pp(a))}parseNodePropertyContinued(e){const t=this.getCurrentNode();t.a+=e,e.slice(-1)!==","&&(t.a=pp(t.a))}parseNodeSpecialProperty(e,t,i){const s=i.split('",').map(function(u){return u.trim().replace(/^\"/,"").replace(/\s/,"_")}),a=s[0],r=s[1],o=s[2],l=s[3];let c=s[4];switch(r){case"int":case"enum":case"bool":case"ULongLong":case"double":case"Number":case"FieldOfView":c=parseFloat(c);break;case"Color":case"ColorRGB":case"Vector3D":case"Lcl_Translation":case"Lcl_Rotation":case"Lcl_Scaling":c=pp(c);break}this.getPrevNode()[a]={type:r,type2:o,flag:l,value:c},this.setCurrentProp(this.getPrevNode(),a)}}class UO{parse(e){const t=new J0(e);t.skip(23);const i=t.getUint32();if(i<6400)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+i);const s=new bT;for(;!this.endOfContent(t);){const a=this.parseNode(t,i);a!==null&&s.add(a.name,a)}return s}endOfContent(e){return e.size()%16===0?(e.getOffset()+160+16&-16)>=e.size():e.getOffset()+160+16>=e.size()}parseNode(e,t){const i={},s=t>=7500?e.getUint64():e.getUint32(),a=t>=7500?e.getUint64():e.getUint32();t>=7500?e.getUint64():e.getUint32();const r=e.getUint8(),o=e.getString(r);if(s===0)return null;const l=[];for(let h=0;h0?l[0]:"",u=l.length>1?l[1]:"",d=l.length>2?l[2]:"";for(i.singleProperty=a===1&&e.getOffset()===s;s>e.getOffset();){const h=this.parseNode(e,t);h!==null&&this.parseSubNode(o,i,h)}return i.propertyList=l,typeof c=="number"&&(i.id=c),u!==""&&(i.attrName=u),d!==""&&(i.attrType=d),o!==""&&(i.name=o),i}parseSubNode(e,t,i){if(i.singleProperty===!0){const s=i.propertyList[0];Array.isArray(s)?(t[i.name]=i,i.a=s):t[i.name]=s}else if(e==="Connections"&&i.name==="C"){const s=[];i.propertyList.forEach(function(a,r){r!==0&&s.push(a)}),t.connections===void 0&&(t.connections=[]),t.connections.push(s)}else if(i.name==="Properties70")Object.keys(i).forEach(function(a){t[a]=i[a]});else if(e==="Properties70"&&i.name==="P"){let s=i.propertyList[0],a=i.propertyList[1];const r=i.propertyList[2],o=i.propertyList[3];let l;s.indexOf("Lcl ")===0&&(s=s.replace("Lcl ","Lcl_")),a.indexOf("Lcl ")===0&&(a=a.replace("Lcl ","Lcl_")),a==="Color"||a==="ColorRGB"||a==="Vector"||a==="Vector3D"||a.indexOf("Lcl_")===0?l=[i.propertyList[4],i.propertyList[5],i.propertyList[6]]:l=i.propertyList[4],t[s]={type:a,type2:r,flag:o,value:l}}else t[i.name]===void 0?typeof i.id=="number"?(t[i.name]={},t[i.name][i.id]=i):t[i.name]=i:i.name==="PoseNode"?(Array.isArray(t[i.name])||(t[i.name]=[t[i.name]]),t[i.name].push(i)):t[i.name][i.id]===void 0&&(t[i.name][i.id]=i)}parseProperty(e){const t=e.getString(1);let i;switch(t){case"C":return e.getBoolean();case"D":return e.getFloat64();case"F":return e.getFloat32();case"I":return e.getInt32();case"L":return e.getInt64();case"R":return i=e.getUint32(),e.getArrayBuffer(i);case"S":return i=e.getUint32(),e.getString(i);case"Y":return e.getInt16();case"b":case"c":case"d":case"f":case"i":case"l":const s=e.getUint32(),a=e.getUint32(),r=e.getUint32();if(a===0)switch(t){case"b":case"c":return e.getBooleanArray(s);case"d":return e.getFloat64Array(s);case"f":return e.getFloat32Array(s);case"i":return e.getInt32Array(s);case"l":return e.getInt64Array(s)}const o=wO(new Uint8Array(e.getArrayBuffer(r))),l=new J0(o.buffer);switch(t){case"b":case"c":return l.getBooleanArray(s);case"d":return l.getFloat64Array(s);case"f":return l.getFloat32Array(s);case"i":return l.getInt32Array(s);case"l":return l.getInt64Array(s)}break;default:throw new Error("THREE.FBXLoader: Unknown property type "+t)}}}class J0{constructor(e,t){this.dv=new DataView(e),this.offset=0,this.littleEndian=t!==void 0?t:!0,this._textDecoder=new TextDecoder}getOffset(){return this.offset}size(){return this.dv.buffer.byteLength}skip(e){this.offset+=e}getBoolean(){return(this.getUint8()&1)===1}getBooleanArray(e){const t=[];for(let i=0;i=0&&(i=new Uint8Array(this.dv.buffer,t,s)),this._textDecoder.decode(i)}}class bT{add(e,t){this[e]=t}}function BO(n){const e="Kaydara FBX Binary \0";return n.byteLength>=e.length&&e===wT(n,0,e.length)}function zO(n){const e=["K","a","y","d","a","r","a","\\","F","B","X","\\","B","i","n","a","r","y","\\","\\"];let t=0;function i(s){const a=n[s-1];return n=n.slice(t+s),t++,a}for(let s=0;s(console.warn(`⚠️ Could not load texture ${u}:`,d.message),null))])}this._processModelMaterials(s,a,e,i.format);const o=this._calculateModelScale(s,e,i.scale);if(s.userData.scaleInfo=o,s.userData.format=i.format,i.wheelSockets){s.userData.wheelSockets=!0,s.userData.wheelModelName=i.wheelModel;const l=this._findWheelSockets(s);s.userData.wheelSocketObjects=l,console.log(`🔌 Found ${Object.keys(l).length} wheel sockets`)}return{model:s,chassisTexture:a,wheelModel:r}}_findWheelSockets(e){const t={},i=["Wheel_BL","Wheel_BR","Wheel_FL","Wheel_FR"];console.log("🔍 Searching for wheel sockets..."),e.traverse(s=>{const a=s.name,r=a.toLowerCase();for(const o of i)(a===o||r===o.toLowerCase())&&(t[o]=s,console.log(` Found socket: "${a}" at position (${s.position.x.toFixed(2)}, ${s.position.y.toFixed(2)}, ${s.position.z.toFixed(2)})`))});for(const s of i)t[s]||console.warn(` ⚠️ Missing wheel socket: ${s}`);return Object.keys(t).length===0&&(console.warn("⚠️ No wheel sockets found! Listing all objects:"),e.traverse(s=>{console.log(` - "${s.name}" (${s.type})`)})),t}_calculateModelScale(e,t,i=null){const s=new vn().setFromObject(e),a=new S;s.getSize(a),console.log(`📐 ${t.toUpperCase()} model dimensions (raw):`),console.log(` Size: X=${a.x.toFixed(2)}, Y=${a.y.toFixed(2)}, Z=${a.z.toFixed(2)}`),console.log(` Min Y: ${s.min.y.toFixed(2)}, Max Y: ${s.max.y.toFixed(2)}`);const r=this.HITBOX_DIMENSIONS[t]||this.HITBOX_DIMENSIONS.octane;let o;if(i!==null)o=i,console.log(` Using override scale: ${o}`);else{const l=a.z,u=r.length*1/l;o=u*.55,console.log(` Target RL: ${r.length} x ${r.width} x ${r.height} uu`),console.log(` Scale to RL: ${u.toFixed(4)}, Final scale: ${o.toFixed(6)}`)}return{scale:o}}_loadFBX(e){return new Promise((t,i)=>{this.fbxLoader.load(e,s=>t(s),void 0,s=>i(new Error(`Failed to load FBX: ${e} - ${s.message}`)))})}_loadGLB(e){return new Promise((t,i)=>{this.gltfLoader.load(e,s=>{t(s.scene)},void 0,s=>i(new Error(`Failed to load GLB: ${e} - ${s.message}`)))})}async loadWheelModel(e){const t=wi(`models/wheels/${e}`,this.assetBase);if(this.wheelModelCache.has(t))return this.wheelModelCache.get(t);if(this.wheelLoadingPromises.has(t))return this.wheelLoadingPromises.get(t);const i=this._loadGLB(t);this.wheelLoadingPromises.set(t,i);try{const s=await i;return console.log(`✓ Loaded wheel model: ${e}`),s.traverse(a=>{a.isMesh&&(a.castShadow=!0,a.receiveShadow=!0)}),this.wheelModelCache.set(t,s),s}catch(s){throw console.error(`Failed to load wheel model ${e}:`,s),s}finally{this.wheelLoadingPromises.delete(t)}}_loadTexture(e){return new Promise((t,i)=>{this.textureLoader.load(e,s=>{s.flipY=!1,s.colorSpace=gt,t(s)},void 0,s=>i(new Error(`Failed to load texture: ${e}`)))})}_processModelMaterials(e,t,i,s="fbx"){console.log(`📦 Processing materials for ${i} (${s}):`);const a=["body","paint"],r=[];e.traverse(o=>{o.isLight&&(r.push(o),console.log(` 🔦 Removing imported light: "${o.name||o.type}"`))}),r.forEach(o=>{o.parent&&o.parent.remove(o)}),e.traverse(o=>{o.isMesh&&(console.log(` Mesh: "${o.name}"`),(Array.isArray(o.material)?o.material:[o.material]).forEach((c,u)=>{console.log(` [${u}] Material: "${c.name}" - Color: #${c.color?.getHexString()||"none"}`);const d=(c.name||"").toLowerCase(),h=(o.name||"").toLowerCase(),f=a.some(p=>d.includes(p)||h.includes(p));if(s==="glb")(c.isMeshStandardMaterial||c.isMeshPhysicalMaterial)&&(console.log(` → GLB material (keeping as-is): metalness=${c.metalness?.toFixed(2)}, roughness=${c.roughness?.toFixed(2)}`),c.userData.originalColor=c.color?.clone(),c.userData.isBodyMaterial=f);else if(c.isMeshPhongMaterial||c.isMeshLambertMaterial||c.isMeshBasicMaterial){let p;f?(p=new Pn({color:c.color,map:c.map,metalness:.8,roughness:.15}),console.log(" → Body material: shiny metallic")):(p=new Pn({color:c.color,map:c.map,metalness:.1,roughness:.6}),console.log(" → Non-body material: matte")),p.name=c.name,Array.isArray(o.material)?o.material[u]=p:o.material=p}}))}),t?console.log(` ✓ Chassis texture loaded for ${i}`):s==="fbx"&&console.log(` ⚠️ No chassis texture for ${i}`)}getModelTypeForCar(e,t){return e&&this.carNameToModel[e]?this.carNameToModel[e]:this.hitboxToModel[t]||"octane"}getModelTypeForHitbox(e){return this.hitboxToModel[e]||"octane"}async createCarMesh(e,t=0){const i=this.getModelTypeForHitbox(e);try{const s=await this.loadModel(i);if(!s||!s.model)return console.warn(`No cached model for ${i}`),null;const a=s.model.userData.format||"fbx";let r;a==="glb"?(r=mp(s.model),r.traverse(c=>{c.isMesh&&(Array.isArray(c.material)?c.material=c.material.map(u=>u.clone()):c.material&&(c.material=c.material.clone()))})):r=s.model.clone(),this.applyTeamColor(r,t);const o=new Mt,l=s.model.userData.scaleInfo;return l&&r.scale.setScalar(l.scale),o.add(r),r.traverse(c=>{c.isMesh&&(c.castShadow=!0)}),o.userData.modelType=i,o.userData.hitboxType=e,o.userData.team=t,o.userData.isFBXModel=a==="fbx",o.userData.isGLBModel=a==="glb",o}catch(s){return console.error(`Failed to create car mesh for ${e}:`,s),null}}applyTeamColor(e,t){const i=t===0?this.TEAM_COLORS.blue:this.TEAM_COLORS.orange,s=["body","paint"];let a=!1;console.log("🔍 Analyzing car meshes for team coloring:"),e.traverse(r=>{if(r.isMesh){const o=Array.isArray(r.material)?r.material:[r.material];console.log(` Mesh: "${r.name}" with ${o.length} material(s)`),o.forEach((l,c)=>{console.log(` [${c}] Material: "${l.name}", isBodyMaterial: ${l.userData?.isBodyMaterial}`)})}}),e.traverse(r=>{r.isMesh&&(Array.isArray(r.material)?r.material:[r.material]).forEach((l,c)=>{const u=(l.name||"").toLowerCase(),d=(r.name||"").toLowerCase(),h=l.userData?.isBodyMaterial||s.some(f=>u.includes(f)||d.includes(f));if(console.log(` Checking "${l.name}" on "${r.name}": isBody=${h}`),h){a=!0;const f=l.clone();f.color=i.clone(),f.metalness=.39,f.roughness=.47,f.userData={...l.userData},Array.isArray(r.material)?r.material[c]=f:r.material=f,console.log(`🎨 Applied team color to: "${l.name}" on mesh "${r.name}" (index ${c})`)}})}),a||console.warn("⚠️ No body material found for team coloring! Check material names.")}updateTeamColor(e,t){this.applyTeamColor(e,t)}isModelReady(e,t){const i=this.getModelTypeForCar(e,t);return this.modelCache.has(this.modelCacheKey(i))}getCarMeshSync(e,t,i=0){const s=this.getModelTypeForCar(e,t),a=this.modelCache.get(this.modelCacheKey(s));if(!a||!a.model)return null;const r=a.model.userData.format||"fbx",o=a.model.userData.wheelSockets;let l;r==="glb"?(l=mp(a.model),l.traverse(d=>{d.isMesh&&(Array.isArray(d.material)?d.material=d.material.map(h=>h.clone()):d.material&&(d.material=d.material.clone()))})):l=a.model.clone(),this.applyTeamColor(l,i);const c=new Mt,u=a.model.userData.scaleInfo;return u&&l.scale.setScalar(u.scale),c.add(l),l.traverse(d=>{d.isMesh&&(d.castShadow=!0)}),c.userData.modelType=s,c.userData.carName=e,c.userData.hitboxType=t,c.userData.team=i,c.userData.isFBXModel=r==="fbx",c.userData.isGLBModel=r==="glb",c.userData.hasWheelSockets=o,o?c.userData.wheels=this._attachWheelsToSockets(l,a.wheelModel):c.userData.wheels=this._findWheelMeshes(l),c}_attachWheelsToSockets(e,t){const i=[],s={Wheel_FL:{side:"left",position:"front"},Wheel_FR:{side:"right",position:"front"},Wheel_BL:{side:"left",position:"rear"},Wheel_BR:{side:"right",position:"rear"}};if(!t)return console.warn("⚠️ No wheel model template available for socket attachment"),i;console.log("🔧 Attaching wheels to sockets...");const a={};e.traverse(r=>{const o=r.name;s[o]&&(a[o]=r)});for(const[r,o]of Object.entries(s)){const l=a[r];if(!l){console.warn(` ⚠️ Socket not found: ${r}`);continue}const c=mp(t);c.traverse(u=>{u.isMesh&&(Array.isArray(u.material)?u.material=u.material.map(d=>d.clone()):u.material&&(u.material=u.material.clone()),u.castShadow=!0)}),c.position.set(0,0,0),c.rotation.set(0,0,0),l.add(c),console.log(` ✓ Attached wheel to ${r} (${o.position} ${o.side})`),i.push({mesh:c,steeringPivot:o.position==="front"?l:null,side:o.side,position:o.position,socket:l})}return console.log(`✓ Attached ${i.length} wheels to sockets`),i}_findWheelMeshes(e){const t=[],i={fl:{side:"left",position:"front"},fr:{side:"right",position:"front"},rl:{side:"left",position:"rear"},rr:{side:"right",position:"rear"}};console.log("🔍 Searching for wheels in model...");const s={};e.traverse(a=>{const o=a.name.toLowerCase().match(/^wheel_(fl|fr|rl|rr)_(y|z)$/);if(o){const l=o[1],c=o[2];s[l]||(s[l]={}),s[l][c]=a,console.log(` Found: "${a.name}" (${c==="y"?"wheel mesh":"steering pivot"})`)}});for(const[a,r]of Object.entries(s)){const o=i[a];if(!o)continue;const l=r.y,c=r.z;l&&(a==="fr"&&(l.rotation.z+=Math.PI,console.log(" Fixed FR wheel orientation (rotation.z += PI)")),t.push({mesh:l,steeringPivot:o.position==="front"?c:null,side:o.side,position:o.position}),console.log(`🛞 Wheel ${a.toUpperCase()}: mesh="${l.name}"${c&&o.position==="front"?`, steering="${c.name}"`:""}`))}return t.length===0?(console.warn("⚠️ No wheel meshes found. Expected: Wheel_FL_Y, Wheel_FR_Y, etc."),console.warn(" Listing all objects in model:"),e.traverse(a=>{console.log(` - "${a.name}" (${a.type})`)})):console.log(`✓ Found ${t.length} wheels`),t}dispose(){}}const jO=2,_p=new Map;function ZO(n){const e=wi("models/ball/scene.gltf",n);let t=_p.get(e);if(!t){const i=new Ag;t=new Promise(s=>{i.load(e,a=>{console.log("✓ Ball model loaded"),s(a.scene)},void 0,a=>{console.error("Failed to load ball model:",a),_p.delete(e),s(null)})}),_p.set(e,t)}return t}class JO{constructor(e,t,i={}){this.scene=e,this.effectsManager=t,this.assetBase=i.assetBase,this.actors={},this.ballActorId=null,this.ballIndicator=null,this.ballVerticalLine=null,this.playerNames=new Set,this.actorToPlayer={},this.actorLinks={},this.playerNameToCarActorId={},this.playerNameToPriActorId={},this.playerTeams={},this.actorLoadouts={},this.carBodyIds={},this.carModelLoader=new YO({assetBase:this.assetBase}),this.pendingCarReplacements=new Map,this._lastGoalScanTime=null,this._firedGoalTimes=new Set,this._p0=new S,this._p1=new S,this._v0=new S,this._v1=new S,this._nextRot=new dt,this._q0=new dt,this._q1=new dt,this._qResult=new dt,this.onPlayerFound=null,this.lastBallTouchTeam=0,this.BALL_TOUCH_DISTANCE=200,this.ballTimeline=[],this.playerTimelineMap={},this.timelineIndices={ball:0,players:{}},this.interpolantsInitialized=!1,this.animationMixer=null,this.animationActions={},this.animationClock=new vg(!1),this.replayDuration=0,this.useAnimationSystem=!1,this.SMOOTHING_WINDOW=5,this.positionBuffers={},this.rotationBuffers={},this.interpolationEnabled=!0,this.interpolationMethod="lerp",this.smoothingWindowSize=12,this.lastFrameInfo=null,this._lowPassState=new Map,this._lowPassAlpha=.3,this._predictState=new Map,this._predictCorrectionTime=.1,this._smoothingBuffers=new Map,this._adaptiveState=new Map,this.ballModel=null,this._ballModelReplaced=!1,this.ballModelReady=ZO(this.assetBase).then(s=>(this.ballModel=s,s!==null))}async waitForBallModel(){const e=await this.ballModelReady;return e&&!this._ballModelReplaced&&this.ballActorId&&this.actors[this.ballActorId]&&(this.replaceBallWithModel(this.ballActorId),this._ballModelReplaced=!0),e}replaceBallWithModel(e){const t=this.actors[e];if(!t||!this.ballModel)return;const i=this.ballModel.clone();i.userData=t.userData,i.position.copy(t.position),i.quaternion.copy(t.quaternion),i.scale.copy(t.scale);const s=92.75;i.scale.set(s,s,s),i.traverse(a=>{a.isMesh&&(a.castShadow=!0,a.receiveShadow=!0)}),this.scene.remove(t),this.scene.add(i),t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose(),this.actors[e]=i,console.log("✓ Ball replaced with GLTF model")}reset(){Object.values(this.actors).forEach(e=>{this.scene.remove(e),e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()}),this.actors={},this.ballActorId=null,this.ballIndicator&&(this.scene.remove(this.ballIndicator),this.ballIndicator.geometry&&this.ballIndicator.geometry.dispose(),this.ballIndicator.material&&this.ballIndicator.material.dispose(),this.ballIndicator=null),this.ballVerticalLine&&(this.scene.remove(this.ballVerticalLine),this.ballVerticalLine.geometry&&this.ballVerticalLine.geometry.dispose(),this.ballVerticalLine.material&&this.ballVerticalLine.material.dispose(),this.ballVerticalLine=null),this.actorToPlayer={},this.actorLinks={},this.playerNames.clear(),this.playerNameToCarActorId={},this.playerNameToPriActorId={},this.playerTeams={},this.actorLoadouts={},this.carBodyIds={},this.pendingCarReplacements.clear(),this._lastGoalScanTime=null,this._firedGoalTimes.clear(),this.ballTimeline=[],this.playerTimelineMap={},this.ballTimelineCorrected=[],this.playerTimelineMapCorrected={},this.ballTimelineFiltered=[],this.playerTimelineMapFiltered={},this.timelineIndices={ball:0,players:{}},this.timelineIndicesFiltered={ball:0,players:{}},this.timelineIndicesCorrected={ball:0,players:{}},this.interpolantsInitialized=!1,this.animationMixer?.stopAllAction?.(),this.animationMixer=null,this.animationActions={},this.replayDuration=0,this.positionBuffers={},this.rotationBuffers={},this._lowPassState.clear(),this._predictState.clear(),this._smoothingBuffers.clear(),this._adaptiveState.clear(),this._ballModelReplaced=!1}resetGoalExplosionPlaybackState(){this._lastGoalScanTime=null,this._firedGoalTimes.clear()}setPlayerTeams(e){this.playerTeams=e}initFromFramework(e){console.log("[ActorManager] Initializing actors from framework..."),this._createBallMesh();const t=e.playerList;t.forEach((i,s)=>{this._createCarMesh(i.name,i.team,s,i.carName,i.hitboxType);const a=this.playerNameToCarActorId[i.name];this.actors[a]}),console.log(`[ActorManager] Created ${t.length} car meshes + 1 ball`)}initInterpolants(e){console.log("[ActorManager] Initializing interpolation system..."),this.ballTimeline=e.ballTimeline||[],this.playerTimelineMap=e.playerTimelines||{},this.ballTimelineCorrected=this._correctTimeShiftedPositions(this.ballTimeline),this.playerTimelineMapCorrected={},Object.entries(this.playerTimelineMap).forEach(([s,a])=>{this.playerTimelineMapCorrected[s]=this._correctTimeShiftedPositions(a)}),this.ballTimelineFiltered=this._filterBadFrames(this.ballTimeline),this.playerTimelineMapFiltered={},Object.entries(this.playerTimelineMap).forEach(([s,a])=>{this.playerTimelineMapFiltered[s]=this._filterBadFrames(a)}),this.timelineIndices={ball:0,players:{}},this.timelineIndicesFiltered={ball:0,players:{}},this.timelineIndicesCorrected={ball:0,players:{}},Object.keys(this.playerTimelineMap).forEach(s=>{this.timelineIndices.players[s]=0,this.timelineIndicesFiltered.players[s]=0,this.timelineIndicesCorrected.players[s]=0}),this.ballTimeline.length>0&&(this.replayDuration=this.ballTimeline[this.ballTimeline.length-1].time),this.useAnimationSystem&&this._initAnimationSystem(),this.interpolantsInitialized=!0;const t=this.ballTimeline.length-this.ballTimelineFiltered.length,i=this.ballTimelineCorrected._correctedCount||0;console.log(` Ball: ${this.ballTimeline.length} keyframes (${i} corrected, ${t} filtered)`),Object.entries(this.playerTimelineMap).forEach(([s,a])=>{const r=this.playerTimelineMapCorrected[s]?._correctedCount||0;console.log(` ${s}: ${a.length} keyframes (${r} corrected)`)}),console.log(` Replay duration: ${this.replayDuration.toFixed(2)}s`),console.log("[ActorManager] Animation system ready")}_initAnimationSystem(){console.log("[ActorManager] Building Three.js animation clips..."),this.animationMixer=new QS(this.scene);const e=this.actors[this.ballActorId];if(e&&this.ballTimeline.length>0){const t=this._createAnimationClip("ball",this.ballTimeline,e);if(t){const i=this.animationMixer.clipAction(t,e);i.setLoop(Xd),i.clampWhenFinished=!0,this.animationActions.ball=i,console.log(` ✓ Ball animation: ${t.duration.toFixed(2)}s`)}}Object.entries(this.playerTimelineMap).forEach(([t,i])=>{const s=this.playerNameToCarActorId[t],a=this.actors[s];if(a&&i.length>0){const r=this._createAnimationClip(t,i,a);if(r){const o=this.animationMixer.clipAction(r,a);o.setLoop(Xd),o.clampWhenFinished=!0,this.animationActions[t]=o,console.log(` ✓ ${t} animation: ${r.duration.toFixed(2)}s`)}}}),console.log("[ActorManager] Animation clips ready")}_createAnimationClip(e,t,i){if(!t||t.length<2)return null;const s=[],a=[],r=[],o=t[0];o.time>0&&(s.push(0),o.position?a.push(o.position.x,o.position.y,o.position.z):a.push(0,0,0),o.rotation?r.push(o.rotation.x,o.rotation.y,o.rotation.z,o.rotation.w):r.push(0,0,0,1));for(const h of t){if(s.push(h.time),h.position)a.push(h.position.x,h.position.y,h.position.z);else{const f=a.length-3;f>=0?a.push(a[f],a[f+1],a[f+2]):a.push(0,0,0)}if(h.rotation)r.push(h.rotation.x,h.rotation.y,h.rotation.z,h.rotation.w);else{const f=r.length-4;f>=0?r.push(r[f],r[f+1],r[f+2],r[f+3]):r.push(0,0,0,1)}}const l=new Hs(".position",s,a,rr),c=new _s(".quaternion",s,r),u=s[s.length-1]-s[0];return new ua(e,u,[l,c])}startAnimations(){this.animationMixer&&(Object.values(this.animationActions).forEach(e=>{e.reset(),e.play()}),this.animationClock.start(),console.log("[ActorManager] Animations started"))}pauseAnimations(){this.animationMixer&&Object.values(this.animationActions).forEach(e=>{e.paused=!0})}resumeAnimations(){this.animationMixer&&Object.values(this.animationActions).forEach(e=>{e.paused=!1})}seekAnimations(e){this.animationMixer&&(Object.values(this.animationActions).forEach(t=>{t.time=e}),this.animationMixer.setTime(e))}updateAnimations(e){!this.animationMixer||!this.useAnimationSystem||this.animationMixer.update(e)}_subsampleTimeline(e){return!e||e.length<4?e:e.filter((t,i)=>i%2===0)}_getOrCreateSmoothingBuffer(e){return this.positionBuffers[e]||(this.positionBuffers[e]=[],this.rotationBuffers[e]=[]),{positions:this.positionBuffers[e],rotations:this.rotationBuffers[e]}}_smoothPosition(e,t){const i=this._getOrCreateSmoothingBuffer(e).positions;for(i.push({x:t.x,y:t.y,z:t.z});i.length>this.SMOOTHING_WINDOW;)i.shift();if(i.length===1)return t;let s=0,a=0,r=0;for(const o of i)s+=o.x,a+=o.y,r+=o.z;return{x:s/i.length,y:a/i.length,z:r/i.length}}_smoothRotation(e,t){const i=this._getOrCreateSmoothingBuffer(e).rotations;for(i.push({x:t.x,y:t.y,z:t.z,w:t.w});i.length>this.SMOOTHING_WINDOW;)i.shift();if(i.length<3)return t;const s=Math.floor(i.length/2);return i[s]}resetSmoothingBuffers(){this.positionBuffers={},this.rotationBuffers={},this._lowPassState.clear()}_findKeyframeIndex(e,t,i=0){if(!e||e.length===0)return-1;if(t<=e[0].time)return 0;if(t>=e[e.length-1].time)return e.length-2;let s=Math.max(0,Math.min(i,e.length-2));if(e[s].time<=t&&e[s+1].time>t)return s;if(s+2t)return s+1;let a=0,r=e.length-2;for(;a<=r;){const o=Math.floor((a+r)/2);if(e[o].time<=t&&e[o+1].time>t)return o;e[o].time>t?r=o-1:a=o+1}return Math.max(0,Math.min(a,e.length-2))}_applySmoothing(e,t){this._smoothingBuffers.has(e)||this._smoothingBuffers.set(e,[]);const i=this._smoothingBuffers.get(e);for(i.push({x:t.x,y:t.y,z:t.z});i.length>this.smoothingWindowSize;)i.shift();if(i.length===1)return t;let s=0,a=0,r=0;for(const o of i)s+=o.x,a+=o.y,r+=o.z;return{x:s/i.length,y:a/i.length,z:r/i.length}}_applyEmaSmoothing(e,t){const i=`ema-${e}`;if(!this._smoothingBuffers.has(i))return this._smoothingBuffers.set(i,{x:t.x,y:t.y,z:t.z}),t;const s=this._smoothingBuffers.get(i),a=Math.max(.05,Math.min(.5,1/this.smoothingWindowSize)),r={x:a*t.x+(1-a)*s.x,y:a*t.y+(1-a)*s.y,z:a*t.z+(1-a)*s.z};return this._smoothingBuffers.set(i,r),r}_applyDoubleEmaSmoothing(e,t){const i=`dema-${e}`;if(!this._smoothingBuffers.has(i))return this._smoothingBuffers.set(i,{level:{x:t.x,y:t.y,z:t.z},trend:{x:0,y:0,z:0}}),t;const s=this._smoothingBuffers.get(i),a=Math.max(.1,Math.min(.6,2/this.smoothingWindowSize)),r=a*.5,o={x:a*t.x+(1-a)*(s.level.x+s.trend.x),y:a*t.y+(1-a)*(s.level.y+s.trend.y),z:a*t.z+(1-a)*(s.level.z+s.trend.z)},l={x:r*(o.x-s.level.x)+(1-r)*s.trend.x,y:r*(o.y-s.level.y)+(1-r)*s.trend.y,z:r*(o.z-s.level.z)+(1-r)*s.trend.z};return s.level=o,s.trend=l,{x:o.x+l.x,y:o.y+l.y,z:o.z+l.z}}_applyWeightedSmoothing(e,t){const i=`wma-${e}`;this._smoothingBuffers.has(i)||this._smoothingBuffers.set(i,[]);const s=this._smoothingBuffers.get(i);for(s.push({x:t.x,y:t.y,z:t.z});s.length>this.smoothingWindowSize;)s.shift();if(s.length===1)return t;let a=0,r=0,o=0,l=0;for(let c=0;cthis.smoothingWindowSize;)s.shift();if(s.length===1)return t;const a=s.length/3;let r=0,o=0,l=0,c=0;for(let u=0;u.001&&(s.derivedVel={x:(t.x-s.lastPos.x)/a,y:(t.y-s.lastPos.y)/a,z:(t.z-s.lastPos.z)/a});const r=Math.sqrt(s.derivedVel.x**2+s.derivedVel.y**2+s.derivedVel.z**2),o=2,l=this.smoothingWindowSize,c=300,u=1500;let d;if(ru)d=o;else{const _=(r-c)/(u-c);d=Math.round(l-_*(l-o))}if(s.buffer.length>=2){const _=s.buffer[s.buffer.length-1],m=s.buffer[s.buffer.length-2],v={x:_.x-m.x,y:_.y-m.y,z:_.z-m.z},y={x:t.x-_.x,y:t.y-_.y,z:t.z-_.z},b=Math.sqrt(v.x**2+v.y**2+v.z**2),T=Math.sqrt(y.x**2+y.y**2+y.z**2);if(b>.1&&T>.1&&(v.x*y.x+v.y*y.y+v.z*y.z)/(b*T)<.5)for(;s.buffer.length>Math.max(2,d/2);)s.buffer.shift()}for(s.buffer.push({x:t.x,y:t.y,z:t.z});s.buffer.length>d;)s.buffer.shift();if(s.lastPos={x:t.x,y:t.y,z:t.z},s.lastTime=i,s.buffer.length===1)return t;let h=0,f=0,p=0,g=0;for(let _=0;_u+10&&(h.z=t.position.z+t.velocity.z*r-.5*c*r*r,h.zu+10&&(p.z=t.position.z+t.velocity.z*o-.5*c*o*o,p.z0&&o>0){const b=d*o;m>b*2&&(v=b*2/m)}const y=_*v+(1-v)*l;return{x:h.x+g.x*y,y:h.y+g.y*y,z:h.z+g.z*y}}_physicsTickInterpolate(e,t,i){const s=t.time-e.time,a=i-e.time,r=a/s;if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};const o=(e.velocity.x+t.velocity.x)/2,l=(e.velocity.y+t.velocity.y)/2,c=(e.velocity.z+t.velocity.z)/2,u=e.position.x+o*a,d=e.position.y+l*a,h=e.position.z+c*a,f=e.position.x+o*s,p=e.position.y+l*s,g=e.position.z+c*s,_=t.position.x-f,m=t.position.y-p,v=t.position.z-g;return{x:u+_*r,y:d+m*r,z:h+v*r}}_velocityOnlyInterpolate(e,t,i){const s=i-e.time,a=t.time-e.time,r=s/a;if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};const o=e.velocity.x+(t.velocity.x-e.velocity.x)*r/2,l=e.velocity.y+(t.velocity.y-e.velocity.y)*r/2,c=e.velocity.z+(t.velocity.z-e.velocity.z)*r/2;return{x:e.position.x+o*s,y:e.position.y+l*s,z:e.position.z+c*s}}_smartHybridInterpolate(e,t,i){const s=i-e.time,a=t.time-e.time,r=Math.max(0,Math.min(1,s/a));if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};const o=Math.sqrt(e.velocity.x**2+e.velocity.y**2+e.velocity.z**2),l=Math.sqrt(t.velocity.x**2+t.velocity.y**2+t.velocity.z**2);let c=1;o>10&&l>10&&(c=(e.velocity.x*t.velocity.x+e.velocity.y*t.velocity.y+e.velocity.z*t.velocity.z)/(o*l));const u=o>10?Math.abs(l-o)/o:0;if(c<.95||u>.1){const h=r*r*(3-2*r);return{x:e.position.x+(t.position.x-e.position.x)*h,y:e.position.y+(t.position.y-e.position.y)*h,z:e.position.z+(t.position.z-e.position.z)*h}}else{const h=(e.velocity.x+t.velocity.x)/2,f=(e.velocity.y+t.velocity.y)/2,p=(e.velocity.z+t.velocity.z)/2,g=e.position.x+h*s,_=e.position.y+f*s,m=e.position.z+p*s,v=e.position.x+h*a,y=e.position.y+f*a,b=e.position.z+p*a,T=t.position.x-v,x=t.position.y-y,M=t.position.z-b;return{x:g+T*r,y:_+x*r,z:m+M*r}}}_isBadFrame(e,t){if(!e.velocity||!t.velocity||!e.position||!t.position)return!1;const i=t.time-e.time;if(i<.001)return!1;const s=(e.velocity.x+t.velocity.x)/2,a=(e.velocity.y+t.velocity.y)/2,r=(e.velocity.z+t.velocity.z)/2,o=Math.sqrt(s**2+a**2+r**2);if(o<200)return!1;const l=t.position.x-e.position.x,c=t.position.y-e.position.y,u=t.position.z-e.position.z,d=Math.sqrt(l*l+c*c+u*u),h=o*i,f=d/h;return f<.6||f>1.4}_filterBadFrames(e){if(!e||e.length<2)return e;const t=[e[0]];for(let i=1;i0&&a.position&&a.velocity){const o=e[s-1];if(o.position&&o.velocity){const l=a.time-o.time;if(l>.001){const c=(o.velocity.x+a.velocity.x)/2,u=(o.velocity.y+a.velocity.y)/2,d=(o.velocity.z+a.velocity.z)/2,h=Math.sqrt(c**2+u**2+d**2);if(h>100){const f=a.position.x-o.position.x,p=a.position.y-o.position.y,g=a.position.z-o.position.z,_=Math.sqrt(f*f+p*p+g*g),m=h*l,v=_/m;let y=0;v>.15&&v<.35?y=l*.75:v>.4&&v<.6?y=l*.5:v>.65&&v<.85&&(y=l*.25),y>0&&(r.position.x+=a.velocity.x*y,r.position.y+=a.velocity.y*y,r.position.z+=a.velocity.z*y,i++)}}}}t.push(r)}return t._correctedCount=i,t}_timeShiftedInterpolate(e,t,i){const s=i-e.time,a=t.time-e.time,r=Math.max(0,Math.min(1,s/a));return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r}}_velocityAnchoredInterpolate(e,t,i,s,a,r){if(!t.velocity||!i.velocity){const m=(s-t.time)/(i.time-t.time);return{x:t.position.x+(i.position.x-t.position.x)*m,y:t.position.y+(i.position.y-t.position.y)*m,z:t.position.z+(i.position.z-t.position.z)*m}}this._velocityAnchorState||(this._velocityAnchorState=new Map);let o=this._velocityAnchorState.get(e);(!o||Math.abs(s-o.lastTime)>.5||r%10===0)&&(o={anchorPos:{...t.position},anchorTime:t.time,anchorIdx:r,lastTime:s},this._velocityAnchorState.set(e,o)),s-o.anchorTime;let u=o.anchorPos.x,d=o.anchorPos.y,h=o.anchorPos.z;const f=(t.velocity.x+i.velocity.x)/2,p=(t.velocity.y+i.velocity.y)/2,g=(t.velocity.z+i.velocity.z)/2,_=s-t.time;return o.anchorIdx===r?(u=o.anchorPos.x+f*_,d=o.anchorPos.y+p*_,h=o.anchorPos.z+g*_):(u=t.position.x+f*_,d=t.position.y+p*_,h=t.position.z+g*_),o.lastTime=s,{x:u,y:d,z:h}}_hermiteInterpolate(e,t,i){const s=t.time-e.time,a=i-e.time,r=Math.max(0,Math.min(1,a/s)),o={x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};if(!e.velocity||!t.velocity)return o;const l=r*r,c=l*r,u=2*c-3*l+1,d=c-2*l+r,h=-2*c+3*l,f=c-l,p={x:e.velocity.x*s,y:e.velocity.y*s,z:e.velocity.z*s},g={x:t.velocity.x*s,y:t.velocity.y*s,z:t.velocity.z*s},_={x:u*e.position.x+d*p.x+h*t.position.x+f*g.x,y:u*e.position.y+d*p.y+h*t.position.y+f*g.y,z:u*e.position.z+d*p.z+h*t.position.z+f*g.z},m=_.x-o.x,v=_.y-o.y,y=_.z-o.z,b=t.position.x-e.position.x,T=t.position.y-e.position.y,x=t.position.z-e.position.z;return m*m+v*v+y*y>b*b+T*T+x*x?o:_}_physicsSimInterpolate(e,t,i,s=!1){const a=t.time-e.time,r=i-e.time,o=Math.max(0,Math.min(1,r/a));if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*o,y:e.position.y+(t.position.y-e.position.y)*o,z:e.position.z+(t.position.z-e.position.z)*o};const l=-650,c=o*o,u=c*o,d=2*u-3*c+1,h=u-2*c+o,f=-2*u+3*c,p=u-c;let g=e.velocity.y*a,_=t.velocity.y*a;if(s){const m=.5*l*a*a;g+=m*.5,_+=m*.5}return{x:d*e.position.x+h*(e.velocity.x*a)+f*t.position.x+p*(t.velocity.x*a),y:d*e.position.y+h*g+f*t.position.y+p*_,z:d*e.position.z+h*(e.velocity.z*a)+f*t.position.z+p*(t.velocity.z*a)}}getBallPositionAt(e){if(!this.ballTimeline||this.ballTimeline.length<2)return null;const t=this.ballTimeline[0];if(e2e3)return s.sleeping?null:{...s.position};if(s.sleeping)return{...s.position};const d=(e-s.time)/r;let h;switch(this.interpolationMethod){case"catmull-rom":{const f=this.ballTimeline[Math.max(0,i-1)],p=this.ballTimeline[Math.min(this.ballTimeline.length-1,i+2)];f?.position&&p?.position?h=this._catmullRomInterpolate(f.position,s.position,a.position,p.position,d):h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}case"lerp-smooth":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applySmoothing("ball",h);break}case"lerp-ema":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyEmaSmoothing("ball",h);break}case"lerp-dema":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyDoubleEmaSmoothing("ball",h);break}case"lerp-wma":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyWeightedSmoothing("ball",h);break}case"lerp-gauss":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyGaussianSmoothing("ball",h);break}case"one-euro":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyOneEuroFilter("ball",h);break}case"predict-correct":{h=this._predictCorrectInterpolate("ball",s,a,e);break}case"velocity-smooth":{h=this._velocitySmoothInterpolate("ball",s,a,e,!0);break}case"physics-tick":{h=this._physicsTickInterpolate(s,a,e);break}case"hermite":{h=this._hermiteInterpolate(s,a,e);break}case"physics-sim":{const f=this.ballTimelineCorrected;if(f&&f.length>=2){const p=this._findKeyframeIndex(f,e,this.timelineIndicesCorrected.ball);this.timelineIndicesCorrected.ball=p;const g=f[p],_=f[p+1];if(g?.position&&_?.position){h=this._physicsSimInterpolate(g,_,e,!0);break}}h=this._physicsSimInterpolate(s,a,e,!0);break}case"velocity-only":{h=this._velocityOnlyInterpolate(s,a,e);break}case"smart-hybrid":{h=this._smartHybridInterpolate(s,a,e);break}case"time-shifted":{const f=this.ballTimelineFiltered;if(!f||f.length<2){h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}const p=this._findKeyframeIndex(f,e,this.timelineIndicesFiltered.ball);this.timelineIndicesFiltered.ball=p;const g=f[p],_=f[p+1];if(!g?.position||!_?.position){h=g?.position?{...g.position}:{...s.position};break}const m=_.time-g.time,v=m>0?Math.max(0,Math.min(1,(e-g.time)/m)):0;h={x:g.position.x+(_.position.x-g.position.x)*v,y:g.position.y+(_.position.y-g.position.y)*v,z:g.position.z+(_.position.z-g.position.z)*v};break}case"position-lerp":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}case"position-catmull":{const f=this.ballTimeline[Math.max(0,i-1)],p=this.ballTimeline[Math.min(this.ballTimeline.length-1,i+2)];f?.position&&p?.position?h=this._catmullRomInterpolate(f.position,s.position,a.position,p.position,d):h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}case"position-smooth":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyLowPassFilter("ball",h);break}case"adaptive-smooth":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyAdaptiveSmoothing("ball",h,e);break}default:{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}}return h}getBallRotationAt(e){if(!this.ballTimeline||this.ballTimeline.length<2)return null;const t=this.ballTimeline[0];if(e2e3)return{...s.rotation}}if(s.sleeping)return{...s.rotation};const o=(e-s.time)/r;return this._q0.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w),this._q1.set(a.rotation.x,a.rotation.y,a.rotation.z,a.rotation.w),this._qResult.slerpQuaternions(this._q0,this._q1,o),{x:this._qResult.x,y:this._qResult.y,z:this._qResult.z,w:this._qResult.w}}getPlayerPositionAt(e,t){const i=this.playerTimelineMap[e];if(!i||i.length<2)return null;const s=i[0];if(t=2){const h=this._findKeyframeIndex(d,t,this.timelineIndicesCorrected.players[e]||0);this.timelineIndicesCorrected.players[e]=h;const f=d[h],p=d[h+1];if(f?.position&&p?.position){u=this._physicsSimInterpolate(f,p,t,!1);break}}u=this._physicsSimInterpolate(r,o,t,!1);break}case"velocity-only":{u=this._velocityOnlyInterpolate(r,o,t);break}case"smart-hybrid":{u=this._smartHybridInterpolate(r,o,t);break}case"time-shifted":{const d=this.playerTimelineMapFiltered[e];if(!d||d.length<2){u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}const h=this._findKeyframeIndex(d,t,this.timelineIndicesFiltered.players[e]||0);this.timelineIndicesFiltered.players[e]=h;const f=d[h],p=d[h+1];if(!f?.position||!p?.position){u=f?.position?{...f.position}:{...r.position};break}const g=p.time-f.time,_=g>0?Math.max(0,Math.min(1,(t-f.time)/g)):0;u={x:f.position.x+(p.position.x-f.position.x)*_,y:f.position.y+(p.position.y-f.position.y)*_,z:f.position.z+(p.position.z-f.position.z)*_};break}case"position-lerp":{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}case"position-catmull":{const d=i[Math.max(0,a-1)],h=i[Math.min(i.length-1,a+2)];d?.position&&h?.position?u=this._catmullRomInterpolate(d.position,r.position,o.position,h.position,c):u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}case"position-smooth":{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c},u=this._applyLowPassFilter(`player-${e}`,u);break}case"adaptive-smooth":{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c},u=this._applyAdaptiveSmoothing(`player-${e}`,u,t);break}default:{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}}return u}getPlayerRotationAt(e,t){const i=this.playerTimelineMap[e];if(!i||i.length<2)return null;const s=i[0];if(t=2){const r=this.getBallPositionAt(t),o=this.getBallRotationAt(t);r?i.position.set(r.x,r.y,r.z):a=!1,o&&i.quaternion.set(o.x,o.y,o.z,o.w)}else i.position.set(s.position.x,s.position.y,s.position.z),i.quaternion.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w);if(i.userData.location.copy(i.position),i.userData.rotation.copy(i.quaternion),i.userData.velocity.set(s.velocity.x,s.velocity.y,s.velocity.z),s.angularVelocity&&i.userData.angularVelocity.set(s.angularVelocity.x,s.angularVelocity.y,s.angularVelocity.z),i.userData.sleeping=s.sleeping,i.visible=a&&s.visible!==!1&&!i.userData.isHiddenByGoal,this.ballIndicator&&(this.ballIndicator.position.set(i.position.x,2,i.position.z),this.ballIndicator.visible=i.visible),this.ballVerticalLine){const o=new Float32Array([i.position.x,2,i.position.z,i.position.x,i.position.y,i.position.z]);this.ballVerticalLine.geometry.setAttribute("position",new rt(o,3)),this.ballVerticalLine.geometry.attributes.position.needsUpdate=!0,this.ballVerticalLine.visible=i.visible}if(i.userData.velocity&&i.visible){let r=this.lastBallTouchTeam,o=this.BALL_TOUCH_DISTANCE;Object.keys(this.actors).forEach(l=>{const c=this.actors[l];if(c&&c.userData.isCar&&c.userData.playerId){const u=i.position.distanceTo(c.position);u{const a=this.playerNameToCarActorId[s.name];if(!a)return;const r=this.actors[a];if(!r)return;const o=s.name;if(!this.useAnimationSystem||!this.animationMixer)if(this.interpolantsInitialized&&this.playerTimelineMap[o]){const c=this.getPlayerPositionAt(o,t),u=this.getPlayerRotationAt(o,t);c&&r.position.set(c.x,c.y,c.z),u&&r.quaternion.set(u.x,u.y,u.z,u.w)}else r.position.set(s.position.x,s.position.y,s.position.z),r.quaternion.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w);r.userData.location.copy(r.position),r.userData.rotation.copy(r.quaternion),r.userData.velocity.set(s.velocity.x,s.velocity.y,s.velocity.z),r.userData.sleeping=s.sleeping,r.userData.steer=s.steer||0;const l=r.position.length()>.1;r.visible=s.isVisible&&l&&!r.userData.sleeping}),this._updateGoalExplosions(t)}_updateGoalExplosions(e){const t=this.effectsManager,i=t&&t.explosions?t.explosions.goalEvents:null;if(!(i instanceof Map)||i.size===0)return;const s=this._lastGoalScanTime;s!==null&&e=c&&e<=c+jO&&(r=!0,o=!0),s!==null&&s=c&&!this._firedGoalTimes.has(c)){this._firedGoalTimes.add(c);const d=this.getBallPositionAt(c)||a&&a.position||null;d&&this.effectsManager.triggerGoalExplosion(d,l.team)}}a&&(a.userData.isHiddenByGoal=r,r&&(a.visible=!1)),o||this.effectsManager.clearGoalExplosions?.(),this._lastGoalScanTime=e}processFrame(e,t,i,s){if(e){if(e.new_actors&&e.new_actors.forEach(a=>{if(!this.actors[a.actor_id]){const r=t(a.object_id),o=r&&r.includes("Ball"),l=r&&r.includes("Car");if(o||l){let c;o?c=new yn(92.75,16,16):c=new Ei(118,36,84);const u=new Pn({color:o?16777215:Math.random()*16777215}),d=new we(c,u);if(d.userData={location:new S,rotation:new dt,isCar:l,isBall:o,playerId:null,lastUpdateTime:e.time,bodyId:null,hasReceivedUpdate:!1},this.scene.add(d),this.actors[a.actor_id]=d,o){this.ballActorId=a.actor_id,this.ballModel&&this.replaceBallWithModel(a.actor_id);const h=92.75,f=new ni(h*.95,h,32),p=new Ye({color:16777215,side:ct});this.ballIndicator=new we(f,p),this.ballIndicator.rotation.x=-Math.PI/2,this.ballIndicator.visible=!1,this.scene.add(this.ballIndicator);const g=new Ge().setFromPoints([new S(0,0,0),new S(0,1,0)]),_=new Rt({color:16777215,opacity:.5,transparent:!0});this.ballVerticalLine=new In(g,_),this.ballVerticalLine.frustumCulled=!1,this.ballVerticalLine.visible=!1,this.scene.add(this.ballVerticalLine)}else l&&this.effectsManager.createBoostTrail(d,a.actor_id)}}}),e.deleted_actors&&e.deleted_actors.forEach(a=>{if(this.actors[a]){const r=this.actors[a];r.userData.isCar&&this.effectsManager.removeBoostTrail(a),this.scene.remove(r),r.geometry&&r.geometry.dispose(),r.material&&r.material.dispose(),delete this.actors[a],this.ballActorId===a&&(this.ballActorId=null,this.ballIndicator&&(this.scene.remove(this.ballIndicator),this.ballIndicator.geometry&&this.ballIndicator.geometry.dispose(),this.ballIndicator.material&&this.ballIndicator.material.dispose(),this.ballIndicator=null),this.ballVerticalLine&&(this.scene.remove(this.ballVerticalLine),this.ballVerticalLine.geometry&&this.ballVerticalLine.geometry.dispose(),this.ballVerticalLine.material&&this.ballVerticalLine.material.dispose(),this.ballVerticalLine=null))}}),e.updated_actors&&e.updated_actors.forEach(a=>{const r=this.actors[a.actor_id];a.attribute.TeamLoadout&&(this.actorLoadouts[a.actor_id]=a.attribute.TeamLoadout,r&&r.userData.isCar&&(r.userData.teamLoadout=a.attribute.TeamLoadout,this.resolveBodyId(r,a.actor_id)));const o=t(a.object_id),l=o&&(o.includes("PRI_TA")||o.includes("PlayerReplicationInfo"));if(a.attribute.String&&this.playerNames.has(a.attribute.String)){const c=a.attribute.String;this.actorToPlayer[a.actor_id]=c,l&&!this.playerNameToPriActorId[c]&&(this.playerNameToPriActorId[c]=a.actor_id,console.log(`[ActorManager] Mapped ${c} -> PRI Actor ${a.actor_id} (object: ${o})`)),this.checkCarPlayerLink(a.actor_id)}if(a.attribute.Reservation&&this.playerNames.has(a.attribute.Reservation.name)){const c=a.attribute.Reservation.name;this.actorToPlayer[a.actor_id]=c,l&&!this.playerNameToPriActorId[c]&&(this.playerNameToPriActorId[c]=a.actor_id,console.log(`[ActorManager] Mapped ${c} -> PRI Actor ${a.actor_id} (object: ${o})`)),this.checkCarPlayerLink(a.actor_id)}if(a.attribute.ActiveActor){const c=a.attribute.ActiveActor.actor;this.actorLinks[a.actor_id]||(this.actorLinks[a.actor_id]=new Set),this.actorLinks[a.actor_id].add(c),r&&r.userData.isCar&&this.checkCarPlayerLink(c,a.actor_id)}if(r&&a.attribute&&a.attribute.RigidBody){const c=a.attribute.RigidBody;if(c.location&&(r.userData.location.set(c.location.x,c.location.z,c.location.y),r.userData.lastUpdateTime=e.time,r.userData.hasReceivedUpdate=!0),c.linear_velocity&&(r.userData.velocity||(r.userData.velocity=new S),r.userData.velocity.set(c.linear_velocity.x,c.linear_velocity.z,c.linear_velocity.y)),c.rotation&&r.userData.rotation.set(c.rotation.x,c.rotation.z,c.rotation.y,-c.rotation.w),c.angular_velocity&&(r.userData.angularVelocity||(r.userData.angularVelocity=new S),r.userData.angularVelocity.set(c.angular_velocity.x,c.angular_velocity.z,c.angular_velocity.y)),c.sleeping!==void 0&&(r.userData.sleeping=c.sleeping,c.sleeping&&(r.userData.velocity&&r.userData.velocity.set(0,0,0),r.userData.angularVelocity&&r.userData.angularVelocity.set(0,0,0))),r.userData.isBall&&r.userData.isHiddenByGoal&&c.location){const u=c.location.x,d=c.location.y,h=c.location.z;Math.sqrt(u*u+d*d+h*h)<500&&(r.userData.isHiddenByGoal=!1)}}}),this.effectsManager.explosions.goalEvents.has(i)){const a=this.effectsManager.explosions.goalEvents.get(i),r=this.actors[this.ballActorId];r&&(s||(this.effectsManager.triggerGoalExplosion(r.position,a.team),console.log(`🎯 GOAL! Explosion at frame ${i} for team ${a.team} by ${a.playerName}`)),r.userData.isHiddenByGoal=!0)}if(this.effectsManager.explosions.demoEvents.has(i)){const a=this.effectsManager.explosions.demoEvents.get(i),r=this.actors[a.victimActorId];if(r){if(!s){const o=r.userData.playerId,l=o&&this.playerTeams&&this.playerTeams[o]||0;this.effectsManager.triggerDemoExplosion(r.position,l),console.log(`💥 DEMO! Explosion at frame ${i} for actor ${a.victimActorId}`)}r.userData.sleeping=!0}}}}resolveBodyId(e,t){if(!e||!e.userData.isCar||!e.userData.teamLoadout)return;let i=0;e.userData.playerId&&Object.prototype.hasOwnProperty.call(this.playerTeams,e.userData.playerId)&&(i=this.playerTeams[e.userData.playerId]);const s=e.userData.teamLoadout,a=i===1?s.orange?.body:s.blue?.body;a&&e.userData.bodyId!==a&&(e.userData.bodyId=a,this.updateCarHitbox(e,a,t))}updateCarHitbox(e,t,i){const s=bw(t),a=s?.name||"Octane",r=s?.hitboxType||"Octane";this.replaceCarWithModel(i,e,a,r)}async replaceCarWithModel(e,t,i,s){if(this.carModelLoader.isModelReady(i,s))this._doCarReplacement(e,t,i,s);else{this.pendingCarReplacements.set(e,{oldMesh:t,carName:i,hitboxType:s});try{const a=this.carModelLoader.getModelTypeForCar(i,s);await this.carModelLoader.loadModel(a);const r=this.pendingCarReplacements.get(e);r&&this.actors[e]===r.oldMesh&&this._doCarReplacement(e,r.oldMesh,r.carName,r.hitboxType),this.pendingCarReplacements.delete(e)}catch(a){console.warn(`Failed to load model for ${i} (${s}):`,a),this.pendingCarReplacements.delete(e),t&&(t.visible=!0)}}}_doCarReplacement(e,t,i,s){let a=0;t.userData.playerId&&Object.prototype.hasOwnProperty.call(this.playerTeams,t.userData.playerId)?a=this.playerTeams[t.userData.playerId]:t.userData.team!==void 0&&(a=t.userData.team);const r=this.carModelLoader.getCarMeshSync(i,s,a);if(!r){console.warn(`Could not get car mesh for ${i} (${s})`);return}const o=r.userData.wheels;r.userData={...t.userData},r.userData.isFBXModel=!0,r.userData.carName=i,r.userData.hitboxType=s,r.userData.wheels=o,r.position.copy(t.position),r.quaternion.copy(t.quaternion),this.scene.remove(t),t.geometry&&t.geometry.dispose(),t.material&&(Array.isArray(t.material)?t.material.forEach(c=>c.dispose()):t.material.dispose()),this.scene.add(r),this.actors[e]=r,this.effectsManager.removeBoostTrail(e),this.effectsManager.createBoostTrail(r,e);const l=this.carModelLoader.getModelTypeForCar(i,s);console.log(`🚗 Replaced car ${e} with ${l.toUpperCase()} model (${i}, ${s} hitbox, team ${a===0?"blue":"orange"})`)}checkCarPlayerLink(e,t){const i=this.actorToPlayer[e],s=this.actorLoadouts[e];if(!(!i&&!s))if(t){const a=this.actors[t];a&&a.userData.isCar&&(this.onPlayerFound&&this.onPlayerFound(i),a.userData.playerId=i,this.playerNameToCarActorId[i]=t,s&&(a.userData.teamLoadout=s),this.resolveBodyId(a,t))}else this.actorLinks[e]&&this.actorLinks[e].forEach(a=>{this.checkCarPlayerLink(e,a)})}updateInterpolation(e,t,i){const s=t[i];if(s&&Object.keys(this.actors).forEach(a=>{const r=this.actors[a],o=r.userData.location,l=r.userData.rotation;if(!o||!l||!r.userData.hasReceivedUpdate)return;let c=null,u=0;for(let d=i+1;dp.actor_id==a&&p.attribute&&p.attribute.RigidBody);if(f){c=f,u=h.time;break}}}if(c){const d=r.userData.lastUpdateTime||s.time,h=u;if(h>d){const f=(e-d)/(h-d),p=Math.max(0,Math.min(1,f)),g=h-d||.033,_=c.attribute.RigidBody;if(_.location)if(this._p0.copy(o),this._p1.set(_.location.x,_.location.z,_.location.y),r.userData.sleeping)r.position.copy(o);else{const m=c.attribute.RigidBody;if(r.userData.velocity&&m.linear_velocity){const v=p,y=v*v,b=y*v;if(g>.5)r.position.lerpVectors(o,this._p1,p);else{this._v0.copy(r.userData.velocity).multiplyScalar(g),this._v1.set(m.linear_velocity.x,m.linear_velocity.z,m.linear_velocity.y).multiplyScalar(g);const T=2*b-3*y+1,x=b-2*y+v,M=-2*b+3*y,C=b-y;r.position.set(T*this._p0.x+x*this._v0.x+M*this._p1.x+C*this._v1.x,T*this._p0.y+x*this._v0.y+M*this._p1.y+C*this._v1.y,T*this._p0.z+x*this._v0.z+M*this._p1.z+C*this._v1.z)}}else r.position.lerpVectors(o,this._p1,p)}else r.position.copy(o);_.rotation?(this._nextRot.set(_.rotation.x,_.rotation.z,_.rotation.y,-_.rotation.w),r.quaternion.slerpQuaternions(l,this._nextRot,p)):r.quaternion.copy(l);return}}r.position.copy(o),r.quaternion.copy(l)}),Object.keys(this.actors).forEach(a=>{const r=this.actors[a];if(r&&r.userData.isCar){const l=r.position.length()>.1,c=r.userData.sleeping===!0;r.visible=l&&!c}}),this.ballActorId&&this.actors[this.ballActorId]){const a=this.actors[this.ballActorId];if(a.visible=!a.userData.isHiddenByGoal,this.ballIndicator&&(this.ballIndicator.position.set(a.position.x,2,a.position.z),this.ballIndicator.visible=a.visible),this.ballVerticalLine){const o=new Float32Array([a.position.x,2,a.position.z,a.position.x,a.position.y,a.position.z]);this.ballVerticalLine.geometry.setAttribute("position",new rt(o,3)),this.ballVerticalLine.geometry.attributes.position.needsUpdate=!0,this.ballVerticalLine.visible=a.visible}if(a.userData.velocity&&a.visible){let r=this.lastBallTouchTeam,o=this.BALL_TOUCH_DISTANCE;Object.keys(this.actors).forEach(l=>{const c=this.actors[l];if(c&&c.userData.isCar&&c.userData.playerId){const u=a.position.distanceTo(c.position);if(u{const s=this.actors[i];if(!s||!s.userData.isCar||!s.userData.isFBXModel&&!s.userData.hasWheelSockets||!s.userData.wheels||s.userData.wheels.length===0)return;const a=s.position;let r=this._previousCarPositions.get(i);r||(r=a.clone(),this._previousCarPositions.set(i,r));const l=new S().subVectors(a,r).length();if(this._previousCarPositions.set(i,a.clone()),l<.01)return;const d=Math.min(l/e,.5)*1;let h=0;s.userData.steer!==void 0&&(h=-s.userData.steer*t),s.userData.wheels.forEach(f=>{if(f.socket){const p=f.side==="left"?1:-1;if(f.mesh.rotateZ(p*d),f.position==="front"&&f.steeringPivot){const g=f.side==="left"?-1:1;f.steeringPivot.rotation.y=g*h}}else{const p=f.side==="left"?-1:1;f.mesh.rotateY(p*d),f.position==="front"&&f.steeringPivot&&(f.steeringPivot.rotation.z=h)}})})}resetWheelTracking(){this._previousCarPositions&&this._previousCarPositions.clear()}updateSupersonicState(e,t,i){const s=this.playerNameToCarActorId[e];if(!s)return;const a=this.actors[s];if(!a||!a.userData.isCar)return;const r=a.userData.velocity||new S(0,0,0);this.effectsManager.updateSupersonicTrail(s,t,a.position,a.quaternion,r,i)}setInterpolationEnabled(e){this.interpolationEnabled=e,console.log(`[ActorManager] Interpolation ${e?"enabled":"disabled"}`)}setInterpolationMethod(e){if(!["lerp","hermite","catmull-rom","predict-correct","velocity-smooth","physics-tick","velocity-only","smart-hybrid","time-shifted","lerp-smooth","lerp-ema","lerp-dema","lerp-wma","lerp-gauss","one-euro","position-lerp","position-catmull","position-smooth","adaptive-smooth"].includes(e)){console.warn(`[ActorManager] Invalid interpolation method: ${e}`);return}this.interpolationMethod=e,this._smoothingBuffers.clear(),this._lowPassState.clear(),this._adaptiveState.clear(),this.resetSmoothingBuffers(),console.log(`[ActorManager] Interpolation method set to: ${e}`)}setSmoothingWindowSize(e){this.smoothingWindowSize=Math.max(1,Math.min(20,e)),this._smoothingBuffers.clear(),console.log(`[ActorManager] Smoothing window size set to: ${this.smoothingWindowSize}`)}getInterpolationSettings(){return{enabled:this.interpolationEnabled,method:this.interpolationMethod,smoothingWindowSize:this.smoothingWindowSize}}clearSmoothingBuffers(){this._smoothingBuffers.clear()}getFrameInfo(){return this.lastFrameInfo}createBallMeshForLive(){const e=new yn(92.75,16,16),t=new Pn({color:16777215}),i=new we(e,t);if(i.castShadow=!0,i.receiveShadow=!0,i.userData={location:new S,rotation:new dt,velocity:new S,angularVelocity:new S,isCar:!1,isBall:!0,playerId:null,sleeping:!1,isHiddenByGoal:!1},this.scene.add(i),this.ballModel){const s=this.ballModel.clone();s.position.copy(i.position),s.quaternion.copy(i.quaternion),s.userData={...i.userData};const a=92.75;return s.scale.set(a,a,a),s.traverse(r=>{r.isMesh&&(r.castShadow=!0,r.receiveShadow=!0)}),this.scene.remove(i),this.scene.add(s),i.geometry&&i.geometry.dispose(),i.material&&i.material.dispose(),console.log("✓ Live ball created with GLTF model"),s}return i}createCarMeshForLive(e,t,i,s=null){const a=`live_car_${t}`,r=new Ei(118,36,84),o=e===0?3381759:16737792,l=new Pn({color:o}),c=new we(r,l);return c.castShadow=!0,c.receiveShadow=!0,c.visible=!1,c.userData={location:new S,rotation:new dt,velocity:new S,angularVelocity:new S,isCar:!0,isBall:!1,playerId:i,team:e,sleeping:!1,steer:0,bodyId:s,liveActorId:a},this.scene.add(c),this.actors[a]=c,this.playerNameToCarActorId[i]=a,this.effectsManager.createBoostTrail(c,a),s&&s>0?this.updateCarHitbox(c,s,a):this.replaceCarWithModel(a,c,"Octane","Octane"),console.log(`[ActorManager] Created live car for ${i} (team ${e===0?"blue":"orange"}, bodyId: ${s})`),c}updateBoostParticlesLive(e,t,i,s){const a=t&&i>0,r=s.userData.velocity||new S(0,0,0);this.effectsManager.updateBoostTrail(e,a,s.position,s.quaternion,r)}updateSupersonicTrailLive(e,t,i,s){const a=s.userData.velocity||new S(0,0,0);this.effectsManager.updateSupersonicTrail(e,t,s.position,s.quaternion,a,i)}removeLiveCar(e){const t=this.actors[e];t&&(this.scene.remove(t),t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose(),delete this.actors[e],this.effectsManager.removeBoostTrail(e))}removeLiveBall(e){e&&(this.scene.remove(e),e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose())}}function Ms(n,e,t){t===-1?(n.clearUpdateRanges?.(),n.addUpdateRange?.(0,n.count*n.itemSize)):n.addUpdateRange?(n.clearUpdateRanges(),n.addUpdateRange(e,t)):(n.updateRange.offset=e,n.updateRange.count=t)}class pt extends Qe{constructor(e,t){super(),this.active=!1,this.orientToMovement=!1,t&&(this.orientToMovement=!0),this.scene=e,this.geometry=null,this.mesh=null,this.nodeCenters=null,this.lastNodeCenter=null,this.currentNodeCenter=null,this.lastOrientationDir=null,this.nodeIDs=null,this.currentLength=0,this.currentEnd=0,this.currentNodeID=0,this.advanceFrequency=60,this.advancePeriod=1/this.advanceFrequency,this.lastAdvanceTime=0,this.paused=!1,this.pauseAdvanceUpdateTimeDiff=0,this._internalTime=0,this._useInternalTime=!1}setAdvanceFrequency(e){this.advanceFrequency=e,this.advancePeriod=1/this.advanceFrequency}initialize(e,t,i,s,a,r){this.deactivate(),this.destroyMesh(),this.length=t>0?t+1:0,this.dragTexture=i?1:0,this.targetObject=r,this.initializeLocalHeadGeometry(s,a),this.nodeIDs=[],this.nodeCenters=[];for(let o=0;o=this.length?0:this.currentEnd+1;if(i?this.updateNodePositionsFromTransformMatrix(s,i):this.updateNodePositionsFromOrientationTangent(s,t.position,t.tangent),this.currentLength>=1&&(this.connectNodes(this.currentEnd,s),this.currentLength>=this.length)){const a=this.currentEnd+1>=this.length?0:this.currentEnd+1;this.disconnectNodes(a)}this.currentLength=this.length&&(this.currentEnd=0),this.currentLength>=1&&(this.currentLengththis.advancePeriod?(this.advance(),this.lastAdvanceTime=t):this.updateHead()}}updateHead=(function(){const e=new Me;return function(){this.currentEnd<0||(this.targetObject.updateMatrixWorld(),e.copy(this.targetObject.matrixWorld),this.updateNodePositionsFromTransformMatrix(this.currentEnd,e))}})();updateNodeID(e,t){this.nodeIDs[e]=t;const i=this.geometry.getAttribute("nodeID"),s=this.geometry.getAttribute("nodeVertexID");for(let a=0;a1e-4)){this.lastOrientationDir||(this.lastOrientationDir=new S),t.setFromUnitVectors(a,r),s.copy(this.currentNodeCenter);for(let f=0;f=7?(fu.setRGB(parseFloat(d[4]),parseFloat(d[5]),parseFloat(d[6]),gt),t.colors.push(fu.r,fu.g,fu.b)):t.colors.push(void 0,void 0,void 0);break;case"vn":t.normals.push(parseFloat(d[1]),parseFloat(d[2]),parseFloat(d[3]));break;case"vt":t.uvs.push(parseFloat(d[1]),parseFloat(d[2]));break}}else if(u==="f"){const h=c.slice(1).trim().split(tv),f=[];for(let g=0,_=h.length;g<_;g++){const m=h[g];if(m.length>0){const v=m.split("/");f.push(v)}}const p=f[0];for(let g=1,_=f.length-1;g<_;g++){const m=f[g],v=f[g+1];t.addFace(p[0],m[0],v[0],p[1],m[1],v[1],p[2],m[2],v[2])}}else if(u==="l"){const d=c.substring(1).trim().split(" ");let h=[];const f=[];if(c.indexOf("/")===-1)h=d;else for(let p=0,g=d.length;p1){const h=s[1].trim().toLowerCase();t.object.smooth=h!=="0"&&h!=="off"}else t.object.smooth=!0;const d=t.object.currentMaterial();d&&(d.smooth=t.object.smooth)}else{if(c==="\0")continue;console.warn('THREE.OBJLoader: Unexpected line: "'+c+'"')}}t.finalize();const a=new Mt;if(a.materialLibraries=[].concat(t.materialLibraries),!(t.objects.length===1&&t.objects[0].geometry.vertices.length===0)===!0)for(let o=0,l=t.objects.length;o0&&g.setAttribute("normal",new Ee(u.normals,3)),u.colors.length>0&&(p=!0,g.setAttribute("color",new Ee(u.colors,3))),u.hasUVIndices===!0&&g.setAttribute("uv",new Ee(u.uvs,2));const _=[];for(let v=0,y=d.length;v1){for(let v=0,y=d.length;v0){const o=new aa({size:1,sizeAttenuation:!1}),l=new Ge;l.setAttribute("position",new Ee(t.vertices,3)),t.colors.length>0&&t.colors[0]!==void 0&&(l.setAttribute("color",new Ee(t.colors,3)),o.vertexColors=!0);const c=new sr(l,o);a.add(c)}return a}}const _p=new Map;async function gO(n,e){const t=Si("models/stadium/stadium.glb",e);let i=_p.get(t);return i||(i=n.loadAsync(t).then(s=>{const a=s.scene;return yO(a),a}).catch(s=>{throw _p.delete(t),s}),_p.set(t,i)),i}function yO(n){const e=["Sol_Trait_T0","Sol_Trait_T1","Milieu_Forme","Milieu_Forme.001","cage_T0","cage_T1","Couleur_Hexagone_T0","Couleur_Hexagone_T1","wall_gradient_color_2","wall_gradient_color_2.001","Fond_BackBoard_Transparent","dégradé_transparent_T0","dégradé_transparent_T1","grid_transperant","Detail_Milieu","Detail_Milieu.001"],t=["Glow","Glass"],i=["Plafond_Hexagone_T0","Plafond_Hexagone_T1","Plafond_Transparent"];n.traverse(s=>{if(!s.isMesh)return;s.receiveShadow=!0,s.castShadow=!i.includes(s.name),t.some(r=>s.name.includes(r))&&(console.log(`[ArenaManager] Disabling frustum culling for: ${s.name}`),s.frustumCulled=!1),s.material&&/^Hexagone_T[01]$/.test(s.material.name??"")&&(s.material=s.material.clone(),s.material.transparent=!0,s.material.opacity=.18,s.material.depthWrite=!1,s.renderOrder=1),s.material&&s.material.name==="bannière_pub"&&(s.visible=!1),s.material&&s.material.name==="Sol_Hexagone"&&(s.material=s.material.clone(),s.material.color.setScalar(.35),s.material.metalness=0,s.material.roughness=1),s.material&&s.material.name&&e.includes(s.material.name)&&(console.log(`[ArenaManager] Fixing visibility for: ${s.name} (material: ${s.material.name})`),s.material=s.material.clone(),s.material.side=ct,s.material.depthWrite=!1,s.renderOrder=1,s.frustumCulled=!1)})}class vO{constructor(e,t={}){this.scene=e,this.assetBase=t.assetBase,this.arenaMeshes=[],this.drawingCollider=null,this.drawingColliderMeshes=[],this.arenaDecorMesh=null,this.showArenaDecor=!0,this.dracoLoader=new bT,this.dracoLoader.setDecoderPath(Si("draco/",this.assetBase)),this.gltfLoader=new Og,this.gltfLoader.setDRACOLoader(this.dracoLoader)}async loadArenaMeshes(){try{console.log("Loading arena mesh...");const t=(await gO(this.gltfLoader,this.assetBase)).clone(!0);t.traverse(i=>{i.isMesh&&this.arenaMeshes.push(i)}),console.log(`[ArenaManager] Collected ${this.arenaMeshes.length} meshes for raycasting`),this.scene.add(t),console.log("Arena mesh loaded successfully with correct orientation")}catch(e){console.error("Error loading arena mesh:",e);const t=new kn(10240,8192),i=new Pn({color:3355443,side:ct}),s=new we(t,i);s.rotation.x=-Math.PI/2,s.receiveShadow=!0,this.scene.add(s),this.arenaMeshes.push(s)}}getArenaMeshes(){return this.arenaMeshes}getDrawingColliderMeshes(){return this.drawingColliderMeshes}async loadDrawingCollider(e=!1){try{console.log("[ArenaManager] Loading drawing collider...");const i=await new _O().loadAsync(Si("models/stadium/DrawingArena.obj",this.assetBase));i.rotation.x=Math.PI/2,i.rotation.y=Math.PI,i.scale.setScalar(.99),i.position.y=20,i.traverse(s=>{s.isMesh&&(this.drawingColliderMeshes.push(s),s.castShadow=!1,s.receiveShadow=!1,e?s.material=new Ye({color:65280,transparent:!0,opacity:.7,side:ct}):s.material=new Ye({visible:!1}))}),this.drawingCollider=i,this.scene.add(i),console.log(`[ArenaManager] Drawing collider loaded with ${this.drawingColliderMeshes.length} meshes`)}catch(t){console.error("[ArenaManager] Failed to load drawing collider:",t)}}setDrawingColliderVisible(e){for(const t of this.drawingColliderMeshes)e?t.material=new Ye({color:65280,wireframe:!0,transparent:!0,opacity:.5}):t.material=new Ye({visible:!1})}async loadArenaDecor(e=!0){try{console.log("[ArenaManager] Loading arena decoration mesh...");const t=await this.gltfLoader.loadAsync(Si("models/stadium/arene.glb",this.assetBase));this.arenaDecorMesh=t.scene,this.showArenaDecor=e,this.arenaDecorMesh.traverse(i=>{i.isMesh&&(i.receiveShadow=!0,i.castShadow=!0)}),this.arenaDecorMesh.visible=e,this.scene.add(this.arenaDecorMesh),console.log(`[ArenaManager] Arena decoration loaded, visible: ${e}`)}catch(t){console.error("[ArenaManager] Failed to load arena decoration:",t)}}setArenaDecorVisible(e){this.showArenaDecor=e,this.arenaDecorMesh&&(this.arenaDecorMesh.visible=e,console.log(`[ArenaManager] Arena decoration visibility set to: ${e}`))}isArenaDecorVisible(){return this.showArenaDecor}}var Ti=Uint8Array,Qr=Uint16Array,bO=Int32Array,xT=new Ti([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),wT=new Ti([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),xO=new Ti([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ST=function(n,e){for(var t=new Qr(31),i=0;i<31;++i)t[i]=e+=1<>1|(Nt&21845)<<1;js=(js&52428)>>2|(js&13107)<<2,js=(js&61680)>>4|(js&3855)<<4,zm[Nt]=((js&65280)>>8|(js&255)<<8)>>1}var Dl=(function(n,e,t){for(var i=n.length,s=0,a=new Qr(e);s>l]=c}else for(o=new Qr(i),s=0;s>15-n[s]);return o}),_c=new Ti(288);for(var Nt=0;Nt<144;++Nt)_c[Nt]=8;for(var Nt=144;Nt<256;++Nt)_c[Nt]=9;for(var Nt=256;Nt<280;++Nt)_c[Nt]=7;for(var Nt=280;Nt<288;++Nt)_c[Nt]=8;var ET=new Ti(32);for(var Nt=0;Nt<32;++Nt)ET[Nt]=5;var MO=Dl(_c,9,1),EO=Dl(ET,5,1),gp=function(n){for(var e=n[0],t=1;te&&(e=n[t]);return e},Oi=function(n,e,t){var i=e/8|0;return(n[i]|n[i+1]<<8)>>(e&7)&t},yp=function(n,e){var t=e/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},CO=function(n){return(n+7)/8|0},AO=function(n,e,t){return(t==null||t>n.length)&&(t=n.length),new Ti(n.subarray(e,t))},RO=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Vi=function(n,e,t){var i=new Error(e||RO[n]);if(i.code=n,Error.captureStackTrace&&Error.captureStackTrace(i,Vi),!t)throw i;return i},PO=function(n,e,t,i){var s=n.length,a=0;if(!s||e.f&&!e.l)return t||new Ti(0);var r=!t,o=r||e.i!=2,l=e.i;r&&(t=new Ti(s*3));var c=function(xe){var Ae=t.length;if(xe>Ae){var L=new Ti(Math.max(Ae*2,xe));L.set(t),t=L}},u=e.f||0,d=e.p||0,h=e.b||0,f=e.l,p=e.d,g=e.m,_=e.n,m=s*8;do{if(!f){u=Oi(n,d,1);var v=Oi(n,d+1,3);if(d+=3,v)if(v==1)f=MO,p=EO,g=9,_=5;else if(v==2){var x=Oi(n,d,31)+257,M=Oi(n,d+10,15)+4,C=x+Oi(n,d+5,31)+1;d+=14;for(var w=new Ti(C),E=new Ti(19),R=0;R>4;if(y<16)w[R++]=y;else{var F=0,W=0;for(y==16?(W=3+Oi(n,d,3),d+=2,F=w[R-1]):y==17?(W=3+Oi(n,d,7),d+=3):y==18&&(W=11+Oi(n,d,127),d+=7);W--;)w[R++]=F}}var H=w.subarray(0,x),ne=w.subarray(x);g=gp(H),_=gp(ne),f=Dl(H,g,1),p=Dl(ne,_,1)}else Vi(1);else{var y=CO(d)+4,b=n[y-4]|n[y-3]<<8,T=y+b;if(T>s){l&&Vi(0);break}o&&c(h+b),t.set(n.subarray(y,T),h),e.b=h+=b,e.p=d=T*8,e.f=u;continue}if(d>m){l&&Vi(0);break}}o&&c(h+131072);for(var oe=(1<>4;if(d+=F&15,d>m){l&&Vi(0);break}if(F||Vi(2),ke<256)t[h++]=ke;else if(ke==256){Ie=d,f=null;break}else{var Xe=ke-254;if(ke>264){var R=ke-257,De=xT[R];Xe=Oi(n,d,(1<>4;Z||Vi(3),d+=Z&15;var ne=TO[ae];if(ae>3){var De=wT[ae];ne+=yp(n,d)&(1<m){l&&Vi(0);break}o&&c(h+131072);var Se=h+Xe;if(h>4>7||(n[0]<<8|n[1])%31)&&Vi(6,"invalid zlib data"),(n[1]>>5&1)==1&&Vi(6,"invalid zlib data: "+(n[1]&32?"need":"unexpected")+" dictionary"),(n[1]>>3&4)+2};function kO(n,e){return PO(n.subarray(LO(n),-4),{i:2},e,e)}var DO=typeof TextDecoder<"u"&&new TextDecoder,OO=0;try{DO.decode(IO,{stream:!0}),OO=1}catch{}function CT(n,e,t){const i=t.length-n-1;if(e>=t[i])return i-1;if(e<=t[n])return n;let s=n,a=i,r=Math.floor((s+a)/2);for(;e=t[r+1];)e=g&&(p[f][0]=p[h][0]/o[v+1][m],_=p[f][0]*o[m][v]);const y=m>=-1?1:-m,b=d-1<=v?g-1:t-d;for(let x=y;x<=b;++x)p[f][x]=(p[h][x]-p[h][x-1])/o[v+1][m+x],_+=p[f][x]*o[m+x][v];d<=v&&(p[f][g]=-p[h][g-1]/o[v+1][d],_+=p[f][g]*o[d][v]),r[g][d]=_;const T=h;h=f,f=T}}let u=t;for(let d=1;d<=i;++d){for(let h=0;h<=t;++h)r[d][h]*=u;u*=t-d}return r}function BO(n,e,t,i,s){const a=st.toArray()),e.startKnot=this.startKnot,e.endKnot=this.endKnot,e}fromJSON(e){return super.fromJSON(e),this.degree=e.degree,this.knots=[...e.knots],this.controlPoints=e.controlPoints.map(t=>new qe(t[0],t[1],t[2],t[3])),this.startKnot=e.startKnot,this.endKnot=e.endKnot,this}}let _t,Zt,Un;class $O extends on{constructor(e){super(e)}load(e,t,i,s){const a=this,r=a.path===""?Us.extractUrlBase(e):a.path,o=new Gn(this.manager);o.setPath(a.path),o.setResponseType("arraybuffer"),o.setRequestHeader(a.requestHeader),o.setWithCredentials(a.withCredentials),o.load(e,function(l){try{t(a.parse(l,r))}catch(c){s?s(c):console.error(c),a.manager.itemError(e)}},i,s)}parse(e,t){if(jO(e))_t=new YO().parse(e);else{const s=PT(e);if(!ZO(s))throw new Error("THREE.FBXLoader: Unknown format.");if(rv(s)<7e3)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+rv(s));_t=new qO().parse(s)}const i=new tf(this.manager).setPath(this.resourcePath||t).setCrossOrigin(this.crossOrigin);return new WO(i,this.manager).parse(_t)}}class WO{constructor(e,t){this.textureLoader=e,this.manager=t}parse(){Zt=this.parseConnections();const e=this.parseImages(),t=this.parseTextures(e),i=this.parseMaterials(t),s=this.parseDeformers(),a=new XO().parse(s);return this.parseScene(s,a,i),Un}parseConnections(){const e=new Map;return"Connections"in _t&&_t.Connections.connections.forEach(function(i){const s=i[0],a=i[1],r=i[2];e.has(s)||e.set(s,{parents:[],children:[]});const o={ID:a,relationship:r};e.get(s).parents.push(o),e.has(a)||e.set(a,{parents:[],children:[]});const l={ID:s,relationship:r};e.get(a).children.push(l)}),e}parseImages(){const e={},t={};if("Video"in _t.Objects){const i=_t.Objects.Video;for(const s in i){const a=i[s],r=parseInt(s);if(e[r]=a.RelativeFilename||a.Filename,"Content"in a){const o=a.Content instanceof ArrayBuffer&&a.Content.byteLength>0,l=typeof a.Content=="string"&&a.Content!=="";if(o||l){const c=this.parseImage(i[s]);t[a.RelativeFilename||a.Filename]=c}}}}for(const i in e){const s=e[i];t[s]!==void 0?e[i]=t[s]:e[i]=e[i].split("\\").pop()}return e}parseImage(e){const t=e.Content,i=e.RelativeFilename||e.Filename,s=i.slice(i.lastIndexOf(".")+1).toLowerCase();let a;switch(s){case"bmp":a="image/bmp";break;case"jpg":case"jpeg":a="image/jpeg";break;case"png":a="image/png";break;case"tif":a="image/tiff";break;case"tga":this.manager.getHandler(".tga")===null&&console.warn("FBXLoader: TGA loader not found, skipping ",i),a="image/tga";break;case"webp":a="image/webp";break;default:console.warn('FBXLoader: Image type "'+s+'" is not supported.');return}if(typeof t=="string")return"data:"+a+";base64,"+t;{const r=new Uint8Array(t);return window.URL.createObjectURL(new Blob([r],{type:a}))}}parseTextures(e){const t=new Map;if("Texture"in _t.Objects){const i=_t.Objects.Texture;for(const s in i){const a=this.parseTexture(i[s],e);t.set(parseInt(s),a)}}return t}parseTexture(e,t){const i=this.loadTexture(e,t);i.ID=e.id,i.name=e.attrName;const s=e.WrapModeU,a=e.WrapModeV,r=s!==void 0?s.value:0,o=a!==void 0?a.value:0;if(i.wrapS=r===0?ps:Hn,i.wrapT=o===0?ps:Hn,"Scaling"in e){const l=e.Scaling.value;i.repeat.x=l[0],i.repeat.y=l[1]}if("Translation"in e){const l=e.Translation.value;i.offset.x=l[0],i.offset.y=l[1]}return i}loadTexture(e,t){const i=e.FileName.split(".").pop().toLowerCase();let s=this.manager.getHandler(`.${i}`);s===null&&(s=this.textureLoader);const a=s.path;a||s.setPath(this.textureLoader.path);const r=Zt.get(e.id).children;let o;if(r!==void 0&&r.length>0&&t[r[0].ID]!==void 0&&(o=t[r[0].ID],(o.indexOf("blob:")===0||o.indexOf("data:")===0)&&s.setPath(void 0)),o===void 0)return console.warn("FBXLoader: Undefined filename, creating placeholder texture."),new Bt;const l=s.load(o);return s.setPath(a),l}parseMaterials(e){const t=new Map;if("Material"in _t.Objects){const i=_t.Objects.Material;for(const s in i){const a=this.parseMaterial(i[s],e);a!==null&&t.set(parseInt(s),a)}}return t}parseMaterial(e,t){const i=e.id,s=e.attrName;let a=e.ShadingModel;if(typeof a=="object"&&(a=a.value),!Zt.has(i))return null;const r=this.parseParameters(e,t,i);let o;switch(a.toLowerCase()){case"phong":o=new ja;break;case"lambert":o=new ef;break;default:console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.',a),o=new ja;break}return o.setValues(r),o.name=s,o}parseParameters(e,t,i){const s={};e.BumpFactor&&(s.bumpScale=e.BumpFactor.value),e.Diffuse?s.color=rt.colorSpaceToWorking(new ue().fromArray(e.Diffuse.value),gt):e.DiffuseColor&&(e.DiffuseColor.type==="Color"||e.DiffuseColor.type==="ColorRGB")&&(s.color=rt.colorSpaceToWorking(new ue().fromArray(e.DiffuseColor.value),gt)),e.DisplacementFactor&&(s.displacementScale=e.DisplacementFactor.value),e.Emissive?s.emissive=rt.colorSpaceToWorking(new ue().fromArray(e.Emissive.value),gt):e.EmissiveColor&&(e.EmissiveColor.type==="Color"||e.EmissiveColor.type==="ColorRGB")&&(s.emissive=rt.colorSpaceToWorking(new ue().fromArray(e.EmissiveColor.value),gt)),e.EmissiveFactor&&(s.emissiveIntensity=parseFloat(e.EmissiveFactor.value)),s.opacity=1-(e.TransparencyFactor?parseFloat(e.TransparencyFactor.value):0),(s.opacity===1||s.opacity===0)&&(s.opacity=e.Opacity?parseFloat(e.Opacity.value):null,s.opacity===null&&(s.opacity=1-(e.TransparentColor?parseFloat(e.TransparentColor.value[0]):0))),s.opacity<1&&(s.transparent=!0),e.ReflectionFactor&&(s.reflectivity=e.ReflectionFactor.value),e.Shininess&&(s.shininess=e.Shininess.value),e.Specular?s.specular=rt.colorSpaceToWorking(new ue().fromArray(e.Specular.value),gt):e.SpecularColor&&e.SpecularColor.type==="Color"&&(s.specular=rt.colorSpaceToWorking(new ue().fromArray(e.SpecularColor.value),gt));const a=this;return Zt.get(i).children.forEach(function(r){const o=r.relationship;switch(o){case"Bump":s.bumpMap=a.getTexture(t,r.ID);break;case"Maya|TEX_ao_map":s.aoMap=a.getTexture(t,r.ID);break;case"DiffuseColor":case"Maya|TEX_color_map":s.map=a.getTexture(t,r.ID),s.map!==void 0&&(s.map.colorSpace=gt);break;case"DisplacementColor":s.displacementMap=a.getTexture(t,r.ID);break;case"EmissiveColor":s.emissiveMap=a.getTexture(t,r.ID),s.emissiveMap!==void 0&&(s.emissiveMap.colorSpace=gt);break;case"NormalMap":case"Maya|TEX_normal_map":s.normalMap=a.getTexture(t,r.ID);break;case"ReflectionColor":s.envMap=a.getTexture(t,r.ID),s.envMap!==void 0&&(s.envMap.mapping=rr,s.envMap.colorSpace=gt);break;case"SpecularColor":s.specularMap=a.getTexture(t,r.ID),s.specularMap!==void 0&&(s.specularMap.colorSpace=gt);break;case"TransparentColor":case"TransparencyFactor":s.alphaMap=a.getTexture(t,r.ID),s.transparent=!0;break;default:console.warn("THREE.FBXLoader: %s map is not supported in three.js, skipping texture.",o);break}}),s}getTexture(e,t){return"LayeredTexture"in _t.Objects&&t in _t.Objects.LayeredTexture&&(console.warn("THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer."),t=Zt.get(t).children[0].ID),e.get(t)}parseDeformers(){const e={},t={};if("Deformer"in _t.Objects){const i=_t.Objects.Deformer;for(const s in i){const a=i[s],r=Zt.get(parseInt(s));if(a.attrType==="Skin"){const o=this.parseSkeleton(r,i);o.ID=s,r.parents.length>1&&console.warn("THREE.FBXLoader: skeleton attached to more than one geometry is not supported."),o.geometryID=r.parents[0].ID,e[s]=o}else if(a.attrType==="BlendShape"){const o={id:s};o.rawTargets=this.parseMorphTargets(r,i),o.id=s,r.parents.length>1&&console.warn("THREE.FBXLoader: morph target attached to more than one geometry is not supported."),t[s]=o}}}return{skeletons:e,morphTargets:t}}parseSkeleton(e,t){const i=[];return e.children.forEach(function(s){const a=t[s.ID];if(a.attrType!=="Cluster")return;const r={ID:s.ID,indices:[],weights:[],transformLink:new Me().fromArray(a.TransformLink.a)};"Indexes"in a&&(r.indices=a.Indexes.a,r.weights=a.Weights.a),i.push(r)}),{rawBones:i,bones:[]}}parseMorphTargets(e,t){const i=[];for(let s=0;s1?r=o:o.length>0?r=o[0]:(r=new ja({name:on.DEFAULT_MATERIAL_NAME,color:13421772}),o.push(r)),"color"in a.attributes&&o.forEach(function(l){l.vertexColors=!0}),a.groups.length>0){let l=!1;for(let c=0,u=a.groups.length;c=o.length)&&(d.materialIndex=o.length,l=!0)}if(l){const c=new ja;o.push(c)}}return a.FBX_Deformer?(s=new Bh(a,r),s.normalizeSkinWeights()):s=new we(a,r),s}createCurve(e,t){const i=e.children.reduce(function(a,r){return t.has(r.ID)&&(a=t.get(r.ID)),a},null),s=new Rt({name:on.DEFAULT_MATERIAL_NAME,color:3342591,linewidth:1});return new In(i,s)}getTransformData(e,t){const i={};"InheritType"in t&&(i.inheritType=parseInt(t.InheritType.value)),"RotationOrder"in t?i.eulerOrder=Zl(t.RotationOrder.value):i.eulerOrder=Zl(0),"Lcl_Translation"in t&&(i.translation=t.Lcl_Translation.value),"PreRotation"in t&&(i.preRotation=t.PreRotation.value),"Lcl_Rotation"in t&&(i.rotation=t.Lcl_Rotation.value),"PostRotation"in t&&(i.postRotation=t.PostRotation.value),"Lcl_Scaling"in t&&(i.scale=t.Lcl_Scaling.value),"ScalingOffset"in t&&(i.scalingOffset=t.ScalingOffset.value),"ScalingPivot"in t&&(i.scalingPivot=t.ScalingPivot.value),"RotationOffset"in t&&(i.rotationOffset=t.RotationOffset.value),"RotationPivot"in t&&(i.rotationPivot=t.RotationPivot.value),e.userData.transformData=i}setLookAtProperties(e,t){"LookAtProperty"in t&&Zt.get(e.ID).children.forEach(function(s){if(s.relationship==="LookAtProperty"){const a=_t.Objects.Model[s.ID];if("Lcl_Translation"in a){const r=a.Lcl_Translation.value;e.target!==void 0?(e.target.position.fromArray(r),Un.add(e.target)):e.lookAt(new S().fromArray(r))}}})}bindSkeleton(e,t,i){const s=this.parsePoseNodes();for(const a in e){const r=e[a];Zt.get(parseInt(r.ID)).parents.forEach(function(l){if(t.has(l.ID)){const c=l.ID;Zt.get(c).parents.forEach(function(d){i.has(d.ID)&&i.get(d.ID).bind(new Lo(r.bones),s[d.ID])})}})}}parsePoseNodes(){const e={};if("Pose"in _t.Objects){const t=_t.Objects.Pose;for(const i in t)if(t[i].attrType==="BindPose"&&t[i].NbPoseNodes>0){const s=t[i].PoseNode;Array.isArray(s)?s.forEach(function(a){e[a.Node]=new Me().fromArray(a.Matrix.a)}):e[s.Node]=new Me().fromArray(s.Matrix.a)}}return e}addGlobalSceneSettings(){if("GlobalSettings"in _t){if("AmbientColor"in _t.GlobalSettings){const e=_t.GlobalSettings.AmbientColor.value,t=e[0],i=e[1],s=e[2];if(t!==0||i!==0||s!==0){const a=new ue().setRGB(t,i,s,gt);Un.add(new mc(a,1))}}"UnitScaleFactor"in _t.GlobalSettings&&(Un.userData.unitScaleFactor=_t.GlobalSettings.UnitScaleFactor.value)}}}class XO{constructor(){this.negativeMaterialIndices=!1}parse(e){const t=new Map;if("Geometry"in _t.Objects){const i=_t.Objects.Geometry;for(const s in i){const a=Zt.get(parseInt(s)),r=this.parseGeometry(a,i[s],e);t.set(parseInt(s),r)}}return this.negativeMaterialIndices===!0&&console.warn("THREE.FBXLoader: The FBX file contains invalid (negative) material indices. The asset might not render as expected."),t}parseGeometry(e,t,i){switch(t.attrType){case"Mesh":return this.parseMeshGeometry(e,t,i);case"NurbsCurve":return this.parseNurbsGeometry(t)}}parseMeshGeometry(e,t,i){const s=i.skeletons,a=[],r=e.parents.map(function(d){return _t.Objects.Model[d.ID]});if(r.length===0)return;const o=e.children.reduce(function(d,h){return s[h.ID]!==void 0&&(d=s[h.ID]),d},null);e.children.forEach(function(d){i.morphTargets[d.ID]!==void 0&&a.push(i.morphTargets[d.ID])});const l=r[0],c={};"RotationOrder"in l&&(c.eulerOrder=Zl(l.RotationOrder.value)),"InheritType"in l&&(c.inheritType=parseInt(l.InheritType.value)),"GeometricTranslation"in l&&(c.translation=l.GeometricTranslation.value),"GeometricRotation"in l&&(c.rotation=l.GeometricRotation.value),"GeometricScaling"in l&&(c.scale=l.GeometricScaling.value);const u=RT(c);return this.genGeometry(t,o,a,u)}genGeometry(e,t,i,s){const a=new Ge;e.attrName&&(a.name=e.attrName);const r=this.parseGeoNode(e,t),o=this.genBuffers(r),l=new Ee(o.vertex,3);if(l.applyMatrix4(s),a.setAttribute("position",l),o.colors.length>0&&a.setAttribute("color",new Ee(o.colors,3)),t&&(a.setAttribute("skinIndex",new kh(o.weightsIndices,4)),a.setAttribute("skinWeight",new Ee(o.vertexWeights,4)),a.FBX_Deformer=t),o.normal.length>0){const c=new at().getNormalMatrix(s),u=new Ee(o.normal,3);u.applyNormalMatrix(c),a.setAttribute("normal",u)}if(o.uvs.forEach(function(c,u){const d=u===0?"uv":`uv${u}`;a.setAttribute(d,new Ee(o.uvs[u],2))}),r.material&&r.material.mappingType!=="AllSame"){let c=o.materialIndex[0],u=0;if(o.materialIndex.forEach(function(d,h){d!==c&&(a.addGroup(u,h-u,c),c=d,u=h)}),a.groups.length>0){const d=a.groups[a.groups.length-1],h=d.start+d.count;h!==o.materialIndex.length&&a.addGroup(h,o.materialIndex.length-h,c)}a.groups.length===0&&a.addGroup(0,o.materialIndex.length,o.materialIndex[0])}return this.addMorphTargets(a,e,i,s),a}parseGeoNode(e,t){const i={};if(i.vertexPositions=e.Vertices!==void 0?e.Vertices.a:[],i.vertexIndices=e.PolygonVertexIndex!==void 0?e.PolygonVertexIndex.a:[],e.LayerElementColor&&e.LayerElementColor[0].Colors&&(i.color=this.parseVertexColors(e.LayerElementColor[0])),e.LayerElementMaterial&&(i.material=this.parseMaterialIndices(e.LayerElementMaterial[0])),e.LayerElementNormal&&(i.normal=this.parseNormals(e.LayerElementNormal[0])),e.LayerElementUV){i.uv=[];let s=0;for(;e.LayerElementUV[s];)e.LayerElementUV[s].UV&&i.uv.push(this.parseUVs(e.LayerElementUV[s])),s++}return i.weightTable={},t!==null&&(i.skeleton=t,t.rawBones.forEach(function(s,a){s.indices.forEach(function(r,o){i.weightTable[r]===void 0&&(i.weightTable[r]=[]),i.weightTable[r].push({id:a,weight:s.weights[o]})})})),i}genBuffers(e){const t={vertex:[],normal:[],colors:[],uvs:[],materialIndex:[],vertexWeights:[],weightsIndices:[]};let i=0,s=0,a=!1,r=[],o=[],l=[],c=[],u=[],d=[];const h=this;return e.vertexIndices.forEach(function(f,p){let g,_=!1;f<0&&(f=f^-1,_=!0);let m=[],v=[];if(r.push(f*3,f*3+1,f*3+2),e.color){const y=pu(p,i,f,e.color);l.push(y[0],y[1],y[2])}if(e.skeleton){if(e.weightTable[f]!==void 0&&e.weightTable[f].forEach(function(y){v.push(y.weight),m.push(y.id)}),v.length>4){a||(console.warn("THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights."),a=!0);const y=[0,0,0,0],b=[0,0,0,0];v.forEach(function(T,x){let M=T,C=m[x];b.forEach(function(w,E,R){if(M>w){R[E]=M,M=w;const k=y[E];y[E]=C,C=k}})}),m=y,v=b}for(;v.length<4;)v.push(0),m.push(0);for(let y=0;y<4;++y)u.push(v[y]),d.push(m[y])}if(e.normal){const y=pu(p,i,f,e.normal);o.push(y[0],y[1],y[2])}e.material&&e.material.mappingType!=="AllSame"&&(g=pu(p,i,f,e.material)[0],g<0&&(h.negativeMaterialIndices=!0,g=0)),e.uv&&e.uv.forEach(function(y,b){const T=pu(p,i,f,y);c[b]===void 0&&(c[b]=[]),c[b].push(T[0]),c[b].push(T[1])}),s++,_&&(h.genFace(t,e,r,g,o,l,c,u,d,s),i++,s=0,r=[],o=[],l=[],c=[],u=[],d=[])}),t}getNormalNewell(e){const t=new S(0,0,0);for(let i=0;i.5?new S(0,1,0):new S(0,0,1)).cross(t).normalize(),a=t.clone().cross(s).normalize();return{normal:t,tangent:s,bitangent:a}}flattenVertex(e,t,i){return new te(e.dot(t),e.dot(i))}genFace(e,t,i,s,a,r,o,l,c,u){let d;if(u>3){const h=[],f=t.baseVertexPositions||t.vertexPositions;for(let m=0;m1&&console.warn("THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.");const r=e.get(a[0].ID);i[s]={name:t[s].attrName,layer:r}}return i}addClip(e){let t=[];const i=this;return e.layer.forEach(function(s){t=t.concat(i.generateTracks(s))}),new da(e.name,-1,t)}generateTracks(e){const t=[];let i=new S,s=new S;if(e.transform&&e.transform.decompose(i,new dt,s),i=i.toArray(),s=s.toArray(),e.T!==void 0&&Object.keys(e.T.curves).length>0){const a=this.generateVectorTrack(e.modelName,e.T.curves,i,"position");a!==void 0&&t.push(a)}if(e.R!==void 0&&Object.keys(e.R.curves).length>0){const a=this.generateRotationTrack(e.modelName,e.R.curves,e.preRotation,e.postRotation,e.eulerOrder);a!==void 0&&t.push(a)}if(e.S!==void 0&&Object.keys(e.S.curves).length>0){const a=this.generateVectorTrack(e.modelName,e.S.curves,s,"scale");a!==void 0&&t.push(a)}if(e.DeformPercent!==void 0){const a=this.generateMorphTrack(e);a!==void 0&&t.push(a)}return t}generateVectorTrack(e,t,i,s){const a=this.getTimesForAllAxes(t),r=this.getKeyframeTrackValues(a,t,i);return new Hs(e+"."+s,a,r)}generateRotationTrack(e,t,i,s,a){let r,o;if(t.x!==void 0&&t.y!==void 0&&t.z!==void 0){const h=this.interpolateRotations(t.x,t.y,t.z,a);r=h[0],o=h[1]}const l=Zl(0);i!==void 0&&(i=i.map(vt.degToRad),i.push(l),i=new an().fromArray(i),i=new dt().setFromEuler(i)),s!==void 0&&(s=s.map(vt.degToRad),s.push(l),s=new an().fromArray(s),s=new dt().setFromEuler(s).invert());const c=new dt,u=new an,d=[];if(!o||!r)return new _s(e+".quaternion",[0],[0]);for(let h=0;h2&&new dt().fromArray(d,(h-3)/3*4).dot(c)<0&&c.set(-c.x,-c.y,-c.z,-c.w),c.toArray(d,h/3*4);return new _s(e+".quaternion",r,d)}generateMorphTrack(e){const t=e.DeformPercent.curves.morph,i=t.values.map(function(a){return a/100}),s=Un.getObjectByName(e.modelName).morphTargetDictionary[e.morphName];return new ua(e.modelName+".morphTargetInfluences["+s+"]",t.times,i)}getTimesForAllAxes(e){let t=[];if(e.x!==void 0&&(t=t.concat(e.x.times)),e.y!==void 0&&(t=t.concat(e.y.times)),e.z!==void 0&&(t=t.concat(e.z.times)),t=t.sort(function(i,s){return i-s}),t.length>1){let i=1,s=t[0];for(let a=1;a=180||f[1]>=180||f[2]>=180){const g=Math.max(...f)/180,_=new an(...c,s),m=new an(...d,s),v=new dt().setFromEuler(_),y=new dt().setFromEuler(m);v.dot(y)&&y.set(-y.x,-y.y,-y.z,-y.w);const b=e.times[o-1],T=e.times[o]-b,x=new dt,M=new an;for(let C=0;C<1;C+=1/g)x.copy(v.clone().slerp(y.clone(),C)),a.push(b+C*T),M.setFromQuaternion(x,s),r.push(M.x),r.push(M.y),r.push(M.z)}else a.push(e.times[o]),r.push(vt.degToRad(e.values[o])),r.push(vt.degToRad(t.values[o])),r.push(vt.degToRad(i.values[o]))}return[a,r]}}class qO{getPrevNode(){return this.nodeStack[this.currentIndent-2]}getCurrentNode(){return this.nodeStack[this.currentIndent-1]}getCurrentProp(){return this.currentProp}pushStack(e){this.nodeStack.push(e),this.currentIndent+=1}popStack(){this.nodeStack.pop(),this.currentIndent-=1}setCurrentProp(e,t){this.currentProp=e,this.currentPropName=t}parse(e){this.currentIndent=0,this.allNodes=new AT,this.nodeStack=[],this.currentProp=[],this.currentPropName="";const t=this,i=e.split(/[\r\n]+/);return i.forEach(function(s,a){const r=s.match(/^[\s\t]*;/),o=s.match(/^[\s\t]*$/);if(r||o)return;const l=s.match("^\\t{"+t.currentIndent+"}(\\w+):(.*){",""),c=s.match("^\\t{"+t.currentIndent+"}(\\w+):[\\s\\t\\r\\n](.*)"),u=s.match("^\\t{"+(t.currentIndent-1)+"}}");l?t.parseNodeBegin(s,l):c?t.parseNodeProperty(s,c,i[++a]):u?t.popStack():s.match(/^[^\s\t}]/)&&t.parseNodePropertyContinued(s)}),this.allNodes}parseNodeBegin(e,t){const i=t[1].trim().replace(/^"/,"").replace(/"$/,""),s=t[2].split(",").map(function(l){return l.trim().replace(/^"/,"").replace(/"$/,"")}),a={name:i},r=this.parseNodeAttr(s),o=this.getCurrentNode();this.currentIndent===0?this.allNodes.add(i,a):i in o?(i==="PoseNode"?o.PoseNode.push(a):o[i].id!==void 0&&(o[i]={},o[i][o[i].id]=o[i]),r.id!==""&&(o[i][r.id]=a)):typeof r.id=="number"?(o[i]={},o[i][r.id]=a):i!=="Properties70"&&(i==="PoseNode"?o[i]=[a]:o[i]=a),typeof r.id=="number"&&(a.id=r.id),r.name!==""&&(a.attrName=r.name),r.type!==""&&(a.attrType=r.type),this.pushStack(a)}parseNodeAttr(e){let t=e[0];e[0]!==""&&(t=parseInt(e[0]),isNaN(t)&&(t=e[0]));let i="",s="";return e.length>1&&(i=e[1].replace(/^(\w+)::/,""),s=e[2]),{id:t,name:i,type:s}}parseNodeProperty(e,t,i){let s=t[1].replace(/^"/,"").replace(/"$/,"").trim(),a=t[2].replace(/^"/,"").replace(/"$/,"").trim();s==="Content"&&a===","&&(a=i.replace(/"/g,"").replace(/,$/,"").trim());const r=this.getCurrentNode();if(r.name==="Properties70"){this.parseNodeSpecialProperty(e,s,a);return}if(s==="C"){const l=a.split(",").slice(1),c=parseInt(l[0]),u=parseInt(l[1]);let d=a.split(",").slice(3);d=d.map(function(h){return h.trim().replace(/^"/,"")}),s="connections",a=[c,u],eF(a,d),r[s]===void 0&&(r[s]=[])}s==="Node"&&(r.id=a),s in r&&Array.isArray(r[s])?r[s].push(a):s!=="a"?r[s]=a:r.a=a,this.setCurrentProp(r,s),s==="a"&&a.slice(-1)!==","&&(r.a=bp(a))}parseNodePropertyContinued(e){const t=this.getCurrentNode();t.a+=e,e.slice(-1)!==","&&(t.a=bp(t.a))}parseNodeSpecialProperty(e,t,i){const s=i.split('",').map(function(u){return u.trim().replace(/^\"/,"").replace(/\s/,"_")}),a=s[0],r=s[1],o=s[2],l=s[3];let c=s[4];switch(r){case"int":case"enum":case"bool":case"ULongLong":case"double":case"Number":case"FieldOfView":c=parseFloat(c);break;case"Color":case"ColorRGB":case"Vector3D":case"Lcl_Translation":case"Lcl_Rotation":case"Lcl_Scaling":c=bp(c);break}this.getPrevNode()[a]={type:r,type2:o,flag:l,value:c},this.setCurrentProp(this.getPrevNode(),a)}}class YO{parse(e){const t=new av(e);t.skip(23);const i=t.getUint32();if(i<6400)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+i);const s=new AT;for(;!this.endOfContent(t);){const a=this.parseNode(t,i);a!==null&&s.add(a.name,a)}return s}endOfContent(e){return e.size()%16===0?(e.getOffset()+160+16&-16)>=e.size():e.getOffset()+160+16>=e.size()}parseNode(e,t){const i={},s=t>=7500?e.getUint64():e.getUint32(),a=t>=7500?e.getUint64():e.getUint32();t>=7500?e.getUint64():e.getUint32();const r=e.getUint8(),o=e.getString(r);if(s===0)return null;const l=[];for(let h=0;h0?l[0]:"",u=l.length>1?l[1]:"",d=l.length>2?l[2]:"";for(i.singleProperty=a===1&&e.getOffset()===s;s>e.getOffset();){const h=this.parseNode(e,t);h!==null&&this.parseSubNode(o,i,h)}return i.propertyList=l,typeof c=="number"&&(i.id=c),u!==""&&(i.attrName=u),d!==""&&(i.attrType=d),o!==""&&(i.name=o),i}parseSubNode(e,t,i){if(i.singleProperty===!0){const s=i.propertyList[0];Array.isArray(s)?(t[i.name]=i,i.a=s):t[i.name]=s}else if(e==="Connections"&&i.name==="C"){const s=[];i.propertyList.forEach(function(a,r){r!==0&&s.push(a)}),t.connections===void 0&&(t.connections=[]),t.connections.push(s)}else if(i.name==="Properties70")Object.keys(i).forEach(function(a){t[a]=i[a]});else if(e==="Properties70"&&i.name==="P"){let s=i.propertyList[0],a=i.propertyList[1];const r=i.propertyList[2],o=i.propertyList[3];let l;s.indexOf("Lcl ")===0&&(s=s.replace("Lcl ","Lcl_")),a.indexOf("Lcl ")===0&&(a=a.replace("Lcl ","Lcl_")),a==="Color"||a==="ColorRGB"||a==="Vector"||a==="Vector3D"||a.indexOf("Lcl_")===0?l=[i.propertyList[4],i.propertyList[5],i.propertyList[6]]:l=i.propertyList[4],t[s]={type:a,type2:r,flag:o,value:l}}else t[i.name]===void 0?typeof i.id=="number"?(t[i.name]={},t[i.name][i.id]=i):t[i.name]=i:i.name==="PoseNode"?(Array.isArray(t[i.name])||(t[i.name]=[t[i.name]]),t[i.name].push(i)):t[i.name][i.id]===void 0&&(t[i.name][i.id]=i)}parseProperty(e){const t=e.getString(1);let i;switch(t){case"C":return e.getBoolean();case"D":return e.getFloat64();case"F":return e.getFloat32();case"I":return e.getInt32();case"L":return e.getInt64();case"R":return i=e.getUint32(),e.getArrayBuffer(i);case"S":return i=e.getUint32(),e.getString(i);case"Y":return e.getInt16();case"b":case"c":case"d":case"f":case"i":case"l":const s=e.getUint32(),a=e.getUint32(),r=e.getUint32();if(a===0)switch(t){case"b":case"c":return e.getBooleanArray(s);case"d":return e.getFloat64Array(s);case"f":return e.getFloat32Array(s);case"i":return e.getInt32Array(s);case"l":return e.getInt64Array(s)}const o=kO(new Uint8Array(e.getArrayBuffer(r))),l=new av(o.buffer);switch(t){case"b":case"c":return l.getBooleanArray(s);case"d":return l.getFloat64Array(s);case"f":return l.getFloat32Array(s);case"i":return l.getInt32Array(s);case"l":return l.getInt64Array(s)}break;default:throw new Error("THREE.FBXLoader: Unknown property type "+t)}}}class av{constructor(e,t){this.dv=new DataView(e),this.offset=0,this.littleEndian=t!==void 0?t:!0,this._textDecoder=new TextDecoder}getOffset(){return this.offset}size(){return this.dv.buffer.byteLength}skip(e){this.offset+=e}getBoolean(){return(this.getUint8()&1)===1}getBooleanArray(e){const t=[];for(let i=0;i=0&&(i=new Uint8Array(this.dv.buffer,t,s)),this._textDecoder.decode(i)}}class AT{add(e,t){this[e]=t}}function jO(n){const e="Kaydara FBX Binary \0";return n.byteLength>=e.length&&e===PT(n,0,e.length)}function ZO(n){const e=["K","a","y","d","a","r","a","\\","F","B","X","\\","B","i","n","a","r","y","\\","\\"];let t=0;function i(s){const a=n[s-1];return n=n.slice(t+s),t++,a}for(let s=0;s(console.warn(`⚠️ Could not load texture ${u}:`,d.message),null))])}this._processModelMaterials(s,a,e,i.format);const o=this._calculateModelScale(s,e,i.scale);if(s.userData.scaleInfo=o,s.userData.format=i.format,i.wheelSockets){s.userData.wheelSockets=!0,s.userData.wheelModelName=i.wheelModel;const l=this._findWheelSockets(s);s.userData.wheelSocketObjects=l,console.log(`🔌 Found ${Object.keys(l).length} wheel sockets`)}return{model:s,chassisTexture:a,wheelModel:r}}_findWheelSockets(e){const t={},i=["Wheel_BL","Wheel_BR","Wheel_FL","Wheel_FR"];console.log("🔍 Searching for wheel sockets..."),e.traverse(s=>{const a=s.name,r=a.toLowerCase();for(const o of i)(a===o||r===o.toLowerCase())&&(t[o]=s,console.log(` Found socket: "${a}" at position (${s.position.x.toFixed(2)}, ${s.position.y.toFixed(2)}, ${s.position.z.toFixed(2)})`))});for(const s of i)t[s]||console.warn(` ⚠️ Missing wheel socket: ${s}`);return Object.keys(t).length===0&&(console.warn("⚠️ No wheel sockets found! Listing all objects:"),e.traverse(s=>{console.log(` - "${s.name}" (${s.type})`)})),t}_calculateModelScale(e,t,i=null){const s=new vn().setFromObject(e),a=new S;s.getSize(a),console.log(`📐 ${t.toUpperCase()} model dimensions (raw):`),console.log(` Size: X=${a.x.toFixed(2)}, Y=${a.y.toFixed(2)}, Z=${a.z.toFixed(2)}`),console.log(` Min Y: ${s.min.y.toFixed(2)}, Max Y: ${s.max.y.toFixed(2)}`);const r=this.HITBOX_DIMENSIONS[t]||this.HITBOX_DIMENSIONS.octane;let o;if(i!==null)o=i,console.log(` Using override scale: ${o}`);else{const l=a.z,u=r.length*1/l;o=u*.55,console.log(` Target RL: ${r.length} x ${r.width} x ${r.height} uu`),console.log(` Scale to RL: ${u.toFixed(4)}, Final scale: ${o.toFixed(6)}`)}return{scale:o}}_loadFBX(e){return new Promise((t,i)=>{this.fbxLoader.load(e,s=>t(s),void 0,s=>i(new Error(`Failed to load FBX: ${e} - ${s.message}`)))})}_loadGLB(e){return new Promise((t,i)=>{this.gltfLoader.load(e,s=>{t(s.scene)},void 0,s=>i(new Error(`Failed to load GLB: ${e} - ${s.message}`)))})}async loadWheelModel(e){const t=Si(`models/wheels/${e}`,this.assetBase);if(this.wheelModelCache.has(t))return this.wheelModelCache.get(t);if(this.wheelLoadingPromises.has(t))return this.wheelLoadingPromises.get(t);const i=this._loadGLB(t);this.wheelLoadingPromises.set(t,i);try{const s=await i;return console.log(`✓ Loaded wheel model: ${e}`),s.traverse(a=>{a.isMesh&&(a.castShadow=!0,a.receiveShadow=!0)}),this.wheelModelCache.set(t,s),s}catch(s){throw console.error(`Failed to load wheel model ${e}:`,s),s}finally{this.wheelLoadingPromises.delete(t)}}_loadTexture(e){return new Promise((t,i)=>{this.textureLoader.load(e,s=>{s.flipY=!1,s.colorSpace=gt,t(s)},void 0,s=>i(new Error(`Failed to load texture: ${e}`)))})}_processModelMaterials(e,t,i,s="fbx"){console.log(`📦 Processing materials for ${i} (${s}):`);const a=["body","paint"],r=[];e.traverse(o=>{o.isLight&&(r.push(o),console.log(` 🔦 Removing imported light: "${o.name||o.type}"`))}),r.forEach(o=>{o.parent&&o.parent.remove(o)}),e.traverse(o=>{o.isMesh&&(console.log(` Mesh: "${o.name}"`),(Array.isArray(o.material)?o.material:[o.material]).forEach((c,u)=>{console.log(` [${u}] Material: "${c.name}" - Color: #${c.color?.getHexString()||"none"}`);const d=(c.name||"").toLowerCase(),h=(o.name||"").toLowerCase(),f=a.some(p=>d.includes(p)||h.includes(p));if(s==="glb")(c.isMeshStandardMaterial||c.isMeshPhysicalMaterial)&&(console.log(` → GLB material (keeping as-is): metalness=${c.metalness?.toFixed(2)}, roughness=${c.roughness?.toFixed(2)}`),c.userData.originalColor=c.color?.clone(),c.userData.isBodyMaterial=f);else if(c.isMeshPhongMaterial||c.isMeshLambertMaterial||c.isMeshBasicMaterial){let p;f?(p=new Pn({color:c.color,map:c.map,metalness:.8,roughness:.15}),console.log(" → Body material: shiny metallic")):(p=new Pn({color:c.color,map:c.map,metalness:.1,roughness:.6}),console.log(" → Non-body material: matte")),p.name=c.name,Array.isArray(o.material)?o.material[u]=p:o.material=p}}))}),t?console.log(` ✓ Chassis texture loaded for ${i}`):s==="fbx"&&console.log(` ⚠️ No chassis texture for ${i}`)}getModelTypeForCar(e,t){return e&&this.carNameToModel[e]?this.carNameToModel[e]:this.hitboxToModel[t]||"octane"}getModelTypeForHitbox(e){return this.hitboxToModel[e]||"octane"}async createCarMesh(e,t=0){const i=this.getModelTypeForHitbox(e);try{const s=await this.loadModel(i);if(!s||!s.model)return console.warn(`No cached model for ${i}`),null;const a=s.model.userData.format||"fbx";let r;a==="glb"?(r=xp(s.model),r.traverse(c=>{c.isMesh&&(Array.isArray(c.material)?c.material=c.material.map(u=>u.clone()):c.material&&(c.material=c.material.clone()))})):r=s.model.clone(),this.applyTeamColor(r,t);const o=new Mt,l=s.model.userData.scaleInfo;return l&&r.scale.setScalar(l.scale),o.add(r),r.traverse(c=>{c.isMesh&&(c.castShadow=!0)}),o.userData.modelType=i,o.userData.hitboxType=e,o.userData.team=t,o.userData.isFBXModel=a==="fbx",o.userData.isGLBModel=a==="glb",o}catch(s){return console.error(`Failed to create car mesh for ${e}:`,s),null}}applyTeamColor(e,t){const i=t===0?this.TEAM_COLORS.blue:this.TEAM_COLORS.orange,s=["body","paint"];let a=!1;console.log("🔍 Analyzing car meshes for team coloring:"),e.traverse(r=>{if(r.isMesh){const o=Array.isArray(r.material)?r.material:[r.material];console.log(` Mesh: "${r.name}" with ${o.length} material(s)`),o.forEach((l,c)=>{console.log(` [${c}] Material: "${l.name}", isBodyMaterial: ${l.userData?.isBodyMaterial}`)})}}),e.traverse(r=>{r.isMesh&&(Array.isArray(r.material)?r.material:[r.material]).forEach((l,c)=>{const u=(l.name||"").toLowerCase(),d=(r.name||"").toLowerCase(),h=l.userData?.isBodyMaterial||s.some(f=>u.includes(f)||d.includes(f));if(console.log(` Checking "${l.name}" on "${r.name}": isBody=${h}`),h){a=!0;const f=l.clone();f.color=i.clone(),f.metalness=.39,f.roughness=.47,f.userData={...l.userData},Array.isArray(r.material)?r.material[c]=f:r.material=f,console.log(`🎨 Applied team color to: "${l.name}" on mesh "${r.name}" (index ${c})`)}})}),a||console.warn("⚠️ No body material found for team coloring! Check material names.")}updateTeamColor(e,t){this.applyTeamColor(e,t)}isModelReady(e,t){const i=this.getModelTypeForCar(e,t);return this.modelCache.has(this.modelCacheKey(i))}getCarMeshSync(e,t,i=0){const s=this.getModelTypeForCar(e,t),a=this.modelCache.get(this.modelCacheKey(s));if(!a||!a.model)return null;const r=a.model.userData.format||"fbx",o=a.model.userData.wheelSockets;let l;r==="glb"?(l=xp(a.model),l.traverse(d=>{d.isMesh&&(Array.isArray(d.material)?d.material=d.material.map(h=>h.clone()):d.material&&(d.material=d.material.clone()))})):l=a.model.clone(),this.applyTeamColor(l,i);const c=new Mt,u=a.model.userData.scaleInfo;return u&&l.scale.setScalar(u.scale),c.add(l),l.traverse(d=>{d.isMesh&&(d.castShadow=!0)}),c.userData.modelType=s,c.userData.carName=e,c.userData.hitboxType=t,c.userData.team=i,c.userData.isFBXModel=r==="fbx",c.userData.isGLBModel=r==="glb",c.userData.hasWheelSockets=o,o?c.userData.wheels=this._attachWheelsToSockets(l,a.wheelModel):c.userData.wheels=this._findWheelMeshes(l),c}_attachWheelsToSockets(e,t){const i=[],s={Wheel_FL:{side:"left",position:"front"},Wheel_FR:{side:"right",position:"front"},Wheel_BL:{side:"left",position:"rear"},Wheel_BR:{side:"right",position:"rear"}};if(!t)return console.warn("⚠️ No wheel model template available for socket attachment"),i;console.log("🔧 Attaching wheels to sockets...");const a={};e.traverse(r=>{const o=r.name;s[o]&&(a[o]=r)});for(const[r,o]of Object.entries(s)){const l=a[r];if(!l){console.warn(` ⚠️ Socket not found: ${r}`);continue}const c=xp(t);c.traverse(u=>{u.isMesh&&(Array.isArray(u.material)?u.material=u.material.map(d=>d.clone()):u.material&&(u.material=u.material.clone()),u.castShadow=!0)}),c.position.set(0,0,0),c.rotation.set(0,0,0),l.add(c),console.log(` ✓ Attached wheel to ${r} (${o.position} ${o.side})`),i.push({mesh:c,steeringPivot:o.position==="front"?l:null,side:o.side,position:o.position,socket:l})}return console.log(`✓ Attached ${i.length} wheels to sockets`),i}_findWheelMeshes(e){const t=[],i={fl:{side:"left",position:"front"},fr:{side:"right",position:"front"},rl:{side:"left",position:"rear"},rr:{side:"right",position:"rear"}};console.log("🔍 Searching for wheels in model...");const s={};e.traverse(a=>{const o=a.name.toLowerCase().match(/^wheel_(fl|fr|rl|rr)_(y|z)$/);if(o){const l=o[1],c=o[2];s[l]||(s[l]={}),s[l][c]=a,console.log(` Found: "${a.name}" (${c==="y"?"wheel mesh":"steering pivot"})`)}});for(const[a,r]of Object.entries(s)){const o=i[a];if(!o)continue;const l=r.y,c=r.z;l&&(a==="fr"&&(l.rotation.z+=Math.PI,console.log(" Fixed FR wheel orientation (rotation.z += PI)")),t.push({mesh:l,steeringPivot:o.position==="front"?c:null,side:o.side,position:o.position}),console.log(`🛞 Wheel ${a.toUpperCase()}: mesh="${l.name}"${c&&o.position==="front"?`, steering="${c.name}"`:""}`))}return t.length===0?(console.warn("⚠️ No wheel meshes found. Expected: Wheel_FL_Y, Wheel_FR_Y, etc."),console.warn(" Listing all objects in model:"),e.traverse(a=>{console.log(` - "${a.name}" (${a.type})`)})):console.log(`✓ Found ${t.length} wheels`),t}dispose(){}}const oF=2,wp=new Map;function lF(n){const e=Si("models/ball/scene.gltf",n);let t=wp.get(e);if(!t){const i=new Og;t=new Promise(s=>{i.load(e,a=>{console.log("✓ Ball model loaded"),s(a.scene)},void 0,a=>{console.error("Failed to load ball model:",a),wp.delete(e),s(null)})}),wp.set(e,t)}return t}class cF{constructor(e,t,i={}){this.scene=e,this.effectsManager=t,this.assetBase=i.assetBase,this.actors={},this.ballActorId=null,this.ballIndicator=null,this.ballVerticalLine=null,this.playerNames=new Set,this.actorToPlayer={},this.actorLinks={},this.playerNameToCarActorId={},this.playerNameToPriActorId={},this.playerTeams={},this.actorLoadouts={},this.carBodyIds={},this.carModelLoader=new rF({assetBase:this.assetBase}),this.pendingCarReplacements=new Map,this._lastGoalScanTime=null,this._firedGoalTimes=new Set,this._p0=new S,this._p1=new S,this._v0=new S,this._v1=new S,this._nextRot=new dt,this._q0=new dt,this._q1=new dt,this._qResult=new dt,this.onPlayerFound=null,this.lastBallTouchTeam=0,this.BALL_TOUCH_DISTANCE=200,this.ballTimeline=[],this.playerTimelineMap={},this.timelineIndices={ball:0,players:{}},this.interpolantsInitialized=!1,this.animationMixer=null,this.animationActions={},this.animationClock=new Eg(!1),this.replayDuration=0,this.useAnimationSystem=!1,this.SMOOTHING_WINDOW=5,this.positionBuffers={},this.rotationBuffers={},this.interpolationEnabled=!0,this.interpolationMethod="lerp",this.smoothingWindowSize=12,this.lastFrameInfo=null,this._lowPassState=new Map,this._lowPassAlpha=.3,this._predictState=new Map,this._predictCorrectionTime=.1,this._smoothingBuffers=new Map,this._adaptiveState=new Map,this.ballModel=null,this._ballModelReplaced=!1,this.ballModelReady=lF(this.assetBase).then(s=>(this.ballModel=s,s!==null))}async waitForBallModel(){const e=await this.ballModelReady;return e&&!this._ballModelReplaced&&this.ballActorId&&this.actors[this.ballActorId]&&(this.replaceBallWithModel(this.ballActorId),this._ballModelReplaced=!0),e}replaceBallWithModel(e){const t=this.actors[e];if(!t||!this.ballModel)return;const i=this.ballModel.clone();i.userData=t.userData,i.position.copy(t.position),i.quaternion.copy(t.quaternion),i.scale.copy(t.scale);const s=92.75;i.scale.set(s,s,s),i.traverse(a=>{a.isMesh&&(a.castShadow=!0,a.receiveShadow=!0)}),this.scene.remove(t),this.scene.add(i),t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose(),this.actors[e]=i,console.log("✓ Ball replaced with GLTF model")}reset(){Object.values(this.actors).forEach(e=>{this.scene.remove(e),e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()}),this.actors={},this.ballActorId=null,this.ballIndicator&&(this.scene.remove(this.ballIndicator),this.ballIndicator.geometry&&this.ballIndicator.geometry.dispose(),this.ballIndicator.material&&this.ballIndicator.material.dispose(),this.ballIndicator=null),this.ballVerticalLine&&(this.scene.remove(this.ballVerticalLine),this.ballVerticalLine.geometry&&this.ballVerticalLine.geometry.dispose(),this.ballVerticalLine.material&&this.ballVerticalLine.material.dispose(),this.ballVerticalLine=null),this.actorToPlayer={},this.actorLinks={},this.playerNames.clear(),this.playerNameToCarActorId={},this.playerNameToPriActorId={},this.playerTeams={},this.actorLoadouts={},this.carBodyIds={},this.pendingCarReplacements.clear(),this._lastGoalScanTime=null,this._firedGoalTimes.clear(),this.ballTimeline=[],this.playerTimelineMap={},this.ballTimelineCorrected=[],this.playerTimelineMapCorrected={},this.ballTimelineFiltered=[],this.playerTimelineMapFiltered={},this.timelineIndices={ball:0,players:{}},this.timelineIndicesFiltered={ball:0,players:{}},this.timelineIndicesCorrected={ball:0,players:{}},this.interpolantsInitialized=!1,this.animationMixer?.stopAllAction?.(),this.animationMixer=null,this.animationActions={},this.replayDuration=0,this.positionBuffers={},this.rotationBuffers={},this._lowPassState.clear(),this._predictState.clear(),this._smoothingBuffers.clear(),this._adaptiveState.clear(),this._ballModelReplaced=!1}resetGoalExplosionPlaybackState(){this._lastGoalScanTime=null,this._firedGoalTimes.clear()}setPlayerTeams(e){this.playerTeams=e}initFromFramework(e){console.log("[ActorManager] Initializing actors from framework..."),this._createBallMesh();const t=e.playerList;t.forEach((i,s)=>{this._createCarMesh(i.name,i.team,s,i.carName,i.hitboxType);const a=this.playerNameToCarActorId[i.name];this.actors[a]}),console.log(`[ActorManager] Created ${t.length} car meshes + 1 ball`)}initInterpolants(e){console.log("[ActorManager] Initializing interpolation system..."),this.ballTimeline=e.ballTimeline||[],this.playerTimelineMap=e.playerTimelines||{},this.ballTimelineCorrected=this._correctTimeShiftedPositions(this.ballTimeline),this.playerTimelineMapCorrected={},Object.entries(this.playerTimelineMap).forEach(([s,a])=>{this.playerTimelineMapCorrected[s]=this._correctTimeShiftedPositions(a)}),this.ballTimelineFiltered=this._filterBadFrames(this.ballTimeline),this.playerTimelineMapFiltered={},Object.entries(this.playerTimelineMap).forEach(([s,a])=>{this.playerTimelineMapFiltered[s]=this._filterBadFrames(a)}),this.timelineIndices={ball:0,players:{}},this.timelineIndicesFiltered={ball:0,players:{}},this.timelineIndicesCorrected={ball:0,players:{}},Object.keys(this.playerTimelineMap).forEach(s=>{this.timelineIndices.players[s]=0,this.timelineIndicesFiltered.players[s]=0,this.timelineIndicesCorrected.players[s]=0}),this.ballTimeline.length>0&&(this.replayDuration=this.ballTimeline[this.ballTimeline.length-1].time),this.useAnimationSystem&&this._initAnimationSystem(),this.interpolantsInitialized=!0;const t=this.ballTimeline.length-this.ballTimelineFiltered.length,i=this.ballTimelineCorrected._correctedCount||0;console.log(` Ball: ${this.ballTimeline.length} keyframes (${i} corrected, ${t} filtered)`),Object.entries(this.playerTimelineMap).forEach(([s,a])=>{const r=this.playerTimelineMapCorrected[s]?._correctedCount||0;console.log(` ${s}: ${a.length} keyframes (${r} corrected)`)}),console.log(` Replay duration: ${this.replayDuration.toFixed(2)}s`),console.log("[ActorManager] Animation system ready")}_initAnimationSystem(){console.log("[ActorManager] Building Three.js animation clips..."),this.animationMixer=new oT(this.scene);const e=this.actors[this.ballActorId];if(e&&this.ballTimeline.length>0){const t=this._createAnimationClip("ball",this.ballTimeline,e);if(t){const i=this.animationMixer.clipAction(t,e);i.setLoop(Jd),i.clampWhenFinished=!0,this.animationActions.ball=i,console.log(` ✓ Ball animation: ${t.duration.toFixed(2)}s`)}}Object.entries(this.playerTimelineMap).forEach(([t,i])=>{const s=this.playerNameToCarActorId[t],a=this.actors[s];if(a&&i.length>0){const r=this._createAnimationClip(t,i,a);if(r){const o=this.animationMixer.clipAction(r,a);o.setLoop(Jd),o.clampWhenFinished=!0,this.animationActions[t]=o,console.log(` ✓ ${t} animation: ${r.duration.toFixed(2)}s`)}}}),console.log("[ActorManager] Animation clips ready")}_createAnimationClip(e,t,i){if(!t||t.length<2)return null;const s=[],a=[],r=[],o=t[0];o.time>0&&(s.push(0),o.position?a.push(o.position.x,o.position.y,o.position.z):a.push(0,0,0),o.rotation?r.push(o.rotation.x,o.rotation.y,o.rotation.z,o.rotation.w):r.push(0,0,0,1));for(const h of t){if(s.push(h.time),h.position)a.push(h.position.x,h.position.y,h.position.z);else{const f=a.length-3;f>=0?a.push(a[f],a[f+1],a[f+2]):a.push(0,0,0)}if(h.rotation)r.push(h.rotation.x,h.rotation.y,h.rotation.z,h.rotation.w);else{const f=r.length-4;f>=0?r.push(r[f],r[f+1],r[f+2],r[f+3]):r.push(0,0,0,1)}}const l=new Hs(".position",s,a,or),c=new _s(".quaternion",s,r),u=s[s.length-1]-s[0];return new da(e,u,[l,c])}startAnimations(){this.animationMixer&&(Object.values(this.animationActions).forEach(e=>{e.reset(),e.play()}),this.animationClock.start(),console.log("[ActorManager] Animations started"))}pauseAnimations(){this.animationMixer&&Object.values(this.animationActions).forEach(e=>{e.paused=!0})}resumeAnimations(){this.animationMixer&&Object.values(this.animationActions).forEach(e=>{e.paused=!1})}seekAnimations(e){this.animationMixer&&(Object.values(this.animationActions).forEach(t=>{t.time=e}),this.animationMixer.setTime(e))}updateAnimations(e){!this.animationMixer||!this.useAnimationSystem||this.animationMixer.update(e)}_subsampleTimeline(e){return!e||e.length<4?e:e.filter((t,i)=>i%2===0)}_getOrCreateSmoothingBuffer(e){return this.positionBuffers[e]||(this.positionBuffers[e]=[],this.rotationBuffers[e]=[]),{positions:this.positionBuffers[e],rotations:this.rotationBuffers[e]}}_smoothPosition(e,t){const i=this._getOrCreateSmoothingBuffer(e).positions;for(i.push({x:t.x,y:t.y,z:t.z});i.length>this.SMOOTHING_WINDOW;)i.shift();if(i.length===1)return t;let s=0,a=0,r=0;for(const o of i)s+=o.x,a+=o.y,r+=o.z;return{x:s/i.length,y:a/i.length,z:r/i.length}}_smoothRotation(e,t){const i=this._getOrCreateSmoothingBuffer(e).rotations;for(i.push({x:t.x,y:t.y,z:t.z,w:t.w});i.length>this.SMOOTHING_WINDOW;)i.shift();if(i.length<3)return t;const s=Math.floor(i.length/2);return i[s]}resetSmoothingBuffers(){this.positionBuffers={},this.rotationBuffers={},this._lowPassState.clear()}_findKeyframeIndex(e,t,i=0){if(!e||e.length===0)return-1;if(t<=e[0].time)return 0;if(t>=e[e.length-1].time)return e.length-2;let s=Math.max(0,Math.min(i,e.length-2));if(e[s].time<=t&&e[s+1].time>t)return s;if(s+2t)return s+1;let a=0,r=e.length-2;for(;a<=r;){const o=Math.floor((a+r)/2);if(e[o].time<=t&&e[o+1].time>t)return o;e[o].time>t?r=o-1:a=o+1}return Math.max(0,Math.min(a,e.length-2))}_applySmoothing(e,t){this._smoothingBuffers.has(e)||this._smoothingBuffers.set(e,[]);const i=this._smoothingBuffers.get(e);for(i.push({x:t.x,y:t.y,z:t.z});i.length>this.smoothingWindowSize;)i.shift();if(i.length===1)return t;let s=0,a=0,r=0;for(const o of i)s+=o.x,a+=o.y,r+=o.z;return{x:s/i.length,y:a/i.length,z:r/i.length}}_applyEmaSmoothing(e,t){const i=`ema-${e}`;if(!this._smoothingBuffers.has(i))return this._smoothingBuffers.set(i,{x:t.x,y:t.y,z:t.z}),t;const s=this._smoothingBuffers.get(i),a=Math.max(.05,Math.min(.5,1/this.smoothingWindowSize)),r={x:a*t.x+(1-a)*s.x,y:a*t.y+(1-a)*s.y,z:a*t.z+(1-a)*s.z};return this._smoothingBuffers.set(i,r),r}_applyDoubleEmaSmoothing(e,t){const i=`dema-${e}`;if(!this._smoothingBuffers.has(i))return this._smoothingBuffers.set(i,{level:{x:t.x,y:t.y,z:t.z},trend:{x:0,y:0,z:0}}),t;const s=this._smoothingBuffers.get(i),a=Math.max(.1,Math.min(.6,2/this.smoothingWindowSize)),r=a*.5,o={x:a*t.x+(1-a)*(s.level.x+s.trend.x),y:a*t.y+(1-a)*(s.level.y+s.trend.y),z:a*t.z+(1-a)*(s.level.z+s.trend.z)},l={x:r*(o.x-s.level.x)+(1-r)*s.trend.x,y:r*(o.y-s.level.y)+(1-r)*s.trend.y,z:r*(o.z-s.level.z)+(1-r)*s.trend.z};return s.level=o,s.trend=l,{x:o.x+l.x,y:o.y+l.y,z:o.z+l.z}}_applyWeightedSmoothing(e,t){const i=`wma-${e}`;this._smoothingBuffers.has(i)||this._smoothingBuffers.set(i,[]);const s=this._smoothingBuffers.get(i);for(s.push({x:t.x,y:t.y,z:t.z});s.length>this.smoothingWindowSize;)s.shift();if(s.length===1)return t;let a=0,r=0,o=0,l=0;for(let c=0;cthis.smoothingWindowSize;)s.shift();if(s.length===1)return t;const a=s.length/3;let r=0,o=0,l=0,c=0;for(let u=0;u.001&&(s.derivedVel={x:(t.x-s.lastPos.x)/a,y:(t.y-s.lastPos.y)/a,z:(t.z-s.lastPos.z)/a});const r=Math.sqrt(s.derivedVel.x**2+s.derivedVel.y**2+s.derivedVel.z**2),o=2,l=this.smoothingWindowSize,c=300,u=1500;let d;if(ru)d=o;else{const _=(r-c)/(u-c);d=Math.round(l-_*(l-o))}if(s.buffer.length>=2){const _=s.buffer[s.buffer.length-1],m=s.buffer[s.buffer.length-2],v={x:_.x-m.x,y:_.y-m.y,z:_.z-m.z},y={x:t.x-_.x,y:t.y-_.y,z:t.z-_.z},b=Math.sqrt(v.x**2+v.y**2+v.z**2),T=Math.sqrt(y.x**2+y.y**2+y.z**2);if(b>.1&&T>.1&&(v.x*y.x+v.y*y.y+v.z*y.z)/(b*T)<.5)for(;s.buffer.length>Math.max(2,d/2);)s.buffer.shift()}for(s.buffer.push({x:t.x,y:t.y,z:t.z});s.buffer.length>d;)s.buffer.shift();if(s.lastPos={x:t.x,y:t.y,z:t.z},s.lastTime=i,s.buffer.length===1)return t;let h=0,f=0,p=0,g=0;for(let _=0;_u+10&&(h.z=t.position.z+t.velocity.z*r-.5*c*r*r,h.zu+10&&(p.z=t.position.z+t.velocity.z*o-.5*c*o*o,p.z0&&o>0){const b=d*o;m>b*2&&(v=b*2/m)}const y=_*v+(1-v)*l;return{x:h.x+g.x*y,y:h.y+g.y*y,z:h.z+g.z*y}}_physicsTickInterpolate(e,t,i){const s=t.time-e.time,a=i-e.time,r=a/s;if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};const o=(e.velocity.x+t.velocity.x)/2,l=(e.velocity.y+t.velocity.y)/2,c=(e.velocity.z+t.velocity.z)/2,u=e.position.x+o*a,d=e.position.y+l*a,h=e.position.z+c*a,f=e.position.x+o*s,p=e.position.y+l*s,g=e.position.z+c*s,_=t.position.x-f,m=t.position.y-p,v=t.position.z-g;return{x:u+_*r,y:d+m*r,z:h+v*r}}_velocityOnlyInterpolate(e,t,i){const s=i-e.time,a=t.time-e.time,r=s/a;if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};const o=e.velocity.x+(t.velocity.x-e.velocity.x)*r/2,l=e.velocity.y+(t.velocity.y-e.velocity.y)*r/2,c=e.velocity.z+(t.velocity.z-e.velocity.z)*r/2;return{x:e.position.x+o*s,y:e.position.y+l*s,z:e.position.z+c*s}}_smartHybridInterpolate(e,t,i){const s=i-e.time,a=t.time-e.time,r=Math.max(0,Math.min(1,s/a));if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};const o=Math.sqrt(e.velocity.x**2+e.velocity.y**2+e.velocity.z**2),l=Math.sqrt(t.velocity.x**2+t.velocity.y**2+t.velocity.z**2);let c=1;o>10&&l>10&&(c=(e.velocity.x*t.velocity.x+e.velocity.y*t.velocity.y+e.velocity.z*t.velocity.z)/(o*l));const u=o>10?Math.abs(l-o)/o:0;if(c<.95||u>.1){const h=r*r*(3-2*r);return{x:e.position.x+(t.position.x-e.position.x)*h,y:e.position.y+(t.position.y-e.position.y)*h,z:e.position.z+(t.position.z-e.position.z)*h}}else{const h=(e.velocity.x+t.velocity.x)/2,f=(e.velocity.y+t.velocity.y)/2,p=(e.velocity.z+t.velocity.z)/2,g=e.position.x+h*s,_=e.position.y+f*s,m=e.position.z+p*s,v=e.position.x+h*a,y=e.position.y+f*a,b=e.position.z+p*a,T=t.position.x-v,x=t.position.y-y,M=t.position.z-b;return{x:g+T*r,y:_+x*r,z:m+M*r}}}_isBadFrame(e,t){if(!e.velocity||!t.velocity||!e.position||!t.position)return!1;const i=t.time-e.time;if(i<.001)return!1;const s=(e.velocity.x+t.velocity.x)/2,a=(e.velocity.y+t.velocity.y)/2,r=(e.velocity.z+t.velocity.z)/2,o=Math.sqrt(s**2+a**2+r**2);if(o<200)return!1;const l=t.position.x-e.position.x,c=t.position.y-e.position.y,u=t.position.z-e.position.z,d=Math.sqrt(l*l+c*c+u*u),h=o*i,f=d/h;return f<.6||f>1.4}_filterBadFrames(e){if(!e||e.length<2)return e;const t=[e[0]];for(let i=1;i0&&a.position&&a.velocity){const o=e[s-1];if(o.position&&o.velocity){const l=a.time-o.time;if(l>.001){const c=(o.velocity.x+a.velocity.x)/2,u=(o.velocity.y+a.velocity.y)/2,d=(o.velocity.z+a.velocity.z)/2,h=Math.sqrt(c**2+u**2+d**2);if(h>100){const f=a.position.x-o.position.x,p=a.position.y-o.position.y,g=a.position.z-o.position.z,_=Math.sqrt(f*f+p*p+g*g),m=h*l,v=_/m;let y=0;v>.15&&v<.35?y=l*.75:v>.4&&v<.6?y=l*.5:v>.65&&v<.85&&(y=l*.25),y>0&&(r.position.x+=a.velocity.x*y,r.position.y+=a.velocity.y*y,r.position.z+=a.velocity.z*y,i++)}}}}t.push(r)}return t._correctedCount=i,t}_timeShiftedInterpolate(e,t,i){const s=i-e.time,a=t.time-e.time,r=Math.max(0,Math.min(1,s/a));return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r}}_velocityAnchoredInterpolate(e,t,i,s,a,r){if(!t.velocity||!i.velocity){const m=(s-t.time)/(i.time-t.time);return{x:t.position.x+(i.position.x-t.position.x)*m,y:t.position.y+(i.position.y-t.position.y)*m,z:t.position.z+(i.position.z-t.position.z)*m}}this._velocityAnchorState||(this._velocityAnchorState=new Map);let o=this._velocityAnchorState.get(e);(!o||Math.abs(s-o.lastTime)>.5||r%10===0)&&(o={anchorPos:{...t.position},anchorTime:t.time,anchorIdx:r,lastTime:s},this._velocityAnchorState.set(e,o)),s-o.anchorTime;let u=o.anchorPos.x,d=o.anchorPos.y,h=o.anchorPos.z;const f=(t.velocity.x+i.velocity.x)/2,p=(t.velocity.y+i.velocity.y)/2,g=(t.velocity.z+i.velocity.z)/2,_=s-t.time;return o.anchorIdx===r?(u=o.anchorPos.x+f*_,d=o.anchorPos.y+p*_,h=o.anchorPos.z+g*_):(u=t.position.x+f*_,d=t.position.y+p*_,h=t.position.z+g*_),o.lastTime=s,{x:u,y:d,z:h}}_hermiteInterpolate(e,t,i){const s=t.time-e.time,a=i-e.time,r=Math.max(0,Math.min(1,a/s)),o={x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};if(!e.velocity||!t.velocity)return o;const l=r*r,c=l*r,u=2*c-3*l+1,d=c-2*l+r,h=-2*c+3*l,f=c-l,p={x:e.velocity.x*s,y:e.velocity.y*s,z:e.velocity.z*s},g={x:t.velocity.x*s,y:t.velocity.y*s,z:t.velocity.z*s},_={x:u*e.position.x+d*p.x+h*t.position.x+f*g.x,y:u*e.position.y+d*p.y+h*t.position.y+f*g.y,z:u*e.position.z+d*p.z+h*t.position.z+f*g.z},m=_.x-o.x,v=_.y-o.y,y=_.z-o.z,b=t.position.x-e.position.x,T=t.position.y-e.position.y,x=t.position.z-e.position.z;return m*m+v*v+y*y>b*b+T*T+x*x?o:_}_physicsSimInterpolate(e,t,i,s=!1){const a=t.time-e.time,r=i-e.time,o=Math.max(0,Math.min(1,r/a));if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*o,y:e.position.y+(t.position.y-e.position.y)*o,z:e.position.z+(t.position.z-e.position.z)*o};const l=-650,c=o*o,u=c*o,d=2*u-3*c+1,h=u-2*c+o,f=-2*u+3*c,p=u-c;let g=e.velocity.y*a,_=t.velocity.y*a;if(s){const m=.5*l*a*a;g+=m*.5,_+=m*.5}return{x:d*e.position.x+h*(e.velocity.x*a)+f*t.position.x+p*(t.velocity.x*a),y:d*e.position.y+h*g+f*t.position.y+p*_,z:d*e.position.z+h*(e.velocity.z*a)+f*t.position.z+p*(t.velocity.z*a)}}getBallPositionAt(e){if(!this.ballTimeline||this.ballTimeline.length<2)return null;const t=this.ballTimeline[0];if(e2e3)return s.sleeping?null:{...s.position};if(s.sleeping)return{...s.position};const d=(e-s.time)/r;let h;switch(this.interpolationMethod){case"catmull-rom":{const f=this.ballTimeline[Math.max(0,i-1)],p=this.ballTimeline[Math.min(this.ballTimeline.length-1,i+2)];f?.position&&p?.position?h=this._catmullRomInterpolate(f.position,s.position,a.position,p.position,d):h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}case"lerp-smooth":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applySmoothing("ball",h);break}case"lerp-ema":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyEmaSmoothing("ball",h);break}case"lerp-dema":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyDoubleEmaSmoothing("ball",h);break}case"lerp-wma":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyWeightedSmoothing("ball",h);break}case"lerp-gauss":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyGaussianSmoothing("ball",h);break}case"one-euro":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyOneEuroFilter("ball",h);break}case"predict-correct":{h=this._predictCorrectInterpolate("ball",s,a,e);break}case"velocity-smooth":{h=this._velocitySmoothInterpolate("ball",s,a,e,!0);break}case"physics-tick":{h=this._physicsTickInterpolate(s,a,e);break}case"hermite":{h=this._hermiteInterpolate(s,a,e);break}case"physics-sim":{const f=this.ballTimelineCorrected;if(f&&f.length>=2){const p=this._findKeyframeIndex(f,e,this.timelineIndicesCorrected.ball);this.timelineIndicesCorrected.ball=p;const g=f[p],_=f[p+1];if(g?.position&&_?.position){h=this._physicsSimInterpolate(g,_,e,!0);break}}h=this._physicsSimInterpolate(s,a,e,!0);break}case"velocity-only":{h=this._velocityOnlyInterpolate(s,a,e);break}case"smart-hybrid":{h=this._smartHybridInterpolate(s,a,e);break}case"time-shifted":{const f=this.ballTimelineFiltered;if(!f||f.length<2){h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}const p=this._findKeyframeIndex(f,e,this.timelineIndicesFiltered.ball);this.timelineIndicesFiltered.ball=p;const g=f[p],_=f[p+1];if(!g?.position||!_?.position){h=g?.position?{...g.position}:{...s.position};break}const m=_.time-g.time,v=m>0?Math.max(0,Math.min(1,(e-g.time)/m)):0;h={x:g.position.x+(_.position.x-g.position.x)*v,y:g.position.y+(_.position.y-g.position.y)*v,z:g.position.z+(_.position.z-g.position.z)*v};break}case"position-lerp":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}case"position-catmull":{const f=this.ballTimeline[Math.max(0,i-1)],p=this.ballTimeline[Math.min(this.ballTimeline.length-1,i+2)];f?.position&&p?.position?h=this._catmullRomInterpolate(f.position,s.position,a.position,p.position,d):h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}case"position-smooth":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyLowPassFilter("ball",h);break}case"adaptive-smooth":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyAdaptiveSmoothing("ball",h,e);break}default:{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}}return h}getBallRotationAt(e){if(!this.ballTimeline||this.ballTimeline.length<2)return null;const t=this.ballTimeline[0];if(e2e3)return{...s.rotation}}if(s.sleeping)return{...s.rotation};const o=(e-s.time)/r;return this._q0.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w),this._q1.set(a.rotation.x,a.rotation.y,a.rotation.z,a.rotation.w),this._qResult.slerpQuaternions(this._q0,this._q1,o),{x:this._qResult.x,y:this._qResult.y,z:this._qResult.z,w:this._qResult.w}}getPlayerPositionAt(e,t){const i=this.playerTimelineMap[e];if(!i||i.length<2)return null;const s=i[0];if(t=2){const h=this._findKeyframeIndex(d,t,this.timelineIndicesCorrected.players[e]||0);this.timelineIndicesCorrected.players[e]=h;const f=d[h],p=d[h+1];if(f?.position&&p?.position){u=this._physicsSimInterpolate(f,p,t,!1);break}}u=this._physicsSimInterpolate(r,o,t,!1);break}case"velocity-only":{u=this._velocityOnlyInterpolate(r,o,t);break}case"smart-hybrid":{u=this._smartHybridInterpolate(r,o,t);break}case"time-shifted":{const d=this.playerTimelineMapFiltered[e];if(!d||d.length<2){u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}const h=this._findKeyframeIndex(d,t,this.timelineIndicesFiltered.players[e]||0);this.timelineIndicesFiltered.players[e]=h;const f=d[h],p=d[h+1];if(!f?.position||!p?.position){u=f?.position?{...f.position}:{...r.position};break}const g=p.time-f.time,_=g>0?Math.max(0,Math.min(1,(t-f.time)/g)):0;u={x:f.position.x+(p.position.x-f.position.x)*_,y:f.position.y+(p.position.y-f.position.y)*_,z:f.position.z+(p.position.z-f.position.z)*_};break}case"position-lerp":{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}case"position-catmull":{const d=i[Math.max(0,a-1)],h=i[Math.min(i.length-1,a+2)];d?.position&&h?.position?u=this._catmullRomInterpolate(d.position,r.position,o.position,h.position,c):u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}case"position-smooth":{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c},u=this._applyLowPassFilter(`player-${e}`,u);break}case"adaptive-smooth":{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c},u=this._applyAdaptiveSmoothing(`player-${e}`,u,t);break}default:{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}}return u}getPlayerRotationAt(e,t){const i=this.playerTimelineMap[e];if(!i||i.length<2)return null;const s=i[0];if(t=2){const r=this.getBallPositionAt(t),o=this.getBallRotationAt(t);r?i.position.set(r.x,r.y,r.z):a=!1,o&&i.quaternion.set(o.x,o.y,o.z,o.w)}else i.position.set(s.position.x,s.position.y,s.position.z),i.quaternion.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w);if(i.userData.location.copy(i.position),i.userData.rotation.copy(i.quaternion),i.userData.velocity.set(s.velocity.x,s.velocity.y,s.velocity.z),s.angularVelocity&&i.userData.angularVelocity.set(s.angularVelocity.x,s.angularVelocity.y,s.angularVelocity.z),i.userData.sleeping=s.sleeping,i.visible=a&&s.visible!==!1&&!i.userData.isHiddenByGoal,this.ballIndicator&&(this.ballIndicator.position.set(i.position.x,2,i.position.z),this.ballIndicator.visible=i.visible),this.ballVerticalLine){const o=new Float32Array([i.position.x,2,i.position.z,i.position.x,i.position.y,i.position.z]);this.ballVerticalLine.geometry.setAttribute("position",new ot(o,3)),this.ballVerticalLine.geometry.attributes.position.needsUpdate=!0,this.ballVerticalLine.visible=i.visible}if(i.userData.velocity&&i.visible){let r=this.lastBallTouchTeam,o=this.BALL_TOUCH_DISTANCE;Object.keys(this.actors).forEach(l=>{const c=this.actors[l];if(c&&c.userData.isCar&&c.userData.playerId){const u=i.position.distanceTo(c.position);u{const a=this.playerNameToCarActorId[s.name];if(!a)return;const r=this.actors[a];if(!r)return;const o=s.name;if(!this.useAnimationSystem||!this.animationMixer)if(this.interpolantsInitialized&&this.playerTimelineMap[o]){const c=this.getPlayerPositionAt(o,t),u=this.getPlayerRotationAt(o,t);c&&r.position.set(c.x,c.y,c.z),u&&r.quaternion.set(u.x,u.y,u.z,u.w)}else r.position.set(s.position.x,s.position.y,s.position.z),r.quaternion.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w);r.userData.location.copy(r.position),r.userData.rotation.copy(r.quaternion),r.userData.velocity.set(s.velocity.x,s.velocity.y,s.velocity.z),r.userData.sleeping=s.sleeping,r.userData.steer=s.steer||0;const l=r.position.length()>.1;r.visible=s.isVisible&&l&&!r.userData.sleeping}),this._updateGoalExplosions(t)}_updateGoalExplosions(e){const t=this.effectsManager,i=t&&t.explosions?t.explosions.goalEvents:null;if(!(i instanceof Map)||i.size===0)return;const s=this._lastGoalScanTime;s!==null&&e=c&&e<=c+oF&&(r=!0,o=!0),s!==null&&s=c&&!this._firedGoalTimes.has(c)){this._firedGoalTimes.add(c);const d=this.getBallPositionAt(c)||a&&a.position||null;d&&this.effectsManager.triggerGoalExplosion(d,l.team)}}a&&(a.userData.isHiddenByGoal=r,r&&(a.visible=!1)),o||this.effectsManager.clearGoalExplosions?.(),this._lastGoalScanTime=e}processFrame(e,t,i,s){if(e){if(e.new_actors&&e.new_actors.forEach(a=>{if(!this.actors[a.actor_id]){const r=t(a.object_id),o=r&&r.includes("Ball"),l=r&&r.includes("Car");if(o||l){let c;o?c=new yn(92.75,16,16):c=new Ci(118,36,84);const u=new Pn({color:o?16777215:Math.random()*16777215}),d=new we(c,u);if(d.userData={location:new S,rotation:new dt,isCar:l,isBall:o,playerId:null,lastUpdateTime:e.time,bodyId:null,hasReceivedUpdate:!1},this.scene.add(d),this.actors[a.actor_id]=d,o){this.ballActorId=a.actor_id,this.ballModel&&this.replaceBallWithModel(a.actor_id);const h=92.75,f=new ni(h*.95,h,32),p=new Ye({color:16777215,side:ct});this.ballIndicator=new we(f,p),this.ballIndicator.rotation.x=-Math.PI/2,this.ballIndicator.visible=!1,this.scene.add(this.ballIndicator);const g=new Ge().setFromPoints([new S(0,0,0),new S(0,1,0)]),_=new Rt({color:16777215,opacity:.5,transparent:!0});this.ballVerticalLine=new In(g,_),this.ballVerticalLine.frustumCulled=!1,this.ballVerticalLine.visible=!1,this.scene.add(this.ballVerticalLine)}else l&&this.effectsManager.createBoostTrail(d,a.actor_id)}}}),e.deleted_actors&&e.deleted_actors.forEach(a=>{if(this.actors[a]){const r=this.actors[a];r.userData.isCar&&this.effectsManager.removeBoostTrail(a),this.scene.remove(r),r.geometry&&r.geometry.dispose(),r.material&&r.material.dispose(),delete this.actors[a],this.ballActorId===a&&(this.ballActorId=null,this.ballIndicator&&(this.scene.remove(this.ballIndicator),this.ballIndicator.geometry&&this.ballIndicator.geometry.dispose(),this.ballIndicator.material&&this.ballIndicator.material.dispose(),this.ballIndicator=null),this.ballVerticalLine&&(this.scene.remove(this.ballVerticalLine),this.ballVerticalLine.geometry&&this.ballVerticalLine.geometry.dispose(),this.ballVerticalLine.material&&this.ballVerticalLine.material.dispose(),this.ballVerticalLine=null))}}),e.updated_actors&&e.updated_actors.forEach(a=>{const r=this.actors[a.actor_id];a.attribute.TeamLoadout&&(this.actorLoadouts[a.actor_id]=a.attribute.TeamLoadout,r&&r.userData.isCar&&(r.userData.teamLoadout=a.attribute.TeamLoadout,this.resolveBodyId(r,a.actor_id)));const o=t(a.object_id),l=o&&(o.includes("PRI_TA")||o.includes("PlayerReplicationInfo"));if(a.attribute.String&&this.playerNames.has(a.attribute.String)){const c=a.attribute.String;this.actorToPlayer[a.actor_id]=c,l&&!this.playerNameToPriActorId[c]&&(this.playerNameToPriActorId[c]=a.actor_id,console.log(`[ActorManager] Mapped ${c} -> PRI Actor ${a.actor_id} (object: ${o})`)),this.checkCarPlayerLink(a.actor_id)}if(a.attribute.Reservation&&this.playerNames.has(a.attribute.Reservation.name)){const c=a.attribute.Reservation.name;this.actorToPlayer[a.actor_id]=c,l&&!this.playerNameToPriActorId[c]&&(this.playerNameToPriActorId[c]=a.actor_id,console.log(`[ActorManager] Mapped ${c} -> PRI Actor ${a.actor_id} (object: ${o})`)),this.checkCarPlayerLink(a.actor_id)}if(a.attribute.ActiveActor){const c=a.attribute.ActiveActor.actor;this.actorLinks[a.actor_id]||(this.actorLinks[a.actor_id]=new Set),this.actorLinks[a.actor_id].add(c),r&&r.userData.isCar&&this.checkCarPlayerLink(c,a.actor_id)}if(r&&a.attribute&&a.attribute.RigidBody){const c=a.attribute.RigidBody;if(c.location&&(r.userData.location.set(c.location.x,c.location.z,c.location.y),r.userData.lastUpdateTime=e.time,r.userData.hasReceivedUpdate=!0),c.linear_velocity&&(r.userData.velocity||(r.userData.velocity=new S),r.userData.velocity.set(c.linear_velocity.x,c.linear_velocity.z,c.linear_velocity.y)),c.rotation&&r.userData.rotation.set(c.rotation.x,c.rotation.z,c.rotation.y,-c.rotation.w),c.angular_velocity&&(r.userData.angularVelocity||(r.userData.angularVelocity=new S),r.userData.angularVelocity.set(c.angular_velocity.x,c.angular_velocity.z,c.angular_velocity.y)),c.sleeping!==void 0&&(r.userData.sleeping=c.sleeping,c.sleeping&&(r.userData.velocity&&r.userData.velocity.set(0,0,0),r.userData.angularVelocity&&r.userData.angularVelocity.set(0,0,0))),r.userData.isBall&&r.userData.isHiddenByGoal&&c.location){const u=c.location.x,d=c.location.y,h=c.location.z;Math.sqrt(u*u+d*d+h*h)<500&&(r.userData.isHiddenByGoal=!1)}}}),this.effectsManager.explosions.goalEvents.has(i)){const a=this.effectsManager.explosions.goalEvents.get(i),r=this.actors[this.ballActorId];r&&(s||(this.effectsManager.triggerGoalExplosion(r.position,a.team),console.log(`🎯 GOAL! Explosion at frame ${i} for team ${a.team} by ${a.playerName}`)),r.userData.isHiddenByGoal=!0)}if(this.effectsManager.explosions.demoEvents.has(i)){const a=this.effectsManager.explosions.demoEvents.get(i),r=this.actors[a.victimActorId];if(r){if(!s){const o=r.userData.playerId,l=o&&this.playerTeams&&this.playerTeams[o]||0;this.effectsManager.triggerDemoExplosion(r.position,l),console.log(`💥 DEMO! Explosion at frame ${i} for actor ${a.victimActorId}`)}r.userData.sleeping=!0}}}}resolveBodyId(e,t){if(!e||!e.userData.isCar||!e.userData.teamLoadout)return;let i=0;e.userData.playerId&&Object.prototype.hasOwnProperty.call(this.playerTeams,e.userData.playerId)&&(i=this.playerTeams[e.userData.playerId]);const s=e.userData.teamLoadout,a=i===1?s.orange?.body:s.blue?.body;a&&e.userData.bodyId!==a&&(e.userData.bodyId=a,this.updateCarHitbox(e,a,t))}updateCarHitbox(e,t,i){const s=Aw(t),a=s?.name||"Octane",r=s?.hitboxType||"Octane";this.replaceCarWithModel(i,e,a,r)}async replaceCarWithModel(e,t,i,s){if(this.carModelLoader.isModelReady(i,s))this._doCarReplacement(e,t,i,s);else{this.pendingCarReplacements.set(e,{oldMesh:t,carName:i,hitboxType:s});try{const a=this.carModelLoader.getModelTypeForCar(i,s);await this.carModelLoader.loadModel(a);const r=this.pendingCarReplacements.get(e);r&&this.actors[e]===r.oldMesh&&this._doCarReplacement(e,r.oldMesh,r.carName,r.hitboxType),this.pendingCarReplacements.delete(e)}catch(a){console.warn(`Failed to load model for ${i} (${s}):`,a),this.pendingCarReplacements.delete(e),t&&(t.visible=!0)}}}_doCarReplacement(e,t,i,s){let a=0;t.userData.playerId&&Object.prototype.hasOwnProperty.call(this.playerTeams,t.userData.playerId)?a=this.playerTeams[t.userData.playerId]:t.userData.team!==void 0&&(a=t.userData.team);const r=this.carModelLoader.getCarMeshSync(i,s,a);if(!r){console.warn(`Could not get car mesh for ${i} (${s})`);return}const o=r.userData.wheels;r.userData={...t.userData},r.userData.isFBXModel=!0,r.userData.carName=i,r.userData.hitboxType=s,r.userData.wheels=o,r.position.copy(t.position),r.quaternion.copy(t.quaternion),this.scene.remove(t),t.geometry&&t.geometry.dispose(),t.material&&(Array.isArray(t.material)?t.material.forEach(c=>c.dispose()):t.material.dispose()),this.scene.add(r),this.actors[e]=r,this.effectsManager.removeBoostTrail(e),this.effectsManager.createBoostTrail(r,e);const l=this.carModelLoader.getModelTypeForCar(i,s);console.log(`🚗 Replaced car ${e} with ${l.toUpperCase()} model (${i}, ${s} hitbox, team ${a===0?"blue":"orange"})`)}checkCarPlayerLink(e,t){const i=this.actorToPlayer[e],s=this.actorLoadouts[e];if(!(!i&&!s))if(t){const a=this.actors[t];a&&a.userData.isCar&&(this.onPlayerFound&&this.onPlayerFound(i),a.userData.playerId=i,this.playerNameToCarActorId[i]=t,s&&(a.userData.teamLoadout=s),this.resolveBodyId(a,t))}else this.actorLinks[e]&&this.actorLinks[e].forEach(a=>{this.checkCarPlayerLink(e,a)})}updateInterpolation(e,t,i){const s=t[i];if(s&&Object.keys(this.actors).forEach(a=>{const r=this.actors[a],o=r.userData.location,l=r.userData.rotation;if(!o||!l||!r.userData.hasReceivedUpdate)return;let c=null,u=0;for(let d=i+1;dp.actor_id==a&&p.attribute&&p.attribute.RigidBody);if(f){c=f,u=h.time;break}}}if(c){const d=r.userData.lastUpdateTime||s.time,h=u;if(h>d){const f=(e-d)/(h-d),p=Math.max(0,Math.min(1,f)),g=h-d||.033,_=c.attribute.RigidBody;if(_.location)if(this._p0.copy(o),this._p1.set(_.location.x,_.location.z,_.location.y),r.userData.sleeping)r.position.copy(o);else{const m=c.attribute.RigidBody;if(r.userData.velocity&&m.linear_velocity){const v=p,y=v*v,b=y*v;if(g>.5)r.position.lerpVectors(o,this._p1,p);else{this._v0.copy(r.userData.velocity).multiplyScalar(g),this._v1.set(m.linear_velocity.x,m.linear_velocity.z,m.linear_velocity.y).multiplyScalar(g);const T=2*b-3*y+1,x=b-2*y+v,M=-2*b+3*y,C=b-y;r.position.set(T*this._p0.x+x*this._v0.x+M*this._p1.x+C*this._v1.x,T*this._p0.y+x*this._v0.y+M*this._p1.y+C*this._v1.y,T*this._p0.z+x*this._v0.z+M*this._p1.z+C*this._v1.z)}}else r.position.lerpVectors(o,this._p1,p)}else r.position.copy(o);_.rotation?(this._nextRot.set(_.rotation.x,_.rotation.z,_.rotation.y,-_.rotation.w),r.quaternion.slerpQuaternions(l,this._nextRot,p)):r.quaternion.copy(l);return}}r.position.copy(o),r.quaternion.copy(l)}),Object.keys(this.actors).forEach(a=>{const r=this.actors[a];if(r&&r.userData.isCar){const l=r.position.length()>.1,c=r.userData.sleeping===!0;r.visible=l&&!c}}),this.ballActorId&&this.actors[this.ballActorId]){const a=this.actors[this.ballActorId];if(a.visible=!a.userData.isHiddenByGoal,this.ballIndicator&&(this.ballIndicator.position.set(a.position.x,2,a.position.z),this.ballIndicator.visible=a.visible),this.ballVerticalLine){const o=new Float32Array([a.position.x,2,a.position.z,a.position.x,a.position.y,a.position.z]);this.ballVerticalLine.geometry.setAttribute("position",new ot(o,3)),this.ballVerticalLine.geometry.attributes.position.needsUpdate=!0,this.ballVerticalLine.visible=a.visible}if(a.userData.velocity&&a.visible){let r=this.lastBallTouchTeam,o=this.BALL_TOUCH_DISTANCE;Object.keys(this.actors).forEach(l=>{const c=this.actors[l];if(c&&c.userData.isCar&&c.userData.playerId){const u=a.position.distanceTo(c.position);if(u{const s=this.actors[i];if(!s||!s.userData.isCar||!s.userData.isFBXModel&&!s.userData.hasWheelSockets||!s.userData.wheels||s.userData.wheels.length===0)return;const a=s.position;let r=this._previousCarPositions.get(i);r||(r=a.clone(),this._previousCarPositions.set(i,r));const l=new S().subVectors(a,r).length();if(this._previousCarPositions.set(i,a.clone()),l<.01)return;const d=Math.min(l/e,.5)*1;let h=0;s.userData.steer!==void 0&&(h=-s.userData.steer*t),s.userData.wheels.forEach(f=>{if(f.socket){const p=f.side==="left"?1:-1;if(f.mesh.rotateZ(p*d),f.position==="front"&&f.steeringPivot){const g=f.side==="left"?-1:1;f.steeringPivot.rotation.y=g*h}}else{const p=f.side==="left"?-1:1;f.mesh.rotateY(p*d),f.position==="front"&&f.steeringPivot&&(f.steeringPivot.rotation.z=h)}})})}resetWheelTracking(){this._previousCarPositions&&this._previousCarPositions.clear()}updateSupersonicState(e,t,i){const s=this.playerNameToCarActorId[e];if(!s)return;const a=this.actors[s];if(!a||!a.userData.isCar)return;const r=a.userData.velocity||new S(0,0,0);this.effectsManager.updateSupersonicTrail(s,t,a.position,a.quaternion,r,i)}setInterpolationEnabled(e){this.interpolationEnabled=e,console.log(`[ActorManager] Interpolation ${e?"enabled":"disabled"}`)}setInterpolationMethod(e){if(!["lerp","hermite","catmull-rom","predict-correct","velocity-smooth","physics-tick","velocity-only","smart-hybrid","time-shifted","lerp-smooth","lerp-ema","lerp-dema","lerp-wma","lerp-gauss","one-euro","position-lerp","position-catmull","position-smooth","adaptive-smooth"].includes(e)){console.warn(`[ActorManager] Invalid interpolation method: ${e}`);return}this.interpolationMethod=e,this._smoothingBuffers.clear(),this._lowPassState.clear(),this._adaptiveState.clear(),this.resetSmoothingBuffers(),console.log(`[ActorManager] Interpolation method set to: ${e}`)}setSmoothingWindowSize(e){this.smoothingWindowSize=Math.max(1,Math.min(20,e)),this._smoothingBuffers.clear(),console.log(`[ActorManager] Smoothing window size set to: ${this.smoothingWindowSize}`)}getInterpolationSettings(){return{enabled:this.interpolationEnabled,method:this.interpolationMethod,smoothingWindowSize:this.smoothingWindowSize}}clearSmoothingBuffers(){this._smoothingBuffers.clear()}getFrameInfo(){return this.lastFrameInfo}createBallMeshForLive(){const e=new yn(92.75,16,16),t=new Pn({color:16777215}),i=new we(e,t);if(i.castShadow=!0,i.receiveShadow=!0,i.userData={location:new S,rotation:new dt,velocity:new S,angularVelocity:new S,isCar:!1,isBall:!0,playerId:null,sleeping:!1,isHiddenByGoal:!1},this.scene.add(i),this.ballModel){const s=this.ballModel.clone();s.position.copy(i.position),s.quaternion.copy(i.quaternion),s.userData={...i.userData};const a=92.75;return s.scale.set(a,a,a),s.traverse(r=>{r.isMesh&&(r.castShadow=!0,r.receiveShadow=!0)}),this.scene.remove(i),this.scene.add(s),i.geometry&&i.geometry.dispose(),i.material&&i.material.dispose(),console.log("✓ Live ball created with GLTF model"),s}return i}createCarMeshForLive(e,t,i,s=null){const a=`live_car_${t}`,r=new Ci(118,36,84),o=e===0?3381759:16737792,l=new Pn({color:o}),c=new we(r,l);return c.castShadow=!0,c.receiveShadow=!0,c.visible=!1,c.userData={location:new S,rotation:new dt,velocity:new S,angularVelocity:new S,isCar:!0,isBall:!1,playerId:i,team:e,sleeping:!1,steer:0,bodyId:s,liveActorId:a},this.scene.add(c),this.actors[a]=c,this.playerNameToCarActorId[i]=a,this.effectsManager.createBoostTrail(c,a),s&&s>0?this.updateCarHitbox(c,s,a):this.replaceCarWithModel(a,c,"Octane","Octane"),console.log(`[ActorManager] Created live car for ${i} (team ${e===0?"blue":"orange"}, bodyId: ${s})`),c}updateBoostParticlesLive(e,t,i,s){const a=t&&i>0,r=s.userData.velocity||new S(0,0,0);this.effectsManager.updateBoostTrail(e,a,s.position,s.quaternion,r)}updateSupersonicTrailLive(e,t,i,s){const a=s.userData.velocity||new S(0,0,0);this.effectsManager.updateSupersonicTrail(e,t,s.position,s.quaternion,a,i)}removeLiveCar(e){const t=this.actors[e];t&&(this.scene.remove(t),t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose(),delete this.actors[e],this.effectsManager.removeBoostTrail(e))}removeLiveBall(e){e&&(this.scene.remove(e),e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose())}}function Ms(n,e,t){t===-1?(n.clearUpdateRanges?.(),n.addUpdateRange?.(0,n.count*n.itemSize)):n.addUpdateRange?(n.clearUpdateRanges(),n.addUpdateRange(e,t)):(n.updateRange.offset=e,n.updateRange.count=t)}class pt extends Qe{constructor(e,t){super(),this.active=!1,this.orientToMovement=!1,t&&(this.orientToMovement=!0),this.scene=e,this.geometry=null,this.mesh=null,this.nodeCenters=null,this.lastNodeCenter=null,this.currentNodeCenter=null,this.lastOrientationDir=null,this.nodeIDs=null,this.currentLength=0,this.currentEnd=0,this.currentNodeID=0,this.advanceFrequency=60,this.advancePeriod=1/this.advanceFrequency,this.lastAdvanceTime=0,this.paused=!1,this.pauseAdvanceUpdateTimeDiff=0,this._internalTime=0,this._useInternalTime=!1}setAdvanceFrequency(e){this.advanceFrequency=e,this.advancePeriod=1/this.advanceFrequency}initialize(e,t,i,s,a,r){this.deactivate(),this.destroyMesh(),this.length=t>0?t+1:0,this.dragTexture=i?1:0,this.targetObject=r,this.initializeLocalHeadGeometry(s,a),this.nodeIDs=[],this.nodeCenters=[];for(let o=0;o=this.length?0:this.currentEnd+1;if(i?this.updateNodePositionsFromTransformMatrix(s,i):this.updateNodePositionsFromOrientationTangent(s,t.position,t.tangent),this.currentLength>=1&&(this.connectNodes(this.currentEnd,s),this.currentLength>=this.length)){const a=this.currentEnd+1>=this.length?0:this.currentEnd+1;this.disconnectNodes(a)}this.currentLength=this.length&&(this.currentEnd=0),this.currentLength>=1&&(this.currentLengththis.advancePeriod?(this.advance(),this.lastAdvanceTime=t):this.updateHead()}}updateHead=(function(){const e=new Me;return function(){this.currentEnd<0||(this.targetObject.updateMatrixWorld(),e.copy(this.targetObject.matrixWorld),this.updateNodePositionsFromTransformMatrix(this.currentEnd,e))}})();updateNodeID(e,t){this.nodeIDs[e]=t;const i=this.geometry.getAttribute("nodeID"),s=this.geometry.getAttribute("nodeVertexID");for(let a=0;a1e-4)){this.lastOrientationDir||(this.lastOrientationDir=new S),t.setFromUnitVectors(a,r),s.copy(this.currentNodeCenter);for(let f=0;fe.add(a)),this.mainTrail=this._createMainTrail(),this.secondaryTrails=this._createSecondaryTrails(),this._updateColors(),this._updateIntensity(),this.mainTrail.activate(),this.secondaryTrails.forEach(a=>a.activate())}_createMainTrail(){const e=new pt(this.scene,!1),t=tv(),i=this.config.mainTrailWidth,s=[new S(0,-i,0),new S(0,i,0),new S(-i,0,0),new S(i,0,0),new S(0,0,-i),new S(0,0,i)];return e.initialize(t,this.config.trailLength,!1,0,s,this.mainTarget),e.setAdvanceFrequency(60),e.mesh&&(e.mesh.frustumCulled=!1,e.mesh.renderOrder=100),e}_createSecondaryTrails(){const e=[];for(let t=0;t<4;t++){const i=new pt(this.scene,!1),s=tv(),a=this.config.secondaryTrailWidth,r=[new S(0,-a,0),new S(0,a,0),new S(-a,0,0),new S(a,0,0),new S(0,0,-a),new S(0,0,a)];i.initialize(s,this.config.trailLength,!1,0,r,this.secondaryTargets[t]),i.setAdvanceFrequency(60),i.mesh&&(i.mesh.frustumCulled=!1,i.mesh.renderOrder=100),e.push(i)}return e}_updateColors(){const e=this.teamColors[this.team]||this.teamColors[0];this.mainTrail?.material&&(this.mainTrail.material.uniforms.headColor.value.copy(e.head),this.mainTrail.material.uniforms.tailColor.value.copy(e.tail));const t=e.head.clone();t.w=e.head.w*.85;const i=e.tail.clone();this.secondaryTrails.forEach(s=>{s?.material&&(s.material.uniforms.headColor.value.copy(t),s.material.uniforms.tailColor.value.copy(i))})}_updateIntensity(){this.mainTrail?.material&&(this.mainTrail.material.uniforms.intensityMultiplier.value=this.intensity),this.secondaryTrails.forEach(e=>{e?.material&&(e.material.uniforms.intensityMultiplier.value=this.intensity)})}setTeam(e){this.team!==e&&(this.team=e,this._updateColors())}setIntensity(e){this.intensity=e,this.dying||this._updateIntensity()}startDying(){this.dying||(this.dying=!0,this.deathTime=0,this.mainTrail.pause(),this.secondaryTrails.forEach(e=>e.pause()))}updatePosition(e,t,i){if(this.dying)return;const s=t.clone().normalize();this.mainTarget.position.copy(e),this.mainTarget.updateMatrixWorld();for(let a=0;a<4;a++){const o=a/4*Math.PI*2+i,l=new S(Math.cos(o)*this.config.secondaryTrailOffset,Math.sin(o)*this.config.secondaryTrailOffset,0);if(s.lengthSq()>.001){const c=new S(0,0,1),u=new dt;u.setFromUnitVectors(c,s),l.applyQuaternion(u)}this.secondaryTargets[a].position.copy(e).add(l),this.secondaryTargets[a].updateMatrixWorld()}}update(e){if(this.dying){this.deathTime+=e;const t=Math.min(1,this.deathTime/this.maxDeathTime),i=this.intensity*(1-t);this.mainTrail?.material&&(this.mainTrail.material.uniforms.intensityMultiplier.value=i),this.secondaryTrails.forEach(s=>{s?.material&&(s.material.uniforms.intensityMultiplier.value=i)}),this.deathTime>=this.maxDeathTime&&(this.active=!1)}this.mainTrail.isActive&&this.mainTrail.update(e),this.secondaryTrails.forEach(t=>{t.isActive&&t.update(e)})}dispose(){this.mainTrail.deactivate(),this.secondaryTrails.forEach(e=>e.deactivate()),this.mainTrail.geometry&&this.mainTrail.geometry.dispose(),this.mainTrail.material&&this.mainTrail.material.dispose(),this.secondaryTrails.forEach(e=>{e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()}),this.scene.remove(this.mainTarget),this.secondaryTargets.forEach(e=>this.scene.remove(e))}}class eF{constructor(e,t=0){this.scene=e,this.team=t,this.active=!1,this.ballRadius=92.75,this.config={trailLength:60,mainTrailWidth:15,secondaryTrailWidth:1.5,secondaryTrailOffset:this.ballRadius*.7},this.rotationSpeed=Math.PI/3,this.currentRotation=0,this.minVelocity=1500,this.maxVelocity=6e3,this.minIntensity=.3,this.maxIntensity=1,this.wasEmitting=!1,this.segments=[],this.currentSegment=null,this.currentIntensity=1}_calculateIntensity(e){if(e<=this.minVelocity)return this.minIntensity;if(e>=this.maxVelocity)return this.maxIntensity;const t=(e-this.minVelocity)/(this.maxVelocity-this.minVelocity);return this.minIntensity+t*(this.maxIntensity-this.minIntensity)}setTeam(e){this.team!==e&&(this.team=e,this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.startDying(),this.currentSegment=null))}activate(){this.active||(this.active=!0,this.currentSegment=null,this.wasEmitting=!1)}deactivate(){this.active&&(this.active=!1,this.currentSegment&&(this.currentSegment.startDying(),this.currentSegment=null))}emit(e,t,i){const s=t.length();if(!(s>=this.minVelocity)){this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.startDying(),this.currentSegment=null),this.wasEmitting=!1;return}this.currentIntensity=this._calculateIntensity(s),this.active||this.activate(),!this.wasEmitting||!this.currentSegment?(this.currentSegment&&!this.currentSegment.dying&&this.currentSegment.startDying(),this.currentSegment=new QO(this.scene,this.team,this.config,this.currentIntensity),this.segments.push(this.currentSegment)):this.currentSegment.setIntensity(this.currentIntensity),this.wasEmitting=!0,this.currentRotation+=this.rotationSpeed*i,this.currentRotation>Math.PI*2&&(this.currentRotation-=Math.PI*2),this.currentSegment.updatePosition(e,t,this.currentRotation)}update(e){for(let t=this.segments.length-1;t>=0;t--){const i=this.segments[t];i.update(e),i.active||(i.dispose(),this.segments.splice(t,1))}}reset(){for(const e of this.segments)e.dispose();this.segments=[],this.currentSegment=null,this.currentRotation=0,this.wasEmitting=!1}addToScene(e){}removeFromScene(e){for(const t of this.segments)t.startDying();this.currentSegment=null}dispose(){for(const e of this.segments)e.dispose();this.segments=[],this.currentSegment=null}}let du=null,hu=null,fu=null,nv=!1;function tF(){nv||(aF(),rF(),oF(),nv=!0)}let di=null;class nF{constructor(e,t,i,s=2){this.scene=e,this.renderer=t,this.camera=i,this.maxExplosions=s,this.explosions=[],this.warmedUp=!1,this.initPool()}initPool(){this.sphereGeo=new yn(1,16,12),this.coreGeo=new yn(1,12,8),this.ringGeo=new ni(.5,1,32),this.particleGeo=new Dn(1,1),this.coreMaterial=new Ye({color:16777130,transparent:!0,opacity:.9,blending:Ht,side:ct,depthWrite:!1}),this.sphereMaterial=new Ye({color:16737792,transparent:!0,opacity:.5,blending:Ht,side:ct,depthWrite:!1}),this.ringMaterial=new Ye({color:16746496,transparent:!0,opacity:.7,blending:Ht,side:ct,depthWrite:!1}),this.particleMaterial=new Ye({color:16763904,transparent:!0,opacity:.8,blending:Ht,side:ct,depthWrite:!1});for(let e=0;e!i.active);t||(t=this.explosions[0],this.resetExplosion(t)),t.active=!0,t.elapsed=0,t.position.copy(e),t.container.position.copy(e),t.container.visible=!0,t.core.scale.set(.1,.1,.1),t.coreMat.opacity=1,t.sphere.scale.set(.1,.1,.1),t.sphere.material.opacity=.6,t.ring.scale.set(.1,.1,.1),t.ring.material.opacity=.8,t.particleMat.opacity=.9,t.particles.forEach((i,s)=>{i.mesh.position.set(0,0,0);const a=s/12*Math.PI*2,r=(Math.random()-.3)*Math.PI,o=350+Math.random()*250;i.velocity.set(Math.cos(a)*Math.cos(r)*o,Math.sin(r)*o+100,Math.sin(a)*Math.cos(r)*o)})}resetExplosion(e){e.active=!1,e.container.visible=!1}update(e){for(const t of this.explosions){if(!t.active)continue;t.elapsed+=e;const i=t.elapsed/t.duration;if(i>=1){this.resetExplosion(t);continue}const s=30+i*80;t.core.scale.set(s,s,s),t.coreMat.opacity=1*Math.pow(1-i,2);const a=50+i*200;t.sphere.scale.set(a,a,a),t.sphere.material.opacity=.6*(1-i);const r=80+i*350;t.ring.scale.set(r,r,r),t.ring.material.opacity=.8*(1-i*i),t.particleMat.opacity=.9*(1-i);for(const o of t.particles)o.mesh.position.add(o.velocity.clone().multiplyScalar(e)),o.velocity.y-=300*e,this.camera&&o.mesh.lookAt(this.camera.position)}}dispose(){for(const e of this.explosions)this.scene.remove(e.container),e.coreMat.dispose(),e.sphere.material.dispose(),e.ring.material.dispose(),e.particleMat.dispose();this.coreGeo.dispose(),this.sphereGeo.dispose(),this.ringGeo.dispose(),this.particleGeo.dispose(),this.coreMaterial.dispose(),this.sphereMaterial.dispose(),this.ringMaterial.dispose(),this.particleMaterial.dispose()}}function TT(n,e=null,t=null){return di&&di.scene!==n&&(di.dispose?.(),di=null),di||(di=new nF(n,e,t)),e&&t&&!di.warmedUp&&(di.renderer=e,di.camera=t,di.warmup()),di}function iF(n,e,t){TT(n,e,t),MT(n,e,t)}let Bn=null;const iv={0:{core:6737151,sphere:35071,ring:43775,particles:8969727},1:{core:16768358,sphere:16737792,ring:16746496,particles:16755268}};class sF{constructor(e,t,i,s=2){this.scene=e,this.renderer=t,this.camera=i,this.maxExplosions=s,this.explosions=[],this.warmedUp=!1,this.initPool()}initPool(){this.coreGeo=new yn(1,16,12),this.sphereGeo=new yn(1,20,14),this.ringGeo=new ni(.3,1,48),this.particleGeo=new Dn(1,1),this.rayGeo=new Dn(1,1);for(let e=0;e!l.active);i||(i=this.explosions[0],this.resetExplosion(i));const s=i.materials[t]||i.materials[0];i.core.material=s.core,i.core2.material=s.core.clone(),i.core3.material=s.sphere.clone(),i.sphere.material=s.sphere;for(const l of i.rings)l.mesh.material=s.ring.clone();for(const l of i.rays)l.mesh.material=s.rays.clone();for(const l of i.particles)l.mesh.material=s.particles.clone();i.active=!0,i.elapsed=0,i.currentTeam=t,i.position.copy(e),i.container.position.copy(e),i.container.visible=!0,i.rotationOffset=0,i.core.scale.set(.1,.1,.1),i.core.material.opacity=1,i.core2.scale.set(.1,.1,.1),i.core2.material.opacity=.8,i.core3.scale.set(.1,.1,.1),i.core3.material.opacity=.5,i.sphere.scale.set(.1,.1,.1),i.sphere.material.opacity=.4;for(const l of i.rings)l.mesh.scale.set(.1,.1,.1),l.mesh.material.opacity=.9;for(let l=0;l=i.particles.length);d++){const h=i.particles[o];h.mesh.position.set(0,0,0),h.mesh.material.opacity=1;const f=h.initialScale;h.mesh.scale.set(f,f,f);const p=c+(Math.random()-.5)*.3,g=u+(Math.random()-.5)*.2,v=1800*(1-d/r*.5)+Math.random()*300;h.velocity.set(Math.cos(p)*Math.cos(g)*v,Math.sin(g)*v+300,Math.sin(p)*Math.cos(g)*v),h.delay=d*.02,o++}}for(;o=1){this.resetExplosion(t);continue}t.rotationOffset+=e*2;const s=this.easeOutElastic(Math.min(i*2,1)),a=this.easeOutExpo(i),r=this.easeOutBack(Math.min(i*1.5,1)),o=1+Math.sin(t.elapsed*15)*.15*(1-i),l=(150+s*300)*o;t.core.scale.set(l,l,l),t.core.material.opacity=1*Math.pow(1-i,1.2);const c=1+Math.sin(t.elapsed*12+1)*.12*(1-i),u=(200+r*400)*c;t.core2.scale.set(u,u,u),t.core2.material.opacity=.7*Math.pow(1-i,1.5);const d=300+a*600;t.core3.scale.set(d,d,d),t.core3.material.opacity=.4*Math.pow(1-i,2);const h=400+a*1200;t.sphere.scale.set(h,h,h),t.sphere.material.opacity=.3*(1-i*i);for(let g=0;g0){g.mesh.position.add(g.velocity.clone().multiplyScalar(e)),g.velocity.y-=600*e,g.velocity.multiplyScalar(.995);const m=Math.max(.3,1-i*.7),v=g.initialScale*m;g.mesh.scale.set(v,v,v)}g.mesh.material.opacity=1*Math.pow(1-i,1.2),this.camera&&g.mesh.lookAt(this.camera.position)}}}dispose(){for(const e of this.explosions){this.scene.remove(e.container);for(const t of Object.values(e.materials))t.core.dispose(),t.sphere.dispose(),t.ring.dispose(),t.particles.dispose(),t.rays.dispose()}this.coreGeo.dispose(),this.sphereGeo.dispose(),this.ringGeo.dispose(),this.particleGeo.dispose(),this.rayGeo.dispose()}}function MT(n,e=null,t=null){return Bn&&Bn.scene!==n&&(Bn.dispose?.(),Bn=null),Bn||(Bn=new sF(n,e,t)),e&&t&&!Bn.warmedUp&&(Bn.renderer=e,Bn.camera=t,Bn.warmup()),Bn}function aF(){if(du)return du;const n=document.createElement("canvas");n.width=64,n.height=64;const e=n.getContext("2d"),t=e.createRadialGradient(32,32,0,32,32,32);return t.addColorStop(0,"rgba(255,255,255,1)"),t.addColorStop(.2,"rgba(255,255,255,0.8)"),t.addColorStop(.5,"rgba(255,255,255,0.3)"),t.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=t,e.fillRect(0,0,64,64),du=new oc(n),du}function rF(){if(hu)return hu;const n=document.createElement("canvas");n.width=128,n.height=128;const e=n.getContext("2d"),t=e.createRadialGradient(64,64,0,64,64,64);return t.addColorStop(0,"rgba(255,255,255,1)"),t.addColorStop(.1,"rgba(255,200,100,0.9)"),t.addColorStop(.4,"rgba(255,100,50,0.4)"),t.addColorStop(.7,"rgba(255,50,0,0.1)"),t.addColorStop(1,"rgba(0,0,0,0)"),e.fillStyle=t,e.fillRect(0,0,128,128),hu=new oc(n),hu}function oF(){if(fu)return fu;const n=document.createElement("canvas");n.width=64,n.height=64;const e=n.getContext("2d"),t=e.createImageData(64,64);for(let i=0;ie.add(a)),this.mainTrail=this._createMainTrail(),this.secondaryTrails=this._createSecondaryTrails(),this._updateColors(),this._updateIntensity(),this.mainTrail.activate(),this.secondaryTrails.forEach(a=>a.activate())}_createMainTrail(){const e=new pt(this.scene,!1),t=lv(),i=this.config.mainTrailWidth,s=[new S(0,-i,0),new S(0,i,0),new S(-i,0,0),new S(i,0,0),new S(0,0,-i),new S(0,0,i)];return e.initialize(t,this.config.trailLength,!1,0,s,this.mainTarget),e.setAdvanceFrequency(60),e.mesh&&(e.mesh.frustumCulled=!1,e.mesh.renderOrder=100),e}_createSecondaryTrails(){const e=[];for(let t=0;t<4;t++){const i=new pt(this.scene,!1),s=lv(),a=this.config.secondaryTrailWidth,r=[new S(0,-a,0),new S(0,a,0),new S(-a,0,0),new S(a,0,0),new S(0,0,-a),new S(0,0,a)];i.initialize(s,this.config.trailLength,!1,0,r,this.secondaryTargets[t]),i.setAdvanceFrequency(60),i.mesh&&(i.mesh.frustumCulled=!1,i.mesh.renderOrder=100),e.push(i)}return e}_updateColors(){const e=this.teamColors[this.team]||this.teamColors[0];this.mainTrail?.material&&(this.mainTrail.material.uniforms.headColor.value.copy(e.head),this.mainTrail.material.uniforms.tailColor.value.copy(e.tail));const t=e.head.clone();t.w=e.head.w*.85;const i=e.tail.clone();this.secondaryTrails.forEach(s=>{s?.material&&(s.material.uniforms.headColor.value.copy(t),s.material.uniforms.tailColor.value.copy(i))})}_updateIntensity(){this.mainTrail?.material&&(this.mainTrail.material.uniforms.intensityMultiplier.value=this.intensity),this.secondaryTrails.forEach(e=>{e?.material&&(e.material.uniforms.intensityMultiplier.value=this.intensity)})}setTeam(e){this.team!==e&&(this.team=e,this._updateColors())}setIntensity(e){this.intensity=e,this.dying||this._updateIntensity()}startDying(){this.dying||(this.dying=!0,this.deathTime=0,this.mainTrail.pause(),this.secondaryTrails.forEach(e=>e.pause()))}updatePosition(e,t,i){if(this.dying)return;const s=t.clone().normalize();this.mainTarget.position.copy(e),this.mainTarget.updateMatrixWorld();for(let a=0;a<4;a++){const o=a/4*Math.PI*2+i,l=new S(Math.cos(o)*this.config.secondaryTrailOffset,Math.sin(o)*this.config.secondaryTrailOffset,0);if(s.lengthSq()>.001){const c=new S(0,0,1),u=new dt;u.setFromUnitVectors(c,s),l.applyQuaternion(u)}this.secondaryTargets[a].position.copy(e).add(l),this.secondaryTargets[a].updateMatrixWorld()}}update(e){if(this.dying){this.deathTime+=e;const t=Math.min(1,this.deathTime/this.maxDeathTime),i=this.intensity*(1-t);this.mainTrail?.material&&(this.mainTrail.material.uniforms.intensityMultiplier.value=i),this.secondaryTrails.forEach(s=>{s?.material&&(s.material.uniforms.intensityMultiplier.value=i)}),this.deathTime>=this.maxDeathTime&&(this.active=!1)}this.mainTrail.isActive&&this.mainTrail.update(e),this.secondaryTrails.forEach(t=>{t.isActive&&t.update(e)})}dispose(){this.mainTrail.deactivate(),this.secondaryTrails.forEach(e=>e.deactivate()),this.mainTrail.geometry&&this.mainTrail.geometry.dispose(),this.mainTrail.material&&this.mainTrail.material.dispose(),this.secondaryTrails.forEach(e=>{e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()}),this.scene.remove(this.mainTarget),this.secondaryTargets.forEach(e=>this.scene.remove(e))}}class dF{constructor(e,t=0){this.scene=e,this.team=t,this.active=!1,this.ballRadius=92.75,this.config={trailLength:60,mainTrailWidth:15,secondaryTrailWidth:1.5,secondaryTrailOffset:this.ballRadius*.7},this.rotationSpeed=Math.PI/3,this.currentRotation=0,this.minVelocity=1500,this.maxVelocity=6e3,this.minIntensity=.3,this.maxIntensity=1,this.wasEmitting=!1,this.segments=[],this.currentSegment=null,this.currentIntensity=1}_calculateIntensity(e){if(e<=this.minVelocity)return this.minIntensity;if(e>=this.maxVelocity)return this.maxIntensity;const t=(e-this.minVelocity)/(this.maxVelocity-this.minVelocity);return this.minIntensity+t*(this.maxIntensity-this.minIntensity)}setTeam(e){this.team!==e&&(this.team=e,this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.startDying(),this.currentSegment=null))}activate(){this.active||(this.active=!0,this.currentSegment=null,this.wasEmitting=!1)}deactivate(){this.active&&(this.active=!1,this.currentSegment&&(this.currentSegment.startDying(),this.currentSegment=null))}emit(e,t,i){const s=t.length();if(!(s>=this.minVelocity)){this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.startDying(),this.currentSegment=null),this.wasEmitting=!1;return}this.currentIntensity=this._calculateIntensity(s),this.active||this.activate(),!this.wasEmitting||!this.currentSegment?(this.currentSegment&&!this.currentSegment.dying&&this.currentSegment.startDying(),this.currentSegment=new uF(this.scene,this.team,this.config,this.currentIntensity),this.segments.push(this.currentSegment)):this.currentSegment.setIntensity(this.currentIntensity),this.wasEmitting=!0,this.currentRotation+=this.rotationSpeed*i,this.currentRotation>Math.PI*2&&(this.currentRotation-=Math.PI*2),this.currentSegment.updatePosition(e,t,this.currentRotation)}update(e){for(let t=this.segments.length-1;t>=0;t--){const i=this.segments[t];i.update(e),i.active||(i.dispose(),this.segments.splice(t,1))}}reset(){for(const e of this.segments)e.dispose();this.segments=[],this.currentSegment=null,this.currentRotation=0,this.wasEmitting=!1}addToScene(e){}removeFromScene(e){for(const t of this.segments)t.startDying();this.currentSegment=null}dispose(){for(const e of this.segments)e.dispose();this.segments=[],this.currentSegment=null}}let mu=null,_u=null,gu=null,cv=!1;function hF(){cv||(_F(),gF(),yF(),cv=!0)}let di=null;class fF{constructor(e,t,i,s=2){this.scene=e,this.renderer=t,this.camera=i,this.maxExplosions=s,this.explosions=[],this.warmedUp=!1,this.initPool()}initPool(){this.sphereGeo=new yn(1,16,12),this.coreGeo=new yn(1,12,8),this.ringGeo=new ni(.5,1,32),this.particleGeo=new kn(1,1),this.coreMaterial=new Ye({color:16777130,transparent:!0,opacity:.9,blending:Ht,side:ct,depthWrite:!1}),this.sphereMaterial=new Ye({color:16737792,transparent:!0,opacity:.5,blending:Ht,side:ct,depthWrite:!1}),this.ringMaterial=new Ye({color:16746496,transparent:!0,opacity:.7,blending:Ht,side:ct,depthWrite:!1}),this.particleMaterial=new Ye({color:16763904,transparent:!0,opacity:.8,blending:Ht,side:ct,depthWrite:!1});for(let e=0;e!i.active);t||(t=this.explosions[0],this.resetExplosion(t)),t.active=!0,t.elapsed=0,t.position.copy(e),t.container.position.copy(e),t.container.visible=!0,t.core.scale.set(.1,.1,.1),t.coreMat.opacity=1,t.sphere.scale.set(.1,.1,.1),t.sphere.material.opacity=.6,t.ring.scale.set(.1,.1,.1),t.ring.material.opacity=.8,t.particleMat.opacity=.9,t.particles.forEach((i,s)=>{i.mesh.position.set(0,0,0);const a=s/12*Math.PI*2,r=(Math.random()-.3)*Math.PI,o=350+Math.random()*250;i.velocity.set(Math.cos(a)*Math.cos(r)*o,Math.sin(r)*o+100,Math.sin(a)*Math.cos(r)*o)})}resetExplosion(e){e.active=!1,e.container.visible=!1}update(e){for(const t of this.explosions){if(!t.active)continue;t.elapsed+=e;const i=t.elapsed/t.duration;if(i>=1){this.resetExplosion(t);continue}const s=30+i*80;t.core.scale.set(s,s,s),t.coreMat.opacity=1*Math.pow(1-i,2);const a=50+i*200;t.sphere.scale.set(a,a,a),t.sphere.material.opacity=.6*(1-i);const r=80+i*350;t.ring.scale.set(r,r,r),t.ring.material.opacity=.8*(1-i*i),t.particleMat.opacity=.9*(1-i);for(const o of t.particles)o.mesh.position.add(o.velocity.clone().multiplyScalar(e)),o.velocity.y-=300*e,this.camera&&o.mesh.lookAt(this.camera.position)}}dispose(){for(const e of this.explosions)this.scene.remove(e.container),e.coreMat.dispose(),e.sphere.material.dispose(),e.ring.material.dispose(),e.particleMat.dispose();this.coreGeo.dispose(),this.sphereGeo.dispose(),this.ringGeo.dispose(),this.particleGeo.dispose(),this.coreMaterial.dispose(),this.sphereMaterial.dispose(),this.ringMaterial.dispose(),this.particleMaterial.dispose()}}function LT(n,e=null,t=null){return di&&di.scene!==n&&(di.dispose?.(),di=null),di||(di=new fF(n,e,t)),e&&t&&!di.warmedUp&&(di.renderer=e,di.camera=t,di.warmup()),di}function pF(n,e,t){LT(n,e,t),kT(n,e,t)}let Bn=null;const uv={0:{core:6737151,sphere:35071,ring:43775,particles:8969727},1:{core:16768358,sphere:16737792,ring:16746496,particles:16755268}};class mF{constructor(e,t,i,s=2){this.scene=e,this.renderer=t,this.camera=i,this.maxExplosions=s,this.explosions=[],this.warmedUp=!1,this.initPool()}initPool(){this.coreGeo=new yn(1,16,12),this.sphereGeo=new yn(1,20,14),this.ringGeo=new ni(.3,1,48),this.particleGeo=new kn(1,1),this.rayGeo=new kn(1,1);for(let e=0;e!l.active);i||(i=this.explosions[0],this.resetExplosion(i));const s=i.materials[t]||i.materials[0];i.core.material=s.core,i.core2.material=s.core.clone(),i.core3.material=s.sphere.clone(),i.sphere.material=s.sphere;for(const l of i.rings)l.mesh.material=s.ring.clone();for(const l of i.rays)l.mesh.material=s.rays.clone();for(const l of i.particles)l.mesh.material=s.particles.clone();i.active=!0,i.elapsed=0,i.currentTeam=t,i.position.copy(e),i.container.position.copy(e),i.container.visible=!0,i.rotationOffset=0,i.core.scale.set(.1,.1,.1),i.core.material.opacity=1,i.core2.scale.set(.1,.1,.1),i.core2.material.opacity=.8,i.core3.scale.set(.1,.1,.1),i.core3.material.opacity=.5,i.sphere.scale.set(.1,.1,.1),i.sphere.material.opacity=.4;for(const l of i.rings)l.mesh.scale.set(.1,.1,.1),l.mesh.material.opacity=.9;for(let l=0;l=i.particles.length);d++){const h=i.particles[o];h.mesh.position.set(0,0,0),h.mesh.material.opacity=1;const f=h.initialScale;h.mesh.scale.set(f,f,f);const p=c+(Math.random()-.5)*.3,g=u+(Math.random()-.5)*.2,v=1800*(1-d/r*.5)+Math.random()*300;h.velocity.set(Math.cos(p)*Math.cos(g)*v,Math.sin(g)*v+300,Math.sin(p)*Math.cos(g)*v),h.delay=d*.02,o++}}for(;o=1){this.resetExplosion(t);continue}t.rotationOffset+=e*2;const s=this.easeOutElastic(Math.min(i*2,1)),a=this.easeOutExpo(i),r=this.easeOutBack(Math.min(i*1.5,1)),o=1+Math.sin(t.elapsed*15)*.15*(1-i),l=(150+s*300)*o;t.core.scale.set(l,l,l),t.core.material.opacity=1*Math.pow(1-i,1.2);const c=1+Math.sin(t.elapsed*12+1)*.12*(1-i),u=(200+r*400)*c;t.core2.scale.set(u,u,u),t.core2.material.opacity=.7*Math.pow(1-i,1.5);const d=300+a*600;t.core3.scale.set(d,d,d),t.core3.material.opacity=.4*Math.pow(1-i,2);const h=400+a*1200;t.sphere.scale.set(h,h,h),t.sphere.material.opacity=.3*(1-i*i);for(let g=0;g0){g.mesh.position.add(g.velocity.clone().multiplyScalar(e)),g.velocity.y-=600*e,g.velocity.multiplyScalar(.995);const m=Math.max(.3,1-i*.7),v=g.initialScale*m;g.mesh.scale.set(v,v,v)}g.mesh.material.opacity=1*Math.pow(1-i,1.2),this.camera&&g.mesh.lookAt(this.camera.position)}}}dispose(){for(const e of this.explosions){this.scene.remove(e.container);for(const t of Object.values(e.materials))t.core.dispose(),t.sphere.dispose(),t.ring.dispose(),t.particles.dispose(),t.rays.dispose()}this.coreGeo.dispose(),this.sphereGeo.dispose(),this.ringGeo.dispose(),this.particleGeo.dispose(),this.rayGeo.dispose()}}function kT(n,e=null,t=null){return Bn&&Bn.scene!==n&&(Bn.dispose?.(),Bn=null),Bn||(Bn=new mF(n,e,t)),e&&t&&!Bn.warmedUp&&(Bn.renderer=e,Bn.camera=t,Bn.warmup()),Bn}function _F(){if(mu)return mu;const n=document.createElement("canvas");n.width=64,n.height=64;const e=n.getContext("2d"),t=e.createRadialGradient(32,32,0,32,32,32);return t.addColorStop(0,"rgba(255,255,255,1)"),t.addColorStop(.2,"rgba(255,255,255,0.8)"),t.addColorStop(.5,"rgba(255,255,255,0.3)"),t.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=t,e.fillRect(0,0,64,64),mu=new dc(n),mu}function gF(){if(_u)return _u;const n=document.createElement("canvas");n.width=128,n.height=128;const e=n.getContext("2d"),t=e.createRadialGradient(64,64,0,64,64,64);return t.addColorStop(0,"rgba(255,255,255,1)"),t.addColorStop(.1,"rgba(255,200,100,0.9)"),t.addColorStop(.4,"rgba(255,100,50,0.4)"),t.addColorStop(.7,"rgba(255,50,0,0.1)"),t.addColorStop(1,"rgba(0,0,0,0)"),e.fillStyle=t,e.fillRect(0,0,128,128),_u=new dc(n),_u}function yF(){if(gu)return gu;const n=document.createElement("canvas");n.width=64,n.height=64;const e=n.getContext("2d"),t=e.createImageData(64,64);for(let i=0;i=o.maxLife){o.active=!1,i[r]=0,s[r]=0;continue}t[r*3]+=o.velocity.x*e,t[r*3+1]+=o.velocity.y*e,t[r*3+2]+=o.velocity.z*e;const l=o.life/o.maxLife;i[r]=Math.pow(1-l,.5);const c=o.initialSize||3;s[r]=c*(1-l*.7),a[r*3]=1,a[r*3+1]=Math.max(.2,.9-l*.7),a[r*3+2]=Math.max(0,.4-l*.4),o.velocity.y+=20*e}this.geometry.attributes.position.needsUpdate=!0,this.geometry.attributes.alpha.needsUpdate=!0,this.geometry.attributes.size.needsUpdate=!0,this.geometry.attributes.color.needsUpdate=!0}addToScene(e){e.add(this.points)}removeFromScene(e){e.remove(this.points)}dispose(){this.geometry.dispose(),this.points.material.dispose()}}class cF{constructor(e,t,i,s){this.scene=e,this.team=t,this.trailWidth=i,this.trailLength=s,this.active=!0,this.dying=!1,this.deathTime=0,this.maxDeathTime=1.5,this.teamColors={0:new qe(.3,.6,1,.9),1:new qe(1,.5,.15,.9)},this.leftTarget=new Qe,this.rightTarget=new Qe,e.add(this.leftTarget),e.add(this.rightTarget),this.leftTrail=this.createTrail(this.leftTarget),this.rightTrail=this.createTrail(this.rightTarget),this.updateColors(),this.leftTrail.activate(),this.rightTrail.activate()}createTrail(e){const t=new pt(this.scene,!1),i=pt.createBaseMaterial();i.blending=Ht,i.depthWrite=!1,i.side=ct;const s=this.trailWidth,a=[new S(0,0,0),new S(0,s,0),new S(-s/2,s/2,0),new S(s/2,s/2,0)];return t.initialize(i,this.trailLength,!1,0,a,e),t.setAdvanceFrequency(60),t.mesh&&(t.mesh.frustumCulled=!1),t}updateColors(){const e=this.teamColors[this.team]||this.teamColors[0],t=new qe(e.x*.3,e.y*.3,e.z*.3,0);this.leftTrail?.material&&(this.leftTrail.material.uniforms.headColor.value.copy(e),this.leftTrail.material.uniforms.tailColor.value.copy(t)),this.rightTrail?.material&&(this.rightTrail.material.uniforms.headColor.value.copy(e),this.rightTrail.material.uniforms.tailColor.value.copy(t))}startDying(){this.dying||(this.dying=!0,this.deathTime=0,this.leftTrail.pause(),this.rightTrail.pause())}updatePosition(e,t,i){this.dying||(this.leftTarget.position.copy(e),this.rightTarget.position.copy(t),this.leftTarget.quaternion.copy(i),this.rightTarget.quaternion.copy(i),this.leftTarget.updateMatrixWorld(),this.rightTarget.updateMatrixWorld())}update(e){if(this.dying){this.deathTime+=e;const i=1-Math.min(1,this.deathTime/this.maxDeathTime),s=this.teamColors[this.team]||this.teamColors[0],a=new qe(s.x,s.y,s.z,s.w*i),r=new qe(s.x*.3,s.y*.3,s.z*.3,0);this.leftTrail?.material&&(this.leftTrail.material.uniforms.headColor.value.copy(a),this.leftTrail.material.uniforms.tailColor.value.copy(r)),this.rightTrail?.material&&(this.rightTrail.material.uniforms.headColor.value.copy(a),this.rightTrail.material.uniforms.tailColor.value.copy(r)),this.deathTime>=this.maxDeathTime&&(this.active=!1)}this.leftTrail.isActive&&this.leftTrail.update(e),this.rightTrail.isActive&&this.rightTrail.update(e)}dispose(){this.leftTrail.deactivate(),this.rightTrail.deactivate(),this.leftTrail.geometry&&this.leftTrail.geometry.dispose(),this.rightTrail.geometry&&this.rightTrail.geometry.dispose(),this.leftTrail.material&&this.leftTrail.material.dispose(),this.rightTrail.material&&this.rightTrail.material.dispose(),this.scene.remove(this.leftTarget),this.scene.remove(this.rightTarget)}}class uF{constructor(e,t=0){this.scene=e,this.team=t,this.active=!1,this.trailLength=80,this.trailWidth=15,this.arenaBounds={floor:0,ceiling:2044,wallX:4096,wallZ:5120},this.groundedThreshold=50,this.segments=[],this.currentSegment=null,this.wasGrounded=!0}setTeam(e){this.team!==e&&(this.team=e,this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.team=e,this.currentSegment.updateColors()))}setActive(e){e&&!this.active?(this.currentSegment=null,this.wasGrounded=!0):!e&&this.active&&this.currentSegment&&(this.currentSegment.startDying(),this.currentSegment=null),this.active=e}isGrounded(e){const t=this.groundedThreshold,i=this.arenaBounds;if(e.yi.ceiling-t)return{grounded:!0,surface:"ceiling",normal:new S(0,-1,0)};if(Math.abs(e.x)>i.wallX-t){const s=e.x>0?-1:1;return{grounded:!0,surface:"wall",normal:new S(s,0,0)}}if(Math.abs(e.z)>i.wallZ-t){const s=e.z>0?-1:1;return{grounded:!0,surface:"wall",normal:new S(0,0,s)}}return{grounded:!1,surface:null,normal:null}}emit(e,t,i){if(!this.active)return;const s=this.isGrounded(e);if(!s.grounded){this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.startDying(),this.currentSegment=null),this.wasGrounded=!1;return}(!this.wasGrounded||!this.currentSegment)&&(this.currentSegment&&!this.currentSegment.dying&&this.currentSegment.startDying(),this.currentSegment=new cF(this.scene,this.team,this.trailWidth,this.trailLength),this.segments.push(this.currentSegment)),this.wasGrounded=!0;const r=new S(-30,5,40),o=new S(-30,5,-40);r.applyQuaternion(t),o.applyQuaternion(t);const l=e.clone().add(r),c=e.clone().add(o),u=2;if(s.surface==="floor")l.y=u,c.y=u;else if(s.surface==="ceiling")l.y=this.arenaBounds.ceiling-u,c.y=this.arenaBounds.ceiling-u;else if(s.surface==="wall"){if(s.normal.x!==0){const d=s.normal.x>0?-this.arenaBounds.wallX+u:this.arenaBounds.wallX-u;l.x=d,c.x=d}else if(s.normal.z!==0){const d=s.normal.z>0?-this.arenaBounds.wallZ+u:this.arenaBounds.wallZ-u;l.z=d,c.z=d}}this.currentSegment.updatePosition(l,c,t)}update(e){for(let t=this.segments.length-1;t>=0;t--){const i=this.segments[t];i.update(e),i.active||(i.dispose(),this.segments.splice(t,1))}}addToScene(e){}removeFromScene(e){for(const t of this.segments)t.startDying();this.currentSegment=null}dispose(){for(const e of this.segments)e.dispose();this.segments=[],this.currentSegment=null}}class dF{constructor(e){this.scene=e,this.renderer=null,this.camera=null,this.explosions={active:[],goalEvents:new Map,demoEvents:new Map},this.boostTrails=new Map,this.supersonicTrails=new Map,this.ballTrail=null,tF()}setRenderContext(e,t){this.renderer=e,this.camera=t,iF(this.scene,e,t)}reset(){this.explosions.active.forEach(e=>e.removeFromScene(this.scene)),this.explosions.active=[],this.clearGoalExplosions(),this.boostTrails.forEach(e=>{e.removeFromScene(this.scene),e.dispose()}),this.boostTrails.clear(),this.supersonicTrails.forEach(e=>{e.removeFromScene(this.scene),e.dispose()}),this.supersonicTrails.clear(),this.ballTrail&&(this.ballTrail.removeFromScene(this.scene),this.ballTrail.dispose(),this.ballTrail=null)}clearEvents(){this.explosions.goalEvents.clear(),this.explosions.demoEvents.clear()}setGoalEvents(e){this.explosions.goalEvents.clear();for(const t of e??[])Number.isFinite(t.frame)&&this.explosions.goalEvents.set(t.frame,{time:t.time,team:t.team??0,playerName:t.playerName??""})}resetBallTrail(){this.ballTrail&&this.ballTrail.reset()}clearGoalExplosions(){Bn&&Bn.clearActive();for(const e of this.explosions.active)e.removeFromScene(this.scene);this.explosions.active=[]}createBoostTrail(e,t){if(this.boostTrails.has(t)){const s=this.boostTrails.get(t);s.removeFromScene(this.scene),s.dispose()}const i=new lF(e);return i.addToScene(this.scene),this.boostTrails.set(t,i),i}removeBoostTrail(e){const t=this.boostTrails.get(e);t&&(t.removeFromScene(this.scene),t.dispose(),this.boostTrails.delete(e))}updateBoostTrail(e,t,i,s,a){const r=this.boostTrails.get(e);r&&(r.setActive(t),t&&r.emit(i,s,a,this._playbackSpeed||1))}createSupersonicTrail(e,t){if(this.supersonicTrails.has(e)){const s=this.supersonicTrails.get(e);s.removeFromScene(this.scene),s.dispose()}const i=new uF(this.scene,t);return i.addToScene(this.scene),this.supersonicTrails.set(e,i),i}removeSupersonicTrail(e){const t=this.supersonicTrails.get(e);t&&(t.removeFromScene(this.scene),t.dispose(),this.supersonicTrails.delete(e))}updateSupersonicTrail(e,t,i,s,a,r){let o=this.supersonicTrails.get(e);!o&&t&&(o=this.createSupersonicTrail(e,r)),o&&(r!==void 0&&o.team!==r&&o.setTeam(r),o.setActive(t),t&&o.emit(i,s,a))}createBallTrail(){return this.ballTrail&&(this.ballTrail.removeFromScene(this.scene),this.ballTrail.dispose()),this.ballTrail=new eF(this.scene,0),this.ballTrail.addToScene(this.scene),console.log("✓ Spiral ball trail created and added to scene"),this.ballTrail}updateBallTrail(e,t,i){this.ballTrail||this.createBallTrail(),i!==void 0&&this.ballTrail.team!==i&&this.ballTrail.setTeam(i);const s=1/60*(this._playbackSpeed||1);this.ballTrail.emit(e,t,s)}triggerGoalExplosion(e,t){const i=MT(this.scene,this.renderer,this.camera);i&&(this.camera&&(i.camera=this.camera),i.trigger(e,t))}triggerDemoExplosion(e,t,i){const s=TT(this.scene);s&&s.trigger(e)}update(e,t=!0,i=1){this._playbackSpeed=i;const s=e*i;di&&di.update(s),Bn&&Bn.update(s);for(let a=this.explosions.active.length-1;a>=0;a--){const r=this.explosions.active[a];r.update(s)&&(r.removeFromScene(this.scene),this.explosions.active.splice(a,1))}t&&(this.boostTrails.forEach(a=>{a.update(s)}),this.supersonicTrails.forEach(a=>{a.update(s)}),this.ballTrail&&this.ballTrail.update(s))}}const sv={Octane:65535,Dominus:16746496,Plank:8978176,Breakout:16711816,Hybrid:8913151,Merc:16776960},hF={0:5744895,1:16751680};function fF(n,e){return e===0||e===1?hF[e]:sv[n]||sv.Octane}class pF{constructor(e){this.scene=e,this.hitboxes=new Map,this.enabled=!1}setEnabled(e){this.enabled=e,this.hitboxes.forEach(({mesh:t})=>{t.visible=e})}createHitboxWireframe(e,t){const i=oy[e]||oy.Octane,s=fF(e,t),a=i.length,r=i.width,o=i.height,l=i.offsetX,c=i.offsetZ;console.log(`[HitboxManager] Creating hitbox for ${e}:`,{dims:i,length:a,width:r,height:o,offsetX:l,offsetY:c});const u=new Mt,d=new Ei(a,o,r),h=new Ye({color:s,transparent:!0,opacity:.35,depthTest:!1,depthWrite:!1,side:ct}),f=new we(d,h);f.frustumCulled=!1,f.renderOrder=1,f.position.set(l,c,0),u.add(f);const p=new Bh(d),g=new Rt({color:s,linewidth:2,transparent:!0,opacity:.9,depthTest:!1}),_=new Ln(p,g);_.frustumCulled=!1,_.renderOrder=2,_.position.set(l,c,0),u.add(_);const m=3.33,v=new yn(m,8,6),y=new ug(v),b=new Rt({color:16777215,linewidth:1,transparent:!0,opacity:.9,depthTest:!1}),T=new Ln(y,b);return T.frustumCulled=!1,u.add(T),u.userData.hitboxType=e,u.userData.team=t??null,u.frustumCulled=!1,u}addHitbox(e,t,i){const s=i===0||i===1?i:null;if(this.hitboxes.has(e)){const r=this.hitboxes.get(e);if(r.hitboxType===t&&r.team===s)return;this.scene.remove(r.mesh),r.mesh.traverse(o=>{o.geometry&&o.geometry.dispose(),o.material&&o.material.dispose()})}const a=this.createHitboxWireframe(t,s);a.visible=this.enabled,this.scene.add(a),this.hitboxes.set(e,{mesh:a,hitboxType:t,team:s})}removeHitbox(e){if(this.hitboxes.has(e)){const{mesh:t}=this.hitboxes.get(e);this.scene.remove(t),t.traverse(i=>{i.geometry&&i.geometry.dispose(),i.material&&i.material.dispose()}),this.hitboxes.delete(e)}}updateHitboxes(e,t,i,s){if(!this.enabled)return;for(const[r,o]of Object.entries(t)){const l=e[o];if(!l||!l.userData.isCar)continue;const c=i?i(r):"Octane",u=s?s(r):null;this.addHitbox(o,c,u);const{mesh:d}=this.hitboxes.get(o);d.position.copy(l.position),d.quaternion.copy(l.quaternion),d.visible=this.enabled&&l.visible}const a=new Set(Object.values(t));for(const r of this.hitboxes.keys())a.has(r)||this.removeHitbox(r)}reset(){this.hitboxes.forEach(({mesh:e})=>{this.scene.remove(e),e.traverse(t=>{t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose()})}),this.hitboxes.clear()}dispose(){this.reset()}}const ET=["baseGroup","glowMesh","innerGlowMesh","lensColumnMesh","lensRimMesh","topGlowMesh","coreGlowMesh","highlightMesh"];function gp(n,e,t,i){const s=new we(new Io(n,32),new Ye({color:e,transparent:!0,opacity:t,blending:Ht,side:ct,depthWrite:!1}));return s.rotation.x=-Math.PI/2,s.renderOrder=i,s}function av(n,e){n&&n.traverse(t=>{const i=t;if(!i.isMesh||!(i.material instanceof Ye))return;const s=i.userData.baseOpacity;i.material.opacity=(s??i.material.opacity)*e})}function pu(n,e,t){n.rotation.x=-Math.PI/2,n.renderOrder=t,n.frustumCulled=!1,n.userData.baseOpacity=e,n.material.transparent=!0,n.material.opacity=e,n.material.side=ct,n.material.depthWrite=!1}function mF(n){const e=new Mt;e.renderOrder=98,e.frustumCulled=!1;const t=new Ye({color:1118477}),i=new Ye({color:16752640,blending:Ht}),s=new we(new Io(n*.55,48),t.clone());pu(s,.86,98),e.add(s);const a=new we(new ni(n*.45,n*.62,48),new Ye({color:16765242,blending:Ht}));pu(a,.78,100),a.position.y=1.4,e.add(a);function r(o,l,c){const u=new Ns;return[[o*Math.cos(-c*.72),o*Math.sin(-c*.72)],[l*Math.cos(-c),l*Math.sin(-c)],[l*Math.cos(c),l*Math.sin(c)],[o*Math.cos(c*.72),o*Math.sin(c*.72)]].forEach(([h,f],p)=>{p===0?u.moveTo(h,f):u.lineTo(h,f)}),u.closePath(),u}for(let o=0;o<3;o+=1){const l=o*(Math.PI*2)/3+Math.PI/2,c=new we(new ur(r(n*.52,n*1.42,.33)),t.clone());pu(c,.86,98),c.rotation.z=l,e.add(c);const u=new we(new ur(r(n*.66,n*1.2,.21)),i.clone());pu(u,.86,99),u.position.y=1.1,u.rotation.z=l,e.add(u)}return e}function rv(n,e){for(const t of ET){const i=n.userData[t];i&&(i.visible=e)}}function _F(){let n=new Map;function e(i){const s=i.player.adapter.boostPads;!s||s.size===0||(console.log(`[boost-pads] Creating ${s.size} boost pads...`),n=new Map,s.forEach((a,r)=>{const o=a.isBig;let l,c,u;if(o){l=new yn(37,24,18),c=new ii({color:16757274,emissive:16747008,emissiveIntensity:.42,metalness:.04,roughness:.08,clearcoat:1,clearcoatRoughness:.025,transmission:.18,thickness:30,ior:1.42,envMapIntensity:1.9,blending:Ht,transparent:!0,opacity:.68,depthWrite:!1}),u=new we(l,c),u.renderOrder=100;const p=mF(37*2.05);p.position.y=-140,u.add(p),u.userData.baseGroup=p;const g=new we(new lr(37*.12,37*.18,112,24,1,!0),new Ye({color:16761664,transparent:!0,opacity:.28,blending:Ht,side:ct,depthWrite:!1}));g.position.y=-62,g.renderOrder=99,u.add(g),u.userData.lensColumnMesh=g;const _=new we(new yn(37*1.03,24,14),new Ye({color:16768890,transparent:!0,opacity:.32,blending:Ht,side:un,depthWrite:!1}));_.renderOrder=101,u.add(_),u.userData.lensRimMesh=_;const m=new yn(37*1.3,20,14),v=new Ye({color:16758315,transparent:!0,opacity:.16,blending:Ht,side:un,depthWrite:!1}),y=new we(m,v);y.renderOrder=99,u.add(y),u.userData.glowMesh=y;const b=new yn(37*1.12,20,14),T=new Ye({color:16761130,transparent:!0,opacity:.22,blending:Ht,side:un,depthWrite:!1}),x=new we(b,T);x.renderOrder=99,u.add(x),u.userData.innerGlowMesh=x,u.userData.needsLight=!0}else{l=new lr(45,45*.92,8,32),c=new ii({color:16761370,emissive:16750336,emissiveIntensity:.72,metalness:.88,roughness:.14,clearcoat:1,clearcoatRoughness:.05,envMapIntensity:2,transparent:!0,opacity:1,depthWrite:!1}),u=new we(l,c),u.renderOrder=100;const g=gp(45*1.42,16756736,.34,101);g.position.y=8/2+.15,u.add(g),u.userData.topGlowMesh=g;const _=gp(45*.74,16777114,.42,102);_.position.y=8/2+.35,u.add(_),u.userData.coreGlowMesh=_;const m=gp(45*.42,16775376,.46,103);m.position.set(-45*.18,8/2+.55,-45*.12),m.scale.y=.34,u.add(m),u.userData.highlightMesh=m}const h=o?130:10;if(u.position.set(a.position.x,h,a.position.y),u.userData.padId=r,u.userData.isBig=o,u.userData.isAvailable=!0,i.scene.add(u),n.set(r,u),u.userData.needsLight){const f=new dr(16751872,.7,480);f.decay=0,f.position.set(a.position.x,h-50,a.position.y),i.scene.add(f),u.userData.light=f}}),console.log(`[boost-pads] ✓ Created ${n.size} boost pad meshes`))}function t(i){i.player.adapter.boostPads.forEach((a,r)=>{const o=n.get(r);if(!o)return;const l=a.isAvailable;o.userData.isAvailable!==l&&(o.userData.isAvailable=l,l?(o.material.color.setHex(a.isBig?16757274:16761370),o.material.emissive.setHex(a.isBig?16747008:16750336),o.material.emissiveIntensity=a.isBig?.42:.72,o.material.opacity=a.isBig?.68:1,o.visible=!0,rv(o,!0),av(o.userData.baseGroup,1),o.userData.light&&(o.userData.light.intensity=.85),o.userData.glowMesh&&(o.userData.glowMesh.visible=!0),o.userData.innerGlowMesh&&(o.userData.innerGlowMesh.visible=!0)):(o.material.color.setHex(a.isBig?9063424:9065472),o.material.emissive.setHex(0),o.material.emissiveIntensity=0,o.material.opacity=.2,o.visible=!0,rv(o,!1),o.userData.baseGroup&&(o.userData.baseGroup.visible=!0,av(o.userData.baseGroup,.26)),o.userData.light&&(o.userData.light.intensity=0),o.userData.glowMesh&&(o.userData.glowMesh.visible=!1),o.userData.innerGlowMesh&&(o.userData.innerGlowMesh.visible=!1)))})}return{id:"boost-pads",setup(i){e(i)},beforeRender(i){t(i)},teardown(i){n.forEach(s=>{i.scene.remove(s),s.geometry.dispose(),s.material.dispose();for(const r of ET){const o=s.userData[r];o&&o.traverse(l=>{const c=l;c.isMesh&&(c.geometry.dispose(),c.material.dispose())})}const a=s.userData.light;a&&(i.scene.remove(a),a.dispose())}),n.clear()}}}const gF=2;function yF(n){if(n.frames.length===0)return null;const e=new Map;for(const s of n.frames)e.set(s.gameState,(e.get(s.gameState)??0)+1);let t=null,i=-1;for(const[s,a]of e.entries())a<=i||(t=s,i=a);return t}function vF(n,e){if(e===null)return null;for(const t of n.frames){if(t.gameState===e)break;return t.gameState}return null}function CT(n,e){return e===null?n.kickoffCountdown<=0:n.gameState===e}function Rg(n,e){return n.kickoffCountdown>0?!0:e!==null&&n.gameState===e}function bF(n,e){return n.ballFrames[e]?.position?!0:n.players.some(t=>t.frames[e]?.position)}function xF(n,e,t,i){return Rg(e,i)&&bF(n,t)}function wF(n,e){return n.timelineEvents.some(t=>t.kind==="goal"&&e.time>=t.time&&e.timec){const h=a.at(-1);h&&h.endTime>=c?h.endTime=Math.max(h.endTime,d):a.push({startTime:c,endTime:d})}o=u}return a}function TF(n,e,t){const i=vt.clamp(t,0,n);for(const s of e){if(i0&&(n.frames[s-1]?.kickoffCountdown??0)>0;)s-=1;let a=e+1;for(;a0;)a+=1;let r=0;for(let c=s;cl>s&&CT(o,t));return!r||r.time===e?null:r.time}function IF(n,e,t,i){const s=fh(n,e),a=n.frames[s];if(!a||!Wu(n,a,s,t,i))return null;const r=n.frames.find((c,u)=>u>s&&!Wu(n,c,u,t,i));if(r)return r.time===e?null:r.time;let o=s;for(;o>0&&Wu(n,n.frames[o-1],o-1,t,i);)o-=1;const l=n.frames[o]?.time;return l===void 0||l===e?null:l}function LF(n){return!!n?.position&&n?.isPresent!==!1}function DF(n,e,t){for(let i=n.length-1;i>=0;i-=1){const s=n[i],a=t-s.time;if(!(a<0)){if(a>RF)break;if(s.kind==="demo"&&s.secondaryPlayerId===e)return s}}return null}const kF="space",OF={space:{id:"space",skyboxUrl:"/skyboxes/PlanetaryEarth4k.hdr",exposure:1.45,rotation:{x:8,y:0,z:28},animation:{enabled:!0,speed:2}}};function FF(n){if(n===!1)return null;if(typeof n=="string"){const e=OF[n];return e||(console.warn(`[player] unknown environment "${n}"; using neutral default`),null)}return n}const NF=new Proxy({},{get:()=>()=>{}});function lv(n){if(!n)return null;const e={};for(const t of Object.keys(n)){const i=n[t];typeof i=="number"&&Number.isFinite(i)&&(e[t]=i)}return e}const cv=48,mu=.14,UF=16,BF=16,zF=.003,HF=.05,VF=1.08,uv=4120,dv=5140,GF=0,$F=2200,WF=new S(0,700,0),XF=new S(-1,0,0),KF=new S(0,-1,0),qF=new S(0,900,0),YF=new S(0,1,0),jF=new S(9600,-5500,12600).normalize();function ZF(n,e){const t=Number.isFinite(e)&&e>0?e:1.7777777777777777,i=n==="overhead"?WF.clone():qF.clone(),s=n==="overhead"?XF.clone():YF.clone(),a=n==="overhead"?KF.clone():jF.clone(),r=JF({aspect:t,fov:cv,forward:a,margin:VF,target:i,up:s});return{position:i.clone().addScaledVector(a,-r),target:i,up:s,fov:cv}}function JF(n){const{aspect:e,fov:t,forward:i,margin:s,target:a,up:r}=n,o=i.clone().normalize(),l=new S().crossVectors(o,r).normalize(),c=new S().crossVectors(l,o).normalize(),u=Math.tan(vt.degToRad(t)/2),d=u*e;let h=1;for(const f of[-uv,uv])for(const p of[GF,$F])for(const g of[-dv,dv]){const _=new S(f,p,g).sub(a),m=Math.abs(_.dot(l)),v=Math.abs(_.dot(c)),y=_.dot(o);h=Math.max(h,m/d-y,v/u-y)}return Math.max(1,h*s)}function QF(n){const e=new Mt;return e.name="replayRoot",e.matrixAutoUpdate=!1,e.matrix.set(1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1),n.add(e),e}class eN extends EventTarget{container;adapter;replay;options;sceneManager;arenaManager;actorManager;effectsManager;hitboxManager;controls;replayRoot;sceneState;effectsEnabled;ready;plugins=[];beforeRenderCallbacks=[];resizeObserver=null;animationFrameId=null;disposed=!1;playing=!1;readyResolved=!1;speed;loop;currentTime=0;lastTickAt=null;freeCameraTransition=null;cameraDistanceScaleValue;customCameraSettingsValue;cameraViewModeValue;attachedPlayerIdValue;ballCamEnabledValue;boostMeterEnabledValue;boostPickupAnimationEnabledValue;hitboxWireframesEnabledValue;hitboxOnlyModeEnabledValue;hitboxTypeByName=null;hitboxTeamByName=null;hitboxesActive=!1;skipPostGoalTransitionsEnabledValue;skipKickoffsEnabledValue;attachmentTouched=!1;liveGameState=null;kickoffGameState=null;timelineSegmentsCacheKey=null;timelineSegmentsCache=[];constructor(e,t,i={},s=null){super(),this.container=e,this.adapter=t,this.replay=s,this.options=i,this.updateReplayGameStates(),this.speed=Math.max(.1,i.initialPlaybackRate??i.speed??1),this.loop=i.loop??!1,this.cameraDistanceScaleValue=Math.max(.25,i.initialCameraDistanceScale??1),this.customCameraSettingsValue=lv(i.initialCustomCameraSettings),this.attachedPlayerIdValue=i.initialAttachedPlayerId??null,this.cameraViewModeValue=i.initialCameraViewMode??(this.attachedPlayerIdValue?"follow":"free"),this.ballCamEnabledValue=i.initialBallCamEnabled??null,this.boostMeterEnabledValue=i.initialBoostMeterEnabled??!1,this.boostPickupAnimationEnabledValue=i.initialBoostPickupAnimationEnabled??!0,this.hitboxWireframesEnabledValue=i.initialHitboxWireframesEnabled??!1,this.hitboxOnlyModeEnabledValue=i.initialHitboxOnlyModeEnabled??!1,this.skipPostGoalTransitionsEnabledValue=i.initialSkipPostGoalTransitionsEnabled??!0,this.skipKickoffsEnabledValue=i.initialSkipKickoffsEnabled??!1,this.sceneManager=new yk(e,{assetBase:i.assetBase,preserveDrawingBuffer:i.preserveDrawingBuffer}),this.sceneManager.initDefaultEnvironment(),this.applyEnvironmentSpec(i.environment??kF),this.arenaManager=new lO(this.scene,{assetBase:i.assetBase}),this.effectsEnabled=i.effects??!0,this.effectsManager=this.effectsEnabled?new dF(this.scene):NF,this.actorManager=new JO(this.scene,this.effectsManager,{assetBase:i.assetBase}),i.motionInterpolation&&this.setMotionInterpolation(i.motionInterpolation),this.actorManager.initFromFramework(t),this.actorManager.initInterpolants(t.getTimelines()),this.hitboxManager=new pF(this.scene),this.syncGoalEvents(),this.controls=new QD(this.camera,this.renderer.domElement),this.controls.zoomSpeed=2.5,this.camera.position.set(0,4e3,6e3),this.controls.target.set(0,200,0),this.controls.update(),this.replayRoot=QF(this.scene),this.sceneState=this.createSceneState(),this.ready=Promise.all([this.arenaManager.loadArenaMeshes().catch(a=>{console.warn("[player] arena load failed",a)}),this.prepareReplayAssets()]).then(()=>{this.markReady()}),this.installResizeHandling();for(const a of i.plugins??[])this.installPlugin(a,!1);this.plugins.some(a=>a.plugin.id==="boost-pads")||this.installPlugin(_F(),!1),this.applyInitialCameraOptions(),this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded(),this.scheduleAnimationFrame(),this.emitChange(),i.autoplay&&this.play()}get scene(){return this.sceneManager.scene}get camera(){return this.sceneManager.camera}get renderer(){return this.sceneManager.renderer}get duration(){return this.adapter.duration}async replaceReplay(e,t,i={}){if(this.disposed)throw new Error("Cannot replace replay on a disposed ReplayPlayer");const s=i.preservePlayback??this.playing;this.playing&&this.setPlayingInternal(!1),this.teardownPlugins(),this.effectsManager.reset(),this.effectsManager.clearEvents?.(),this.hitboxManager.reset(),this.actorManager.reset(),this.adapter=e,this.replay=t,this.updateReplayGameStates(),this.timelineSegmentsCacheKey=null,this.timelineSegmentsCache=[],this.hitboxTypeByName=null,this.hitboxTeamByName=null,this.hitboxesActive=!1,this.freeCameraTransition=null,this.actorManager.initFromFramework(e),this.actorManager.initInterpolants(e.getTimelines()),this.syncGoalEvents();const a=this.attachedPlayerIdValue&&this.adapter.playerList.some(r=>r.id===this.attachedPlayerIdValue)?this.attachedPlayerIdValue:null;a!==this.attachedPlayerIdValue&&(this.attachedPlayerIdValue=a,this.cameraViewModeValue==="follow"&&(this.cameraViewModeValue="free")),this.seekInternal(i.currentTime??0),this.readyResolved=!1,this.ready=this.prepareReplayAssets().then(()=>{this.markReady()}),await this.ready,this.setupPlugins(),this.applyInitialCameraOptions(),this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded(),s&&this.setPlayingInternal(!0),this.render(),this.emitChange()}setEnvironment(e){this.applyEnvironmentSpec(e)}applyEnvironmentSpec(e){const t=FF(e);if(!t){this.sceneManager.setDefaultBackground();return}this.sceneManager.applyEnvironment(t).catch(i=>{console.warn(`[player] environment "${t.id}" failed to load`,i)})}play(){this.playing||(this.setPlayingInternal(!0),this.emitChange())}pause(){this.playing&&(this.setPlayingInternal(!1),this.emitChange())}togglePlayback(){this.playing?this.pause():this.play()}seek(e){this.seekInternal(e),this.playing&&(this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded()),this.emitChange()}setPlaybackRate(e){this.speed=Math.max(.1,e),this.emitChange()}setLoop(e){this.loop=e}setMotionInterpolation(e){this.actorManager.interpolationMethod=e==="linear"?"lerp":"hermite"}setFrameIndex(e){const t=this.adapter.frameTimes;if(t.length===0||!Number.isFinite(e))return;const i=Math.min(Math.max(Math.trunc(e),0),t.length-1);this.playing&&this.setPlayingInternal(!1),this.seekInternal(t[i]),this.emitChange()}stepFrames(e){Number.isFinite(e)&&this.setFrameIndex(this.adapter.frameIndexAt(this.currentTime)+Math.trunc(e))}stepForwardFrame(){this.stepFrames(1)}stepBackwardFrame(){this.stepFrames(-1)}setCameraDistanceScale(e){this.cameraDistanceScaleValue=Math.max(.25,e),this.getCameraPlugin()?.setDistanceScale(this.cameraDistanceScaleValue),this.emitChange()}setCustomCameraSettings(e){this.applyCustomCameraSettings(e),this.emitChange()}setAttachedPlayer(e){this.attachedPlayerIdValue=e,this.cameraViewModeValue=e?"follow":"free",this.attachmentTouched=!0,this.freeCameraTransition=null,this.syncCameraAttachment(),this.emitChange()}setCameraViewMode(e){this.cameraViewModeValue=e,this.attachmentTouched=!0,this.freeCameraTransition=null,this.syncCameraAttachment(),this.emitChange()}setFreeCameraPreset(e,t={}){this.cameraViewModeValue="free",this.attachmentTouched=!0,this.syncCameraAttachment();const i=ZF(e,this.camera.aspect);t.instant?(this.camera.position.copy(i.position),this.controls.target.copy(i.target),this.camera.up.copy(i.up).normalize(),this.camera.fov=i.fov,this.camera.updateProjectionMatrix(),this.camera.lookAt(i.target),this.controls.enabled=!0,this.freeCameraTransition=null):this.freeCameraTransition=i,this.emitChange()}setBallCamEnabled(e){this.ballCamEnabledValue=e,this.getCameraPlugin()?.setBallCam(e),this.emitChange()}setBoostMeterEnabled(e){this.boostMeterEnabledValue=e,this.emitChange()}setBoostPickupAnimationEnabled(e){this.boostPickupAnimationEnabledValue=e,this.emitChange()}setHitboxWireframesEnabled(e){this.hitboxWireframesEnabledValue=e,this.emitChange()}setHitboxOnlyModeEnabled(e){this.hitboxOnlyModeEnabledValue=e,this.emitChange()}setSkipPostGoalTransitionsEnabled(e){this.skipPostGoalTransitionsEnabledValue=e,e&&this.playing&&this.skipPostGoalTransitionIfNeeded(),this.emitChange()}setSkipKickoffsEnabled(e){this.skipKickoffsEnabledValue=e,e&&this.playing&&(this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded()),this.emitChange()}setState(e){e.speed!==void 0&&(this.speed=Math.max(.1,e.speed)),e.cameraDistanceScale!==void 0&&(this.cameraDistanceScaleValue=Math.max(.25,e.cameraDistanceScale),this.getCameraPlugin()?.setDistanceScale(this.cameraDistanceScaleValue)),e.customCameraSettings!==void 0&&this.applyCustomCameraSettings(e.customCameraSettings),e.cameraViewMode!==void 0&&(this.cameraViewModeValue=e.cameraViewMode,this.attachmentTouched=!0),e.attachedPlayerId!==void 0&&(this.attachedPlayerIdValue=e.attachedPlayerId,this.attachmentTouched=!0,e.cameraViewMode===void 0&&(this.cameraViewModeValue=e.attachedPlayerId?"follow":"free")),(e.cameraViewMode!==void 0||e.attachedPlayerId!==void 0)&&(this.freeCameraTransition=null,this.syncCameraAttachment()),e.useReplayBallCam===!0?(this.ballCamEnabledValue=null,this.getCameraPlugin()?.setBallCam(null)):e.ballCamEnabled!==void 0&&(this.ballCamEnabledValue=e.ballCamEnabled,this.getCameraPlugin()?.setBallCam(e.ballCamEnabled)),e.boostMeterEnabled!==void 0&&(this.boostMeterEnabledValue=e.boostMeterEnabled),e.boostPickupAnimationEnabled!==void 0&&(this.boostPickupAnimationEnabledValue=e.boostPickupAnimationEnabled),e.hitboxWireframesEnabled!==void 0&&(this.hitboxWireframesEnabledValue=e.hitboxWireframesEnabled),e.hitboxOnlyModeEnabled!==void 0&&(this.hitboxOnlyModeEnabledValue=e.hitboxOnlyModeEnabled),e.skipPostGoalTransitionsEnabled!==void 0&&(this.skipPostGoalTransitionsEnabledValue=e.skipPostGoalTransitionsEnabled),e.skipKickoffsEnabled!==void 0&&(this.skipKickoffsEnabledValue=e.skipKickoffsEnabled),e.currentTime!==void 0&&this.seekInternal(e.currentTime),e.playing!==void 0&&e.playing!==this.playing&&this.setPlayingInternal(e.playing),this.playing&&(e.currentTime!==void 0||e.playing!==void 0)&&(this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded()),this.emitChange()}getState(){const e=this.adapter.frameIndexAt(this.currentTime),t=this.getCameraPlugin();let i=this.cameraViewModeValue,s=this.attachedPlayerIdValue;if(t)if(t.getMode()==="follow"){i="follow";const a=t.getTarget();s=(a?this.adapter.playerList.find(o=>o.name===a):void 0)?.id??s}else i="free",s=null;return{currentTime:this.currentTime,duration:this.duration,frameIndex:e,activeMetadata:this.replay?CF(this.replay,e,this.currentTime):null,playing:this.playing,speed:this.speed,cameraDistanceScale:this.cameraDistanceScaleValue,customCameraSettings:this.customCameraSettingsValue,cameraViewMode:i,attachedPlayerId:s,ballCamEnabled:t?t.getBallCam():this.ballCamEnabledValue??!1,useReplayBallCam:this.ballCamEnabledValue===null,effectiveBallCamEnabled:t?t.getBallCam():this.ballCamEnabledValue??!1,boostMeterEnabled:this.boostMeterEnabledValue,boostPickupAnimationEnabled:this.boostPickupAnimationEnabledValue,hitboxWireframesEnabled:this.hitboxWireframesEnabledValue,hitboxOnlyModeEnabled:this.hitboxOnlyModeEnabledValue,skipPostGoalTransitionsEnabled:this.skipPostGoalTransitionsEnabledValue,skipKickoffsEnabled:this.skipKickoffsEnabledValue}}getSnapshot(){return this.getState()}getTimelineDuration(){return this.replay?.duration??this.duration}getTimelineCurrentTime(){return this.projectReplayTimeToTimeline(this.currentTime).timelineTime}getTimelineSegments(){if(!this.replay)return[];const e=`${this.skipPostGoalTransitionsEnabledValue}:${this.skipKickoffsEnabledValue}`;return this.timelineSegmentsCacheKey===e?this.timelineSegmentsCache:(this.timelineSegmentsCacheKey=e,this.timelineSegmentsCache=SF(this.replay,this.skipPostGoalTransitionsEnabledValue,this.skipKickoffsEnabledValue,this.liveGameState,this.kickoffGameState),this.timelineSegmentsCache)}projectReplayTimeToTimeline(e){return TF(this.replay?.duration??this.duration,this.getTimelineSegments(),e)}projectTimelineTimeToReplay(e){return MF(this.replay?.duration??this.duration,this.getTimelineDuration(),this.getTimelineSegments(),e)}subscribe(e){const t=i=>{e(i.detail)};return this.addEventListener("change",t),e(this.getState()),()=>{this.removeEventListener("change",t)}}onBeforeRender(e){return this.beforeRenderCallbacks.push(e),()=>{const t=this.beforeRenderCallbacks.indexOf(e);t>=0&&this.beforeRenderCallbacks.splice(t,1)}}addPlugin(e){return this.installPlugin(e,!0)}removePlugin(e){const t=this.plugins.findIndex(s=>s.plugin.id===e);if(t<0)return!1;const[i]=this.plugins.splice(t,1);return i.plugin.teardown?.(this.createPluginContext()),!0}getPlugins(){return this.plugins.map(e=>e.plugin)}destroy(){if(!this.disposed){for(this.disposed=!0,this.playing=!1,this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.beforeRenderCallbacks.length=0;this.plugins.length>0;)this.plugins.pop()?.plugin.teardown?.(this.createPluginContext());this.controls.dispose(),this.effectsEnabled&&this.effectsManager.reset(),this.hitboxManager.dispose(),this.actorManager.reset(),this.sceneManager.dispose()}}dispose(){this.destroy()}setPlayingInternal(e){this.playing=e,this.lastTickAt=null,e?this.actorManager.resumeAnimations():this.actorManager.pauseAnimations()}prepareReplayAssets(){return this.actorManager.waitForBallModel().catch(()=>!1).then(()=>{if(this.effectsEnabled)try{this.effectsManager.setRenderContext(this.renderer,this.camera)}catch(e){console.warn("[player] explosion warmup failed",e)}})}markReady(){this.readyResolved=!0,this.lastTickAt=null}updateReplayGameStates(){if(!this.replay){this.liveGameState=null,this.kickoffGameState=null;return}this.liveGameState=yF(this.replay),this.kickoffGameState=vF(this.replay,this.liveGameState)}syncGoalEvents(){this.effectsEnabled&&(this.effectsManager.clearEvents?.(),this.replay&&this.effectsManager.setGoalEvents(this.replay.timelineEvents.filter(e=>e.kind==="goal").map(e=>({frame:e.frame,time:e.time,team:e.isTeamZero?0:1,playerName:e.playerName??""}))))}teardownPlugins(){const e=this.createPluginContext();for(const t of this.plugins)t.plugin.teardown?.(e)}setupPlugins(){for(const e of this.plugins)e.plugin.setup?.(this.createPluginContext()),e.plugin.id==="camera"&&this.pushCameraParityState(),e.plugin.onStateChange?.(this.createPluginStateContext(this.getState()))}seekInternal(e){this.currentTime=vt.clamp(e,0,this.duration),this.actorManager.seekAnimations(this.currentTime),this.effectsManager.resetBallTrail(),this.effectsManager.clearGoalExplosions?.(),this.actorManager.resetGoalExplosionPlaybackState(),this.actorManager.resetWheelTracking()}getPlaybackEndTime(){return this.replay?EF(this.replay.duration,this.getTimelineSegments()):this.duration}skipPastKickoffIfNeeded(){if(!this.replay||!this.skipKickoffsEnabledValue)return!1;const e=PF(this.replay,this.currentTime,this.liveGameState,this.kickoffGameState);return e===null?!1:(this.seekInternal(e),!0)}skipPostGoalTransitionIfNeeded(){if(!this.replay||!this.skipPostGoalTransitionsEnabledValue)return!1;const e=IF(this.replay,this.currentTime,this.liveGameState,this.kickoffGameState);return e===null?!1:(this.seekInternal(e),!0)}getCameraPlugin(){const e=this.plugins.find(t=>t.plugin.id==="camera")?.plugin;return e&&typeof e.follow=="function"?e:null}playerNameForId(e){return this.adapter.playerList.find(t=>t.id===e)?.name??null}applyReplayBallCam(){if(this.ballCamEnabledValue!==null||this.cameraViewModeValue!=="follow"||!this.attachedPlayerIdValue)return;const e=this.playerNameForId(this.attachedPlayerIdValue);if(!e)return;const t=this.adapter.getAllPlayers().find(i=>i.name===e);t&&this.getCameraPlugin()?.setBallCam(t.isBallCam)}syncCameraAttachment(){const e=this.getCameraPlugin();if(e){if(this.cameraViewModeValue==="follow"&&this.attachedPlayerIdValue){const t=this.playerNameForId(this.attachedPlayerIdValue);if(!t){console.warn(`[player] no player with id ${JSON.stringify(this.attachedPlayerIdValue)}`);return}this.camera.up.set(0,1,0),e.follow(t);return}e.getMode()==="follow"&&e.release()}}applyCustomCameraSettings(e){this.customCameraSettingsValue=lv(e);const t=this.getCameraPlugin();t&&(t.setCameraSettings(null),this.customCameraSettingsValue&&t.setCameraSettings(this.customCameraSettingsValue))}pushCameraParityState(){const e=this.getCameraPlugin();e&&(this.cameraDistanceScaleValue!==1&&e.setDistanceScale(this.cameraDistanceScaleValue),this.customCameraSettingsValue&&e.setCameraSettings(this.customCameraSettingsValue),this.ballCamEnabledValue!==null&&e.setBallCam(this.ballCamEnabledValue),this.attachmentTouched&&this.syncCameraAttachment())}applyInitialCameraOptions(){const e=this.options;(e.initialAttachedPlayerId!==void 0||e.initialCameraViewMode!==void 0)&&(this.attachmentTouched=!0),this.pushCameraParityState()}computeFrameRenderInfo(){const e=this.adapter.frameTimes,t=this.adapter.frameIndexAt(this.currentTime),i=Math.min(t+1,Math.max(e.length-1,0)),s=e[t]??0,a=e[i]??s,r=a>s?vt.clamp((this.currentTime-s)/(a-s),0,1):0;return{frameIndex:t,nextFrameIndex:i,alpha:r,currentTime:this.currentTime}}installResizeHandling(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>this.sceneManager.onWindowResize()),this.resizeObserver.observe(this.container))}scheduleAnimationFrame(){this.animationFrameId!==null||this.disposed||(this.animationFrameId=requestAnimationFrame(this.tick))}tick=e=>{if(this.animationFrameId=null,this.disposed)return;let t=!1,i=0;if(this.playing&&this.readyResolved){i=this.lastTickAt===null?0:Math.min(.1,(e-this.lastTickAt)/1e3),this.lastTickAt=e;let s=this.currentTime+i*this.speed;const a=this.getPlaybackEndTime();s>=a&&(this.loop?(s=0,this.actorManager.seekAnimations(0),this.effectsManager.resetBallTrail(),this.effectsManager.clearGoalExplosions?.(),this.actorManager.resetGoalExplosionPlaybackState(),this.actorManager.resetWheelTracking()):(s=a,this.playing=!1)),t=s!==this.currentTime||!this.playing,this.currentTime=s,this.playing&&(t=this.skipPostGoalTransitionIfNeeded()||t,t=this.skipPastKickoffIfNeeded()||t)}else this.playing&&(this.lastTickAt=null);this.render(i),t&&this.emitChange(),this.scheduleAnimationFrame()};renderFrame(e=0){if(this.adapter.seek(this.currentTime),this.playing&&this.actorManager.updateAnimations(e*this.speed),this.actorManager.updateFromFramework(this.adapter,this.currentTime),this.updatePlayerStates(),this.applyReplayBallCam(),this.updateHitboxVisualization(),this.effectsManager.update(e,this.playing,this.speed),this.playing&&this.actorManager.updateWheelRotations(),this.sceneManager.updateSkyboxAnimation(this.playing?e*this.speed:0),this.controls.update(),this.beforeRenderCallbacks.length>0){const t=this.computeFrameRenderInfo();for(const i of[...this.beforeRenderCallbacks])i(t)}if(this.plugins.length>0){const t=this.createRenderContext();for(const i of this.plugins)i.plugin.beforeRender?.(t)}this.updateFreeCameraTransition(),this.renderer.render(this.scene,this.camera)}render(e=0){this.renderFrame(e)}updateFreeCameraTransition(){const e=this.freeCameraTransition;if(!e)return;this.controls.enabled=!1,this.camera.position.lerp(e.position,mu),this.controls.target.lerp(e.target,mu),this.camera.up.lerp(e.up,mu).normalize(),this.camera.fov=vt.lerp(this.camera.fov,e.fov,mu),this.camera.updateProjectionMatrix(),this.camera.lookAt(this.controls.target);const t=this.camera.position.distanceToSquared(e.position)<=UF,i=this.controls.target.distanceToSquared(e.target)<=BF,s=this.camera.up.angleTo(e.up)<=zF,a=Math.abs(this.camera.fov-e.fov)<=HF;!t||!i||!s||!a||(this.camera.position.copy(e.position),this.controls.target.copy(e.target),this.camera.up.copy(e.up).normalize(),this.camera.fov=e.fov,this.camera.updateProjectionMatrix(),this.camera.lookAt(e.target),this.controls.enabled=!0,this.freeCameraTransition=null)}updatePlayerStates(){if(!this.playing)return;const e=this.hitboxOnlyModeEnabledValue;for(const t of this.adapter.getAllPlayers())this.actorManager.updateBoostState(t.name,t.isBoosting&&!e,t.isKickoffReset),this.actorManager.updateSupersonicState(t.name,t.isSupersonic&&!e,t.team)}updateHitboxVisualization(){const e=this.hitboxWireframesEnabledValue||this.hitboxOnlyModeEnabledValue;if(!e&&!this.hitboxesActive||(this.hitboxesActive=e,this.hitboxManager.setEnabled(e),!e))return;const t=this.actorManager;if(this.hitboxTypeByName||(this.hitboxTypeByName=new Map(this.adapter.getAllPlayers().map(i=>[i.name,i.hitboxType]))),this.hitboxTeamByName||(this.hitboxTeamByName=new Map(this.adapter.getAllPlayers().map(i=>[i.name,i.team]))),this.hitboxManager.updateHitboxes(t.actors,t.playerNameToCarActorId,i=>this.hitboxTypeByName?.get(i)??"Octane",i=>this.hitboxTeamByName?.get(i)??null),this.hitboxOnlyModeEnabledValue)for(const i of Object.values(t.playerNameToCarActorId)){const s=i===void 0?void 0:t.actors[i];s&&(s.visible=!1)}}installPlugin(e,t){const i=typeof e=="function"?e():e;if(this.plugins.some(a=>a.plugin.id===i.id))throw new Error(`Player plugin "${i.id}" is already installed`);const s={definition:e,plugin:i};return this.plugins.push(s),i.setup?.(this.createPluginContext()),i.id==="camera"&&this.pushCameraParityState(),i.onStateChange?.(this.createPluginStateContext(this.getState())),t&&this.render(),()=>{const a=this.plugins.indexOf(s);a<0||(this.plugins.splice(a,1),i.teardown?.(this.createPluginContext()))}}createSceneState(){const e=this.actorManager,t=this,i=new we;return{get scene(){return t.scene},replayRoot:this.replayRoot,get camera(){return t.camera},get renderer(){return t.renderer},controls:this.controls,resize:()=>this.sceneManager.onWindowResize(),dispose:()=>this.destroy(),get ballMesh(){return(e.ballActorId!=null?e.actors[e.ballActorId]:null)??i},get playerMeshes(){const s=new Map;for(const a of t.adapter.playerList){const r=e.playerNameToCarActorId[a.name],o=r!=null?e.actors[r]:void 0;o&&s.set(a.id,o)}return s},playerBodyMeshes:new Map,playerHitboxes:new Map,playerBoostTrails:new Map,playerBoostMeters:new Map,playerDemoIndicators:new Map,updateWallVisibility:()=>{}}}createPluginContext(){return{player:this,replay:this.replay,options:this.options,scene:this.scene,camera:this.camera,renderer:this.renderer,container:this.container}}createPluginStateContext(e){return{...this.createPluginContext(),state:e}}createRenderContext(){const e=this.actorManager,t=this.adapter.ball,i={position:t.position,rotation:t.rotation,velocity:t.velocity,visible:t.visible,object3d:e.ballActorId!=null?e.actors[e.ballActorId]??null:null},s=this.adapter.getAllPlayers().map(a=>{const r=e.playerNameToCarActorId[a.name];return{id:a.id,name:a.name,team:a.team,carName:a.carName,hitboxType:a.hitboxType,position:a.position,rotation:a.rotation,velocity:a.velocity,boost:a.boost,isBoosting:a.isBoosting,visible:a.isVisible,object3d:r!=null?e.actors[r]??null:null}});return{...this.createPluginContext(),...this.computeFrameRenderInfo(),state:this.getState(),time:this.currentTime,ball:i,cars:s}}emitChange(){const e=this.getState(),t=this.createPluginStateContext(e);for(const i of this.plugins)i.plugin.onStateChange?.(t);this.dispatchEvent(new CustomEvent("change",{detail:e}))}}const Wt={LEFT:1,RIGHT:2,MIDDLE:4},$=Object.freeze({NONE:0,ROTATE:1,TRUCK:2,SCREEN_PAN:4,OFFSET:8,DOLLY:16,ZOOM:32,TOUCH_ROTATE:64,TOUCH_TRUCK:128,TOUCH_SCREEN_PAN:256,TOUCH_OFFSET:512,TOUCH_DOLLY:1024,TOUCH_ZOOM:2048,TOUCH_DOLLY_TRUCK:4096,TOUCH_DOLLY_SCREEN_PAN:8192,TOUCH_DOLLY_OFFSET:16384,TOUCH_DOLLY_ROTATE:32768,TOUCH_ZOOM_TRUCK:65536,TOUCH_ZOOM_OFFSET:131072,TOUCH_ZOOM_SCREEN_PAN:262144,TOUCH_ZOOM_ROTATE:524288}),Hr={NONE:0,IN:1,OUT:-1};function La(n){return n.isPerspectiveCamera}function Js(n){return n.isOrthographicCamera}const Vr=Math.PI*2,hv=Math.PI/2,RT=1e-5,Qo=Math.PI/180;function Ni(n,e,t){return Math.max(e,Math.min(t,n))}function Ot(n,e=RT){return Math.abs(n)0==f>u&&(f=u,t.value=(f-u)/a),f}function pv(n,e,t,i,s=1/0,a,r){i=Math.max(1e-4,i);const o=2/i,l=o*a,c=1/(1+l+.48*l*l+.235*l*l*l);let u=e.x,d=e.y,h=e.z,f=n.x-u,p=n.y-d,g=n.z-h;const _=u,m=d,v=h,y=s*i,b=y*y,T=f*f+p*p+g*g;if(T>b){const U=Math.sqrt(T);f=f/U*y,p=p/U*y,g=g/U*y}u=n.x-f,d=n.y-p,h=n.z-g;const x=(t.x+o*f)*a,M=(t.y+o*p)*a,C=(t.z+o*g)*a;t.x=(t.x-o*x)*c,t.y=(t.y-o*M)*c,t.z=(t.z-o*C)*c,r.x=u+(f+x)*c,r.y=d+(p+M)*c,r.z=h+(g+C)*c;const w=_-n.x,E=m-n.y,R=v-n.z,D=r.x-_,O=r.y-m,k=r.z-v;return w*D+E*O+R*k>0&&(r.x=_,r.y=m,r.z=v,t.x=(r.x-_)/a,t.y=(r.y-m)/a,t.z=(r.z-v)/a),r}function yp(n,e){e.set(0,0),n.forEach(t=>{e.x+=t.clientX,e.y+=t.clientY}),e.x/=n.length,e.y/=n.length}function vp(n,e){return Js(n)?(console.warn(`${e} is not supported in OrthographicCamera`),!0):!1}class tN{constructor(){this._listeners={}}addEventListener(e,t){const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){const i=this._listeners;return i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){const s=this._listeners[e];if(s!==void 0){const a=s.indexOf(t);a!==-1&&s.splice(a,1)}}removeAllEventListeners(e){if(!e){this._listeners={};return}Array.isArray(this._listeners[e])&&(this._listeners[e].length=0)}dispatchEvent(e){const i=this._listeners[e.type];if(i!==void 0){e.target=this;const s=i.slice(0);for(let a=0,r=s.length;a{},this._enabled=!0,this._state=$.NONE,this._viewport=null,this._changedDolly=0,this._changedZoom=0,this._hasRested=!0,this._boundaryEnclosesCamera=!1,this._needsUpdate=!0,this._updatedLastTime=!1,this._elementRect=new DOMRect,this._isDragging=!1,this._dragNeedsUpdate=!0,this._activePointers=[],this._lockedPointer=null,this._interactiveArea=new DOMRect(0,0,1,1),this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._isUserControllingOffset=!1,this._isUserControllingZoom=!1,this._lastDollyDirection=Hr.NONE,this._thetaVelocity={value:0},this._phiVelocity={value:0},this._radiusVelocity={value:0},this._targetVelocity=new tt.Vector3,this._focalOffsetVelocity=new tt.Vector3,this._zoomVelocity={value:0},this._truckInternal=(m,v,y,b)=>{let T,x;if(La(this._camera)){const M=ft.copy(this._camera.position).sub(this._target),C=this._camera.getEffectiveFOV()*Qo,w=M.length()*Math.tan(C*.5);T=this.truckSpeed*m*w/this._elementRect.height,x=this.truckSpeed*v*w/this._elementRect.height}else if(Js(this._camera)){const M=this._camera;T=this.truckSpeed*m*(M.right-M.left)/M.zoom/this._elementRect.width,x=this.truckSpeed*v*(M.top-M.bottom)/M.zoom/this._elementRect.height}else return;b?(y?this.setFocalOffset(this._focalOffsetEnd.x+T,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(T,0,!0),this.forward(-x,!0)):y?this.setFocalOffset(this._focalOffsetEnd.x+T,this._focalOffsetEnd.y+x,this._focalOffsetEnd.z,!0):this.truck(T,x,!0)},this._rotateInternal=(m,v)=>{const y=Vr*this.azimuthRotateSpeed*m/this._elementRect.height,b=Vr*this.polarRotateSpeed*v/this._elementRect.height;this.rotate(y,b,!0)},this._dollyInternal=(m,v,y)=>{const b=Math.pow(.95,-m*this.dollySpeed),T=this._sphericalEnd.radius,x=this._sphericalEnd.radius*b,M=Ni(x,this.minDistance,this.maxDistance),C=M-x;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(x,!0):this.infinityDolly&&!this.dollyToCursor?(this.dollyInFixed(C,!0),this._dollyToNoClamp(M,!0)):this._dollyToNoClamp(M,!0),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?x:M)-T,this._dollyControlCoord.set(v,y)),this._lastDollyDirection=Math.sign(-m)},this._zoomInternal=(m,v,y)=>{const b=Math.pow(.95,m*this.dollySpeed),T=this._zoom,x=this._zoom*b;this.zoomTo(x,!0),this.dollyToCursor&&(this._changedZoom+=x-T,this._dollyControlCoord.set(v,y))},typeof tt>"u"&&console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information."),this._camera=e,this._yAxisUpSpace=new tt.Quaternion().setFromUnitVectors(this._camera.up,yu),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=$.NONE,this._target=new tt.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new tt.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=new tt.Spherical().setFromVector3(ft.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace)),this._sphericalEnd=this._spherical.clone(),this._lastDistance=this._spherical.radius,this._zoom=this._camera.zoom,this._zoomEnd=this._zoom,this._lastZoom=this._zoom,this._nearPlaneCorners=[new tt.Vector3,new tt.Vector3,new tt.Vector3,new tt.Vector3],this._updateNearPlaneCorners(),this._boundary=new tt.Box3(new tt.Vector3(-1/0,-1/0,-1/0),new tt.Vector3(1/0,1/0,1/0)),this._cameraUp0=this._camera.up.clone(),this._target0=this._target.clone(),this._position0=this._camera.position.clone(),this._zoom0=this._zoom,this._focalOffset0=this._focalOffset.clone(),this._dollyControlCoord=new tt.Vector2,this.mouseButtons={left:$.ROTATE,middle:$.DOLLY,right:$.TRUCK,wheel:La(this._camera)?$.DOLLY:Js(this._camera)?$.ZOOM:$.NONE},this.touches={one:$.TOUCH_ROTATE,two:La(this._camera)?$.TOUCH_DOLLY_TRUCK:Js(this._camera)?$.TOUCH_ZOOM_TRUCK:$.NONE,three:$.TOUCH_TRUCK};const i=new tt.Vector2,s=new tt.Vector2,a=new tt.Vector2,r=m=>{if(!this._enabled||!this._domElement)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const b=this._domElement.getBoundingClientRect(),T=m.clientX/b.width,x=m.clientY/b.height;if(Tthis._interactiveArea.right||xthis._interactiveArea.bottom)return}const v=m.pointerType!=="mouse"?null:(m.buttons&Wt.LEFT)===Wt.LEFT?Wt.LEFT:(m.buttons&Wt.MIDDLE)===Wt.MIDDLE?Wt.MIDDLE:(m.buttons&Wt.RIGHT)===Wt.RIGHT?Wt.RIGHT:null;if(v!==null){const b=this._findPointerByMouseButton(v);b&&this._disposePointer(b)}if((m.buttons&Wt.LEFT)===Wt.LEFT&&this._lockedPointer)return;const y={pointerId:m.pointerId,clientX:m.clientX,clientY:m.clientY,deltaX:0,deltaY:0,mouseButton:v};this._activePointers.push(y),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),this._isDragging=!0,h(m)},o=m=>{m.cancelable&&m.preventDefault();const v=m.pointerId,y=this._lockedPointer||this._findPointerById(v);if(y){if(y.clientX=m.clientX,y.clientY=m.clientY,y.deltaX=m.movementX,y.deltaY=m.movementY,this._state=0,m.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else(!this._isDragging&&this._lockedPointer||this._isDragging&&(m.buttons&Wt.LEFT)===Wt.LEFT)&&(this._state=this._state|this.mouseButtons.left),this._isDragging&&(m.buttons&Wt.MIDDLE)===Wt.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),this._isDragging&&(m.buttons&Wt.RIGHT)===Wt.RIGHT&&(this._state=this._state|this.mouseButtons.right);f()}},l=m=>{const v=this._findPointerById(m.pointerId);if(!(v&&v===this._lockedPointer)){if(v&&this._disposePointer(v),m.pointerType==="touch")switch(this._activePointers.length){case 0:this._state=$.NONE;break;case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else this._state=$.NONE;p()}};let c=-1;const u=m=>{if(!this._domElement||!this._enabled||this.mouseButtons.wheel===$.NONE)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const x=this._domElement.getBoundingClientRect(),M=m.clientX/x.width,C=m.clientY/x.height;if(Mthis._interactiveArea.right||Cthis._interactiveArea.bottom)return}if(m.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===$.ROTATE||this.mouseButtons.wheel===$.TRUCK){const x=performance.now();c-x<1e3&&this._getClientRect(this._elementRect),c=x}const v=iN?-1:-3,y=m.deltaMode===1||m.ctrlKey?m.deltaY/v:m.deltaY/(v*10),b=this.dollyToCursor?(m.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,T=this.dollyToCursor?(m.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case $.ROTATE:{this._rotateInternal(m.deltaX,m.deltaY),this._isUserControllingRotate=!0;break}case $.TRUCK:{this._truckInternal(m.deltaX,m.deltaY,!1,!1),this._isUserControllingTruck=!0;break}case $.SCREEN_PAN:{this._truckInternal(m.deltaX,m.deltaY,!1,!0),this._isUserControllingTruck=!0;break}case $.OFFSET:{this._truckInternal(m.deltaX,m.deltaY,!0,!1),this._isUserControllingOffset=!0;break}case $.DOLLY:{this._dollyInternal(-y,b,T),this._isUserControllingDolly=!0;break}case $.ZOOM:{this._zoomInternal(-y,b,T),this._isUserControllingZoom=!0;break}}this.dispatchEvent({type:"control"})},d=m=>{if(!(!this._domElement||!this._enabled)){if(this.mouseButtons.right===km.ACTION.NONE){const v=m instanceof PointerEvent?m.pointerId:0,y=this._findPointerById(v);y&&this._disposePointer(y),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l);return}m.preventDefault()}},h=m=>{if(!this._enabled)return;if(yp(this._activePointers,Kn),this._getClientRect(this._elementRect),i.copy(Kn),s.copy(Kn),this._activePointers.length>=2){const y=Kn.x-this._activePointers[1].clientX,b=Kn.y-this._activePointers[1].clientY,T=Math.sqrt(y*y+b*b);a.set(0,T);const x=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,M=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;s.set(x,M)}if(this._state=0,!m)this._lockedPointer&&(this._state=this._state|this.mouseButtons.left);else if("pointerType"in m&&m.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else!this._lockedPointer&&(m.buttons&Wt.LEFT)===Wt.LEFT&&(this._state=this._state|this.mouseButtons.left),(m.buttons&Wt.MIDDLE)===Wt.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),(m.buttons&Wt.RIGHT)===Wt.RIGHT&&(this._state=this._state|this.mouseButtons.right);((this._state&$.ROTATE)===$.ROTATE||(this._state&$.TOUCH_ROTATE)===$.TOUCH_ROTATE||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE)&&(this._sphericalEnd.theta=this._spherical.theta,this._sphericalEnd.phi=this._spherical.phi,this._thetaVelocity.value=0,this._phiVelocity.value=0),((this._state&$.TRUCK)===$.TRUCK||(this._state&$.SCREEN_PAN)===$.SCREEN_PAN||(this._state&$.TOUCH_TRUCK)===$.TOUCH_TRUCK||(this._state&$.TOUCH_SCREEN_PAN)===$.TOUCH_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN)&&(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),((this._state&$.DOLLY)===$.DOLLY||(this._state&$.TOUCH_DOLLY)===$.TOUCH_DOLLY||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE)&&(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),((this._state&$.ZOOM)===$.ZOOM||(this._state&$.TOUCH_ZOOM)===$.TOUCH_ZOOM||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_ZOOM_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE)&&(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),((this._state&$.OFFSET)===$.OFFSET||(this._state&$.TOUCH_OFFSET)===$.TOUCH_OFFSET||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET)&&(this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0)),this.dispatchEvent({type:"controlstart"})},f=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,yp(this._activePointers,Kn);const v=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,y=v?-v.deltaX:s.x-Kn.x,b=v?-v.deltaY:s.y-Kn.y;if(s.copy(Kn),((this._state&$.ROTATE)===$.ROTATE||(this._state&$.TOUCH_ROTATE)===$.TOUCH_ROTATE||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE)&&(this._rotateInternal(y,b),this._isUserControllingRotate=!0),(this._state&$.DOLLY)===$.DOLLY||(this._state&$.ZOOM)===$.ZOOM){const T=this.dollyToCursor?(i.x-this._elementRect.x)/this._elementRect.width*2-1:0,x=this.dollyToCursor?(i.y-this._elementRect.y)/this._elementRect.height*-2+1:0,M=this.dollyDragInverted?-1:1;(this._state&$.DOLLY)===$.DOLLY?(this._dollyInternal(M*b*gu,T,x),this._isUserControllingDolly=!0):(this._zoomInternal(M*b*gu,T,x),this._isUserControllingZoom=!0)}if((this._state&$.TOUCH_DOLLY)===$.TOUCH_DOLLY||(this._state&$.TOUCH_ZOOM)===$.TOUCH_ZOOM||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_ZOOM_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE){const T=Kn.x-this._activePointers[1].clientX,x=Kn.y-this._activePointers[1].clientY,M=Math.sqrt(T*T+x*x),C=a.y-M;a.set(0,M);const w=this.dollyToCursor?(s.x-this._elementRect.x)/this._elementRect.width*2-1:0,E=this.dollyToCursor?(s.y-this._elementRect.y)/this._elementRect.height*-2+1:0;(this._state&$.TOUCH_DOLLY)===$.TOUCH_DOLLY||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET?(this._dollyInternal(C*gu,w,E),this._isUserControllingDolly=!0):(this._zoomInternal(C*gu,w,E),this._isUserControllingZoom=!0)}((this._state&$.TRUCK)===$.TRUCK||(this._state&$.TOUCH_TRUCK)===$.TOUCH_TRUCK||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK)&&(this._truckInternal(y,b,!1,!1),this._isUserControllingTruck=!0),((this._state&$.SCREEN_PAN)===$.SCREEN_PAN||(this._state&$.TOUCH_SCREEN_PAN)===$.TOUCH_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_ZOOM_SCREEN_PAN)&&(this._truckInternal(y,b,!1,!0),this._isUserControllingTruck=!0),((this._state&$.OFFSET)===$.OFFSET||(this._state&$.TOUCH_OFFSET)===$.TOUCH_OFFSET||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET)&&(this._truckInternal(y,b,!0,!1),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},p=()=>{yp(this._activePointers,Kn),s.copy(Kn),this._dragNeedsUpdate=!1,(this._activePointers.length===0||this._activePointers.length===1&&this._activePointers[0]===this._lockedPointer)&&(this._isDragging=!1),this._activePointers.length===0&&this._domElement&&(this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this.dispatchEvent({type:"controlend"}))};this.lockPointer=()=>{!this._enabled||!this._domElement||(this.cancel(),this._lockedPointer={pointerId:-1,clientX:0,clientY:0,deltaX:0,deltaY:0,mouseButton:null},this._activePointers.push(this._lockedPointer),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.requestPointerLock(),this._domElement.ownerDocument.addEventListener("pointerlockchange",g),this._domElement.ownerDocument.addEventListener("pointerlockerror",_),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),h())},this.unlockPointer=()=>{var m,v,y;this._lockedPointer!==null&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),(m=this._domElement)===null||m===void 0||m.ownerDocument.exitPointerLock(),(v=this._domElement)===null||v===void 0||v.ownerDocument.removeEventListener("pointerlockchange",g),(y=this._domElement)===null||y===void 0||y.ownerDocument.removeEventListener("pointerlockerror",_),this.cancel()};const g=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},_=()=>{this.unlockPointer()};this._addAllEventListeners=m=>{this._domElement=m,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",r),this._domElement.addEventListener("pointercancel",l),this._domElement.addEventListener("wheel",u,{passive:!1}),this._domElement.addEventListener("contextmenu",d)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect="",this._domElement.removeEventListener("pointerdown",r),this._domElement.removeEventListener("pointercancel",l),this._domElement.removeEventListener("wheel",u,{passive:!1}),this._domElement.removeEventListener("contextmenu",d),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.removeEventListener("pointerlockchange",g),this._domElement.ownerDocument.removeEventListener("pointerlockerror",_))},this.cancel=()=>{this._state!==$.NONE&&(this._state=$.NONE,this._activePointers.length=0,p())},t&&this.connect(t),this.update(0)}get camera(){return this._camera}set camera(e){this._camera=e,this.updateCameraUp(),this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0}get enabled(){return this._enabled}set enabled(e){this._enabled=e,this._domElement&&(e?(this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none"):(this.cancel(),this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect=""))}get active(){return!this._hasRested}get currentAction(){return this._state}get distance(){return this._spherical.radius}set distance(e){this._spherical.radius===e&&this._sphericalEnd.radius===e||(this._spherical.radius=e,this._sphericalEnd.radius=e,this._needsUpdate=!0)}get azimuthAngle(){return this._spherical.theta}set azimuthAngle(e){this._spherical.theta===e&&this._sphericalEnd.theta===e||(this._spherical.theta=e,this._sphericalEnd.theta=e,this._needsUpdate=!0)}get polarAngle(){return this._spherical.phi}set polarAngle(e){this._spherical.phi===e&&this._sphericalEnd.phi===e||(this._spherical.phi=e,this._sphericalEnd.phi=e,this._needsUpdate=!0)}get boundaryEnclosesCamera(){return this._boundaryEnclosesCamera}set boundaryEnclosesCamera(e){this._boundaryEnclosesCamera=e,this._needsUpdate=!0}set interactiveArea(e){this._interactiveArea.width=Ni(e.width,0,1),this._interactiveArea.height=Ni(e.height,0,1),this._interactiveArea.x=Ni(e.x,0,1-this._interactiveArea.width),this._interactiveArea.y=Ni(e.y,0,1-this._interactiveArea.height)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}rotate(e,t,i=!1){return this.rotateTo(this._sphericalEnd.theta+e,this._sphericalEnd.phi+t,i)}rotateAzimuthTo(e,t=!1){return this.rotateTo(e,this._sphericalEnd.phi,t)}rotatePolarTo(e,t=!1){return this.rotateTo(this._sphericalEnd.theta,e,t)}rotateTo(e,t,i=!1){this._isUserControllingRotate=!1;const s=Ni(e,this.minAzimuthAngle,this.maxAzimuthAngle),a=Ni(t,this.minPolarAngle,this.maxPolarAngle);this._sphericalEnd.theta=s,this._sphericalEnd.phi=a,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,i||(this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi);const r=!i||Ct(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ct(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(r)}dolly(e,t=!1){return this.dollyTo(this._sphericalEnd.radius-e,t)}dollyTo(e,t=!1){return this._isUserControllingDolly=!1,this._lastDollyDirection=Hr.NONE,this._changedDolly=0,this._dollyToNoClamp(Ni(e,this.minDistance,this.maxDistance),t)}_dollyToNoClamp(e,t=!1){const i=this._sphericalEnd.radius;if(this.colliderMeshes.length>=1){const r=this._collisionTest(),o=Ct(r,this._spherical.radius);if(!(i>e)&&o)return Promise.resolve();this._sphericalEnd.radius=Math.min(e,r)}else this._sphericalEnd.radius=e;this._needsUpdate=!0,t||(this._spherical.radius=this._sphericalEnd.radius);const a=!t||Ct(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(a)}dollyInFixed(e,t=!1){this._targetEnd.add(this._getCameraDirection(nl).multiplyScalar(e)),t||this._target.copy(this._targetEnd);const i=!t||Ct(this._target.x,this._targetEnd.x,this.restThreshold)&&Ct(this._target.y,this._targetEnd.y,this.restThreshold)&&Ct(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(i)}zoom(e,t=!1){return this.zoomTo(this._zoomEnd+e,t)}zoomTo(e,t=!1){this._isUserControllingZoom=!1,this._zoomEnd=Ni(e,this.minZoom,this.maxZoom),this._needsUpdate=!0,t||(this._zoom=this._zoomEnd);const i=!t||Ct(this._zoom,this._zoomEnd,this.restThreshold);return this._changedZoom=0,this._createOnRestPromise(i)}pan(e,t,i=!1){return console.warn("`pan` has been renamed to `truck`"),this.truck(e,t,i)}truck(e,t,i=!1){this._camera.updateMatrix(),es.setFromMatrixColumn(this._camera.matrix,0),ts.setFromMatrixColumn(this._camera.matrix,1),es.multiplyScalar(e),ts.multiplyScalar(-t);const s=ft.copy(es).add(ts),a=Tt.copy(this._targetEnd).add(s);return this.moveTo(a.x,a.y,a.z,i)}forward(e,t=!1){ft.setFromMatrixColumn(this._camera.matrix,0),ft.crossVectors(this._camera.up,ft),ft.multiplyScalar(e);const i=Tt.copy(this._targetEnd).add(ft);return this.moveTo(i.x,i.y,i.z,t)}elevate(e,t=!1){return ft.copy(this._camera.up).multiplyScalar(e),this.moveTo(this._targetEnd.x+ft.x,this._targetEnd.y+ft.y,this._targetEnd.z+ft.z,t)}moveTo(e,t,i,s=!1){this._isUserControllingTruck=!1;const a=ft.set(e,t,i).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,a,this.boundaryFriction),this._needsUpdate=!0,s||this._target.copy(this._targetEnd);const r=!s||Ct(this._target.x,this._targetEnd.x,this.restThreshold)&&Ct(this._target.y,this._targetEnd.y,this.restThreshold)&&Ct(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(r)}lookInDirectionOf(e,t,i,s=!1){const o=ft.set(e,t,i).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd);return this.setPosition(o.x,o.y,o.z,s)}fitToBox(e,t,{cover:i=!1,paddingLeft:s=0,paddingRight:a=0,paddingBottom:r=0,paddingTop:o=0}={}){const l=[],c=e.isBox3?$r.copy(e):$r.setFromObject(e);c.isEmpty()&&(console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve());const u=fv(this._sphericalEnd.theta,hv),d=fv(this._sphericalEnd.phi,hv);l.push(this.rotateTo(u,d,t));const h=ft.setFromSpherical(this._sphericalEnd).normalize(),f=vv.setFromUnitVectors(h,xp),p=Ct(Math.abs(h.y),1);p&&f.multiply(Sp.setFromAxisAngle(yu,u)),f.multiply(this._yAxisUpSpaceInverse);const g=yv.makeEmpty();Tt.copy(c.min).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.min).setX(c.max.x).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.min).setY(c.max.y).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.max).setZ(c.min.z).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.min).setZ(c.max.z).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.max).setY(c.min.y).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.max).setX(c.min.x).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.max).applyQuaternion(f),g.expandByPoint(Tt),g.min.x-=s,g.min.y-=r,g.max.x+=a,g.max.y+=o,f.setFromUnitVectors(xp,h),p&&f.premultiply(Sp.invert()),f.premultiply(this._yAxisUpSpace);const _=g.getSize(ft),m=g.getCenter(Tt).applyQuaternion(f);if(La(this._camera)){const v=this.getDistanceToFitBox(_.x,_.y,_.z,i);l.push(this.moveTo(m.x,m.y,m.z,t)),l.push(this.dollyTo(v,t)),l.push(this.setFocalOffset(0,0,0,t))}else if(Js(this._camera)){const v=this._camera,y=v.right-v.left,b=v.top-v.bottom,T=i?Math.max(y/_.x,b/_.y):Math.min(y/_.x,b/_.y);l.push(this.moveTo(m.x,m.y,m.z,t)),l.push(this.zoomTo(T,t)),l.push(this.setFocalOffset(0,0,0,t))}return Promise.all(l)}fitToSphere(e,t){const i=[],a="isObject3D"in e?km.createBoundingSphere(e,wp):wp.copy(e);if(i.push(this.moveTo(a.center.x,a.center.y,a.center.z,t)),La(this._camera)){const r=this.getDistanceToFitSphere(a.radius);i.push(this.dollyTo(r,t))}else if(Js(this._camera)){const r=this._camera.right-this._camera.left,o=this._camera.top-this._camera.bottom,l=2*a.radius,c=Math.min(r/l,o/l);i.push(this.zoomTo(c,t))}return i.push(this.setFocalOffset(0,0,0,t)),Promise.all(i)}setLookAt(e,t,i,s,a,r,o=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Hr.NONE,this._changedDolly=0;const l=Tt.set(s,a,r),c=ft.set(e,t,i);this._targetEnd.copy(l),this._sphericalEnd.setFromVector3(c.sub(l).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,o||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const u=!o||Ct(this._target.x,this._targetEnd.x,this.restThreshold)&&Ct(this._target.y,this._targetEnd.y,this.restThreshold)&&Ct(this._target.z,this._targetEnd.z,this.restThreshold)&&Ct(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ct(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Ct(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(u)}lerpLookAt(e,t,i,s,a,r,o,l,c,u,d,h,f,p=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Hr.NONE,this._changedDolly=0;const g=ft.set(s,a,r),_=Tt.set(e,t,i);vi.setFromVector3(_.sub(g).applyQuaternion(this._yAxisUpSpace));const m=Gr.set(u,d,h),v=Tt.set(o,l,c);il.setFromVector3(v.sub(m).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(g.lerp(m,f));const y=il.theta-vi.theta,b=il.phi-vi.phi,T=il.radius-vi.radius;this._sphericalEnd.set(vi.radius+T*f,vi.phi+b*f,vi.theta+y*f),this.normalizeRotations(),this._needsUpdate=!0,p||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const x=!p||Ct(this._target.x,this._targetEnd.x,this.restThreshold)&&Ct(this._target.y,this._targetEnd.y,this.restThreshold)&&Ct(this._target.z,this._targetEnd.z,this.restThreshold)&&Ct(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ct(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Ct(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(x)}setPosition(e,t,i,s=!1){return this.setLookAt(e,t,i,this._targetEnd.x,this._targetEnd.y,this._targetEnd.z,s)}setTarget(e,t,i,s=!1){const a=this.getPosition(ft),r=this.setLookAt(a.x,a.y,a.z,e,t,i,s);return this._sphericalEnd.phi=Ni(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),r}setFocalOffset(e,t,i,s=!1){this._isUserControllingOffset=!1,this._focalOffsetEnd.set(e,t,i),this._needsUpdate=!0,s||this._focalOffset.copy(this._focalOffsetEnd);const a=!s||Ct(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&Ct(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&Ct(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(a)}setOrbitPoint(e,t,i){this._camera.updateMatrixWorld(),es.setFromMatrixColumn(this._camera.matrixWorldInverse,0),ts.setFromMatrixColumn(this._camera.matrixWorldInverse,1),Da.setFromMatrixColumn(this._camera.matrixWorldInverse,2);const s=ft.set(e,t,i),a=s.distanceTo(this._camera.position),r=s.sub(this._camera.position);es.multiplyScalar(r.x),ts.multiplyScalar(r.y),Da.multiplyScalar(r.z),ft.copy(es).add(ts).add(Da),ft.z=ft.z+a,this.dollyTo(a,!1),this.setFocalOffset(-ft.x,ft.y,-ft.z,!1),this.moveTo(e,t,i,!1)}setBoundary(e){if(!e){this._boundary.min.set(-1/0,-1/0,-1/0),this._boundary.max.set(1/0,1/0,1/0),this._needsUpdate=!0;return}this._boundary.copy(e),this._boundary.clampPoint(this._targetEnd,this._targetEnd),this._needsUpdate=!0}setViewport(e,t,i,s){if(e===null){this._viewport=null;return}this._viewport=this._viewport||new tt.Vector4,typeof e=="number"?this._viewport.set(e,t,i,s):this._viewport.copy(e)}getDistanceToFitBox(e,t,i,s=!1){if(vp(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const a=e/t,r=this._camera.getEffectiveFOV()*Qo,o=this._camera.aspect;return((s?a>o:at.pointerId===e)}_findPointerByMouseButton(e){return this._activePointers.find(t=>t.mouseButton===e)}_disposePointer(e){this._activePointers.splice(this._activePointers.indexOf(e),1)}_encloseToBoundary(e,t,i){const s=t.lengthSq();if(s===0)return e;const a=Tt.copy(t).add(e),o=this._boundary.clampPoint(a,Gr).sub(a),l=o.lengthSq();if(l===0)return e.add(t);if(l===s)return e;if(i===0)return e.add(t).add(o);{const c=1+i*l/t.dot(o);return e.add(Tt.copy(t).multiplyScalar(c)).add(o.multiplyScalar(1-i))}}_updateNearPlaneCorners(){if(La(this._camera)){const e=this._camera,t=e.near,i=e.getEffectiveFOV()*Qo,s=Math.tan(i*.5)*t,a=s*e.aspect;this._nearPlaneCorners[0].set(-a,-s,0),this._nearPlaneCorners[1].set(a,-s,0),this._nearPlaneCorners[2].set(a,s,0),this._nearPlaneCorners[3].set(-a,s,0)}else if(Js(this._camera)){const e=this._camera,t=1/e.zoom,i=e.left*t,s=e.right*t,a=e.top*t,r=e.bottom*t;this._nearPlaneCorners[0].set(i,a,0),this._nearPlaneCorners[1].set(s,a,0),this._nearPlaneCorners[2].set(s,r,0),this._nearPlaneCorners[3].set(i,r,0)}}_collisionTest(){let e=1/0;if(!(this.colliderMeshes.length>=1)||vp(this._camera,"_collisionTest"))return e;const i=this._getTargetDirection(nl);Tp.lookAt(mv,i,this._camera.up);for(let s=0;s<4;s++){const a=Tt.copy(this._nearPlaneCorners[s]);a.applyMatrix4(Tp);const r=Gr.addVectors(this._target,a);vu.set(r,i),vu.far=this._spherical.radius+1;const o=vu.intersectObjects(this.colliderMeshes);o.length!==0&&o[0].distance{const i=()=>{this.removeEventListener("rest",i),t()};this.addEventListener("rest",i)}))}_addAllEventListeners(e){}_removeAllEventListeners(){}get dampingFactor(){return console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead."),0}set dampingFactor(e){console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead.")}get draggingDampingFactor(){return console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead."),0}set draggingDampingFactor(e){console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead.")}static createBoundingSphere(e,t=new tt.Sphere){const i=t,s=i.center;$r.makeEmpty(),e.traverseVisible(r=>{r.isMesh&&$r.expandByObject(r)}),$r.getCenter(s);let a=0;return e.traverseVisible(r=>{if(!r.isMesh)return;const o=r;if(!o.geometry)return;const l=o.geometry.clone();l.applyMatrix4(o.matrixWorld);const u=l.attributes.position;for(let d=0,h=u.count;di.preventDefault()),this.isFollowingViewer=!1,this.followTargetPosition=new S,this.followTargetQuaternion=new dt,this.followPositionLerpFactor=.12,this.followRotationSlerpFactor=.1,this.hasFollowTarget=!1,this.isRightMouseDown=!1,this.lastMouseX=null,this.lastMouseY=null,this.savedCameraState=null,this.isInReplayMode=!1}setMode(e){if(this.mode=e,e==="ballOrbit"){if(this.controls.enabled=!0,this.lastBallOrbitPos=null,this.ballOrbitScrollHandler||(this.ballOrbitScrollHandler=t=>{if(this.mode==="ballOrbit"&&!this.isFollowingViewer){t.preventDefault();const i=Math.max(this.controls.distance*.2,100);t.deltaY>0?this.controls.dolly(-i,!0):this.controls.dolly(i,!0)}},this.domElement.addEventListener("wheel",this.ballOrbitScrollHandler,{passive:!1})),this.targetBall){const t=this.targetBall.position;this.camera.position.distanceTo(t),this.controls.setLookAt(this.camera.position.x,this.camera.position.y,this.camera.position.z,t.x,t.y,t.z,!1)}return}if(e==="free"){if(this.controls.enabled=!1,!this.freeCamKeys){this.freeCamKeys={forward:!1,backward:!1,left:!1,right:!1,up:!1,down:!1},this.freeCamSpeed=2e3,this.freeCamRotation={yaw:0,pitch:0};const t=new S;this.camera.getWorldDirection(t),this.freeCamRotation.yaw=Math.atan2(t.x,t.z),this.freeCamRotation.pitch=Math.asin(-t.y),this.onKeyDown=i=>this.handleFreeCamKeyDown(i),this.onKeyUp=i=>this.handleFreeCamKeyUp(i),this.onMouseMove=i=>this.handleFreeCamMouseMove(i),this.onMouseDown=i=>{i.button===2&&this.mode==="free"&&!this.isFollowingViewer&&(this.isRightMouseDown=!0,this.domElement.requestPointerLock?.())},this.onMouseUp=i=>{i.button===2&&(this.isRightMouseDown=!1,document.pointerLockElement===this.domElement&&document.exitPointerLock?.())},this.onPointerLockChange=()=>{document.pointerLockElement!==this.domElement&&(this.isRightMouseDown=!1)},this.onMouseLeave=()=>{document.pointerLockElement!==this.domElement&&(this.isRightMouseDown=!1)},this.onWindowBlur=()=>{this.isRightMouseDown=!1,document.pointerLockElement===this.domElement&&document.exitPointerLock?.(),this.freeCamKeys&&(this.freeCamKeys.forward=!1,this.freeCamKeys.backward=!1,this.freeCamKeys.left=!1,this.freeCamKeys.right=!1,this.freeCamKeys.up=!1,this.freeCamKeys.down=!1)},this.onVisibilityChange=()=>{document.hidden&&(this.isRightMouseDown=!1,document.pointerLockElement===this.domElement&&document.exitPointerLock?.(),this.freeCamKeys&&(this.freeCamKeys.forward=!1,this.freeCamKeys.backward=!1,this.freeCamKeys.left=!1,this.freeCamKeys.right=!1,this.freeCamKeys.up=!1,this.freeCamKeys.down=!1))},document.addEventListener("keydown",this.onKeyDown),document.addEventListener("keyup",this.onKeyUp),document.addEventListener("mousemove",this.onMouseMove),this.domElement.addEventListener("mousedown",this.onMouseDown),document.addEventListener("mouseup",this.onMouseUp),document.addEventListener("pointerlockchange",this.onPointerLockChange),this.domElement.addEventListener("mouseleave",this.onMouseLeave),window.addEventListener("blur",this.onWindowBlur),document.addEventListener("visibilitychange",this.onVisibilityChange)}this.isRightMouseDown=!1}else this.controls.enabled=!1,this.lastIsBallCam=null,this.currentBlend=0,this.targetBlend=0}setTargetCar(e){if(this.targetCar!==e&&(this.currentBallCamAngle=null,this.targetCar&&e)){this.targetHandoff={elapsed:0,duration:sN,startPosition:this.camera.position.clone(),startQuaternion:this.camera.quaternion.clone()};const t=new S().subVectors(this.camera.position,e.position);t.y=0,t.length()>.01&&(t.normalize(),this.smoothedCarYaw=Math.atan2(-t.x,-t.z)),this.lastCarPos&&this.lastCarPos.copy(e.position)}this.targetCar=e}setTargetBall(e){this.targetBall=e}handleFreeCamKeyDown(e){if(this.mode!=="free"||this.isFollowingViewer)return;const t=e.target;if(!(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable))switch(e.code){case"KeyW":case"ArrowUp":this.freeCamKeys.forward=!0;break;case"KeyS":case"ArrowDown":this.freeCamKeys.backward=!0;break;case"KeyA":case"ArrowLeft":this.freeCamKeys.left=!0;break;case"KeyD":case"ArrowRight":this.freeCamKeys.right=!0;break;case"Space":this.freeCamKeys.up=!0;break;case"ShiftLeft":case"ShiftRight":this.freeCamKeys.down=!0;break}}handleFreeCamKeyUp(e){switch(e.code){case"KeyW":case"ArrowUp":this.freeCamKeys.forward=!1;break;case"KeyS":case"ArrowDown":this.freeCamKeys.backward=!1;break;case"KeyA":case"ArrowLeft":this.freeCamKeys.left=!1;break;case"KeyD":case"ArrowRight":this.freeCamKeys.right=!1;break;case"Space":this.freeCamKeys.up=!1;break;case"ShiftLeft":case"ShiftRight":this.freeCamKeys.down=!1;break}}handleFreeCamMouseMove(e){if(this.mode!=="free"||!this.isRightMouseDown||this.isFollowingViewer)return;const t=e.movementX||0,i=e.movementY||0,s=.003;this.freeCamRotation.yaw-=t*s,this.freeCamRotation.pitch+=i*s,this.freeCamRotation.pitch=Math.max(-Math.PI/2+.01,Math.min(Math.PI/2-.01,this.freeCamRotation.pitch))}updateFreeCam(e){if(!this.freeCamKeys)return;const t=new S(Math.sin(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch),-Math.sin(this.freeCamRotation.pitch),Math.cos(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch));t.normalize();const i=new S(Math.sin(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch),-Math.sin(this.freeCamRotation.pitch),Math.cos(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch));i.normalize();const s=new S(Math.sin(this.freeCamRotation.yaw-Math.PI/2),0,Math.cos(this.freeCamRotation.yaw-Math.PI/2)),a=new S(0,1,0),r=new S,o=this.freeCamSpeed*e;this.freeCamKeys.forward&&r.add(i.clone().multiplyScalar(o)),this.freeCamKeys.backward&&r.add(i.clone().multiplyScalar(-o)),this.freeCamKeys.right&&r.add(s.clone().multiplyScalar(o)),this.freeCamKeys.left&&r.add(s.clone().multiplyScalar(-o)),this.freeCamKeys.up&&r.add(a.clone().multiplyScalar(o)),this.freeCamKeys.down&&r.add(a.clone().multiplyScalar(-o)),r.length()>0&&r.normalize().multiplyScalar(o),this.camera.position.add(r);const l=this.camera.position.clone().add(t);this.camera.lookAt(l),this.controls.setLookAt(this.camera.position.x,this.camera.position.y,this.camera.position.z,l.x,l.y,l.z,!1)}update(e,t=!0){if(this.isFollowingViewer){this.updateFollowInterpolation(e);return}if(this.mode==="free"){this.updateFreeCam(e),this.controls.update(e);return}if(this.mode==="ballOrbit"){if(this.targetBall){const p=this.targetBall.position;this.lastBallOrbitPos||(this.lastBallOrbitPos=p.clone());const g=new S().subVectors(p,this.lastBallOrbitPos);if(this.controls.setTarget(p.x,p.y,p.z,!1),g.lengthSq()>.01){const _=new S;this.controls.getPosition(_);const m=_.x+g.x,v=_.y+g.y,y=_.z+g.z;this.controls.setPosition(m,v,y,!1),this.lastBallOrbitPos.copy(p)}}this.controls.update(e);return}if(!this.targetCar){this.controls.update(e);return}const i=this.targetCar.position.clone(),s=this.targetCar.quaternion;if(this.lastIsBallCam!==null&&this.lastIsBallCam!==t&&!t){const p=new S().subVectors(this.camera.position,i);p.y=0,p.length()>.01&&(p.normalize(),this.smoothedCarYaw=Math.atan2(-p.x,-p.z))}this.lastIsBallCam=t;const a=this.calculateCarCamPosition(i,s,e),r=this.calculateBallCamPosition(i,s,e);this.targetBlend=t?1:0;const o=Math.max(.15,Math.min(.6,this.baseDuration/this.transitionSpeed)),l=e/o;this.currentBlendthis.targetBlend&&(this.currentBlend=Math.max(this.currentBlend-l,this.targetBlend));const c=this.currentBlend,u=c*c*(3-2*c),d=new S().lerpVectors(a.cameraPos,r.cameraPos,u);this._tempMatrix.lookAt(a.cameraPos,a.lookTarget,new S(0,1,0)),this._tempQuatCarCam.setFromRotationMatrix(this._tempMatrix),this._tempMatrix.lookAt(r.cameraPos,r.lookTarget,new S(0,1,0)),this._tempQuatBallCam.setFromRotationMatrix(this._tempMatrix),this._tempQuatCarCam.dot(this._tempQuatBallCam)<0&&this._tempQuatBallCam.set(-this._tempQuatBallCam.x,-this._tempQuatBallCam.y,-this._tempQuatBallCam.z,-this._tempQuatBallCam.w);const h=new dt().slerpQuaternions(this._tempQuatCarCam,this._tempQuatBallCam,u);if(this.targetHandoff){this.targetHandoff.elapsed+=e;const p=Math.min(1,this.targetHandoff.elapsed/this.targetHandoff.duration),g=p*p*(3-2*p),_=d.clone(),m=h.clone();d.lerpVectors(this.targetHandoff.startPosition,_,g),h.slerpQuaternions(this.targetHandoff.startQuaternion,m,g),p>=1&&(this.targetHandoff=null)}if(this.camera.position.copy(d),this.camera.quaternion.copy(h),this.followAngle!==0){const p=this.followAngle*Math.PI/180;this.camera.rotateX(-p)}this.currentCamPos||(this.currentCamPos=new S),this.currentLookTarget||(this.currentLookTarget=new S),this.currentCamPos.copy(d);const f=new S(0,0,-1).applyQuaternion(this.camera.quaternion);this.currentLookTarget.copy(d).add(f.multiplyScalar(100)),this.enforceMinHeight()}calculateBallCamPosition(e,t,i=1/60){if(!this.targetBall)return this.calculateCarCamPosition(e,t,i);const s=this.targetBall.position.clone(),a=new S().subVectors(e,s);a.y=0,a.normalize();const r=e.clone().add(a.multiplyScalar(this.followDistance)),o=s.y-e.y,c=Math.min(1,Math.max(0,o/800));r.y=e.y+this.followHeight-c*100,r.y.01)s.normalize(),u=Math.atan2(s.x,s.z);else if(a>.05){s.normalize();let y=Math.atan2(s.x,s.z)-o;for(;y>Math.PI;)y-=Math.PI*2;for(;y<-Math.PI;)y+=Math.PI*2;Math.abs(y)>Math.PI/2?u=o+Math.PI:u=o}else u=o;this.lastCarPos.copy(e),this.smoothedCarYaw===void 0&&(this.smoothedCarYaw=u);let d=u-this.smoothedCarYaw;for(;d>Math.PI;)d-=Math.PI*2;for(;d<-Math.PI;)d+=Math.PI*2;const h=c?this.swivelSpeed*.4:this.swivelSpeed;this.smoothedCarYaw+=d*Math.min(1,h*(1/60));const f=-Math.sin(this.smoothedCarYaw),p=-Math.cos(this.smoothedCarYaw),g=new S(e.x+f*this.followDistance,e.y+this.followHeight,e.z+p*this.followDistance);g.yMath.PI;)s-=Math.PI*2;for(;s<-Math.PI;)s+=Math.PI*2;this.followCurrentOrbitParams.azimuth+=s*.15,this.followCurrentOrbitParams.polar+=(this.followTargetOrbitParams.polar-this.followCurrentOrbitParams.polar)*.15,this.controls.setTarget(t.x,t.y,t.z,!1),this.controls.dollyTo(this.followCurrentOrbitParams.distance,!1),this.controls.rotateTo(this.followCurrentOrbitParams.azimuth,this.followCurrentOrbitParams.polar,!1),this.controls.update(e)}}else{if(this.camera.position.lerp(this.followTargetPosition,this.followPositionLerpFactor),this.camera.quaternion.slerp(this.followTargetQuaternion,this.followRotationSlerpFactor),this.freeCamRotation){const i=new S;this.camera.getWorldDirection(i),this.freeCamRotation.yaw=Math.atan2(i.x,i.z),this.freeCamRotation.pitch=Math.asin(-i.y)}const t=new S;this.camera.getWorldDirection(t),t.multiplyScalar(100).add(this.camera.position),this.controls.setLookAt(this.camera.position.x,this.camera.position.y,this.camera.position.z,t.x,t.y,t.z,!1)}}setDefaultFreecamPosition(){if(this.camera.position.copy(this.defaultFreecamPosition),this.camera.lookAt(this.defaultFreecamLookAt),this.freeCamRotation){const e=new S;this.camera.getWorldDirection(e),this.freeCamRotation.yaw=Math.atan2(e.x,e.z),this.freeCamRotation.pitch=Math.asin(-e.y)}this.controls.setLookAt(this.defaultFreecamPosition.x,this.defaultFreecamPosition.y,this.defaultFreecamPosition.z,this.defaultFreecamLookAt.x,this.defaultFreecamLookAt.y,this.defaultFreecamLookAt.z,!1)}getIsPointerLocked(){return this.isPointerLocked||!1}setPointerLockCallback(e){this.onPointerLockStateChange=e}dispose(){this.controls.dispose(),this.ballOrbitScrollHandler&&this.domElement.removeEventListener("wheel",this.ballOrbitScrollHandler),this.onKeyDown&&document.removeEventListener("keydown",this.onKeyDown),this.onKeyUp&&document.removeEventListener("keyup",this.onKeyUp),this.onMouseMove&&document.removeEventListener("mousemove",this.onMouseMove),this.onMouseDown&&this.domElement.removeEventListener("mousedown",this.onMouseDown),this.onMouseUp&&document.removeEventListener("mouseup",this.onMouseUp),this.onPointerLockChange&&document.removeEventListener("pointerlockchange",this.onPointerLockChange),this.onMouseLeave&&this.domElement.removeEventListener("mouseleave",this.onMouseLeave),this.onWindowBlur&&window.removeEventListener("blur",this.onWindowBlur),this.onVisibilityChange&&document.removeEventListener("visibilitychange",this.onVisibilityChange)}}function xv(n){if(n.pitch===void 0||n.angle!==void 0)return n;const{pitch:e,...t}=n;return{...t,angle:e}}const rN={distance:260,height:90,angle:-4,stiffness:.45,swivelSpeed:4.3,transitionSpeed:1.3,fov:110};function oN(n={}){let e=null,t=null,i=n.mode??(n.follow?"follow":"orbit"),s=n.follow??null,a=n.ballCam??null,r=a??!0,o=xv({...n.settings}),l=1;const c=n.useRecordedSettings!==!1;let u=null;const d=new S;let h=!1;function f(){if(!(!t||!e)){if(t.player.controls.enabled=i==="orbit",i==="free")e.setMode("free");else if(i==="ballOrbit"){const y=_();y&&e.setTargetBall(y),e.setMode("ballOrbit")}else e.setMode("car");u=null}}function p(){return!c||!t||!s?null:t.player.adapter.getPlayer(s)?.cameraSettings??null}function g(){const y={...rN,...p(),...o};return l!==1&&y.distance!==void 0&&(y.distance*=l),y}function _(){if(!t)return null;const y=t.player.actorManager;return y.ballActorId!=null?y.actors[y.ballActorId]??null:null}function m(y){const b=g().fov;if(!b)return;const T=b*Math.PI/180,x=16/9,M=2*Math.atan(Math.tan(T/2)/x),C=2*Math.atan(Math.tan(T/2)/y.aspect),w=Math.max(M,C)*180/Math.PI;Math.abs(y.fov-w)>.1&&(y.fov=w,y.updateProjectionMatrix())}function v(y,b){if(!e)return;if(i==="free"){o.freeCamSpeed&&(e.freeCamSpeed=o.freeCamSpeed),e.update(b);return}if(i==="ballOrbit"){y.ball.object3d&&e.setTargetBall(y.ball.object3d),e.update(b);return}const x=(s?y.cars.find(C=>C.name===s):void 0)?.object3d??null;if(!x){e.update(b);return}e.setTargetCar(x),y.ball.object3d&&e.setTargetBall(y.ball.object3d),e.setFollowSettings(g());const M=s?y.player.adapter.getPlayer(s):void 0;r=a??M?.isBallCam??!0,d.copy(x.position),h=!0,e.update(b,r)}return{id:"camera",setup(y){t=y,e=new aN(y.camera,y.renderer.domElement),f()},beforeRender(y){if(!e||(m(y.camera),i==="orbit"))return;const b=performance.now(),T=u===null?1/60:Math.min(.1,(b-u)/1e3);u=b,v(y,T)},teardown(){i="orbit",t&&(t.player.controls.enabled=!0),e?.dispose(),e=null,t=null},setMode(y){y!==i&&(i=y,f())},getMode(){return i},follow(y){s=y,i="follow",f()},release(){i="orbit",t&&h&&t.player.controls.target.copy(d),f()},getTarget(){return s},setBallCam(y){a=y,y!==null&&(r=y)},getBallCam(){return r},setCameraSettings(y){o=y===null?{}:{...o,...xv(y)}},setDistanceScale(y){l=Math.max(.25,y)},getDistanceScale(){return l},getCameraSettings(){return g()},getRecordedSettings(){const y=p();return y?{...y}:null}}}const lN={"top-left":"top: 8px; left: 8px;","top-right":"top: 8px; right: 8px;","bottom-left":"bottom: 8px; left: 8px;","bottom-right":"bottom: 8px; right: 8px;"};function cN(n={}){const e=n.corner??"top-right",t=n.updateIntervalMs??500,i=()=>typeof n.mount=="function"?n.mount():n.mount??null;let s=null,a=null,r=null,o=0,l=performance.now(),c=0,u=0;const d=typeof n.onSample=="function";return{id:"fps-overlay",setup(h){if(l=performance.now(),o=0,u=h.player.getState().frameIndex,c=u,d)return;const f=i(),p=f!=null;s=document.createElement("div"),s.className="player-fps-overlay",s.style.cssText=p?` + `,transparent:!0,depthWrite:!1,blending:Ht});this.points=new sr(t,o),this.points.frustumCulled=!1,this.nextParticleIndex=0}setActive(e){this.active=e}emit(e,t,i,s=1){if(!this.active)return;const a=Math.floor(Math.random()*3)+3,r=Math.max(1,Math.round(a*s));for(let o=0;o=o.maxLife){o.active=!1,i[r]=0,s[r]=0;continue}t[r*3]+=o.velocity.x*e,t[r*3+1]+=o.velocity.y*e,t[r*3+2]+=o.velocity.z*e;const l=o.life/o.maxLife;i[r]=Math.pow(1-l,.5);const c=o.initialSize||3;s[r]=c*(1-l*.7),a[r*3]=1,a[r*3+1]=Math.max(.2,.9-l*.7),a[r*3+2]=Math.max(0,.4-l*.4),o.velocity.y+=20*e}this.geometry.attributes.position.needsUpdate=!0,this.geometry.attributes.alpha.needsUpdate=!0,this.geometry.attributes.size.needsUpdate=!0,this.geometry.attributes.color.needsUpdate=!0}addToScene(e){e.add(this.points)}removeFromScene(e){e.remove(this.points)}dispose(){this.geometry.dispose(),this.points.material.dispose()}}class bF{constructor(e,t,i,s){this.scene=e,this.team=t,this.trailWidth=i,this.trailLength=s,this.active=!0,this.dying=!1,this.deathTime=0,this.maxDeathTime=1.5,this.teamColors={0:new qe(.3,.6,1,.9),1:new qe(1,.5,.15,.9)},this.leftTarget=new Qe,this.rightTarget=new Qe,e.add(this.leftTarget),e.add(this.rightTarget),this.leftTrail=this.createTrail(this.leftTarget),this.rightTrail=this.createTrail(this.rightTarget),this.updateColors(),this.leftTrail.activate(),this.rightTrail.activate()}createTrail(e){const t=new pt(this.scene,!1),i=pt.createBaseMaterial();i.blending=Ht,i.depthWrite=!1,i.side=ct;const s=this.trailWidth,a=[new S(0,0,0),new S(0,s,0),new S(-s/2,s/2,0),new S(s/2,s/2,0)];return t.initialize(i,this.trailLength,!1,0,a,e),t.setAdvanceFrequency(60),t.mesh&&(t.mesh.frustumCulled=!1),t}updateColors(){const e=this.teamColors[this.team]||this.teamColors[0],t=new qe(e.x*.3,e.y*.3,e.z*.3,0);this.leftTrail?.material&&(this.leftTrail.material.uniforms.headColor.value.copy(e),this.leftTrail.material.uniforms.tailColor.value.copy(t)),this.rightTrail?.material&&(this.rightTrail.material.uniforms.headColor.value.copy(e),this.rightTrail.material.uniforms.tailColor.value.copy(t))}startDying(){this.dying||(this.dying=!0,this.deathTime=0,this.leftTrail.pause(),this.rightTrail.pause())}updatePosition(e,t,i){this.dying||(this.leftTarget.position.copy(e),this.rightTarget.position.copy(t),this.leftTarget.quaternion.copy(i),this.rightTarget.quaternion.copy(i),this.leftTarget.updateMatrixWorld(),this.rightTarget.updateMatrixWorld())}update(e){if(this.dying){this.deathTime+=e;const i=1-Math.min(1,this.deathTime/this.maxDeathTime),s=this.teamColors[this.team]||this.teamColors[0],a=new qe(s.x,s.y,s.z,s.w*i),r=new qe(s.x*.3,s.y*.3,s.z*.3,0);this.leftTrail?.material&&(this.leftTrail.material.uniforms.headColor.value.copy(a),this.leftTrail.material.uniforms.tailColor.value.copy(r)),this.rightTrail?.material&&(this.rightTrail.material.uniforms.headColor.value.copy(a),this.rightTrail.material.uniforms.tailColor.value.copy(r)),this.deathTime>=this.maxDeathTime&&(this.active=!1)}this.leftTrail.isActive&&this.leftTrail.update(e),this.rightTrail.isActive&&this.rightTrail.update(e)}dispose(){this.leftTrail.deactivate(),this.rightTrail.deactivate(),this.leftTrail.geometry&&this.leftTrail.geometry.dispose(),this.rightTrail.geometry&&this.rightTrail.geometry.dispose(),this.leftTrail.material&&this.leftTrail.material.dispose(),this.rightTrail.material&&this.rightTrail.material.dispose(),this.scene.remove(this.leftTarget),this.scene.remove(this.rightTarget)}}class xF{constructor(e,t=0){this.scene=e,this.team=t,this.active=!1,this.trailLength=80,this.trailWidth=15,this.arenaBounds={floor:0,ceiling:2044,wallX:4096,wallZ:5120},this.groundedThreshold=50,this.segments=[],this.currentSegment=null,this.wasGrounded=!0}setTeam(e){this.team!==e&&(this.team=e,this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.team=e,this.currentSegment.updateColors()))}setActive(e){e&&!this.active?(this.currentSegment=null,this.wasGrounded=!0):!e&&this.active&&this.currentSegment&&(this.currentSegment.startDying(),this.currentSegment=null),this.active=e}isGrounded(e){const t=this.groundedThreshold,i=this.arenaBounds;if(e.yi.ceiling-t)return{grounded:!0,surface:"ceiling",normal:new S(0,-1,0)};if(Math.abs(e.x)>i.wallX-t){const s=e.x>0?-1:1;return{grounded:!0,surface:"wall",normal:new S(s,0,0)}}if(Math.abs(e.z)>i.wallZ-t){const s=e.z>0?-1:1;return{grounded:!0,surface:"wall",normal:new S(0,0,s)}}return{grounded:!1,surface:null,normal:null}}emit(e,t,i){if(!this.active)return;const s=this.isGrounded(e);if(!s.grounded){this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.startDying(),this.currentSegment=null),this.wasGrounded=!1;return}(!this.wasGrounded||!this.currentSegment)&&(this.currentSegment&&!this.currentSegment.dying&&this.currentSegment.startDying(),this.currentSegment=new bF(this.scene,this.team,this.trailWidth,this.trailLength),this.segments.push(this.currentSegment)),this.wasGrounded=!0;const r=new S(-30,5,40),o=new S(-30,5,-40);r.applyQuaternion(t),o.applyQuaternion(t);const l=e.clone().add(r),c=e.clone().add(o),u=2;if(s.surface==="floor")l.y=u,c.y=u;else if(s.surface==="ceiling")l.y=this.arenaBounds.ceiling-u,c.y=this.arenaBounds.ceiling-u;else if(s.surface==="wall"){if(s.normal.x!==0){const d=s.normal.x>0?-this.arenaBounds.wallX+u:this.arenaBounds.wallX-u;l.x=d,c.x=d}else if(s.normal.z!==0){const d=s.normal.z>0?-this.arenaBounds.wallZ+u:this.arenaBounds.wallZ-u;l.z=d,c.z=d}}this.currentSegment.updatePosition(l,c,t)}update(e){for(let t=this.segments.length-1;t>=0;t--){const i=this.segments[t];i.update(e),i.active||(i.dispose(),this.segments.splice(t,1))}}addToScene(e){}removeFromScene(e){for(const t of this.segments)t.startDying();this.currentSegment=null}dispose(){for(const e of this.segments)e.dispose();this.segments=[],this.currentSegment=null}}class wF{constructor(e){this.scene=e,this.renderer=null,this.camera=null,this.explosions={active:[],goalEvents:new Map,demoEvents:new Map},this.boostTrails=new Map,this.supersonicTrails=new Map,this.ballTrail=null,hF()}setRenderContext(e,t){this.renderer=e,this.camera=t,pF(this.scene,e,t)}reset(){this.explosions.active.forEach(e=>e.removeFromScene(this.scene)),this.explosions.active=[],this.clearGoalExplosions(),this.boostTrails.forEach(e=>{e.removeFromScene(this.scene),e.dispose()}),this.boostTrails.clear(),this.supersonicTrails.forEach(e=>{e.removeFromScene(this.scene),e.dispose()}),this.supersonicTrails.clear(),this.ballTrail&&(this.ballTrail.removeFromScene(this.scene),this.ballTrail.dispose(),this.ballTrail=null)}clearEvents(){this.explosions.goalEvents.clear(),this.explosions.demoEvents.clear()}setGoalEvents(e){this.explosions.goalEvents.clear();for(const t of e??[])Number.isFinite(t.frame)&&this.explosions.goalEvents.set(t.frame,{time:t.time,team:t.team??0,playerName:t.playerName??""})}resetBallTrail(){this.ballTrail&&this.ballTrail.reset()}clearGoalExplosions(){Bn&&Bn.clearActive();for(const e of this.explosions.active)e.removeFromScene(this.scene);this.explosions.active=[]}createBoostTrail(e,t){if(this.boostTrails.has(t)){const s=this.boostTrails.get(t);s.removeFromScene(this.scene),s.dispose()}const i=new vF(e);return i.addToScene(this.scene),this.boostTrails.set(t,i),i}removeBoostTrail(e){const t=this.boostTrails.get(e);t&&(t.removeFromScene(this.scene),t.dispose(),this.boostTrails.delete(e))}updateBoostTrail(e,t,i,s,a){const r=this.boostTrails.get(e);r&&(r.setActive(t),t&&r.emit(i,s,a,this._playbackSpeed||1))}createSupersonicTrail(e,t){if(this.supersonicTrails.has(e)){const s=this.supersonicTrails.get(e);s.removeFromScene(this.scene),s.dispose()}const i=new xF(this.scene,t);return i.addToScene(this.scene),this.supersonicTrails.set(e,i),i}removeSupersonicTrail(e){const t=this.supersonicTrails.get(e);t&&(t.removeFromScene(this.scene),t.dispose(),this.supersonicTrails.delete(e))}updateSupersonicTrail(e,t,i,s,a,r){let o=this.supersonicTrails.get(e);!o&&t&&(o=this.createSupersonicTrail(e,r)),o&&(r!==void 0&&o.team!==r&&o.setTeam(r),o.setActive(t),t&&o.emit(i,s,a))}createBallTrail(){return this.ballTrail&&(this.ballTrail.removeFromScene(this.scene),this.ballTrail.dispose()),this.ballTrail=new dF(this.scene,0),this.ballTrail.addToScene(this.scene),console.log("✓ Spiral ball trail created and added to scene"),this.ballTrail}updateBallTrail(e,t,i){this.ballTrail||this.createBallTrail(),i!==void 0&&this.ballTrail.team!==i&&this.ballTrail.setTeam(i);const s=1/60*(this._playbackSpeed||1);this.ballTrail.emit(e,t,s)}triggerGoalExplosion(e,t){const i=kT(this.scene,this.renderer,this.camera);i&&(this.camera&&(i.camera=this.camera),i.trigger(e,t))}triggerDemoExplosion(e,t,i){const s=LT(this.scene);s&&s.trigger(e)}update(e,t=!0,i=1){this._playbackSpeed=i;const s=e*i;di&&di.update(s),Bn&&Bn.update(s);for(let a=this.explosions.active.length-1;a>=0;a--){const r=this.explosions.active[a];r.update(s)&&(r.removeFromScene(this.scene),this.explosions.active.splice(a,1))}t&&(this.boostTrails.forEach(a=>{a.update(s)}),this.supersonicTrails.forEach(a=>{a.update(s)}),this.ballTrail&&this.ballTrail.update(s))}}const dv={Octane:65535,Dominus:16746496,Plank:8978176,Breakout:16711816,Hybrid:8913151,Merc:16776960},SF={0:5744895,1:16751680};function TF(n,e){return e===0||e===1?SF[e]:dv[n]||dv.Octane}class MF{constructor(e){this.scene=e,this.hitboxes=new Map,this.enabled=!1}setEnabled(e){this.enabled=e,this.hitboxes.forEach(({mesh:t})=>{t.visible=e})}createHitboxWireframe(e,t){const i=py[e]||py.Octane,s=TF(e,t),a=i.length,r=i.width,o=i.height,l=i.offsetX,c=i.offsetZ;console.log(`[HitboxManager] Creating hitbox for ${e}:`,{dims:i,length:a,width:r,height:o,offsetX:l,offsetY:c});const u=new Mt,d=new Ci(a,o,r),h=new Ye({color:s,transparent:!0,opacity:.35,depthTest:!1,depthWrite:!1,side:ct}),f=new we(d,h);f.frustumCulled=!1,f.renderOrder=1,f.position.set(l,c,0),u.add(f);const p=new Wh(d),g=new Rt({color:s,linewidth:2,transparent:!0,opacity:.9,depthTest:!1}),_=new Ln(p,g);_.frustumCulled=!1,_.renderOrder=2,_.position.set(l,c,0),u.add(_);const m=3.33,v=new yn(m,8,6),y=new gg(v),b=new Rt({color:16777215,linewidth:1,transparent:!0,opacity:.9,depthTest:!1}),T=new Ln(y,b);return T.frustumCulled=!1,u.add(T),u.userData.hitboxType=e,u.userData.team=t??null,u.frustumCulled=!1,u}addHitbox(e,t,i){const s=i===0||i===1?i:null;if(this.hitboxes.has(e)){const r=this.hitboxes.get(e);if(r.hitboxType===t&&r.team===s)return;this.scene.remove(r.mesh),r.mesh.traverse(o=>{o.geometry&&o.geometry.dispose(),o.material&&o.material.dispose()})}const a=this.createHitboxWireframe(t,s);a.visible=this.enabled,this.scene.add(a),this.hitboxes.set(e,{mesh:a,hitboxType:t,team:s})}removeHitbox(e){if(this.hitboxes.has(e)){const{mesh:t}=this.hitboxes.get(e);this.scene.remove(t),t.traverse(i=>{i.geometry&&i.geometry.dispose(),i.material&&i.material.dispose()}),this.hitboxes.delete(e)}}updateHitboxes(e,t,i,s){if(!this.enabled)return;for(const[r,o]of Object.entries(t)){const l=e[o];if(!l||!l.userData.isCar)continue;const c=i?i(r):"Octane",u=s?s(r):null;this.addHitbox(o,c,u);const{mesh:d}=this.hitboxes.get(o);d.position.copy(l.position),d.quaternion.copy(l.quaternion),d.visible=this.enabled&&l.visible}const a=new Set(Object.values(t));for(const r of this.hitboxes.keys())a.has(r)||this.removeHitbox(r)}reset(){this.hitboxes.forEach(({mesh:e})=>{this.scene.remove(e),e.traverse(t=>{t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose()})}),this.hitboxes.clear()}dispose(){this.reset()}}const DT=["baseGroup","glowMesh","innerGlowMesh","lensColumnMesh","lensRimMesh","topGlowMesh","coreGlowMesh","highlightMesh"];function Sp(n,e,t,i){const s=new we(new Do(n,32),new Ye({color:e,transparent:!0,opacity:t,blending:Ht,side:ct,depthWrite:!1}));return s.rotation.x=-Math.PI/2,s.renderOrder=i,s}function hv(n,e){n&&n.traverse(t=>{const i=t;if(!i.isMesh||!(i.material instanceof Ye))return;const s=i.userData.baseOpacity;i.material.opacity=(s??i.material.opacity)*e})}function yu(n,e,t){n.rotation.x=-Math.PI/2,n.renderOrder=t,n.frustumCulled=!1,n.userData.baseOpacity=e,n.material.transparent=!0,n.material.opacity=e,n.material.side=ct,n.material.depthWrite=!1}function EF(n){const e=new Mt;e.renderOrder=98,e.frustumCulled=!1;const t=new Ye({color:1118477}),i=new Ye({color:16752640,blending:Ht}),s=new we(new Do(n*.55,48),t.clone());yu(s,.86,98),e.add(s);const a=new we(new ni(n*.45,n*.62,48),new Ye({color:16765242,blending:Ht}));yu(a,.78,100),a.position.y=1.4,e.add(a);function r(o,l,c){const u=new Ns;return[[o*Math.cos(-c*.72),o*Math.sin(-c*.72)],[l*Math.cos(-c),l*Math.sin(-c)],[l*Math.cos(c),l*Math.sin(c)],[o*Math.cos(c*.72),o*Math.sin(c*.72)]].forEach(([h,f],p)=>{p===0?u.moveTo(h,f):u.lineTo(h,f)}),u.closePath(),u}for(let o=0;o<3;o+=1){const l=o*(Math.PI*2)/3+Math.PI/2,c=new we(new dr(r(n*.52,n*1.42,.33)),t.clone());yu(c,.86,98),c.rotation.z=l,e.add(c);const u=new we(new dr(r(n*.66,n*1.2,.21)),i.clone());yu(u,.86,99),u.position.y=1.1,u.rotation.z=l,e.add(u)}return e}function fv(n,e){for(const t of DT){const i=n.userData[t];i&&(i.visible=e)}}function CF(){let n=new Map;function e(i){const s=i.player.adapter.boostPads;!s||s.size===0||(console.log(`[boost-pads] Creating ${s.size} boost pads...`),n=new Map,s.forEach((a,r)=>{const o=a.isBig;let l,c,u;if(o){l=new yn(37,24,18),c=new ii({color:16757274,emissive:16747008,emissiveIntensity:.42,metalness:.04,roughness:.08,clearcoat:1,clearcoatRoughness:.025,transmission:.18,thickness:30,ior:1.42,envMapIntensity:1.9,blending:Ht,transparent:!0,opacity:.68,depthWrite:!1}),u=new we(l,c),u.renderOrder=100;const p=EF(37*2.05);p.position.y=-140,u.add(p),u.userData.baseGroup=p;const g=new we(new cr(37*.12,37*.18,112,24,1,!0),new Ye({color:16761664,transparent:!0,opacity:.28,blending:Ht,side:ct,depthWrite:!1}));g.position.y=-62,g.renderOrder=99,u.add(g),u.userData.lensColumnMesh=g;const _=new we(new yn(37*1.03,24,14),new Ye({color:16768890,transparent:!0,opacity:.32,blending:Ht,side:un,depthWrite:!1}));_.renderOrder=101,u.add(_),u.userData.lensRimMesh=_;const m=new yn(37*1.3,20,14),v=new Ye({color:16758315,transparent:!0,opacity:.16,blending:Ht,side:un,depthWrite:!1}),y=new we(m,v);y.renderOrder=99,u.add(y),u.userData.glowMesh=y;const b=new yn(37*1.12,20,14),T=new Ye({color:16761130,transparent:!0,opacity:.22,blending:Ht,side:un,depthWrite:!1}),x=new we(b,T);x.renderOrder=99,u.add(x),u.userData.innerGlowMesh=x,u.userData.needsLight=!0}else{l=new cr(45,45*.92,8,32),c=new ii({color:16761370,emissive:16750336,emissiveIntensity:.72,metalness:.88,roughness:.14,clearcoat:1,clearcoatRoughness:.05,envMapIntensity:2,transparent:!0,opacity:1,depthWrite:!1}),u=new we(l,c),u.renderOrder=100;const g=Sp(45*1.42,16756736,.34,101);g.position.y=8/2+.15,u.add(g),u.userData.topGlowMesh=g;const _=Sp(45*.74,16777114,.42,102);_.position.y=8/2+.35,u.add(_),u.userData.coreGlowMesh=_;const m=Sp(45*.42,16775376,.46,103);m.position.set(-45*.18,8/2+.55,-45*.12),m.scale.y=.34,u.add(m),u.userData.highlightMesh=m}const h=o?130:10;if(u.position.set(a.position.x,h,a.position.y),u.userData.padId=r,u.userData.isBig=o,u.userData.isAvailable=!0,i.scene.add(u),n.set(r,u),u.userData.needsLight){const f=new hr(16751872,.7,480);f.decay=0,f.position.set(a.position.x,h-50,a.position.y),i.scene.add(f),u.userData.light=f}}),console.log(`[boost-pads] ✓ Created ${n.size} boost pad meshes`))}function t(i){i.player.adapter.boostPads.forEach((a,r)=>{const o=n.get(r);if(!o)return;const l=a.isAvailable;o.userData.isAvailable!==l&&(o.userData.isAvailable=l,l?(o.material.color.setHex(a.isBig?16757274:16761370),o.material.emissive.setHex(a.isBig?16747008:16750336),o.material.emissiveIntensity=a.isBig?.42:.72,o.material.opacity=a.isBig?.68:1,o.visible=!0,fv(o,!0),hv(o.userData.baseGroup,1),o.userData.light&&(o.userData.light.intensity=.85),o.userData.glowMesh&&(o.userData.glowMesh.visible=!0),o.userData.innerGlowMesh&&(o.userData.innerGlowMesh.visible=!0)):(o.material.color.setHex(a.isBig?9063424:9065472),o.material.emissive.setHex(0),o.material.emissiveIntensity=0,o.material.opacity=.2,o.visible=!0,fv(o,!1),o.userData.baseGroup&&(o.userData.baseGroup.visible=!0,hv(o.userData.baseGroup,.26)),o.userData.light&&(o.userData.light.intensity=0),o.userData.glowMesh&&(o.userData.glowMesh.visible=!1),o.userData.innerGlowMesh&&(o.userData.innerGlowMesh.visible=!1)))})}return{id:"boost-pads",setup(i){e(i)},beforeRender(i){t(i)},teardown(i){n.forEach(s=>{i.scene.remove(s),s.geometry.dispose(),s.material.dispose();for(const r of DT){const o=s.userData[r];o&&o.traverse(l=>{const c=l;c.isMesh&&(c.geometry.dispose(),c.material.dispose())})}const a=s.userData.light;a&&(i.scene.remove(a),a.dispose())}),n.clear()}}}const AF=2;function RF(n){if(n.frames.length===0)return null;const e=new Map;for(const s of n.frames)e.set(s.gameState,(e.get(s.gameState)??0)+1);let t=null,i=-1;for(const[s,a]of e.entries())a<=i||(t=s,i=a);return t}function PF(n,e){if(e===null)return null;for(const t of n.frames){if(t.gameState===e)break;return t.gameState}return null}function OT(n,e){return e===null?n.kickoffCountdown<=0:n.gameState===e}function Fg(n,e){return n.kickoffCountdown>0?!0:e!==null&&n.gameState===e}function IF(n,e){return n.ballFrames[e]?.position?!0:n.players.some(t=>t.frames[e]?.position)}function LF(n,e,t,i){return Fg(e,i)&&IF(n,t)}function kF(n,e){return n.timelineEvents.some(t=>t.kind==="goal"&&e.time>=t.time&&e.timec){const h=a.at(-1);h&&h.endTime>=c?h.endTime=Math.max(h.endTime,d):a.push({startTime:c,endTime:d})}o=u}return a}function OF(n,e,t){const i=vt.clamp(t,0,n);for(const s of e){if(i0&&(n.frames[s-1]?.kickoffCountdown??0)>0;)s-=1;let a=e+1;for(;a0;)a+=1;let r=0;for(let c=s;cl>s&&OT(o,t));return!r||r.time===e?null:r.time}function VF(n,e,t,i){const s=vh(n,e),a=n.frames[s];if(!a||!Yu(n,a,s,t,i))return null;const r=n.frames.find((c,u)=>u>s&&!Yu(n,c,u,t,i));if(r)return r.time===e?null:r.time;let o=s;for(;o>0&&Yu(n,n.frames[o-1],o-1,t,i);)o-=1;const l=n.frames[o]?.time;return l===void 0||l===e?null:l}function GF(n){return!!n?.position&&n?.isPresent!==!1}function $F(n,e,t){for(let i=n.length-1;i>=0;i-=1){const s=n[i],a=t-s.time;if(!(a<0)){if(a>zF)break;if(s.kind==="demo"&&s.secondaryPlayerId===e)return s}}return null}const WF="space",XF={space:{id:"space",skyboxUrl:"/skyboxes/PlanetaryEarth4k.hdr",exposure:1.45,rotation:{x:8,y:0,z:28},animation:{enabled:!0,speed:2}}};function KF(n){if(n===!1)return null;if(typeof n=="string"){const e=XF[n];return e||(console.warn(`[player] unknown environment "${n}"; using neutral default`),null)}return n}const qF=new Proxy({},{get:()=>()=>{}});function mv(n){if(!n)return null;const e={};for(const t of Object.keys(n)){const i=n[t];typeof i=="number"&&Number.isFinite(i)&&(e[t]=i)}return e}const _v=48,vu=.14,YF=16,jF=16,ZF=.003,JF=.05,QF=1.08,gv=4120,yv=5140,eN=0,tN=2200,nN=new S(0,700,0),iN=new S(-1,0,0),sN=new S(0,-1,0),aN=new S(0,900,0),rN=new S(0,1,0),oN=new S(9600,-5500,12600).normalize();function lN(n,e){const t=Number.isFinite(e)&&e>0?e:1.7777777777777777,i=n==="overhead"?nN.clone():aN.clone(),s=n==="overhead"?iN.clone():rN.clone(),a=n==="overhead"?sN.clone():oN.clone(),r=cN({aspect:t,fov:_v,forward:a,margin:QF,target:i,up:s});return{position:i.clone().addScaledVector(a,-r),target:i,up:s,fov:_v}}function cN(n){const{aspect:e,fov:t,forward:i,margin:s,target:a,up:r}=n,o=i.clone().normalize(),l=new S().crossVectors(o,r).normalize(),c=new S().crossVectors(l,o).normalize(),u=Math.tan(vt.degToRad(t)/2),d=u*e;let h=1;for(const f of[-gv,gv])for(const p of[eN,tN])for(const g of[-yv,yv]){const _=new S(f,p,g).sub(a),m=Math.abs(_.dot(l)),v=Math.abs(_.dot(c)),y=_.dot(o);h=Math.max(h,m/d-y,v/u-y)}return Math.max(1,h*s)}function uN(n){const e=new Mt;return e.name="replayRoot",e.matrixAutoUpdate=!1,e.matrix.set(1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1),n.add(e),e}class dN extends EventTarget{container;adapter;replay;options;sceneManager;arenaManager;actorManager;effectsManager;hitboxManager;controls;replayRoot;sceneState;effectsEnabled;ready;plugins=[];beforeRenderCallbacks=[];resizeObserver=null;animationFrameId=null;disposed=!1;playing=!1;readyResolved=!1;speed;loop;currentTime=0;lastTickAt=null;freeCameraTransition=null;cameraDistanceScaleValue;customCameraSettingsValue;cameraViewModeValue;attachedPlayerIdValue;ballCamEnabledValue;boostMeterEnabledValue;boostPickupAnimationEnabledValue;hitboxWireframesEnabledValue;hitboxOnlyModeEnabledValue;hitboxTypeByName=null;hitboxTeamByName=null;hitboxesActive=!1;skipPostGoalTransitionsEnabledValue;skipKickoffsEnabledValue;attachmentTouched=!1;liveGameState=null;kickoffGameState=null;timelineSegmentsCacheKey=null;timelineSegmentsCache=[];constructor(e,t,i={},s=null){super(),this.container=e,this.adapter=t,this.replay=s,this.options=i,this.updateReplayGameStates(),this.speed=Math.max(.1,i.initialPlaybackRate??i.speed??1),this.loop=i.loop??!1,this.cameraDistanceScaleValue=Math.max(.25,i.initialCameraDistanceScale??1),this.customCameraSettingsValue=mv(i.initialCustomCameraSettings),this.attachedPlayerIdValue=i.initialAttachedPlayerId??null,this.cameraViewModeValue=i.initialCameraViewMode??(this.attachedPlayerIdValue?"follow":"free"),this.ballCamEnabledValue=i.initialBallCamEnabled??null,this.boostMeterEnabledValue=i.initialBoostMeterEnabled??!1,this.boostPickupAnimationEnabledValue=i.initialBoostPickupAnimationEnabled??!0,this.hitboxWireframesEnabledValue=i.initialHitboxWireframesEnabled??!1,this.hitboxOnlyModeEnabledValue=i.initialHitboxOnlyModeEnabled??!1,this.skipPostGoalTransitionsEnabledValue=i.initialSkipPostGoalTransitionsEnabled??!0,this.skipKickoffsEnabledValue=i.initialSkipKickoffsEnabled??!1,this.sceneManager=new RD(e,{assetBase:i.assetBase,preserveDrawingBuffer:i.preserveDrawingBuffer}),this.sceneManager.initDefaultEnvironment(),this.applyEnvironmentSpec(i.environment??WF),this.arenaManager=new vO(this.scene,{assetBase:i.assetBase}),this.effectsEnabled=i.effects??!0,this.effectsManager=this.effectsEnabled?new wF(this.scene):qF,this.actorManager=new cF(this.scene,this.effectsManager,{assetBase:i.assetBase}),i.motionInterpolation&&this.setMotionInterpolation(i.motionInterpolation),this.actorManager.initFromFramework(t),this.actorManager.initInterpolants(t.getTimelines()),this.hitboxManager=new MF(this.scene),this.syncGoalEvents(),this.controls=new uD(this.camera,this.renderer.domElement),this.controls.zoomSpeed=2.5,this.camera.position.set(0,4e3,6e3),this.controls.target.set(0,200,0),this.controls.update(),this.replayRoot=uN(this.scene),this.sceneState=this.createSceneState(),this.ready=Promise.all([this.arenaManager.loadArenaMeshes().catch(a=>{console.warn("[player] arena load failed",a)}),this.prepareReplayAssets()]).then(()=>{this.markReady()}),this.installResizeHandling();for(const a of i.plugins??[])this.installPlugin(a,!1);this.plugins.some(a=>a.plugin.id==="boost-pads")||this.installPlugin(CF(),!1),this.applyInitialCameraOptions(),this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded(),this.scheduleAnimationFrame(),this.emitChange(),i.autoplay&&this.play()}get scene(){return this.sceneManager.scene}get camera(){return this.sceneManager.camera}get renderer(){return this.sceneManager.renderer}get duration(){return this.adapter.duration}async replaceReplay(e,t,i={}){if(this.disposed)throw new Error("Cannot replace replay on a disposed ReplayPlayer");const s=i.preservePlayback??this.playing;this.playing&&this.setPlayingInternal(!1),this.teardownPlugins(),this.effectsManager.reset(),this.effectsManager.clearEvents?.(),this.hitboxManager.reset(),this.actorManager.reset(),this.adapter=e,this.replay=t,this.updateReplayGameStates(),this.timelineSegmentsCacheKey=null,this.timelineSegmentsCache=[],this.hitboxTypeByName=null,this.hitboxTeamByName=null,this.hitboxesActive=!1,this.freeCameraTransition=null,this.actorManager.initFromFramework(e),this.actorManager.initInterpolants(e.getTimelines()),this.syncGoalEvents();const a=this.attachedPlayerIdValue&&this.adapter.playerList.some(r=>r.id===this.attachedPlayerIdValue)?this.attachedPlayerIdValue:null;a!==this.attachedPlayerIdValue&&(this.attachedPlayerIdValue=a,this.cameraViewModeValue==="follow"&&(this.cameraViewModeValue="free")),this.seekInternal(i.currentTime??0),this.readyResolved=!1,this.ready=this.prepareReplayAssets().then(()=>{this.markReady()}),await this.ready,this.setupPlugins(),this.applyInitialCameraOptions(),this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded(),s&&this.setPlayingInternal(!0),this.render(),this.emitChange()}setEnvironment(e){this.applyEnvironmentSpec(e)}applyEnvironmentSpec(e){const t=KF(e);if(!t){this.sceneManager.setDefaultBackground();return}this.sceneManager.applyEnvironment(t).catch(i=>{console.warn(`[player] environment "${t.id}" failed to load`,i)})}play(){this.playing||(this.setPlayingInternal(!0),this.emitChange())}pause(){this.playing&&(this.setPlayingInternal(!1),this.emitChange())}togglePlayback(){this.playing?this.pause():this.play()}seek(e){this.seekInternal(e),this.playing&&(this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded()),this.emitChange()}setPlaybackRate(e){this.speed=Math.max(.1,e),this.emitChange()}setLoop(e){this.loop=e}setMotionInterpolation(e){this.actorManager.interpolationMethod=e==="linear"?"lerp":"hermite"}setFrameIndex(e){const t=this.adapter.frameTimes;if(t.length===0||!Number.isFinite(e))return;const i=Math.min(Math.max(Math.trunc(e),0),t.length-1);this.playing&&this.setPlayingInternal(!1),this.seekInternal(t[i]),this.emitChange()}stepFrames(e){Number.isFinite(e)&&this.setFrameIndex(this.adapter.frameIndexAt(this.currentTime)+Math.trunc(e))}stepForwardFrame(){this.stepFrames(1)}stepBackwardFrame(){this.stepFrames(-1)}setCameraDistanceScale(e){this.cameraDistanceScaleValue=Math.max(.25,e),this.getCameraPlugin()?.setDistanceScale(this.cameraDistanceScaleValue),this.emitChange()}setCustomCameraSettings(e){this.applyCustomCameraSettings(e),this.emitChange()}setAttachedPlayer(e){this.attachedPlayerIdValue=e,this.cameraViewModeValue=e?"follow":"free",this.attachmentTouched=!0,this.freeCameraTransition=null,this.syncCameraAttachment(),this.emitChange()}setCameraViewMode(e){this.cameraViewModeValue=e,this.attachmentTouched=!0,this.freeCameraTransition=null,this.syncCameraAttachment(),this.emitChange()}setFreeCameraPreset(e,t={}){this.cameraViewModeValue="free",this.attachmentTouched=!0,this.syncCameraAttachment();const i=lN(e,this.camera.aspect);t.instant?(this.camera.position.copy(i.position),this.controls.target.copy(i.target),this.camera.up.copy(i.up).normalize(),this.camera.fov=i.fov,this.camera.updateProjectionMatrix(),this.camera.lookAt(i.target),this.controls.enabled=!0,this.freeCameraTransition=null):this.freeCameraTransition=i,this.emitChange()}setBallCamEnabled(e){this.ballCamEnabledValue=e,this.getCameraPlugin()?.setBallCam(e),this.emitChange()}setBoostMeterEnabled(e){this.boostMeterEnabledValue=e,this.emitChange()}setBoostPickupAnimationEnabled(e){this.boostPickupAnimationEnabledValue=e,this.emitChange()}setHitboxWireframesEnabled(e){this.hitboxWireframesEnabledValue=e,this.emitChange()}setHitboxOnlyModeEnabled(e){this.hitboxOnlyModeEnabledValue=e,this.emitChange()}setSkipPostGoalTransitionsEnabled(e){this.skipPostGoalTransitionsEnabledValue=e,e&&this.playing&&this.skipPostGoalTransitionIfNeeded(),this.emitChange()}setSkipKickoffsEnabled(e){this.skipKickoffsEnabledValue=e,e&&this.playing&&(this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded()),this.emitChange()}setState(e){e.speed!==void 0&&(this.speed=Math.max(.1,e.speed)),e.cameraDistanceScale!==void 0&&(this.cameraDistanceScaleValue=Math.max(.25,e.cameraDistanceScale),this.getCameraPlugin()?.setDistanceScale(this.cameraDistanceScaleValue)),e.customCameraSettings!==void 0&&this.applyCustomCameraSettings(e.customCameraSettings),e.cameraViewMode!==void 0&&(this.cameraViewModeValue=e.cameraViewMode,this.attachmentTouched=!0),e.attachedPlayerId!==void 0&&(this.attachedPlayerIdValue=e.attachedPlayerId,this.attachmentTouched=!0,e.cameraViewMode===void 0&&(this.cameraViewModeValue=e.attachedPlayerId?"follow":"free")),(e.cameraViewMode!==void 0||e.attachedPlayerId!==void 0)&&(this.freeCameraTransition=null,this.syncCameraAttachment()),e.useReplayBallCam===!0?(this.ballCamEnabledValue=null,this.getCameraPlugin()?.setBallCam(null)):e.ballCamEnabled!==void 0&&(this.ballCamEnabledValue=e.ballCamEnabled,this.getCameraPlugin()?.setBallCam(e.ballCamEnabled)),e.boostMeterEnabled!==void 0&&(this.boostMeterEnabledValue=e.boostMeterEnabled),e.boostPickupAnimationEnabled!==void 0&&(this.boostPickupAnimationEnabledValue=e.boostPickupAnimationEnabled),e.hitboxWireframesEnabled!==void 0&&(this.hitboxWireframesEnabledValue=e.hitboxWireframesEnabled),e.hitboxOnlyModeEnabled!==void 0&&(this.hitboxOnlyModeEnabledValue=e.hitboxOnlyModeEnabled),e.skipPostGoalTransitionsEnabled!==void 0&&(this.skipPostGoalTransitionsEnabledValue=e.skipPostGoalTransitionsEnabled),e.skipKickoffsEnabled!==void 0&&(this.skipKickoffsEnabledValue=e.skipKickoffsEnabled),e.currentTime!==void 0&&this.seekInternal(e.currentTime),e.playing!==void 0&&e.playing!==this.playing&&this.setPlayingInternal(e.playing),this.playing&&(e.currentTime!==void 0||e.playing!==void 0)&&(this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded()),this.emitChange()}getState(){const e=this.adapter.frameIndexAt(this.currentTime),t=this.getCameraPlugin();let i=this.cameraViewModeValue,s=this.attachedPlayerIdValue;if(t)if(t.getMode()==="follow"){i="follow";const a=t.getTarget();s=(a?this.adapter.playerList.find(o=>o.name===a):void 0)?.id??s}else i="free",s=null;return{currentTime:this.currentTime,duration:this.duration,frameIndex:e,activeMetadata:this.replay?UF(this.replay,e,this.currentTime):null,playing:this.playing,speed:this.speed,cameraDistanceScale:this.cameraDistanceScaleValue,customCameraSettings:this.customCameraSettingsValue,cameraViewMode:i,attachedPlayerId:s,ballCamEnabled:t?t.getBallCam():this.ballCamEnabledValue??!1,useReplayBallCam:this.ballCamEnabledValue===null,effectiveBallCamEnabled:t?t.getBallCam():this.ballCamEnabledValue??!1,boostMeterEnabled:this.boostMeterEnabledValue,boostPickupAnimationEnabled:this.boostPickupAnimationEnabledValue,hitboxWireframesEnabled:this.hitboxWireframesEnabledValue,hitboxOnlyModeEnabled:this.hitboxOnlyModeEnabledValue,skipPostGoalTransitionsEnabled:this.skipPostGoalTransitionsEnabledValue,skipKickoffsEnabled:this.skipKickoffsEnabledValue}}getSnapshot(){return this.getState()}getTimelineDuration(){return this.replay?.duration??this.duration}getTimelineCurrentTime(){return this.projectReplayTimeToTimeline(this.currentTime).timelineTime}getTimelineSegments(){if(!this.replay)return[];const e=`${this.skipPostGoalTransitionsEnabledValue}:${this.skipKickoffsEnabledValue}`;return this.timelineSegmentsCacheKey===e?this.timelineSegmentsCache:(this.timelineSegmentsCacheKey=e,this.timelineSegmentsCache=DF(this.replay,this.skipPostGoalTransitionsEnabledValue,this.skipKickoffsEnabledValue,this.liveGameState,this.kickoffGameState),this.timelineSegmentsCache)}projectReplayTimeToTimeline(e){return OF(this.replay?.duration??this.duration,this.getTimelineSegments(),e)}projectTimelineTimeToReplay(e){return FF(this.replay?.duration??this.duration,this.getTimelineDuration(),this.getTimelineSegments(),e)}subscribe(e){const t=i=>{e(i.detail)};return this.addEventListener("change",t),e(this.getState()),()=>{this.removeEventListener("change",t)}}onBeforeRender(e){return this.beforeRenderCallbacks.push(e),()=>{const t=this.beforeRenderCallbacks.indexOf(e);t>=0&&this.beforeRenderCallbacks.splice(t,1)}}addPlugin(e){return this.installPlugin(e,!0)}removePlugin(e){const t=this.plugins.findIndex(s=>s.plugin.id===e);if(t<0)return!1;const[i]=this.plugins.splice(t,1);return i.plugin.teardown?.(this.createPluginContext()),!0}getPlugins(){return this.plugins.map(e=>e.plugin)}destroy(){if(!this.disposed){for(this.disposed=!0,this.playing=!1,this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.beforeRenderCallbacks.length=0;this.plugins.length>0;)this.plugins.pop()?.plugin.teardown?.(this.createPluginContext());this.controls.dispose(),this.effectsEnabled&&this.effectsManager.reset(),this.hitboxManager.dispose(),this.actorManager.reset(),this.sceneManager.dispose()}}dispose(){this.destroy()}setPlayingInternal(e){this.playing=e,this.lastTickAt=null,e?this.actorManager.resumeAnimations():this.actorManager.pauseAnimations()}prepareReplayAssets(){return this.actorManager.waitForBallModel().catch(()=>!1).then(()=>{if(this.effectsEnabled)try{this.effectsManager.setRenderContext(this.renderer,this.camera)}catch(e){console.warn("[player] explosion warmup failed",e)}})}markReady(){this.readyResolved=!0,this.lastTickAt=null}updateReplayGameStates(){if(!this.replay){this.liveGameState=null,this.kickoffGameState=null;return}this.liveGameState=RF(this.replay),this.kickoffGameState=PF(this.replay,this.liveGameState)}syncGoalEvents(){this.effectsEnabled&&(this.effectsManager.clearEvents?.(),this.replay&&this.effectsManager.setGoalEvents(this.replay.timelineEvents.filter(e=>e.kind==="goal").map(e=>({frame:e.frame,time:e.time,team:e.isTeamZero?0:1,playerName:e.playerName??""}))))}teardownPlugins(){const e=this.createPluginContext();for(const t of this.plugins)t.plugin.teardown?.(e)}setupPlugins(){for(const e of this.plugins)e.plugin.setup?.(this.createPluginContext()),e.plugin.id==="camera"&&this.pushCameraParityState(),e.plugin.onStateChange?.(this.createPluginStateContext(this.getState()))}seekInternal(e){this.currentTime=vt.clamp(e,0,this.duration),this.actorManager.seekAnimations(this.currentTime),this.effectsManager.resetBallTrail(),this.effectsManager.clearGoalExplosions?.(),this.actorManager.resetGoalExplosionPlaybackState(),this.actorManager.resetWheelTracking()}getPlaybackEndTime(){return this.replay?NF(this.replay.duration,this.getTimelineSegments()):this.duration}skipPastKickoffIfNeeded(){if(!this.replay||!this.skipKickoffsEnabledValue)return!1;const e=HF(this.replay,this.currentTime,this.liveGameState,this.kickoffGameState);return e===null?!1:(this.seekInternal(e),!0)}skipPostGoalTransitionIfNeeded(){if(!this.replay||!this.skipPostGoalTransitionsEnabledValue)return!1;const e=VF(this.replay,this.currentTime,this.liveGameState,this.kickoffGameState);return e===null?!1:(this.seekInternal(e),!0)}getCameraPlugin(){const e=this.plugins.find(t=>t.plugin.id==="camera")?.plugin;return e&&typeof e.follow=="function"?e:null}playerNameForId(e){return this.adapter.playerList.find(t=>t.id===e)?.name??null}applyReplayBallCam(){if(this.ballCamEnabledValue!==null||this.cameraViewModeValue!=="follow"||!this.attachedPlayerIdValue)return;const e=this.playerNameForId(this.attachedPlayerIdValue);if(!e)return;const t=this.adapter.getAllPlayers().find(i=>i.name===e);t&&this.getCameraPlugin()?.setBallCam(t.isBallCam)}syncCameraAttachment(){const e=this.getCameraPlugin();if(e){if(this.cameraViewModeValue==="follow"&&this.attachedPlayerIdValue){const t=this.playerNameForId(this.attachedPlayerIdValue);if(!t){console.warn(`[player] no player with id ${JSON.stringify(this.attachedPlayerIdValue)}`);return}this.camera.up.set(0,1,0),e.follow(t);return}e.getMode()==="follow"&&e.release()}}applyCustomCameraSettings(e){this.customCameraSettingsValue=mv(e);const t=this.getCameraPlugin();t&&(t.setCameraSettings(null),this.customCameraSettingsValue&&t.setCameraSettings(this.customCameraSettingsValue))}pushCameraParityState(){const e=this.getCameraPlugin();e&&(this.cameraDistanceScaleValue!==1&&e.setDistanceScale(this.cameraDistanceScaleValue),this.customCameraSettingsValue&&e.setCameraSettings(this.customCameraSettingsValue),this.ballCamEnabledValue!==null&&e.setBallCam(this.ballCamEnabledValue),this.attachmentTouched&&this.syncCameraAttachment())}applyInitialCameraOptions(){const e=this.options;(e.initialAttachedPlayerId!==void 0||e.initialCameraViewMode!==void 0)&&(this.attachmentTouched=!0),this.pushCameraParityState()}computeFrameRenderInfo(){const e=this.adapter.frameTimes,t=this.adapter.frameIndexAt(this.currentTime),i=Math.min(t+1,Math.max(e.length-1,0)),s=e[t]??0,a=e[i]??s,r=a>s?vt.clamp((this.currentTime-s)/(a-s),0,1):0;return{frameIndex:t,nextFrameIndex:i,alpha:r,currentTime:this.currentTime}}installResizeHandling(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>this.sceneManager.onWindowResize()),this.resizeObserver.observe(this.container))}scheduleAnimationFrame(){this.animationFrameId!==null||this.disposed||(this.animationFrameId=requestAnimationFrame(this.tick))}tick=e=>{if(this.animationFrameId=null,this.disposed)return;let t=!1,i=0;if(this.playing&&this.readyResolved){i=this.lastTickAt===null?0:Math.min(.1,(e-this.lastTickAt)/1e3),this.lastTickAt=e;let s=this.currentTime+i*this.speed;const a=this.getPlaybackEndTime();s>=a&&(this.loop?(s=0,this.actorManager.seekAnimations(0),this.effectsManager.resetBallTrail(),this.effectsManager.clearGoalExplosions?.(),this.actorManager.resetGoalExplosionPlaybackState(),this.actorManager.resetWheelTracking()):(s=a,this.playing=!1)),t=s!==this.currentTime||!this.playing,this.currentTime=s,this.playing&&(t=this.skipPostGoalTransitionIfNeeded()||t,t=this.skipPastKickoffIfNeeded()||t)}else this.playing&&(this.lastTickAt=null);this.render(i),t&&this.emitChange(),this.scheduleAnimationFrame()};renderFrame(e=0){if(this.adapter.seek(this.currentTime),this.playing&&this.actorManager.updateAnimations(e*this.speed),this.actorManager.updateFromFramework(this.adapter,this.currentTime),this.updatePlayerStates(),this.applyReplayBallCam(),this.updateHitboxVisualization(),this.effectsManager.update(e,this.playing,this.speed),this.playing&&this.actorManager.updateWheelRotations(),this.sceneManager.updateSkyboxAnimation(this.playing?e*this.speed:0),this.controls.update(),this.beforeRenderCallbacks.length>0){const t=this.computeFrameRenderInfo();for(const i of[...this.beforeRenderCallbacks])i(t)}if(this.plugins.length>0){const t=this.createRenderContext();for(const i of this.plugins)i.plugin.beforeRender?.(t)}this.updateFreeCameraTransition(),this.renderer.render(this.scene,this.camera)}render(e=0){this.renderFrame(e)}updateFreeCameraTransition(){const e=this.freeCameraTransition;if(!e)return;this.controls.enabled=!1,this.camera.position.lerp(e.position,vu),this.controls.target.lerp(e.target,vu),this.camera.up.lerp(e.up,vu).normalize(),this.camera.fov=vt.lerp(this.camera.fov,e.fov,vu),this.camera.updateProjectionMatrix(),this.camera.lookAt(this.controls.target);const t=this.camera.position.distanceToSquared(e.position)<=YF,i=this.controls.target.distanceToSquared(e.target)<=jF,s=this.camera.up.angleTo(e.up)<=ZF,a=Math.abs(this.camera.fov-e.fov)<=JF;!t||!i||!s||!a||(this.camera.position.copy(e.position),this.controls.target.copy(e.target),this.camera.up.copy(e.up).normalize(),this.camera.fov=e.fov,this.camera.updateProjectionMatrix(),this.camera.lookAt(e.target),this.controls.enabled=!0,this.freeCameraTransition=null)}updatePlayerStates(){if(!this.playing)return;const e=this.hitboxOnlyModeEnabledValue;for(const t of this.adapter.getAllPlayers())this.actorManager.updateBoostState(t.name,t.isBoosting&&!e,t.isKickoffReset),this.actorManager.updateSupersonicState(t.name,t.isSupersonic&&!e,t.team)}updateHitboxVisualization(){const e=this.hitboxWireframesEnabledValue||this.hitboxOnlyModeEnabledValue;if(!e&&!this.hitboxesActive||(this.hitboxesActive=e,this.hitboxManager.setEnabled(e),!e))return;const t=this.actorManager;if(this.hitboxTypeByName||(this.hitboxTypeByName=new Map(this.adapter.getAllPlayers().map(i=>[i.name,i.hitboxType]))),this.hitboxTeamByName||(this.hitboxTeamByName=new Map(this.adapter.getAllPlayers().map(i=>[i.name,i.team]))),this.hitboxManager.updateHitboxes(t.actors,t.playerNameToCarActorId,i=>this.hitboxTypeByName?.get(i)??"Octane",i=>this.hitboxTeamByName?.get(i)??null),this.hitboxOnlyModeEnabledValue)for(const i of Object.values(t.playerNameToCarActorId)){const s=i===void 0?void 0:t.actors[i];s&&(s.visible=!1)}}installPlugin(e,t){const i=typeof e=="function"?e():e;if(this.plugins.some(a=>a.plugin.id===i.id))throw new Error(`Player plugin "${i.id}" is already installed`);const s={definition:e,plugin:i};return this.plugins.push(s),i.setup?.(this.createPluginContext()),i.id==="camera"&&this.pushCameraParityState(),i.onStateChange?.(this.createPluginStateContext(this.getState())),t&&this.render(),()=>{const a=this.plugins.indexOf(s);a<0||(this.plugins.splice(a,1),i.teardown?.(this.createPluginContext()))}}createSceneState(){const e=this.actorManager,t=this,i=new we;return{get scene(){return t.scene},replayRoot:this.replayRoot,get camera(){return t.camera},get renderer(){return t.renderer},controls:this.controls,resize:()=>this.sceneManager.onWindowResize(),dispose:()=>this.destroy(),get ballMesh(){return(e.ballActorId!=null?e.actors[e.ballActorId]:null)??i},get playerMeshes(){const s=new Map;for(const a of t.adapter.playerList){const r=e.playerNameToCarActorId[a.name],o=r!=null?e.actors[r]:void 0;o&&s.set(a.id,o)}return s},playerBodyMeshes:new Map,playerHitboxes:new Map,playerBoostTrails:new Map,playerBoostMeters:new Map,playerDemoIndicators:new Map,updateWallVisibility:()=>{}}}createPluginContext(){return{player:this,replay:this.replay,options:this.options,scene:this.scene,camera:this.camera,renderer:this.renderer,container:this.container}}createPluginStateContext(e){return{...this.createPluginContext(),state:e}}createRenderContext(){const e=this.actorManager,t=this.adapter.ball,i={position:t.position,rotation:t.rotation,velocity:t.velocity,visible:t.visible,object3d:e.ballActorId!=null?e.actors[e.ballActorId]??null:null},s=this.adapter.getAllPlayers().map(a=>{const r=e.playerNameToCarActorId[a.name];return{id:a.id,name:a.name,team:a.team,carName:a.carName,hitboxType:a.hitboxType,position:a.position,rotation:a.rotation,velocity:a.velocity,boost:a.boost,isBoosting:a.isBoosting,visible:a.isVisible,object3d:r!=null?e.actors[r]??null:null}});return{...this.createPluginContext(),...this.computeFrameRenderInfo(),state:this.getState(),time:this.currentTime,ball:i,cars:s}}emitChange(){const e=this.getState(),t=this.createPluginStateContext(e);for(const i of this.plugins)i.plugin.onStateChange?.(t);this.dispatchEvent(new CustomEvent("change",{detail:e}))}}const Wt={LEFT:1,RIGHT:2,MIDDLE:4},$=Object.freeze({NONE:0,ROTATE:1,TRUCK:2,SCREEN_PAN:4,OFFSET:8,DOLLY:16,ZOOM:32,TOUCH_ROTATE:64,TOUCH_TRUCK:128,TOUCH_SCREEN_PAN:256,TOUCH_OFFSET:512,TOUCH_DOLLY:1024,TOUCH_ZOOM:2048,TOUCH_DOLLY_TRUCK:4096,TOUCH_DOLLY_SCREEN_PAN:8192,TOUCH_DOLLY_OFFSET:16384,TOUCH_DOLLY_ROTATE:32768,TOUCH_ZOOM_TRUCK:65536,TOUCH_ZOOM_OFFSET:131072,TOUCH_ZOOM_SCREEN_PAN:262144,TOUCH_ZOOM_ROTATE:524288}),Vr={NONE:0,IN:1,OUT:-1};function ka(n){return n.isPerspectiveCamera}function Js(n){return n.isOrthographicCamera}const Gr=Math.PI*2,vv=Math.PI/2,NT=1e-5,nl=Math.PI/180;function Ui(n,e,t){return Math.max(e,Math.min(t,n))}function Ot(n,e=NT){return Math.abs(n)0==f>u&&(f=u,t.value=(f-u)/a),f}function xv(n,e,t,i,s=1/0,a,r){i=Math.max(1e-4,i);const o=2/i,l=o*a,c=1/(1+l+.48*l*l+.235*l*l*l);let u=e.x,d=e.y,h=e.z,f=n.x-u,p=n.y-d,g=n.z-h;const _=u,m=d,v=h,y=s*i,b=y*y,T=f*f+p*p+g*g;if(T>b){const U=Math.sqrt(T);f=f/U*y,p=p/U*y,g=g/U*y}u=n.x-f,d=n.y-p,h=n.z-g;const x=(t.x+o*f)*a,M=(t.y+o*p)*a,C=(t.z+o*g)*a;t.x=(t.x-o*x)*c,t.y=(t.y-o*M)*c,t.z=(t.z-o*C)*c,r.x=u+(f+x)*c,r.y=d+(p+M)*c,r.z=h+(g+C)*c;const w=_-n.x,E=m-n.y,R=v-n.z,k=r.x-_,O=r.y-m,D=r.z-v;return w*k+E*O+R*D>0&&(r.x=_,r.y=m,r.z=v,t.x=(r.x-_)/a,t.y=(r.y-m)/a,t.z=(r.z-v)/a),r}function Tp(n,e){e.set(0,0),n.forEach(t=>{e.x+=t.clientX,e.y+=t.clientY}),e.x/=n.length,e.y/=n.length}function Mp(n,e){return Js(n)?(console.warn(`${e} is not supported in OrthographicCamera`),!0):!1}class hN{constructor(){this._listeners={}}addEventListener(e,t){const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){const i=this._listeners;return i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){const s=this._listeners[e];if(s!==void 0){const a=s.indexOf(t);a!==-1&&s.splice(a,1)}}removeAllEventListeners(e){if(!e){this._listeners={};return}Array.isArray(this._listeners[e])&&(this._listeners[e].length=0)}dispatchEvent(e){const i=this._listeners[e.type];if(i!==void 0){e.target=this;const s=i.slice(0);for(let a=0,r=s.length;a{},this._enabled=!0,this._state=$.NONE,this._viewport=null,this._changedDolly=0,this._changedZoom=0,this._hasRested=!0,this._boundaryEnclosesCamera=!1,this._needsUpdate=!0,this._updatedLastTime=!1,this._elementRect=new DOMRect,this._isDragging=!1,this._dragNeedsUpdate=!0,this._activePointers=[],this._lockedPointer=null,this._interactiveArea=new DOMRect(0,0,1,1),this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._isUserControllingOffset=!1,this._isUserControllingZoom=!1,this._lastDollyDirection=Vr.NONE,this._thetaVelocity={value:0},this._phiVelocity={value:0},this._radiusVelocity={value:0},this._targetVelocity=new tt.Vector3,this._focalOffsetVelocity=new tt.Vector3,this._zoomVelocity={value:0},this._truckInternal=(m,v,y,b)=>{let T,x;if(ka(this._camera)){const M=ft.copy(this._camera.position).sub(this._target),C=this._camera.getEffectiveFOV()*nl,w=M.length()*Math.tan(C*.5);T=this.truckSpeed*m*w/this._elementRect.height,x=this.truckSpeed*v*w/this._elementRect.height}else if(Js(this._camera)){const M=this._camera;T=this.truckSpeed*m*(M.right-M.left)/M.zoom/this._elementRect.width,x=this.truckSpeed*v*(M.top-M.bottom)/M.zoom/this._elementRect.height}else return;b?(y?this.setFocalOffset(this._focalOffsetEnd.x+T,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(T,0,!0),this.forward(-x,!0)):y?this.setFocalOffset(this._focalOffsetEnd.x+T,this._focalOffsetEnd.y+x,this._focalOffsetEnd.z,!0):this.truck(T,x,!0)},this._rotateInternal=(m,v)=>{const y=Gr*this.azimuthRotateSpeed*m/this._elementRect.height,b=Gr*this.polarRotateSpeed*v/this._elementRect.height;this.rotate(y,b,!0)},this._dollyInternal=(m,v,y)=>{const b=Math.pow(.95,-m*this.dollySpeed),T=this._sphericalEnd.radius,x=this._sphericalEnd.radius*b,M=Ui(x,this.minDistance,this.maxDistance),C=M-x;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(x,!0):this.infinityDolly&&!this.dollyToCursor?(this.dollyInFixed(C,!0),this._dollyToNoClamp(M,!0)):this._dollyToNoClamp(M,!0),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?x:M)-T,this._dollyControlCoord.set(v,y)),this._lastDollyDirection=Math.sign(-m)},this._zoomInternal=(m,v,y)=>{const b=Math.pow(.95,m*this.dollySpeed),T=this._zoom,x=this._zoom*b;this.zoomTo(x,!0),this.dollyToCursor&&(this._changedZoom+=x-T,this._dollyControlCoord.set(v,y))},typeof tt>"u"&&console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information."),this._camera=e,this._yAxisUpSpace=new tt.Quaternion().setFromUnitVectors(this._camera.up,wu),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=$.NONE,this._target=new tt.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new tt.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=new tt.Spherical().setFromVector3(ft.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace)),this._sphericalEnd=this._spherical.clone(),this._lastDistance=this._spherical.radius,this._zoom=this._camera.zoom,this._zoomEnd=this._zoom,this._lastZoom=this._zoom,this._nearPlaneCorners=[new tt.Vector3,new tt.Vector3,new tt.Vector3,new tt.Vector3],this._updateNearPlaneCorners(),this._boundary=new tt.Box3(new tt.Vector3(-1/0,-1/0,-1/0),new tt.Vector3(1/0,1/0,1/0)),this._cameraUp0=this._camera.up.clone(),this._target0=this._target.clone(),this._position0=this._camera.position.clone(),this._zoom0=this._zoom,this._focalOffset0=this._focalOffset.clone(),this._dollyControlCoord=new tt.Vector2,this.mouseButtons={left:$.ROTATE,middle:$.DOLLY,right:$.TRUCK,wheel:ka(this._camera)?$.DOLLY:Js(this._camera)?$.ZOOM:$.NONE},this.touches={one:$.TOUCH_ROTATE,two:ka(this._camera)?$.TOUCH_DOLLY_TRUCK:Js(this._camera)?$.TOUCH_ZOOM_TRUCK:$.NONE,three:$.TOUCH_TRUCK};const i=new tt.Vector2,s=new tt.Vector2,a=new tt.Vector2,r=m=>{if(!this._enabled||!this._domElement)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const b=this._domElement.getBoundingClientRect(),T=m.clientX/b.width,x=m.clientY/b.height;if(Tthis._interactiveArea.right||xthis._interactiveArea.bottom)return}const v=m.pointerType!=="mouse"?null:(m.buttons&Wt.LEFT)===Wt.LEFT?Wt.LEFT:(m.buttons&Wt.MIDDLE)===Wt.MIDDLE?Wt.MIDDLE:(m.buttons&Wt.RIGHT)===Wt.RIGHT?Wt.RIGHT:null;if(v!==null){const b=this._findPointerByMouseButton(v);b&&this._disposePointer(b)}if((m.buttons&Wt.LEFT)===Wt.LEFT&&this._lockedPointer)return;const y={pointerId:m.pointerId,clientX:m.clientX,clientY:m.clientY,deltaX:0,deltaY:0,mouseButton:v};this._activePointers.push(y),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),this._isDragging=!0,h(m)},o=m=>{m.cancelable&&m.preventDefault();const v=m.pointerId,y=this._lockedPointer||this._findPointerById(v);if(y){if(y.clientX=m.clientX,y.clientY=m.clientY,y.deltaX=m.movementX,y.deltaY=m.movementY,this._state=0,m.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else(!this._isDragging&&this._lockedPointer||this._isDragging&&(m.buttons&Wt.LEFT)===Wt.LEFT)&&(this._state=this._state|this.mouseButtons.left),this._isDragging&&(m.buttons&Wt.MIDDLE)===Wt.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),this._isDragging&&(m.buttons&Wt.RIGHT)===Wt.RIGHT&&(this._state=this._state|this.mouseButtons.right);f()}},l=m=>{const v=this._findPointerById(m.pointerId);if(!(v&&v===this._lockedPointer)){if(v&&this._disposePointer(v),m.pointerType==="touch")switch(this._activePointers.length){case 0:this._state=$.NONE;break;case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else this._state=$.NONE;p()}};let c=-1;const u=m=>{if(!this._domElement||!this._enabled||this.mouseButtons.wheel===$.NONE)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const x=this._domElement.getBoundingClientRect(),M=m.clientX/x.width,C=m.clientY/x.height;if(Mthis._interactiveArea.right||Cthis._interactiveArea.bottom)return}if(m.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===$.ROTATE||this.mouseButtons.wheel===$.TRUCK){const x=performance.now();c-x<1e3&&this._getClientRect(this._elementRect),c=x}const v=pN?-1:-3,y=m.deltaMode===1||m.ctrlKey?m.deltaY/v:m.deltaY/(v*10),b=this.dollyToCursor?(m.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,T=this.dollyToCursor?(m.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case $.ROTATE:{this._rotateInternal(m.deltaX,m.deltaY),this._isUserControllingRotate=!0;break}case $.TRUCK:{this._truckInternal(m.deltaX,m.deltaY,!1,!1),this._isUserControllingTruck=!0;break}case $.SCREEN_PAN:{this._truckInternal(m.deltaX,m.deltaY,!1,!0),this._isUserControllingTruck=!0;break}case $.OFFSET:{this._truckInternal(m.deltaX,m.deltaY,!0,!1),this._isUserControllingOffset=!0;break}case $.DOLLY:{this._dollyInternal(-y,b,T),this._isUserControllingDolly=!0;break}case $.ZOOM:{this._zoomInternal(-y,b,T),this._isUserControllingZoom=!0;break}}this.dispatchEvent({type:"control"})},d=m=>{if(!(!this._domElement||!this._enabled)){if(this.mouseButtons.right===Hm.ACTION.NONE){const v=m instanceof PointerEvent?m.pointerId:0,y=this._findPointerById(v);y&&this._disposePointer(y),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l);return}m.preventDefault()}},h=m=>{if(!this._enabled)return;if(Tp(this._activePointers,Kn),this._getClientRect(this._elementRect),i.copy(Kn),s.copy(Kn),this._activePointers.length>=2){const y=Kn.x-this._activePointers[1].clientX,b=Kn.y-this._activePointers[1].clientY,T=Math.sqrt(y*y+b*b);a.set(0,T);const x=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,M=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;s.set(x,M)}if(this._state=0,!m)this._lockedPointer&&(this._state=this._state|this.mouseButtons.left);else if("pointerType"in m&&m.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else!this._lockedPointer&&(m.buttons&Wt.LEFT)===Wt.LEFT&&(this._state=this._state|this.mouseButtons.left),(m.buttons&Wt.MIDDLE)===Wt.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),(m.buttons&Wt.RIGHT)===Wt.RIGHT&&(this._state=this._state|this.mouseButtons.right);((this._state&$.ROTATE)===$.ROTATE||(this._state&$.TOUCH_ROTATE)===$.TOUCH_ROTATE||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE)&&(this._sphericalEnd.theta=this._spherical.theta,this._sphericalEnd.phi=this._spherical.phi,this._thetaVelocity.value=0,this._phiVelocity.value=0),((this._state&$.TRUCK)===$.TRUCK||(this._state&$.SCREEN_PAN)===$.SCREEN_PAN||(this._state&$.TOUCH_TRUCK)===$.TOUCH_TRUCK||(this._state&$.TOUCH_SCREEN_PAN)===$.TOUCH_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN)&&(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),((this._state&$.DOLLY)===$.DOLLY||(this._state&$.TOUCH_DOLLY)===$.TOUCH_DOLLY||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE)&&(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),((this._state&$.ZOOM)===$.ZOOM||(this._state&$.TOUCH_ZOOM)===$.TOUCH_ZOOM||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_ZOOM_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE)&&(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),((this._state&$.OFFSET)===$.OFFSET||(this._state&$.TOUCH_OFFSET)===$.TOUCH_OFFSET||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET)&&(this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0)),this.dispatchEvent({type:"controlstart"})},f=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,Tp(this._activePointers,Kn);const v=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,y=v?-v.deltaX:s.x-Kn.x,b=v?-v.deltaY:s.y-Kn.y;if(s.copy(Kn),((this._state&$.ROTATE)===$.ROTATE||(this._state&$.TOUCH_ROTATE)===$.TOUCH_ROTATE||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE)&&(this._rotateInternal(y,b),this._isUserControllingRotate=!0),(this._state&$.DOLLY)===$.DOLLY||(this._state&$.ZOOM)===$.ZOOM){const T=this.dollyToCursor?(i.x-this._elementRect.x)/this._elementRect.width*2-1:0,x=this.dollyToCursor?(i.y-this._elementRect.y)/this._elementRect.height*-2+1:0,M=this.dollyDragInverted?-1:1;(this._state&$.DOLLY)===$.DOLLY?(this._dollyInternal(M*b*xu,T,x),this._isUserControllingDolly=!0):(this._zoomInternal(M*b*xu,T,x),this._isUserControllingZoom=!0)}if((this._state&$.TOUCH_DOLLY)===$.TOUCH_DOLLY||(this._state&$.TOUCH_ZOOM)===$.TOUCH_ZOOM||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_ZOOM_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE){const T=Kn.x-this._activePointers[1].clientX,x=Kn.y-this._activePointers[1].clientY,M=Math.sqrt(T*T+x*x),C=a.y-M;a.set(0,M);const w=this.dollyToCursor?(s.x-this._elementRect.x)/this._elementRect.width*2-1:0,E=this.dollyToCursor?(s.y-this._elementRect.y)/this._elementRect.height*-2+1:0;(this._state&$.TOUCH_DOLLY)===$.TOUCH_DOLLY||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET?(this._dollyInternal(C*xu,w,E),this._isUserControllingDolly=!0):(this._zoomInternal(C*xu,w,E),this._isUserControllingZoom=!0)}((this._state&$.TRUCK)===$.TRUCK||(this._state&$.TOUCH_TRUCK)===$.TOUCH_TRUCK||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK)&&(this._truckInternal(y,b,!1,!1),this._isUserControllingTruck=!0),((this._state&$.SCREEN_PAN)===$.SCREEN_PAN||(this._state&$.TOUCH_SCREEN_PAN)===$.TOUCH_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_ZOOM_SCREEN_PAN)&&(this._truckInternal(y,b,!1,!0),this._isUserControllingTruck=!0),((this._state&$.OFFSET)===$.OFFSET||(this._state&$.TOUCH_OFFSET)===$.TOUCH_OFFSET||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET)&&(this._truckInternal(y,b,!0,!1),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},p=()=>{Tp(this._activePointers,Kn),s.copy(Kn),this._dragNeedsUpdate=!1,(this._activePointers.length===0||this._activePointers.length===1&&this._activePointers[0]===this._lockedPointer)&&(this._isDragging=!1),this._activePointers.length===0&&this._domElement&&(this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this.dispatchEvent({type:"controlend"}))};this.lockPointer=()=>{!this._enabled||!this._domElement||(this.cancel(),this._lockedPointer={pointerId:-1,clientX:0,clientY:0,deltaX:0,deltaY:0,mouseButton:null},this._activePointers.push(this._lockedPointer),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.requestPointerLock(),this._domElement.ownerDocument.addEventListener("pointerlockchange",g),this._domElement.ownerDocument.addEventListener("pointerlockerror",_),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),h())},this.unlockPointer=()=>{var m,v,y;this._lockedPointer!==null&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),(m=this._domElement)===null||m===void 0||m.ownerDocument.exitPointerLock(),(v=this._domElement)===null||v===void 0||v.ownerDocument.removeEventListener("pointerlockchange",g),(y=this._domElement)===null||y===void 0||y.ownerDocument.removeEventListener("pointerlockerror",_),this.cancel()};const g=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},_=()=>{this.unlockPointer()};this._addAllEventListeners=m=>{this._domElement=m,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",r),this._domElement.addEventListener("pointercancel",l),this._domElement.addEventListener("wheel",u,{passive:!1}),this._domElement.addEventListener("contextmenu",d)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect="",this._domElement.removeEventListener("pointerdown",r),this._domElement.removeEventListener("pointercancel",l),this._domElement.removeEventListener("wheel",u,{passive:!1}),this._domElement.removeEventListener("contextmenu",d),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.removeEventListener("pointerlockchange",g),this._domElement.ownerDocument.removeEventListener("pointerlockerror",_))},this.cancel=()=>{this._state!==$.NONE&&(this._state=$.NONE,this._activePointers.length=0,p())},t&&this.connect(t),this.update(0)}get camera(){return this._camera}set camera(e){this._camera=e,this.updateCameraUp(),this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0}get enabled(){return this._enabled}set enabled(e){this._enabled=e,this._domElement&&(e?(this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none"):(this.cancel(),this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect=""))}get active(){return!this._hasRested}get currentAction(){return this._state}get distance(){return this._spherical.radius}set distance(e){this._spherical.radius===e&&this._sphericalEnd.radius===e||(this._spherical.radius=e,this._sphericalEnd.radius=e,this._needsUpdate=!0)}get azimuthAngle(){return this._spherical.theta}set azimuthAngle(e){this._spherical.theta===e&&this._sphericalEnd.theta===e||(this._spherical.theta=e,this._sphericalEnd.theta=e,this._needsUpdate=!0)}get polarAngle(){return this._spherical.phi}set polarAngle(e){this._spherical.phi===e&&this._sphericalEnd.phi===e||(this._spherical.phi=e,this._sphericalEnd.phi=e,this._needsUpdate=!0)}get boundaryEnclosesCamera(){return this._boundaryEnclosesCamera}set boundaryEnclosesCamera(e){this._boundaryEnclosesCamera=e,this._needsUpdate=!0}set interactiveArea(e){this._interactiveArea.width=Ui(e.width,0,1),this._interactiveArea.height=Ui(e.height,0,1),this._interactiveArea.x=Ui(e.x,0,1-this._interactiveArea.width),this._interactiveArea.y=Ui(e.y,0,1-this._interactiveArea.height)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}rotate(e,t,i=!1){return this.rotateTo(this._sphericalEnd.theta+e,this._sphericalEnd.phi+t,i)}rotateAzimuthTo(e,t=!1){return this.rotateTo(e,this._sphericalEnd.phi,t)}rotatePolarTo(e,t=!1){return this.rotateTo(this._sphericalEnd.theta,e,t)}rotateTo(e,t,i=!1){this._isUserControllingRotate=!1;const s=Ui(e,this.minAzimuthAngle,this.maxAzimuthAngle),a=Ui(t,this.minPolarAngle,this.maxPolarAngle);this._sphericalEnd.theta=s,this._sphericalEnd.phi=a,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,i||(this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi);const r=!i||Ct(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ct(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(r)}dolly(e,t=!1){return this.dollyTo(this._sphericalEnd.radius-e,t)}dollyTo(e,t=!1){return this._isUserControllingDolly=!1,this._lastDollyDirection=Vr.NONE,this._changedDolly=0,this._dollyToNoClamp(Ui(e,this.minDistance,this.maxDistance),t)}_dollyToNoClamp(e,t=!1){const i=this._sphericalEnd.radius;if(this.colliderMeshes.length>=1){const r=this._collisionTest(),o=Ct(r,this._spherical.radius);if(!(i>e)&&o)return Promise.resolve();this._sphericalEnd.radius=Math.min(e,r)}else this._sphericalEnd.radius=e;this._needsUpdate=!0,t||(this._spherical.radius=this._sphericalEnd.radius);const a=!t||Ct(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(a)}dollyInFixed(e,t=!1){this._targetEnd.add(this._getCameraDirection(al).multiplyScalar(e)),t||this._target.copy(this._targetEnd);const i=!t||Ct(this._target.x,this._targetEnd.x,this.restThreshold)&&Ct(this._target.y,this._targetEnd.y,this.restThreshold)&&Ct(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(i)}zoom(e,t=!1){return this.zoomTo(this._zoomEnd+e,t)}zoomTo(e,t=!1){this._isUserControllingZoom=!1,this._zoomEnd=Ui(e,this.minZoom,this.maxZoom),this._needsUpdate=!0,t||(this._zoom=this._zoomEnd);const i=!t||Ct(this._zoom,this._zoomEnd,this.restThreshold);return this._changedZoom=0,this._createOnRestPromise(i)}pan(e,t,i=!1){return console.warn("`pan` has been renamed to `truck`"),this.truck(e,t,i)}truck(e,t,i=!1){this._camera.updateMatrix(),ts.setFromMatrixColumn(this._camera.matrix,0),ns.setFromMatrixColumn(this._camera.matrix,1),ts.multiplyScalar(e),ns.multiplyScalar(-t);const s=ft.copy(ts).add(ns),a=Tt.copy(this._targetEnd).add(s);return this.moveTo(a.x,a.y,a.z,i)}forward(e,t=!1){ft.setFromMatrixColumn(this._camera.matrix,0),ft.crossVectors(this._camera.up,ft),ft.multiplyScalar(e);const i=Tt.copy(this._targetEnd).add(ft);return this.moveTo(i.x,i.y,i.z,t)}elevate(e,t=!1){return ft.copy(this._camera.up).multiplyScalar(e),this.moveTo(this._targetEnd.x+ft.x,this._targetEnd.y+ft.y,this._targetEnd.z+ft.z,t)}moveTo(e,t,i,s=!1){this._isUserControllingTruck=!1;const a=ft.set(e,t,i).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,a,this.boundaryFriction),this._needsUpdate=!0,s||this._target.copy(this._targetEnd);const r=!s||Ct(this._target.x,this._targetEnd.x,this.restThreshold)&&Ct(this._target.y,this._targetEnd.y,this.restThreshold)&&Ct(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(r)}lookInDirectionOf(e,t,i,s=!1){const o=ft.set(e,t,i).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd);return this.setPosition(o.x,o.y,o.z,s)}fitToBox(e,t,{cover:i=!1,paddingLeft:s=0,paddingRight:a=0,paddingBottom:r=0,paddingTop:o=0}={}){const l=[],c=e.isBox3?Wr.copy(e):Wr.setFromObject(e);c.isEmpty()&&(console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve());const u=bv(this._sphericalEnd.theta,vv),d=bv(this._sphericalEnd.phi,vv);l.push(this.rotateTo(u,d,t));const h=ft.setFromSpherical(this._sphericalEnd).normalize(),f=Ev.setFromUnitVectors(h,Cp),p=Ct(Math.abs(h.y),1);p&&f.multiply(Rp.setFromAxisAngle(wu,u)),f.multiply(this._yAxisUpSpaceInverse);const g=Mv.makeEmpty();Tt.copy(c.min).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.min).setX(c.max.x).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.min).setY(c.max.y).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.max).setZ(c.min.z).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.min).setZ(c.max.z).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.max).setY(c.min.y).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.max).setX(c.min.x).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.max).applyQuaternion(f),g.expandByPoint(Tt),g.min.x-=s,g.min.y-=r,g.max.x+=a,g.max.y+=o,f.setFromUnitVectors(Cp,h),p&&f.premultiply(Rp.invert()),f.premultiply(this._yAxisUpSpace);const _=g.getSize(ft),m=g.getCenter(Tt).applyQuaternion(f);if(ka(this._camera)){const v=this.getDistanceToFitBox(_.x,_.y,_.z,i);l.push(this.moveTo(m.x,m.y,m.z,t)),l.push(this.dollyTo(v,t)),l.push(this.setFocalOffset(0,0,0,t))}else if(Js(this._camera)){const v=this._camera,y=v.right-v.left,b=v.top-v.bottom,T=i?Math.max(y/_.x,b/_.y):Math.min(y/_.x,b/_.y);l.push(this.moveTo(m.x,m.y,m.z,t)),l.push(this.zoomTo(T,t)),l.push(this.setFocalOffset(0,0,0,t))}return Promise.all(l)}fitToSphere(e,t){const i=[],a="isObject3D"in e?Hm.createBoundingSphere(e,Ap):Ap.copy(e);if(i.push(this.moveTo(a.center.x,a.center.y,a.center.z,t)),ka(this._camera)){const r=this.getDistanceToFitSphere(a.radius);i.push(this.dollyTo(r,t))}else if(Js(this._camera)){const r=this._camera.right-this._camera.left,o=this._camera.top-this._camera.bottom,l=2*a.radius,c=Math.min(r/l,o/l);i.push(this.zoomTo(c,t))}return i.push(this.setFocalOffset(0,0,0,t)),Promise.all(i)}setLookAt(e,t,i,s,a,r,o=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Vr.NONE,this._changedDolly=0;const l=Tt.set(s,a,r),c=ft.set(e,t,i);this._targetEnd.copy(l),this._sphericalEnd.setFromVector3(c.sub(l).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,o||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const u=!o||Ct(this._target.x,this._targetEnd.x,this.restThreshold)&&Ct(this._target.y,this._targetEnd.y,this.restThreshold)&&Ct(this._target.z,this._targetEnd.z,this.restThreshold)&&Ct(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ct(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Ct(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(u)}lerpLookAt(e,t,i,s,a,r,o,l,c,u,d,h,f,p=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Vr.NONE,this._changedDolly=0;const g=ft.set(s,a,r),_=Tt.set(e,t,i);vi.setFromVector3(_.sub(g).applyQuaternion(this._yAxisUpSpace));const m=$r.set(u,d,h),v=Tt.set(o,l,c);rl.setFromVector3(v.sub(m).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(g.lerp(m,f));const y=rl.theta-vi.theta,b=rl.phi-vi.phi,T=rl.radius-vi.radius;this._sphericalEnd.set(vi.radius+T*f,vi.phi+b*f,vi.theta+y*f),this.normalizeRotations(),this._needsUpdate=!0,p||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const x=!p||Ct(this._target.x,this._targetEnd.x,this.restThreshold)&&Ct(this._target.y,this._targetEnd.y,this.restThreshold)&&Ct(this._target.z,this._targetEnd.z,this.restThreshold)&&Ct(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ct(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Ct(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(x)}setPosition(e,t,i,s=!1){return this.setLookAt(e,t,i,this._targetEnd.x,this._targetEnd.y,this._targetEnd.z,s)}setTarget(e,t,i,s=!1){const a=this.getPosition(ft),r=this.setLookAt(a.x,a.y,a.z,e,t,i,s);return this._sphericalEnd.phi=Ui(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),r}setFocalOffset(e,t,i,s=!1){this._isUserControllingOffset=!1,this._focalOffsetEnd.set(e,t,i),this._needsUpdate=!0,s||this._focalOffset.copy(this._focalOffsetEnd);const a=!s||Ct(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&Ct(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&Ct(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(a)}setOrbitPoint(e,t,i){this._camera.updateMatrixWorld(),ts.setFromMatrixColumn(this._camera.matrixWorldInverse,0),ns.setFromMatrixColumn(this._camera.matrixWorldInverse,1),Da.setFromMatrixColumn(this._camera.matrixWorldInverse,2);const s=ft.set(e,t,i),a=s.distanceTo(this._camera.position),r=s.sub(this._camera.position);ts.multiplyScalar(r.x),ns.multiplyScalar(r.y),Da.multiplyScalar(r.z),ft.copy(ts).add(ns).add(Da),ft.z=ft.z+a,this.dollyTo(a,!1),this.setFocalOffset(-ft.x,ft.y,-ft.z,!1),this.moveTo(e,t,i,!1)}setBoundary(e){if(!e){this._boundary.min.set(-1/0,-1/0,-1/0),this._boundary.max.set(1/0,1/0,1/0),this._needsUpdate=!0;return}this._boundary.copy(e),this._boundary.clampPoint(this._targetEnd,this._targetEnd),this._needsUpdate=!0}setViewport(e,t,i,s){if(e===null){this._viewport=null;return}this._viewport=this._viewport||new tt.Vector4,typeof e=="number"?this._viewport.set(e,t,i,s):this._viewport.copy(e)}getDistanceToFitBox(e,t,i,s=!1){if(Mp(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const a=e/t,r=this._camera.getEffectiveFOV()*nl,o=this._camera.aspect;return((s?a>o:at.pointerId===e)}_findPointerByMouseButton(e){return this._activePointers.find(t=>t.mouseButton===e)}_disposePointer(e){this._activePointers.splice(this._activePointers.indexOf(e),1)}_encloseToBoundary(e,t,i){const s=t.lengthSq();if(s===0)return e;const a=Tt.copy(t).add(e),o=this._boundary.clampPoint(a,$r).sub(a),l=o.lengthSq();if(l===0)return e.add(t);if(l===s)return e;if(i===0)return e.add(t).add(o);{const c=1+i*l/t.dot(o);return e.add(Tt.copy(t).multiplyScalar(c)).add(o.multiplyScalar(1-i))}}_updateNearPlaneCorners(){if(ka(this._camera)){const e=this._camera,t=e.near,i=e.getEffectiveFOV()*nl,s=Math.tan(i*.5)*t,a=s*e.aspect;this._nearPlaneCorners[0].set(-a,-s,0),this._nearPlaneCorners[1].set(a,-s,0),this._nearPlaneCorners[2].set(a,s,0),this._nearPlaneCorners[3].set(-a,s,0)}else if(Js(this._camera)){const e=this._camera,t=1/e.zoom,i=e.left*t,s=e.right*t,a=e.top*t,r=e.bottom*t;this._nearPlaneCorners[0].set(i,a,0),this._nearPlaneCorners[1].set(s,a,0),this._nearPlaneCorners[2].set(s,r,0),this._nearPlaneCorners[3].set(i,r,0)}}_collisionTest(){let e=1/0;if(!(this.colliderMeshes.length>=1)||Mp(this._camera,"_collisionTest"))return e;const i=this._getTargetDirection(al);Pp.lookAt(wv,i,this._camera.up);for(let s=0;s<4;s++){const a=Tt.copy(this._nearPlaneCorners[s]);a.applyMatrix4(Pp);const r=$r.addVectors(this._target,a);Su.set(r,i),Su.far=this._spherical.radius+1;const o=Su.intersectObjects(this.colliderMeshes);o.length!==0&&o[0].distance{const i=()=>{this.removeEventListener("rest",i),t()};this.addEventListener("rest",i)}))}_addAllEventListeners(e){}_removeAllEventListeners(){}get dampingFactor(){return console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead."),0}set dampingFactor(e){console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead.")}get draggingDampingFactor(){return console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead."),0}set draggingDampingFactor(e){console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead.")}static createBoundingSphere(e,t=new tt.Sphere){const i=t,s=i.center;Wr.makeEmpty(),e.traverseVisible(r=>{r.isMesh&&Wr.expandByObject(r)}),Wr.getCenter(s);let a=0;return e.traverseVisible(r=>{if(!r.isMesh)return;const o=r;if(!o.geometry)return;const l=o.geometry.clone();l.applyMatrix4(o.matrixWorld);const u=l.attributes.position;for(let d=0,h=u.count;di.preventDefault()),this.isFollowingViewer=!1,this.followTargetPosition=new S,this.followTargetQuaternion=new dt,this.followPositionLerpFactor=.12,this.followRotationSlerpFactor=.1,this.hasFollowTarget=!1,this.isRightMouseDown=!1,this.lastMouseX=null,this.lastMouseY=null,this.savedCameraState=null,this.isInReplayMode=!1}setMode(e){if(this.mode=e,e==="ballOrbit"){if(this.controls.enabled=!0,this.lastBallOrbitPos=null,this.ballOrbitScrollHandler||(this.ballOrbitScrollHandler=t=>{if(this.mode==="ballOrbit"&&!this.isFollowingViewer){t.preventDefault();const i=Math.max(this.controls.distance*.2,100);t.deltaY>0?this.controls.dolly(-i,!0):this.controls.dolly(i,!0)}},this.domElement.addEventListener("wheel",this.ballOrbitScrollHandler,{passive:!1})),this.targetBall){const t=this.targetBall.position;this.camera.position.distanceTo(t),this.controls.setLookAt(this.camera.position.x,this.camera.position.y,this.camera.position.z,t.x,t.y,t.z,!1)}return}if(e==="free"){if(this.controls.enabled=!1,!this.freeCamKeys){this.freeCamKeys={forward:!1,backward:!1,left:!1,right:!1,up:!1,down:!1},this.freeCamSpeed=2e3,this.freeCamRotation={yaw:0,pitch:0};const t=new S;this.camera.getWorldDirection(t),this.freeCamRotation.yaw=Math.atan2(t.x,t.z),this.freeCamRotation.pitch=Math.asin(-t.y),this.onKeyDown=i=>this.handleFreeCamKeyDown(i),this.onKeyUp=i=>this.handleFreeCamKeyUp(i),this.onMouseMove=i=>this.handleFreeCamMouseMove(i),this.onMouseDown=i=>{i.button===2&&this.mode==="free"&&!this.isFollowingViewer&&(this.isRightMouseDown=!0,this.domElement.requestPointerLock?.())},this.onMouseUp=i=>{i.button===2&&(this.isRightMouseDown=!1,document.pointerLockElement===this.domElement&&document.exitPointerLock?.())},this.onPointerLockChange=()=>{document.pointerLockElement!==this.domElement&&(this.isRightMouseDown=!1)},this.onMouseLeave=()=>{document.pointerLockElement!==this.domElement&&(this.isRightMouseDown=!1)},this.onWindowBlur=()=>{this.isRightMouseDown=!1,document.pointerLockElement===this.domElement&&document.exitPointerLock?.(),this.freeCamKeys&&(this.freeCamKeys.forward=!1,this.freeCamKeys.backward=!1,this.freeCamKeys.left=!1,this.freeCamKeys.right=!1,this.freeCamKeys.up=!1,this.freeCamKeys.down=!1)},this.onVisibilityChange=()=>{document.hidden&&(this.isRightMouseDown=!1,document.pointerLockElement===this.domElement&&document.exitPointerLock?.(),this.freeCamKeys&&(this.freeCamKeys.forward=!1,this.freeCamKeys.backward=!1,this.freeCamKeys.left=!1,this.freeCamKeys.right=!1,this.freeCamKeys.up=!1,this.freeCamKeys.down=!1))},document.addEventListener("keydown",this.onKeyDown),document.addEventListener("keyup",this.onKeyUp),document.addEventListener("mousemove",this.onMouseMove),this.domElement.addEventListener("mousedown",this.onMouseDown),document.addEventListener("mouseup",this.onMouseUp),document.addEventListener("pointerlockchange",this.onPointerLockChange),this.domElement.addEventListener("mouseleave",this.onMouseLeave),window.addEventListener("blur",this.onWindowBlur),document.addEventListener("visibilitychange",this.onVisibilityChange)}this.isRightMouseDown=!1}else this.controls.enabled=!1,this.lastIsBallCam=null,this.currentBlend=0,this.targetBlend=0}setTargetCar(e){if(this.targetCar!==e&&(this.currentBallCamAngle=null,this.targetCar&&e)){this.targetHandoff={elapsed:0,duration:mN,startPosition:this.camera.position.clone(),startQuaternion:this.camera.quaternion.clone()};const t=new S().subVectors(this.camera.position,e.position);t.y=0,t.length()>.01&&(t.normalize(),this.smoothedCarYaw=Math.atan2(-t.x,-t.z)),this.lastCarPos&&this.lastCarPos.copy(e.position)}this.targetCar=e}setTargetBall(e){this.targetBall=e}handleFreeCamKeyDown(e){if(this.mode!=="free"||this.isFollowingViewer)return;const t=e.target;if(!(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable))switch(e.code){case"KeyW":case"ArrowUp":this.freeCamKeys.forward=!0;break;case"KeyS":case"ArrowDown":this.freeCamKeys.backward=!0;break;case"KeyA":case"ArrowLeft":this.freeCamKeys.left=!0;break;case"KeyD":case"ArrowRight":this.freeCamKeys.right=!0;break;case"Space":this.freeCamKeys.up=!0;break;case"ShiftLeft":case"ShiftRight":this.freeCamKeys.down=!0;break}}handleFreeCamKeyUp(e){switch(e.code){case"KeyW":case"ArrowUp":this.freeCamKeys.forward=!1;break;case"KeyS":case"ArrowDown":this.freeCamKeys.backward=!1;break;case"KeyA":case"ArrowLeft":this.freeCamKeys.left=!1;break;case"KeyD":case"ArrowRight":this.freeCamKeys.right=!1;break;case"Space":this.freeCamKeys.up=!1;break;case"ShiftLeft":case"ShiftRight":this.freeCamKeys.down=!1;break}}handleFreeCamMouseMove(e){if(this.mode!=="free"||!this.isRightMouseDown||this.isFollowingViewer)return;const t=e.movementX||0,i=e.movementY||0,s=.003;this.freeCamRotation.yaw-=t*s,this.freeCamRotation.pitch+=i*s,this.freeCamRotation.pitch=Math.max(-Math.PI/2+.01,Math.min(Math.PI/2-.01,this.freeCamRotation.pitch))}updateFreeCam(e){if(!this.freeCamKeys)return;const t=new S(Math.sin(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch),-Math.sin(this.freeCamRotation.pitch),Math.cos(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch));t.normalize();const i=new S(Math.sin(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch),-Math.sin(this.freeCamRotation.pitch),Math.cos(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch));i.normalize();const s=new S(Math.sin(this.freeCamRotation.yaw-Math.PI/2),0,Math.cos(this.freeCamRotation.yaw-Math.PI/2)),a=new S(0,1,0),r=new S,o=this.freeCamSpeed*e;this.freeCamKeys.forward&&r.add(i.clone().multiplyScalar(o)),this.freeCamKeys.backward&&r.add(i.clone().multiplyScalar(-o)),this.freeCamKeys.right&&r.add(s.clone().multiplyScalar(o)),this.freeCamKeys.left&&r.add(s.clone().multiplyScalar(-o)),this.freeCamKeys.up&&r.add(a.clone().multiplyScalar(o)),this.freeCamKeys.down&&r.add(a.clone().multiplyScalar(-o)),r.length()>0&&r.normalize().multiplyScalar(o),this.camera.position.add(r);const l=this.camera.position.clone().add(t);this.camera.lookAt(l),this.controls.setLookAt(this.camera.position.x,this.camera.position.y,this.camera.position.z,l.x,l.y,l.z,!1)}update(e,t=!0){if(this.isFollowingViewer){this.updateFollowInterpolation(e);return}if(this.mode==="free"){this.updateFreeCam(e),this.controls.update(e);return}if(this.mode==="ballOrbit"){if(this.targetBall){const p=this.targetBall.position;this.lastBallOrbitPos||(this.lastBallOrbitPos=p.clone());const g=new S().subVectors(p,this.lastBallOrbitPos);if(this.controls.setTarget(p.x,p.y,p.z,!1),g.lengthSq()>.01){const _=new S;this.controls.getPosition(_);const m=_.x+g.x,v=_.y+g.y,y=_.z+g.z;this.controls.setPosition(m,v,y,!1),this.lastBallOrbitPos.copy(p)}}this.controls.update(e);return}if(!this.targetCar){this.controls.update(e);return}const i=this.targetCar.position.clone(),s=this.targetCar.quaternion;if(this.lastIsBallCam!==null&&this.lastIsBallCam!==t&&!t){const p=new S().subVectors(this.camera.position,i);p.y=0,p.length()>.01&&(p.normalize(),this.smoothedCarYaw=Math.atan2(-p.x,-p.z))}this.lastIsBallCam=t;const a=this.calculateCarCamPosition(i,s,e),r=this.calculateBallCamPosition(i,s,e);this.targetBlend=t?1:0;const o=Math.max(.15,Math.min(.6,this.baseDuration/this.transitionSpeed)),l=e/o;this.currentBlendthis.targetBlend&&(this.currentBlend=Math.max(this.currentBlend-l,this.targetBlend));const c=this.currentBlend,u=c*c*(3-2*c),d=new S().lerpVectors(a.cameraPos,r.cameraPos,u);this._tempMatrix.lookAt(a.cameraPos,a.lookTarget,new S(0,1,0)),this._tempQuatCarCam.setFromRotationMatrix(this._tempMatrix),this._tempMatrix.lookAt(r.cameraPos,r.lookTarget,new S(0,1,0)),this._tempQuatBallCam.setFromRotationMatrix(this._tempMatrix),this._tempQuatCarCam.dot(this._tempQuatBallCam)<0&&this._tempQuatBallCam.set(-this._tempQuatBallCam.x,-this._tempQuatBallCam.y,-this._tempQuatBallCam.z,-this._tempQuatBallCam.w);const h=new dt().slerpQuaternions(this._tempQuatCarCam,this._tempQuatBallCam,u);if(this.targetHandoff){this.targetHandoff.elapsed+=e;const p=Math.min(1,this.targetHandoff.elapsed/this.targetHandoff.duration),g=p*p*(3-2*p),_=d.clone(),m=h.clone();d.lerpVectors(this.targetHandoff.startPosition,_,g),h.slerpQuaternions(this.targetHandoff.startQuaternion,m,g),p>=1&&(this.targetHandoff=null)}if(this.camera.position.copy(d),this.camera.quaternion.copy(h),this.followAngle!==0){const p=this.followAngle*Math.PI/180;this.camera.rotateX(-p)}this.currentCamPos||(this.currentCamPos=new S),this.currentLookTarget||(this.currentLookTarget=new S),this.currentCamPos.copy(d);const f=new S(0,0,-1).applyQuaternion(this.camera.quaternion);this.currentLookTarget.copy(d).add(f.multiplyScalar(100)),this.enforceMinHeight()}calculateBallCamPosition(e,t,i=1/60){if(!this.targetBall)return this.calculateCarCamPosition(e,t,i);const s=this.targetBall.position.clone(),a=new S().subVectors(e,s);a.y=0,a.normalize();const r=e.clone().add(a.multiplyScalar(this.followDistance)),o=s.y-e.y,c=Math.min(1,Math.max(0,o/800));r.y=e.y+this.followHeight-c*100,r.y.01)s.normalize(),u=Math.atan2(s.x,s.z);else if(a>.05){s.normalize();let y=Math.atan2(s.x,s.z)-o;for(;y>Math.PI;)y-=Math.PI*2;for(;y<-Math.PI;)y+=Math.PI*2;Math.abs(y)>Math.PI/2?u=o+Math.PI:u=o}else u=o;this.lastCarPos.copy(e),this.smoothedCarYaw===void 0&&(this.smoothedCarYaw=u);let d=u-this.smoothedCarYaw;for(;d>Math.PI;)d-=Math.PI*2;for(;d<-Math.PI;)d+=Math.PI*2;const h=c?this.swivelSpeed*.4:this.swivelSpeed;this.smoothedCarYaw+=d*Math.min(1,h*(1/60));const f=-Math.sin(this.smoothedCarYaw),p=-Math.cos(this.smoothedCarYaw),g=new S(e.x+f*this.followDistance,e.y+this.followHeight,e.z+p*this.followDistance);g.yMath.PI;)s-=Math.PI*2;for(;s<-Math.PI;)s+=Math.PI*2;this.followCurrentOrbitParams.azimuth+=s*.15,this.followCurrentOrbitParams.polar+=(this.followTargetOrbitParams.polar-this.followCurrentOrbitParams.polar)*.15,this.controls.setTarget(t.x,t.y,t.z,!1),this.controls.dollyTo(this.followCurrentOrbitParams.distance,!1),this.controls.rotateTo(this.followCurrentOrbitParams.azimuth,this.followCurrentOrbitParams.polar,!1),this.controls.update(e)}}else{if(this.camera.position.lerp(this.followTargetPosition,this.followPositionLerpFactor),this.camera.quaternion.slerp(this.followTargetQuaternion,this.followRotationSlerpFactor),this.freeCamRotation){const i=new S;this.camera.getWorldDirection(i),this.freeCamRotation.yaw=Math.atan2(i.x,i.z),this.freeCamRotation.pitch=Math.asin(-i.y)}const t=new S;this.camera.getWorldDirection(t),t.multiplyScalar(100).add(this.camera.position),this.controls.setLookAt(this.camera.position.x,this.camera.position.y,this.camera.position.z,t.x,t.y,t.z,!1)}}setDefaultFreecamPosition(){if(this.camera.position.copy(this.defaultFreecamPosition),this.camera.lookAt(this.defaultFreecamLookAt),this.freeCamRotation){const e=new S;this.camera.getWorldDirection(e),this.freeCamRotation.yaw=Math.atan2(e.x,e.z),this.freeCamRotation.pitch=Math.asin(-e.y)}this.controls.setLookAt(this.defaultFreecamPosition.x,this.defaultFreecamPosition.y,this.defaultFreecamPosition.z,this.defaultFreecamLookAt.x,this.defaultFreecamLookAt.y,this.defaultFreecamLookAt.z,!1)}getIsPointerLocked(){return this.isPointerLocked||!1}setPointerLockCallback(e){this.onPointerLockStateChange=e}dispose(){this.controls.dispose(),this.ballOrbitScrollHandler&&this.domElement.removeEventListener("wheel",this.ballOrbitScrollHandler),this.onKeyDown&&document.removeEventListener("keydown",this.onKeyDown),this.onKeyUp&&document.removeEventListener("keyup",this.onKeyUp),this.onMouseMove&&document.removeEventListener("mousemove",this.onMouseMove),this.onMouseDown&&this.domElement.removeEventListener("mousedown",this.onMouseDown),this.onMouseUp&&document.removeEventListener("mouseup",this.onMouseUp),this.onPointerLockChange&&document.removeEventListener("pointerlockchange",this.onPointerLockChange),this.onMouseLeave&&this.domElement.removeEventListener("mouseleave",this.onMouseLeave),this.onWindowBlur&&window.removeEventListener("blur",this.onWindowBlur),this.onVisibilityChange&&document.removeEventListener("visibilitychange",this.onVisibilityChange)}}function Av(n){if(n.pitch===void 0||n.angle!==void 0)return n;const{pitch:e,...t}=n;return{...t,angle:e}}const gN={distance:260,height:90,angle:-4,stiffness:.45,swivelSpeed:4.3,transitionSpeed:1.3,fov:110};function yN(n={}){let e=null,t=null,i=n.mode??(n.follow?"follow":"orbit"),s=n.follow??null,a=n.ballCam??null,r=a??!0,o=Av({...n.settings}),l=1;const c=n.useRecordedSettings!==!1;let u=null;const d=new S;let h=!1;function f(){if(!(!t||!e)){if(t.player.controls.enabled=i==="orbit",i==="free")e.setMode("free");else if(i==="ballOrbit"){const y=_();y&&e.setTargetBall(y),e.setMode("ballOrbit")}else e.setMode("car");u=null}}function p(){return!c||!t||!s?null:t.player.adapter.getPlayer(s)?.cameraSettings??null}function g(){const y={...gN,...p(),...o};return l!==1&&y.distance!==void 0&&(y.distance*=l),y}function _(){if(!t)return null;const y=t.player.actorManager;return y.ballActorId!=null?y.actors[y.ballActorId]??null:null}function m(y){const b=g().fov;if(!b)return;const T=b*Math.PI/180,x=16/9,M=2*Math.atan(Math.tan(T/2)/x),C=2*Math.atan(Math.tan(T/2)/y.aspect),w=Math.max(M,C)*180/Math.PI;Math.abs(y.fov-w)>.1&&(y.fov=w,y.updateProjectionMatrix())}function v(y,b){if(!e)return;if(i==="free"){o.freeCamSpeed&&(e.freeCamSpeed=o.freeCamSpeed),e.update(b);return}if(i==="ballOrbit"){y.ball.object3d&&e.setTargetBall(y.ball.object3d),e.update(b);return}const x=(s?y.cars.find(C=>C.name===s):void 0)?.object3d??null;if(!x){e.update(b);return}e.setTargetCar(x),y.ball.object3d&&e.setTargetBall(y.ball.object3d),e.setFollowSettings(g());const M=s?y.player.adapter.getPlayer(s):void 0;r=a??M?.isBallCam??!0,d.copy(x.position),h=!0,e.update(b,r)}return{id:"camera",setup(y){t=y,e=new _N(y.camera,y.renderer.domElement),f()},beforeRender(y){if(!e||(m(y.camera),i==="orbit"))return;const b=performance.now(),T=u===null?1/60:Math.min(.1,(b-u)/1e3);u=b,v(y,T)},teardown(){i="orbit",t&&(t.player.controls.enabled=!0),e?.dispose(),e=null,t=null},setMode(y){y!==i&&(i=y,f())},getMode(){return i},follow(y){s=y,i="follow",f()},release(){i="orbit",t&&h&&t.player.controls.target.copy(d),f()},getTarget(){return s},setBallCam(y){a=y,y!==null&&(r=y)},getBallCam(){return r},setCameraSettings(y){o=y===null?{}:{...o,...Av(y)}},setDistanceScale(y){l=Math.max(.25,y)},getDistanceScale(){return l},getCameraSettings(){return g()},getRecordedSettings(){const y=p();return y?{...y}:null}}}const vN={"top-left":"top: 8px; left: 8px;","top-right":"top: 8px; right: 8px;","bottom-left":"bottom: 8px; left: 8px;","bottom-right":"bottom: 8px; right: 8px;"};function bN(n={}){const e=n.corner??"top-right",t=n.updateIntervalMs??500,i=()=>typeof n.mount=="function"?n.mount():n.mount??null;let s=null,a=null,r=null,o=0,l=performance.now(),c=0,u=0;const d=typeof n.onSample=="function";return{id:"fps-overlay",setup(h){if(l=performance.now(),o=0,u=h.player.getState().frameIndex,c=u,d)return;const f=i(),p=f!=null;s=document.createElement("div"),s.className="player-fps-overlay",s.style.cssText=p?` display: inline-flex; gap: 10px; align-items: center; font: 600 11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace; color: #c8d4e6; letter-spacing: 0.02em; white-space: nowrap; `:` - position: absolute; ${lN[e]} + position: absolute; ${vN[e]} z-index: 30; pointer-events: none; user-select: none; display: flex; gap: 10px; font: 600 11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace; @@ -3938,7 +3938,7 @@ void main() { border: 1px solid rgba(255, 255, 255, 0.12); border-radius: 6px; padding: 4px 8px; letter-spacing: 0.02em; white-space: nowrap; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6); - `;const g=document.createElement("span");g.append("Render "),a=document.createElement("span"),a.style.color="#7fd4ff",a.textContent="– fps",g.append(a);const _=document.createElement("span");_.append("Replay "),r=document.createElement("span"),r.style.color="#9affc0",r.textContent="– fps",_.append(r),s.append(g,_),f?f.appendChild(s):(getComputedStyle(h.container).position==="static"&&(h.container.style.position="relative"),h.container.appendChild(s))},beforeRender(h){o+=1,u=h.frameIndex;const f=performance.now(),p=f-l;if(puN(u,i,s,a,n.currentTime))}}function bu(n){return{...n,setup:n.setup?e=>{n.setup?.(Om(e,n.id))}:void 0,onStateChange:n.onStateChange?e=>{n.onStateChange?.(IT(e,n.id))}:void 0,beforeRender:n.beforeRender?e=>{n.beforeRender?.(dN(e,n.id))}:void 0,teardown:n.teardown?e=>{n.teardown?.(Om(e,n.id))}:void 0}}const hN=255;function Qh(n){return n==null?null:n*100/hN}const fN=1.35,pN="#57a8ff",mN="#ff9c40",_N=256,gN=160,yN=360,vN=225,bN=260,xN=430,LT=18,wv=120;function wN(n){return n?pN:mN}function SN(n){return n.events.filter(e=>!e.available&&e.playerId)}function DT(n,e){const t=document.createElement("canvas");t.width=_N,t.height=gN;const i=t.getContext("2d");if(!i)throw new Error("Unable to create boost pickup count canvas");i.clearRect(0,0,t.width,t.height),i.textAlign="center",i.textBaseline="middle",i.lineJoin="round",i.font="800 124px sans-serif",i.lineWidth=18,i.strokeStyle="rgba(4, 10, 18, 0.88)",i.strokeText(`${n}`,t.width/2,t.height/2),i.fillStyle=e,i.fillText(`${n}`,t.width/2,t.height/2);const s=new oc(t);return s.colorSpace=gt,s.needsUpdate=!0,s}function TN(n){n?.dispose()}function MN(n){const e=new Mt;e.visible=!1,e.renderOrder=60,e.frustumCulled=!1;const t=DT(1,n),i=new Ih({map:t,transparent:!0,depthTest:!1,depthWrite:!1}),s=new Lh(i);s.scale.set(yN,vN,1),s.renderOrder=62,s.frustumCulled=!1,e.add(s);const a=new Ye({color:n,transparent:!0,opacity:0,side:ct,depthTest:!1,depthWrite:!1,blending:Ht}),r=new we(new ni(wv*.72,wv,36),a);return r.position.z=LT,r.renderOrder=61,r.frustumCulled=!1,e.add(r),{group:e,textMaterial:i,ringMaterial:a}}function EN(n,e){n.currentCount!==e&&(TN(n.textMaterial.map),n.textMaterial.map=DT(e,n.color),n.textMaterial.needsUpdate=!0,n.currentCount=e)}function CN(n){const e=new Map;for(const s of n.replay.players)e.set(s.id,s);const t=[];for(const s of n.replay.boostPads)for(const a of SN(s))t.push({pad:s,event:a});t.sort((s,a)=>s.event.time!==a.event.time?s.event.time-a.event.time:s.event.frame!==a.event.frame?s.event.frame-a.event.frame:s.pad.index-a.pad.index);const i=[];for(const{pad:s,event:a}of t){if(!a.playerId)continue;const r=e.get(a.playerId);if(!r)continue;const o=wN(r.isTeamZero),{group:l,textMaterial:c,ringMaterial:u}=MN(o);l.position.copy(s.position),n.scene.replayRoot.add(l),i.push({time:a.time,pad:s,event:a,player:r,color:o,currentCount:1,position:new S(s.position.x,s.position.y,s.position.z),size:s.size,group:l,textMaterial:c,ringMaterial:u})}return i}function AN(n,e,t){const i=vt.clamp(e/t,0,1),s=1-Math.pow(1-i,3),a=i*i,r=n.size==="big"?xN:bN,o=n.size==="big"?360:280,l=1+Math.sin(i*Math.PI)*.22;n.group.visible=!0,n.group.position.set(n.position.x,n.position.y,n.position.z+r+s*o),n.group.scale.setScalar(l),n.textMaterial.opacity=Math.max(0,1-a),n.ringMaterial.opacity=Math.max(0,.48*(1-i));const c=n.group.children[1];if(c){const u=.75+s*(n.size==="big"?2.8:1.85);c.scale.setScalar(u),c.position.z=LT-r-s*o}}function RN(n={}){const e=Math.max(.1,n.durationSeconds??fN);let t=[];function i(a){return n.includePickup?.({pad:a.pad,event:a.event,player:a.player})??!0}function s(){for(const a of t)a.group.visible=!1}return{id:"boost-pickup-animation",setup(a){t=CN(a)},beforeRender(a){if(!a.state.boostPickupAnimationEnabled){s();return}const r=a.currentTime-e,o=new Map;for(const l of t){if(l.time>a.currentTime){l.group.visible=!1;continue}if(!i(l)){l.group.visible=!1;continue}const c=(o.get(l.player.id)??0)+1;if(o.set(l.player.id,c),l.time{(r instanceof we||r instanceof Lh)&&r.geometry?.dispose()}),a.textMaterial.map?.dispose(),a.textMaterial.dispose(),a.ringMaterial.dispose();t=[]}}}const PN=60,IN=["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"];function LN(n){if(n&&MediaRecorder.isTypeSupported(n))return n;for(const e of IN)if(MediaRecorder.isTypeSupported(e))return e;return""}function DN(n){return n instanceof Error?n.message:String(n)}function kN(n={}){let e=null,t=null,i=[],s=null,a=0,r=0,o="",l=0,c=null,u=null,d=null,h=null,f=!1,p=null;const g=new Set;function _(){return{state:t?t.state==="recording"?"recording":"stopping":c?"error":s?"ready":"idle",elapsedSeconds:r,mimeType:o,sizeBytes:l,error:c}}function m(){const x=_();n.onStatusChange?.(x);for(const M of g)M(x)}function v(){if(!e)throw new Error("Canvas recorder plugin is not installed");return e}function y(x){t=null,h=null,f=!1,s=x,l=x?.size??0,p&&e&&e.player.setState({currentTime:p.currentTime,speed:p.speed,playing:p.playing}),p=null,x&&n.onComplete?.(x),m(),d?.(x),d=null,u=null}function b(x){c=DN(x),t=null,h=null,f=!1,p=null,m(),d?.(null),d=null,u=null}const T={id:"canvas-recorder",setup(x){e=x},beforeRender(x){t?.state==="recording"&&(r=(performance.now()-a)/1e3,m()),t?.state==="recording"&&h!==null&&x.currentTime>=h&&T.stop()},onStateChange(x){f&&t?.state==="recording"&&!x.state.playing&&r>0&&T.stop()},teardown(){t?.state==="recording"&&t.stop(),e=null,t=null,h=null,f=!1,p=null,d?.(null),d=null,u=null,g.clear()},start(x={}){const M=v();if(t?.state==="recording")throw new Error("Canvas recording is already in progress");if(typeof MediaRecorder>"u")throw new Error("MediaRecorder is not available in this browser");const C=M.scene.renderer.domElement;if(!C.captureStream)throw new Error("Canvas captureStream is not available in this browser");c=null,s=null,i=[],l=0,r=0,a=performance.now(),o=LN(x.mimeType??n.mimeType);const w=Math.max(1,x.fps??n.fps??PN),E=C.captureStream(w);t=new MediaRecorder(E,{mimeType:o,videoBitsPerSecond:x.videoBitsPerSecond??n.videoBitsPerSecond}),u=new Promise(R=>{d=R}),t.addEventListener("dataavailable",R=>{R.data.size>0&&(i.push(R.data),l+=R.data.size,m())}),t.addEventListener("stop",()=>{E.getTracks().forEach(R=>R.stop()),y(new Blob(i,{type:o||"video/webm"}))},{once:!0}),t.addEventListener("error",R=>{E.getTracks().forEach(D=>D.stop()),b(R.error??R)},{once:!0}),t.start(1e3),m()},stop(){if(!t)return Promise.resolve(s);if(t.state==="inactive")return u??Promise.resolve(s);const x=u??new Promise(M=>{d=M});return t.stop(),m(),x},clear(){if(t?.state==="recording")throw new Error("Cannot clear a recording while recording is in progress");s=null,i=[],l=0,r=0,c=null,m()},getRecording(){return s},getStatus(){return _()},subscribe(x){return g.add(x),x(_()),()=>{g.delete(x)}},recordRange(x={}){const M=v(),C=M.player.getState();(x.restorePlaybackState??!0)&&(p=C);const w=x.playbackRate??C.speed,E=x.startTime??C.currentTime;h=x.endTime??C.duration,f=!0,M.player.setState({currentTime:E,speed:w,playing:!1}),T.start(x);const R=u;return M.player.play(),(R??Promise.resolve(null)).then(D=>{if(!D)throw new Error("Recording stopped without producing a video");return D})},recordFullReplay(x={}){return T.recordRange({...x,startTime:x.startTime??0,endTime:x.endTime??v().replay.duration})}};return T}const Sv="subtr-actor-timeline-overlay-styles";function ON(){if(document.getElementById(Sv))return;const n=document.createElement("style");n.id=Sv,n.textContent=` + `;const g=document.createElement("span");g.append("Render "),a=document.createElement("span"),a.style.color="#7fd4ff",a.textContent="– fps",g.append(a);const _=document.createElement("span");_.append("Replay "),r=document.createElement("span"),r.style.color="#9affc0",r.textContent="– fps",_.append(r),s.append(g,_),f?f.appendChild(s):(getComputedStyle(h.container).position==="static"&&(h.container.style.position="relative"),h.container.appendChild(s))},beforeRender(h){o+=1,u=h.frameIndex;const f=performance.now(),p=f-l;if(pxN(u,i,s,a,n.currentTime))}}function Tu(n){return{...n,setup:n.setup?e=>{n.setup?.(Vm(e,n.id))}:void 0,onStateChange:n.onStateChange?e=>{n.onStateChange?.(BT(e,n.id))}:void 0,beforeRender:n.beforeRender?e=>{n.beforeRender?.(wN(e,n.id))}:void 0,teardown:n.teardown?e=>{n.teardown?.(Vm(e,n.id))}:void 0}}const SN=255;function rf(n){return n==null?null:n*100/SN}const TN=1.35,MN="#57a8ff",EN="#ff9c40",CN=256,AN=160,RN=360,PN=225,IN=260,LN=430,zT=18,Rv=120;function kN(n){return n?MN:EN}function DN(n){return n.events.filter(e=>!e.available&&e.playerId)}function HT(n,e){const t=document.createElement("canvas");t.width=CN,t.height=AN;const i=t.getContext("2d");if(!i)throw new Error("Unable to create boost pickup count canvas");i.clearRect(0,0,t.width,t.height),i.textAlign="center",i.textBaseline="middle",i.lineJoin="round",i.font="800 124px sans-serif",i.lineWidth=18,i.strokeStyle="rgba(4, 10, 18, 0.88)",i.strokeText(`${n}`,t.width/2,t.height/2),i.fillStyle=e,i.fillText(`${n}`,t.width/2,t.height/2);const s=new dc(t);return s.colorSpace=gt,s.needsUpdate=!0,s}function ON(n){n?.dispose()}function FN(n){const e=new Mt;e.visible=!1,e.renderOrder=60,e.frustumCulled=!1;const t=HT(1,n),i=new Nh({map:t,transparent:!0,depthTest:!1,depthWrite:!1}),s=new Uh(i);s.scale.set(RN,PN,1),s.renderOrder=62,s.frustumCulled=!1,e.add(s);const a=new Ye({color:n,transparent:!0,opacity:0,side:ct,depthTest:!1,depthWrite:!1,blending:Ht}),r=new we(new ni(Rv*.72,Rv,36),a);return r.position.z=zT,r.renderOrder=61,r.frustumCulled=!1,e.add(r),{group:e,textMaterial:i,ringMaterial:a}}function NN(n,e){n.currentCount!==e&&(ON(n.textMaterial.map),n.textMaterial.map=HT(e,n.color),n.textMaterial.needsUpdate=!0,n.currentCount=e)}function UN(n){const e=new Map;for(const s of n.replay.players)e.set(s.id,s);const t=[];for(const s of n.replay.boostPads)for(const a of DN(s))t.push({pad:s,event:a});t.sort((s,a)=>s.event.time!==a.event.time?s.event.time-a.event.time:s.event.frame!==a.event.frame?s.event.frame-a.event.frame:s.pad.index-a.pad.index);const i=[];for(const{pad:s,event:a}of t){if(!a.playerId)continue;const r=e.get(a.playerId);if(!r)continue;const o=kN(r.isTeamZero),{group:l,textMaterial:c,ringMaterial:u}=FN(o);l.position.copy(s.position),n.scene.replayRoot.add(l),i.push({time:a.time,pad:s,event:a,player:r,color:o,currentCount:1,position:new S(s.position.x,s.position.y,s.position.z),size:s.size,group:l,textMaterial:c,ringMaterial:u})}return i}function BN(n,e,t){const i=vt.clamp(e/t,0,1),s=1-Math.pow(1-i,3),a=i*i,r=n.size==="big"?LN:IN,o=n.size==="big"?360:280,l=1+Math.sin(i*Math.PI)*.22;n.group.visible=!0,n.group.position.set(n.position.x,n.position.y,n.position.z+r+s*o),n.group.scale.setScalar(l),n.textMaterial.opacity=Math.max(0,1-a),n.ringMaterial.opacity=Math.max(0,.48*(1-i));const c=n.group.children[1];if(c){const u=.75+s*(n.size==="big"?2.8:1.85);c.scale.setScalar(u),c.position.z=zT-r-s*o}}function zN(n={}){const e=Math.max(.1,n.durationSeconds??TN);let t=[];function i(a){return n.includePickup?.({pad:a.pad,event:a.event,player:a.player})??!0}function s(){for(const a of t)a.group.visible=!1}return{id:"boost-pickup-animation",setup(a){t=UN(a)},beforeRender(a){if(!a.state.boostPickupAnimationEnabled){s();return}const r=a.currentTime-e,o=new Map;for(const l of t){if(l.time>a.currentTime){l.group.visible=!1;continue}if(!i(l)){l.group.visible=!1;continue}const c=(o.get(l.player.id)??0)+1;if(o.set(l.player.id,c),l.time{(r instanceof we||r instanceof Uh)&&r.geometry?.dispose()}),a.textMaterial.map?.dispose(),a.textMaterial.dispose(),a.ringMaterial.dispose();t=[]}}}const HN=60,VN=["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"];function GN(n){if(n&&MediaRecorder.isTypeSupported(n))return n;for(const e of VN)if(MediaRecorder.isTypeSupported(e))return e;return""}function $N(n){return n instanceof Error?n.message:String(n)}function WN(n={}){let e=null,t=null,i=[],s=null,a=0,r=0,o="",l=0,c=null,u=null,d=null,h=null,f=!1,p=null;const g=new Set;function _(){return{state:t?t.state==="recording"?"recording":"stopping":c?"error":s?"ready":"idle",elapsedSeconds:r,mimeType:o,sizeBytes:l,error:c}}function m(){const x=_();n.onStatusChange?.(x);for(const M of g)M(x)}function v(){if(!e)throw new Error("Canvas recorder plugin is not installed");return e}function y(x){t=null,h=null,f=!1,s=x,l=x?.size??0,p&&e&&e.player.setState({currentTime:p.currentTime,speed:p.speed,playing:p.playing}),p=null,x&&n.onComplete?.(x),m(),d?.(x),d=null,u=null}function b(x){c=$N(x),t=null,h=null,f=!1,p=null,m(),d?.(null),d=null,u=null}const T={id:"canvas-recorder",setup(x){e=x},beforeRender(x){t?.state==="recording"&&(r=(performance.now()-a)/1e3,m()),t?.state==="recording"&&h!==null&&x.currentTime>=h&&T.stop()},onStateChange(x){f&&t?.state==="recording"&&!x.state.playing&&r>0&&T.stop()},teardown(){t?.state==="recording"&&t.stop(),e=null,t=null,h=null,f=!1,p=null,d?.(null),d=null,u=null,g.clear()},start(x={}){const M=v();if(t?.state==="recording")throw new Error("Canvas recording is already in progress");if(typeof MediaRecorder>"u")throw new Error("MediaRecorder is not available in this browser");const C=M.scene.renderer.domElement;if(!C.captureStream)throw new Error("Canvas captureStream is not available in this browser");c=null,s=null,i=[],l=0,r=0,a=performance.now(),o=GN(x.mimeType??n.mimeType);const w=Math.max(1,x.fps??n.fps??HN),E=C.captureStream(w);t=new MediaRecorder(E,{mimeType:o,videoBitsPerSecond:x.videoBitsPerSecond??n.videoBitsPerSecond}),u=new Promise(R=>{d=R}),t.addEventListener("dataavailable",R=>{R.data.size>0&&(i.push(R.data),l+=R.data.size,m())}),t.addEventListener("stop",()=>{E.getTracks().forEach(R=>R.stop()),y(new Blob(i,{type:o||"video/webm"}))},{once:!0}),t.addEventListener("error",R=>{E.getTracks().forEach(k=>k.stop()),b(R.error??R)},{once:!0}),t.start(1e3),m()},stop(){if(!t)return Promise.resolve(s);if(t.state==="inactive")return u??Promise.resolve(s);const x=u??new Promise(M=>{d=M});return t.stop(),m(),x},clear(){if(t?.state==="recording")throw new Error("Cannot clear a recording while recording is in progress");s=null,i=[],l=0,r=0,c=null,m()},getRecording(){return s},getStatus(){return _()},subscribe(x){return g.add(x),x(_()),()=>{g.delete(x)}},recordRange(x={}){const M=v(),C=M.player.getState();(x.restorePlaybackState??!0)&&(p=C);const w=x.playbackRate??C.speed,E=x.startTime??C.currentTime;h=x.endTime??C.duration,f=!0,M.player.setState({currentTime:E,speed:w,playing:!1}),T.start(x);const R=u;return M.player.play(),(R??Promise.resolve(null)).then(k=>{if(!k)throw new Error("Recording stopped without producing a video");return k})},recordFullReplay(x={}){return T.recordRange({...x,startTime:x.startTime??0,endTime:x.endTime??v().replay.duration})}};return T}const Pv="subtr-actor-timeline-overlay-styles";function XN(){if(document.getElementById(Pv))return;const n=document.createElement("style");n.id=Pv,n.textContent=` .sap-tl-root { position: absolute; inset: 0; @@ -4411,8 +4411,8 @@ void main() { font-size: 0.72rem; } } - `,document.head.append(n)}const FN=new Set(["goal","save","bookmark"]),NN=.2,Mp=60,UN=2,BN=4,zN=.01,Tv=.01;function Fm(n){if(!Number.isFinite(n))return"--:--.--";const e=Math.max(0,n),t=Math.floor(e/60),i=Math.floor(e%60),s=Math.floor((e-Math.floor(e))*100);return`${t}:${String(i).padStart(2,"0")}.${String(s).padStart(2,"0")}`}function Mv(n){switch(n.kind){case"goal":return 5;case"demo":return 4;case"save":return 3;case"assist":return 2;case"shot":case"bookmark":return 1;default:return 0}}function HN(n){switch(n.kind){case"goal":case"goal-context":case"goal-tag":return BN;default:return UN}}function Pg(n){return n.seekTime!==void 0&&Number.isFinite(n.seekTime)?Math.max(0,n.seekTime):Number.isFinite(n.time)?Math.max(0,n.time-HN(n)):0}function VN(n){if(n.color)return n.color;if(n.isTeamZero===!0)return"#3b82f6";if(n.isTeamZero===!1)return"#f59e0b";switch(n.kind){case"goal":return"#f5f7fa";case"demo":return"#ef4444";case"save":return"#34d399";case"assist":return"#c084fc";case"shot":return"#60a5fa";case"bookmark":return"#facc15";default:return"#d1d9e0"}}function GN(n){if(n.events.length>1)return`${n.events.length}`;const e=n.events[0];return e?e.shortLabel&&e.shortLabel.trim()!==""?e.shortLabel.slice(0,3).toUpperCase():e.kind.slice(0,1).toUpperCase():""}function Nm(n){return[...n].sort((e,t)=>{const i=Mv(t)-Mv(e);return i!==0?i:e.time-t.time})}function $N(n){return n.events.map(e=>`${Fm(e.time)} ${e.label??e.kind}`).join(` -`)}function kT(n){const e=new Map;for(const t of n){const i=t.frame!==void 0?`frame:${t.frame}`:`time:${t.time.toFixed(2)}`,s=e.get(i);if(s){s.events.push(t);continue}e.set(i,{key:i,time:t.time,events:[t]})}return[...e.values()].map(t=>({...t,events:Nm(t.events)})).sort((t,i)=>t.time-i.time)}function Ev(n){if(n.length<=Mp)return n;const e=n[0]?.time??0,i=(n[n.length-1]?.time??e)-e;if(i<=0)return[{key:"compact:0",time:e,events:Nm(n.flatMap(r=>r.events))}];const s=i/Mp,a=new Map;for(const r of n){const o=Math.min(Mp-1,Math.max(0,Math.floor((r.time-e)/s))),l=a.get(o);if(l){l.events.push(...r.events);continue}a.set(o,{key:`compact:${o}`,time:r.time,events:[...r.events]})}return[...a.values()].map(r=>({...r,events:Nm(r.events)})).sort((r,o)=>r.time-o.time)}function OT(n,e){return n?typeof n=="function"?n(e):n:[]}function WN(n,e){const t=[];for(const i of n){const s=OT(i.source,e);s.length!==0&&t.push({key:i.key,label:i.label,buckets:kT(s)})}return t}function XN(n,e){return n?typeof n=="function"?n(e):n:[]}function KN(n,e){const t=new Set,i=[];for(const s of n)for(const a of XN(s,e)){const r=a.id;if(r!==void 0){if(t.has(r))continue;t.add(r)}i.push(a)}return i}function qN(n){const e=new Map;for(const t of n){const i=t.lane??"default",s=t.laneLabel??t.lane??"",a=e.get(i);if(a){a.ranges.push(t);continue}e.set(i,{key:i,label:s,ranges:[t]})}return[...e.values()].map(t=>({...t,ranges:[...t.ranges].sort((i,s)=>i.startTime-s.startTime)}))}function YN(n){return n.color?n.color:n.isTeamZero===!0?"#3b82f6":n.isTeamZero===!1?"#f59e0b":"#d1d9e0"}function jN(n,e){if(n.replayEvents)return OT(n.replayEvents,e);if(n.includeReplayEvents===!1)return[];const t=new Set(n.replayEventKinds??FN);return e.replay.timelineEvents.filter(i=>t.has(i.kind))}function ZN(n,e){const t=e.player.projectReplayTimeToTimeline(Pg(n));if(!t.hiddenBySkip)return t.seekTime;const i=Math.min(e.player.getTimelineDuration(),t.timelineTime+zN);return e.player.projectTimelineTimeToReplay(i)}function xu(n,e){return`${n/Math.max(e,1e-4)*100}%`}function JN(n,e,t){let i=n.timelineTime,s=e.timelineTime;return s<=i&&(n.hiddenBySkip||e.hiddenBySkip)&&(i>=t?(i=Math.max(0,t-Tv),s=t):s=Math.min(t,i+Tv)),{startTimelineTime:i,endTimelineTime:s}}function QN(n={}){const e=n.pauseWhileScrubbing??!0;let t=0;const i=n.events?[{key:"events:initial",label:n.eventsLabel??"Events",source:n.events}]:[],s=n.ranges?[n.ranges]:[];let a=null,r=null,o=null,l=null,c=null,u=null,d=null,h=null,f=null,p=null,g=null,_=null,m=!1,v="",y=!1,b=!1,T=null,x=[],M=[],C=null;const w=new Map,E=[],R=[],D=[],O=[];let k=0,U=new Set;function F(){T&&(ke(T),H({...T,state:T.player.getState()}))}function W(){T&&(Z(T),H({...T,state:T.player.getState()}))}function H(X){if(!l||!c||!u||!d||!h||!f||!r)return;const ie=X.player.getTimelineCurrentTime(),xe=X.player.getTimelineDuration(),Ae=[xe.toFixed(4),X.state.skipKickoffsEnabled?"1":"0",X.state.skipPostGoalTransitionsEnabled?"1":"0"].join(":");C!==Ae&&(ke(X),Z(X),C=Ae),l.min="0",l.max=`${xe}`,l.step="0.01",l.value=`${Math.min(ie,xe)}`,c.dataset.playing=X.state.playing?"true":"false",c.setAttribute("aria-label",X.state.playing?"Pause replay":"Play replay"),c.title=X.state.playing?"Pause replay":"Play replay",u.textContent=X.state.playing?"||":">",d.textContent=X.state.playing?"Pause":"Play",h.textContent=Fm(ie),f.textContent=`-${Fm(xe-ie)}`,r.dataset.scrubbing=y?"true":"false",De(ie);for(const G of R){const j=Math.max(0,G.startTimelineTime),Y=Math.min(xe,G.endTimelineTime);if(Math.max(0,Y-j)<=1e-4){G.element.hidden=!0;continue}G.element.hidden=!1,G.element.dataset.active=ie>=j&&ie<=Y?"true":"false"}const L=xu(Math.min(ie,xe),xe);for(const G of O)G.element.style.left=L;for(const G of D)G.element.style.left=L}function ne(X){let ie=0,xe=E.length;for(;iek)for(let G=k;G{ie.player.seek(ZN(Ae,ie))}),G.dataset.active="false",G.dataset.passed="false";const j={element:G,timelineTime:L.timelineTime,active:!1,passed:!1};return w.set(X.key,j),E.push(j),G}function ke(X){if(!g||!p)return;g.replaceChildren(),p.replaceChildren(),w.clear(),E.splice(0,E.length),k=0,U=new Set,O.splice(0,O.length);const ie=jN(n,X);x=[],ie.length>0&&x.push({key:"replay",label:n.replayEventsLabel??"Replay",buckets:kT(ie)}),x.push(...WN(i,X));const xe=Math.max(X.player.getTimelineDuration(),1e-4),Ae=x[0];if(Ae?.key==="replay")for(const G of Ev(Ae.buckets)){const j=Xe({...G,key:`${Ae.key}:${G.key}`},X,xe);j&&g.append(j)}const L=x.filter(G=>G.key!=="replay");p.hidden=L.length===0;for(const G of L){const j=document.createElement("div");j.className="sap-tl-event-lane",j.dataset.label=G.label;const Y=document.createElement("span");Y.className="sap-tl-event-lane-label",Y.textContent=G.label,Y.setAttribute("aria-label",G.label),j.append(Y);const Q=document.createElement("div");Q.className="sap-tl-event-lane-track";const _e=document.createElement("div");_e.className="sap-tl-markers";for(const ge of Ev(G.buckets)){const $e=Xe({...ge,key:`${G.key}:${ge.key}`},X,xe);$e&&_e.append($e)}const ce=document.createElement("div");ce.className="sap-tl-event-playhead",Q.append(_e,ce),O.push({element:ce}),j.append(Q),p.append(j)}E.sort((G,j)=>G.timelineTime-j.timelineTime)}function Z(X){if(!o)return;o.replaceChildren(),R.splice(0,R.length),D.splice(0,D.length);const ie=KN(s,X).filter(Ae=>Number.isFinite(Ae.startTime)&&Number.isFinite(Ae.endTime)&&Ae.endTime>Ae.startTime);M=qN(ie);const xe=Math.max(X.player.getTimelineDuration(),1e-4);if(M.length===0){o.hidden=!0;return}o.hidden=!1;for(const Ae of M){const L=document.createElement("div");L.className="sap-tl-range-lane";const G=document.createElement("div");if(G.className="sap-tl-range-lane-track",Ae.label){L.dataset.label=Ae.label;const Y=document.createElement("span");Y.className="sap-tl-range-lane-label",Y.textContent=Ae.label,Y.setAttribute("aria-label",Ae.label),L.append(Y)}for(const Y of Ae.ranges){const Q=X.player.projectReplayTimeToTimeline(Y.startTime),_e=X.player.projectReplayTimeToTimeline(Y.endTime),{startTimelineTime:ce,endTimelineTime:ge}=JN(Q,_e,xe),$e=document.createElement("div");$e.className="sap-tl-range-segment",Y.className&&$e.classList.add(Y.className),$e.style.background=YN(Y),$e.title=Y.label??Ae.label,$e.dataset.active="false",$e.style.left=xu(ce,xe),$e.style.width=xu(Math.max(0,ge-ce),xe),G.append($e),R.push({range:Y,element:$e,startTimelineTime:ce,endTimelineTime:ge})}const j=document.createElement("div");j.className="sap-tl-range-playhead",G.append(j),D.push({element:j}),L.append(G),o.append(L)}}function se(){y&&(y=!1,r?.setAttribute("data-scrubbing","false"),b&&T?.player.play(),b=!1)}function Se(){if(y||(y=!0,r?.setAttribute("data-scrubbing","true"),!e))return;const X=T?.player;X&&(b=X.getState().playing,b&&X.pause())}return{id:"timeline-overlay",addEventSource(X,ie={}){return i.push({key:ie.id??`events:${t++}`,label:ie.label??"Events",source:X}),F(),()=>{this.removeEventSource(X)}},removeEventSource(X){const ie=i.findIndex(xe=>xe.source===X);return ie<0?!1:(i.splice(ie,1),F(),!0)},refreshEvents(){F()},addRangeSource(X){return s.push(X),W(),()=>{this.removeRangeSource(X)}},removeRangeSource(X){const ie=s.indexOf(X);return ie<0?!1:(s.splice(ie,1),W(),!0)},refreshRanges(){W()},setup(X){T=X,ON(),getComputedStyle(X.container).position==="static"&&(m=!0,v=X.container.style.position,X.container.style.position="relative"),a=document.createElement("div"),a.className="sap-tl-root",r=document.createElement("div"),r.className="sap-tl-shell",r.dataset.scrubbing="false";const ie=document.createElement("div");ie.className="sap-tl-topline";const xe=document.createElement("div");xe.className="sap-tl-primary",c=document.createElement("button"),c.type="button",c.className="sap-tl-toggle sap-tl-track-toggle",u=document.createElement("span"),u.className="sap-tl-toggle-icon",u.setAttribute("aria-hidden","true"),u.textContent=">",d=document.createElement("span"),d.className="sap-tl-toggle-label",d.textContent="Play",c.append(u,d),c.addEventListener("click",()=>{X.player.togglePlayback()}),h=document.createElement("span"),h.className="sap-tl-current",h.textContent="0:00.00",f=document.createElement("span"),f.className="sap-tl-remaining",f.textContent="-0:00.00",xe.append(h),ie.append(xe,f);const Ae=document.createElement("div");Ae.className="sap-tl-track-wrap",o=document.createElement("div"),o.className="sap-tl-ranges",o.hidden=!0,p=document.createElement("div"),p.className="sap-tl-event-lanes",p.hidden=!0;const L=document.createElement("div");L.className="sap-tl-track-rail";const G=document.createElement("div");G.className="sap-tl-main-rail",g=document.createElement("div"),g.className="sap-tl-markers",l=document.createElement("input"),l.className="sap-tl-range",l.type="range",l.min="0",l.max=`${X.replay.duration}`,l.step="0.01",l.value="0";const j=()=>{Se()},Y=()=>{l&&X.player.seek(X.player.projectTimelineTimeToReplay(Number(l.value)))},Q=()=>{se()};l.addEventListener("pointerdown",j),l.addEventListener("input",Y),l.addEventListener("change",Q),window.addEventListener("pointerup",Q),window.addEventListener("pointercancel",Q),_=()=>{l?.removeEventListener("pointerdown",j),l?.removeEventListener("input",Y),l?.removeEventListener("change",Q),window.removeEventListener("pointerup",Q),window.removeEventListener("pointercancel",Q)},L.append(G,g,l),Ae.append(o,p,c,L),r.append(ie,Ae),a.append(r),X.container.append(a),ke(X),Z(X),H({...X,state:X.player.getState()})},onStateChange(X){T=X,H(X)},teardown(X){_?.(),_=null,se(),a?.remove(),a=null,r=null,o=null,p=null,l=null,c=null,u=null,d=null,h=null,f=null,g=null,T=null,x=[],M=[],C=null,w.clear(),E.splice(0,E.length),R.splice(0,R.length),D.splice(0,D.length),O.splice(0,O.length),k=0,U=new Set,m&&(X.container.style.position=v,m=!1)}}}function e3(n,e,t={}){const i=new xw(e.raw,{motionSmoothing:t.motionSmoothing,smoothingBlendFactor:t.smoothingBlendFactor,smoothingAnchorInterval:t.smoothingAnchorInterval,timelineCompaction:t.timelineCompaction,disableFrameFiltering:t.disableFrameFiltering}),s=new eN(n,i,t,e.replay);return s.getPlugins().some(a=>a.id==="camera")||s.addPlugin(oN()),s}const t3="https://ballchasing.com",n3=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function i3(n,e){const i=(e instanceof URL?e.href:e).replace(/\/+$/,"");return new URL(`${i}/${n.replace(/^\/+/,"")}`)}function Cv(n){return n3.test(n.trim())}function Ig(n){const e=n.trim();if(Cv(e))return e.toLowerCase();let t;try{t=new URL(e)}catch{throw new Error(`Invalid Ballchasing replay id: ${n}`)}if(!/(^|\.)ballchasing\.com$/i.test(t.hostname))throw new Error(`Invalid Ballchasing replay URL: ${n}`);const i=t.pathname.split("/").filter(Boolean),s=i.findIndex(o=>o==="replay"),a=i.findIndex(o=>o==="replays"),r=s>=0?i[s+1]:a>=0?i[a+1]:void 0;if(!r||!Cv(r))throw new Error(`Invalid Ballchasing replay URL: ${n}`);return r.toLowerCase()}function s3(n){return`ballchasing-${Ig(n)}.replay`}function a3(n,e=t3){const t=Ig(n);return i3(`dl/replay/${encodeURIComponent(t)}`,e)}const Um=250,Av="subtr-actor-ballchasing-overlay-styles",Ep="#3b82f6",Rv="#f59e0b";function r3(){if(document.getElementById(Av))return;const n=document.createElement("style");n.id=Av,n.textContent=` + `,document.head.append(n)}const KN=new Set(["goal","save","bookmark"]),qN=.2,Ip=60,YN=2,jN=4,ZN=.01,Iv=.01;function Gm(n){if(!Number.isFinite(n))return"--:--.--";const e=Math.max(0,n),t=Math.floor(e/60),i=Math.floor(e%60),s=Math.floor((e-Math.floor(e))*100);return`${t}:${String(i).padStart(2,"0")}.${String(s).padStart(2,"0")}`}function Lv(n){switch(n.kind){case"goal":return 5;case"demo":return 4;case"save":return 3;case"assist":return 2;case"shot":case"bookmark":return 1;default:return 0}}function JN(n){switch(n.kind){case"goal":case"goal-context":case"goal-tag":return jN;default:return YN}}function Ng(n){return n.seekTime!==void 0&&Number.isFinite(n.seekTime)?Math.max(0,n.seekTime):Number.isFinite(n.time)?Math.max(0,n.time-JN(n)):0}function QN(n){if(n.color)return n.color;if(n.isTeamZero===!0)return"#3b82f6";if(n.isTeamZero===!1)return"#f59e0b";switch(n.kind){case"goal":return"#f5f7fa";case"demo":return"#ef4444";case"save":return"#34d399";case"assist":return"#c084fc";case"shot":return"#60a5fa";case"bookmark":return"#facc15";default:return"#d1d9e0"}}function e3(n){if(n.events.length>1)return`${n.events.length}`;const e=n.events[0];return e?e.shortLabel&&e.shortLabel.trim()!==""?e.shortLabel.slice(0,3).toUpperCase():e.kind.slice(0,1).toUpperCase():""}function $m(n){return[...n].sort((e,t)=>{const i=Lv(t)-Lv(e);return i!==0?i:e.time-t.time})}function t3(n){return n.events.map(e=>`${Gm(e.time)} ${e.label??e.kind}`).join(` +`)}function VT(n){const e=new Map;for(const t of n){const i=t.frame!==void 0?`frame:${t.frame}`:`time:${t.time.toFixed(2)}`,s=e.get(i);if(s){s.events.push(t);continue}e.set(i,{key:i,time:t.time,events:[t]})}return[...e.values()].map(t=>({...t,events:$m(t.events)})).sort((t,i)=>t.time-i.time)}function kv(n){if(n.length<=Ip)return n;const e=n[0]?.time??0,i=(n[n.length-1]?.time??e)-e;if(i<=0)return[{key:"compact:0",time:e,events:$m(n.flatMap(r=>r.events))}];const s=i/Ip,a=new Map;for(const r of n){const o=Math.min(Ip-1,Math.max(0,Math.floor((r.time-e)/s))),l=a.get(o);if(l){l.events.push(...r.events);continue}a.set(o,{key:`compact:${o}`,time:r.time,events:[...r.events]})}return[...a.values()].map(r=>({...r,events:$m(r.events)})).sort((r,o)=>r.time-o.time)}function GT(n,e){return n?typeof n=="function"?n(e):n:[]}function n3(n,e){const t=[];for(const i of n){const s=GT(i.source,e);s.length!==0&&t.push({key:i.key,label:i.label,buckets:VT(s)})}return t}function i3(n,e){return n?typeof n=="function"?n(e):n:[]}function s3(n,e){const t=new Set,i=[];for(const s of n)for(const a of i3(s,e)){const r=a.id;if(r!==void 0){if(t.has(r))continue;t.add(r)}i.push(a)}return i}function a3(n){const e=new Map;for(const t of n){const i=t.lane??"default",s=t.laneLabel??t.lane??"",a=e.get(i);if(a){a.ranges.push(t);continue}e.set(i,{key:i,label:s,ranges:[t]})}return[...e.values()].map(t=>({...t,ranges:[...t.ranges].sort((i,s)=>i.startTime-s.startTime)}))}function r3(n){return n.color?n.color:n.isTeamZero===!0?"#3b82f6":n.isTeamZero===!1?"#f59e0b":"#d1d9e0"}function o3(n,e){if(n.replayEvents)return GT(n.replayEvents,e);if(n.includeReplayEvents===!1)return[];const t=new Set(n.replayEventKinds??KN);return e.replay.timelineEvents.filter(i=>t.has(i.kind))}function l3(n,e){const t=e.player.projectReplayTimeToTimeline(Ng(n));if(!t.hiddenBySkip)return t.seekTime;const i=Math.min(e.player.getTimelineDuration(),t.timelineTime+ZN);return e.player.projectTimelineTimeToReplay(i)}function Mu(n,e){return`${n/Math.max(e,1e-4)*100}%`}function c3(n,e,t){let i=n.timelineTime,s=e.timelineTime;return s<=i&&(n.hiddenBySkip||e.hiddenBySkip)&&(i>=t?(i=Math.max(0,t-Iv),s=t):s=Math.min(t,i+Iv)),{startTimelineTime:i,endTimelineTime:s}}function u3(n={}){const e=n.pauseWhileScrubbing??!0;let t=0;const i=n.events?[{key:"events:initial",label:n.eventsLabel??"Events",source:n.events}]:[],s=n.ranges?[n.ranges]:[];let a=null,r=null,o=null,l=null,c=null,u=null,d=null,h=null,f=null,p=null,g=null,_=null,m=!1,v="",y=!1,b=!1,T=null,x=[],M=[],C=null;const w=new Map,E=[],R=[],k=[],O=[];let D=0,U=new Set;function F(){T&&(De(T),H({...T,state:T.player.getState()}))}function W(){T&&(Z(T),H({...T,state:T.player.getState()}))}function H(X){if(!l||!c||!u||!d||!h||!f||!r)return;const ie=X.player.getTimelineCurrentTime(),xe=X.player.getTimelineDuration(),Ae=[xe.toFixed(4),X.state.skipKickoffsEnabled?"1":"0",X.state.skipPostGoalTransitionsEnabled?"1":"0"].join(":");C!==Ae&&(De(X),Z(X),C=Ae),l.min="0",l.max=`${xe}`,l.step="0.01",l.value=`${Math.min(ie,xe)}`,c.dataset.playing=X.state.playing?"true":"false",c.setAttribute("aria-label",X.state.playing?"Pause replay":"Play replay"),c.title=X.state.playing?"Pause replay":"Play replay",u.textContent=X.state.playing?"||":">",d.textContent=X.state.playing?"Pause":"Play",h.textContent=Gm(ie),f.textContent=`-${Gm(xe-ie)}`,r.dataset.scrubbing=y?"true":"false",ke(ie);for(const G of R){const j=Math.max(0,G.startTimelineTime),Y=Math.min(xe,G.endTimelineTime);if(Math.max(0,Y-j)<=1e-4){G.element.hidden=!0;continue}G.element.hidden=!1,G.element.dataset.active=ie>=j&&ie<=Y?"true":"false"}const L=Mu(Math.min(ie,xe),xe);for(const G of O)G.element.style.left=L;for(const G of k)G.element.style.left=L}function ne(X){let ie=0,xe=E.length;for(;ieD)for(let G=D;G{ie.player.seek(l3(Ae,ie))}),G.dataset.active="false",G.dataset.passed="false";const j={element:G,timelineTime:L.timelineTime,active:!1,passed:!1};return w.set(X.key,j),E.push(j),G}function De(X){if(!g||!p)return;g.replaceChildren(),p.replaceChildren(),w.clear(),E.splice(0,E.length),D=0,U=new Set,O.splice(0,O.length);const ie=o3(n,X);x=[],ie.length>0&&x.push({key:"replay",label:n.replayEventsLabel??"Replay",buckets:VT(ie)}),x.push(...n3(i,X));const xe=Math.max(X.player.getTimelineDuration(),1e-4),Ae=x[0];if(Ae?.key==="replay")for(const G of kv(Ae.buckets)){const j=Xe({...G,key:`${Ae.key}:${G.key}`},X,xe);j&&g.append(j)}const L=x.filter(G=>G.key!=="replay");p.hidden=L.length===0;for(const G of L){const j=document.createElement("div");j.className="sap-tl-event-lane",j.dataset.label=G.label;const Y=document.createElement("span");Y.className="sap-tl-event-lane-label",Y.textContent=G.label,Y.setAttribute("aria-label",G.label),j.append(Y);const Q=document.createElement("div");Q.className="sap-tl-event-lane-track";const _e=document.createElement("div");_e.className="sap-tl-markers";for(const ge of kv(G.buckets)){const $e=Xe({...ge,key:`${G.key}:${ge.key}`},X,xe);$e&&_e.append($e)}const ce=document.createElement("div");ce.className="sap-tl-event-playhead",Q.append(_e,ce),O.push({element:ce}),j.append(Q),p.append(j)}E.sort((G,j)=>G.timelineTime-j.timelineTime)}function Z(X){if(!o)return;o.replaceChildren(),R.splice(0,R.length),k.splice(0,k.length);const ie=s3(s,X).filter(Ae=>Number.isFinite(Ae.startTime)&&Number.isFinite(Ae.endTime)&&Ae.endTime>Ae.startTime);M=a3(ie);const xe=Math.max(X.player.getTimelineDuration(),1e-4);if(M.length===0){o.hidden=!0;return}o.hidden=!1;for(const Ae of M){const L=document.createElement("div");L.className="sap-tl-range-lane";const G=document.createElement("div");if(G.className="sap-tl-range-lane-track",Ae.label){L.dataset.label=Ae.label;const Y=document.createElement("span");Y.className="sap-tl-range-lane-label",Y.textContent=Ae.label,Y.setAttribute("aria-label",Ae.label),L.append(Y)}for(const Y of Ae.ranges){const Q=X.player.projectReplayTimeToTimeline(Y.startTime),_e=X.player.projectReplayTimeToTimeline(Y.endTime),{startTimelineTime:ce,endTimelineTime:ge}=c3(Q,_e,xe),$e=document.createElement("div");$e.className="sap-tl-range-segment",Y.className&&$e.classList.add(Y.className),$e.style.background=r3(Y),$e.title=Y.label??Ae.label,$e.dataset.active="false",$e.style.left=Mu(ce,xe),$e.style.width=Mu(Math.max(0,ge-ce),xe),G.append($e),R.push({range:Y,element:$e,startTimelineTime:ce,endTimelineTime:ge})}const j=document.createElement("div");j.className="sap-tl-range-playhead",G.append(j),k.push({element:j}),L.append(G),o.append(L)}}function ae(){y&&(y=!1,r?.setAttribute("data-scrubbing","false"),b&&T?.player.play(),b=!1)}function Se(){if(y||(y=!0,r?.setAttribute("data-scrubbing","true"),!e))return;const X=T?.player;X&&(b=X.getState().playing,b&&X.pause())}return{id:"timeline-overlay",addEventSource(X,ie={}){return i.push({key:ie.id??`events:${t++}`,label:ie.label??"Events",source:X}),F(),()=>{this.removeEventSource(X)}},removeEventSource(X){const ie=i.findIndex(xe=>xe.source===X);return ie<0?!1:(i.splice(ie,1),F(),!0)},refreshEvents(){F()},addRangeSource(X){return s.push(X),W(),()=>{this.removeRangeSource(X)}},removeRangeSource(X){const ie=s.indexOf(X);return ie<0?!1:(s.splice(ie,1),W(),!0)},refreshRanges(){W()},setup(X){T=X,XN(),getComputedStyle(X.container).position==="static"&&(m=!0,v=X.container.style.position,X.container.style.position="relative"),a=document.createElement("div"),a.className="sap-tl-root",r=document.createElement("div"),r.className="sap-tl-shell",r.dataset.scrubbing="false";const ie=document.createElement("div");ie.className="sap-tl-topline";const xe=document.createElement("div");xe.className="sap-tl-primary",c=document.createElement("button"),c.type="button",c.className="sap-tl-toggle sap-tl-track-toggle",u=document.createElement("span"),u.className="sap-tl-toggle-icon",u.setAttribute("aria-hidden","true"),u.textContent=">",d=document.createElement("span"),d.className="sap-tl-toggle-label",d.textContent="Play",c.append(u,d),c.addEventListener("click",()=>{X.player.togglePlayback()}),h=document.createElement("span"),h.className="sap-tl-current",h.textContent="0:00.00",f=document.createElement("span"),f.className="sap-tl-remaining",f.textContent="-0:00.00",xe.append(h),ie.append(xe,f);const Ae=document.createElement("div");Ae.className="sap-tl-track-wrap",o=document.createElement("div"),o.className="sap-tl-ranges",o.hidden=!0,p=document.createElement("div"),p.className="sap-tl-event-lanes",p.hidden=!0;const L=document.createElement("div");L.className="sap-tl-track-rail";const G=document.createElement("div");G.className="sap-tl-main-rail",g=document.createElement("div"),g.className="sap-tl-markers",l=document.createElement("input"),l.className="sap-tl-range",l.type="range",l.min="0",l.max=`${X.replay.duration}`,l.step="0.01",l.value="0";const j=()=>{Se()},Y=()=>{l&&X.player.seek(X.player.projectTimelineTimeToReplay(Number(l.value)))},Q=()=>{ae()};l.addEventListener("pointerdown",j),l.addEventListener("input",Y),l.addEventListener("change",Q),window.addEventListener("pointerup",Q),window.addEventListener("pointercancel",Q),_=()=>{l?.removeEventListener("pointerdown",j),l?.removeEventListener("input",Y),l?.removeEventListener("change",Q),window.removeEventListener("pointerup",Q),window.removeEventListener("pointercancel",Q)},L.append(G,g,l),Ae.append(o,p,c,L),r.append(ie,Ae),a.append(r),X.container.append(a),De(X),Z(X),H({...X,state:X.player.getState()})},onStateChange(X){T=X,H(X)},teardown(X){_?.(),_=null,ae(),a?.remove(),a=null,r=null,o=null,p=null,l=null,c=null,u=null,d=null,h=null,f=null,g=null,T=null,x=[],M=[],C=null,w.clear(),E.splice(0,E.length),R.splice(0,R.length),k.splice(0,k.length),O.splice(0,O.length),D=0,U=new Set,m&&(X.container.style.position=v,m=!1)}}}function d3(n,e,t={}){const i=new Rw(e.raw,{motionSmoothing:t.motionSmoothing,smoothingBlendFactor:t.smoothingBlendFactor,smoothingAnchorInterval:t.smoothingAnchorInterval,timelineCompaction:t.timelineCompaction,disableFrameFiltering:t.disableFrameFiltering}),s=new dN(n,i,t,e.replay);return s.getPlugins().some(a=>a.id==="camera")||s.addPlugin(yN()),s}const h3="https://ballchasing.com",f3=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function p3(n,e){const i=(e instanceof URL?e.href:e).replace(/\/+$/,"");return new URL(`${i}/${n.replace(/^\/+/,"")}`)}function Dv(n){return f3.test(n.trim())}function Ug(n){const e=n.trim();if(Dv(e))return e.toLowerCase();let t;try{t=new URL(e)}catch{throw new Error(`Invalid Ballchasing replay id: ${n}`)}if(!/(^|\.)ballchasing\.com$/i.test(t.hostname))throw new Error(`Invalid Ballchasing replay URL: ${n}`);const i=t.pathname.split("/").filter(Boolean),s=i.findIndex(o=>o==="replay"),a=i.findIndex(o=>o==="replays"),r=s>=0?i[s+1]:a>=0?i[a+1]:void 0;if(!r||!Dv(r))throw new Error(`Invalid Ballchasing replay URL: ${n}`);return r.toLowerCase()}function m3(n){return`ballchasing-${Ug(n)}.replay`}function _3(n,e=h3){const t=Ug(n);return p3(`dl/replay/${encodeURIComponent(t)}`,e)}const Wm=250,Ov="subtr-actor-ballchasing-overlay-styles",Lp="#3b82f6",Fv="#f59e0b";function g3(){if(document.getElementById(Ov))return;const n=document.createElement("style");n.id=Ov,n.textContent=` .sap-bc-overlay-root { position: absolute; inset: 0; @@ -4541,14 +4541,14 @@ void main() { right: calc(50% + 2.7rem); flex-direction: row; justify-content: flex-end; - border-bottom: 2px solid ${Ep}; + border-bottom: 2px solid ${Lp}; } .sap-bc-team-hud-orange { left: calc(50% + 2.7rem); flex-direction: row; justify-content: flex-start; - border-bottom: 2px solid ${Rv}; + border-bottom: 2px solid ${Fv}; } .sap-bc-hud-player { @@ -4656,7 +4656,7 @@ void main() { .sap-bc-followed-boost-ring { --sap-bc-followed-boost: 0%; - --sap-bc-followed-color: ${Ep}; + --sap-bc-followed-color: ${Lp}; position: relative; display: grid; place-items: center; @@ -4676,11 +4676,11 @@ void main() { } .sap-bc-followed-hud-blue .sap-bc-followed-boost-ring { - --sap-bc-followed-color: ${Ep}; + --sap-bc-followed-color: ${Lp}; } .sap-bc-followed-hud-orange .sap-bc-followed-boost-ring { - --sap-bc-followed-color: ${Rv}; + --sap-bc-followed-color: ${Fv}; } .sap-bc-followed-boost-value { @@ -4795,7 +4795,7 @@ void main() { font-size: 0.68rem; } } - `,document.head.append(n)}function o3(n,e){const t=n.players[e],i=t.frame?.boostAmount??0,s=t.nextFrame?.boostAmount??i;return vt.lerp(i,s,n.alpha)}function l3(n,e){const t=n.replay.players.find(h=>h.id===e);if(!t)return null;const i=fh(n.replay,n.state.currentTime),s=Math.min(i+1,n.replay.frames.length-1),a=n.replay.frames[i],r=n.replay.frames[s]??a,o=a?.time??n.state.currentTime,l=r?.time??o,c=l>o?vt.clamp((n.state.currentTime-o)/(l-o),0,1):0,u=t.frames[i]?.boostAmount??0,d=t.frames[s]?.boostAmount??u;return vt.lerp(u,d,c)}function Pv(n,e,t,i){if(!n||!e)return;const s=Math.max(0,Math.min(100,Math.round(Qh(t))));n.style.width=`${s}%`,e.textContent=`${s} ${i}`}function Iv(n,e,t,i){if(!n)return;const s=Math.max(0,Math.min(100,Math.round(Qh(e))));n.root.hidden=!1,n.root.classList.toggle("sap-bc-followed-hud-blue",i),n.root.classList.toggle("sap-bc-followed-hud-orange",!i),n.root.setAttribute("aria-label",`${t} boost ${s}`),n.ring.style.setProperty("--sap-bc-followed-boost",`${s}%`),n.value.textContent=`${s}`,n.name.textContent=t}function Lv(n,e,t,i){if(!n)return;const s=()=>{e.player.setAttachedPlayer(t)};n.classList.add("sap-bc-player-selectable"),n.tabIndex=0,n.setAttribute("role","button"),n.setAttribute("aria-label",`Follow ${i}`),n.title=`Follow ${i}`,n.addEventListener("click",s),n.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),s())})}function c3(n,e,t,i,s){if(n.getWorldPosition(s),s.add(e),s.project(t),s.z<-1||s.z>1)return!1;const a=i.clientWidth||1,r=i.clientHeight||1;return s.x=(s.x+1)*a/2,s.y=(1-s.y)*r/2,!(s.x<-80||s.x>a+80||s.y<-80||s.y>r+80)}function u3(n={}){const e=n.showFloatingNames??!0,t=n.showFloatingBoostBars??!0,i=n.showTeamBoostHud??!0,s=n.showFollowedPlayerHud??!0;let a=null,r=null,o=null,l=null,c=null,u=!1,d="";const h=new Map,f=n.floatingLiftUu,p=new S,g=new S;function _(){const b=typeof f=="function"?f():f;return typeof b=="number"&&Number.isFinite(b)?b:Um}function m(b){for(const[T,x]of h.entries()){const M=T===b;x.floatingRoot?.classList.toggle("sap-bc-player-following",M),x.teamHudEntry?.classList.toggle("sap-bc-player-following",M),x.floatingRoot?.setAttribute("aria-pressed",M?"true":"false"),x.teamHudEntry?.setAttribute("aria-pressed",M?"true":"false")}}function v(b){if(!c||!b.state.attachedPlayerId){c&&(c.root.hidden=!0);return}const T=b.replay.players.find(M=>M.id===b.state.attachedPlayerId);if(!T){c.root.hidden=!0;return}const x=l3(b,T.id);if(x===null){c.root.hidden=!0;return}Iv(c,x,T.name,T.isTeamZero)}function y(b,T){if(r3(),getComputedStyle(T).position==="static"&&(u=!0,d=T.style.position,T.style.position="relative"),a=document.createElement("div"),a.className="sap-bc-overlay-root",e||t?(r=document.createElement("div"),r.className="sap-bc-floating-layer",a.append(r)):r=null,i?(o=document.createElement("div"),o.className="sap-bc-team-hud sap-bc-team-hud-blue",l=document.createElement("div"),l.className="sap-bc-team-hud sap-bc-team-hud-orange",a.append(o,l)):(o=null,l=null),s){const x=document.createElement("div");x.className="sap-bc-followed-hud",x.hidden=!0;const M=document.createElement("div");M.className="sap-bc-followed-boost-ring";const C=document.createElement("span");C.className="sap-bc-followed-boost-value",M.append(C);const w=document.createElement("div");w.className="sap-bc-followed-meta",w.textContent="Boost";const E=document.createElement("span");E.className="sap-bc-followed-name",w.append(E),x.append(M,w),a.append(x),c={root:x,ring:M,value:C,name:E}}else c=null;for(const x of b.replay.players){let M=null,C=null,w=null,E=null;r&&(M=document.createElement("div"),M.className="sap-bc-floating-track",M.hidden=!0,(e||t)&&(C=document.createElement("div"),C.className=`sap-bc-boost-bar ${x.isTeamZero?"sap-bc-boost-bar-blue":"sap-bc-boost-bar-orange"}`,w=document.createElement("div"),w.className=`sap-bc-boost-fill ${x.isTeamZero?"sap-bc-boost-fill-blue":"sap-bc-boost-fill-orange"}`,E=document.createElement("span"),E.className="sap-bc-boost-text",C.append(w,E),M.append(C)),Lv(M,b,x.id,x.name),r.append(M));let R=null,D=null,O=null;if(i){R=document.createElement("div"),R.className="sap-bc-hud-player";const k=document.createElement("div");k.className=`sap-bc-hud-boost-bar ${x.isTeamZero?"sap-bc-boost-bar-blue":"sap-bc-boost-bar-orange"}`,D=document.createElement("div"),D.className=`sap-bc-hud-boost-fill ${x.isTeamZero?"sap-bc-boost-fill-blue":"sap-bc-boost-fill-orange"}`,O=document.createElement("span"),O.className="sap-bc-hud-boost-text",k.append(D,O),R.append(k),Lv(R,b,x.id,x.name),(x.isTeamZero?o:l)?.append(R)}h.set(x.id,{floatingRoot:M,floatingBoostFill:w,floatingBoostText:E,teamHudEntry:R,teamHudFill:D,teamHudText:O})}T.append(a),m(b.player.getState().attachedPlayerId),v({...b,state:b.player.getState()})}return{id:"ballchasing-overlay",setup(b){y(b,b.container)},onStateChange(b){m(b.state.attachedPlayerId),v(b)},teardown(b){a?.remove(),a=null,r=null,o=null,l=null,c=null,h.clear(),u&&(b.container.style.position=d,u=!1)},beforeRender(b){if(!a)return;g.copy(b.scene.camera.up).normalize().multiplyScalar(_()*(b.options.fieldScale??1));let T=!1;for(const[x,M]of b.players.entries()){const C=h.get(M.track.id);if(!C)continue;const w=o3(b,x),E=C.floatingRoot?.classList.contains("sap-bc-player-following")??!1;E&&(Iv(c,w,M.track.name,M.track.isTeamZero),T=!0),Pv(C.floatingBoostFill,C.floatingBoostText,w,M.track.name),Pv(C.teamHudFill,C.teamHudText,w,M.track.name);const R=M.mesh,D=R!==null&&M.interpolatedPosition!==null;if(C.teamHudEntry?.classList.toggle("sap-bc-hud-player-inactive",!D),!!C.floatingRoot){if(E||!D||!c3(R,g,b.scene.camera,b.container,p)){C.floatingRoot.hidden=!0;continue}C.floatingRoot.hidden=!1,C.floatingRoot.style.transform=`translate(${p.x.toFixed(1)}px, ${p.y.toFixed(1)}px) translate(-50%, -100%)`}}!T&&c&&(c.root.hidden=!0)}}}function d3(){return` + `,document.head.append(n)}function y3(n,e){const t=n.players[e],i=t.frame?.boostAmount??0,s=t.nextFrame?.boostAmount??i;return vt.lerp(i,s,n.alpha)}function v3(n,e){const t=n.replay.players.find(h=>h.id===e);if(!t)return null;const i=vh(n.replay,n.state.currentTime),s=Math.min(i+1,n.replay.frames.length-1),a=n.replay.frames[i],r=n.replay.frames[s]??a,o=a?.time??n.state.currentTime,l=r?.time??o,c=l>o?vt.clamp((n.state.currentTime-o)/(l-o),0,1):0,u=t.frames[i]?.boostAmount??0,d=t.frames[s]?.boostAmount??u;return vt.lerp(u,d,c)}function Nv(n,e,t,i){if(!n||!e)return;const s=Math.max(0,Math.min(100,Math.round(rf(t))));n.style.width=`${s}%`,e.textContent=`${s} ${i}`}function Uv(n,e,t,i){if(!n)return;const s=Math.max(0,Math.min(100,Math.round(rf(e))));n.root.hidden=!1,n.root.classList.toggle("sap-bc-followed-hud-blue",i),n.root.classList.toggle("sap-bc-followed-hud-orange",!i),n.root.setAttribute("aria-label",`${t} boost ${s}`),n.ring.style.setProperty("--sap-bc-followed-boost",`${s}%`),n.value.textContent=`${s}`,n.name.textContent=t}function Bv(n,e,t,i){if(!n)return;const s=()=>{e.player.setAttachedPlayer(t)};n.classList.add("sap-bc-player-selectable"),n.tabIndex=0,n.setAttribute("role","button"),n.setAttribute("aria-label",`Follow ${i}`),n.title=`Follow ${i}`,n.addEventListener("click",s),n.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),s())})}function b3(n,e,t,i,s){if(n.getWorldPosition(s),s.add(e),s.project(t),s.z<-1||s.z>1)return!1;const a=i.clientWidth||1,r=i.clientHeight||1;return s.x=(s.x+1)*a/2,s.y=(1-s.y)*r/2,!(s.x<-80||s.x>a+80||s.y<-80||s.y>r+80)}function x3(n={}){const e=n.showFloatingNames??!0,t=n.showFloatingBoostBars??!0,i=n.showTeamBoostHud??!0,s=n.showFollowedPlayerHud??!0;let a=null,r=null,o=null,l=null,c=null,u=!1,d="";const h=new Map,f=n.floatingLiftUu,p=new S,g=new S;function _(){const b=typeof f=="function"?f():f;return typeof b=="number"&&Number.isFinite(b)?b:Wm}function m(b){for(const[T,x]of h.entries()){const M=T===b;x.floatingRoot?.classList.toggle("sap-bc-player-following",M),x.teamHudEntry?.classList.toggle("sap-bc-player-following",M),x.floatingRoot?.setAttribute("aria-pressed",M?"true":"false"),x.teamHudEntry?.setAttribute("aria-pressed",M?"true":"false")}}function v(b){if(!c||!b.state.attachedPlayerId){c&&(c.root.hidden=!0);return}const T=b.replay.players.find(M=>M.id===b.state.attachedPlayerId);if(!T){c.root.hidden=!0;return}const x=v3(b,T.id);if(x===null){c.root.hidden=!0;return}Uv(c,x,T.name,T.isTeamZero)}function y(b,T){if(g3(),getComputedStyle(T).position==="static"&&(u=!0,d=T.style.position,T.style.position="relative"),a=document.createElement("div"),a.className="sap-bc-overlay-root",e||t?(r=document.createElement("div"),r.className="sap-bc-floating-layer",a.append(r)):r=null,i?(o=document.createElement("div"),o.className="sap-bc-team-hud sap-bc-team-hud-blue",l=document.createElement("div"),l.className="sap-bc-team-hud sap-bc-team-hud-orange",a.append(o,l)):(o=null,l=null),s){const x=document.createElement("div");x.className="sap-bc-followed-hud",x.hidden=!0;const M=document.createElement("div");M.className="sap-bc-followed-boost-ring";const C=document.createElement("span");C.className="sap-bc-followed-boost-value",M.append(C);const w=document.createElement("div");w.className="sap-bc-followed-meta",w.textContent="Boost";const E=document.createElement("span");E.className="sap-bc-followed-name",w.append(E),x.append(M,w),a.append(x),c={root:x,ring:M,value:C,name:E}}else c=null;for(const x of b.replay.players){let M=null,C=null,w=null,E=null;r&&(M=document.createElement("div"),M.className="sap-bc-floating-track",M.hidden=!0,(e||t)&&(C=document.createElement("div"),C.className=`sap-bc-boost-bar ${x.isTeamZero?"sap-bc-boost-bar-blue":"sap-bc-boost-bar-orange"}`,w=document.createElement("div"),w.className=`sap-bc-boost-fill ${x.isTeamZero?"sap-bc-boost-fill-blue":"sap-bc-boost-fill-orange"}`,E=document.createElement("span"),E.className="sap-bc-boost-text",C.append(w,E),M.append(C)),Bv(M,b,x.id,x.name),r.append(M));let R=null,k=null,O=null;if(i){R=document.createElement("div"),R.className="sap-bc-hud-player";const D=document.createElement("div");D.className=`sap-bc-hud-boost-bar ${x.isTeamZero?"sap-bc-boost-bar-blue":"sap-bc-boost-bar-orange"}`,k=document.createElement("div"),k.className=`sap-bc-hud-boost-fill ${x.isTeamZero?"sap-bc-boost-fill-blue":"sap-bc-boost-fill-orange"}`,O=document.createElement("span"),O.className="sap-bc-hud-boost-text",D.append(k,O),R.append(D),Bv(R,b,x.id,x.name),(x.isTeamZero?o:l)?.append(R)}h.set(x.id,{floatingRoot:M,floatingBoostFill:w,floatingBoostText:E,teamHudEntry:R,teamHudFill:k,teamHudText:O})}T.append(a),m(b.player.getState().attachedPlayerId),v({...b,state:b.player.getState()})}return{id:"ballchasing-overlay",setup(b){y(b,b.container)},onStateChange(b){m(b.state.attachedPlayerId),v(b)},teardown(b){a?.remove(),a=null,r=null,o=null,l=null,c=null,h.clear(),u&&(b.container.style.position=d,u=!1)},beforeRender(b){if(!a)return;g.copy(b.scene.camera.up).normalize().multiplyScalar(_()*(b.options.fieldScale??1));let T=!1;for(const[x,M]of b.players.entries()){const C=h.get(M.track.id);if(!C)continue;const w=y3(b,x),E=C.floatingRoot?.classList.contains("sap-bc-player-following")??!1;E&&(Uv(c,w,M.track.name,M.track.isTeamZero),T=!0),Nv(C.floatingBoostFill,C.floatingBoostText,w,M.track.name),Nv(C.teamHudFill,C.teamHudText,w,M.track.name);const R=M.mesh,k=R!==null&&M.interpolatedPosition!==null;if(C.teamHudEntry?.classList.toggle("sap-bc-hud-player-inactive",!k),!!C.floatingRoot){if(E||!k||!b3(R,g,b.scene.camera,b.container,p)){C.floatingRoot.hidden=!0;continue}C.floatingRoot.hidden=!1,C.floatingRoot.style.transform=`translate(${p.x.toFixed(1)}px, ${p.y.toFixed(1)}px) translate(-50%, -100%)`}}!T&&c&&(c.root.hidden=!0)}}}function w3(){return{guid:{a:0,b:0,c:0,d:0},code:null,name:null,training_type:"Training_None",difficulty:"D_Easy",creator_name:null,description:null,tags:[],map_name:null,created_at:0n,updated_at:0n,creator_player_id:{uid:0n,epic_account_id:null,platform:null,splitscreen_id:0},rounds:[],player_team_number:0,unowned:!1,perfect_completed:!1,shots_completed:0}}let kp=null;async function S3(){return kp||(kp=(async()=>{const n=await F1(()=>import("./rl_replay_subtr_actor-Cnltgw4Z.js"),[],import.meta.url),e=n.default;return typeof e=="function"&&await e(),n})()),kp}async function zv(n){return n?.bindings??S3()}function T3(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function Xr(n){try{return n()}catch(e){throw e instanceof Error?e:new Error(String(e))}}class ta{constructor(e,t){this.bindings=e,this.lossless=t}lossless;cachedPack=null;static async load(e,t){return ta.fromBytes(e,await zv(t))}static fromBytes(e,t){const i=Xr(()=>t.parse_training_pack_lossless(T3(e)));return new ta(t,i)}static async create(e,t){return ta.createWithBindings(await zv(t),e)}static createWithBindings(e,t){const i={...w3(),...t},s=Xr(()=>e.new_training_pack(i));return new ta(e,s)}static fromLosslessJson(e,t){const i=new ta(t,e);return i.view(),i}view(){return this.cachedPack||(this.cachedPack=Xr(()=>this.bindings.training_pack_from_lossless(this.lossless))),this.cachedPack}apply(e){this.lossless=Xr(e),this.cachedPack=null}get losslessJson(){return this.lossless}get pack(){return structuredClone(this.view())}toJSON(){return this.pack}get name(){return this.view().name}get code(){return this.view().code}get description(){return this.view().description}get creatorName(){return this.view().creator_name}get trainingType(){return this.view().training_type}get difficulty(){return this.view().difficulty}get mapName(){return this.view().map_name}get guid(){return{...this.view().guid}}get tags(){return[...this.view().tags]}get rounds(){return structuredClone(this.view().rounds)}get roundCount(){return this.view().rounds.length}updateMetadata(e){const t={...this.view(),...e};this.apply(()=>this.bindings.update_training_pack_metadata(this.lossless,t))}setName(e){this.updateMetadata({name:e})}setCode(e){this.updateMetadata({code:e})}setDescription(e){this.updateMetadata({description:e})}setCreatorName(e){this.updateMetadata({creator_name:e})}setTrainingType(e){this.updateMetadata({training_type:e})}setDifficulty(e){this.updateMetadata({difficulty:e})}setMapName(e){this.updateMetadata({map_name:e})}setTags(e){this.updateMetadata({tags:e})}setGuid(e){this.updateMetadata({guid:e})}addRound(e){this.apply(()=>this.bindings.training_pack_add_round(this.lossless,e))}insertRound(e,t){this.apply(()=>this.bindings.training_pack_insert_round(this.lossless,e,t))}removeRound(e){const t=this.view().rounds[e];return this.apply(()=>this.bindings.training_pack_remove_round(this.lossless,e)),structuredClone(t)}moveRound(e,t){this.apply(()=>this.bindings.training_pack_move_round(this.lossless,e,t))}duplicateRound(e){this.apply(()=>this.bindings.training_pack_duplicate_round(this.lossless,e))}getRoundArchetypes(e){return Xr(()=>this.bindings.training_pack_round_archetypes(this.lossless,e))}setRoundArchetype(e,t,i){this.apply(()=>this.bindings.training_pack_set_round_archetype(this.lossless,e,t,i))}addRoundArchetype(e,t){this.apply(()=>this.bindings.training_pack_add_round_archetype(this.lossless,e,t))}removeRoundArchetype(e,t){const i=this.getRoundArchetypes(e)[t];return this.apply(()=>this.bindings.training_pack_remove_round_archetype(this.lossless,e,t)),i}setRoundBall(e,t){this.apply(()=>this.bindings.training_pack_set_round_ball(this.lossless,e,t))}addRoundCar(e,t){this.addRoundArchetype(e,{kind:"CarSpawnPoint",...t})}setRoundTimeLimit(e,t){this.apply(()=>this.bindings.training_pack_set_round_time_limit(this.lossless,e,t))}appendRoundsFrom(e){const t=e.view().rounds.length;return this.apply(()=>this.bindings.training_pack_append_rounds(this.lossless,e.lossless)),t}toBytes(){return Xr(()=>this.bindings.serialize_training_pack(this.lossless))}}const $T=8,M3=17,E3=32768/Math.PI;function Ol(n){return Math.round(n*E3)}function ju(n,e){const{x:t,y:i,z:s,w:a}=e,r=2*(i*n.z-s*n.y),o=2*(s*n.x-t*n.z),l=2*(t*n.y-i*n.x);return{x:n.x+a*r+(i*l-s*o),y:n.y+a*o+(s*r-t*l),z:n.z+a*l+(t*o-i*r)}}function C3(n){const e=n?.x??0,t=n?.y??0,i=n?.z??0,s=Math.hypot(e,t),a=Math.hypot(s,i);return a===0?{rotator:{pitch:0,yaw:0,roll:0},speed:0}:{rotator:{pitch:Ol(Math.atan2(i,s)),yaw:Ol(Math.atan2(t,e)),roll:0},speed:a}}function A3(n){const e=ju({x:1,y:0,z:0},n),t=ju({x:0,y:1,z:0},n),i=ju({x:0,y:0,z:1},n);return{pitch:Ol(Math.atan2(e.z,Math.hypot(e.x,e.y))),yaw:Ol(Math.atan2(e.y,e.x)),roll:Ol(Math.atan2(t.z,i.z))}}const R3=1,P3=300,I3=400,L3=20;function k3(n,e){const t=P3,i=I3,s=L3,a=n.linearVelocity,r=a?.x??0,o=a?.y??0,l=a?.z??0,c=Math.hypot(r,o,l);if(c<=t)return null;const u=n.rotation?ju({x:1,y:0,z:0},n.rotation):{x:1,y:0,z:0},d=r*u.x+o*u.y+l*u.z,h=d(e>>>0).toString(16).padStart(8,"0").toUpperCase()).join("")}function z3(n){return`${B3(n)}.Tem`}function H3(n=Math.floor(Date.now()/1e3)){const e=BigInt(n);return{guid:U3(),name:"Captured Training Pack",training_type:"Training_Striker",difficulty:"D_Medium",map_name:"Park_P",created_at:e,updated_at:e}}function V3(){return`
@@ -4822,6 +4822,7 @@ void main() { + @@ -5219,6 +5220,70 @@ void main() {
+ +
--
--
-`}const en="#3b82f6",tn="#f59e0b",h3=new Set(["wavedash"]),f3=new Set(["air_dribble","ball_carry","ceiling_shot","double_tap","flick","flip_reset","half_flip","half_volley","one_timer","speed_flip","wall_aerial","wall_aerial_shot","wavedash"]);function Ci(n){return n.split(/[_-]+/).filter(e=>e.length>0).map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1)}`).join(" ")}function Dv(n){return f3.has(n)&&!h3.has(n)}function ef(n){return n===!0?en:n===!1?tn:null}const FT=["timeline","core_player","player_possession","possession","loose_possession","ball_half","ball_third","territorial_pressure","movement","player_activity","field_third","field_half","ball_depth","depth_role","ball_proximity","shadow_defense","rotation_role","first_man_change","goal_context","backboard","ceiling_shot","wall_aerial","wall_aerial_shot","center","flick","flip_reset","dodge_reset","double_tap","fifty_fifty","kickoff","one_timer","pass","ball_carry","controlled_play","rush","dodge","speed_flip","half_flip","half_volley","wavedash","whiff","powerslide","touch","boost_pickups","boost_respawn","bump","demolition"],NT=["air_dribble","ball_carry","ceiling_shot","double_tap","flick","flip_reset","half_flip","half_volley","one_timer","speed_flip","wall_aerial","wall_aerial_shot","wavedash"],Lg=[...new Set([...FT,...NT])],p3=new Set(NT);function io(){return Object.fromEntries(Lg.map(n=>[n,0]))}function Cp(n){return{...n??io()}}function wu(n,e){n[e]+=1}function m3(n){return Lg.includes(n)}function UT(n){if(n==null)return null;if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function Bm(n){return UT(n.meta.primary_player)}function _3(n){return n.meta.team_is_team_0??null}function g3(n){const e=n.meta.stream;return!p3.has(e)||!m3(e)?null:e}function zm(n){const e=n.meta.timing.type==="span"?n.meta.timing.end_frame:n.meta.timing.frame;return typeof e=="number"&&Number.isFinite(e)?e:null}function Hm(n){const e=n.meta.timing.type==="span"?n.meta.timing.end_time:n.meta.timing.time;return typeof e=="number"&&Number.isFinite(e)?e:null}function y3(n,e){const t=zm(n);if(t!==null)return t<=e.frame_number;const i=Hm(n);return i!==null&&i<=e.time}function v3(n){return[...n].sort((e,t)=>{const i=zm(e),s=zm(t);if(i!==s)return(i??Number.POSITIVE_INFINITY)-(s??Number.POSITIVE_INFINITY);const a=Hm(e),r=Hm(t);return a!==r?(a??Number.POSITIVE_INFINITY)-(r??Number.POSITIVE_INFINITY):(Bm(e)??"").localeCompare(Bm(t)??"")})}function BT(n){const e=zT(n);for(const t of n.frames)e.applyFrame(t);return n}function zT(n){const e=Lg.map(s=>({eventType:s,events:v3(jl(n).filter(a=>a.meta.stream===s)),index:0})),t=new Map,i={teamZero:io(),teamOne:io()};return{applyFrame(s){for(const a of e)for(;a.index({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function x3(n,e,t,i){n.is_last_backboard=i,n.time_since_last_backboard=n.last_backboard_time==null?null:Math.max(0,t-n.last_backboard_time),n.frames_since_last_backboard=n.last_backboard_frame==null?null:Math.max(0,e-n.last_backboard_frame)}function w3(n,e,t,i){n.count+=1,n.last_backboard_time=e.time,n.last_backboard_frame=e.frame,n.time_since_last_backboard=Math.max(0,i-e.time),n.frames_since_last_backboard=Math.max(0,t-e.frame)}function S3(n,e){Object.assign(n,e??HT())}function Ov(n,e){n.count=e}function T3(n){const e=VT(n);for(const t of n.frames)e.applyFrame(t);return n}function VT(n){const e=b3(ve(n,"backboard"));let t=0,i=0,s=0,a=null;const r=new Map;return{applyFrame(o){for(const[c,u]of r)x3(u,o.frame_number,o.time,c===a);let l=!1;for(;t({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function Vm(n){return`${n.key}\0${n.value}`}function Su(n){return n.map(Vm).join("")}function GT(n,e){e.sort((s,a)=>Vm(s).localeCompare(Vm(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Su(s.labels)===Su(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Su(s.labels).localeCompare(Su(a.labels))))}function Nv(n,e){return n.labeled_event_counts?.entries.filter(t=>t.labels.some(i=>i.key==="origin"&&i.value===e)).reduce((t,i)=>t+i.count,0)??0}function $T(n){return n.labeled_event_counts?.entries.reduce((e,t)=>e+t.count,0)??0}function WT(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function Uv(n,e){GT(n,[{key:"kind",value:"carry"}]),n.carry_count=$T(n),n.total_carry_time+=e.duration,n.total_straight_line_distance+=e.straight_line_distance,n.total_path_distance+=e.path_distance,n.longest_carry_time=Math.max(n.longest_carry_time,e.duration),n.furthest_carry_distance=Math.max(n.furthest_carry_distance,e.straight_line_distance),n.fastest_carry_speed=Math.max(n.fastest_carry_speed,e.average_speed),n.carry_speed_sum+=e.average_speed,n.average_horizontal_gap_sum+=e.average_horizontal_gap,n.average_vertical_gap_sum+=e.average_vertical_gap}function Bv(n,e){e.air_dribble_origin!=null&>(n,[{key:"origin",value:e.air_dribble_origin}]),n.count=$T(n),n.ground_to_air_count=Nv(n,"ground_to_air"),n.wall_to_air_count=Nv(n,"wall_to_air"),n.total_time+=e.duration,n.total_straight_line_distance+=e.straight_line_distance,n.total_path_distance+=e.path_distance,n.longest_time=Math.max(n.longest_time,e.duration),n.furthest_distance=Math.max(n.furthest_distance,e.straight_line_distance),n.fastest_speed=Math.max(n.fastest_speed,e.average_speed),n.speed_sum+=e.average_speed,n.average_horizontal_gap_sum+=e.average_horizontal_gap,n.average_vertical_gap_sum+=e.average_vertical_gap,n.total_touch_count+=e.touch_count,n.max_touch_count=Math.max(n.max_touch_count,e.touch_count)}function Ap(n,e){Object.assign(n,e??Xu()),e?.labeled_event_counts?n.labeled_event_counts=WT(e.labeled_event_counts):delete n.labeled_event_counts}function Rp(n,e){Object.assign(n,e??Ku()),e?.labeled_event_counts?n.labeled_event_counts=WT(e.labeled_event_counts):delete n.labeled_event_counts}function E3(n){const e=XT(n);for(const t of n.frames)e.applyFrame(t);return n}function XT(n){const e=M3(ve(n,"ball_carry"));let t=0;const i=new Map,s=new Map,a=Xu(),r=Xu(),o=Ku(),l=Ku();return{applyFrame(c){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function A3(n,e){n.bumps_inflicted+=1,e.is_team_bump&&(n.team_bumps_inflicted+=1),n.last_bump_time=e.time,n.last_bump_frame=e.frame,n.last_bump_strength=e.strength,n.max_bump_strength=Math.max(n.max_bump_strength,e.strength),n.cumulative_bump_strength+=e.strength}function R3(n,e){n.bumps_taken+=1,e.is_team_bump&&(n.team_bumps_taken+=1)}function P3(n,e){n.bumps_inflicted+=1,e.is_team_bump&&(n.team_bumps_inflicted+=1)}function I3(n,e){Object.assign(n,e??Gm())}function Hv(n,e){Object.assign(n,e)}function L3(n){const e=KT(n);for(const t of n.frames)e.applyFrame(t);return n}function KT(n){const e=C3(ve(n,"bump"));let t=0;const i=new Map,s=zv(),a=zv();return{applyFrame(r){for(;t=t&&n0&&(s.overfill_total=sn(s.overfill_total,i),e.field_half==="opponent"&&(s.overfill_from_stolen=sn(s.overfill_from_stolen,i)))}function $v(n,e){e.boost_granted!=null&&(n.stats.amount_respawned=sn(n.stats.amount_respawned,rn(e.boost_granted)))}class U3{constructor(e){this.points=e}index=0;sample(e){for(;this.index+1e?0:rn(t.value)}}function Km(n,e){return`${n}:${e}`}function B3(n){const e=new Map,t=n.accumulation_tracks;for(const i of t??[]){const s=pl(i.player_id);e.set(Km(s,i.quantity),new U3(i.points))}return e}function z3(n){return[...ve(n,"boost_pickup")].sort((e,t)=>e.frame-t.frame||e.time-t.time)}function H3(n){return[...ve(n,"respawn")].sort((e,t)=>e.frame-t.frame||e.time-t.time)}function Lp(n,e){for(const t of qT)n[t]=e[t]}function YT(n){const e=z3(n),t=H3(n),i=B3(n);let s=0,a=0;const r=new Map,o=Ip(),l=Ip(),c=(d,h)=>{const f=pl(d);let p=r.get(f);return p||(p=Ip(),r.set(f,p)),p.isTeamZero=h,p},u=(d,h,f)=>{const p=g=>i.get(Km(h,g))?.sample(f)??0;d.amount_used=p("boost_used"),d.amount_used_while_grounded=p("boost_used_grounded"),d.amount_used_while_airborne=p("boost_used_airborne"),d.amount_used_while_supersonic=p("boost_used_supersonic")};return{applyFrame(d,h){for(;s({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function qm(n){return`${n.key}\0${n.value}`}function Mu(n){return n.map(qm).join("")}function K3(n,e){e.sort((s,a)=>qm(s).localeCompare(qm(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Mu(s.labels)===Mu(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Mu(s.labels).localeCompare(Mu(a.labels))))}function q3(n,e){return n.labeled_event_counts?.entries.filter(t=>t.labels.some(i=>i.key==="confidence_band"&&i.value===e)).reduce((t,i)=>t+i.count,0)??0}function Y3(n){return n.labeled_event_counts?.entries.reduce((e,t)=>e+t.count,0)??0}function j3(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function Z3(n,e,t,i){n.is_last_ceiling_shot=i,n.time_since_last_ceiling_shot=n.last_ceiling_shot_time==null?null:Math.max(0,jT(t,n.last_ceiling_shot_time)),n.frames_since_last_ceiling_shot=n.last_ceiling_shot_frame==null?null:Math.max(0,e-n.last_ceiling_shot_frame)}function J3(n,e,t,i){K3(n,[{key:"confidence_band",value:e.confidence>=$3?"high":"standard"}]),n.count=Y3(n),n.high_confidence_count=q3(n,"high"),n.is_last_ceiling_shot=!0,n.last_ceiling_shot_time=e.time,n.last_ceiling_shot_frame=e.frame,n.time_since_last_ceiling_shot=Math.max(0,jT(i,e.time)),n.frames_since_last_ceiling_shot=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=W3(n.cumulative_confidence,e.confidence)}function Q3(n,e){Object.assign(n,e??ZT()),e?.labeled_event_counts?n.labeled_event_counts=j3(e.labeled_event_counts):delete n.labeled_event_counts}function eU(n){const e=JT(n);for(const t of n.frames)e.applyFrame(t);return n}function JT(n){const e=X3(ve(n,"ceiling_shot"));let t=0,i=null;const s=new Map;return{applyFrame(a){if(a.is_live_play){for(const[r,o]of s)Z3(o,a.frame_number,a.time,i===r);for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function sU(n,e){Object.assign(n,e??Dg())}function Kv(n,e){Object.assign(n,e)}function qv(n,e){n.score+=e.score_delta,n.goals+=e.goals_delta,n.assists+=e.assists_delta,n.saves+=e.saves_delta,n.shots+=e.shots_delta}function QT(n,e){if(e.time_after_kickoff!=null){const t=Math.max(0,e.time_after_kickoff);t<10?n.kickoff_goal_count+=1:t<20?n.short_goal_count+=1:t<40?n.medium_goal_count+=1:n.long_goal_count+=1}if(e.goal_buildup==="counter_attack"?n.counter_attack_goal_count+=1:e.goal_buildup==="sustained_pressure"?n.sustained_pressure_goal_count+=1:e.goal_buildup!=null&&(n.other_buildup_goal_count+=1),e.ball_air_time_before_goal!=null){const t=Math.max(0,e.ball_air_time_before_goal);n.goal_ball_air_time_sample_count+=1,n.cumulative_goal_ball_air_time=ns(n.cumulative_goal_ball_air_time,t),n.last_goal_ball_air_time=t}}function Dp(n,e){return n!=null&&e!=null&&ql(n)===ql(e)}function Yv(n,e){return n?e.y:-e.y}function aU(n,e){if(n.ball_position==null||e.position==null)return!1;const t=!n.scoring_team_is_team_0,i=Yv(t,n.ball_position);if(i>tU)return!1;const s=Yv(t,e.position);return s=iU}function rU(n,e,t){const i=t.is_team_0===e.scoring_team_is_team_0,s=Dp(t.player,e.defending_team_most_back_player),a=Dp(t.player,e.scoring_team_most_back_player);s&&(n.goals_conceded_while_last_defender+=1),a&&(n.goals_for_while_most_back+=1),s&&(n.goals_against_while_most_back+=1),!i&&aU(e,t)&&(n.caught_ahead_of_play_on_conceded_goals+=1),!i&&t.boost_amount!=null&&(n.goal_against_boost_sample_count+=1,n.cumulative_boost_on_goals_against=ns(n.cumulative_boost_on_goals_against,t.boost_amount),n.last_boost_on_goal_against=t.boost_amount),!i&&t.average_boost_in_leadup!=null&&t.min_boost_in_leadup!=null&&(n.goal_against_boost_leadup_sample_count+=1,n.cumulative_average_boost_in_goal_against_leadup=ns(n.cumulative_average_boost_in_goal_against_leadup,t.average_boost_in_leadup),n.cumulative_min_boost_in_goal_against_leadup=ns(n.cumulative_min_boost_in_goal_against_leadup,t.min_boost_in_leadup),n.last_average_boost_in_goal_against_leadup=t.average_boost_in_leadup,n.last_min_boost_in_goal_against_leadup=t.min_boost_in_leadup),!i&&t.position!=null&&(n.goal_against_position_sample_count+=1,n.cumulative_goal_against_position_x=ns(n.cumulative_goal_against_position_x,t.position.x),n.cumulative_goal_against_position_y=ns(n.cumulative_goal_against_position_y,t.position.y),n.cumulative_goal_against_position_z=ns(n.cumulative_goal_against_position_z,t.position.z),n.last_goal_against_position={...t.position});const r=Dp(t.player,e.scorer),o=r?e.scorer_last_touch?.ball_position:null;o!=null&&(n.scoring_goal_last_touch_position_sample_count+=1,n.cumulative_scoring_goal_last_touch_position_x=ns(n.cumulative_scoring_goal_last_touch_position_x,o.x),n.cumulative_scoring_goal_last_touch_position_y=ns(n.cumulative_scoring_goal_last_touch_position_y,o.y),n.cumulative_scoring_goal_last_touch_position_z=ns(n.cumulative_scoring_goal_last_touch_position_z,o.z),n.last_scoring_goal_last_touch_position={...o}),r&&QT(n,e)}function oU(n,e,t,i){QT(i.scoring_team_is_team_0?e:t,i);for(const s of i.players){const a=ql(s.player),r=n.get(a)??Dg();n.set(a,r),rU(r,i,s)}}function lU(n){const e=eM(n);for(const t of n.frames)e.applyFrame(t);return n}function eM(n){const e=Xv(ve(n,"core_player")),t=Xv(ve(n,"goal_context"));let i=0,s=0;const a=new Map,r=Ym(),o=Ym();return{applyFrame(l){for(;i({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function Jv(n,e){n.count+=1,n.total_time=jv(n.total_time,e.duration),n.longest_time=Math.max(n.longest_time,e.duration),n.touch_count+=e.touch_count,n.total_advance_distance=jv(n.total_advance_distance,e.total_advance_distance)}function Op(n,e){Object.assign(n,e??qu())}function uU(n){const e=tM(n);for(const t of n.frames)e.applyFrame(t);return n}function tM(n){const e=cU(ve(n,"controlled_play"));let t=0;const i=new Map,s=qu(),a=qu();return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function hU(n,e){n.count+=1,e.on_ball&&(n.on_ball_count+=1)}function fU(n,e){Object.assign(n,e??nM())}function pU(n){const e=iM(n);for(const t of n.frames)e.applyFrame(t);return n}function iM(n){const e=dU(ve(n,"dodge_reset"));let t=0;const i=new Map;return{applyFrame(s){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function _U(n,e,t,i){n.is_last_double_tap=i,n.time_since_last_double_tap=n.last_double_tap_time==null?null:Math.max(0,t-n.last_double_tap_time),n.frames_since_last_double_tap=n.last_double_tap_frame==null?null:Math.max(0,e-n.last_double_tap_frame)}function gU(n,e,t,i){n.count+=1,n.last_double_tap_time=e.time,n.last_double_tap_frame=e.frame,n.time_since_last_double_tap=Math.max(0,i-e.time),n.frames_since_last_double_tap=Math.max(0,t-e.frame)}function yU(n,e){Object.assign(n,e??sM())}function tb(n,e){n.count=e}function vU(n){const e=aM(n);for(const t of n.frames)e.applyFrame(t);return n}function aM(n){const e=mU(ve(n,"double_tap"));let t=0,i=0,s=0,a=null;const r=new Map;return{applyFrame(o){for(const[c,u]of r)_U(u,o.frame_number,o.time,c===a);let l=!1;for(;t({event:e,index:t})).sort((e,t)=>e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function xU(n,e){Object.assign(n,e??rM())}function sb(n,e){Object.assign(n,e)}function wU(n){const e=oM(n);for(const t of n.frames)e.applyFrame(t);return n}function oM(n){const e=bU(ve(n,"demolition"));let t=0;const i=new Map,s=ib(),a=ib();function r(o){const l=nb(o),c=i.get(l)??rM();return i.set(l,c),c}return{applyFrame(o){for(;t({event:e,index:t})).sort((e,t)=>e.event.resolve_frame!==t.event.resolve_frame?e.event.resolve_frame-t.event.resolve_frame:e.event.resolve_time!==t.event.resolve_time?e.event.resolve_time-t.event.resolve_time:e.index-t.index).map(({event:e})=>e)}function TU(n){return{key:"phase",value:n?"kickoff":"open_play"}}function MU(n,e){return e==null?{key:"outcome",value:"neutral"}:{key:"outcome",value:e===n?"win":"loss"}}function EU(n,e){return e==null?{key:"possession_after",value:"neutral"}:{key:"possession_after",value:e===n?"self":"opponent"}}function CU(n,e){return{key:"dodge_state",value:(n?e.team_zero_dodge_contact:e.team_one_dodge_contact)?"dodge":"no_dodge"}}function Zm(n){return`${n.key}\0${n.value}`}function Eu(n){return n.map(Zm).join("")}function AU(n,e){e.sort((s,a)=>Zm(s).localeCompare(Zm(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Eu(s.labels)===Eu(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Eu(s.labels).localeCompare(Eu(a.labels))))}function RU(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function rb(n,e,t){n.count+=1,t.winning_team_is_team_0==null?n.neutral_outcomes+=1:t.winning_team_is_team_0===e?n.wins+=1:n.losses+=1,t.possession_team_is_team_0==null?n.neutral_possession_after_count+=1:t.possession_team_is_team_0===e?n.possession_after_count+=1:n.opponent_possession_after_count+=1,t.is_kickoff&&(n.kickoff_count+=1,t.winning_team_is_team_0==null?n.kickoff_neutral_outcomes+=1:t.winning_team_is_team_0===e?n.kickoff_wins+=1:n.kickoff_losses+=1,t.possession_team_is_team_0==null?n.kickoff_neutral_possession_after_count+=1:t.possession_team_is_team_0===e?n.kickoff_possession_after_count+=1:n.kickoff_opponent_possession_after_count+=1)}function ob(n,e,t){AU(n,[TU(t.is_kickoff),MU(e,t.winning_team_is_team_0),EU(e,t.possession_team_is_team_0),CU(e,t)]),n.count+=1,t.winning_team_is_team_0==null?n.neutral_outcomes+=1:t.winning_team_is_team_0===e?n.wins+=1:n.losses+=1,t.possession_team_is_team_0===e&&(n.possession_after_count+=1),t.is_kickoff&&(n.kickoff_count+=1,t.winning_team_is_team_0==null?n.kickoff_neutral_outcomes+=1:t.winning_team_is_team_0===e?n.kickoff_wins+=1:n.kickoff_losses+=1,t.possession_team_is_team_0===e&&(n.kickoff_possession_after_count+=1))}function PU(n,e){Object.assign(n,e??jm()),e?.labeled_event_counts?n.labeled_event_counts=RU(e.labeled_event_counts):delete n.labeled_event_counts}function lb(n,e){Object.assign(n,e)}function IU(n){const e=lM(n);for(const t of n.frames)e.applyFrame(t);return n}function lM(n){const e=SU(ve(n,"fifty_fifty"));let t=0;const i=ab(),s=ab(),a=new Map;return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function Jm(n){return`${n.key}\0${n.value}`}function Cu(n){return n.map(Jm).join("")}function dM(n,e){e.sort((s,a)=>Jm(s).localeCompare(Jm(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Cu(s.labels)===Cu(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Cu(s.labels).localeCompare(Cu(a.labels))))}function DU(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function kU(n){return[{key:"kickoff_spawn",value:n.spawn_position},{key:"taker_outcome",value:n.outcome},{key:"kickoff_approach",value:n.approach},{key:"approach_flip_direction",value:n.approach_flip_direction}]}function OU(n){return[{key:"kickoff_spawn",value:n.spawn_position},{key:"support_behavior",value:n.support_behavior}]}function ub(n,e,t){n.count+=1,t.outcome==="neutral"?n.neutral_outcomes+=1:t.outcome===(e?"team_zero_win":"team_one_win")?n.wins+=1:t.outcome===(e?"team_one_win":"team_zero_win")&&(n.losses+=1),t.kickoff_possession_outcome==="contested"?n.contested_kickoff_possessions+=1:t.kickoff_possession_outcome===(e?"team_zero_possession":"team_one_possession")?n.kickoff_possessions+=1:t.kickoff_possession_outcome===(e?"team_one_possession":"team_zero_possession")?n.opponent_kickoff_possessions+=1:t.kickoff_possession_outcome===(e?"team_zero_advantage":"team_one_advantage")?n.kickoff_possession_advantages+=1:n.opponent_kickoff_possession_advantages+=1,t.kickoff_goal&&(n.kickoff_goal_count+=1,t.scoring_team_is_team_0===e?n.kickoff_goals_for+=1:t.scoring_team_is_team_0!=null&&(n.kickoff_goals_against+=1)),t.win_strength!=null&&(n.win_strength_sample_count+=1,n.cumulative_win_strength+=t.win_strength)}function db(n,e,t){t&&(t.boost_after!=null&&(n.boost_after_sample_count+=1,n.cumulative_boost_after+=t.boost_after,e.boost_after_sample_count+=1,e.cumulative_boost_after+=t.boost_after),t.outcome==="fake"?(n.fake_count+=1,e.fake_count+=1):t.outcome==="missed"&&(n.missed_count+=1,e.missed_count+=1))}function FU(n,e,t){n.count+=1,dM(n,kU(t)),t.outcome==="touched"?n.touches+=1:t.outcome==="fake"?n.fakes+=1:t.outcome==="missed"&&(n.misses+=1),e.kickoff_goal&&e.scoring_team_is_team_0===t.is_team_0&&(n.kickoff_goal_count+=1),t.boost_after!=null&&(n.boost_after_sample_count+=1,n.cumulative_boost_after+=t.boost_after)}function NU(n,e,t){n.count+=1,dM(n,OU(t)),t.first_touch_time!=null&&(n.touches+=1),t.support_behavior==="go_for_boost"?n.support_go_for_boosts+=1:t.support_behavior==="cheat"?n.support_cheats+=1:t.support_behavior==="other"&&(n.support_other+=1),e.kickoff_goal&&e.scoring_team_is_team_0===t.is_team_0&&(n.kickoff_goal_count+=1),t.boost_after!=null&&(n.boost_after_sample_count+=1,n.cumulative_boost_after+=t.boost_after)}function Au(n,e,t){const i=cM(t.player),s=n.get(i)??uM();n.set(i,s),"outcome"in t?FU(s,e,t):NU(s,e,t)}function hb(n,e){Object.assign(n,e)}function UU(n,e){Object.assign(n,e??uM()),e?.labeled_event_counts?n.labeled_event_counts=DU(e.labeled_event_counts):delete n.labeled_event_counts}function BU(n){const e=hM(n);for(const t of n.frames)e.applyFrame(t);return n}function hM(n){const e=LU(ve(n,"kickoff"));let t=0;const i=cb(),s=cb(),a=new Map;return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function Qm(n){return`${n.key}\0${n.value}`}function Ru(n){return n.map(Qm).join("")}function VU(n,e){e.sort((s,a)=>Qm(s).localeCompare(Qm(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Ru(s.labels)===Ru(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Ru(s.labels).localeCompare(Ru(a.labels))))}function GU(n,e){return n.labeled_event_counts?.entries.filter(t=>t.labels.some(i=>i.key==="confidence_band"&&i.value===e)).reduce((t,i)=>t+i.count,0)??0}function $U(n){return n==="forward"||n==="reverse"||n==="side"?n:"other"}function WU(n){return n==="left"||n==="right"?n:"center"}function XU(n){return n.labeled_event_counts?.entries.reduce((e,t)=>e+t.count,0)??0}function KU(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function qU(n,e,t,i){n.is_last_flick=i,n.time_since_last_flick=n.last_flick_time==null?null:Math.max(0,fM(t,n.last_flick_time)),n.frames_since_last_flick=n.last_flick_frame==null?null:Math.max(0,e-n.last_flick_frame)}function YU(n,e,t,i){VU(n,[{key:"confidence_band",value:e.confidence>=zU?"high":"standard"},{key:"kind",value:$U(e.kind)},{key:"direction",value:WU(e.direction)}]),n.count=XU(n),n.high_confidence_count=GU(n,"high"),n.is_last_flick=!0,n.last_flick_time=e.time,n.last_flick_frame=e.frame,n.time_since_last_flick=Math.max(0,fM(i,e.time)),n.frames_since_last_flick=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=Np(n.cumulative_confidence,e.confidence),n.cumulative_setup_duration=Np(n.cumulative_setup_duration,e.setup_duration),n.cumulative_ball_speed_change=Np(n.cumulative_ball_speed_change,e.ball_speed_change)}function jU(n,e){Object.assign(n,e??pM()),e?.labeled_event_counts?n.labeled_event_counts=KU(e.labeled_event_counts):delete n.labeled_event_counts}function ZU(n){const e=mM(n);for(const t of n.frames)e.applyFrame(t);return n}function mM(n){const e=HU(ve(n,"flick"));let t=0,i=null;const s=new Map;return{applyFrame(a){if(a.is_live_play){for(const[r,o]of s)qU(o,a.frame_number,a.time,r===i);for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function QU(n,e){n.count+=1,n.total_time_to_use+=e.time_since_reset,n.min_time_to_use=n.min_time_to_use===null?e.time_since_reset:Math.min(n.min_time_to_use,e.time_since_reset)}function eB(n,e){Object.assign(n,e??_M())}function tB(n){const e=gM(n);for(const t of n.frames)e.applyFrame(t);return n}function gM(n){const e=JU(ve(n,"flip_reset"));let t=0;const i=new Map;return{applyFrame(s){for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function iB(n,e,t,i){n.is_last_half_volley=i,n.time_since_last_half_volley=n.last_half_volley_time==null?null:Math.max(0,vM(t,n.last_half_volley_time)),n.frames_since_last_half_volley=n.last_half_volley_frame==null?null:Math.max(0,e-n.last_half_volley_frame)}function sB(n,e,t,i){n.count+=1,n.total_ball_speed=yM(n.total_ball_speed,e.ball_speed),n.fastest_ball_speed=Math.max(n.fastest_ball_speed,e.ball_speed),n.last_half_volley_time=e.time,n.last_half_volley_frame=e.frame,n.time_since_last_half_volley=Math.max(0,vM(i,e.time)),n.frames_since_last_half_volley=Math.max(0,t-e.frame)}function aB(n,e){Object.assign(n,e??bM())}function _b(n,e){Object.assign(n,e)}function rB(n){const e=xM(n);for(const t of n.frames)e.applyFrame(t);return n}function xM(n){const e=nB(ve(n,"half_volley"));let t=0,i=null;const s=new Map,a={count:0,total_ball_speed:0,fastest_ball_speed:0},r={count:0,total_ball_speed:0,fastest_ball_speed:0};return{applyFrame(o){for(const[l,c]of s)iB(c,o.frame_number,o.time,o.is_live_play&&l===i);if(!o.is_live_play)i=null;else{let l=!1;for(;te.frame!==t.frame?e.frame-t.frame:e.time!==t.time?e.time-t.time:Gi(e.player).localeCompare(Gi(t.player)))}function uB(n){return[...n].sort((e,t)=>e.resolved_frame!==t.resolved_frame?e.resolved_frame-t.resolved_frame:e.resolved_time!==t.resolved_time?e.resolved_time-t.resolved_time:e.frame!==t.frame?e.frame-t.frame:e.time!==t.time?e.time-t.time:Gi(e.player).localeCompare(Gi(t.player)))}function Up(){return{count:0,highConfidenceCount:0,lastTime:null,lastFrame:null,lastResolvedTime:null,lastResolvedFrame:null,lastQuality:null,bestQuality:0,cumulativeQuality:0,labeledCounts:{entries:[]}}}function oo(n){return Math.fround(n)}function dB(n,e){return oo(oo(n)+oo(e))}function hB(n,e){return{key:"confidence_band",value:n>=e?"high":"standard"}}function fB(n,e){const t=e.sort((s,a)=>s.key===a.key?s.value.localeCompare(a.value):s.key.localeCompare(a.key)),i=n.entries.find(s=>s.labels.length===t.length&&s.labels.every((a,r)=>a.key===t[r]?.key&&a.value===t[r]?.value));if(i){i.count+=1;return}n.entries.push({labels:t,count:1}),n.entries.sort((s,a)=>JSON.stringify(s.labels).localeCompare(JSON.stringify(a.labels)))}function Oo(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function Bp(n,e,t,i,s){n.count+=1,e.confidence>=s&&(n.highConfidenceCount+=1),fB(n.labeledCounts,[hB(e.confidence,s)]),n.lastTime=e.time,n.lastFrame=e.frame,n.lastResolvedTime=i,n.lastResolvedFrame=t,n.lastQuality=e.confidence,n.bestQuality=Math.max(n.bestQuality,e.confidence),n.cumulativeQuality=dB(n.cumulativeQuality,e.confidence)}function kg(n,e){return n?.lastTime==null?null:n.lastResolvedFrame===e.frame_number?0:Math.max(0,oo(oo(e.time)-oo(n.lastTime)))}function Og(n,e){return n?.lastFrame==null?null:n.lastResolvedFrame===e.frame_number?0:Math.max(0,e.frame_number-n.lastFrame)}function wM(n,e,t,i){n.count=e?.count??0,n.high_confidence_count=e?.highConfidenceCount??0,n.is_last_speed_flip=i,n.last_speed_flip_time=e?.lastTime??null,n.last_speed_flip_frame=e?.lastFrame??null,n.time_since_last_speed_flip=kg(e,t),n.frames_since_last_speed_flip=Og(e,t),n.last_quality=e?.lastQuality??null,n.best_quality=e?.bestQuality??0,n.cumulative_quality=e?.cumulativeQuality??0,e?.labeledCounts.entries.length?n.labeled_event_counts=Oo(e.labeledCounts):delete n.labeled_event_counts}function SM(n,e,t,i){n.count=e?.count??0,n.high_confidence_count=e?.highConfidenceCount??0,n.is_last_half_flip=i,n.last_half_flip_time=e?.lastTime??null,n.last_half_flip_frame=e?.lastFrame??null,n.time_since_last_half_flip=kg(e,t),n.frames_since_last_half_flip=Og(e,t),n.last_quality=e?.lastQuality??null,n.best_quality=e?.bestQuality??0,n.cumulative_quality=e?.cumulativeQuality??0,e?.labeledCounts.entries.length?n.labeled_event_counts=Oo(e.labeledCounts):delete n.labeled_event_counts}function TM(n,e,t,i){n.count=e?.count??0,n.high_confidence_count=e?.highConfidenceCount??0,n.is_last_wavedash=i,n.last_wavedash_time=e?.lastTime??null,n.last_wavedash_frame=e?.lastFrame??null,n.time_since_last_wavedash=kg(e,t),n.frames_since_last_wavedash=Og(e,t),n.last_quality=e?.lastQuality??null,n.best_quality=e?.bestQuality??0,n.cumulative_quality=e?.cumulativeQuality??0,e?.labeledCounts.entries.length?n.labeled_event_counts=Oo(e.labeledCounts):delete n.labeled_event_counts}function pB(n){const e={...n};return n.labeled_event_counts?e.labeled_event_counts=Oo(n.labeled_event_counts):delete e.labeled_event_counts,e}function mB(n){const e={...n};return n.labeled_event_counts?e.labeled_event_counts=Oo(n.labeled_event_counts):delete e.labeled_event_counts,e}function _B(n){const e={...n};return n.labeled_event_counts?e.labeled_event_counts=Oo(n.labeled_event_counts):delete e.labeled_event_counts,e}function gB(n,e){if(e){Object.assign(n,e);return}wM(n,void 0,{frame_number:0,time:0},!1)}function yB(n,e){if(e){Object.assign(n,e);return}SM(n,void 0,{frame_number:0,time:0},!1)}function vB(n,e){if(e){Object.assign(n,e);return}TM(n,void 0,{frame_number:0,time:0},!1)}function bB(n){return n.is_live_play||n.ball_has_been_hit===!1}function xB(n){const e=MM(n);for(const t of n.frames)e.applyFrame(t);return n}function MM(n){const e=uB(ve(n,"speed_flip")),t=gb(ve(n,"half_flip")),i=gb(ve(n,"wavedash"));let s=0,a=0,r=0,o=null,l=null,c=null;const u=new Map,d=new Map,h=new Map,f=new Map,p=new Map,g=new Map;return{applyFrame(_){if(bB(_)){for(;swB.map(e=>({labels:[{key:"height_band",value:n},{key:"speed_band",value:e}],value:0}))).sort((n,e)=>JSON.stringify(n.labels).localeCompare(JSON.stringify(e.labels)))}}function Yu(n=!1){return{tracked_time:0,total_distance:0,speed_integral:0,time_slow_speed:0,time_boost_speed:0,time_supersonic_speed:0,time_on_ground:0,time_low_air:0,time_high_air:0,labeled_tracked_time:n?MB():{entries:[]}}}function EB(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function CB(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function AB(n,e,t){const i=CB(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=is(s.value,t):(n.entries.push({labels:i,value:ra(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function RB(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),value:e.value}))}}function vb(n,e){const t=ra(e.dt);n.tracked_time=is(n.tracked_time,t),n.total_distance=is(n.total_distance,e.distance),n.speed_integral=is(n.speed_integral,TB(e.speed,t)),e.speed_band==="slow"?n.time_slow_speed=is(n.time_slow_speed,t):e.speed_band==="boost"?n.time_boost_speed=is(n.time_boost_speed,t):e.speed_band==="supersonic"&&(n.time_supersonic_speed=is(n.time_supersonic_speed,t)),e.height_band==="ground"?n.time_on_ground=is(n.time_on_ground,t):e.height_band==="low_air"?n.time_low_air=is(n.time_low_air,t):e.height_band==="high_air"&&(n.time_high_air=is(n.time_high_air,t));const i=n.labeled_tracked_time??{entries:[]};n.labeled_tracked_time=i,AB(i,[{key:"speed_band",value:e.speed_band},{key:"height_band",value:e.height_band}],t)}function zp(n,e){const t=e??Yu(!0),i=t.labeled_tracked_time;Object.assign(n,t,{labeled_tracked_time:i?RB(i):void 0}),i?.entries.length||delete n.labeled_tracked_time}function PB(n){const e=EM(n);for(const t of n.frames)e.applyFrame(t);return n}function EM(n){const e=EB(ve(n,"movement"));let t=0;const i=new Map,s=Yu(),a=Yu();return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function LB(n,e,t,i){n.is_last_one_timer=i,n.time_since_last_one_timer=n.last_one_timer_time==null?null:Math.max(0,t-n.last_one_timer_time),n.frames_since_last_one_timer=n.last_one_timer_frame==null?null:Math.max(0,e-n.last_one_timer_frame)}function DB(n,e,t,i){n.count+=1,n.total_ball_speed+=e.ball_speed,n.fastest_ball_speed=Math.max(n.fastest_ball_speed,e.ball_speed),n.total_pass_distance+=e.pass_travel_distance,n.last_one_timer_time=e.time,n.last_one_timer_frame=e.frame,n.time_since_last_one_timer=Math.max(0,i-e.time),n.frames_since_last_one_timer=Math.max(0,t-e.frame)}function kB(n,e){Object.assign(n,e??CM())}function xb(n,e){Object.assign(n,e)}function OB(n){const e=AM(n);for(const t of n.frames)e.applyFrame(t);return n}function AM(n){const e=IB(ve(n,"one_timer"));let t=0,i=null;const s=new Map,a={count:0,total_ball_speed:0,fastest_ball_speed:0},r={count:0,total_ball_speed:0,fastest_ball_speed:0};return{applyFrame(o){for(const[l,c]of s)LB(c,o.frame_number,o.time,o.is_live_play&&l===i);if(!o.is_live_play)i=null;else{let l=!1;for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.index-t.index}).map(({event:e})=>e)}function NB(n,e,t,i){n.is_last_completed_pass=i,n.time_since_last_completed_pass=n.last_completed_pass_time==null?null:Math.max(0,t-n.last_completed_pass_time),n.frames_since_last_completed_pass=n.last_completed_pass_frame==null?null:Math.max(0,e-n.last_completed_pass_frame)}function UB(n,e,t,i){n.completed_pass_count+=1,n.total_pass_distance+=e.ball_travel_distance,n.total_pass_advance+=e.ball_advance_distance,n.longest_pass_distance=Math.max(n.longest_pass_distance,e.ball_travel_distance),n.last_completed_pass_time=e.time,n.last_completed_pass_frame=e.frame,n.time_since_last_completed_pass=Math.max(0,i-e.time),n.frames_since_last_completed_pass=Math.max(0,t-e.frame)}function BB(n,e){Object.assign(n,e??e_())}function wb(n,e){Object.assign(n,e)}function zB(n){const e=RM(n);for(const t of n.frames)e.applyFrame(t);return n}function RM(n){const e=FB(ve(n,"pass"));let t=0,i=null;const s=new Map,a={completed_pass_count:0,total_pass_distance:0,total_pass_advance:0,longest_pass_distance:0},r={completed_pass_count:0,total_pass_distance:0,total_pass_advance:0,longest_pass_distance:0};return{applyFrame(o){for(const[l,c]of s)NB(c,o.frame_number,o.time,o.is_live_play&&l===i);if(!o.is_live_play)i=null;else{let l=!1;for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function GB(n){return t_(n)}function $B(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function PM(n,e,t){const i=$B(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=ml(s.value,t):(n.entries.push({labels:i,value:Ll(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function WB(n,e){return n.key==="possession_state"&&n.value==="team_zero"?{key:"possession_state",value:e?"own":"opponent"}:n.key==="possession_state"&&n.value==="team_one"?{key:"possession_state",value:e?"opponent":"own"}:n.key==="field_third"&&n.value==="team_zero_third"?{key:"field_third",value:e?"defensive_third":"offensive_third"}:n.key==="field_third"&&n.value==="team_one_third"?{key:"field_third",value:e?"offensive_third":"defensive_third"}:n.key==="field_half"&&n.value==="team_zero_side"?{key:"field_half",value:e?"defensive_half":"offensive_half"}:n.key==="field_half"&&n.value==="team_one_side"?{key:"field_half",value:e?"offensive_half":"defensive_half"}:{...n}}function Sb(n,e){const t={entries:[]};for(const i of n.labeled_time.entries)PM(t,i.labels.map(s=>WB(s,e)),i.value);return{tracked_time:n.tracked_time,possession_time:e?n.team_zero_time:n.team_one_time,opponent_possession_time:e?n.team_one_time:n.team_zero_time,neutral_time:n.neutral_time,labeled_time:t}}function XB(n,e){n.active=e.active,n.possessionState=e.possession_state}function KB(n,e,t){if(!e.active)return;const i=Ll(t.dt);n.tracked_time=ml(n.tracked_time,i),e.possessionState==="team_zero"?n.team_zero_time=ml(n.team_zero_time,i):e.possessionState==="team_one"?n.team_one_time=ml(n.team_one_time,i):n.neutral_time=ml(n.neutral_time,i);const s=[{key:"possession_state",value:e.possessionState}];e.fieldThird!=null&&s.push({key:"field_third",value:e.fieldThird}),e.fieldHalf!=null&&s.push({key:"field_half",value:e.fieldHalf}),PM(n.labeled_time,s,i)}function Tb(n,e){Object.assign(n,e??VB())}function qB(n){const e=IM(n);for(const t of n.frames)e.applyFrame(t);return n}function IM(n){const e=GB(ve(n,"possession")),t=t_(ve(n,"ball_third")),i=t_(ve(n,"ball_half"));let s=0,a=0,r=0;const o=HB(),l={active:!1,possessionState:"neutral",fieldThird:null,fieldHalf:null};return{applyFrame(c){for(;s({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function ka(n,e){const t=eh(e.player),i=n.get(t)??LM();return n.set(t,i),i}function jB(n,e){switch(n.active_game_time=Xt(n.active_game_time,e.duration),e.state){case"tracked":n.tracked_time=Xt(n.tracked_time,e.duration);break;case"demolished":n.time_demolished=Xt(n.time_demolished,e.duration);break}}function ZB(n,e){switch(e.state){case"defensive":n.time_defensive_third=Xt(n.time_defensive_third,e.duration);break;case"neutral":n.time_neutral_third=Xt(n.time_neutral_third,e.duration);break;case"offensive":n.time_offensive_third=Xt(n.time_offensive_third,e.duration);break}}function JB(n,e){switch(e.state){case"defensive":n.time_defensive_half=Xt(n.time_defensive_half,e.duration);break;case"offensive":n.time_offensive_half=Xt(n.time_offensive_half,e.duration);break}}function QB(n,e){switch(e.state){case"behind_ball":n.time_behind_ball=Xt(n.time_behind_ball,e.duration);break;case"level_with_ball":n.time_level_with_ball=Xt(n.time_level_with_ball,e.duration);break;case"ahead_of_ball":n.time_in_front_of_ball=Xt(n.time_in_front_of_ball,e.duration);break}}function ez(n,e){switch(e.state){case"no_teammates":n.time_no_teammates=Xt(n.time_no_teammates,e.duration);break;case"most_back":n.time_most_back=Xt(n.time_most_back,e.duration);break;case"most_forward":n.time_most_forward=Xt(n.time_most_forward,e.duration);break;case"mid":n.time_mid_role=Xt(n.time_mid_role,e.duration);break;case"other":n.time_other_role=Xt(n.time_other_role,e.duration);break}}function tz(n,e,t){t.state.closest_to_ball_team&&(e.tracked_time=Xt(e.tracked_time,t.duration),e.time_closest_to_ball_team=Xt(e.time_closest_to_ball_team,t.duration),n.time_closest_to_ball_team=Xt(n.time_closest_to_ball_team,t.duration)),t.state.closest_to_ball_absolute&&(e.time_closest_to_ball_absolute=Xt(e.time_closest_to_ball_absolute,t.duration),n.time_closest_to_ball_absolute=Xt(n.time_closest_to_ball_absolute,t.duration)),t.state.farthest_from_ball&&(n.time_farthest_from_ball=Xt(n.time_farthest_from_ball,t.duration))}function nz(n,e){e.state==="shadowing"&&(n.time_shadow_defense=Xt(n.time_shadow_defense,e.duration))}function iz(n,e){Object.assign(n,e??LM())}function Mb(n,e){Object.assign(n,e??n_())}function Oa(n,e){const t=YB(n),i=new Array(t.length).fill(0);return{applyThroughFrame(s){for(let a=0;as.frame_number)break;const o=sz(r,s),l=o-i[a];l>0&&(i[a]=o,e({...r,duration:l}))}}}}function sz(n,e){if(e.frame_number>=n.end_frame)return n.duration;const t=n.end_time-n.time;if(t<=0)return 0;const i=Math.max(0,e.time-n.time);return n.duration*Math.min(1,i/t)}function az(n){const e=DM(n);for(const t of n.frames)e.applyFrame(t);return n}function DM(n){const e=new Map,t=n_(),i=n_(),s=[Oa(ve(n,"player_activity"),a=>jB(ka(e,a),a)),Oa(ve(n,"field_third"),a=>ZB(ka(e,a),a)),Oa(ve(n,"field_half"),a=>JB(ka(e,a),a)),Oa(ve(n,"ball_depth"),a=>QB(ka(e,a),a)),Oa(ve(n,"depth_role"),a=>ez(ka(e,a),a)),Oa(ve(n,"ball_proximity"),a=>tz(ka(e,a),a.is_team_0?t:i,a)),Oa(ve(n,"shadow_defense"),a=>nz(ka(e,a),a))];return{applyFrame(a){for(const r of s)r.applyThroughFrame(a);Mb(a.team_zero.positioning,t),Mb(a.team_one.positioning,i);for(const r of a.players)iz(r.positioning,e.get(eh(r.player_id))),rz(r.positioning,n,r.player_id)}}}function rz(n,e,t){const i=e.positioning_summary;if(!Array.isArray(i))return;const s=eh(t),a=i.find(r=>!r||typeof r!="object"?!1:eh(r.player_id)===s);a?.distance&&Object.assign(n,a.distance)}function Vp(n){if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function _l(){return{total_duration:0,press_count:0}}function oz(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function lz(n){return n.gameplay_phase==="active_play"||n.gameplay_phase==="kickoff_waiting_for_touch"}function Gp(n,e){Object.assign(n,e??_l())}function cz(n){const e=kM(n);for(const t of n.frames)e.applyFrame(t);return n}function kM(n){const e=oz(ve(n,"powerslide"));let t=0;const i=new Map,s=new Map,a=_l(),r=_l();return{applyFrame(o){const l=lz(o);for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function fz(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function OM(n,e,t){const i=fz(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=gl(s.value,t):(n.entries.push({labels:i,value:Dl(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function pz(n,e){return n.key==="field_half"&&n.value==="team_zero_side"?{key:"field_half",value:e?"defensive_half":"offensive_half"}:n.key==="field_half"&&n.value==="team_one_side"?{key:"field_half",value:e?"offensive_half":"defensive_half"}:{...n}}function Eb(n,e){const t={entries:[]};for(const i of n.labeled_time.entries)OM(t,i.labels.map(s=>pz(s,e)),i.value);return{tracked_time:n.tracked_time,defensive_half_time:e?n.team_zero_side_time:n.team_one_side_time,offensive_half_time:e?n.team_one_side_time:n.team_zero_side_time,neutral_time:n.neutral_time,labeled_time:t}}function mz(n,e){n.active=e.active,n.fieldHalf=e.field_half}function _z(n,e,t){if(!e.active)return;const i=Dl(t.dt);n.tracked_time=gl(n.tracked_time,i),e.fieldHalf==="team_zero_side"?n.team_zero_side_time=gl(n.team_zero_side_time,i):e.fieldHalf==="team_one_side"?n.team_one_side_time=gl(n.team_one_side_time,i):n.neutral_time=gl(n.neutral_time,i),OM(n.labeled_time,[{key:"field_half",value:e.fieldHalf}],i)}function Cb(n,e){Object.assign(n,e??dz())}function gz(n){const e=FM(n);for(const t of n.frames)e.applyFrame(t);return n}function FM(n){const e=hz(ve(n,"ball_half"));let t=0;const i=uz(),s={active:!1,fieldHalf:"neutral"};return{applyFrame(a){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function xz(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function NM(n,e,t){const i=xz(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=yl(s.value,t):(n.entries.push({labels:i,value:kl(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function wz(n,e){return n.key==="field_third"&&n.value==="team_zero_third"?{key:"field_third",value:e?"defensive_third":"offensive_third"}:n.key==="field_third"&&n.value==="team_one_third"?{key:"field_third",value:e?"offensive_third":"defensive_third"}:{...n}}function Ab(n,e){const t={entries:[]};for(const i of n.labeled_time.entries)NM(t,i.labels.map(s=>wz(s,e)),i.value);return{tracked_time:n.tracked_time,defensive_third_time:e?n.team_zero_third_time:n.team_one_third_time,neutral_third_time:n.neutral_third_time,offensive_third_time:e?n.team_one_third_time:n.team_zero_third_time,labeled_time:t}}function Sz(n,e){n.active=e.active,n.fieldThird=e.field_third}function Tz(n,e,t){if(!e.active)return;const i=kl(t.dt);n.tracked_time=yl(n.tracked_time,i),e.fieldThird==="team_zero_third"?n.team_zero_third_time=yl(n.team_zero_third_time,i):e.fieldThird==="team_one_third"?n.team_one_third_time=yl(n.team_one_third_time,i):n.neutral_third_time=yl(n.neutral_third_time,i),NM(n.labeled_time,[{key:"field_third",value:e.fieldThird}],i)}function Rb(n,e){Object.assign(n,e??vz())}function Mz(n){const e=UM(n);for(const t of n.frames)e.applyFrame(t);return n}function UM(n){const e=bz(ve(n,"ball_third"));let t=0;const i=yz(),s={active:!1,fieldThird:"neutral_third"};return{applyFrame(a){for(;t({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function Cz(n,e,t){n.session_count+=1,n.session_time=Pu(n.session_time,t.duration),n.offensive_half_time=Pu(n.offensive_half_time,t.offensive_half_time),n.offensive_third_time=Pu(n.offensive_third_time,t.offensive_third_time),n.longest_session_time=Math.max(n.longest_session_time,t.duration),n.average_session_time=n.session_count===0?0:ju(n.session_time/n.session_count),e.opponent_session_count+=1,e.opponent_session_time=Pu(e.opponent_session_time,t.duration),e.opponent_longest_session_time=Math.max(e.opponent_longest_session_time,t.duration)}function Ib(n,e){Object.assign(n,e)}function Az(n){const e=BM(n);for(const t of n.frames)e.applyFrame(t);return n}function BM(n){const e=Ez(ve(n,"territorial_pressure"));let t=0;const i=Pb(),s=Pb();return{applyFrame(a){for(;t=e[t].end_frame;){const r=e[t];Cz(r.team_is_team_0?i:s,r.team_is_team_0?s:i,r),t+=1}Ib(a.team_zero.territorial_pressure,i),Ib(a.team_one.territorial_pressure,s)}}}function Kr(n,e){return Math.fround(Math.fround(n)+Math.fround(e))}function zM(n){if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function HM(){return{active_game_time:0,time_first_man:0,time_second_man:0,time_third_man:0,time_ambiguous_role:0,longest_first_man_stint_time:0,first_man_stint_count:0,became_first_man_count:0,lost_first_man_count:0,current_role_state:"unknown"}}function Lb(){return{first_man_changes_for_team:0,rotation_count:0}}function Db(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function Rz(n,e,t,i,s){const a=n.stats;switch(a.active_game_time=Kr(a.active_game_time,t),a.current_role_state=e.state,e.state){case"first_man":{n.lastFirstManEndTime!==null&&e.time-n.lastFirstManEndTime<=s?n.currentFirstManStintTime=Kr(n.currentFirstManStintTime,t):(n.currentFirstManStintTime=t,a.first_man_stint_count+=1),n.lastFirstManEndTime=i,a.longest_first_man_stint_time=Math.max(a.longest_first_man_stint_time,n.currentFirstManStintTime),a.time_first_man=Kr(a.time_first_man,t);break}case"second_man":a.time_second_man=Kr(a.time_second_man,t);break;case"third_man":a.time_third_man=Kr(a.time_third_man,t);break;case"ambiguous":a.time_ambiguous_role=Kr(a.time_ambiguous_role,t);break}}function Pz(n,e){if(e.frame_number>=n.end_frame)return n.duration;const t=n.end_time-n.time;if(t<=0)return 0;const i=Math.max(0,e.time-n.time);return n.duration*Math.min(1,i/t)}function i_(n,e){const t=zM(e),i=n.get(t)??{currentFirstManStintTime:0,lastFirstManEndTime:null,stats:HM()};return n.set(t,i),i}function Iz(n,e,t){n.first_man_changes_for_team+=1,n.rotation_count+=1,i_(e,t.previous_first_man).stats.lost_first_man_count+=1,i_(e,t.next_first_man).stats.became_first_man_count+=1}function Lz(n,e){Object.assign(n,e??HM())}function kb(n,e){Object.assign(n,e)}function Dz(n){const e=VM(n);for(const t of n.frames)e.applyFrame(t);return n}function VM(n){const e=Db(ve(n,"rotation_role")),t=Db(ve(n,"first_man_change")),i=n.config.rotation_first_man_stint_end_grace_seconds,s=new Array(e.length).fill(0);let a=0;const r=new Map,o=Lb(),l=Lb();return{applyFrame(c){for(let u=0;uc.frame_number)break;const h=Pz(d,c),f=h-s[u];if(f>0){s[u]=h;const p=c.frame_number>=d.end_frame?d.end_time:Math.min(c.time,d.end_time);Rz(i_(r,d.player),d,f,p,i)}}for(;a({event:e,index:t})).sort((e,t)=>e.event.start_frame!==t.event.start_frame?e.event.start_frame-t.event.start_frame:e.event.start_time!==t.event.start_time?e.event.start_time-t.event.start_time:e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.index-t.index).map(({event:e})=>e)}function Oz(n,e){n.count+=1,e.attackers===2&&e.defenders===1?n.two_v_one_count+=1:e.attackers===2&&e.defenders===2?n.two_v_two_count+=1:e.attackers===2&&e.defenders===3?n.two_v_three_count+=1:e.attackers===3&&e.defenders===1?n.three_v_one_count+=1:e.attackers===3&&e.defenders===2?n.three_v_two_count+=1:e.attackers===3&&e.defenders===3&&(n.three_v_three_count+=1)}function Fb(n,e){Object.assign(n,e)}function Fz(n){const e=GM(n);for(const t of n.frames)e.applyFrame(t);return n}function GM(n){const e=kz(ve(n,"rush"));let t=0;const i=Ob(),s=Ob(),a=n.config.rush_min_possession_retained_seconds;return{applyFrame(r){for(;t=e[t].start_frame&&r.time-e[t].start_time>=a;){const o=e[t];Oz(o.is_team_0?i:s,o),t+=1}Fb(r.team_zero.rush,i),Fb(r.team_one.rush,s)}}}const Nz=["control","hard_hit","medium_hit"],Uz=["ground","high_air","low_air"],Bz=["air","ground","wall"],zz=["dodge","no_dodge"];function lo(n){return Math.fround(n)}function Zu(n,e){return lo(lo(n)+lo(e))}function $M(n,e){return lo(lo(n)-lo(e))}function $p(n){if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function Hz(){return{entries:zz.flatMap(n=>Uz.flatMap(e=>Nz.flatMap(t=>Bz.map(i=>({labels:[{key:"dodge_state",value:n},{key:"height_band",value:e},{key:"kind",value:t},{key:"surface",value:i}],count:0}))))).sort((n,e)=>JSON.stringify(n.labels).localeCompare(JSON.stringify(e.labels)))}}function WM(){return{touch_count:0,control_touch_count:0,medium_hit_count:0,hard_hit_count:0,aerial_touch_count:0,high_aerial_touch_count:0,wall_touch_count:0,first_touch_count:0,is_last_touch:!1,last_touch_time:null,last_touch_frame:null,time_since_last_touch:null,frames_since_last_touch:null,last_ball_speed_change:null,max_ball_speed_change:0,cumulative_ball_speed_change:0,total_ball_travel_distance:0,total_ball_advance_distance:0,total_ball_retreat_distance:0,labeled_touch_counts:Hz()}}const Vz=WM();function Nb(){return{stats:WM(),labeledCountsVersion:0,labeledCountsSnapshot:void 0,labeledCountsSnapshotVersion:-1}}function Gz(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function $z(n,e){e.sort((s,a)=>s.key===a.key?s.value.localeCompare(a.value):s.key.localeCompare(a.key));const t=n.labeled_touch_counts?.entries??[];n.labeled_touch_counts={entries:t};const i=t.find(s=>s.labels.length===e.length&&s.labels.every((a,r)=>a.key===e[r]?.key&&a.value===e[r]?.value));i?i.count+=1:(t.push({labels:e,count:1}),t.sort((s,a)=>JSON.stringify(s.labels).localeCompare(JSON.stringify(a.labels))))}function Wz(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function Iu(n,e){return n.tags?.find(t=>t.group===e)?.value??null}function Xz(n,e,t){const i=Iu(e,"kind")??"control",s=Iu(e,"height_band")??"ground",a=Iu(e,"surface")??"ground",r=Iu(e,"dodge_state")??"no_dodge",o=n.stats;o.touch_count+=1,i==="control"?o.control_touch_count+=1:i==="medium_hit"?o.medium_hit_count+=1:i==="hard_hit"&&(o.hard_hit_count+=1),s==="low_air"?o.aerial_touch_count+=1:s==="high_air"&&(o.aerial_touch_count+=1,o.high_aerial_touch_count+=1),a==="wall"&&(o.wall_touch_count+=1),$z(o,[{key:"kind",value:i},{key:"height_band",value:s},{key:"surface",value:a},{key:"dodge_state",value:r}]),n.labeledCountsVersion+=1,o.last_touch_time=e.time,o.last_touch_frame=e.frame,o.time_since_last_touch=Math.max(0,$M(t.time,e.time)),o.frames_since_last_touch=Math.max(0,t.frame_number-e.frame),o.last_ball_speed_change=e.ball_speed_change,o.max_ball_speed_change=Math.max(o.max_ball_speed_change,e.ball_speed_change),o.cumulative_ball_speed_change=Zu(o.cumulative_ball_speed_change,e.ball_speed_change)}function Kz(n){return n.labeledCountsSnapshotVersion!==n.labeledCountsVersion&&(n.labeledCountsSnapshot=n.stats.labeled_touch_counts?Wz(n.stats.labeled_touch_counts):void 0,n.labeledCountsSnapshotVersion=n.labeledCountsVersion),n.labeledCountsSnapshot}function qz(n,e){if(!e){Object.assign(n,Vz);return}Object.assign(n,e.stats,{labeled_touch_counts:Kz(e)})}function Yz(n){const e=XM(n);for(const t of n.frames)e.applyFrame(t);return n}function XM(n){const e=Gz(ve(n,"touch")),t=e.flatMap(o=>o.ball_movement?[{player:o.player,movement:o.ball_movement}]:[]).sort((o,l)=>o.movement.end_frame!==l.movement.end_frame?o.movement.end_frame-l.movement.end_frame:o.movement.end_time-l.movement.end_time);let i=0,s=0,a=null;const r=new Map;return{applyFrame(o){if(!o.is_live_play)a=null;else{for(const l of r.values()){const c=l.stats;c.is_last_touch=!1,c.last_touch_time!=null&&(c.time_since_last_touch=Math.max(0,$M(o.time,c.last_touch_time))),c.last_touch_frame!=null&&(c.frames_since_last_touch=Math.max(0,o.frame_number-c.last_touch_frame))}for(;i({event:e,index:t})).sort((e,t)=>e.event.resolved_frame!==t.event.resolved_frame?e.event.resolved_frame-t.event.resolved_frame:e.event.resolved_time!==t.event.resolved_time?e.event.resolved_time-t.event.resolved_time:e.index-t.index).map(({event:e})=>e)}function Jz(n,e,t){n.is_last_whiff=!1,n.time_since_last_whiff=n.last_whiff_time==null?null:Math.max(0,t-n.last_whiff_time),n.frames_since_last_whiff=n.last_whiff_frame==null?null:Math.max(0,e-n.last_whiff_frame)}function Qz(n,e,t,i){if((e.kind??"whiff")==="beaten_to_ball"){n.beaten_to_ball_count+=1;return}n.whiff_count+=1,e.aerial?n.aerial_whiff_count+=1:n.grounded_whiff_count+=1,e.dodge_active&&(n.dodge_whiff_count+=1),n.is_last_whiff=!0,n.last_whiff_time=e.time,n.last_whiff_frame=e.frame,n.time_since_last_whiff=Math.max(0,i-e.time),n.frames_since_last_whiff=Math.max(0,t-e.frame),n.last_closest_approach_distance=e.closest_approach_distance,n.best_closest_approach_distance=n.best_closest_approach_distance==null?e.closest_approach_distance:Math.min(n.best_closest_approach_distance,e.closest_approach_distance),n.cumulative_closest_approach_distance+=e.closest_approach_distance}function Ub(n,e){Object.assign(n,e??s_())}function eH(n){const e=KM(n);for(const t of n.frames)e.applyFrame(t);return n}function KM(n){const e=Zz(ve(n,"whiff"));let t=0,i=null;const s=new Map,a=new Map;return{applyFrame(r){if(r.is_live_play){for(const o of s.values())Jz(o,r.frame_number,r.time);for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function iH(n,e,t,i){n.is_last_wall_aerial=i,n.time_since_last_wall_aerial=n.last_wall_aerial_time==null?null:Math.max(0,qM(t,n.last_wall_aerial_time)),n.frames_since_last_wall_aerial=n.last_wall_aerial_frame==null?null:Math.max(0,e-n.last_wall_aerial_frame)}function sH(n,e,t,i){n.count+=1,e.confidence>=tH&&(n.high_confidence_count+=1),n.is_last_wall_aerial=!0,n.last_wall_aerial_time=e.time,n.last_wall_aerial_frame=e.frame,n.time_since_last_wall_aerial=Math.max(0,qM(i,e.time)),n.frames_since_last_wall_aerial=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=Lu(n.cumulative_confidence,e.confidence),n.cumulative_setup_duration=Lu(n.cumulative_setup_duration,e.setup_duration),n.cumulative_takeoff_to_touch_time=Lu(n.cumulative_takeoff_to_touch_time,e.time_since_takeoff),n.cumulative_touch_height=Lu(n.cumulative_touch_height,e.player_position[2]??0)}function aH(n,e){Object.assign(n,e??YM())}function rH(n){const e=jM(n);for(const t of n.frames)e.applyFrame(t);return n}function jM(n){const e=nH(ve(n,"wall_aerial"));let t=0,i=null;const s=new Map;return{applyFrame(a){for(const[r,o]of s)iH(o,a.frame_number,a.time,a.is_live_play&&r===i);if(!a.is_live_play)i=null;else{for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function cH(n,e,t,i){n.is_last_wall_aerial_shot=i,n.time_since_last_wall_aerial_shot=n.last_wall_aerial_shot_time==null?null:Math.max(0,ZM(t,n.last_wall_aerial_shot_time)),n.frames_since_last_wall_aerial_shot=n.last_wall_aerial_shot_frame==null?null:Math.max(0,e-n.last_wall_aerial_shot_frame)}function uH(n,e,t,i){n.count+=1,e.confidence>=oH&&(n.high_confidence_count+=1),n.is_last_wall_aerial_shot=!0,n.last_wall_aerial_shot_time=e.time,n.last_wall_aerial_shot_frame=e.frame,n.time_since_last_wall_aerial_shot=Math.max(0,ZM(i,e.time)),n.frames_since_last_wall_aerial_shot=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=Xp(n.cumulative_confidence,e.confidence),n.cumulative_takeoff_to_shot_time=Xp(n.cumulative_takeoff_to_shot_time,e.time_since_takeoff),n.cumulative_shot_height=Xp(n.cumulative_shot_height,e.player_position[2]??0)}function dH(n,e){Object.assign(n,e??JM())}function hH(n){const e=QM(n);for(const t of n.frames)e.applyFrame(t);return n}function QM(n){const e=lH(ve(n,"wall_aerial_shot"));let t=0,i=null;const s=new Map;return{applyFrame(a){for(const[r,o]of s)cH(o,a.frame_number,a.time,a.is_live_play&&r===i);if(!a.is_live_play)i=null;else{let r=!1;for(;t[f.frame_number,p])),a=new Map,r={...n,frames:[]},o=_H.flatMap(f=>f.createFrameAccumulator?[f.createFrameAccumulator(r)]:[]),l=Math.max(1,t.materializationChunkSize??fH),c=Math.max(l,t.maxMaterializationChunkSize??pH);let u=-1,d=l;const h=f=>{if(f<=u)return;const p=Math.min(i.length-1,Math.max(f,u+d));for(let g=u+1;g<=p;g+=1){const _=i[g],m=_?bH(vH(_)):void 0;if(m){for(const v of o)v.applyFrame(m);a.set(m.frame_number,m)}}u=p,d=Math.min(c,i.length,d*mH)};return{get(f){const p=s.get(f);if(p!==void 0)return h(p),a.get(f)}}}function yH(n){return!n||typeof n!="object"?n:{...n}}function vH(n){return{...n,team_zero:{...n.team_zero},team_one:{...n.team_one},players:n.players.map(e=>({...e,player_id:yH(e.player_id)}))}}function bH(n){return{...n,team_zero:Yl(n.team_zero??{}),team_one:Yl(n.team_one??{}),players:n.players.map(t=>eE(t))}}function jl(n){return n.events?.events??[]}function ve(n,e){return jl(n).filter(t=>t.payload.kind===e).map(t=>t.payload.payload)}const xH=new Set(["is_team_0","name","player_id"]);function Hb(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0}function wH(n){return!n||typeof n!="object"||Array.isArray(n)?!1:Object.keys(n).every(e=>xH.has(e))}function SH(n){return Hb(n.team_zero)&&Hb(n.team_one)&&n.players.every(e=>wH(e))}function TH(n){return new Map(BT(n).frames.map(e=>[e.frame_number,e]))}function MH(n,e,t){const i=n.frames.filter(s=>SH(s)).length;if(i===n.frames.length)return gH(n,e,t);if(i>0)throw new Error("stats timeline frames must be either all compact scaffolds or all materialized snapshots");return TH(n)}function zt(n,e){return n.get(e)??null}const Ng=[{stage:"validating",index:1,total:9,label:"Parse replay",start:0,end:.08},{stage:"processing",index:2,total:9,label:"Process replay frames",start:.08,end:.62},{stage:"building-stats",index:3,total:9,label:"Build stats events",start:.62,end:.7},{stage:"serializing-replay",index:4,total:9,label:"Serialize replay data",start:.7,end:.76},{stage:"serializing-stats",index:5,total:9,label:"Serialize stats timeline",start:.76,end:.86},{stage:"normalizing",index:6,total:9,label:"Normalize replay model",start:.86,end:.91},{stage:"decoding-replay",index:7,total:9,label:"Decode replay data",start:.91,end:.94},{stage:"decoding-stats",index:8,total:9,label:"Decode stats chunks",start:.94,end:.96},{stage:"deriving-stats",index:9,total:9,label:"Derive stats snapshots",start:.96,end:1}];function tE(n){return Math.max(0,Math.min(1,n))}function Kp(n,e,t){if(n!==void 0)return tE((n-e)/(t-e))}function Ug(n){if(n.stage!=="stats-timeline")return n;const e=n.progress;return e===void 0?{...n,stage:"building-stats"}:e<.35?{...n,stage:"building-stats",progress:Kp(e,0,.35)}:e<.55?{...n,stage:"serializing-replay",progress:Kp(e,.35,.55)}:{...n,stage:"serializing-stats",progress:Kp(e,.55,.92)}}function nE(n){const e=Ug(n);return Ng.find(t=>t.stage===e.stage)}function EH(){return Ng.map(({stage:n,index:e,total:t,label:i})=>({stage:n,index:e,total:t,label:i}))}function CH(n){const e=nE(n);return{stage:e.stage,index:e.index,total:e.total,label:e.label}}function AH(n){const e=Ug(n),t=nE(e);return Ng.map(({stage:i,index:s,total:a,label:r})=>{if(st.index)return{stage:i,index:s,total:a,label:r,state:"pending",completion:0,indeterminate:!1};const o=e.progress!==void 0;return{stage:i,index:s,total:a,label:r,state:"active",completion:o?tE(e.progress??0):1,indeterminate:!o}})}function tf(n){const e=Ug(n),t=e.progress===void 0?null:Math.round(e.progress*100);switch(e.stage){case"validating":return"Parsing replay...";case"processing":return t!==null&&e.totalFrames!==void 0?`Processing replay frames... ${t}% (${e.processedFrames??0}/${e.totalFrames})`:"Processing replay frames...";case"building-stats":return t!==null?e.totalFrames!==void 0?`Building stats events... ${t}% (${e.processedFrames??0}/${e.totalFrames})`:`Building stats events... ${t}%`:"Building stats events...";case"serializing-replay":return t!==null?`Serializing replay data... ${t}%`:"Serializing replay data...";case"serializing-stats":return t!==null?`Serializing stats timeline... ${t}%`:"Serializing stats timeline...";case"decoding-replay":return t!==null?`Decoding replay data... ${t}%`:"Decoding replay data...";case"decoding-stats":return t!==null?e.totalChunks!==void 0?`Decoding stats chunks... ${t}% (${e.processedChunks??0}/${e.totalChunks})`:`Decoding stats chunks... ${t}%`:"Decoding stats chunks...";case"deriving-stats":return t!==null?`Deriving stats snapshots... ${t}%`:"Deriving stats snapshots...";case"normalizing":return t!==null?`Normalizing replay model... ${t}%`:"Normalizing replay model...";default:return"Loading replay..."}}function RH(n){return n instanceof Error?n:new Error(String(n))}function Rs(n,e){return JSON.parse(n.decode(new Uint8Array(e)))}async function PH(n,e,t){t?.({stage:"decoding-stats",progress:0});const i=Rs(n,e.configBuffer);t?.({stage:"decoding-stats",progress:.05}),await Za();const s=Rs(n,e.replayMetaBuffer);t?.({stage:"decoding-stats",progress:.1}),await Za();const a=Rs(n,e.eventsBuffer),r=Rs(n,e.activitySummaryBuffer),o=Rs(n,e.positioningSummaryBuffer),l=Rs(n,e.accumulationTracksBuffer);t?.({stage:"decoding-stats",progress:.15}),await Za();const c=[],u=e.frameChunkBuffers.length;for(let d=0;d{let t=!1,i=null;const s=()=>{t||(t=!0,i!==null&&clearTimeout(i),e())};i=setTimeout(s,n),requestAnimationFrame(()=>s())})}async function iE(n,e={}){if(typeof Worker>"u")throw new Error("Replay loading worker is not available in this environment");const t=new Worker(new URL(""+new URL("replayLoader.worker-D3pjMe81.js",import.meta.url).href,import.meta.url),{type:"module"}),i=n.slice(),s=e.reportEveryNFrames??100;return new Promise((a,r)=>{const o=()=>{t.terminate()};t.onmessage=async c=>{const u=c.data;if(u.type==="progress"){e.onProgress?.(u.progress);return}if(u.type==="error"){o(),r(new Error(u.error));return}o();try{const d=new TextDecoder;e.onProgress?.({stage:"decoding-replay",progress:0}),await Za();const h=Rs(d,u.replayBuffer);e.onProgress?.({stage:"decoding-replay",progress:.5}),await Za();const f=Rs(d,u.rawReplayBuffer);e.onProgress?.({stage:"decoding-replay",progress:1}),await Za();const p=await PH(d,u.statsTimelineParts,e.onProgress),g=MH(p);a({replay:h,raw:f,statsTimeline:p,statsFrameLookup:g})}catch(d){r(RH(d))}},t.onerror=c=>{o(),r(new Error(c.message||"Replay loading worker failed"))};const l={type:"load-replay",bytes:i.buffer,reportEveryNFrames:s};t.postMessage(l,[i.buffer])})}function IH(n){const e=document.createElement("div");e.className="replay-load-modal",e.hidden=!0;const t=document.createElement("div");t.className="replay-load-modal__dialog",t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-labelledby","replay-load-modal-title");const i=document.createElement("p");i.className="replay-load-modal__eyebrow",i.textContent="Replay loading";const s=document.createElement("h2");s.id="replay-load-modal-title",s.className="replay-load-modal__title",s.textContent="Preparing replay pipeline";const a=document.createElement("p");a.className="replay-load-modal__status",a.textContent="Preparing replay...";const r=document.createElement("div");r.className="replay-load-modal__phase-list";const o=new Map;for(const f of EH()){const p=document.createElement("div");p.className="replay-load-modal__phase-row",p.dataset.state="pending";const g=document.createElement("p");g.className="replay-load-modal__phase-label",g.textContent=`${f.index}. ${f.label}`;const _=document.createElement("div");_.className="replay-load-modal__phase-bar";const m=document.createElement("div");m.className="replay-load-modal__phase-fill",m.dataset.indeterminate="false",_.append(m),p.append(g,_),r.append(p),o.set(f.stage,{row:p,fill:m})}const l=document.createElement("p");l.className="replay-load-modal__meta",t.append(i,s,a,r,l),e.append(t),n.append(e);let c="";const u=()=>{for(const{row:f,fill:p}of o.values())f.dataset.state="pending",p.style.width="0%",p.dataset.indeterminate="false"},d=f=>{for(const p of AH(f)){const g=o.get(p.stage);g&&(g.row.dataset.state=p.state,g.fill.dataset.indeterminate=p.indeterminate?"true":"false",g.fill.style.width=`${Math.round(p.completion*100)}%`)}},h=f=>{e.hidden=!f};return{show(f,p="Preparing replay..."){c=f,h(!0),u(),s.textContent="Preparing replay pipeline",a.textContent=p,l.textContent=`Loading ${f}`},update(f){h(!0);const p=CH(f);if(d(f),s.textContent=`Phase ${p.index} of ${p.total}: ${p.label}`,a.textContent=tf(f),f.stage==="processing"&&f.totalFrames!==void 0){l.textContent=`${f.processedFrames??0}/${f.totalFrames} frames`;return}if(f.stage==="decoding-stats"&&f.totalChunks!==void 0){l.textContent=`${f.processedChunks??0}/${f.totalChunks} chunks`;return}l.textContent=c?`Loading ${c}`:""},hide(){h(!1)},destroy(){e.remove()}}}const LH=["free","follow"];function sE(n){return n.useReplayBallCam??!1?"player":n.ballCamEnabled?"on":"off"}function Vb(n){return n.useReplayBallCam?"player":n.ballCam===!0?"on":n.ballCam===!1?"off":"player"}const aE={fov:110,height:100,pitch:-4,distance:270,stiffness:0,swivelSpeed:1,transitionSpeed:1};class Bg{constructor(e){this.options=e}lastFreeCameraPreset=null;get freeCameraPreset(){return this.lastFreeCameraPreset}set freeCameraPreset(e){this.lastFreeCameraPreset=e}ballCamModeValue="player";get ballCamMode(){return this.ballCamModeValue}autoPossessionEnabledValue=!1;get autoPossessionEnabled(){return this.autoPossessionEnabledValue}static ballCamEnabledForMode(e){return e==="player"?null:e==="on"}followPlayerWithReplayCamera(e,t={}){const i=this.options.getReplayPlayer();i&&(t.preserveAutoPossession||this.setAutoPossessionEnabled(!1,{requestConfigSync:!1}),i.setAttachedPlayer(e),i.setCameraViewMode("follow"),t.usePlayerCameraSettings!==!1&&i.setCustomCameraSettings(null),this.setBallCamMode(t.ballCam??"player"),this.lastFreeCameraPreset=null,t.requestConfigSync!==!1&&this.options.requestConfigSync())}setAutoPossessionEnabled(e,t={}){if(this.autoPossessionEnabledValue===e){this.renderAutoPossessionButton();return}this.autoPossessionEnabledValue=e,this.renderAutoPossessionButton(),t.notify!==!1&&this.options.onAutoPossessionChange?.(e),t.requestConfigSync!==!1&&this.options.requestConfigSync()}renderBallCamButtons(){const{ballCamOffButton:e,ballCamOnButton:t,ballCamPlayerButton:i}=this.options.elements,s=[["off",e],["on",t],["player",i]];for(const[a,r]of s){const o=a===this.ballCamModeValue;r.dataset.active=o?"true":"false",r.setAttribute("aria-pressed",o?"true":"false")}}renderAutoPossessionButton(){this.options.elements.cameraViewAutoPossession.checked=this.autoPossessionEnabledValue}disableAutoPossessionForManualCameraControl(){this.setAutoPossessionEnabled(!1,{requestConfigSync:!1})}setBallCamMode(e){this.ballCamModeValue=e,this.options.getReplayPlayer()?.setBallCamEnabled(Bg.ballCamEnabledForMode(e)),this.renderBallCamButtons()}get nameplateLiftUu(){const e=Number(this.options.elements.nameplateLift.value);return Number.isFinite(e)?e:Um}applyNameplateLiftUu(e){const{nameplateLift:t,nameplateLiftReadout:i}=this.options.elements,s=e??Um;t.value=`${s}`,i.textContent=qn(s,"",0)}installEventListeners(e){const{elements:t}=this.options;t.usePlayerCameraSettings.addEventListener("change",()=>{const s=t.usePlayerCameraSettings.checked;t.cameraSettingsControls.hidden=s,this.options.getReplayPlayer()?.setCustomCameraSettings(s?null:this.readCustomCameraSettings()),this.options.requestConfigSync()},{signal:e});for(const s of[t.customCameraFov,t.customCameraHeight,t.customCameraPitch,t.customCameraDistance,t.customCameraStiffness,t.customCameraSwivelSpeed,t.customCameraTransitionSpeed])s.addEventListener("input",()=>{const a=this.readCustomCameraSettings();this.syncCustomCameraSettingControls(a),this.options.getReplayPlayer()?.setCustomCameraSettings(a),this.options.requestConfigSync()},{signal:e});t.attachedPlayer.addEventListener("change",()=>{const s=this.options.getReplayPlayer(),a=t.attachedPlayer.value||null;this.disableAutoPossessionForManualCameraControl(),s?.setAttachedPlayer(a),a&&(s?.setCustomCameraSettings(null),this.setBallCamMode("player")),this.lastFreeCameraPreset=null,this.options.requestConfigSync()},{signal:e}),t.cameraViewFreeButton.addEventListener("click",()=>{this.options.getReplayPlayer()?.setCameraViewMode("free"),this.disableAutoPossessionForManualCameraControl(),this.lastFreeCameraPreset=null,this.options.requestConfigSync()},{signal:e}),t.cameraViewFollowButton.addEventListener("click",()=>{const s=this.options.getReplayPlayer();this.disableAutoPossessionForManualCameraControl(),s?.setCameraViewMode("follow"),s?.getState().attachedPlayerId&&(s.setCustomCameraSettings(null),this.setBallCamMode("player")),this.lastFreeCameraPreset=null,this.options.requestConfigSync()},{signal:e}),t.cameraViewOverheadButton.addEventListener("click",()=>{this.options.getReplayPlayer()?.setFreeCameraPreset("overhead"),this.disableAutoPossessionForManualCameraControl(),this.lastFreeCameraPreset="overhead",this.options.requestConfigSync()},{signal:e}),t.cameraViewSideButton.addEventListener("click",()=>{this.options.getReplayPlayer()?.setFreeCameraPreset("side"),this.disableAutoPossessionForManualCameraControl(),this.lastFreeCameraPreset="side",this.options.requestConfigSync()},{signal:e});const i=[["off",t.ballCamOffButton],["on",t.ballCamOnButton],["player",t.ballCamPlayerButton]];for(const[s,a]of i)a.addEventListener("click",()=>{this.setBallCamMode(s),this.options.requestConfigSync()},{signal:e});t.cameraViewAutoPossession.addEventListener("change",()=>{this.setAutoPossessionEnabled(t.cameraViewAutoPossession.checked)},{signal:e}),t.nameplateLift.addEventListener("input",()=>{t.nameplateLiftReadout.textContent=qn(this.nameplateLiftUu,"",0),this.options.requestConfigSync()},{signal:e})}setTransportEnabled(e,t){this.options.elements.attachedPlayer.disabled=!e,this.syncModeButtons(e?t:void 0)}syncState(e){const{elements:t}=this.options;t.usePlayerCameraSettings.checked=e.customCameraSettings===null,t.cameraSettingsControls.hidden=t.usePlayerCameraSettings.checked,this.syncCustomCameraSettingControls(e.customCameraSettings??this.getFallbackCameraSettings()),this.ballCamModeValue=sE(e),this.renderBallCamButtons(),t.attachedPlayer.value=e.attachedPlayerId??"",this.syncAvailability(e),this.renderProfile(e)}syncAvailability(e){this.syncModeButtons(e);const i=this.options.getReplayPlayer()!==null&&e?.cameraViewMode==="follow"&&(e.attachedPlayerId??null)!==null;this.options.elements.usePlayerCameraSettings.disabled=!i,this.setCameraSettingControlsEnabled(i&&e?.customCameraSettings!==null),this.options.elements.ballCamOffButton.disabled=!i,this.options.elements.ballCamOnButton.disabled=!i,this.options.elements.ballCamPlayerButton.disabled=!i,this.renderBallCamButtons()}syncModeButtons(e){const t=e?.cameraViewMode??"free",i=this.options.getReplayPlayer()!==null&&e!==void 0,s=(e?.attachedPlayerId??null)!==null;for(const l of LH){const c=this.getCameraViewButton(l);c.disabled=!i||l==="follow"&&!s;const u=l===t;c.dataset.active=u?"true":"false",c.setAttribute("aria-pressed",u?"true":"false")}const{cameraViewOverheadButton:a,cameraViewSideButton:r}=this.options.elements,{cameraViewAutoPossession:o}=this.options.elements;a.disabled=!i,r.disabled=!i,o.disabled=!i,a.dataset.active="false",r.dataset.active="false",this.renderAutoPossessionButton(),a.setAttribute("aria-pressed","false"),r.setAttribute("aria-pressed","false")}populateAttachedPlayerOptions(e){const{attachedPlayer:t}=this.options.elements;t.replaceChildren(),t.append(new Option("Free camera",""));for(const i of e)t.append(new Option(`${i.name} (${i.isTeamZero?"Blue":"Orange"})`,i.id))}renderProfile(e){const t=this.options.elements,i=this.options.getReplayPlayer(),s=e?.attachedPlayerId??null;if(!i||e?.cameraViewMode!=="follow"||s===null){this.renderEmptyProfile("Free camera");return}const a=i.replay.players.find(o=>o.id===s);if(!a){this.renderEmptyProfile("Unknown");return}const r=this.getEffectiveCameraSettings(e);t.cameraProfileReadout.textContent=e.customCameraSettings===null?a.name:`${a.name} custom`,t.cameraFovReadout.textContent=qn(r.fov,"",0),t.cameraHeightReadout.textContent=qn(r.height,"",0),t.cameraPitchReadout.textContent=qn(r.pitch,"",0),t.cameraBaseDistanceReadout.textContent=qn(r.distance,"",0),t.cameraStiffnessReadout.textContent=qn(r.stiffness,"",2)}getFallbackCameraSettings(){return aE}getAttachedPlayerCameraSettings(e){const t=this.options.getReplayPlayer();return!t||e===null?null:t.replay.players.find(i=>i.id===e)?.cameraSettings??null}getEffectiveCameraSettings(e){return{...this.getFallbackCameraSettings(),...this.getAttachedPlayerCameraSettings(e.attachedPlayerId)??{},...e.customCameraSettings??{}}}readCustomCameraSettings(){const e=this.options.elements;return{fov:Number(e.customCameraFov.value),height:Number(e.customCameraHeight.value),pitch:Number(e.customCameraPitch.value),distance:Number(e.customCameraDistance.value),stiffness:Number(e.customCameraStiffness.value),swivelSpeed:Number(e.customCameraSwivelSpeed.value),transitionSpeed:Number(e.customCameraTransitionSpeed.value)}}setCameraSettingControlsEnabled(e){const t=this.options.elements;t.cameraSettingsControls.hidden=t.usePlayerCameraSettings.checked,t.customCameraFov.disabled=!e,t.customCameraHeight.disabled=!e,t.customCameraPitch.disabled=!e,t.customCameraDistance.disabled=!e,t.customCameraStiffness.disabled=!e,t.customCameraSwivelSpeed.disabled=!e,t.customCameraTransitionSpeed.disabled=!e}syncCustomCameraSettingControls(e){const t=this.options.elements,i=this.getFallbackCameraSettings(),s=e.fov??i.fov,a=e.height??i.height,r=e.pitch??i.pitch,o=e.distance??i.distance,l=e.stiffness??i.stiffness,c=e.swivelSpeed??i.swivelSpeed,u=e.transitionSpeed??i.transitionSpeed;t.customCameraFov.value=`${s}`,t.customCameraHeight.value=`${a}`,t.customCameraPitch.value=`${r}`,t.customCameraDistance.value=`${o}`,t.customCameraStiffness.value=`${l}`,t.customCameraSwivelSpeed.value=`${c}`,t.customCameraTransitionSpeed.value=`${u}`,t.customCameraFovReadout.textContent=qn(s,"",0),t.customCameraHeightReadout.textContent=qn(a,"",0),t.customCameraPitchReadout.textContent=qn(r,"",0),t.customCameraDistanceReadout.textContent=qn(o,"",0),t.customCameraStiffnessReadout.textContent=qn(l,"",2),t.customCameraSwivelSpeedReadout.textContent=qn(c,"",1),t.customCameraTransitionSpeedReadout.textContent=qn(u,"",2)}getCameraViewButton(e){switch(e){case"free":return this.options.elements.cameraViewFreeButton;case"follow":return this.options.elements.cameraViewFollowButton}}renderEmptyProfile(e){const t=this.options.elements;t.cameraProfileReadout.textContent=e,t.cameraFovReadout.textContent="--",t.cameraHeightReadout.textContent="--",t.cameraPitchReadout.textContent="--",t.cameraBaseDistanceReadout.textContent="--",t.cameraStiffnessReadout.textContent="--"}}function qn(n,e="",t=0){return n===void 0||Number.isNaN(n)?"--":`${n.toFixed(t)}${e}`}function DH(n){return new Bg(n)}const Gb="subtr-actor-touch-overlay-styles",zg=5882879,Hg=16761180,$b=120,Wb=4,kH=196,qp=24,Xb=210,Kb=5,OH=.1,FH=48,NH=["team","intention","kind","height_band","surface","dodge_state","flag"],UH=[{label:"Blue team",color:zg},{label:"Orange team",color:Hg}],rE=[{label:"Shot",color:16711880},{label:"Save",color:58998},{label:"Clear",color:16764928},{label:"Boom",color:16020150},{label:"Pass",color:47103},{label:"Control",color:0},{label:"Advance",color:16486972}],Ju=[{label:"Control",color:0},{label:"Medium hit",color:16436245},{label:"Hard hit",color:16735596}],Qu=[{label:"Ground",color:10741301},{label:"Low air",color:3718648},{label:"High air",color:8490232}],oE=[{label:"Ground",color:8702998},{label:"Air",color:6333946},{label:"Wall",color:16347926}],a_=[{label:"No dodge",color:9741240},{label:"Dodge",color:15235577}],r_=[{label:"First touch",color:16777215},{label:"Contested",color:15680580}],BH=[{title:"Team",entries:UH},{title:"Intention",entries:rE},{title:"Hit strength",entries:Ju},{title:"Height",entries:Qu},{title:"Surface",entries:oE},{title:"Dodge",entries:a_},{title:"Flags",entries:r_}];function fc(n){return Object.fromEntries(n.map(e=>[e.label.toLowerCase().replaceAll(" ","_"),e.color]))}const lE=fc(rE),cE={...fc(Ju),medium_hit:Ju[1].color,hard_hit:Ju[2].color},uE={...fc(Qu),low_air:Qu[1].color,high_air:Qu[2].color},dE=fc(oE),hE={...fc(a_),no_dodge:a_[0].color},o_={first_touch:r_[0].color,contested:r_[1].color},Vi=10134961;function jn(n,e){const t=n.tags;if(!Array.isArray(t))return null;const i=t.find(s=>s.group===e);return i?i.value:null}function fE(n){return jn(n,"possession")??jn(n,"action")}function At(n){const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function Yp(n,e){return Math.max(0,n-e)}function ed(n){return n==="team"||n==="intention"||n==="kind"||n==="height_band"||n==="surface"||n==="dodge_state"||n==="flag"}function ho(n){const e=Array.isArray(n)?n:n?[n]:["team"],t=new Set,i=[];for(const s of e)ed(s)&&!t.has(s)&&(t.add(s),i.push(s));return i.length>0?i:["team"]}function pE(n){return n[n.length-1]??"team"}function zH(n,e,t){const i=HH(n,pE(t)),s=i?` · ${i.replaceAll("_"," ")}`:"";if(e==="markers")return`${n.playerName}${s}`;const a=Math.round(n.totalBallAdvanceDistance),r=Math.round(n.totalBallRetreatDistance);return a>0&&r>0?`${n.playerName} +${a} / -${r} uu${s}`:r>0?`${n.playerName} -${r} uu${s}`:`${n.playerName} +${a} uu${s}`}function HH(n,e){return e==="intention"?n.intention:e==="kind"?n.kind:e==="height_band"?n.heightBand:e==="surface"?n.surface:e==="dodge_state"?n.dodgeState:e==="flag"?n.contested?"contested":n.firstTouch?"first_touch":null:null}function VH(n){return n.split("_").filter(Boolean).map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1)}`).join(" ")}function sl(n,e,t){return typeof e!="string"||e.length===0?null:{key:n,value:e,label:VH(e),color:t[e]??Vi}}function qb(n,e,t){return e!==!0?null:{key:n,value:"true",label:t,color:o_[n]??Vi}}function GH(n){const e=jn(n,"reception")==="first_touch",t=jn(n,"contested")!=null;return[sl("intention",fE(n),lE),sl("kind",jn(n,"kind"),cE),sl("height_band",jn(n,"height_band"),uE),sl("surface",jn(n,"surface"),dE),sl("dodge_state",jn(n,"dodge_state"),hE),qb("first_touch",e,"First touch"),qb("contested",t,"Contested")].filter(i=>i!=null)}function mE(n,e){return e==="intention"?lE[n.intention??""]??Vi:e==="kind"?cE[n.kind??""]??Vi:e==="height_band"?uE[n.heightBand??""]??Vi:e==="surface"?dE[n.surface??""]??Vi:e==="dodge_state"?hE[n.dodgeState??""]??Vi:e==="flag"?n.contested?o_.contested??Vi:n.firstTouch?o_.first_touch??Vi:Vi:n.isTeamZero?zg:Hg}function $H(n,e){return(e.length>0?e:["team"]).map(i=>mE(n,i))}function _E(n,e){const t=[],i=[...ve(n,"touch")].sort((s,a)=>s.frame!==a.frame?s.frame-a.frame:s.time!==a.time?s.time-a.time:0);for(const s of i){const a=At(s.player),r=e.ballFrames[s.frame]?.position;if(!r)continue;const o=s.ball_movement,c=(o?e.ballFrames[o.end_frame]?.position:null)??r,u=t.length,d=GH(s);t.push({id:`touch-stat:${s.frame}:${a}:${u+1}`,time:e.frames[s.frame]?.time??s.time,frame:s.frame,isTeamZero:s.is_team_0,playerId:a,playerName:e.players.find(h=>h.id===a)?.name??a,kind:jn(s,"kind"),intention:fE(s),heightBand:jn(s,"height_band"),surface:jn(s,"surface"),dodgeState:jn(s,"dodge_state"),firstTouch:jn(s,"reception")==="first_touch",contested:jn(s,"contested")!=null,classifications:d,position:{x:r.x,y:r.y,z:r.z},endPosition:{x:c.x,y:c.y,z:c.z},totalBallTravelDistance:o?Yp(o.travel_distance,0):0,totalBallAdvanceDistance:o?Yp(o.advance_distance,0):0,totalBallRetreatDistance:o?Yp(o.retreat_distance,0):0})}return t}function WH(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function XH(){if(document.getElementById(Gb))return;const n=document.createElement("style");n.id=Gb,n.textContent=` +`}const en="#3b82f6",tn="#f59e0b",G3=new Set(["wavedash"]),$3=new Set(["air_dribble","ball_carry","ceiling_shot","double_tap","flick","flip_reset","half_flip","half_volley","one_timer","speed_flip","wall_aerial","wall_aerial_shot","wavedash"]);function Ai(n){return n.split(/[_-]+/).filter(e=>e.length>0).map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1)}`).join(" ")}function Hv(n){return $3.has(n)&&!G3.has(n)}function of(n){return n===!0?en:n===!1?tn:null}const XT=["timeline","core_player","player_possession","possession","loose_possession","ball_half","ball_third","territorial_pressure","movement","player_activity","field_third","field_half","ball_depth","depth_role","ball_proximity","shadow_defense","rotation_role","first_man_change","goal_context","backboard","ceiling_shot","wall_aerial","wall_aerial_shot","center","flick","flip_reset","dodge_reset","double_tap","fifty_fifty","kickoff","one_timer","pass","ball_carry","controlled_play","rush","dodge","speed_flip","half_flip","half_volley","wavedash","whiff","powerslide","touch","boost_pickups","boost_respawn","bump","demolition"],KT=["air_dribble","ball_carry","ceiling_shot","double_tap","flick","flip_reset","half_flip","half_volley","one_timer","speed_flip","wall_aerial","wall_aerial_shot","wavedash"],Bg=[...new Set([...XT,...KT])],W3=new Set(KT);function ao(){return Object.fromEntries(Bg.map(n=>[n,0]))}function Dp(n){return{...n??ao()}}function Eu(n,e){n[e]+=1}function X3(n){return Bg.includes(n)}function qT(n){if(n==null)return null;if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function Xm(n){return qT(n.meta.primary_player)}function K3(n){return n.meta.team_is_team_0??null}function q3(n){const e=n.meta.stream;return!W3.has(e)||!X3(e)?null:e}function Km(n){const e=n.meta.timing.type==="span"?n.meta.timing.end_frame:n.meta.timing.frame;return typeof e=="number"&&Number.isFinite(e)?e:null}function qm(n){const e=n.meta.timing.type==="span"?n.meta.timing.end_time:n.meta.timing.time;return typeof e=="number"&&Number.isFinite(e)?e:null}function Y3(n,e){const t=Km(n);if(t!==null)return t<=e.frame_number;const i=qm(n);return i!==null&&i<=e.time}function j3(n){return[...n].sort((e,t)=>{const i=Km(e),s=Km(t);if(i!==s)return(i??Number.POSITIVE_INFINITY)-(s??Number.POSITIVE_INFINITY);const a=qm(e),r=qm(t);return a!==r?(a??Number.POSITIVE_INFINITY)-(r??Number.POSITIVE_INFINITY):(Xm(e)??"").localeCompare(Xm(t)??"")})}function YT(n){const e=jT(n);for(const t of n.frames)e.applyFrame(t);return n}function jT(n){const e=Bg.map(s=>({eventType:s,events:j3(ec(n).filter(a=>a.meta.stream===s)),index:0})),t=new Map,i={teamZero:ao(),teamOne:ao()};return{applyFrame(s){for(const a of e)for(;a.index({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function J3(n,e,t,i){n.is_last_backboard=i,n.time_since_last_backboard=n.last_backboard_time==null?null:Math.max(0,t-n.last_backboard_time),n.frames_since_last_backboard=n.last_backboard_frame==null?null:Math.max(0,e-n.last_backboard_frame)}function Q3(n,e,t,i){n.count+=1,n.last_backboard_time=e.time,n.last_backboard_frame=e.frame,n.time_since_last_backboard=Math.max(0,i-e.time),n.frames_since_last_backboard=Math.max(0,t-e.frame)}function eU(n,e){Object.assign(n,e??ZT())}function Gv(n,e){n.count=e}function tU(n){const e=JT(n);for(const t of n.frames)e.applyFrame(t);return n}function JT(n){const e=Z3(ve(n,"backboard"));let t=0,i=0,s=0,a=null;const r=new Map;return{applyFrame(o){for(const[c,u]of r)J3(u,o.frame_number,o.time,c===a);let l=!1;for(;t({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function Ym(n){return`${n.key}\0${n.value}`}function Cu(n){return n.map(Ym).join("")}function QT(n,e){e.sort((s,a)=>Ym(s).localeCompare(Ym(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Cu(s.labels)===Cu(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Cu(s.labels).localeCompare(Cu(a.labels))))}function Wv(n,e){return n.labeled_event_counts?.entries.filter(t=>t.labels.some(i=>i.key==="origin"&&i.value===e)).reduce((t,i)=>t+i.count,0)??0}function eM(n){return n.labeled_event_counts?.entries.reduce((e,t)=>e+t.count,0)??0}function tM(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function Xv(n,e){QT(n,[{key:"kind",value:"carry"}]),n.carry_count=eM(n),n.total_carry_time+=e.duration,n.total_straight_line_distance+=e.straight_line_distance,n.total_path_distance+=e.path_distance,n.longest_carry_time=Math.max(n.longest_carry_time,e.duration),n.furthest_carry_distance=Math.max(n.furthest_carry_distance,e.straight_line_distance),n.fastest_carry_speed=Math.max(n.fastest_carry_speed,e.average_speed),n.carry_speed_sum+=e.average_speed,n.average_horizontal_gap_sum+=e.average_horizontal_gap,n.average_vertical_gap_sum+=e.average_vertical_gap}function Kv(n,e){e.air_dribble_origin!=null&&QT(n,[{key:"origin",value:e.air_dribble_origin}]),n.count=eM(n),n.ground_to_air_count=Wv(n,"ground_to_air"),n.wall_to_air_count=Wv(n,"wall_to_air"),n.total_time+=e.duration,n.total_straight_line_distance+=e.straight_line_distance,n.total_path_distance+=e.path_distance,n.longest_time=Math.max(n.longest_time,e.duration),n.furthest_distance=Math.max(n.furthest_distance,e.straight_line_distance),n.fastest_speed=Math.max(n.fastest_speed,e.average_speed),n.speed_sum+=e.average_speed,n.average_horizontal_gap_sum+=e.average_horizontal_gap,n.average_vertical_gap_sum+=e.average_vertical_gap,n.total_touch_count+=e.touch_count,n.max_touch_count=Math.max(n.max_touch_count,e.touch_count)}function Op(n,e){Object.assign(n,e??Zu()),e?.labeled_event_counts?n.labeled_event_counts=tM(e.labeled_event_counts):delete n.labeled_event_counts}function Fp(n,e){Object.assign(n,e??Ju()),e?.labeled_event_counts?n.labeled_event_counts=tM(e.labeled_event_counts):delete n.labeled_event_counts}function iU(n){const e=nM(n);for(const t of n.frames)e.applyFrame(t);return n}function nM(n){const e=nU(ve(n,"ball_carry"));let t=0;const i=new Map,s=new Map,a=Zu(),r=Zu(),o=Ju(),l=Ju();return{applyFrame(c){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function aU(n,e){n.bumps_inflicted+=1,e.is_team_bump&&(n.team_bumps_inflicted+=1),n.last_bump_time=e.time,n.last_bump_frame=e.frame,n.last_bump_strength=e.strength,n.max_bump_strength=Math.max(n.max_bump_strength,e.strength),n.cumulative_bump_strength+=e.strength}function rU(n,e){n.bumps_taken+=1,e.is_team_bump&&(n.team_bumps_taken+=1)}function oU(n,e){n.bumps_inflicted+=1,e.is_team_bump&&(n.team_bumps_inflicted+=1)}function lU(n,e){Object.assign(n,e??jm())}function Yv(n,e){Object.assign(n,e)}function cU(n){const e=iM(n);for(const t of n.frames)e.applyFrame(t);return n}function iM(n){const e=sU(ve(n,"bump"));let t=0;const i=new Map,s=qv(),a=qv();return{applyFrame(r){for(;t=t&&n0&&(s.overfill_total=sn(s.overfill_total,i),e.field_half==="opponent"&&(s.overfill_from_stolen=sn(s.overfill_from_stolen,i)))}function Jv(n,e){e.boost_granted!=null&&(n.stats.amount_respawned=sn(n.stats.amount_respawned,rn(e.boost_granted)))}class mU{constructor(e){this.points=e}index=0;sample(e){for(;this.index+1e?0:rn(t.value)}}function e_(n,e){return`${n}:${e}`}function _U(n){const e=new Map,t=n.accumulation_tracks;for(const i of t??[]){const s=gl(i.player_id);e.set(e_(s,i.quantity),new mU(i.points))}return e}function gU(n){return[...ve(n,"boost_pickup")].sort((e,t)=>e.frame-t.frame||e.time-t.time)}function yU(n){return[...ve(n,"respawn")].sort((e,t)=>e.frame-t.frame||e.time-t.time)}function Bp(n,e){for(const t of sM)n[t]=e[t]}function aM(n){const e=gU(n),t=yU(n),i=_U(n);let s=0,a=0;const r=new Map,o=Up(),l=Up(),c=(d,h)=>{const f=gl(d);let p=r.get(f);return p||(p=Up(),r.set(f,p)),p.isTeamZero=h,p},u=(d,h,f)=>{const p=g=>i.get(e_(h,g))?.sample(f)??0;d.amount_used=p("boost_used"),d.amount_used_while_grounded=p("boost_used_grounded"),d.amount_used_while_airborne=p("boost_used_airborne"),d.amount_used_while_supersonic=p("boost_used_supersonic")};return{applyFrame(d,h){for(;s({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function t_(n){return`${n.key}\0${n.value}`}function Ru(n){return n.map(t_).join("")}function TU(n,e){e.sort((s,a)=>t_(s).localeCompare(t_(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Ru(s.labels)===Ru(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Ru(s.labels).localeCompare(Ru(a.labels))))}function MU(n,e){return n.labeled_event_counts?.entries.filter(t=>t.labels.some(i=>i.key==="confidence_band"&&i.value===e)).reduce((t,i)=>t+i.count,0)??0}function EU(n){return n.labeled_event_counts?.entries.reduce((e,t)=>e+t.count,0)??0}function CU(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function AU(n,e,t,i){n.is_last_ceiling_shot=i,n.time_since_last_ceiling_shot=n.last_ceiling_shot_time==null?null:Math.max(0,rM(t,n.last_ceiling_shot_time)),n.frames_since_last_ceiling_shot=n.last_ceiling_shot_frame==null?null:Math.max(0,e-n.last_ceiling_shot_frame)}function RU(n,e,t,i){TU(n,[{key:"confidence_band",value:e.confidence>=xU?"high":"standard"}]),n.count=EU(n),n.high_confidence_count=MU(n,"high"),n.is_last_ceiling_shot=!0,n.last_ceiling_shot_time=e.time,n.last_ceiling_shot_frame=e.frame,n.time_since_last_ceiling_shot=Math.max(0,rM(i,e.time)),n.frames_since_last_ceiling_shot=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=wU(n.cumulative_confidence,e.confidence)}function PU(n,e){Object.assign(n,e??oM()),e?.labeled_event_counts?n.labeled_event_counts=CU(e.labeled_event_counts):delete n.labeled_event_counts}function IU(n){const e=lM(n);for(const t of n.frames)e.applyFrame(t);return n}function lM(n){const e=SU(ve(n,"ceiling_shot"));let t=0,i=null;const s=new Map;return{applyFrame(a){if(a.is_live_play){for(const[r,o]of s)AU(o,a.frame_number,a.time,i===r);for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function OU(n,e){Object.assign(n,e??zg())}function tb(n,e){Object.assign(n,e)}function nb(n,e){n.score+=e.score_delta,n.goals+=e.goals_delta,n.assists+=e.assists_delta,n.saves+=e.saves_delta,n.shots+=e.shots_delta}function cM(n,e){if(e.time_after_kickoff!=null){const t=Math.max(0,e.time_after_kickoff);t<10?n.kickoff_goal_count+=1:t<20?n.short_goal_count+=1:t<40?n.medium_goal_count+=1:n.long_goal_count+=1}if(e.goal_buildup==="counter_attack"?n.counter_attack_goal_count+=1:e.goal_buildup==="sustained_pressure"?n.sustained_pressure_goal_count+=1:e.goal_buildup!=null&&(n.other_buildup_goal_count+=1),e.ball_air_time_before_goal!=null){const t=Math.max(0,e.ball_air_time_before_goal);n.goal_ball_air_time_sample_count+=1,n.cumulative_goal_ball_air_time=is(n.cumulative_goal_ball_air_time,t),n.last_goal_ball_air_time=t}}function zp(n,e){return n!=null&&e!=null&&Jl(n)===Jl(e)}function ib(n,e){return n?e.y:-e.y}function FU(n,e){if(n.ball_position==null||e.position==null)return!1;const t=!n.scoring_team_is_team_0,i=ib(t,n.ball_position);if(i>LU)return!1;const s=ib(t,e.position);return s=DU}function NU(n,e,t){const i=t.is_team_0===e.scoring_team_is_team_0,s=zp(t.player,e.defending_team_most_back_player),a=zp(t.player,e.scoring_team_most_back_player);s&&(n.goals_conceded_while_last_defender+=1),a&&(n.goals_for_while_most_back+=1),s&&(n.goals_against_while_most_back+=1),!i&&FU(e,t)&&(n.caught_ahead_of_play_on_conceded_goals+=1),!i&&t.boost_amount!=null&&(n.goal_against_boost_sample_count+=1,n.cumulative_boost_on_goals_against=is(n.cumulative_boost_on_goals_against,t.boost_amount),n.last_boost_on_goal_against=t.boost_amount),!i&&t.average_boost_in_leadup!=null&&t.min_boost_in_leadup!=null&&(n.goal_against_boost_leadup_sample_count+=1,n.cumulative_average_boost_in_goal_against_leadup=is(n.cumulative_average_boost_in_goal_against_leadup,t.average_boost_in_leadup),n.cumulative_min_boost_in_goal_against_leadup=is(n.cumulative_min_boost_in_goal_against_leadup,t.min_boost_in_leadup),n.last_average_boost_in_goal_against_leadup=t.average_boost_in_leadup,n.last_min_boost_in_goal_against_leadup=t.min_boost_in_leadup),!i&&t.position!=null&&(n.goal_against_position_sample_count+=1,n.cumulative_goal_against_position_x=is(n.cumulative_goal_against_position_x,t.position.x),n.cumulative_goal_against_position_y=is(n.cumulative_goal_against_position_y,t.position.y),n.cumulative_goal_against_position_z=is(n.cumulative_goal_against_position_z,t.position.z),n.last_goal_against_position={...t.position});const r=zp(t.player,e.scorer),o=r?e.scorer_last_touch?.ball_position:null;o!=null&&(n.scoring_goal_last_touch_position_sample_count+=1,n.cumulative_scoring_goal_last_touch_position_x=is(n.cumulative_scoring_goal_last_touch_position_x,o.x),n.cumulative_scoring_goal_last_touch_position_y=is(n.cumulative_scoring_goal_last_touch_position_y,o.y),n.cumulative_scoring_goal_last_touch_position_z=is(n.cumulative_scoring_goal_last_touch_position_z,o.z),n.last_scoring_goal_last_touch_position={...o}),r&&cM(n,e)}function UU(n,e,t,i){cM(i.scoring_team_is_team_0?e:t,i);for(const s of i.players){const a=Jl(s.player),r=n.get(a)??zg();n.set(a,r),NU(r,i,s)}}function BU(n){const e=uM(n);for(const t of n.frames)e.applyFrame(t);return n}function uM(n){const e=eb(ve(n,"core_player")),t=eb(ve(n,"goal_context"));let i=0,s=0;const a=new Map,r=n_(),o=n_();return{applyFrame(l){for(;i({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function rb(n,e){n.count+=1,n.total_time=sb(n.total_time,e.duration),n.longest_time=Math.max(n.longest_time,e.duration),n.touch_count+=e.touch_count,n.total_advance_distance=sb(n.total_advance_distance,e.total_advance_distance)}function Vp(n,e){Object.assign(n,e??Qu())}function HU(n){const e=dM(n);for(const t of n.frames)e.applyFrame(t);return n}function dM(n){const e=zU(ve(n,"controlled_play"));let t=0;const i=new Map,s=Qu(),a=Qu();return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function GU(n,e){n.count+=1,e.on_ball&&(n.on_ball_count+=1)}function $U(n,e){Object.assign(n,e??hM())}function WU(n){const e=fM(n);for(const t of n.frames)e.applyFrame(t);return n}function fM(n){const e=VU(ve(n,"dodge_reset"));let t=0;const i=new Map;return{applyFrame(s){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function KU(n,e,t,i){n.is_last_double_tap=i,n.time_since_last_double_tap=n.last_double_tap_time==null?null:Math.max(0,t-n.last_double_tap_time),n.frames_since_last_double_tap=n.last_double_tap_frame==null?null:Math.max(0,e-n.last_double_tap_frame)}function qU(n,e,t,i){n.count+=1,n.last_double_tap_time=e.time,n.last_double_tap_frame=e.frame,n.time_since_last_double_tap=Math.max(0,i-e.time),n.frames_since_last_double_tap=Math.max(0,t-e.frame)}function YU(n,e){Object.assign(n,e??pM())}function cb(n,e){n.count=e}function jU(n){const e=mM(n);for(const t of n.frames)e.applyFrame(t);return n}function mM(n){const e=XU(ve(n,"double_tap"));let t=0,i=0,s=0,a=null;const r=new Map;return{applyFrame(o){for(const[c,u]of r)KU(u,o.frame_number,o.time,c===a);let l=!1;for(;t({event:e,index:t})).sort((e,t)=>e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function JU(n,e){Object.assign(n,e??_M())}function hb(n,e){Object.assign(n,e)}function QU(n){const e=gM(n);for(const t of n.frames)e.applyFrame(t);return n}function gM(n){const e=ZU(ve(n,"demolition"));let t=0;const i=new Map,s=db(),a=db();function r(o){const l=ub(o),c=i.get(l)??_M();return i.set(l,c),c}return{applyFrame(o){for(;t({event:e,index:t})).sort((e,t)=>e.event.resolve_frame!==t.event.resolve_frame?e.event.resolve_frame-t.event.resolve_frame:e.event.resolve_time!==t.event.resolve_time?e.event.resolve_time-t.event.resolve_time:e.index-t.index).map(({event:e})=>e)}function tB(n){return{key:"phase",value:n?"kickoff":"open_play"}}function nB(n,e){return e==null?{key:"outcome",value:"neutral"}:{key:"outcome",value:e===n?"win":"loss"}}function iB(n,e){return e==null?{key:"possession_after",value:"neutral"}:{key:"possession_after",value:e===n?"self":"opponent"}}function sB(n,e){return{key:"dodge_state",value:(n?e.team_zero_dodge_contact:e.team_one_dodge_contact)?"dodge":"no_dodge"}}function s_(n){return`${n.key}\0${n.value}`}function Pu(n){return n.map(s_).join("")}function aB(n,e){e.sort((s,a)=>s_(s).localeCompare(s_(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Pu(s.labels)===Pu(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Pu(s.labels).localeCompare(Pu(a.labels))))}function rB(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function pb(n,e,t){n.count+=1,t.winning_team_is_team_0==null?n.neutral_outcomes+=1:t.winning_team_is_team_0===e?n.wins+=1:n.losses+=1,t.possession_team_is_team_0==null?n.neutral_possession_after_count+=1:t.possession_team_is_team_0===e?n.possession_after_count+=1:n.opponent_possession_after_count+=1,t.is_kickoff&&(n.kickoff_count+=1,t.winning_team_is_team_0==null?n.kickoff_neutral_outcomes+=1:t.winning_team_is_team_0===e?n.kickoff_wins+=1:n.kickoff_losses+=1,t.possession_team_is_team_0==null?n.kickoff_neutral_possession_after_count+=1:t.possession_team_is_team_0===e?n.kickoff_possession_after_count+=1:n.kickoff_opponent_possession_after_count+=1)}function mb(n,e,t){aB(n,[tB(t.is_kickoff),nB(e,t.winning_team_is_team_0),iB(e,t.possession_team_is_team_0),sB(e,t)]),n.count+=1,t.winning_team_is_team_0==null?n.neutral_outcomes+=1:t.winning_team_is_team_0===e?n.wins+=1:n.losses+=1,t.possession_team_is_team_0===e&&(n.possession_after_count+=1),t.is_kickoff&&(n.kickoff_count+=1,t.winning_team_is_team_0==null?n.kickoff_neutral_outcomes+=1:t.winning_team_is_team_0===e?n.kickoff_wins+=1:n.kickoff_losses+=1,t.possession_team_is_team_0===e&&(n.kickoff_possession_after_count+=1))}function oB(n,e){Object.assign(n,e??i_()),e?.labeled_event_counts?n.labeled_event_counts=rB(e.labeled_event_counts):delete n.labeled_event_counts}function _b(n,e){Object.assign(n,e)}function lB(n){const e=yM(n);for(const t of n.frames)e.applyFrame(t);return n}function yM(n){const e=eB(ve(n,"fifty_fifty"));let t=0;const i=fb(),s=fb(),a=new Map;return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function a_(n){return`${n.key}\0${n.value}`}function Iu(n){return n.map(a_).join("")}function xM(n,e){e.sort((s,a)=>a_(s).localeCompare(a_(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Iu(s.labels)===Iu(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Iu(s.labels).localeCompare(Iu(a.labels))))}function uB(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function dB(n){return[{key:"kickoff_spawn",value:n.spawn_position},{key:"taker_outcome",value:n.outcome},{key:"kickoff_approach",value:n.approach},{key:"approach_flip_direction",value:n.approach_flip_direction}]}function hB(n){return[{key:"kickoff_spawn",value:n.spawn_position},{key:"support_behavior",value:n.support_behavior}]}function yb(n,e,t){n.count+=1,t.outcome==="neutral"?n.neutral_outcomes+=1:t.outcome===(e?"team_zero_win":"team_one_win")?n.wins+=1:t.outcome===(e?"team_one_win":"team_zero_win")&&(n.losses+=1),t.kickoff_possession_outcome==="contested"?n.contested_kickoff_possessions+=1:t.kickoff_possession_outcome===(e?"team_zero_possession":"team_one_possession")?n.kickoff_possessions+=1:t.kickoff_possession_outcome===(e?"team_one_possession":"team_zero_possession")?n.opponent_kickoff_possessions+=1:t.kickoff_possession_outcome===(e?"team_zero_advantage":"team_one_advantage")?n.kickoff_possession_advantages+=1:n.opponent_kickoff_possession_advantages+=1,t.kickoff_goal&&(n.kickoff_goal_count+=1,t.scoring_team_is_team_0===e?n.kickoff_goals_for+=1:t.scoring_team_is_team_0!=null&&(n.kickoff_goals_against+=1)),t.win_strength!=null&&(n.win_strength_sample_count+=1,n.cumulative_win_strength+=t.win_strength)}function vb(n,e,t){t&&(t.boost_after!=null&&(n.boost_after_sample_count+=1,n.cumulative_boost_after+=t.boost_after,e.boost_after_sample_count+=1,e.cumulative_boost_after+=t.boost_after),t.outcome==="fake"?(n.fake_count+=1,e.fake_count+=1):t.outcome==="missed"&&(n.missed_count+=1,e.missed_count+=1))}function fB(n,e,t){n.count+=1,xM(n,dB(t)),t.outcome==="touched"?n.touches+=1:t.outcome==="fake"?n.fakes+=1:t.outcome==="missed"&&(n.misses+=1),e.kickoff_goal&&e.scoring_team_is_team_0===t.is_team_0&&(n.kickoff_goal_count+=1),t.boost_after!=null&&(n.boost_after_sample_count+=1,n.cumulative_boost_after+=t.boost_after)}function pB(n,e,t){n.count+=1,xM(n,hB(t)),t.first_touch_time!=null&&(n.touches+=1),t.support_behavior==="go_for_boost"?n.support_go_for_boosts+=1:t.support_behavior==="cheat"?n.support_cheats+=1:t.support_behavior==="other"&&(n.support_other+=1),e.kickoff_goal&&e.scoring_team_is_team_0===t.is_team_0&&(n.kickoff_goal_count+=1),t.boost_after!=null&&(n.boost_after_sample_count+=1,n.cumulative_boost_after+=t.boost_after)}function Lu(n,e,t){const i=vM(t.player),s=n.get(i)??bM();n.set(i,s),"outcome"in t?fB(s,e,t):pB(s,e,t)}function bb(n,e){Object.assign(n,e)}function mB(n,e){Object.assign(n,e??bM()),e?.labeled_event_counts?n.labeled_event_counts=uB(e.labeled_event_counts):delete n.labeled_event_counts}function _B(n){const e=wM(n);for(const t of n.frames)e.applyFrame(t);return n}function wM(n){const e=cB(ve(n,"kickoff"));let t=0;const i=gb(),s=gb(),a=new Map;return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function r_(n){return`${n.key}\0${n.value}`}function ku(n){return n.map(r_).join("")}function vB(n,e){e.sort((s,a)=>r_(s).localeCompare(r_(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>ku(s.labels)===ku(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>ku(s.labels).localeCompare(ku(a.labels))))}function bB(n,e){return n.labeled_event_counts?.entries.filter(t=>t.labels.some(i=>i.key==="confidence_band"&&i.value===e)).reduce((t,i)=>t+i.count,0)??0}function xB(n){return n==="forward"||n==="reverse"||n==="side"?n:"other"}function wB(n){return n==="left"||n==="right"?n:"center"}function SB(n){return n.labeled_event_counts?.entries.reduce((e,t)=>e+t.count,0)??0}function TB(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function MB(n,e,t,i){n.is_last_flick=i,n.time_since_last_flick=n.last_flick_time==null?null:Math.max(0,SM(t,n.last_flick_time)),n.frames_since_last_flick=n.last_flick_frame==null?null:Math.max(0,e-n.last_flick_frame)}function EB(n,e,t,i){vB(n,[{key:"confidence_band",value:e.confidence>=gB?"high":"standard"},{key:"kind",value:xB(e.kind)},{key:"direction",value:wB(e.direction)}]),n.count=SB(n),n.high_confidence_count=bB(n,"high"),n.is_last_flick=!0,n.last_flick_time=e.time,n.last_flick_frame=e.frame,n.time_since_last_flick=Math.max(0,SM(i,e.time)),n.frames_since_last_flick=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=$p(n.cumulative_confidence,e.confidence),n.cumulative_setup_duration=$p(n.cumulative_setup_duration,e.setup_duration),n.cumulative_ball_speed_change=$p(n.cumulative_ball_speed_change,e.ball_speed_change)}function CB(n,e){Object.assign(n,e??TM()),e?.labeled_event_counts?n.labeled_event_counts=TB(e.labeled_event_counts):delete n.labeled_event_counts}function AB(n){const e=MM(n);for(const t of n.frames)e.applyFrame(t);return n}function MM(n){const e=yB(ve(n,"flick"));let t=0,i=null;const s=new Map;return{applyFrame(a){if(a.is_live_play){for(const[r,o]of s)MB(o,a.frame_number,a.time,r===i);for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function PB(n,e){n.count+=1,n.total_time_to_use+=e.time_since_reset,n.min_time_to_use=n.min_time_to_use===null?e.time_since_reset:Math.min(n.min_time_to_use,e.time_since_reset)}function IB(n,e){Object.assign(n,e??EM())}function LB(n){const e=CM(n);for(const t of n.frames)e.applyFrame(t);return n}function CM(n){const e=RB(ve(n,"flip_reset"));let t=0;const i=new Map;return{applyFrame(s){for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function DB(n,e,t,i){n.is_last_half_volley=i,n.time_since_last_half_volley=n.last_half_volley_time==null?null:Math.max(0,RM(t,n.last_half_volley_time)),n.frames_since_last_half_volley=n.last_half_volley_frame==null?null:Math.max(0,e-n.last_half_volley_frame)}function OB(n,e,t,i){n.count+=1,n.total_ball_speed=AM(n.total_ball_speed,e.ball_speed),n.fastest_ball_speed=Math.max(n.fastest_ball_speed,e.ball_speed),n.last_half_volley_time=e.time,n.last_half_volley_frame=e.frame,n.time_since_last_half_volley=Math.max(0,RM(i,e.time)),n.frames_since_last_half_volley=Math.max(0,t-e.frame)}function FB(n,e){Object.assign(n,e??PM())}function Tb(n,e){Object.assign(n,e)}function NB(n){const e=IM(n);for(const t of n.frames)e.applyFrame(t);return n}function IM(n){const e=kB(ve(n,"half_volley"));let t=0,i=null;const s=new Map,a={count:0,total_ball_speed:0,fastest_ball_speed:0},r={count:0,total_ball_speed:0,fastest_ball_speed:0};return{applyFrame(o){for(const[l,c]of s)DB(c,o.frame_number,o.time,o.is_live_play&&l===i);if(!o.is_live_play)i=null;else{let l=!1;for(;te.frame!==t.frame?e.frame-t.frame:e.time!==t.time?e.time-t.time:$i(e.player).localeCompare($i(t.player)))}function HB(n){return[...n].sort((e,t)=>e.resolved_frame!==t.resolved_frame?e.resolved_frame-t.resolved_frame:e.resolved_time!==t.resolved_time?e.resolved_time-t.resolved_time:e.frame!==t.frame?e.frame-t.frame:e.time!==t.time?e.time-t.time:$i(e.player).localeCompare($i(t.player)))}function Wp(){return{count:0,highConfidenceCount:0,lastTime:null,lastFrame:null,lastResolvedTime:null,lastResolvedFrame:null,lastQuality:null,bestQuality:0,cumulativeQuality:0,labeledCounts:{entries:[]}}}function co(n){return Math.fround(n)}function VB(n,e){return co(co(n)+co(e))}function GB(n,e){return{key:"confidence_band",value:n>=e?"high":"standard"}}function $B(n,e){const t=e.sort((s,a)=>s.key===a.key?s.value.localeCompare(a.value):s.key.localeCompare(a.key)),i=n.entries.find(s=>s.labels.length===t.length&&s.labels.every((a,r)=>a.key===t[r]?.key&&a.value===t[r]?.value));if(i){i.count+=1;return}n.entries.push({labels:t,count:1}),n.entries.sort((s,a)=>JSON.stringify(s.labels).localeCompare(JSON.stringify(a.labels)))}function Uo(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function Xp(n,e,t,i,s){n.count+=1,e.confidence>=s&&(n.highConfidenceCount+=1),$B(n.labeledCounts,[GB(e.confidence,s)]),n.lastTime=e.time,n.lastFrame=e.frame,n.lastResolvedTime=i,n.lastResolvedFrame=t,n.lastQuality=e.confidence,n.bestQuality=Math.max(n.bestQuality,e.confidence),n.cumulativeQuality=VB(n.cumulativeQuality,e.confidence)}function Hg(n,e){return n?.lastTime==null?null:n.lastResolvedFrame===e.frame_number?0:Math.max(0,co(co(e.time)-co(n.lastTime)))}function Vg(n,e){return n?.lastFrame==null?null:n.lastResolvedFrame===e.frame_number?0:Math.max(0,e.frame_number-n.lastFrame)}function LM(n,e,t,i){n.count=e?.count??0,n.high_confidence_count=e?.highConfidenceCount??0,n.is_last_speed_flip=i,n.last_speed_flip_time=e?.lastTime??null,n.last_speed_flip_frame=e?.lastFrame??null,n.time_since_last_speed_flip=Hg(e,t),n.frames_since_last_speed_flip=Vg(e,t),n.last_quality=e?.lastQuality??null,n.best_quality=e?.bestQuality??0,n.cumulative_quality=e?.cumulativeQuality??0,e?.labeledCounts.entries.length?n.labeled_event_counts=Uo(e.labeledCounts):delete n.labeled_event_counts}function kM(n,e,t,i){n.count=e?.count??0,n.high_confidence_count=e?.highConfidenceCount??0,n.is_last_half_flip=i,n.last_half_flip_time=e?.lastTime??null,n.last_half_flip_frame=e?.lastFrame??null,n.time_since_last_half_flip=Hg(e,t),n.frames_since_last_half_flip=Vg(e,t),n.last_quality=e?.lastQuality??null,n.best_quality=e?.bestQuality??0,n.cumulative_quality=e?.cumulativeQuality??0,e?.labeledCounts.entries.length?n.labeled_event_counts=Uo(e.labeledCounts):delete n.labeled_event_counts}function DM(n,e,t,i){n.count=e?.count??0,n.high_confidence_count=e?.highConfidenceCount??0,n.is_last_wavedash=i,n.last_wavedash_time=e?.lastTime??null,n.last_wavedash_frame=e?.lastFrame??null,n.time_since_last_wavedash=Hg(e,t),n.frames_since_last_wavedash=Vg(e,t),n.last_quality=e?.lastQuality??null,n.best_quality=e?.bestQuality??0,n.cumulative_quality=e?.cumulativeQuality??0,e?.labeledCounts.entries.length?n.labeled_event_counts=Uo(e.labeledCounts):delete n.labeled_event_counts}function WB(n){const e={...n};return n.labeled_event_counts?e.labeled_event_counts=Uo(n.labeled_event_counts):delete e.labeled_event_counts,e}function XB(n){const e={...n};return n.labeled_event_counts?e.labeled_event_counts=Uo(n.labeled_event_counts):delete e.labeled_event_counts,e}function KB(n){const e={...n};return n.labeled_event_counts?e.labeled_event_counts=Uo(n.labeled_event_counts):delete e.labeled_event_counts,e}function qB(n,e){if(e){Object.assign(n,e);return}LM(n,void 0,{frame_number:0,time:0},!1)}function YB(n,e){if(e){Object.assign(n,e);return}kM(n,void 0,{frame_number:0,time:0},!1)}function jB(n,e){if(e){Object.assign(n,e);return}DM(n,void 0,{frame_number:0,time:0},!1)}function ZB(n){return n.is_live_play||n.ball_has_been_hit===!1}function JB(n){const e=OM(n);for(const t of n.frames)e.applyFrame(t);return n}function OM(n){const e=HB(ve(n,"speed_flip")),t=Mb(ve(n,"half_flip")),i=Mb(ve(n,"wavedash"));let s=0,a=0,r=0,o=null,l=null,c=null;const u=new Map,d=new Map,h=new Map,f=new Map,p=new Map,g=new Map;return{applyFrame(_){if(ZB(_)){for(;sQB.map(e=>({labels:[{key:"height_band",value:n},{key:"speed_band",value:e}],value:0}))).sort((n,e)=>JSON.stringify(n.labels).localeCompare(JSON.stringify(e.labels)))}}function ed(n=!1){return{tracked_time:0,total_distance:0,speed_integral:0,time_slow_speed:0,time_boost_speed:0,time_supersonic_speed:0,time_on_ground:0,time_low_air:0,time_high_air:0,labeled_tracked_time:n?nz():{entries:[]}}}function iz(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function sz(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function az(n,e,t){const i=sz(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=ss(s.value,t):(n.entries.push({labels:i,value:oa(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function rz(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),value:e.value}))}}function Cb(n,e){const t=oa(e.dt);n.tracked_time=ss(n.tracked_time,t),n.total_distance=ss(n.total_distance,e.distance),n.speed_integral=ss(n.speed_integral,tz(e.speed,t)),e.speed_band==="slow"?n.time_slow_speed=ss(n.time_slow_speed,t):e.speed_band==="boost"?n.time_boost_speed=ss(n.time_boost_speed,t):e.speed_band==="supersonic"&&(n.time_supersonic_speed=ss(n.time_supersonic_speed,t)),e.height_band==="ground"?n.time_on_ground=ss(n.time_on_ground,t):e.height_band==="low_air"?n.time_low_air=ss(n.time_low_air,t):e.height_band==="high_air"&&(n.time_high_air=ss(n.time_high_air,t));const i=n.labeled_tracked_time??{entries:[]};n.labeled_tracked_time=i,az(i,[{key:"speed_band",value:e.speed_band},{key:"height_band",value:e.height_band}],t)}function Kp(n,e){const t=e??ed(!0),i=t.labeled_tracked_time;Object.assign(n,t,{labeled_tracked_time:i?rz(i):void 0}),i?.entries.length||delete n.labeled_tracked_time}function oz(n){const e=FM(n);for(const t of n.frames)e.applyFrame(t);return n}function FM(n){const e=iz(ve(n,"movement"));let t=0;const i=new Map,s=ed(),a=ed();return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function cz(n,e,t,i){n.is_last_one_timer=i,n.time_since_last_one_timer=n.last_one_timer_time==null?null:Math.max(0,t-n.last_one_timer_time),n.frames_since_last_one_timer=n.last_one_timer_frame==null?null:Math.max(0,e-n.last_one_timer_frame)}function uz(n,e,t,i){n.count+=1,n.total_ball_speed+=e.ball_speed,n.fastest_ball_speed=Math.max(n.fastest_ball_speed,e.ball_speed),n.total_pass_distance+=e.pass_travel_distance,n.last_one_timer_time=e.time,n.last_one_timer_frame=e.frame,n.time_since_last_one_timer=Math.max(0,i-e.time),n.frames_since_last_one_timer=Math.max(0,t-e.frame)}function dz(n,e){Object.assign(n,e??NM())}function Rb(n,e){Object.assign(n,e)}function hz(n){const e=UM(n);for(const t of n.frames)e.applyFrame(t);return n}function UM(n){const e=lz(ve(n,"one_timer"));let t=0,i=null;const s=new Map,a={count:0,total_ball_speed:0,fastest_ball_speed:0},r={count:0,total_ball_speed:0,fastest_ball_speed:0};return{applyFrame(o){for(const[l,c]of s)cz(c,o.frame_number,o.time,o.is_live_play&&l===i);if(!o.is_live_play)i=null;else{let l=!1;for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.index-t.index}).map(({event:e})=>e)}function pz(n,e,t,i){n.is_last_completed_pass=i,n.time_since_last_completed_pass=n.last_completed_pass_time==null?null:Math.max(0,t-n.last_completed_pass_time),n.frames_since_last_completed_pass=n.last_completed_pass_frame==null?null:Math.max(0,e-n.last_completed_pass_frame)}function mz(n,e,t,i){n.completed_pass_count+=1,n.total_pass_distance+=e.ball_travel_distance,n.total_pass_advance+=e.ball_advance_distance,n.longest_pass_distance=Math.max(n.longest_pass_distance,e.ball_travel_distance),n.last_completed_pass_time=e.time,n.last_completed_pass_frame=e.frame,n.time_since_last_completed_pass=Math.max(0,i-e.time),n.frames_since_last_completed_pass=Math.max(0,t-e.frame)}function _z(n,e){Object.assign(n,e??o_())}function Pb(n,e){Object.assign(n,e)}function gz(n){const e=BM(n);for(const t of n.frames)e.applyFrame(t);return n}function BM(n){const e=fz(ve(n,"pass"));let t=0,i=null;const s=new Map,a={completed_pass_count:0,total_pass_distance:0,total_pass_advance:0,longest_pass_distance:0},r={completed_pass_count:0,total_pass_distance:0,total_pass_advance:0,longest_pass_distance:0};return{applyFrame(o){for(const[l,c]of s)pz(c,o.frame_number,o.time,o.is_live_play&&l===i);if(!o.is_live_play)i=null;else{let l=!1;for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function bz(n){return l_(n)}function xz(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function zM(n,e,t){const i=xz(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=yl(s.value,t):(n.entries.push({labels:i,value:Fl(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function wz(n,e){return n.key==="possession_state"&&n.value==="team_zero"?{key:"possession_state",value:e?"own":"opponent"}:n.key==="possession_state"&&n.value==="team_one"?{key:"possession_state",value:e?"opponent":"own"}:n.key==="field_third"&&n.value==="team_zero_third"?{key:"field_third",value:e?"defensive_third":"offensive_third"}:n.key==="field_third"&&n.value==="team_one_third"?{key:"field_third",value:e?"offensive_third":"defensive_third"}:n.key==="field_half"&&n.value==="team_zero_side"?{key:"field_half",value:e?"defensive_half":"offensive_half"}:n.key==="field_half"&&n.value==="team_one_side"?{key:"field_half",value:e?"offensive_half":"defensive_half"}:{...n}}function Ib(n,e){const t={entries:[]};for(const i of n.labeled_time.entries)zM(t,i.labels.map(s=>wz(s,e)),i.value);return{tracked_time:n.tracked_time,possession_time:e?n.team_zero_time:n.team_one_time,opponent_possession_time:e?n.team_one_time:n.team_zero_time,neutral_time:n.neutral_time,labeled_time:t}}function Sz(n,e){n.active=e.active,n.possessionState=e.possession_state}function Tz(n,e,t){if(!e.active)return;const i=Fl(t.dt);n.tracked_time=yl(n.tracked_time,i),e.possessionState==="team_zero"?n.team_zero_time=yl(n.team_zero_time,i):e.possessionState==="team_one"?n.team_one_time=yl(n.team_one_time,i):n.neutral_time=yl(n.neutral_time,i);const s=[{key:"possession_state",value:e.possessionState}];e.fieldThird!=null&&s.push({key:"field_third",value:e.fieldThird}),e.fieldHalf!=null&&s.push({key:"field_half",value:e.fieldHalf}),zM(n.labeled_time,s,i)}function Lb(n,e){Object.assign(n,e??vz())}function Mz(n){const e=HM(n);for(const t of n.frames)e.applyFrame(t);return n}function HM(n){const e=bz(ve(n,"possession")),t=l_(ve(n,"ball_third")),i=l_(ve(n,"ball_half"));let s=0,a=0,r=0;const o=yz(),l={active:!1,possessionState:"neutral",fieldThird:null,fieldHalf:null};return{applyFrame(c){for(;s({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function Oa(n,e){const t=rh(e.player),i=n.get(t)??VM();return n.set(t,i),i}function Cz(n,e){switch(n.active_game_time=Xt(n.active_game_time,e.duration),e.state){case"tracked":n.tracked_time=Xt(n.tracked_time,e.duration);break;case"demolished":n.time_demolished=Xt(n.time_demolished,e.duration);break}}function Az(n,e){switch(e.state){case"defensive":n.time_defensive_third=Xt(n.time_defensive_third,e.duration);break;case"neutral":n.time_neutral_third=Xt(n.time_neutral_third,e.duration);break;case"offensive":n.time_offensive_third=Xt(n.time_offensive_third,e.duration);break}}function Rz(n,e){switch(e.state){case"defensive":n.time_defensive_half=Xt(n.time_defensive_half,e.duration);break;case"offensive":n.time_offensive_half=Xt(n.time_offensive_half,e.duration);break}}function Pz(n,e){switch(e.state){case"behind_ball":n.time_behind_ball=Xt(n.time_behind_ball,e.duration);break;case"level_with_ball":n.time_level_with_ball=Xt(n.time_level_with_ball,e.duration);break;case"ahead_of_ball":n.time_in_front_of_ball=Xt(n.time_in_front_of_ball,e.duration);break}}function Iz(n,e){switch(e.state){case"no_teammates":n.time_no_teammates=Xt(n.time_no_teammates,e.duration);break;case"most_back":n.time_most_back=Xt(n.time_most_back,e.duration);break;case"most_forward":n.time_most_forward=Xt(n.time_most_forward,e.duration);break;case"mid":n.time_mid_role=Xt(n.time_mid_role,e.duration);break;case"other":n.time_other_role=Xt(n.time_other_role,e.duration);break}}function Lz(n,e,t){t.state.closest_to_ball_team&&(e.tracked_time=Xt(e.tracked_time,t.duration),e.time_closest_to_ball_team=Xt(e.time_closest_to_ball_team,t.duration),n.time_closest_to_ball_team=Xt(n.time_closest_to_ball_team,t.duration)),t.state.closest_to_ball_absolute&&(e.time_closest_to_ball_absolute=Xt(e.time_closest_to_ball_absolute,t.duration),n.time_closest_to_ball_absolute=Xt(n.time_closest_to_ball_absolute,t.duration)),t.state.farthest_from_ball&&(n.time_farthest_from_ball=Xt(n.time_farthest_from_ball,t.duration))}function kz(n,e){e.state==="shadowing"&&(n.time_shadow_defense=Xt(n.time_shadow_defense,e.duration))}function Dz(n,e){Object.assign(n,e??VM())}function kb(n,e){Object.assign(n,e??c_())}function Fa(n,e){const t=Ez(n),i=new Array(t.length).fill(0);return{applyThroughFrame(s){for(let a=0;as.frame_number)break;const o=Oz(r,s),l=o-i[a];l>0&&(i[a]=o,e({...r,duration:l}))}}}}function Oz(n,e){if(e.frame_number>=n.end_frame)return n.duration;const t=n.end_time-n.time;if(t<=0)return 0;const i=Math.max(0,e.time-n.time);return n.duration*Math.min(1,i/t)}function Fz(n){const e=GM(n);for(const t of n.frames)e.applyFrame(t);return n}function GM(n){const e=new Map,t=c_(),i=c_(),s=[Fa(ve(n,"player_activity"),a=>Cz(Oa(e,a),a)),Fa(ve(n,"field_third"),a=>Az(Oa(e,a),a)),Fa(ve(n,"field_half"),a=>Rz(Oa(e,a),a)),Fa(ve(n,"ball_depth"),a=>Pz(Oa(e,a),a)),Fa(ve(n,"depth_role"),a=>Iz(Oa(e,a),a)),Fa(ve(n,"ball_proximity"),a=>Lz(Oa(e,a),a.is_team_0?t:i,a)),Fa(ve(n,"shadow_defense"),a=>kz(Oa(e,a),a))];return{applyFrame(a){for(const r of s)r.applyThroughFrame(a);kb(a.team_zero.positioning,t),kb(a.team_one.positioning,i);for(const r of a.players)Dz(r.positioning,e.get(rh(r.player_id))),Nz(r.positioning,n,r.player_id)}}}function Nz(n,e,t){const i=e.positioning_summary;if(!Array.isArray(i))return;const s=rh(t),a=i.find(r=>!r||typeof r!="object"?!1:rh(r.player_id)===s);a?.distance&&Object.assign(n,a.distance)}function Yp(n){if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function vl(){return{total_duration:0,press_count:0}}function Uz(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function Bz(n){return n.gameplay_phase==="active_play"||n.gameplay_phase==="kickoff_waiting_for_touch"}function jp(n,e){Object.assign(n,e??vl())}function zz(n){const e=$M(n);for(const t of n.frames)e.applyFrame(t);return n}function $M(n){const e=Uz(ve(n,"powerslide"));let t=0;const i=new Map,s=new Map,a=vl(),r=vl();return{applyFrame(o){const l=Bz(o);for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function $z(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function WM(n,e,t){const i=$z(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=bl(s.value,t):(n.entries.push({labels:i,value:Nl(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function Wz(n,e){return n.key==="field_half"&&n.value==="team_zero_side"?{key:"field_half",value:e?"defensive_half":"offensive_half"}:n.key==="field_half"&&n.value==="team_one_side"?{key:"field_half",value:e?"offensive_half":"defensive_half"}:{...n}}function Db(n,e){const t={entries:[]};for(const i of n.labeled_time.entries)WM(t,i.labels.map(s=>Wz(s,e)),i.value);return{tracked_time:n.tracked_time,defensive_half_time:e?n.team_zero_side_time:n.team_one_side_time,offensive_half_time:e?n.team_one_side_time:n.team_zero_side_time,neutral_time:n.neutral_time,labeled_time:t}}function Xz(n,e){n.active=e.active,n.fieldHalf=e.field_half}function Kz(n,e,t){if(!e.active)return;const i=Nl(t.dt);n.tracked_time=bl(n.tracked_time,i),e.fieldHalf==="team_zero_side"?n.team_zero_side_time=bl(n.team_zero_side_time,i):e.fieldHalf==="team_one_side"?n.team_one_side_time=bl(n.team_one_side_time,i):n.neutral_time=bl(n.neutral_time,i),WM(n.labeled_time,[{key:"field_half",value:e.fieldHalf}],i)}function Ob(n,e){Object.assign(n,e??Vz())}function qz(n){const e=XM(n);for(const t of n.frames)e.applyFrame(t);return n}function XM(n){const e=Gz(ve(n,"ball_half"));let t=0;const i=Hz(),s={active:!1,fieldHalf:"neutral"};return{applyFrame(a){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function Jz(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function KM(n,e,t){const i=Jz(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=xl(s.value,t):(n.entries.push({labels:i,value:Ul(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function Qz(n,e){return n.key==="field_third"&&n.value==="team_zero_third"?{key:"field_third",value:e?"defensive_third":"offensive_third"}:n.key==="field_third"&&n.value==="team_one_third"?{key:"field_third",value:e?"offensive_third":"defensive_third"}:{...n}}function Fb(n,e){const t={entries:[]};for(const i of n.labeled_time.entries)KM(t,i.labels.map(s=>Qz(s,e)),i.value);return{tracked_time:n.tracked_time,defensive_third_time:e?n.team_zero_third_time:n.team_one_third_time,neutral_third_time:n.neutral_third_time,offensive_third_time:e?n.team_one_third_time:n.team_zero_third_time,labeled_time:t}}function eH(n,e){n.active=e.active,n.fieldThird=e.field_third}function tH(n,e,t){if(!e.active)return;const i=Ul(t.dt);n.tracked_time=xl(n.tracked_time,i),e.fieldThird==="team_zero_third"?n.team_zero_third_time=xl(n.team_zero_third_time,i):e.fieldThird==="team_one_third"?n.team_one_third_time=xl(n.team_one_third_time,i):n.neutral_third_time=xl(n.neutral_third_time,i),KM(n.labeled_time,[{key:"field_third",value:e.fieldThird}],i)}function Nb(n,e){Object.assign(n,e??jz())}function nH(n){const e=qM(n);for(const t of n.frames)e.applyFrame(t);return n}function qM(n){const e=Zz(ve(n,"ball_third"));let t=0;const i=Yz(),s={active:!1,fieldThird:"neutral_third"};return{applyFrame(a){for(;t({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function sH(n,e,t){n.session_count+=1,n.session_time=Du(n.session_time,t.duration),n.offensive_half_time=Du(n.offensive_half_time,t.offensive_half_time),n.offensive_third_time=Du(n.offensive_third_time,t.offensive_third_time),n.longest_session_time=Math.max(n.longest_session_time,t.duration),n.average_session_time=n.session_count===0?0:td(n.session_time/n.session_count),e.opponent_session_count+=1,e.opponent_session_time=Du(e.opponent_session_time,t.duration),e.opponent_longest_session_time=Math.max(e.opponent_longest_session_time,t.duration)}function Bb(n,e){Object.assign(n,e)}function aH(n){const e=YM(n);for(const t of n.frames)e.applyFrame(t);return n}function YM(n){const e=iH(ve(n,"territorial_pressure"));let t=0;const i=Ub(),s=Ub();return{applyFrame(a){for(;t=e[t].end_frame;){const r=e[t];sH(r.team_is_team_0?i:s,r.team_is_team_0?s:i,r),t+=1}Bb(a.team_zero.territorial_pressure,i),Bb(a.team_one.territorial_pressure,s)}}}function Yr(n,e){return Math.fround(Math.fround(n)+Math.fround(e))}function jM(n){if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function ZM(){return{active_game_time:0,time_first_man:0,time_second_man:0,time_third_man:0,time_ambiguous_role:0,longest_first_man_stint_time:0,first_man_stint_count:0,became_first_man_count:0,lost_first_man_count:0,current_role_state:"unknown"}}function zb(){return{first_man_changes_for_team:0,rotation_count:0}}function Hb(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function rH(n,e,t,i,s){const a=n.stats;switch(a.active_game_time=Yr(a.active_game_time,t),a.current_role_state=e.state,e.state){case"first_man":{n.lastFirstManEndTime!==null&&e.time-n.lastFirstManEndTime<=s?n.currentFirstManStintTime=Yr(n.currentFirstManStintTime,t):(n.currentFirstManStintTime=t,a.first_man_stint_count+=1),n.lastFirstManEndTime=i,a.longest_first_man_stint_time=Math.max(a.longest_first_man_stint_time,n.currentFirstManStintTime),a.time_first_man=Yr(a.time_first_man,t);break}case"second_man":a.time_second_man=Yr(a.time_second_man,t);break;case"third_man":a.time_third_man=Yr(a.time_third_man,t);break;case"ambiguous":a.time_ambiguous_role=Yr(a.time_ambiguous_role,t);break}}function oH(n,e){if(e.frame_number>=n.end_frame)return n.duration;const t=n.end_time-n.time;if(t<=0)return 0;const i=Math.max(0,e.time-n.time);return n.duration*Math.min(1,i/t)}function u_(n,e){const t=jM(e),i=n.get(t)??{currentFirstManStintTime:0,lastFirstManEndTime:null,stats:ZM()};return n.set(t,i),i}function lH(n,e,t){n.first_man_changes_for_team+=1,n.rotation_count+=1,u_(e,t.previous_first_man).stats.lost_first_man_count+=1,u_(e,t.next_first_man).stats.became_first_man_count+=1}function cH(n,e){Object.assign(n,e??ZM())}function Vb(n,e){Object.assign(n,e)}function uH(n){const e=JM(n);for(const t of n.frames)e.applyFrame(t);return n}function JM(n){const e=Hb(ve(n,"rotation_role")),t=Hb(ve(n,"first_man_change")),i=n.config.rotation_first_man_stint_end_grace_seconds,s=new Array(e.length).fill(0);let a=0;const r=new Map,o=zb(),l=zb();return{applyFrame(c){for(let u=0;uc.frame_number)break;const h=oH(d,c),f=h-s[u];if(f>0){s[u]=h;const p=c.frame_number>=d.end_frame?d.end_time:Math.min(c.time,d.end_time);rH(u_(r,d.player),d,f,p,i)}}for(;a({event:e,index:t})).sort((e,t)=>e.event.start_frame!==t.event.start_frame?e.event.start_frame-t.event.start_frame:e.event.start_time!==t.event.start_time?e.event.start_time-t.event.start_time:e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.index-t.index).map(({event:e})=>e)}function hH(n,e){n.count+=1,e.attackers===2&&e.defenders===1?n.two_v_one_count+=1:e.attackers===2&&e.defenders===2?n.two_v_two_count+=1:e.attackers===2&&e.defenders===3?n.two_v_three_count+=1:e.attackers===3&&e.defenders===1?n.three_v_one_count+=1:e.attackers===3&&e.defenders===2?n.three_v_two_count+=1:e.attackers===3&&e.defenders===3&&(n.three_v_three_count+=1)}function $b(n,e){Object.assign(n,e)}function fH(n){const e=QM(n);for(const t of n.frames)e.applyFrame(t);return n}function QM(n){const e=dH(ve(n,"rush"));let t=0;const i=Gb(),s=Gb(),a=n.config.rush_min_possession_retained_seconds;return{applyFrame(r){for(;t=e[t].start_frame&&r.time-e[t].start_time>=a;){const o=e[t];hH(o.is_team_0?i:s,o),t+=1}$b(r.team_zero.rush,i),$b(r.team_one.rush,s)}}}const pH=["control","hard_hit","medium_hit"],mH=["ground","high_air","low_air"],_H=["air","ground","wall"],gH=["dodge","no_dodge"];function uo(n){return Math.fround(n)}function nd(n,e){return uo(uo(n)+uo(e))}function eE(n,e){return uo(uo(n)-uo(e))}function Zp(n){if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function yH(){return{entries:gH.flatMap(n=>mH.flatMap(e=>pH.flatMap(t=>_H.map(i=>({labels:[{key:"dodge_state",value:n},{key:"height_band",value:e},{key:"kind",value:t},{key:"surface",value:i}],count:0}))))).sort((n,e)=>JSON.stringify(n.labels).localeCompare(JSON.stringify(e.labels)))}}function tE(){return{touch_count:0,control_touch_count:0,medium_hit_count:0,hard_hit_count:0,aerial_touch_count:0,high_aerial_touch_count:0,wall_touch_count:0,first_touch_count:0,is_last_touch:!1,last_touch_time:null,last_touch_frame:null,time_since_last_touch:null,frames_since_last_touch:null,last_ball_speed_change:null,max_ball_speed_change:0,cumulative_ball_speed_change:0,total_ball_travel_distance:0,total_ball_advance_distance:0,total_ball_retreat_distance:0,labeled_touch_counts:yH()}}const vH=tE();function Wb(){return{stats:tE(),labeledCountsVersion:0,labeledCountsSnapshot:void 0,labeledCountsSnapshotVersion:-1}}function bH(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function xH(n,e){e.sort((s,a)=>s.key===a.key?s.value.localeCompare(a.value):s.key.localeCompare(a.key));const t=n.labeled_touch_counts?.entries??[];n.labeled_touch_counts={entries:t};const i=t.find(s=>s.labels.length===e.length&&s.labels.every((a,r)=>a.key===e[r]?.key&&a.value===e[r]?.value));i?i.count+=1:(t.push({labels:e,count:1}),t.sort((s,a)=>JSON.stringify(s.labels).localeCompare(JSON.stringify(a.labels))))}function wH(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function Ou(n,e){return n.tags?.find(t=>t.group===e)?.value??null}function SH(n,e,t){const i=Ou(e,"kind")??"control",s=Ou(e,"height_band")??"ground",a=Ou(e,"surface")??"ground",r=Ou(e,"dodge_state")??"no_dodge",o=n.stats;o.touch_count+=1,i==="control"?o.control_touch_count+=1:i==="medium_hit"?o.medium_hit_count+=1:i==="hard_hit"&&(o.hard_hit_count+=1),s==="low_air"?o.aerial_touch_count+=1:s==="high_air"&&(o.aerial_touch_count+=1,o.high_aerial_touch_count+=1),a==="wall"&&(o.wall_touch_count+=1),xH(o,[{key:"kind",value:i},{key:"height_band",value:s},{key:"surface",value:a},{key:"dodge_state",value:r}]),n.labeledCountsVersion+=1,o.last_touch_time=e.time,o.last_touch_frame=e.frame,o.time_since_last_touch=Math.max(0,eE(t.time,e.time)),o.frames_since_last_touch=Math.max(0,t.frame_number-e.frame),o.last_ball_speed_change=e.ball_speed_change,o.max_ball_speed_change=Math.max(o.max_ball_speed_change,e.ball_speed_change),o.cumulative_ball_speed_change=nd(o.cumulative_ball_speed_change,e.ball_speed_change)}function TH(n){return n.labeledCountsSnapshotVersion!==n.labeledCountsVersion&&(n.labeledCountsSnapshot=n.stats.labeled_touch_counts?wH(n.stats.labeled_touch_counts):void 0,n.labeledCountsSnapshotVersion=n.labeledCountsVersion),n.labeledCountsSnapshot}function MH(n,e){if(!e){Object.assign(n,vH);return}Object.assign(n,e.stats,{labeled_touch_counts:TH(e)})}function EH(n){const e=nE(n);for(const t of n.frames)e.applyFrame(t);return n}function nE(n){const e=bH(ve(n,"touch")),t=e.flatMap(o=>o.ball_movement?[{player:o.player,movement:o.ball_movement}]:[]).sort((o,l)=>o.movement.end_frame!==l.movement.end_frame?o.movement.end_frame-l.movement.end_frame:o.movement.end_time-l.movement.end_time);let i=0,s=0,a=null;const r=new Map;return{applyFrame(o){if(!o.is_live_play)a=null;else{for(const l of r.values()){const c=l.stats;c.is_last_touch=!1,c.last_touch_time!=null&&(c.time_since_last_touch=Math.max(0,eE(o.time,c.last_touch_time))),c.last_touch_frame!=null&&(c.frames_since_last_touch=Math.max(0,o.frame_number-c.last_touch_frame))}for(;i({event:e,index:t})).sort((e,t)=>e.event.resolved_frame!==t.event.resolved_frame?e.event.resolved_frame-t.event.resolved_frame:e.event.resolved_time!==t.event.resolved_time?e.event.resolved_time-t.event.resolved_time:e.index-t.index).map(({event:e})=>e)}function RH(n,e,t){n.is_last_whiff=!1,n.time_since_last_whiff=n.last_whiff_time==null?null:Math.max(0,t-n.last_whiff_time),n.frames_since_last_whiff=n.last_whiff_frame==null?null:Math.max(0,e-n.last_whiff_frame)}function PH(n,e,t,i){if((e.kind??"whiff")==="beaten_to_ball"){n.beaten_to_ball_count+=1;return}n.whiff_count+=1,e.aerial?n.aerial_whiff_count+=1:n.grounded_whiff_count+=1,e.dodge_active&&(n.dodge_whiff_count+=1),n.is_last_whiff=!0,n.last_whiff_time=e.time,n.last_whiff_frame=e.frame,n.time_since_last_whiff=Math.max(0,i-e.time),n.frames_since_last_whiff=Math.max(0,t-e.frame),n.last_closest_approach_distance=e.closest_approach_distance,n.best_closest_approach_distance=n.best_closest_approach_distance==null?e.closest_approach_distance:Math.min(n.best_closest_approach_distance,e.closest_approach_distance),n.cumulative_closest_approach_distance+=e.closest_approach_distance}function Xb(n,e){Object.assign(n,e??d_())}function IH(n){const e=iE(n);for(const t of n.frames)e.applyFrame(t);return n}function iE(n){const e=AH(ve(n,"whiff"));let t=0,i=null;const s=new Map,a=new Map;return{applyFrame(r){if(r.is_live_play){for(const o of s.values())RH(o,r.frame_number,r.time);for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function DH(n,e,t,i){n.is_last_wall_aerial=i,n.time_since_last_wall_aerial=n.last_wall_aerial_time==null?null:Math.max(0,sE(t,n.last_wall_aerial_time)),n.frames_since_last_wall_aerial=n.last_wall_aerial_frame==null?null:Math.max(0,e-n.last_wall_aerial_frame)}function OH(n,e,t,i){n.count+=1,e.confidence>=LH&&(n.high_confidence_count+=1),n.is_last_wall_aerial=!0,n.last_wall_aerial_time=e.time,n.last_wall_aerial_frame=e.frame,n.time_since_last_wall_aerial=Math.max(0,sE(i,e.time)),n.frames_since_last_wall_aerial=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=Fu(n.cumulative_confidence,e.confidence),n.cumulative_setup_duration=Fu(n.cumulative_setup_duration,e.setup_duration),n.cumulative_takeoff_to_touch_time=Fu(n.cumulative_takeoff_to_touch_time,e.time_since_takeoff),n.cumulative_touch_height=Fu(n.cumulative_touch_height,e.player_position[2]??0)}function FH(n,e){Object.assign(n,e??aE())}function NH(n){const e=rE(n);for(const t of n.frames)e.applyFrame(t);return n}function rE(n){const e=kH(ve(n,"wall_aerial"));let t=0,i=null;const s=new Map;return{applyFrame(a){for(const[r,o]of s)DH(o,a.frame_number,a.time,a.is_live_play&&r===i);if(!a.is_live_play)i=null;else{for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function zH(n,e,t,i){n.is_last_wall_aerial_shot=i,n.time_since_last_wall_aerial_shot=n.last_wall_aerial_shot_time==null?null:Math.max(0,oE(t,n.last_wall_aerial_shot_time)),n.frames_since_last_wall_aerial_shot=n.last_wall_aerial_shot_frame==null?null:Math.max(0,e-n.last_wall_aerial_shot_frame)}function HH(n,e,t,i){n.count+=1,e.confidence>=UH&&(n.high_confidence_count+=1),n.is_last_wall_aerial_shot=!0,n.last_wall_aerial_shot_time=e.time,n.last_wall_aerial_shot_frame=e.frame,n.time_since_last_wall_aerial_shot=Math.max(0,oE(i,e.time)),n.frames_since_last_wall_aerial_shot=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=Qp(n.cumulative_confidence,e.confidence),n.cumulative_takeoff_to_shot_time=Qp(n.cumulative_takeoff_to_shot_time,e.time_since_takeoff),n.cumulative_shot_height=Qp(n.cumulative_shot_height,e.player_position[2]??0)}function VH(n,e){Object.assign(n,e??lE())}function GH(n){const e=cE(n);for(const t of n.frames)e.applyFrame(t);return n}function cE(n){const e=BH(ve(n,"wall_aerial_shot"));let t=0,i=null;const s=new Map;return{applyFrame(a){for(const[r,o]of s)zH(o,a.frame_number,a.time,a.is_live_play&&r===i);if(!a.is_live_play)i=null;else{let r=!1;for(;t[f.frame_number,p])),a=new Map,r={...n,frames:[]},o=KH.flatMap(f=>f.createFrameAccumulator?[f.createFrameAccumulator(r)]:[]),l=Math.max(1,t.materializationChunkSize??$H),c=Math.max(l,t.maxMaterializationChunkSize??WH);let u=-1,d=l;const h=f=>{if(f<=u)return;const p=Math.min(i.length-1,Math.max(f,u+d));for(let g=u+1;g<=p;g+=1){const _=i[g],m=_?ZH(jH(_)):void 0;if(m){for(const v of o)v.applyFrame(m);a.set(m.frame_number,m)}}u=p,d=Math.min(c,i.length,d*XH)};return{get(f){const p=s.get(f);if(p!==void 0)return h(p),a.get(f)}}}function YH(n){return!n||typeof n!="object"?n:{...n}}function jH(n){return{...n,team_zero:{...n.team_zero},team_one:{...n.team_one},players:n.players.map(e=>({...e,player_id:YH(e.player_id)}))}}function ZH(n){return{...n,team_zero:Ql(n.team_zero??{}),team_one:Ql(n.team_one??{}),players:n.players.map(t=>uE(t))}}function ec(n){return n.events?.events??[]}function ve(n,e){return ec(n).filter(t=>t.payload.kind===e).map(t=>t.payload.payload)}const JH=new Set(["is_team_0","name","player_id"]);function Yb(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0}function QH(n){return!n||typeof n!="object"||Array.isArray(n)?!1:Object.keys(n).every(e=>JH.has(e))}function eV(n){return Yb(n.team_zero)&&Yb(n.team_one)&&n.players.every(e=>QH(e))}function tV(n){return new Map(YT(n).frames.map(e=>[e.frame_number,e]))}function nV(n,e,t){const i=n.frames.filter(s=>eV(s)).length;if(i===n.frames.length)return qH(n,e,t);if(i>0)throw new Error("stats timeline frames must be either all compact scaffolds or all materialized snapshots");return tV(n)}function zt(n,e){return n.get(e)??null}const $g=[{stage:"validating",index:1,total:9,label:"Parse replay",start:0,end:.08},{stage:"processing",index:2,total:9,label:"Process replay frames",start:.08,end:.62},{stage:"building-stats",index:3,total:9,label:"Build stats events",start:.62,end:.7},{stage:"serializing-replay",index:4,total:9,label:"Serialize replay data",start:.7,end:.76},{stage:"serializing-stats",index:5,total:9,label:"Serialize stats timeline",start:.76,end:.86},{stage:"normalizing",index:6,total:9,label:"Normalize replay model",start:.86,end:.91},{stage:"decoding-replay",index:7,total:9,label:"Decode replay data",start:.91,end:.94},{stage:"decoding-stats",index:8,total:9,label:"Decode stats chunks",start:.94,end:.96},{stage:"deriving-stats",index:9,total:9,label:"Derive stats snapshots",start:.96,end:1}];function dE(n){return Math.max(0,Math.min(1,n))}function em(n,e,t){if(n!==void 0)return dE((n-e)/(t-e))}function Wg(n){if(n.stage!=="stats-timeline")return n;const e=n.progress;return e===void 0?{...n,stage:"building-stats"}:e<.35?{...n,stage:"building-stats",progress:em(e,0,.35)}:e<.55?{...n,stage:"serializing-replay",progress:em(e,.35,.55)}:{...n,stage:"serializing-stats",progress:em(e,.55,.92)}}function hE(n){const e=Wg(n);return $g.find(t=>t.stage===e.stage)}function iV(){return $g.map(({stage:n,index:e,total:t,label:i})=>({stage:n,index:e,total:t,label:i}))}function sV(n){const e=hE(n);return{stage:e.stage,index:e.index,total:e.total,label:e.label}}function aV(n){const e=Wg(n),t=hE(e);return $g.map(({stage:i,index:s,total:a,label:r})=>{if(st.index)return{stage:i,index:s,total:a,label:r,state:"pending",completion:0,indeterminate:!1};const o=e.progress!==void 0;return{stage:i,index:s,total:a,label:r,state:"active",completion:o?dE(e.progress??0):1,indeterminate:!o}})}function lf(n){const e=Wg(n),t=e.progress===void 0?null:Math.round(e.progress*100);switch(e.stage){case"validating":return"Parsing replay...";case"processing":return t!==null&&e.totalFrames!==void 0?`Processing replay frames... ${t}% (${e.processedFrames??0}/${e.totalFrames})`:"Processing replay frames...";case"building-stats":return t!==null?e.totalFrames!==void 0?`Building stats events... ${t}% (${e.processedFrames??0}/${e.totalFrames})`:`Building stats events... ${t}%`:"Building stats events...";case"serializing-replay":return t!==null?`Serializing replay data... ${t}%`:"Serializing replay data...";case"serializing-stats":return t!==null?`Serializing stats timeline... ${t}%`:"Serializing stats timeline...";case"decoding-replay":return t!==null?`Decoding replay data... ${t}%`:"Decoding replay data...";case"decoding-stats":return t!==null?e.totalChunks!==void 0?`Decoding stats chunks... ${t}% (${e.processedChunks??0}/${e.totalChunks})`:`Decoding stats chunks... ${t}%`:"Decoding stats chunks...";case"deriving-stats":return t!==null?`Deriving stats snapshots... ${t}%`:"Deriving stats snapshots...";case"normalizing":return t!==null?`Normalizing replay model... ${t}%`:"Normalizing replay model...";default:return"Loading replay..."}}function rV(n){return n instanceof Error?n:new Error(String(n))}function Rs(n,e){return JSON.parse(n.decode(new Uint8Array(e)))}async function oV(n,e,t){t?.({stage:"decoding-stats",progress:0});const i=Rs(n,e.configBuffer);t?.({stage:"decoding-stats",progress:.05}),await Ja();const s=Rs(n,e.replayMetaBuffer);t?.({stage:"decoding-stats",progress:.1}),await Ja();const a=Rs(n,e.eventsBuffer),r=Rs(n,e.activitySummaryBuffer),o=Rs(n,e.positioningSummaryBuffer),l=Rs(n,e.accumulationTracksBuffer);t?.({stage:"decoding-stats",progress:.15}),await Ja();const c=[],u=e.frameChunkBuffers.length;for(let d=0;d{let t=!1,i=null;const s=()=>{t||(t=!0,i!==null&&clearTimeout(i),e())};i=setTimeout(s,n),requestAnimationFrame(()=>s())})}async function fE(n,e={}){if(typeof Worker>"u")throw new Error("Replay loading worker is not available in this environment");const t=new Worker(new URL(""+new URL("replayLoader.worker-BOmyAjmY.js",import.meta.url).href,import.meta.url),{type:"module"}),i=n.slice(),s=e.reportEveryNFrames??100;return new Promise((a,r)=>{const o=()=>{t.terminate()};t.onmessage=async c=>{const u=c.data;if(u.type==="progress"){e.onProgress?.(u.progress);return}if(u.type==="error"){o(),r(new Error(u.error));return}o();try{const d=new TextDecoder;e.onProgress?.({stage:"decoding-replay",progress:0}),await Ja();const h=Rs(d,u.replayBuffer);e.onProgress?.({stage:"decoding-replay",progress:.5}),await Ja();const f=Rs(d,u.rawReplayBuffer);e.onProgress?.({stage:"decoding-replay",progress:1}),await Ja();const p=await oV(d,u.statsTimelineParts,e.onProgress),g=nV(p);a({replay:h,raw:f,statsTimeline:p,statsFrameLookup:g})}catch(d){r(rV(d))}},t.onerror=c=>{o(),r(new Error(c.message||"Replay loading worker failed"))};const l={type:"load-replay",bytes:i.buffer,reportEveryNFrames:s};t.postMessage(l,[i.buffer])})}function lV(n){const e=document.createElement("div");e.className="replay-load-modal",e.hidden=!0;const t=document.createElement("div");t.className="replay-load-modal__dialog",t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-labelledby","replay-load-modal-title");const i=document.createElement("p");i.className="replay-load-modal__eyebrow",i.textContent="Replay loading";const s=document.createElement("h2");s.id="replay-load-modal-title",s.className="replay-load-modal__title",s.textContent="Preparing replay pipeline";const a=document.createElement("p");a.className="replay-load-modal__status",a.textContent="Preparing replay...";const r=document.createElement("div");r.className="replay-load-modal__phase-list";const o=new Map;for(const f of iV()){const p=document.createElement("div");p.className="replay-load-modal__phase-row",p.dataset.state="pending";const g=document.createElement("p");g.className="replay-load-modal__phase-label",g.textContent=`${f.index}. ${f.label}`;const _=document.createElement("div");_.className="replay-load-modal__phase-bar";const m=document.createElement("div");m.className="replay-load-modal__phase-fill",m.dataset.indeterminate="false",_.append(m),p.append(g,_),r.append(p),o.set(f.stage,{row:p,fill:m})}const l=document.createElement("p");l.className="replay-load-modal__meta",t.append(i,s,a,r,l),e.append(t),n.append(e);let c="";const u=()=>{for(const{row:f,fill:p}of o.values())f.dataset.state="pending",p.style.width="0%",p.dataset.indeterminate="false"},d=f=>{for(const p of aV(f)){const g=o.get(p.stage);g&&(g.row.dataset.state=p.state,g.fill.dataset.indeterminate=p.indeterminate?"true":"false",g.fill.style.width=`${Math.round(p.completion*100)}%`)}},h=f=>{e.hidden=!f};return{show(f,p="Preparing replay..."){c=f,h(!0),u(),s.textContent="Preparing replay pipeline",a.textContent=p,l.textContent=`Loading ${f}`},update(f){h(!0);const p=sV(f);if(d(f),s.textContent=`Phase ${p.index} of ${p.total}: ${p.label}`,a.textContent=lf(f),f.stage==="processing"&&f.totalFrames!==void 0){l.textContent=`${f.processedFrames??0}/${f.totalFrames} frames`;return}if(f.stage==="decoding-stats"&&f.totalChunks!==void 0){l.textContent=`${f.processedChunks??0}/${f.totalChunks} chunks`;return}l.textContent=c?`Loading ${c}`:""},hide(){h(!1)},destroy(){e.remove()}}}const cV=["free","follow"];function pE(n){return n.useReplayBallCam??!1?"player":n.ballCamEnabled?"on":"off"}function jb(n){return n.useReplayBallCam?"player":n.ballCam===!0?"on":n.ballCam===!1?"off":"player"}const mE={fov:110,height:100,pitch:-4,distance:270,stiffness:0,swivelSpeed:1,transitionSpeed:1};class Xg{constructor(e){this.options=e}lastFreeCameraPreset=null;get freeCameraPreset(){return this.lastFreeCameraPreset}set freeCameraPreset(e){this.lastFreeCameraPreset=e}ballCamModeValue="player";get ballCamMode(){return this.ballCamModeValue}autoPossessionEnabledValue=!1;get autoPossessionEnabled(){return this.autoPossessionEnabledValue}static ballCamEnabledForMode(e){return e==="player"?null:e==="on"}followPlayerWithReplayCamera(e,t={}){const i=this.options.getReplayPlayer();i&&(t.preserveAutoPossession||this.setAutoPossessionEnabled(!1,{requestConfigSync:!1}),i.setAttachedPlayer(e),i.setCameraViewMode("follow"),t.usePlayerCameraSettings!==!1&&i.setCustomCameraSettings(null),this.setBallCamMode(t.ballCam??"player"),this.lastFreeCameraPreset=null,t.requestConfigSync!==!1&&this.options.requestConfigSync())}setAutoPossessionEnabled(e,t={}){if(this.autoPossessionEnabledValue===e){this.renderAutoPossessionButton();return}this.autoPossessionEnabledValue=e,this.renderAutoPossessionButton(),t.notify!==!1&&this.options.onAutoPossessionChange?.(e),t.requestConfigSync!==!1&&this.options.requestConfigSync()}renderBallCamButtons(){const{ballCamOffButton:e,ballCamOnButton:t,ballCamPlayerButton:i}=this.options.elements,s=[["off",e],["on",t],["player",i]];for(const[a,r]of s){const o=a===this.ballCamModeValue;r.dataset.active=o?"true":"false",r.setAttribute("aria-pressed",o?"true":"false")}}renderAutoPossessionButton(){this.options.elements.cameraViewAutoPossession.checked=this.autoPossessionEnabledValue}disableAutoPossessionForManualCameraControl(){this.setAutoPossessionEnabled(!1,{requestConfigSync:!1})}setBallCamMode(e){this.ballCamModeValue=e,this.options.getReplayPlayer()?.setBallCamEnabled(Xg.ballCamEnabledForMode(e)),this.renderBallCamButtons()}get nameplateLiftUu(){const e=Number(this.options.elements.nameplateLift.value);return Number.isFinite(e)?e:Wm}applyNameplateLiftUu(e){const{nameplateLift:t,nameplateLiftReadout:i}=this.options.elements,s=e??Wm;t.value=`${s}`,i.textContent=qn(s,"",0)}installEventListeners(e){const{elements:t}=this.options;t.usePlayerCameraSettings.addEventListener("change",()=>{const s=t.usePlayerCameraSettings.checked;t.cameraSettingsControls.hidden=s,this.options.getReplayPlayer()?.setCustomCameraSettings(s?null:this.readCustomCameraSettings()),this.options.requestConfigSync()},{signal:e});for(const s of[t.customCameraFov,t.customCameraHeight,t.customCameraPitch,t.customCameraDistance,t.customCameraStiffness,t.customCameraSwivelSpeed,t.customCameraTransitionSpeed])s.addEventListener("input",()=>{const a=this.readCustomCameraSettings();this.syncCustomCameraSettingControls(a),this.options.getReplayPlayer()?.setCustomCameraSettings(a),this.options.requestConfigSync()},{signal:e});t.attachedPlayer.addEventListener("change",()=>{const s=this.options.getReplayPlayer(),a=t.attachedPlayer.value||null;this.disableAutoPossessionForManualCameraControl(),s?.setAttachedPlayer(a),a&&(s?.setCustomCameraSettings(null),this.setBallCamMode("player")),this.lastFreeCameraPreset=null,this.options.requestConfigSync()},{signal:e}),t.cameraViewFreeButton.addEventListener("click",()=>{this.options.getReplayPlayer()?.setCameraViewMode("free"),this.disableAutoPossessionForManualCameraControl(),this.lastFreeCameraPreset=null,this.options.requestConfigSync()},{signal:e}),t.cameraViewFollowButton.addEventListener("click",()=>{const s=this.options.getReplayPlayer();this.disableAutoPossessionForManualCameraControl(),s?.setCameraViewMode("follow"),s?.getState().attachedPlayerId&&(s.setCustomCameraSettings(null),this.setBallCamMode("player")),this.lastFreeCameraPreset=null,this.options.requestConfigSync()},{signal:e}),t.cameraViewOverheadButton.addEventListener("click",()=>{this.options.getReplayPlayer()?.setFreeCameraPreset("overhead"),this.disableAutoPossessionForManualCameraControl(),this.lastFreeCameraPreset="overhead",this.options.requestConfigSync()},{signal:e}),t.cameraViewSideButton.addEventListener("click",()=>{this.options.getReplayPlayer()?.setFreeCameraPreset("side"),this.disableAutoPossessionForManualCameraControl(),this.lastFreeCameraPreset="side",this.options.requestConfigSync()},{signal:e});const i=[["off",t.ballCamOffButton],["on",t.ballCamOnButton],["player",t.ballCamPlayerButton]];for(const[s,a]of i)a.addEventListener("click",()=>{this.setBallCamMode(s),this.options.requestConfigSync()},{signal:e});t.cameraViewAutoPossession.addEventListener("change",()=>{this.setAutoPossessionEnabled(t.cameraViewAutoPossession.checked)},{signal:e}),t.nameplateLift.addEventListener("input",()=>{t.nameplateLiftReadout.textContent=qn(this.nameplateLiftUu,"",0),this.options.requestConfigSync()},{signal:e})}setTransportEnabled(e,t){this.options.elements.attachedPlayer.disabled=!e,this.syncModeButtons(e?t:void 0)}syncState(e){const{elements:t}=this.options;t.usePlayerCameraSettings.checked=e.customCameraSettings===null,t.cameraSettingsControls.hidden=t.usePlayerCameraSettings.checked,this.syncCustomCameraSettingControls(e.customCameraSettings??this.getFallbackCameraSettings()),this.ballCamModeValue=pE(e),this.renderBallCamButtons(),t.attachedPlayer.value=e.attachedPlayerId??"",this.syncAvailability(e),this.renderProfile(e)}syncAvailability(e){this.syncModeButtons(e);const i=this.options.getReplayPlayer()!==null&&e?.cameraViewMode==="follow"&&(e.attachedPlayerId??null)!==null;this.options.elements.usePlayerCameraSettings.disabled=!i,this.setCameraSettingControlsEnabled(i&&e?.customCameraSettings!==null),this.options.elements.ballCamOffButton.disabled=!i,this.options.elements.ballCamOnButton.disabled=!i,this.options.elements.ballCamPlayerButton.disabled=!i,this.renderBallCamButtons()}syncModeButtons(e){const t=e?.cameraViewMode??"free",i=this.options.getReplayPlayer()!==null&&e!==void 0,s=(e?.attachedPlayerId??null)!==null;for(const l of cV){const c=this.getCameraViewButton(l);c.disabled=!i||l==="follow"&&!s;const u=l===t;c.dataset.active=u?"true":"false",c.setAttribute("aria-pressed",u?"true":"false")}const{cameraViewOverheadButton:a,cameraViewSideButton:r}=this.options.elements,{cameraViewAutoPossession:o}=this.options.elements;a.disabled=!i,r.disabled=!i,o.disabled=!i,a.dataset.active="false",r.dataset.active="false",this.renderAutoPossessionButton(),a.setAttribute("aria-pressed","false"),r.setAttribute("aria-pressed","false")}populateAttachedPlayerOptions(e){const{attachedPlayer:t}=this.options.elements;t.replaceChildren(),t.append(new Option("Free camera",""));for(const i of e)t.append(new Option(`${i.name} (${i.isTeamZero?"Blue":"Orange"})`,i.id))}renderProfile(e){const t=this.options.elements,i=this.options.getReplayPlayer(),s=e?.attachedPlayerId??null;if(!i||e?.cameraViewMode!=="follow"||s===null){this.renderEmptyProfile("Free camera");return}const a=i.replay.players.find(o=>o.id===s);if(!a){this.renderEmptyProfile("Unknown");return}const r=this.getEffectiveCameraSettings(e);t.cameraProfileReadout.textContent=e.customCameraSettings===null?a.name:`${a.name} custom`,t.cameraFovReadout.textContent=qn(r.fov,"",0),t.cameraHeightReadout.textContent=qn(r.height,"",0),t.cameraPitchReadout.textContent=qn(r.pitch,"",0),t.cameraBaseDistanceReadout.textContent=qn(r.distance,"",0),t.cameraStiffnessReadout.textContent=qn(r.stiffness,"",2)}getFallbackCameraSettings(){return mE}getAttachedPlayerCameraSettings(e){const t=this.options.getReplayPlayer();return!t||e===null?null:t.replay.players.find(i=>i.id===e)?.cameraSettings??null}getEffectiveCameraSettings(e){return{...this.getFallbackCameraSettings(),...this.getAttachedPlayerCameraSettings(e.attachedPlayerId)??{},...e.customCameraSettings??{}}}readCustomCameraSettings(){const e=this.options.elements;return{fov:Number(e.customCameraFov.value),height:Number(e.customCameraHeight.value),pitch:Number(e.customCameraPitch.value),distance:Number(e.customCameraDistance.value),stiffness:Number(e.customCameraStiffness.value),swivelSpeed:Number(e.customCameraSwivelSpeed.value),transitionSpeed:Number(e.customCameraTransitionSpeed.value)}}setCameraSettingControlsEnabled(e){const t=this.options.elements;t.cameraSettingsControls.hidden=t.usePlayerCameraSettings.checked,t.customCameraFov.disabled=!e,t.customCameraHeight.disabled=!e,t.customCameraPitch.disabled=!e,t.customCameraDistance.disabled=!e,t.customCameraStiffness.disabled=!e,t.customCameraSwivelSpeed.disabled=!e,t.customCameraTransitionSpeed.disabled=!e}syncCustomCameraSettingControls(e){const t=this.options.elements,i=this.getFallbackCameraSettings(),s=e.fov??i.fov,a=e.height??i.height,r=e.pitch??i.pitch,o=e.distance??i.distance,l=e.stiffness??i.stiffness,c=e.swivelSpeed??i.swivelSpeed,u=e.transitionSpeed??i.transitionSpeed;t.customCameraFov.value=`${s}`,t.customCameraHeight.value=`${a}`,t.customCameraPitch.value=`${r}`,t.customCameraDistance.value=`${o}`,t.customCameraStiffness.value=`${l}`,t.customCameraSwivelSpeed.value=`${c}`,t.customCameraTransitionSpeed.value=`${u}`,t.customCameraFovReadout.textContent=qn(s,"",0),t.customCameraHeightReadout.textContent=qn(a,"",0),t.customCameraPitchReadout.textContent=qn(r,"",0),t.customCameraDistanceReadout.textContent=qn(o,"",0),t.customCameraStiffnessReadout.textContent=qn(l,"",2),t.customCameraSwivelSpeedReadout.textContent=qn(c,"",1),t.customCameraTransitionSpeedReadout.textContent=qn(u,"",2)}getCameraViewButton(e){switch(e){case"free":return this.options.elements.cameraViewFreeButton;case"follow":return this.options.elements.cameraViewFollowButton}}renderEmptyProfile(e){const t=this.options.elements;t.cameraProfileReadout.textContent=e,t.cameraFovReadout.textContent="--",t.cameraHeightReadout.textContent="--",t.cameraPitchReadout.textContent="--",t.cameraBaseDistanceReadout.textContent="--",t.cameraStiffnessReadout.textContent="--"}}function qn(n,e="",t=0){return n===void 0||Number.isNaN(n)?"--":`${n.toFixed(t)}${e}`}function uV(n){return new Xg(n)}const Zb="subtr-actor-touch-overlay-styles",Kg=5882879,qg=16761180,Jb=120,Qb=4,dV=196,tm=24,ex=210,tx=5,hV=.1,fV=48,pV=["team","intention","kind","height_band","surface","dodge_state","flag"],mV=[{label:"Blue team",color:Kg},{label:"Orange team",color:qg}],_E=[{label:"Shot",color:16711880},{label:"Save",color:58998},{label:"Clear",color:16764928},{label:"Boom",color:16020150},{label:"Pass",color:47103},{label:"Control",color:0},{label:"Advance",color:16486972}],id=[{label:"Control",color:0},{label:"Medium hit",color:16436245},{label:"Hard hit",color:16735596}],sd=[{label:"Ground",color:10741301},{label:"Low air",color:3718648},{label:"High air",color:8490232}],gE=[{label:"Ground",color:8702998},{label:"Air",color:6333946},{label:"Wall",color:16347926}],h_=[{label:"No dodge",color:9741240},{label:"Dodge",color:15235577}],f_=[{label:"First touch",color:16777215},{label:"Contested",color:15680580}],_V=[{title:"Team",entries:mV},{title:"Intention",entries:_E},{title:"Hit strength",entries:id},{title:"Height",entries:sd},{title:"Surface",entries:gE},{title:"Dodge",entries:h_},{title:"Flags",entries:f_}];function gc(n){return Object.fromEntries(n.map(e=>[e.label.toLowerCase().replaceAll(" ","_"),e.color]))}const yE=gc(_E),vE={...gc(id),medium_hit:id[1].color,hard_hit:id[2].color},bE={...gc(sd),low_air:sd[1].color,high_air:sd[2].color},xE=gc(gE),wE={...gc(h_),no_dodge:h_[0].color},p_={first_touch:f_[0].color,contested:f_[1].color},Gi=10134961;function jn(n,e){const t=n.tags;if(!Array.isArray(t))return null;const i=t.find(s=>s.group===e);return i?i.value:null}function SE(n){return jn(n,"possession")??jn(n,"action")}function At(n){const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function nm(n,e){return Math.max(0,n-e)}function ad(n){return n==="team"||n==="intention"||n==="kind"||n==="height_band"||n==="surface"||n==="dodge_state"||n==="flag"}function po(n){const e=Array.isArray(n)?n:n?[n]:["team"],t=new Set,i=[];for(const s of e)ad(s)&&!t.has(s)&&(t.add(s),i.push(s));return i.length>0?i:["team"]}function TE(n){return n[n.length-1]??"team"}function gV(n,e,t){const i=yV(n,TE(t)),s=i?` · ${i.replaceAll("_"," ")}`:"";if(e==="markers")return`${n.playerName}${s}`;const a=Math.round(n.totalBallAdvanceDistance),r=Math.round(n.totalBallRetreatDistance);return a>0&&r>0?`${n.playerName} +${a} / -${r} uu${s}`:r>0?`${n.playerName} -${r} uu${s}`:`${n.playerName} +${a} uu${s}`}function yV(n,e){return e==="intention"?n.intention:e==="kind"?n.kind:e==="height_band"?n.heightBand:e==="surface"?n.surface:e==="dodge_state"?n.dodgeState:e==="flag"?n.contested?"contested":n.firstTouch?"first_touch":null:null}function vV(n){return n.split("_").filter(Boolean).map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1)}`).join(" ")}function ol(n,e,t){return typeof e!="string"||e.length===0?null:{key:n,value:e,label:vV(e),color:t[e]??Gi}}function nx(n,e,t){return e!==!0?null:{key:n,value:"true",label:t,color:p_[n]??Gi}}function bV(n){const e=jn(n,"reception")==="first_touch",t=jn(n,"contested")!=null;return[ol("intention",SE(n),yE),ol("kind",jn(n,"kind"),vE),ol("height_band",jn(n,"height_band"),bE),ol("surface",jn(n,"surface"),xE),ol("dodge_state",jn(n,"dodge_state"),wE),nx("first_touch",e,"First touch"),nx("contested",t,"Contested")].filter(i=>i!=null)}function ME(n,e){return e==="intention"?yE[n.intention??""]??Gi:e==="kind"?vE[n.kind??""]??Gi:e==="height_band"?bE[n.heightBand??""]??Gi:e==="surface"?xE[n.surface??""]??Gi:e==="dodge_state"?wE[n.dodgeState??""]??Gi:e==="flag"?n.contested?p_.contested??Gi:n.firstTouch?p_.first_touch??Gi:Gi:n.isTeamZero?Kg:qg}function xV(n,e){return(e.length>0?e:["team"]).map(i=>ME(n,i))}function EE(n,e){const t=[],i=[...ve(n,"touch")].sort((s,a)=>s.frame!==a.frame?s.frame-a.frame:s.time!==a.time?s.time-a.time:0);for(const s of i){const a=At(s.player),r=e.ballFrames[s.frame]?.position;if(!r)continue;const o=s.ball_movement,c=(o?e.ballFrames[o.end_frame]?.position:null)??r,u=t.length,d=bV(s);t.push({id:`touch-stat:${s.frame}:${a}:${u+1}`,time:e.frames[s.frame]?.time??s.time,frame:s.frame,isTeamZero:s.is_team_0,playerId:a,playerName:e.players.find(h=>h.id===a)?.name??a,kind:jn(s,"kind"),intention:SE(s),heightBand:jn(s,"height_band"),surface:jn(s,"surface"),dodgeState:jn(s,"dodge_state"),firstTouch:jn(s,"reception")==="first_touch",contested:jn(s,"contested")!=null,classifications:d,position:{x:r.x,y:r.y,z:r.z},endPosition:{x:c.x,y:c.y,z:c.z},totalBallTravelDistance:o?nm(o.travel_distance,0):0,totalBallAdvanceDistance:o?nm(o.advance_distance,0):0,totalBallRetreatDistance:o?nm(o.retreat_distance,0):0})}return t}function wV(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function SV(){if(document.getElementById(Zb))return;const n=document.createElement("style");n.id=Zb,n.textContent=` .sap-touch-overlay-root { position: absolute; inset: 0; @@ -5504,45 +5569,45 @@ void main() { border-color: rgba(255, 193, 92, 0.5); background: rgba(76, 41, 7, 0.84); } - `,document.head.append(n)}function KH(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}function gE(n){return[n.line.material,n.cone.material].flatMap(e=>Array.isArray(e)?e:[e])}function Yb(n,e){for(const t of gE(n))t.transparent=!0,t.opacity=e,t.depthWrite=!1,t.depthTest=!1}function jb(n){n.removeFromParent(),n.line.geometry.dispose(),n.cone.geometry.dispose();for(const e of gE(n))e.dispose()}function l_(n){for(const e of n.ringSegments){e.removeFromParent(),e.geometry.dispose();const t=Array.isArray(e.material)?e.material:[e.material];for(const i of t)i.dispose()}n.ringSegments=[],n.ringColorsKey=""}function qH(n,e,t){const i=new ni(e,t,48,1),s=new Ye({color:n,transparent:!0,opacity:.7,side:ct,depthWrite:!1,depthTest:!1}),a=new we(i,s);return a.rotation.x=-Math.PI/2,a.renderOrder=40,a}function YH(n,e){const t=e.length>0?e:[Vi],i=t.join("|");if(n.ringColorsKey===i)return;l_(n);const s=t.length,a=Wb*Math.max(0,s-1),r=(kH-$b-a)/s,o=t.map((l,c)=>{const u=$b+c*(r+Wb);return qH(l,u,u+r)});for(const l of o)n.ring.add(l),n.ringSegments.push(l);n.ringColorsKey=i}function jH(n,e){for(const t of n.ringSegments){const i=Array.isArray(t.material)?t.material:[t.material];for(const s of i)s.opacity=e}}class ZH{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;arrowStart=new S;arrowEnd=new S;arrowDirection=new S;labelOffset=new S(0,0,Xb);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=Kb;mode="markers";colorModes=["team"];constructor(e,t,i,s,a){XH(),this.scene=e,this.container=t,this.decaySeconds=Math.max(.1,a?.decaySeconds??Kb),this.mode=a?.mode??"markers",this.colorModes=ho(a?.colorModes??a?.colorMode),this.labelOffset.set(0,0,Xb),this.markers=_E(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="touch-event-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-touch-overlay-root",this.container.append(this.labelRoot)}getDecaySeconds(){return this.decaySeconds}setDecaySeconds(e){this.decaySeconds=Math.max(.1,e)}getMode(){return this.mode}setMode(e){this.mode=e}getColorModes(){return[...this.colorModes]}setColorMode(e){this.setColorModes([e])}setColorModes(e){this.colorModes=ho([...e])}update(e){const t=WH(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.ring.removeFromParent(),l_(a),jb(a.arrow),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.1+.6*r,c=.95+(1-r)*.28,u=pE(this.colorModes),d=mE(s,u),h=$H(s,this.colorModes);YH(o,h),jH(o,l),o.arrow.setColor(d),o.ring.position.set(s.position.x,s.position.y,s.position.z+qp),o.ring.scale.setScalar(c),o.label.textContent=zH(s,this.mode,this.colorModes),o.label.classList.toggle("sap-touch-overlay-label-advancement",this.mode==="advancement");const f=u==="team";o.label.classList.toggle("sap-touch-overlay-label-blue",f&&s.isTeamZero),o.label.classList.toggle("sap-touch-overlay-label-orange",f&&!s.isTeamZero),o.label.style.borderColor=f?"":`#${d.toString(16).padStart(6,"0")}cc`,o.label.style.background=f?"":`#${d.toString(16).padStart(6,"0")}66`,this.updateArrow(o,s,l),this.worldPosition.set(s.position.x,s.position.y,s.position.z),this.worldPosition.add(this.labelOffset),this.scene.replayRoot.localToWorld(this.worldPosition),KH(this.worldPosition,this.scene.camera,this.container,this.projectedPosition)?(o.label.hidden=!1,o.label.style.opacity=`${.22+.78*r}`,o.label.style.transform=`translate(${this.projectedPosition.x.toFixed(1)}px, ${this.projectedPosition.y.toFixed(1)}px) translate(-50%, -100%)`):o.label.hidden=!0}}dispose(){for(const e of this.views.values())e.ring.removeFromParent(),l_(e),jb(e.arrow),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition,this.changedContainerPosition=!1)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=new Mt;i.renderOrder=40,this.group.add(i);const s=new Tg(new S(0,1,0),new S,1,e.isTeamZero?zg:Hg,1,1);s.visible=!1,s.renderOrder=45,s.line.renderOrder=45,s.cone.renderOrder=45,Yb(s,.7),this.group.add(s);const a=document.createElement("div");a.className=`sap-touch-overlay-label ${e.isTeamZero?"sap-touch-overlay-label-blue":"sap-touch-overlay-label-orange"}`,a.textContent=e.playerName,a.hidden=!0,this.labelRoot.append(a);const r={marker:e,ring:i,ringSegments:[],ringColorsKey:"",arrow:s,label:a};return this.views.set(e.id,r),r}updateArrow(e,t,i){if(this.mode!=="advancement"||t.totalBallTravelDistance<=OH){e.arrow.visible=!1;return}this.arrowStart.set(t.position.x,t.position.y,t.position.z+qp*2),this.arrowEnd.set(t.endPosition.x,t.endPosition.y,t.endPosition.z+qp*2),this.arrowDirection.copy(this.arrowEnd).sub(this.arrowStart);const s=this.arrowDirection.length();if(s0&&r>0)return a/r}const t=n.frames[0],i=n.frames.at(-1);if(t&&i){const s=i.frame_number-t.frame_number,a=i.time-t.time;if(s>0&&a>0)return s/a}return tV}function iV(n,e={}){if(!n)return[];const t=e.preRollSeconds??JH,i=e.minPossessionSeconds??QH,s=e.samePlayerBridgeSeconds??eV,a=ve(n,"player_possession").map(d=>({playerId:At(d.player_id),startFrame:Math.max(0,Math.trunc(al(d.start_frame))),endFrame:Math.max(0,Math.trunc(al(d.end_frame))),startTime:al(d.start_time),endTime:al(d.end_time),duration:al(d.duration),sustainedControl:d.sustained_control})).filter(d=>d.endFrame>d.startFrame&&(d.sustainedControl||d.duration>=i)).sort((d,h)=>d.startFrame-h.startFrame||d.endFrame-h.endFrame),r=nV(n,a),o=Math.max(0,Math.round(t*r)),l=Math.max(0,Math.round(s*r)),c=[];let u=null;for(const d of a){let h=Math.max(0,d.startFrame-o);u&&u.playerId!==d.playerId&&(h=Math.max(h,u.endFrame));const f=c.at(-1);if(f&&f.playerId===d.playerId&&h<=f.endFrame+l){c[c.length-1]={...f,endFrame:Math.max(f.endFrame,d.endFrame),possessionEndFrame:Math.max(f.possessionEndFrame,d.endFrame)},u=d;continue}c.push({playerId:d.playerId,startFrame:h,endFrame:d.endFrame,possessionStartFrame:d.startFrame,possessionEndFrame:d.endFrame}),u=d}return c.map((d,h)=>({...d,endFrame:c[h+1]?.startFrame??Number.POSITIVE_INFINITY}))}function sV(n,e){const t=Math.max(0,Math.trunc(e));return n.find(s=>t>=s.startFrame&&tthis.update(i))))}reset(){this.unsubscribeBeforeRender?.(),this.unsubscribeBeforeRender=null,this.sourcePlayer=null,this.sourceTimeline=null,this.spans=[]}syncCurrentFrame(){const e=this.options.getReplayPlayer();if(!e)return;const t=e.getState();this.update({frameIndex:t.frameIndex,nextFrameIndex:t.frameIndex,alpha:0,currentTime:t.currentTime})}update(e){const t=this.options.getCameraControlsController(),i=this.options.getReplayPlayer();if(!t?.autoPossessionEnabled||!i)return;const s=sV(this.spans,e.frameIndex);if(!s||!i.replay.players.some(r=>r.id===s))return;const a=i.getState();a.cameraViewMode==="follow"&&a.attachedPlayerId===s||t.followPlayerWithReplayCamera(s,{ballCam:"player",preserveAutoPossession:!0,requestConfigSync:!1,usePlayerCameraSettings:!1})}}function rV(n){return new aV(n)}const oV=236,Zl=4120,lV=2300,cV=16185075,uV=.18,dV=1118481,td=5882879,nd=16761180,hV=.55,jp=.12,Zb=.28,fV=3,pV=4,Jb=5,Qb=2,mV=6,_V=856343,gV=.42,yV=18,vV=.24,bV=10,ex=220,xV=200,yE=140,wV=220,SV=100,TV=120;function MV(n){const e=xV/2;if(n){const s=-Zl+ex,a=-e;return{minX:s,maxX:a,centerX:(s+a)/2,width:a-s}}const t=e,i=Zl-ex;return{minX:t,maxX:i,centerX:(t+i)/2,width:i-t}}function EV(n,e,t){if(n.length<2)return[];const i=Math.min(...n),s=Math.max(...n),a=s-i,r=e?-1:1,o=-r;return a<=t?[{kind:"other",centerY:(i+s)/2,halfDepth:Math.max(t-a/2,t*.35),directions:[r,o]}]:[{kind:"back",centerY:e?i:s,halfDepth:t,directions:[r]},{kind:"forward",centerY:e?s:i,halfDepth:t,directions:[o]}]}function CV(n,e){const t=new Ns;return t.moveTo(0,e/2),t.lineTo(n/2,-e/2),t.lineTo(-n/2,-e/2),t.closePath(),new ur(t)}function tx(n){const e=SV*n,t=new Ye({color:dV,transparent:!0,opacity:.9,side:ct,depthWrite:!1,depthTest:!1}),i=new Mt;i.visible=!1;const s=new Dn(yE*.55*n,1),a=new we(s,t);a.position.z=Jb,a.renderOrder=22,i.add(a);const r=CV(TV*n,e),o=new we(r,t);return o.position.z=Jb,o.renderOrder=23,i.add(o),{group:i,shaftGeom:s,shaftMesh:a,headGeom:r,headMesh:o,material:t,headLength:e}}function Zp(n,e,t,i){const s=Math.max(t-n.headLength,n.headLength*.2);n.group.position.x=e,n.group.rotation.z=i>0?0:Math.PI,n.shaftMesh.scale.y=s,n.shaftMesh.position.y=-n.headLength/2,n.headMesh.position.y=t/2-n.headLength/2,n.group.visible=!0}function th(n){n.group.visible=!1}function qr(n,e){const t=new Mt;t.visible=!1;const i=new Ye({color:cV,transparent:!0,opacity:uV,side:ct,depthWrite:!1,depthTest:!1}),s=new Dn(1,1),a=new we(s,i);a.position.z=fV,a.renderOrder=20,t.add(a);const r=new Ye({color:e,transparent:!0,opacity:hV,side:ct,depthWrite:!1,depthTest:!1}),o=new Dn(1,1),l=new we(o,r);l.position.z=pV,l.renderOrder=21,t.add(l);const c=tx(n),u=tx(n);return t.add(c.group),t.add(u.group),{group:t,floorGeom:s,floorMesh:a,floorMaterial:i,stripeGeom:o,stripeMesh:l,stripeMaterial:r,primaryMarker:c,secondaryMarker:u}}function AV(n){n.group.visible=!1,th(n.primaryMarker),th(n.secondaryMarker)}function RV(n,e,t,i){const s=e.halfDepth*2*i,a=Zl*2*i,r=t.width*i,o=t.centerX*i,l=yE*i,c=Math.max(s-32*i,n.primaryMarker.headLength*1.15),u=Math.min(c,Math.max(wV*i,s*.6));if(n.group.position.y=e.centerY*i,n.floorMesh.position.x=0,n.floorMesh.scale.set(a,s,1),n.stripeMesh.position.x=o,n.stripeMesh.scale.set(l,s,1),th(n.primaryMarker),th(n.secondaryMarker),e.directions.length===1)Zp(n.primaryMarker,o,u,e.directions[0]);else{const d=r*.18;Zp(n.primaryMarker,o-d,u,e.directions[0]),Zp(n.secondaryMarker,o+d,u,e.directions[1])}n.group.visible=!0}function nx(n){n.group.removeFromParent(),n.shaftGeom.dispose(),n.headGeom.dispose(),n.material.dispose()}class PV{replay;blueBack;blueForward;blueOther;orangeBack;orangeForward;orangeOther;constructor(e,t,i){this.replay=t,this.blueBack=qr(i,td),this.blueForward=qr(i,td),this.blueOther=qr(i,td),this.orangeBack=qr(i,nd),this.orangeForward=qr(i,nd),this.orangeOther=qr(i,nd);for(const s of this.getZones())e.add(s.group)}update(e,t){const{frameIndex:i}=e,s=oV;for(const a of[!0,!1]){const r=this.replay.players.filter(d=>d.isTeamZero===a).length,o=[];for(const d of this.replay.players){if(d.isTeamZero!==a)continue;const h=d.frames[i];h?.position&&o.push(h.position.y)}const l=MV(a),c=this.getTeamZones(a);for(const d of c.values())AV(d);if(r<2||o.length!==r)continue;const u=EV(o,a,s);for(const d of u){const h=c.get(d.kind);h&&RV(h,d,l,t)}}}dispose(){for(const e of this.getZones())e.group.removeFromParent(),e.floorGeom.dispose(),e.floorMaterial.dispose(),e.stripeGeom.dispose(),e.stripeMaterial.dispose(),nx(e.primaryMarker),nx(e.secondaryMarker)}getTeamZones(e){return e?new Map([["back",this.blueBack],["forward",this.blueForward],["other",this.blueOther]]):new Map([["back",this.orangeBack],["forward",this.orangeForward],["other",this.orangeOther]])}getZones(){return[this.blueBack,this.blueForward,this.blueOther,this.orangeBack,this.orangeForward,this.orangeOther]}}function IV(n){return n==null||Number.isNaN(n)?null:n<0?"team-zero":"team-one"}class LV{group;teamZeroSide;teamOneSide;constructor(e,t){this.group=new Mt,this.teamZeroSide=this.createHalfFieldSide(td),this.teamOneSide=this.createHalfFieldSide(nd);const i=Zl*t,s=5120*t;this.teamZeroSide.mesh.position.set(0,-s/2,Qb),this.teamZeroSide.mesh.scale.set(i*2,s,1),this.teamOneSide.mesh.position.set(0,s/2,Qb),this.teamOneSide.mesh.scale.set(i*2,s,1),this.group.add(this.teamZeroSide.mesh),this.group.add(this.teamOneSide.mesh),e.add(this.group)}update(e){const t=IV(e);this.teamZeroSide.material.opacity=t==="team-zero"?Zb:jp,this.teamOneSide.material.opacity=t==="team-one"?Zb:jp}dispose(){this.group.removeFromParent(),this.teamZeroSide.mesh.geometry.dispose(),this.teamZeroSide.material.dispose(),this.teamOneSide.mesh.geometry.dispose(),this.teamOneSide.material.dispose()}createHalfFieldSide(e){const t=new Dn(1,1),i=new Ye({color:e,transparent:!0,opacity:jp,side:ct,depthWrite:!1,depthTest:!1}),s=new we(t,i);return s.renderOrder=18,{mesh:s,material:i}}}function DV(n,e){const t=new Mt,i=Zl*2*e,s=(a,r,o)=>{const l=new Dn(i,r*e),c=new Ye({color:_V,transparent:!0,opacity:o,side:ct,depthWrite:!1,depthTest:!1}),u=new we(l,c);return u.position.set(0,a,mV),u.renderOrder=24,u};for(const a of[-1,1]){const r=a*lV*e;t.add(s(r,yV,gV))}return t.add(s(0,bV,vV)),n.add(t),t}function cn(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function c_(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function Oi(n,e){return`
${n}${e}
`}function kV(n,e){return` - ${Oi("50s",cn(n?.count))} - ${Oi("Blue wins",`${cn(n?.wins)} (${c_(n?.wins,n?.count)})`)} - ${Oi("Orange wins",`${cn(n?.losses)} (${c_(n?.losses,n?.count)})`)} - ${Oi("Neutral",cn(n?.neutral_outcomes))} - ${Oi("Blue poss after",cn(n?.possession_after_count))} - ${Oi("Orange poss after",cn(n?.opponent_possession_after_count))} - ${Oi("Kickoff 50s",cn(n?.kickoff_count))} - ${Oi("Blue kickoff wins",cn(n?.kickoff_wins))} - ${Oi("Orange kickoff wins",cn(n?.kickoff_losses))} - ${Oi("Blue kickoff poss",cn(n?.kickoff_possession_after_count))} - ${Oi("Orange kickoff poss",cn(n?.kickoff_opponent_possession_after_count))} - `}function ix(n){return` + `,document.head.append(n)}function TV(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}function CE(n){return[n.line.material,n.cone.material].flatMap(e=>Array.isArray(e)?e:[e])}function ix(n,e){for(const t of CE(n))t.transparent=!0,t.opacity=e,t.depthWrite=!1,t.depthTest=!1}function sx(n){n.removeFromParent(),n.line.geometry.dispose(),n.cone.geometry.dispose();for(const e of CE(n))e.dispose()}function m_(n){for(const e of n.ringSegments){e.removeFromParent(),e.geometry.dispose();const t=Array.isArray(e.material)?e.material:[e.material];for(const i of t)i.dispose()}n.ringSegments=[],n.ringColorsKey=""}function MV(n,e,t){const i=new ni(e,t,48,1),s=new Ye({color:n,transparent:!0,opacity:.7,side:ct,depthWrite:!1,depthTest:!1}),a=new we(i,s);return a.rotation.x=-Math.PI/2,a.renderOrder=40,a}function EV(n,e){const t=e.length>0?e:[Gi],i=t.join("|");if(n.ringColorsKey===i)return;m_(n);const s=t.length,a=Qb*Math.max(0,s-1),r=(dV-Jb-a)/s,o=t.map((l,c)=>{const u=Jb+c*(r+Qb);return MV(l,u,u+r)});for(const l of o)n.ring.add(l),n.ringSegments.push(l);n.ringColorsKey=i}function CV(n,e){for(const t of n.ringSegments){const i=Array.isArray(t.material)?t.material:[t.material];for(const s of i)s.opacity=e}}class AV{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;arrowStart=new S;arrowEnd=new S;arrowDirection=new S;labelOffset=new S(0,0,ex);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=tx;mode="markers";colorModes=["team"];constructor(e,t,i,s,a){SV(),this.scene=e,this.container=t,this.decaySeconds=Math.max(.1,a?.decaySeconds??tx),this.mode=a?.mode??"markers",this.colorModes=po(a?.colorModes??a?.colorMode),this.labelOffset.set(0,0,ex),this.markers=EE(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="touch-event-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-touch-overlay-root",this.container.append(this.labelRoot)}getDecaySeconds(){return this.decaySeconds}setDecaySeconds(e){this.decaySeconds=Math.max(.1,e)}getMode(){return this.mode}setMode(e){this.mode=e}getColorModes(){return[...this.colorModes]}setColorMode(e){this.setColorModes([e])}setColorModes(e){this.colorModes=po([...e])}update(e){const t=wV(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.ring.removeFromParent(),m_(a),sx(a.arrow),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.1+.6*r,c=.95+(1-r)*.28,u=TE(this.colorModes),d=ME(s,u),h=xV(s,this.colorModes);EV(o,h),CV(o,l),o.arrow.setColor(d),o.ring.position.set(s.position.x,s.position.y,s.position.z+tm),o.ring.scale.setScalar(c),o.label.textContent=gV(s,this.mode,this.colorModes),o.label.classList.toggle("sap-touch-overlay-label-advancement",this.mode==="advancement");const f=u==="team";o.label.classList.toggle("sap-touch-overlay-label-blue",f&&s.isTeamZero),o.label.classList.toggle("sap-touch-overlay-label-orange",f&&!s.isTeamZero),o.label.style.borderColor=f?"":`#${d.toString(16).padStart(6,"0")}cc`,o.label.style.background=f?"":`#${d.toString(16).padStart(6,"0")}66`,this.updateArrow(o,s,l),this.worldPosition.set(s.position.x,s.position.y,s.position.z),this.worldPosition.add(this.labelOffset),this.scene.replayRoot.localToWorld(this.worldPosition),TV(this.worldPosition,this.scene.camera,this.container,this.projectedPosition)?(o.label.hidden=!1,o.label.style.opacity=`${.22+.78*r}`,o.label.style.transform=`translate(${this.projectedPosition.x.toFixed(1)}px, ${this.projectedPosition.y.toFixed(1)}px) translate(-50%, -100%)`):o.label.hidden=!0}}dispose(){for(const e of this.views.values())e.ring.removeFromParent(),m_(e),sx(e.arrow),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition,this.changedContainerPosition=!1)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=new Mt;i.renderOrder=40,this.group.add(i);const s=new Ig(new S(0,1,0),new S,1,e.isTeamZero?Kg:qg,1,1);s.visible=!1,s.renderOrder=45,s.line.renderOrder=45,s.cone.renderOrder=45,ix(s,.7),this.group.add(s);const a=document.createElement("div");a.className=`sap-touch-overlay-label ${e.isTeamZero?"sap-touch-overlay-label-blue":"sap-touch-overlay-label-orange"}`,a.textContent=e.playerName,a.hidden=!0,this.labelRoot.append(a);const r={marker:e,ring:i,ringSegments:[],ringColorsKey:"",arrow:s,label:a};return this.views.set(e.id,r),r}updateArrow(e,t,i){if(this.mode!=="advancement"||t.totalBallTravelDistance<=hV){e.arrow.visible=!1;return}this.arrowStart.set(t.position.x,t.position.y,t.position.z+tm*2),this.arrowEnd.set(t.endPosition.x,t.endPosition.y,t.endPosition.z+tm*2),this.arrowDirection.copy(this.arrowEnd).sub(this.arrowStart);const s=this.arrowDirection.length();if(s0&&r>0)return a/r}const t=n.frames[0],i=n.frames.at(-1);if(t&&i){const s=i.frame_number-t.frame_number,a=i.time-t.time;if(s>0&&a>0)return s/a}return LV}function DV(n,e={}){if(!n)return[];const t=e.preRollSeconds??RV,i=e.minPossessionSeconds??PV,s=e.samePlayerBridgeSeconds??IV,a=ve(n,"player_possession").map(d=>({playerId:At(d.player_id),startFrame:Math.max(0,Math.trunc(ll(d.start_frame))),endFrame:Math.max(0,Math.trunc(ll(d.end_frame))),startTime:ll(d.start_time),endTime:ll(d.end_time),duration:ll(d.duration),sustainedControl:d.sustained_control})).filter(d=>d.endFrame>d.startFrame&&(d.sustainedControl||d.duration>=i)).sort((d,h)=>d.startFrame-h.startFrame||d.endFrame-h.endFrame),r=kV(n,a),o=Math.max(0,Math.round(t*r)),l=Math.max(0,Math.round(s*r)),c=[];let u=null;for(const d of a){let h=Math.max(0,d.startFrame-o);u&&u.playerId!==d.playerId&&(h=Math.max(h,u.endFrame));const f=c.at(-1);if(f&&f.playerId===d.playerId&&h<=f.endFrame+l){c[c.length-1]={...f,endFrame:Math.max(f.endFrame,d.endFrame),possessionEndFrame:Math.max(f.possessionEndFrame,d.endFrame)},u=d;continue}c.push({playerId:d.playerId,startFrame:h,endFrame:d.endFrame,possessionStartFrame:d.startFrame,possessionEndFrame:d.endFrame}),u=d}return c.map((d,h)=>({...d,endFrame:c[h+1]?.startFrame??Number.POSITIVE_INFINITY}))}function OV(n,e){const t=Math.max(0,Math.trunc(e));return n.find(s=>t>=s.startFrame&&tthis.update(i))))}reset(){this.unsubscribeBeforeRender?.(),this.unsubscribeBeforeRender=null,this.sourcePlayer=null,this.sourceTimeline=null,this.spans=[]}syncCurrentFrame(){const e=this.options.getReplayPlayer();if(!e)return;const t=e.getState();this.update({frameIndex:t.frameIndex,nextFrameIndex:t.frameIndex,alpha:0,currentTime:t.currentTime})}update(e){const t=this.options.getCameraControlsController(),i=this.options.getReplayPlayer();if(!t?.autoPossessionEnabled||!i)return;const s=OV(this.spans,e.frameIndex);if(!s||!i.replay.players.some(r=>r.id===s))return;const a=i.getState();a.cameraViewMode==="follow"&&a.attachedPlayerId===s||t.followPlayerWithReplayCamera(s,{ballCam:"player",preserveAutoPossession:!0,requestConfigSync:!1,usePlayerCameraSettings:!1})}}function NV(n){return new FV(n)}const UV=236,tc=4120,BV=2300,zV=16185075,HV=.18,VV=1118481,rd=5882879,od=16761180,GV=.55,im=.12,ax=.28,$V=3,WV=4,rx=5,ox=2,XV=6,KV=856343,qV=.42,YV=18,jV=.24,ZV=10,lx=220,JV=200,AE=140,QV=220,e5=100,t5=120;function n5(n){const e=JV/2;if(n){const s=-tc+lx,a=-e;return{minX:s,maxX:a,centerX:(s+a)/2,width:a-s}}const t=e,i=tc-lx;return{minX:t,maxX:i,centerX:(t+i)/2,width:i-t}}function i5(n,e,t){if(n.length<2)return[];const i=Math.min(...n),s=Math.max(...n),a=s-i,r=e?-1:1,o=-r;return a<=t?[{kind:"other",centerY:(i+s)/2,halfDepth:Math.max(t-a/2,t*.35),directions:[r,o]}]:[{kind:"back",centerY:e?i:s,halfDepth:t,directions:[r]},{kind:"forward",centerY:e?s:i,halfDepth:t,directions:[o]}]}function s5(n,e){const t=new Ns;return t.moveTo(0,e/2),t.lineTo(n/2,-e/2),t.lineTo(-n/2,-e/2),t.closePath(),new dr(t)}function cx(n){const e=e5*n,t=new Ye({color:VV,transparent:!0,opacity:.9,side:ct,depthWrite:!1,depthTest:!1}),i=new Mt;i.visible=!1;const s=new kn(AE*.55*n,1),a=new we(s,t);a.position.z=rx,a.renderOrder=22,i.add(a);const r=s5(t5*n,e),o=new we(r,t);return o.position.z=rx,o.renderOrder=23,i.add(o),{group:i,shaftGeom:s,shaftMesh:a,headGeom:r,headMesh:o,material:t,headLength:e}}function sm(n,e,t,i){const s=Math.max(t-n.headLength,n.headLength*.2);n.group.position.x=e,n.group.rotation.z=i>0?0:Math.PI,n.shaftMesh.scale.y=s,n.shaftMesh.position.y=-n.headLength/2,n.headMesh.position.y=t/2-n.headLength/2,n.group.visible=!0}function oh(n){n.group.visible=!1}function jr(n,e){const t=new Mt;t.visible=!1;const i=new Ye({color:zV,transparent:!0,opacity:HV,side:ct,depthWrite:!1,depthTest:!1}),s=new kn(1,1),a=new we(s,i);a.position.z=$V,a.renderOrder=20,t.add(a);const r=new Ye({color:e,transparent:!0,opacity:GV,side:ct,depthWrite:!1,depthTest:!1}),o=new kn(1,1),l=new we(o,r);l.position.z=WV,l.renderOrder=21,t.add(l);const c=cx(n),u=cx(n);return t.add(c.group),t.add(u.group),{group:t,floorGeom:s,floorMesh:a,floorMaterial:i,stripeGeom:o,stripeMesh:l,stripeMaterial:r,primaryMarker:c,secondaryMarker:u}}function a5(n){n.group.visible=!1,oh(n.primaryMarker),oh(n.secondaryMarker)}function r5(n,e,t,i){const s=e.halfDepth*2*i,a=tc*2*i,r=t.width*i,o=t.centerX*i,l=AE*i,c=Math.max(s-32*i,n.primaryMarker.headLength*1.15),u=Math.min(c,Math.max(QV*i,s*.6));if(n.group.position.y=e.centerY*i,n.floorMesh.position.x=0,n.floorMesh.scale.set(a,s,1),n.stripeMesh.position.x=o,n.stripeMesh.scale.set(l,s,1),oh(n.primaryMarker),oh(n.secondaryMarker),e.directions.length===1)sm(n.primaryMarker,o,u,e.directions[0]);else{const d=r*.18;sm(n.primaryMarker,o-d,u,e.directions[0]),sm(n.secondaryMarker,o+d,u,e.directions[1])}n.group.visible=!0}function ux(n){n.group.removeFromParent(),n.shaftGeom.dispose(),n.headGeom.dispose(),n.material.dispose()}class o5{replay;blueBack;blueForward;blueOther;orangeBack;orangeForward;orangeOther;constructor(e,t,i){this.replay=t,this.blueBack=jr(i,rd),this.blueForward=jr(i,rd),this.blueOther=jr(i,rd),this.orangeBack=jr(i,od),this.orangeForward=jr(i,od),this.orangeOther=jr(i,od);for(const s of this.getZones())e.add(s.group)}update(e,t){const{frameIndex:i}=e,s=UV;for(const a of[!0,!1]){const r=this.replay.players.filter(d=>d.isTeamZero===a).length,o=[];for(const d of this.replay.players){if(d.isTeamZero!==a)continue;const h=d.frames[i];h?.position&&o.push(h.position.y)}const l=n5(a),c=this.getTeamZones(a);for(const d of c.values())a5(d);if(r<2||o.length!==r)continue;const u=i5(o,a,s);for(const d of u){const h=c.get(d.kind);h&&r5(h,d,l,t)}}}dispose(){for(const e of this.getZones())e.group.removeFromParent(),e.floorGeom.dispose(),e.floorMaterial.dispose(),e.stripeGeom.dispose(),e.stripeMaterial.dispose(),ux(e.primaryMarker),ux(e.secondaryMarker)}getTeamZones(e){return e?new Map([["back",this.blueBack],["forward",this.blueForward],["other",this.blueOther]]):new Map([["back",this.orangeBack],["forward",this.orangeForward],["other",this.orangeOther]])}getZones(){return[this.blueBack,this.blueForward,this.blueOther,this.orangeBack,this.orangeForward,this.orangeOther]}}function l5(n){return n==null||Number.isNaN(n)?null:n<0?"team-zero":"team-one"}class c5{group;teamZeroSide;teamOneSide;constructor(e,t){this.group=new Mt,this.teamZeroSide=this.createHalfFieldSide(rd),this.teamOneSide=this.createHalfFieldSide(od);const i=tc*t,s=5120*t;this.teamZeroSide.mesh.position.set(0,-s/2,ox),this.teamZeroSide.mesh.scale.set(i*2,s,1),this.teamOneSide.mesh.position.set(0,s/2,ox),this.teamOneSide.mesh.scale.set(i*2,s,1),this.group.add(this.teamZeroSide.mesh),this.group.add(this.teamOneSide.mesh),e.add(this.group)}update(e){const t=l5(e);this.teamZeroSide.material.opacity=t==="team-zero"?ax:im,this.teamOneSide.material.opacity=t==="team-one"?ax:im}dispose(){this.group.removeFromParent(),this.teamZeroSide.mesh.geometry.dispose(),this.teamZeroSide.material.dispose(),this.teamOneSide.mesh.geometry.dispose(),this.teamOneSide.material.dispose()}createHalfFieldSide(e){const t=new kn(1,1),i=new Ye({color:e,transparent:!0,opacity:im,side:ct,depthWrite:!1,depthTest:!1}),s=new we(t,i);return s.renderOrder=18,{mesh:s,material:i}}}function u5(n,e){const t=new Mt,i=tc*2*e,s=(a,r,o)=>{const l=new kn(i,r*e),c=new Ye({color:KV,transparent:!0,opacity:o,side:ct,depthWrite:!1,depthTest:!1}),u=new we(l,c);return u.position.set(0,a,XV),u.renderOrder=24,u};for(const a of[-1,1]){const r=a*BV*e;t.add(s(r,YV,qV))}return t.add(s(0,ZV,jV)),n.add(t),t}function cn(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function __(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function Fi(n,e){return`
${n}${e}
`}function d5(n,e){return` + ${Fi("50s",cn(n?.count))} + ${Fi("Blue wins",`${cn(n?.wins)} (${__(n?.wins,n?.count)})`)} + ${Fi("Orange wins",`${cn(n?.losses)} (${__(n?.losses,n?.count)})`)} + ${Fi("Neutral",cn(n?.neutral_outcomes))} + ${Fi("Blue poss after",cn(n?.possession_after_count))} + ${Fi("Orange poss after",cn(n?.opponent_possession_after_count))} + ${Fi("Kickoff 50s",cn(n?.kickoff_count))} + ${Fi("Blue kickoff wins",cn(n?.kickoff_wins))} + ${Fi("Orange kickoff wins",cn(n?.kickoff_losses))} + ${Fi("Blue kickoff poss",cn(n?.kickoff_possession_after_count))} + ${Fi("Orange kickoff poss",cn(n?.kickoff_opponent_possession_after_count))} + `}function dx(n){return`
50s${cn(n?.count)}
-
Wins${cn(n?.wins)} (${c_(n?.wins,n?.count)})
+
Wins${cn(n?.wins)} (${__(n?.wins,n?.count)})
Losses${cn(n?.losses)}
Neutral${cn(n?.neutral_outcomes)}
Poss after${cn(n?.possession_after_count)}
Kickoff 50s${cn(n?.kickoff_count)}
Kickoff wins${cn(n?.kickoff_wins)}
Kickoff poss${cn(n?.kickoff_possession_after_count)}
- `}function OV(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function FV(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function sx(n,e,t=1){if(n===void 0||Number.isNaN(n))return"?";const i=FV(n,e,t);return i==="?"?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${i})`}function ax(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function u_(n,e){return`
${ax(n)}${ax(e)}
`}function NV(n){const e=new Set,t=[];for(const i of n??[])e.has(i)||(e.add(i),t.push(i));return t}function vE(n,e){return n==="neutral"?"Neutral":e.kind==="shared"?n==="own"?"Blue control":"Orange control":n==="own"?"Team control":"Opp control"}function d_(n){return n.kind==="shared"?["own","neutral","opponent"]:["own","neutral","opponent"]}function UV(n,e){return n==="neutral_third"?"Neutral third":e.kind==="shared"?n==="defensive_third"?"Blue third":"Orange third":n==="defensive_third"?"Own third":"Opp third"}function BV(n){return n.kind==="shared"?["defensive_third","neutral_third","offensive_third"]:["defensive_third","neutral_third","offensive_third"]}function zV(n,e){return n==="neutral"?"Neutral":e.kind==="shared"?n==="defensive_half"?"Blue half":"Orange half":n==="defensive_half"?"Own half":"Opp half"}function HV(n){return n.kind==="shared"?["defensive_half","neutral","offensive_half"]:["defensive_half","neutral","offensive_half"]}function VV(n,e,t,i){for(const s of t){const a=s==="possession_state"?d_(i):s==="field_third"?BV(i):HV(i),r=a.indexOf(n[s]),o=a.indexOf(e[s]),l=r===-1?Number.MAX_SAFE_INTEGER:r,c=o===-1?Number.MAX_SAFE_INTEGER:o;if(l!==c)return l-c}return 0}function GV(n,e,t){const i=(s,a)=>s==="possession_state"?vE(a,t):s==="field_third"?UV(a,t):zV(a,t);if(e.length===1){const s=e[0];return i(s,n[s])}return e.map(s=>i(s,n[s])).join(" / ")}function $V(n,e,t,i){if(e.length===0)return"";const s=new Map;if(n?.labeled_time?.entries?.length)for(const a of n.labeled_time.entries){const r=new Map(a.labels.map(d=>[d.key,d.value])),o={};let l=!0;for(const d of e){const h=r.get(d);if(h===void 0){l=!1;break}o[d]=h}if(!l)continue;const c=e.map(d=>`${d}:${o[d]}`).join("|"),u=s.get(c);u?u.total+=a.value:s.set(c,{values:o,total:a.value})}if(s.size===0&&e.length===1&&e[0]==="possession_state"){const a=new Map;return n&&(a.set("own",n.possession_time),a.set("neutral",n.neutral_time??0),a.set("opponent",n.opponent_possession_time)),d_(i).some(r=>(a.get(r)??0)>0)?d_(i).filter(r=>a.has(r)).map(r=>u_(vE(r,i),sx(a.get(r),t))).join(""):""}return[...s.values()].sort((a,r)=>VV(a.values,r.values,e,i)).map(a=>u_(GV(a.values,e,i),sx(a.total,t))).join("")}function rx(n,e){const t=n?.tracked_time,i=NV(e.breakdownClasses),s=$V(n,i,t,e.labelPerspective);return` - ${u_("Tracked",OV(t,1,"s"))} + `}function h5(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function f5(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function hx(n,e,t=1){if(n===void 0||Number.isNaN(n))return"?";const i=f5(n,e,t);return i==="?"?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${i})`}function fx(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function g_(n,e){return`
${fx(n)}${fx(e)}
`}function p5(n){const e=new Set,t=[];for(const i of n??[])e.has(i)||(e.add(i),t.push(i));return t}function RE(n,e){return n==="neutral"?"Neutral":e.kind==="shared"?n==="own"?"Blue control":"Orange control":n==="own"?"Team control":"Opp control"}function y_(n){return n.kind==="shared"?["own","neutral","opponent"]:["own","neutral","opponent"]}function m5(n,e){return n==="neutral_third"?"Neutral third":e.kind==="shared"?n==="defensive_third"?"Blue third":"Orange third":n==="defensive_third"?"Own third":"Opp third"}function _5(n){return n.kind==="shared"?["defensive_third","neutral_third","offensive_third"]:["defensive_third","neutral_third","offensive_third"]}function g5(n,e){return n==="neutral"?"Neutral":e.kind==="shared"?n==="defensive_half"?"Blue half":"Orange half":n==="defensive_half"?"Own half":"Opp half"}function y5(n){return n.kind==="shared"?["defensive_half","neutral","offensive_half"]:["defensive_half","neutral","offensive_half"]}function v5(n,e,t,i){for(const s of t){const a=s==="possession_state"?y_(i):s==="field_third"?_5(i):y5(i),r=a.indexOf(n[s]),o=a.indexOf(e[s]),l=r===-1?Number.MAX_SAFE_INTEGER:r,c=o===-1?Number.MAX_SAFE_INTEGER:o;if(l!==c)return l-c}return 0}function b5(n,e,t){const i=(s,a)=>s==="possession_state"?RE(a,t):s==="field_third"?m5(a,t):g5(a,t);if(e.length===1){const s=e[0];return i(s,n[s])}return e.map(s=>i(s,n[s])).join(" / ")}function x5(n,e,t,i){if(e.length===0)return"";const s=new Map;if(n?.labeled_time?.entries?.length)for(const a of n.labeled_time.entries){const r=new Map(a.labels.map(d=>[d.key,d.value])),o={};let l=!0;for(const d of e){const h=r.get(d);if(h===void 0){l=!1;break}o[d]=h}if(!l)continue;const c=e.map(d=>`${d}:${o[d]}`).join("|"),u=s.get(c);u?u.total+=a.value:s.set(c,{values:o,total:a.value})}if(s.size===0&&e.length===1&&e[0]==="possession_state"){const a=new Map;return n&&(a.set("own",n.possession_time),a.set("neutral",n.neutral_time??0),a.set("opponent",n.opponent_possession_time)),y_(i).some(r=>(a.get(r)??0)>0)?y_(i).filter(r=>a.has(r)).map(r=>g_(RE(r,i),hx(a.get(r),t))).join(""):""}return[...s.values()].sort((a,r)=>v5(a.values,r.values,e,i)).map(a=>g_(b5(a.values,e,i),hx(a.total,t))).join("")}function px(n,e){const t=n?.tracked_time,i=p5(e.breakdownClasses),s=x5(n,i,t,e.labelPerspective);return` + ${g_("Tracked",h5(t,1,"s"))} ${s} - `}function WV(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function XV(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function KV(n,e,t=1){if(n===void 0||Number.isNaN(n))return"?";const i=XV(n,e,t);return i==="?"?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${i})`}function ox(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function bE(n,e){return`
${ox(n)}${ox(e)}
`}function qV(n,e){return n==="neutral"?"Neutral zone":e.kind==="shared"?n==="defensive_half"?"Blue side":"Orange side":n==="defensive_half"?"Own half":"Opp half"}function YV(n,e,t){const i=new Map;if(n&&(i.set("defensive_half",n.defensive_half_time),i.set("neutral",n.neutral_time??0),i.set("offensive_half",n.offensive_half_time)),n?.labeled_time?.entries?.length){i.clear();for(const a of n.labeled_time.entries){const r=a.labels.find(o=>o.key==="field_half")?.value;r&&i.set(r,(i.get(r)??0)+a.value)}}const s=["defensive_half","neutral","offensive_half"];return s.some(a=>(i.get(a)??0)>0)?s.filter(a=>i.has(a)).map(a=>bE(qV(a,t),KV(i.get(a),e))).join(""):""}function lx(n,e){const t=n?.tracked_time,i=YV(n,t,e.labelPerspective);return` - ${i.length===0?bE("Tracked",WV(t,1,"s")):""} + `}function w5(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function S5(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function T5(n,e,t=1){if(n===void 0||Number.isNaN(n))return"?";const i=S5(n,e,t);return i==="?"?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${i})`}function mx(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function PE(n,e){return`
${mx(n)}${mx(e)}
`}function M5(n,e){return n==="neutral"?"Neutral zone":e.kind==="shared"?n==="defensive_half"?"Blue side":"Orange side":n==="defensive_half"?"Own half":"Opp half"}function E5(n,e,t){const i=new Map;if(n&&(i.set("defensive_half",n.defensive_half_time),i.set("neutral",n.neutral_time??0),i.set("offensive_half",n.offensive_half_time)),n?.labeled_time?.entries?.length){i.clear();for(const a of n.labeled_time.entries){const r=a.labels.find(o=>o.key==="field_half")?.value;r&&i.set(r,(i.get(r)??0)+a.value)}}const s=["defensive_half","neutral","offensive_half"];return s.some(a=>(i.get(a)??0)>0)?s.filter(a=>i.has(a)).map(a=>PE(M5(a,t),T5(i.get(a),e))).join(""):""}function _x(n,e){const t=n?.tracked_time,i=E5(n,t,e.labelPerspective);return` + ${i.length===0?PE("Tracked",w5(t,1,"s")):""} ${i} - `}function jV(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function ZV(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function JV(n,e,t=1){if(n===void 0||Number.isNaN(n))return"?";const i=ZV(n,e,t);return i==="?"?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${i})`}function cx(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function xE(n,e){return`
${cx(n)}${cx(e)}
`}function QV(n,e){return n==="neutral_third"?"Neutral third":e.kind==="shared"?n==="defensive_third"?"Blue third":"Orange third":n==="defensive_third"?"Own third":"Opp third"}function e5(n,e,t){const i=new Map;if(n&&(i.set("defensive_third",n.defensive_third_time),i.set("neutral_third",n.neutral_third_time??0),i.set("offensive_third",n.offensive_third_time)),n?.labeled_time?.entries?.length){i.clear();for(const a of n.labeled_time.entries){const r=a.labels.find(o=>o.key==="field_third")?.value;r&&i.set(r,(i.get(r)??0)+a.value)}}const s=["defensive_third","neutral_third","offensive_third"];return s.some(a=>(i.get(a)??0)>0)?s.filter(a=>i.has(a)).map(a=>xE(QV(a,t),JV(i.get(a),e))).join(""):""}function ux(n,e){const t=n?.tracked_time,i=e5(n,t,e.labelPerspective);return` - ${i.length===0?xE("Tracked",jV(t,1,"s")):""} + `}function C5(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function A5(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function R5(n,e,t=1){if(n===void 0||Number.isNaN(n))return"?";const i=A5(n,e,t);return i==="?"?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${i})`}function gx(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function IE(n,e){return`
${gx(n)}${gx(e)}
`}function P5(n,e){return n==="neutral_third"?"Neutral third":e.kind==="shared"?n==="defensive_third"?"Blue third":"Orange third":n==="defensive_third"?"Own third":"Opp third"}function I5(n,e,t){const i=new Map;if(n&&(i.set("defensive_third",n.defensive_third_time),i.set("neutral_third",n.neutral_third_time??0),i.set("offensive_third",n.offensive_third_time)),n?.labeled_time?.entries?.length){i.clear();for(const a of n.labeled_time.entries){const r=a.labels.find(o=>o.key==="field_third")?.value;r&&i.set(r,(i.get(r)??0)+a.value)}}const s=["defensive_third","neutral_third","offensive_third"];return s.some(a=>(i.get(a)??0)>0)?s.filter(a=>i.has(a)).map(a=>IE(P5(a,t),R5(i.get(a),e))).join(""):""}function yx(n,e){const t=n?.tracked_time,i=I5(n,t,e.labelPerspective);return` + ${i.length===0?IE("Tracked",C5(t,1,"s")):""} ${i} - `}function Fa(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function Na(n,e){return`
${n}${e}
`}function Jp(n){return` - ${Na("Rushes",Fa(n?.count))} - ${Na("2v1",Fa(n?.two_v_one_count))} - ${Na("2v2",Fa(n?.two_v_two_count))} - ${Na("2v3",Fa(n?.two_v_three_count))} - ${Na("3v1",Fa(n?.three_v_one_count))} - ${Na("3v2",Fa(n?.three_v_two_count))} - ${Na("3v3",Fa(n?.three_v_three_count))} - `}const dx="subtr-actor-fifty-fifty-overlay-styles",t5=5882879,n5=16761180,i5=15988472,s5=180,a5=4;function h_(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function hx(n,e){const t=h_(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function r5(n,e){const t=hx(e,n.team_zero_player),i=hx(e,n.team_one_player),s=n.is_kickoff?"Kickoff 50/50":"50/50",a=n.winning_team_is_team_0===void 0?null:n.winning_team_is_team_0,r=n.possession_team_is_team_0===void 0?null:n.possession_team_is_team_0,o=a===null?"neutral":a?"blue win":"orange win",l=r===null?"neutral poss":r?"blue poss":"orange poss",c=a===null?"sap-fifty-fifty-overlay-label-neutral":a?"sap-fifty-fifty-overlay-label-blue":"sap-fifty-fifty-overlay-label-orange";return{text:`${s}: ${t} vs ${i} | ${o} | ${l}`,className:c,winnerIsTeamZero:a}}function wE(n,e){return ve(n,"fifty_fifty").map(t=>{const i=r5(t,e),s=new S(...t.team_zero_position),a=new S(...t.team_one_position),r=new S(...t.midpoint),o=e.frames[t.start_frame]?.time??t.start_time;return{id:`fifty-fifty:${t.start_frame}:${h_(t.team_zero_player)}:${h_(t.team_one_player)}`,time:o,frame:t.start_frame,label:i.text,labelClassName:i.className,axisStart:s,axisEnd:a,midpoint:r,winnerIsTeamZero:i.winnerIsTeamZero}})}function o5(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function l5(){if(document.getElementById(dx))return;const n=document.createElement("style");n.id=dx,n.textContent=` + `}function Na(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function Ua(n,e){return`
${n}${e}
`}function am(n){return` + ${Ua("Rushes",Na(n?.count))} + ${Ua("2v1",Na(n?.two_v_one_count))} + ${Ua("2v2",Na(n?.two_v_two_count))} + ${Ua("2v3",Na(n?.two_v_three_count))} + ${Ua("3v1",Na(n?.three_v_one_count))} + ${Ua("3v2",Na(n?.three_v_two_count))} + ${Ua("3v3",Na(n?.three_v_three_count))} + `}const vx="subtr-actor-fifty-fifty-overlay-styles",L5=5882879,k5=16761180,D5=15988472,O5=180,F5=4;function v_(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function bx(n,e){const t=v_(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function N5(n,e){const t=bx(e,n.team_zero_player),i=bx(e,n.team_one_player),s=n.is_kickoff?"Kickoff 50/50":"50/50",a=n.winning_team_is_team_0===void 0?null:n.winning_team_is_team_0,r=n.possession_team_is_team_0===void 0?null:n.possession_team_is_team_0,o=a===null?"neutral":a?"blue win":"orange win",l=r===null?"neutral poss":r?"blue poss":"orange poss",c=a===null?"sap-fifty-fifty-overlay-label-neutral":a?"sap-fifty-fifty-overlay-label-blue":"sap-fifty-fifty-overlay-label-orange";return{text:`${s}: ${t} vs ${i} | ${o} | ${l}`,className:c,winnerIsTeamZero:a}}function LE(n,e){return ve(n,"fifty_fifty").map(t=>{const i=N5(t,e),s=new S(...t.team_zero_position),a=new S(...t.team_one_position),r=new S(...t.midpoint),o=e.frames[t.start_frame]?.time??t.start_time;return{id:`fifty-fifty:${t.start_frame}:${v_(t.team_zero_player)}:${v_(t.team_one_player)}`,time:o,frame:t.start_frame,label:i.text,labelClassName:i.className,axisStart:s,axisEnd:a,midpoint:r,winnerIsTeamZero:i.winnerIsTeamZero}})}function U5(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function B5(){if(document.getElementById(vx))return;const n=document.createElement("style");n.id=vx,n.textContent=` .sap-fifty-fifty-overlay-root { position: absolute; inset: 0; @@ -5584,7 +5649,7 @@ void main() { border-color: rgba(243, 246, 248, 0.4); background: rgba(34, 41, 47, 0.86); } - `,document.head.append(n)}function c5(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class u5{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;labelOffset=new S(0,0,s5);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=a5;constructor(e,t,i,s){l5(),this.scene=e,this.container=t,this.markers=wE(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="fifty-fifty-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-fifty-fifty-overlay-root",this.container.append(this.labelRoot)}update(e){const t=o5(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.line.removeFromParent(),a.line.geometry.dispose(),a.material.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.12+.78*r;o.material.opacity=l;const c=o.line.geometry.getAttribute("position");c.setXYZ(0,s.axisStart.x,s.axisStart.y,s.axisStart.z+24),c.setXYZ(1,s.axisEnd.x,s.axisEnd.y,s.axisEnd.z+24),c.needsUpdate=!0,this.worldPosition.copy(s.midpoint).add(this.labelOffset),this.scene.replayRoot.localToWorld(this.worldPosition),c5(this.worldPosition,this.scene.camera,this.container,this.projectedPosition)?(o.label.hidden=!1,o.label.style.opacity=`${.24+.76*r}`,o.label.style.transform=`translate(${this.projectedPosition.x.toFixed(1)}px, ${this.projectedPosition.y.toFixed(1)}px) translate(-50%, -100%)`):o.label.hidden=!0}}dispose(){for(const e of this.views.values())e.line.removeFromParent(),e.line.geometry.dispose(),e.material.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition,this.changedContainerPosition=!1)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=new Ge().setFromPoints([e.axisStart,e.axisEnd]),s=new Rt({color:e.winnerIsTeamZero===null?i5:e.winnerIsTeamZero?t5:n5,transparent:!0,opacity:.9}),a=new In(i,s);a.renderOrder=3,this.group.add(a);const r=document.createElement("div");r.className=`sap-fifty-fifty-overlay-label ${e.labelClassName}`,r.textContent=e.label,this.labelRoot.append(r);const o={marker:e,line:a,material:s,label:r};return this.views.set(e.id,o),o}}const fx="subtr-actor-ceiling-shot-overlay-styles",d5=5882879,h5=16761180,f5=16185075,p5=140,m5=215,_5=220,g5=4.5;function SE(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function y5(n,e){const t=SE(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function TE(n,e){return ve(n,"ceiling_shot").map(t=>{const i=y5(e,t.player),s=SE(t.player),a=e.frames[t.frame]?.time??t.time,r=t.confidence;return{id:`ceiling-shot:${t.frame}:${s}:${Math.round(r*1e3)}`,time:a,frame:t.frame,isTeamZero:t.is_team_0,playerId:s,playerName:i,ceilingContactPosition:{x:t.ceiling_contact_position[0],y:t.ceiling_contact_position[1],z:t.ceiling_contact_position[2]},touchPosition:{x:t.touch_position[0],y:t.touch_position[1],z:t.touch_position[2]},quality:r,qualityLabel:`${Math.round(r*100)}%`}})}function v5(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function b5(){if(document.getElementById(fx))return;const n=document.createElement("style");n.id=fx,n.textContent=` + `,document.head.append(n)}function z5(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class H5{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;labelOffset=new S(0,0,O5);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=F5;constructor(e,t,i,s){B5(),this.scene=e,this.container=t,this.markers=LE(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="fifty-fifty-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-fifty-fifty-overlay-root",this.container.append(this.labelRoot)}update(e){const t=U5(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.line.removeFromParent(),a.line.geometry.dispose(),a.material.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.12+.78*r;o.material.opacity=l;const c=o.line.geometry.getAttribute("position");c.setXYZ(0,s.axisStart.x,s.axisStart.y,s.axisStart.z+24),c.setXYZ(1,s.axisEnd.x,s.axisEnd.y,s.axisEnd.z+24),c.needsUpdate=!0,this.worldPosition.copy(s.midpoint).add(this.labelOffset),this.scene.replayRoot.localToWorld(this.worldPosition),z5(this.worldPosition,this.scene.camera,this.container,this.projectedPosition)?(o.label.hidden=!1,o.label.style.opacity=`${.24+.76*r}`,o.label.style.transform=`translate(${this.projectedPosition.x.toFixed(1)}px, ${this.projectedPosition.y.toFixed(1)}px) translate(-50%, -100%)`):o.label.hidden=!0}}dispose(){for(const e of this.views.values())e.line.removeFromParent(),e.line.geometry.dispose(),e.material.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition,this.changedContainerPosition=!1)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=new Ge().setFromPoints([e.axisStart,e.axisEnd]),s=new Rt({color:e.winnerIsTeamZero===null?D5:e.winnerIsTeamZero?L5:k5,transparent:!0,opacity:.9}),a=new In(i,s);a.renderOrder=3,this.group.add(a);const r=document.createElement("div");r.className=`sap-fifty-fifty-overlay-label ${e.labelClassName}`,r.textContent=e.label,this.labelRoot.append(r);const o={marker:e,line:a,material:s,label:r};return this.views.set(e.id,o),o}}const xx="subtr-actor-ceiling-shot-overlay-styles",V5=5882879,G5=16761180,$5=16185075,W5=140,X5=215,K5=220,q5=4.5;function kE(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function Y5(n,e){const t=kE(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function DE(n,e){return ve(n,"ceiling_shot").map(t=>{const i=Y5(e,t.player),s=kE(t.player),a=e.frames[t.frame]?.time??t.time,r=t.confidence;return{id:`ceiling-shot:${t.frame}:${s}:${Math.round(r*1e3)}`,time:a,frame:t.frame,isTeamZero:t.is_team_0,playerId:s,playerName:i,ceilingContactPosition:{x:t.ceiling_contact_position[0],y:t.ceiling_contact_position[1],z:t.ceiling_contact_position[2]},touchPosition:{x:t.touch_position[0],y:t.touch_position[1],z:t.touch_position[2]},quality:r,qualityLabel:`${Math.round(r*100)}%`}})}function j5(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function Z5(){if(document.getElementById(xx))return;const n=document.createElement("style");n.id=xx,n.textContent=` .sap-ceiling-shot-overlay-root { position: absolute; inset: 0; @@ -5621,13 +5686,13 @@ void main() { border-color: rgba(255, 193, 92, 0.5); background: rgba(76, 41, 7, 0.84); } - `,document.head.append(n)}function x5(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class w5{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;labelOffset=new S(0,0,_5);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=g5;constructor(e,t,i,s){b5(),this.scene=e,this.container=t,this.markers=TE(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="ceiling-shot-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-ceiling-shot-overlay-root",this.container.append(this.labelRoot)}update(e){const t=v5(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.ring.removeFromParent(),a.ring.geometry.dispose(),a.ringMaterial.dispose(),a.beam.removeFromParent(),a.beamGeometry.dispose(),a.beamMaterial.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.14+.6*r,c=.94+(1-r)*.18;o.ringMaterial.opacity=l,o.beamMaterial.opacity=.18+.55*r,o.ring.position.set(s.touchPosition.x,s.touchPosition.y,s.touchPosition.z+12),o.ring.scale.setScalar(c+s.quality*.08),this.worldPosition.set(s.touchPosition.x,s.touchPosition.y,s.touchPosition.z).add(this.labelOffset);const u=x5(this.worldPosition,this.scene.camera,this.container,this.projectedPosition);o.label.style.display=u?"block":"none",u&&(o.label.style.left=`${this.projectedPosition.x}px`,o.label.style.top=`${this.projectedPosition.y}px`,o.label.style.opacity=`${.42+.58*r}`)}}dispose(){for(const e of this.views.values())e.ring.removeFromParent(),e.ring.geometry.dispose(),e.ringMaterial.dispose(),e.beam.removeFromParent(),e.beamGeometry.dispose(),e.beamMaterial.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=e.quality>=.8?f5:e.isTeamZero?d5:h5,s=new Ye({color:i,transparent:!0,opacity:.8,side:ct,depthWrite:!1,depthTest:!1}),a=new ni(p5,m5,48),r=new we(a,s);r.renderOrder=30,this.group.add(r);const o=new Ge().setFromPoints([new S(e.ceilingContactPosition.x,e.ceilingContactPosition.y,e.ceilingContactPosition.z),new S(e.touchPosition.x,e.touchPosition.y,e.touchPosition.z)]),l=new Rt({color:i,transparent:!0,opacity:.7,depthWrite:!1,depthTest:!1}),c=new In(o,l);c.renderOrder=29,this.group.add(c);const u=document.createElement("div");u.className=`sap-ceiling-shot-overlay-label ${e.isTeamZero?"sap-ceiling-shot-overlay-label-blue":"sap-ceiling-shot-overlay-label-orange"}`,u.textContent=`${e.playerName} ceiling shot ${e.qualityLabel}`,this.labelRoot.append(u);const d={marker:e,ring:r,ringMaterial:s,beam:c,beamGeometry:o,beamMaterial:l,label:u};return this.views.set(e.id,d),d}}const S5="#d1d9e0",ME=new Set(["flick_goal","double_tap_goal","one_timer_goal","passing_goal","air_dribble_goal","flip_reset_goal","bump_goal","demo_goal","half_volley_goal"]);function T5(n){return n.metadata.performer==="scorer"||n.metadata.modifiers?.includes("by_scorer")?"scorer":n.metadata.performer==="teammate"?"teammate":ME.has(n.kind)?"unknown":"scorer"}function M5(n){const e=T5(n);return e==="unknown"?"performer unknown":ME.has(n.kind)?`by ${e}`:null}function ji(n,e){return n.players.find(t=>t.id===e)?.name??e}function kn(n,e,t){return n.frames[e??-1]?.time??t}function E5(n){const e=n.kind;return e!=="forward"&&e!=="reverse"&&e!=="side"?"flick":`${n.direction==="left"||n.direction==="right"?`${n.direction} `:""}${e} flick`}function C5(n){const e=new Set(n),t=new Set(["goal"]);return e.has("core")&&(t.add("save"),t.add("shot"),t.add("assist")),e.has("demo")&&t.add("demo"),[...t]}function A5(n,e){const t=new Set(C5(e));return n.timelineEvents.filter(i=>t.has(i.kind))}function R5(n,e){return wE(n,e).map(t=>({id:t.id,time:t.time,frame:t.frame,kind:"fifty-fifty",label:t.label,shortLabel:t.label.startsWith("Kickoff 50/50")?"KO":"50",isTeamZero:t.winnerIsTeamZero,color:t.winnerIsTeamZero===null?S5:t.winnerIsTeamZero?en:tn}))}function P5(n,e){return(ve(n,"flick")??[]).map((t,i)=>{const s=At(t.player),a=ji(e,s),r=E5(t);return{id:`flick:${t.frame}:${s}:${i+1}`,time:kn(e,t.frame,t.time),frame:t.frame,kind:"flick",label:`${a} ${r}`,shortLabel:"F",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function I5(n,e){return _E(n,e).map(t=>({id:t.id,time:t.time,frame:t.frame,kind:"touch",label:`${t.playerName} touch`,shortLabel:"T",playerId:t.playerId,playerName:t.playerName,isTeamZero:t.isTeamZero,color:t.isTeamZero?en:tn}))}function L5(n,e){return ve(n,"backboard").map((t,i)=>{const s=At(t.player),a=e.players.find(r=>r.id===s)?.name??s;return{id:`backboard:${t.frame}:${s}:${i}`,time:kn(e,t.frame,t.time),frame:t.frame,kind:"backboard",label:`${a} backboard`,shortLabel:"BB",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function D5(n,e){return TE(n,e).map(t=>({id:t.id,time:t.time,frame:t.frame,kind:"ceiling-shot",label:`${t.playerName} ceiling shot ${t.qualityLabel}`,shortLabel:"CS",playerId:t.playerId,playerName:t.playerName,isTeamZero:t.isTeamZero,color:t.isTeamZero?en:tn}))}function k5(n,e){return ve(n,"wall_aerial").map((t,i)=>{const s=At(t.player),a=ji(e,s),r=kn(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Ci(t.wall).toLowerCase();return{id:`wall-aerial:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"wall-aerial",label:`${a} wall-to-air setup ${o}% | ${l} wall`,shortLabel:"W2A",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function O5(n,e){return ve(n,"wall_aerial_shot").map((t,i)=>{const s=At(t.player),a=ji(e,s),r=kn(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Ci(t.wall).toLowerCase();return{id:`wall-aerial-shot:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"wall-aerial-shot",label:`${a} wall shot ${o}% | ${l} wall`,shortLabel:"WS",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function F5(n,e){return ve(n,"double_tap").map((t,i)=>{const s=At(t.player),a=ji(e,s);return{id:`double-tap:${t.frame}:${s}:${i}`,time:kn(e,t.frame,t.time),frame:t.frame,kind:"double-tap",label:`${a} double tap`,shortLabel:"DT",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function N5(n,e){return ve(n,"center").map((t,i)=>{const s=At(t.player),a=ji(e,s),r=kn(e,t.frame,t.time),o=Math.round(t.lateral_centering_distance);return{id:`center:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"center",label:`${a} center | ${o}uu lateral`,shortLabel:"C",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function U5(n,e){return ve(n,"one_timer").map((t,i)=>{const s=At(t.player),a=At(t.passer),r=ji(e,s),o=ji(e,a),l=kn(e,t.frame,t.time),c=Math.round(t.ball_speed);return{id:`one-timer:${t.frame}:${a}:${s}:${i}`,time:l,frame:t.frame,kind:"one-timer",label:`${r} one-timer from ${o} | ${c}uu/s`,shortLabel:"OT",playerId:s,playerName:r,secondaryPlayerId:a,secondaryPlayerName:o,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function B5(n){return Ci(n.replace(/_pass$/,""))}function z5(n,e){return ve(n,"pass").map((t,i)=>{const s=At(t.passer),a=At(t.receiver),r=ji(e,s),o=ji(e,a),l=kn(e,t.frame,t.time),c=Math.round(t.ball_travel_distance),u=B5(t.pass_kind);return{id:`pass:${t.frame}:${s}:${a}:${i}`,time:l,frame:t.frame,kind:"pass",label:`${r} to ${o} ${u.toLowerCase()} pass | ${c}uu`,shortLabel:"P",playerId:s,playerName:r,secondaryPlayerId:a,secondaryPlayerName:o,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function H5(n,e){return ve(n,"half_volley").map((t,i)=>{const s=At(t.player),a=ji(e,s),r=kn(e,t.frame,t.time),o=Math.round(t.ball_speed);return{id:`half-volley:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"half-volley",label:`${a} half volley | ${o}uu/s`,shortLabel:"HV",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function V5(n,e){return ve(n,"rush").map((t,i)=>{const s=kn(e,t.end_frame,t.end_time),a=`${t.attackers}v${t.defenders}`,r=t.is_team_0?"Blue":"Orange";return{id:`rush:${t.start_frame}:${t.end_frame}:${i}`,time:s,frame:t.end_frame,kind:"rush",label:`${r} rush ${a}`,shortLabel:"R",playerId:null,playerName:null,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function G5(n,e){return(ve(n,"powerslide")??[]).filter(t=>t.active).map((t,i)=>{const s=At(t.player),a=ji(e,s);return{id:`powerslide:${t.frame}:${s}:${i+1}`,time:kn(e,t.frame,t.time),frame:t.frame,kind:"powerslide",label:`${a} powerslide`,shortLabel:"PS",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function $5(n,e){return ve(n,"speed_flip").map(t=>{const i=t.player?At(t.player):null,s=i?e.players.find(o=>o.id===i)?.name??i:"Unknown",a=e.frames[t.frame]?.time??t.time,r=Math.round(t.confidence*100);return{id:`speed-flip:${t.frame}:${i}:${Math.round(t.confidence*1e3)}`,time:a,frame:t.frame,kind:"speed-flip",label:`${s} speed flip ${r}%`,shortLabel:"SF",playerId:i,playerName:s,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function W5(n,e){return(ve(n,"dodge")??[]).map((t,i)=>{const s=At(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=kn(e,t.frame,t.time),o=Math.round((t.dodge_impulse?.confidence??1)*100),l=(t.dodge_impulse?.direction_label??"dodge").replaceAll("_"," ");return{id:`dodge:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"dodge",label:`${a} flip impulse ${l} ${o}%`,shortLabel:"FI",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function X5(n,e){return ve(n,"half_flip").map((t,i)=>{const s=At(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=kn(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Math.round(t.end_speed-t.start_speed);return{id:`half-flip:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"half-flip",label:`${a} half flip ${o}% | +${l}uu/s`,shortLabel:"HF",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function K5(n,e){return ve(n,"wavedash").map((t,i)=>{const s=At(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=kn(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Math.round(t.horizontal_speed_gain);return{id:`wavedash:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"wavedash",label:`${a} wavedash ${o}% | +${l}uu/s`,shortLabel:"WD",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function q5(n,e){return ve(n,"bump").map((t,i)=>{const s=At(t.initiator),a=At(t.victim),r=e.players.find(u=>u.id===s)?.name??s,o=e.players.find(u=>u.id===a)?.name??a,l=kn(e,t.frame,t.time),c=Math.round(t.confidence*100);return{id:`bump:${t.frame}:${s}:${a}:${i}`,time:l,frame:t.frame,kind:"bump",label:`${r} bumped ${o} ${c}%`,shortLabel:"B",playerId:s,playerName:r,isTeamZero:t.initiator_is_team_0,color:t.initiator_is_team_0?en:tn}})}function Y5(n){return n.kind==="beaten_to_ball"?"BT":n.dodge_active?"DW":n.aerial?"AW":"W"}function j5(n){const e=[n.aerial?"aerial":"grounded"];return n.dodge_active&&e.push("dodge"),e.join(" ")}function Z5(n){return n.kind==="beaten_to_ball"?"beaten to ball":"whiff"}function J5(n,e){return ve(n,"whiff").map((t,i)=>{const s=At(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=kn(e,t.frame,t.time),o=Math.round(t.closest_approach_distance),l=Math.round(t.approach_speed);return{id:`whiff:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"whiff",label:`${a} ${j5(t)} ${Z5(t)} | ${o}uu closest, ${l}uu/s`,shortLabel:Y5(t),playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}const EE={flick:P5,ceiling_shot:D5,wall_aerial:k5,wall_aerial_shot:O5,double_tap:F5,center:N5,one_timer:U5,pass:z5,half_flip:X5,half_volley:H5,speed_flip:$5},CE=Object.keys(EE),AE=.02,ei=1e-4,Q5=200,RE=.08,f_={big:"rgba(245, 158, 11, 0.92)",small:"rgba(52, 211, 153, 0.86)"},px={both:"rgba(52, 211, 153, 0.86)",inferred_only:"rgba(239, 68, 68, 0.9)",reported_only:"rgba(59, 130, 246, 0.9)"};function e4(n){const e=n.config?.ball_half_neutral_zone_half_width_y;return typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):Q5}function nh(n,e,t){return n?.frames?.[e??-1]?.time??t}function t4(n,e,t,i,s,a){const r=e?.ballFrames[n]?.position?.y;return typeof r=="number"&&Number.isFinite(r)&&Math.abs(r)<=t+ei||a>ei?"neutral":i>s+ei?"team_zero_side":s>i+ei?"team_one_side":null}function PE(n,e,t){if(n==="neutral")return{id:`half-control:neutral:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"half-control",laneLabel:"Half Control",label:"Neutral half control",color:"rgba(209, 217, 224, 0.7)",isTeamZero:null};const i=n==="team_zero_side";return{id:`half-control:${n}:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"half-control",laneLabel:"Half Control",label:i?"Blue half control":"Orange half control",color:ef(i)??void 0,isTeamZero:i}}function nf(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function n4(n,e){const t=nf(ve(n,"possession")),i=[];let s=0,a=!1,r="neutral",o=null;for(const l of n.frames){for(;s0)return n4(n,e);const t=[];let i=0,s=0,a=0,r=null;for(const o of n.frames){if(!Number.isFinite(o.time)||!Number.isFinite(o.dt)||o.dt<=0){r=o;continue}const l=o,c=l.team_zero?.possession?.possession_time??0,u=l.team_one?.possession?.possession_time??0,d=l.team_zero?.possession?.neutral_time??0,h=c-i,f=u-s,p=d-a;i=c,s=u,a=d;let g=null;const{startTime:_,endTime:m}=_r(o,r,e);h>f+ei&&h>p+ei?g={id:`possession:team_zero:${_.toFixed(3)}`,startTime:_,endTime:m,lane:"possession",laneLabel:"Possession",label:"Blue possession",color:"rgba(59, 130, 246, 0.88)",isTeamZero:!0}:f>h+ei&&f>p+ei&&(g={id:`possession:team_one:${_.toFixed(3)}`,startTime:_,endTime:m,lane:"possession",laneLabel:"Possession",label:"Orange possession",color:"rgba(245, 158, 11, 0.88)",isTeamZero:!1}),Fo(t,g),r=o}return t}function s4(n,e){const t=nf(ve(n,"ball_half")),i=[];let s=0,a=!1,r="neutral",o=null;for(const l of n.frames){for(;s0)return s4(n,e);const t=[];let i=0,s=0,a=0;const r=e4(n);let o=null;for(const l of n.frames){if(!Number.isFinite(l.time)||!Number.isFinite(l.dt)||l.dt<=0){o=l;continue}const c=l,u=c.team_zero?.ball_half?.defensive_half_time??0,d=c.team_one?.ball_half?.defensive_half_time??0,h=c.team_zero?.ball_half?.neutral_time??0,f=u-i,p=d-s,g=h-a;i=u,s=d,a=h;const{startTime:_,endTime:m}=_r(l,o,e),v=t4(l.frame_number,e,r,f,p,g),y=v?PE(v,_,m):null;Fo(t,y),o=l}return t}function r4(n,e,t){return t>ei?"neutral_third":n>e+ei?"team_zero_third":e>n+ei?"team_one_third":null}function IE(n,e,t){if(n==="neutral_third")return{id:`third-control:neutral_third:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"third-control",laneLabel:"Third Control",label:"Neutral third control",color:"rgba(209, 217, 224, 0.7)",isTeamZero:null};const i=n==="team_zero_third";return{id:`third-control:${n}:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"third-control",laneLabel:"Third Control",label:i?"Blue third control":"Orange third control",color:ef(i)??void 0,isTeamZero:i}}function o4(n,e){const t=nf(ve(n,"ball_third")),i=[];let s=0,a=!1,r="neutral_third",o=null;for(const l of n.frames){for(;s0)return o4(n,e);const t=[];let i=0,s=0,a=0,r=null;for(const o of n.frames){if(!Number.isFinite(o.time)||!Number.isFinite(o.dt)||o.dt<=0){r=o;continue}const l=o,c=l.team_zero?.ball_third?.defensive_third_time??0,u=l.team_one?.ball_third?.defensive_third_time??0,d=l.team_zero?.ball_third?.neutral_third_time??0,h=c-i,f=u-s,p=d-a;i=c,s=u,a=d;const{startTime:g,endTime:_}=_r(o,r,e),m=r4(h,f,p),v=m?IE(m,g,_):null;Fo(t,v),r=o}return t}function c4(n,e){return ve(n,"fifty_fifty").map((t,i)=>{const s=nh(e,t.start_frame,t.start_time),a=Math.max(s,nh(e,t.resolve_frame,t.resolve_time)),r=t.winning_team_is_team_0==null?"Neutral":t.winning_team_is_team_0?"Blue win":"Orange win",o=t.is_kickoff?"kickoff ":"";return{id:`fifty-fifty:${t.start_frame}:${t.resolve_frame}:${i}`,startTime:s,endTime:a,lane:"fifty-fifty",laneLabel:"50/50",label:`${r} ${o}50/50`,shortLabel:t.is_kickoff?"KO":"50",color:t.winning_team_is_team_0==null?"rgba(209, 217, 224, 0.7)":t.winning_team_is_team_0?"rgba(59, 130, 246, 0.48)":"rgba(245, 158, 11, 0.48)",isTeamZero:t.winning_team_is_team_0}}).sort((t,i)=>t.startTime!==i.startTime?t.startTime-i.startTime:(t.id??"").localeCompare(i.id??""))}function u4(n,e){return ve(n,"rush").map((t,i)=>{const s=e?.frames[t.start_frame]?.time??t.start_time,a=e?.frames[t.end_frame]?.time??t.end_time,r=`${t.attackers}v${t.defenders}`,o=t.is_team_0;return{id:`rush-range:${t.start_frame}:${t.end_frame}:${i}`,startTime:s,endTime:Math.max(s,a),lane:"rush",laneLabel:"Rush",label:`${o?"Blue":"Orange"} rush ${r}`,color:o?"rgba(59, 130, 246, 0.4)":"rgba(245, 158, 11, 0.4)",isTeamZero:o}})}function d4(n,e={}){const t=LE(e),i=new Set(e.detections??["both","inferred_only","reported_only"]),s=new Set(e.activities??["active","inactive","unknown"]),a=new Set(e.fieldHalves??["own","opponent","unknown"]),r=e.playerIds?new Set(e.playerIds):null;if(t.size===0||i.size===0||!s.has("unknown")||!a.has("unknown")||r?.size===0)return[];const o=new Map(n.players.map(c=>[c.id,c.isTeamZero])),l=[];for(const c of n.boostPads)if(t.has(c.size))for(let u=0;uc.startTime!==u.startTime?c.startTime-u.startTime:(c.id??"").localeCompare(u.id??""))}function LE(n){if(n.padTypes)return new Set(n.padTypes);if(n.sizes){const e=new Set(n.sizes),t=new Set;return e.has("big")&&t.add("big"),e.has("small")&&t.add("small"),e.has("big")&&e.has("small")&&t.add("ambiguous"),t}return new Set(["big","small","ambiguous"])}function mx(n){const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function h4(n){return{big:"big",small:"small",ambiguous:"ambiguous"}[n]}function f4(n){return{both:"counted",inferred_only:"inferred",reported_only:"reported"}[n]}function p4(n,e){return n==="inferred_only"?"I":n==="reported_only"?"R":{big:"100",small:"12",ambiguous:"?"}[e]}function m4(n,e,t={}){const i=ve(n,"boost_pickup");if(i.length===0&&e)return d4(e,t);const s=LE(t),a=new Set(t.detections??["both","inferred_only","reported_only"]),r=new Set(t.activities??["active","inactive","unknown"]),o=new Set(t.fieldHalves??["own","opponent","unknown"]),l=t.playerIds?new Set(t.playerIds):null;if(s.size===0||a.size===0||r.size===0||o.size===0||l?.size===0)return[];const c=new Map((e?.players??[]).map(u=>[u.id,u.name]));return i.filter(u=>{const d=mx(u.player_id);return s.has(u.pad_type)&&a.has(u.detection)&&r.has(u.activity)&&o.has(u.field_half)&&(!l||l.has(d))}).map((u,d)=>{const h=mx(u.player_id),f=c.get(h)??h,p=Math.max(0,nh(e,u.frame,u.time)),g=f4(u.detection),_=h4(u.pad_type);return{id:`boost-pickup:${u.detection}:${u.frame}:${h}:${d}`,startTime:p,endTime:Math.max(p+RE,p),lane:"boost-pickups",laneLabel:"Boost Pickups",label:`${f} ${g} ${_} boost pickup`,shortLabel:p4(u.detection,u.pad_type),color:ef(u.is_team_0)??(u.detection==="both"?u.pad_type==="big"?f_.big:u.pad_type==="small"?f_.small:px.both:px[u.detection]),isTeamZero:u.is_team_0}}).sort((u,d)=>u.startTime!==d.startTime?u.startTime-d.startTime:(u.id??"").localeCompare(d.id??""))}const id=[{fieldName:"time_defensive_third",aliases:["time_defensive_zone"],label:"Def third",relativeColor:"own"},{fieldName:"time_neutral_third",aliases:["time_neutral_zone"],label:"Neutral third",relativeColor:"neutral"},{fieldName:"time_offensive_third",aliases:["time_offensive_zone"],label:"Off third",relativeColor:"opp"}];function DE(n,e){return n.relativeColor==="neutral"?"rgba(209, 217, 224, 0.68)":(n.relativeColor==="own"?e:!e)?"rgba(89, 195, 255, 0.74)":"rgba(255, 193, 92, 0.78)"}function Vg(n){const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function _4(n,e){const t=n.positioning;if(!t)return 0;for(const i of[e.fieldName,...e.aliases??[]]){const s=t[i];if(typeof s=="number"&&Number.isFinite(s))return s}return 0}function g4(n){switch(n){case"defensive":return id[0];case"neutral":return id[1];case"offensive":return id[2]}}function y4(n){const e=new Map;for(const t of n.frames)for(const i of t.players){const s=Vg(i.player_id);e.has(s)||e.set(s,i.name)}return e}function v4(n){const e=nf(ve(n,"field_third")),t=[],i=new Map,s=y4(n);for(const a of e){if(!Number.isFinite(a.time)||!Number.isFinite(a.end_time)||a.end_time-a.time<=ei)continue;const r=Vg(a.player),o=g4(a.state);kE(t,i,{id:`time-in-zone:${r}:${o.fieldName}:${a.time.toFixed(3)}`,startTime:a.time,endTime:a.end_time,lane:`time-in-zone:${r}`,laneLabel:s.get(r)??r,label:o.label,color:DE(o,a.is_team_0),isTeamZero:a.is_team_0})}return t}function b4(n,e){if(ve(n,"field_third").length>0)return v4(n);const t=new Map,i=[],s=new Map;let a=null;for(const r of n.frames){if(!Number.isFinite(r.time)||!Number.isFinite(r.dt)||r.dt<=0){a=r;continue}const{startTime:o,endTime:l}=_r(r,a,e);if(l-o<=ei){a=r;continue}for(const c of r.players){const u=Vg(c.player_id),d=t.get(u)??new Map;let h=null,f=0;for(const p of id){const g=_4(c,p),_=g-(d.get(p.fieldName)??0);_>f+ei&&(f=_,h=p),d.set(p.fieldName,g)}t.set(u,d),h&&kE(i,s,{id:`time-in-zone:${u}:${h.fieldName}:${o.toFixed(3)}`,startTime:o,endTime:l,lane:`time-in-zone:${u}`,laneLabel:c.name,label:h.label,color:DE(h,c.is_team_0),isTeamZero:c.is_team_0})}a=r}return i}function _r(n,e,t){const i=t?.frames[n.frame_number]?.time??n.time,s=e?t?.frames[e.frame_number]?.time??e.time:Math.max(0,i-n.dt);return{startTime:Math.max(0,s),endTime:Math.max(s,i)}}function Fo(n,e){if(!e)return;const t=n[n.length-1];if(t&&t.lane===e.lane&&t.label===e.label&&Math.abs(t.endTime-e.startTime)<=AE){t.endTime=e.endTime;return}n.push(e)}function kE(n,e,t){if(!t)return;const i=t.lane??"",s=e.get(i);if(s&&s.label===t.label&&Math.abs(s.endTime-t.startTime)<=AE){s.endTime=t.endTime;return}n.push(t),e.set(i,t)}const Qp=236,OE="relative-positioning",x4={last:"Last",upfield:"Upfield",level:"Level",mid:"Mid"};function ta(n){return n?"team-blue":"team-orange"}function FE(n,e,t){return`
+ `,document.head.append(n)}function J5(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class Q5{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;labelOffset=new S(0,0,K5);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=q5;constructor(e,t,i,s){Z5(),this.scene=e,this.container=t,this.markers=DE(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="ceiling-shot-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-ceiling-shot-overlay-root",this.container.append(this.labelRoot)}update(e){const t=j5(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.ring.removeFromParent(),a.ring.geometry.dispose(),a.ringMaterial.dispose(),a.beam.removeFromParent(),a.beamGeometry.dispose(),a.beamMaterial.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.14+.6*r,c=.94+(1-r)*.18;o.ringMaterial.opacity=l,o.beamMaterial.opacity=.18+.55*r,o.ring.position.set(s.touchPosition.x,s.touchPosition.y,s.touchPosition.z+12),o.ring.scale.setScalar(c+s.quality*.08),this.worldPosition.set(s.touchPosition.x,s.touchPosition.y,s.touchPosition.z).add(this.labelOffset);const u=J5(this.worldPosition,this.scene.camera,this.container,this.projectedPosition);o.label.style.display=u?"block":"none",u&&(o.label.style.left=`${this.projectedPosition.x}px`,o.label.style.top=`${this.projectedPosition.y}px`,o.label.style.opacity=`${.42+.58*r}`)}}dispose(){for(const e of this.views.values())e.ring.removeFromParent(),e.ring.geometry.dispose(),e.ringMaterial.dispose(),e.beam.removeFromParent(),e.beamGeometry.dispose(),e.beamMaterial.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=e.quality>=.8?$5:e.isTeamZero?V5:G5,s=new Ye({color:i,transparent:!0,opacity:.8,side:ct,depthWrite:!1,depthTest:!1}),a=new ni(W5,X5,48),r=new we(a,s);r.renderOrder=30,this.group.add(r);const o=new Ge().setFromPoints([new S(e.ceilingContactPosition.x,e.ceilingContactPosition.y,e.ceilingContactPosition.z),new S(e.touchPosition.x,e.touchPosition.y,e.touchPosition.z)]),l=new Rt({color:i,transparent:!0,opacity:.7,depthWrite:!1,depthTest:!1}),c=new In(o,l);c.renderOrder=29,this.group.add(c);const u=document.createElement("div");u.className=`sap-ceiling-shot-overlay-label ${e.isTeamZero?"sap-ceiling-shot-overlay-label-blue":"sap-ceiling-shot-overlay-label-orange"}`,u.textContent=`${e.playerName} ceiling shot ${e.qualityLabel}`,this.labelRoot.append(u);const d={marker:e,ring:r,ringMaterial:s,beam:c,beamGeometry:o,beamMaterial:l,label:u};return this.views.set(e.id,d),d}}const e4="#d1d9e0",OE=new Set(["flick_goal","double_tap_goal","one_timer_goal","passing_goal","air_dribble_goal","flip_reset_goal","bump_goal","demo_goal","half_volley_goal"]);function t4(n){return n.metadata.performer==="scorer"||n.metadata.modifiers?.includes("by_scorer")?"scorer":n.metadata.performer==="teammate"?"teammate":OE.has(n.kind)?"unknown":"scorer"}function n4(n){const e=t4(n);return e==="unknown"?"performer unknown":OE.has(n.kind)?`by ${e}`:null}function Zi(n,e){return n.players.find(t=>t.id===e)?.name??e}function Dn(n,e,t){return n.frames[e??-1]?.time??t}function i4(n){const e=n.kind;return e!=="forward"&&e!=="reverse"&&e!=="side"?"flick":`${n.direction==="left"||n.direction==="right"?`${n.direction} `:""}${e} flick`}function s4(n){const e=new Set(n),t=new Set(["goal"]);return e.has("core")&&(t.add("save"),t.add("shot"),t.add("assist")),e.has("demo")&&t.add("demo"),[...t]}function a4(n,e){const t=new Set(s4(e));return n.timelineEvents.filter(i=>t.has(i.kind))}function r4(n,e){return LE(n,e).map(t=>({id:t.id,time:t.time,frame:t.frame,kind:"fifty-fifty",label:t.label,shortLabel:t.label.startsWith("Kickoff 50/50")?"KO":"50",isTeamZero:t.winnerIsTeamZero,color:t.winnerIsTeamZero===null?e4:t.winnerIsTeamZero?en:tn}))}function o4(n,e){return(ve(n,"flick")??[]).map((t,i)=>{const s=At(t.player),a=Zi(e,s),r=i4(t);return{id:`flick:${t.frame}:${s}:${i+1}`,time:Dn(e,t.frame,t.time),frame:t.frame,kind:"flick",label:`${a} ${r}`,shortLabel:"F",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function l4(n,e){return EE(n,e).map(t=>({id:t.id,time:t.time,frame:t.frame,kind:"touch",label:`${t.playerName} touch`,shortLabel:"T",playerId:t.playerId,playerName:t.playerName,isTeamZero:t.isTeamZero,color:t.isTeamZero?en:tn}))}function c4(n,e){return ve(n,"backboard").map((t,i)=>{const s=At(t.player),a=e.players.find(r=>r.id===s)?.name??s;return{id:`backboard:${t.frame}:${s}:${i}`,time:Dn(e,t.frame,t.time),frame:t.frame,kind:"backboard",label:`${a} backboard`,shortLabel:"BB",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function u4(n,e){return DE(n,e).map(t=>({id:t.id,time:t.time,frame:t.frame,kind:"ceiling-shot",label:`${t.playerName} ceiling shot ${t.qualityLabel}`,shortLabel:"CS",playerId:t.playerId,playerName:t.playerName,isTeamZero:t.isTeamZero,color:t.isTeamZero?en:tn}))}function d4(n,e){return ve(n,"wall_aerial").map((t,i)=>{const s=At(t.player),a=Zi(e,s),r=Dn(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Ai(t.wall).toLowerCase();return{id:`wall-aerial:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"wall-aerial",label:`${a} wall-to-air setup ${o}% | ${l} wall`,shortLabel:"W2A",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function h4(n,e){return ve(n,"wall_aerial_shot").map((t,i)=>{const s=At(t.player),a=Zi(e,s),r=Dn(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Ai(t.wall).toLowerCase();return{id:`wall-aerial-shot:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"wall-aerial-shot",label:`${a} wall shot ${o}% | ${l} wall`,shortLabel:"WS",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function f4(n,e){return ve(n,"double_tap").map((t,i)=>{const s=At(t.player),a=Zi(e,s);return{id:`double-tap:${t.frame}:${s}:${i}`,time:Dn(e,t.frame,t.time),frame:t.frame,kind:"double-tap",label:`${a} double tap`,shortLabel:"DT",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function p4(n,e){return ve(n,"center").map((t,i)=>{const s=At(t.player),a=Zi(e,s),r=Dn(e,t.frame,t.time),o=Math.round(t.lateral_centering_distance);return{id:`center:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"center",label:`${a} center | ${o}uu lateral`,shortLabel:"C",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function m4(n,e){return ve(n,"one_timer").map((t,i)=>{const s=At(t.player),a=At(t.passer),r=Zi(e,s),o=Zi(e,a),l=Dn(e,t.frame,t.time),c=Math.round(t.ball_speed);return{id:`one-timer:${t.frame}:${a}:${s}:${i}`,time:l,frame:t.frame,kind:"one-timer",label:`${r} one-timer from ${o} | ${c}uu/s`,shortLabel:"OT",playerId:s,playerName:r,secondaryPlayerId:a,secondaryPlayerName:o,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function _4(n){return Ai(n.replace(/_pass$/,""))}function g4(n,e){return ve(n,"pass").map((t,i)=>{const s=At(t.passer),a=At(t.receiver),r=Zi(e,s),o=Zi(e,a),l=Dn(e,t.frame,t.time),c=Math.round(t.ball_travel_distance),u=_4(t.pass_kind);return{id:`pass:${t.frame}:${s}:${a}:${i}`,time:l,frame:t.frame,kind:"pass",label:`${r} to ${o} ${u.toLowerCase()} pass | ${c}uu`,shortLabel:"P",playerId:s,playerName:r,secondaryPlayerId:a,secondaryPlayerName:o,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function y4(n,e){return ve(n,"half_volley").map((t,i)=>{const s=At(t.player),a=Zi(e,s),r=Dn(e,t.frame,t.time),o=Math.round(t.ball_speed);return{id:`half-volley:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"half-volley",label:`${a} half volley | ${o}uu/s`,shortLabel:"HV",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function v4(n,e){return ve(n,"rush").map((t,i)=>{const s=Dn(e,t.end_frame,t.end_time),a=`${t.attackers}v${t.defenders}`,r=t.is_team_0?"Blue":"Orange";return{id:`rush:${t.start_frame}:${t.end_frame}:${i}`,time:s,frame:t.end_frame,kind:"rush",label:`${r} rush ${a}`,shortLabel:"R",playerId:null,playerName:null,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function b4(n,e){return(ve(n,"powerslide")??[]).filter(t=>t.active).map((t,i)=>{const s=At(t.player),a=Zi(e,s);return{id:`powerslide:${t.frame}:${s}:${i+1}`,time:Dn(e,t.frame,t.time),frame:t.frame,kind:"powerslide",label:`${a} powerslide`,shortLabel:"PS",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function x4(n,e){return ve(n,"speed_flip").map(t=>{const i=t.player?At(t.player):null,s=i?e.players.find(o=>o.id===i)?.name??i:"Unknown",a=e.frames[t.frame]?.time??t.time,r=Math.round(t.confidence*100);return{id:`speed-flip:${t.frame}:${i}:${Math.round(t.confidence*1e3)}`,time:a,frame:t.frame,kind:"speed-flip",label:`${s} speed flip ${r}%`,shortLabel:"SF",playerId:i,playerName:s,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function w4(n,e){return(ve(n,"dodge")??[]).map((t,i)=>{const s=At(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=Dn(e,t.frame,t.time),o=Math.round((t.dodge_impulse?.confidence??1)*100),l=(t.dodge_impulse?.direction_label??"dodge").replaceAll("_"," ");return{id:`dodge:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"dodge",label:`${a} flip impulse ${l} ${o}%`,shortLabel:"FI",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function S4(n,e){return ve(n,"half_flip").map((t,i)=>{const s=At(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=Dn(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Math.round(t.end_speed-t.start_speed);return{id:`half-flip:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"half-flip",label:`${a} half flip ${o}% | +${l}uu/s`,shortLabel:"HF",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function T4(n,e){return ve(n,"wavedash").map((t,i)=>{const s=At(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=Dn(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Math.round(t.horizontal_speed_gain);return{id:`wavedash:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"wavedash",label:`${a} wavedash ${o}% | +${l}uu/s`,shortLabel:"WD",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function M4(n,e){return ve(n,"bump").map((t,i)=>{const s=At(t.initiator),a=At(t.victim),r=e.players.find(u=>u.id===s)?.name??s,o=e.players.find(u=>u.id===a)?.name??a,l=Dn(e,t.frame,t.time),c=Math.round(t.confidence*100);return{id:`bump:${t.frame}:${s}:${a}:${i}`,time:l,frame:t.frame,kind:"bump",label:`${r} bumped ${o} ${c}%`,shortLabel:"B",playerId:s,playerName:r,isTeamZero:t.initiator_is_team_0,color:t.initiator_is_team_0?en:tn}})}function E4(n){return n.kind==="beaten_to_ball"?"BT":n.dodge_active?"DW":n.aerial?"AW":"W"}function C4(n){const e=[n.aerial?"aerial":"grounded"];return n.dodge_active&&e.push("dodge"),e.join(" ")}function A4(n){return n.kind==="beaten_to_ball"?"beaten to ball":"whiff"}function R4(n,e){return ve(n,"whiff").map((t,i)=>{const s=At(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=Dn(e,t.frame,t.time),o=Math.round(t.closest_approach_distance),l=Math.round(t.approach_speed);return{id:`whiff:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"whiff",label:`${a} ${C4(t)} ${A4(t)} | ${o}uu closest, ${l}uu/s`,shortLabel:E4(t),playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}const FE={flick:o4,ceiling_shot:u4,wall_aerial:d4,wall_aerial_shot:h4,double_tap:f4,center:p4,one_timer:m4,pass:g4,half_flip:S4,half_volley:y4,speed_flip:x4},NE=Object.keys(FE),UE=.02,ei=1e-4,P4=200,BE=.08,b_={big:"rgba(245, 158, 11, 0.92)",small:"rgba(52, 211, 153, 0.86)"},wx={both:"rgba(52, 211, 153, 0.86)",inferred_only:"rgba(239, 68, 68, 0.9)",reported_only:"rgba(59, 130, 246, 0.9)"};function I4(n){const e=n.config?.ball_half_neutral_zone_half_width_y;return typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):P4}function lh(n,e,t){return n?.frames?.[e??-1]?.time??t}function L4(n,e,t,i,s,a){const r=e?.ballFrames[n]?.position?.y;return typeof r=="number"&&Number.isFinite(r)&&Math.abs(r)<=t+ei||a>ei?"neutral":i>s+ei?"team_zero_side":s>i+ei?"team_one_side":null}function zE(n,e,t){if(n==="neutral")return{id:`half-control:neutral:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"half-control",laneLabel:"Half Control",label:"Neutral half control",color:"rgba(209, 217, 224, 0.7)",isTeamZero:null};const i=n==="team_zero_side";return{id:`half-control:${n}:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"half-control",laneLabel:"Half Control",label:i?"Blue half control":"Orange half control",color:of(i)??void 0,isTeamZero:i}}function cf(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function k4(n,e){const t=cf(ve(n,"possession")),i=[];let s=0,a=!1,r="neutral",o=null;for(const l of n.frames){for(;s0)return k4(n,e);const t=[];let i=0,s=0,a=0,r=null;for(const o of n.frames){if(!Number.isFinite(o.time)||!Number.isFinite(o.dt)||o.dt<=0){r=o;continue}const l=o,c=l.team_zero?.possession?.possession_time??0,u=l.team_one?.possession?.possession_time??0,d=l.team_zero?.possession?.neutral_time??0,h=c-i,f=u-s,p=d-a;i=c,s=u,a=d;let g=null;const{startTime:_,endTime:m}=gr(o,r,e);h>f+ei&&h>p+ei?g={id:`possession:team_zero:${_.toFixed(3)}`,startTime:_,endTime:m,lane:"possession",laneLabel:"Possession",label:"Blue possession",color:"rgba(59, 130, 246, 0.88)",isTeamZero:!0}:f>h+ei&&f>p+ei&&(g={id:`possession:team_one:${_.toFixed(3)}`,startTime:_,endTime:m,lane:"possession",laneLabel:"Possession",label:"Orange possession",color:"rgba(245, 158, 11, 0.88)",isTeamZero:!1}),Bo(t,g),r=o}return t}function O4(n,e){const t=cf(ve(n,"ball_half")),i=[];let s=0,a=!1,r="neutral",o=null;for(const l of n.frames){for(;s0)return O4(n,e);const t=[];let i=0,s=0,a=0;const r=I4(n);let o=null;for(const l of n.frames){if(!Number.isFinite(l.time)||!Number.isFinite(l.dt)||l.dt<=0){o=l;continue}const c=l,u=c.team_zero?.ball_half?.defensive_half_time??0,d=c.team_one?.ball_half?.defensive_half_time??0,h=c.team_zero?.ball_half?.neutral_time??0,f=u-i,p=d-s,g=h-a;i=u,s=d,a=h;const{startTime:_,endTime:m}=gr(l,o,e),v=L4(l.frame_number,e,r,f,p,g),y=v?zE(v,_,m):null;Bo(t,y),o=l}return t}function N4(n,e,t){return t>ei?"neutral_third":n>e+ei?"team_zero_third":e>n+ei?"team_one_third":null}function HE(n,e,t){if(n==="neutral_third")return{id:`third-control:neutral_third:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"third-control",laneLabel:"Third Control",label:"Neutral third control",color:"rgba(209, 217, 224, 0.7)",isTeamZero:null};const i=n==="team_zero_third";return{id:`third-control:${n}:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"third-control",laneLabel:"Third Control",label:i?"Blue third control":"Orange third control",color:of(i)??void 0,isTeamZero:i}}function U4(n,e){const t=cf(ve(n,"ball_third")),i=[];let s=0,a=!1,r="neutral_third",o=null;for(const l of n.frames){for(;s0)return U4(n,e);const t=[];let i=0,s=0,a=0,r=null;for(const o of n.frames){if(!Number.isFinite(o.time)||!Number.isFinite(o.dt)||o.dt<=0){r=o;continue}const l=o,c=l.team_zero?.ball_third?.defensive_third_time??0,u=l.team_one?.ball_third?.defensive_third_time??0,d=l.team_zero?.ball_third?.neutral_third_time??0,h=c-i,f=u-s,p=d-a;i=c,s=u,a=d;const{startTime:g,endTime:_}=gr(o,r,e),m=N4(h,f,p),v=m?HE(m,g,_):null;Bo(t,v),r=o}return t}function z4(n,e){return ve(n,"fifty_fifty").map((t,i)=>{const s=lh(e,t.start_frame,t.start_time),a=Math.max(s,lh(e,t.resolve_frame,t.resolve_time)),r=t.winning_team_is_team_0==null?"Neutral":t.winning_team_is_team_0?"Blue win":"Orange win",o=t.is_kickoff?"kickoff ":"";return{id:`fifty-fifty:${t.start_frame}:${t.resolve_frame}:${i}`,startTime:s,endTime:a,lane:"fifty-fifty",laneLabel:"50/50",label:`${r} ${o}50/50`,shortLabel:t.is_kickoff?"KO":"50",color:t.winning_team_is_team_0==null?"rgba(209, 217, 224, 0.7)":t.winning_team_is_team_0?"rgba(59, 130, 246, 0.48)":"rgba(245, 158, 11, 0.48)",isTeamZero:t.winning_team_is_team_0}}).sort((t,i)=>t.startTime!==i.startTime?t.startTime-i.startTime:(t.id??"").localeCompare(i.id??""))}function H4(n,e){return ve(n,"rush").map((t,i)=>{const s=e?.frames[t.start_frame]?.time??t.start_time,a=e?.frames[t.end_frame]?.time??t.end_time,r=`${t.attackers}v${t.defenders}`,o=t.is_team_0;return{id:`rush-range:${t.start_frame}:${t.end_frame}:${i}`,startTime:s,endTime:Math.max(s,a),lane:"rush",laneLabel:"Rush",label:`${o?"Blue":"Orange"} rush ${r}`,color:o?"rgba(59, 130, 246, 0.4)":"rgba(245, 158, 11, 0.4)",isTeamZero:o}})}function V4(n,e={}){const t=VE(e),i=new Set(e.detections??["both","inferred_only","reported_only"]),s=new Set(e.activities??["active","inactive","unknown"]),a=new Set(e.fieldHalves??["own","opponent","unknown"]),r=e.playerIds?new Set(e.playerIds):null;if(t.size===0||i.size===0||!s.has("unknown")||!a.has("unknown")||r?.size===0)return[];const o=new Map(n.players.map(c=>[c.id,c.isTeamZero])),l=[];for(const c of n.boostPads)if(t.has(c.size))for(let u=0;uc.startTime!==u.startTime?c.startTime-u.startTime:(c.id??"").localeCompare(u.id??""))}function VE(n){if(n.padTypes)return new Set(n.padTypes);if(n.sizes){const e=new Set(n.sizes),t=new Set;return e.has("big")&&t.add("big"),e.has("small")&&t.add("small"),e.has("big")&&e.has("small")&&t.add("ambiguous"),t}return new Set(["big","small","ambiguous"])}function Sx(n){const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function G4(n){return{big:"big",small:"small",ambiguous:"ambiguous"}[n]}function $4(n){return{both:"counted",inferred_only:"inferred",reported_only:"reported"}[n]}function W4(n,e){return n==="inferred_only"?"I":n==="reported_only"?"R":{big:"100",small:"12",ambiguous:"?"}[e]}function X4(n,e,t={}){const i=ve(n,"boost_pickup");if(i.length===0&&e)return V4(e,t);const s=VE(t),a=new Set(t.detections??["both","inferred_only","reported_only"]),r=new Set(t.activities??["active","inactive","unknown"]),o=new Set(t.fieldHalves??["own","opponent","unknown"]),l=t.playerIds?new Set(t.playerIds):null;if(s.size===0||a.size===0||r.size===0||o.size===0||l?.size===0)return[];const c=new Map((e?.players??[]).map(u=>[u.id,u.name]));return i.filter(u=>{const d=Sx(u.player_id);return s.has(u.pad_type)&&a.has(u.detection)&&r.has(u.activity)&&o.has(u.field_half)&&(!l||l.has(d))}).map((u,d)=>{const h=Sx(u.player_id),f=c.get(h)??h,p=Math.max(0,lh(e,u.frame,u.time)),g=$4(u.detection),_=G4(u.pad_type);return{id:`boost-pickup:${u.detection}:${u.frame}:${h}:${d}`,startTime:p,endTime:Math.max(p+BE,p),lane:"boost-pickups",laneLabel:"Boost Pickups",label:`${f} ${g} ${_} boost pickup`,shortLabel:W4(u.detection,u.pad_type),color:of(u.is_team_0)??(u.detection==="both"?u.pad_type==="big"?b_.big:u.pad_type==="small"?b_.small:wx.both:wx[u.detection]),isTeamZero:u.is_team_0}}).sort((u,d)=>u.startTime!==d.startTime?u.startTime-d.startTime:(u.id??"").localeCompare(d.id??""))}const ld=[{fieldName:"time_defensive_third",aliases:["time_defensive_zone"],label:"Def third",relativeColor:"own"},{fieldName:"time_neutral_third",aliases:["time_neutral_zone"],label:"Neutral third",relativeColor:"neutral"},{fieldName:"time_offensive_third",aliases:["time_offensive_zone"],label:"Off third",relativeColor:"opp"}];function GE(n,e){return n.relativeColor==="neutral"?"rgba(209, 217, 224, 0.68)":(n.relativeColor==="own"?e:!e)?"rgba(89, 195, 255, 0.74)":"rgba(255, 193, 92, 0.78)"}function Yg(n){const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function K4(n,e){const t=n.positioning;if(!t)return 0;for(const i of[e.fieldName,...e.aliases??[]]){const s=t[i];if(typeof s=="number"&&Number.isFinite(s))return s}return 0}function q4(n){switch(n){case"defensive":return ld[0];case"neutral":return ld[1];case"offensive":return ld[2]}}function Y4(n){const e=new Map;for(const t of n.frames)for(const i of t.players){const s=Yg(i.player_id);e.has(s)||e.set(s,i.name)}return e}function j4(n){const e=cf(ve(n,"field_third")),t=[],i=new Map,s=Y4(n);for(const a of e){if(!Number.isFinite(a.time)||!Number.isFinite(a.end_time)||a.end_time-a.time<=ei)continue;const r=Yg(a.player),o=q4(a.state);$E(t,i,{id:`time-in-zone:${r}:${o.fieldName}:${a.time.toFixed(3)}`,startTime:a.time,endTime:a.end_time,lane:`time-in-zone:${r}`,laneLabel:s.get(r)??r,label:o.label,color:GE(o,a.is_team_0),isTeamZero:a.is_team_0})}return t}function Z4(n,e){if(ve(n,"field_third").length>0)return j4(n);const t=new Map,i=[],s=new Map;let a=null;for(const r of n.frames){if(!Number.isFinite(r.time)||!Number.isFinite(r.dt)||r.dt<=0){a=r;continue}const{startTime:o,endTime:l}=gr(r,a,e);if(l-o<=ei){a=r;continue}for(const c of r.players){const u=Yg(c.player_id),d=t.get(u)??new Map;let h=null,f=0;for(const p of ld){const g=K4(c,p),_=g-(d.get(p.fieldName)??0);_>f+ei&&(f=_,h=p),d.set(p.fieldName,g)}t.set(u,d),h&&$E(i,s,{id:`time-in-zone:${u}:${h.fieldName}:${o.toFixed(3)}`,startTime:o,endTime:l,lane:`time-in-zone:${u}`,laneLabel:c.name,label:h.label,color:GE(h,c.is_team_0),isTeamZero:c.is_team_0})}a=r}return i}function gr(n,e,t){const i=t?.frames[n.frame_number]?.time??n.time,s=e?t?.frames[e.frame_number]?.time??e.time:Math.max(0,i-n.dt);return{startTime:Math.max(0,s),endTime:Math.max(s,i)}}function Bo(n,e){if(!e)return;const t=n[n.length-1];if(t&&t.lane===e.lane&&t.label===e.label&&Math.abs(t.endTime-e.startTime)<=UE){t.endTime=e.endTime;return}n.push(e)}function $E(n,e,t){if(!t)return;const i=t.lane??"",s=e.get(i);if(s&&s.label===t.label&&Math.abs(s.endTime-t.startTime)<=UE){s.endTime=t.endTime;return}n.push(t),e.set(i,t)}const rm=236,WE="relative-positioning",J4={last:"Last",upfield:"Upfield",level:"Level",mid:"Mid"};function na(n){return n?"team-blue":"team-orange"}function XE(n,e,t){return`
${n} ${t.metaHtml??""}
${e} -
`}function Tn(n,e,t,i=""){return FE(n,t,{metaHtml:i,tone:e?"blue":"orange"})}function si(n,e){return`
${[!0,!1].map(t=>{const i=n.filter(a=>a.is_team_0===t);if(i.length===0)return"";const s=t?"Blue":"Orange";return`
+
`}function Tn(n,e,t,i=""){return XE(n,t,{metaHtml:i,tone:e?"blue":"orange"})}function si(n,e){return`
${[!0,!1].map(t=>{const i=n.filter(a=>a.is_team_0===t);if(i.length===0)return"";const s=t?"Blue":"Orange";return`

${s} team

${i.length} player${i.length===1?"":"s"} @@ -5635,12 +5700,12 @@ void main() {
${i.map(e).join("")}
-
`}).join("")}
`}function sf(n,e,t=""){return FE(n,e,{metaHtml:t,tone:"shared"})}function wn(n,e,t){const i=zt(n.statsFrameLookup,e);return i?i.players.find(s=>At(s.player_id)===t)??null:null}function w4(n,e,t){const i=n.players.find(p=>p.id===e);if(!i||!i.frames[t]?.position)return"mid";const a=i.isTeamZero,r=n.players.filter(p=>p.isTeamZero===a).length,o=[];let l=0;for(const p of n.players){if(p.isTeamZero!==a)continue;const g=p.frames[t];if(!g?.position)continue;const _=a?g.position.y:-g.position.y;o.push(_),p.id===e&&(l=_)}if(r<2||o.length!==r)return"mid";const c=Math.min(...o),u=Math.max(...o);if(u-c<=Qp)return"level";const h=l-c<=Qp,f=u-l<=Qp;return h&&!f?"last":f&&!h?"upfield":"mid"}function S4(n){let e=null,t=null;const i=new Set,s=["possession_state","field_half","field_third"];return{id:"possession",label:"Possession",setup(){a()},teardown(){},onBeforeRender(){},getTimelineRanges(o){return i4(o.statsTimeline,o.replay)},getConfig(){return{breakdownClasses:r()}},applyConfig(o){if(i.clear(),o&&typeof o=="object"&&!Array.isArray(o)){const l=o.breakdownClasses;if(Array.isArray(l))for(const c of l)s.includes(c)&&i.add(c)}a(),n.rerenderCurrentState()},renderStats(o,l){const u=zt(l.statsFrameLookup,o)?.team_zero?.possession;return u?sf("Control State",rx(u,{labelPerspective:{kind:"shared"},breakdownClasses:r()})):""},renderFocusedPlayerStats(o,l,c){const u=zt(c.statsFrameLookup,l),d=wn(c,l,o),h=d?.is_team_0?u?.team_zero?.possession:u?.team_one?.possession;return!h||!d?"":rx(h,{labelPerspective:{kind:"team"},breakdownClasses:r()})},renderSettings(){if(!e){e=document.createElement("div"),e.className="module-settings-card";const o=document.createElement("div");o.className="module-settings-header";const l=document.createElement("div"),c=document.createElement("p");c.className="module-settings-eyebrow",c.textContent="Stat display";const u=document.createElement("h3");u.textContent="Possession breakdown",l.append(c,u),t=document.createElement("strong"),t.className="metric-readout",o.append(l,t);const d=document.createElement("div");d.className="module-settings-options";const h=document.createElement("label");h.className="toggle";const f=document.createElement("input");f.type="checkbox",f.dataset.breakdownClass="possession_state",f.addEventListener("change",()=>{f.checked?i.add("possession_state"):i.delete("possession_state"),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const p=document.createElement("span");p.textContent="Control",h.append(f,p),d.append(h);const g=document.createElement("label");g.className="toggle";const _=document.createElement("input");_.type="checkbox",_.dataset.breakdownClass="field_third",_.addEventListener("change",()=>{_.checked?i.add("field_third"):i.delete("field_third"),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const m=document.createElement("span");m.textContent="Thirds",g.append(_,m),d.append(g);const v=document.createElement("label");v.className="toggle";const y=document.createElement("input");y.type="checkbox",y.dataset.breakdownClass="field_half",y.addEventListener("change",()=>{y.checked?i.add("field_half"):i.delete("field_half"),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const b=document.createElement("span");b.textContent="Halves",v.append(y,b),d.append(v),e.append(o,d)}return a(),e}};function a(){if(e){for(const o of e.querySelectorAll("input[data-breakdown-class]")){const l=o.dataset.breakdownClass;o.checked=l?i.has(l):!1}if(t){const o=s.filter(l=>i.has(l));t.textContent=o.length===0?"Total only":o.map(l=>l==="possession_state"?"Control":l==="field_half"?"Halves":"Thirds").join(" x ")}}}function r(){return s.filter(o=>i.has(o))}}function T4(){let n=null;return{id:"fifty-fifty",label:"50/50",setup(e){n=new u5(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},getTimelineEvents(e){return R5(e.statsTimeline,e.replay)},getTimelineRanges(e){return c4(e.statsTimeline,e.replay)},renderStats(e,t){const i=zt(t.statsFrameLookup,e);if(!i)return"";const s=sf("Challenge Summary",kV(i.team_zero?.fifty_fifty)),a=si(i.players,r=>Tn(r.name,r.is_team_0,ix(r.fifty_fifty)));return s+a},renderFocusedPlayerStats(e,t,i){const s=wn(i,t,e);return s?ix(s.fifty_fifty):""}}}function M4(){let n=null,e=null;return{id:"ball_half",label:"Half Control",setup(t){e=t.replay,n=new LV(t.player.sceneState.replayRoot,t.fieldScale)},teardown(){n?.dispose(),n=null,e=null},onBeforeRender(t){const i=e?.ballFrames[t.frameIndex];n?.update(i?.position?.y??null)},getTimelineRanges(t){return a4(t.statsTimeline,t.replay)},renderStats(t,i){const a=zt(i.statsFrameLookup,t)?.team_zero?.ball_half;return a?sf("Field State",lx(a,{labelPerspective:{kind:"shared"}})):""},renderFocusedPlayerStats(t,i,s){const a=zt(s.statsFrameLookup,i),r=wn(s,i,t),o=r?.is_team_0?a?.team_zero?.ball_half:a?.team_one?.ball_half;return!o||!r?"":lx(o,{labelPerspective:{kind:"team"}})}}}function E4(){return{id:"ball_third",label:"Third Control",setup(){},teardown(){},onBeforeRender(){},getTimelineRanges(n){return l4(n.statsTimeline,n.replay)},renderStats(n,e){const i=zt(e.statsFrameLookup,n)?.team_zero?.ball_third;return i?sf("Field State",ux(i,{labelPerspective:{kind:"shared"}})):""},renderFocusedPlayerStats(n,e,t){const i=zt(t.statsFrameLookup,e),s=wn(t,e,n),a=s?.is_team_0?i?.team_zero?.ball_third:i?.team_one?.ball_third;return!a||!s?"":ux(a,{labelPerspective:{kind:"team"}})}}}function C4(){return{id:"rush",label:"Rush",setup(){},teardown(){},onBeforeRender(){},getTimelineRanges(n){return u4(n.statsTimeline,n.replay)},getTimelineEvents(n){return V5(n.statsTimeline,n.replay)},renderStats(n,e){const t=zt(e.statsFrameLookup,n),i=t?.team_zero?.rush,s=t?.team_one?.rush;return!i||!s?"":[Tn("Blue Team",!0,Jp(i)),Tn("Orange Team",!1,Jp(s))].join("")},renderFocusedPlayerStats(n,e,t){const i=zt(t.statsFrameLookup,e),s=wn(t,e,n),a=s?.is_team_0?i?.team_zero?.rush:i?.team_one?.rush;return!a||!s?"":Jp(a)}}}const p_={speed_band:{valueOrder:["slow","boost","supersonic"],formatValue:n=>({slow:"Slow",boost:"Boost",supersonic:"Supersonic"})[n]??n},height_band:{valueOrder:["ground","low_air","high_air"],formatValue:n=>({ground:"Ground",low_air:"Low air",high_air:"High air"})[n]??n}};function A4(n){const e=new Set,t=[];for(const i of n??[])e.has(i)||(e.add(i),t.push(i));return t}function em(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function R4(n,e,t=1){return n===void 0||Number.isNaN(n)?"?":e===void 0||Number.isNaN(e)||e<=0?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${(n*100/e).toFixed(t)}%)`}function _x(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function sd(n,e){return`
${_x(n)}${_x(e)}
`}function P4(n,e,t){for(const i of t){const{valueOrder:s}=p_[i],a=s.indexOf(n[i]),r=s.indexOf(e[i]),o=a===-1?Number.MAX_SAFE_INTEGER:a,l=r===-1?Number.MAX_SAFE_INTEGER:r;if(o!==l)return o-l}return 0}function I4(n,e){if(e.length===1){const t=e[0];return p_[t].formatValue(n[t])}return e.map(t=>p_[t].formatValue(n[t])).join(" / ")}function L4(n,e,t){if(e.length===0||!n?.labeled_tracked_time?.entries?.length)return"";const i=new Map,s=n?.labeled_tracked_time?.entries??[];for(const a of s){const r=new Map(a.labels.map(d=>[d.key,d.value])),o={};let l=!0;for(const d of e){const h=r.get(d);if(h===void 0){l=!1;break}o[d]=h}if(!l)continue;const c=e.map(d=>`${d}:${o[d]}`).join("|"),u=i.get(c);u?u.total+=a.value:i.set(c,{values:o,total:a.value})}return[...i.values()].sort((a,r)=>P4(a.values,r.values,e)).map(a=>sd(I4(a.values,e),R4(a.total,t))).join("")}function gx(n,e={}){const t=n?.tracked_time,i=n&&t&&t>0?n.speed_integral/t:t===0?0:void 0,s=A4(e.breakdownClasses),a=L4(n,s,t);return` - ${sd("Tracked",em(t,1,"s"))} - ${sd("Distance",em(n?.total_distance,0," uu"))} - ${sd("Avg speed",em(i,0," uu/s"))} + `}).join("")}
`}function uf(n,e,t=""){return XE(n,e,{metaHtml:t,tone:"shared"})}function wn(n,e,t){const i=zt(n.statsFrameLookup,e);return i?i.players.find(s=>At(s.player_id)===t)??null:null}function Q4(n,e,t){const i=n.players.find(p=>p.id===e);if(!i||!i.frames[t]?.position)return"mid";const a=i.isTeamZero,r=n.players.filter(p=>p.isTeamZero===a).length,o=[];let l=0;for(const p of n.players){if(p.isTeamZero!==a)continue;const g=p.frames[t];if(!g?.position)continue;const _=a?g.position.y:-g.position.y;o.push(_),p.id===e&&(l=_)}if(r<2||o.length!==r)return"mid";const c=Math.min(...o),u=Math.max(...o);if(u-c<=rm)return"level";const h=l-c<=rm,f=u-l<=rm;return h&&!f?"last":f&&!h?"upfield":"mid"}function eG(n){let e=null,t=null;const i=new Set,s=["possession_state","field_half","field_third"];return{id:"possession",label:"Possession",setup(){a()},teardown(){},onBeforeRender(){},getTimelineRanges(o){return D4(o.statsTimeline,o.replay)},getConfig(){return{breakdownClasses:r()}},applyConfig(o){if(i.clear(),o&&typeof o=="object"&&!Array.isArray(o)){const l=o.breakdownClasses;if(Array.isArray(l))for(const c of l)s.includes(c)&&i.add(c)}a(),n.rerenderCurrentState()},renderStats(o,l){const u=zt(l.statsFrameLookup,o)?.team_zero?.possession;return u?uf("Control State",px(u,{labelPerspective:{kind:"shared"},breakdownClasses:r()})):""},renderFocusedPlayerStats(o,l,c){const u=zt(c.statsFrameLookup,l),d=wn(c,l,o),h=d?.is_team_0?u?.team_zero?.possession:u?.team_one?.possession;return!h||!d?"":px(h,{labelPerspective:{kind:"team"},breakdownClasses:r()})},renderSettings(){if(!e){e=document.createElement("div"),e.className="module-settings-card";const o=document.createElement("div");o.className="module-settings-header";const l=document.createElement("div"),c=document.createElement("p");c.className="module-settings-eyebrow",c.textContent="Stat display";const u=document.createElement("h3");u.textContent="Possession breakdown",l.append(c,u),t=document.createElement("strong"),t.className="metric-readout",o.append(l,t);const d=document.createElement("div");d.className="module-settings-options";const h=document.createElement("label");h.className="toggle";const f=document.createElement("input");f.type="checkbox",f.dataset.breakdownClass="possession_state",f.addEventListener("change",()=>{f.checked?i.add("possession_state"):i.delete("possession_state"),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const p=document.createElement("span");p.textContent="Control",h.append(f,p),d.append(h);const g=document.createElement("label");g.className="toggle";const _=document.createElement("input");_.type="checkbox",_.dataset.breakdownClass="field_third",_.addEventListener("change",()=>{_.checked?i.add("field_third"):i.delete("field_third"),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const m=document.createElement("span");m.textContent="Thirds",g.append(_,m),d.append(g);const v=document.createElement("label");v.className="toggle";const y=document.createElement("input");y.type="checkbox",y.dataset.breakdownClass="field_half",y.addEventListener("change",()=>{y.checked?i.add("field_half"):i.delete("field_half"),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const b=document.createElement("span");b.textContent="Halves",v.append(y,b),d.append(v),e.append(o,d)}return a(),e}};function a(){if(e){for(const o of e.querySelectorAll("input[data-breakdown-class]")){const l=o.dataset.breakdownClass;o.checked=l?i.has(l):!1}if(t){const o=s.filter(l=>i.has(l));t.textContent=o.length===0?"Total only":o.map(l=>l==="possession_state"?"Control":l==="field_half"?"Halves":"Thirds").join(" x ")}}}function r(){return s.filter(o=>i.has(o))}}function tG(){let n=null;return{id:"fifty-fifty",label:"50/50",setup(e){n=new H5(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},getTimelineEvents(e){return r4(e.statsTimeline,e.replay)},getTimelineRanges(e){return z4(e.statsTimeline,e.replay)},renderStats(e,t){const i=zt(t.statsFrameLookup,e);if(!i)return"";const s=uf("Challenge Summary",d5(i.team_zero?.fifty_fifty)),a=si(i.players,r=>Tn(r.name,r.is_team_0,dx(r.fifty_fifty)));return s+a},renderFocusedPlayerStats(e,t,i){const s=wn(i,t,e);return s?dx(s.fifty_fifty):""}}}function nG(){let n=null,e=null;return{id:"ball_half",label:"Half Control",setup(t){e=t.replay,n=new c5(t.player.sceneState.replayRoot,t.fieldScale)},teardown(){n?.dispose(),n=null,e=null},onBeforeRender(t){const i=e?.ballFrames[t.frameIndex];n?.update(i?.position?.y??null)},getTimelineRanges(t){return F4(t.statsTimeline,t.replay)},renderStats(t,i){const a=zt(i.statsFrameLookup,t)?.team_zero?.ball_half;return a?uf("Field State",_x(a,{labelPerspective:{kind:"shared"}})):""},renderFocusedPlayerStats(t,i,s){const a=zt(s.statsFrameLookup,i),r=wn(s,i,t),o=r?.is_team_0?a?.team_zero?.ball_half:a?.team_one?.ball_half;return!o||!r?"":_x(o,{labelPerspective:{kind:"team"}})}}}function iG(){return{id:"ball_third",label:"Third Control",setup(){},teardown(){},onBeforeRender(){},getTimelineRanges(n){return B4(n.statsTimeline,n.replay)},renderStats(n,e){const i=zt(e.statsFrameLookup,n)?.team_zero?.ball_third;return i?uf("Field State",yx(i,{labelPerspective:{kind:"shared"}})):""},renderFocusedPlayerStats(n,e,t){const i=zt(t.statsFrameLookup,e),s=wn(t,e,n),a=s?.is_team_0?i?.team_zero?.ball_third:i?.team_one?.ball_third;return!a||!s?"":yx(a,{labelPerspective:{kind:"team"}})}}}function sG(){return{id:"rush",label:"Rush",setup(){},teardown(){},onBeforeRender(){},getTimelineRanges(n){return H4(n.statsTimeline,n.replay)},getTimelineEvents(n){return v4(n.statsTimeline,n.replay)},renderStats(n,e){const t=zt(e.statsFrameLookup,n),i=t?.team_zero?.rush,s=t?.team_one?.rush;return!i||!s?"":[Tn("Blue Team",!0,am(i)),Tn("Orange Team",!1,am(s))].join("")},renderFocusedPlayerStats(n,e,t){const i=zt(t.statsFrameLookup,e),s=wn(t,e,n),a=s?.is_team_0?i?.team_zero?.rush:i?.team_one?.rush;return!a||!s?"":am(a)}}}const x_={speed_band:{valueOrder:["slow","boost","supersonic"],formatValue:n=>({slow:"Slow",boost:"Boost",supersonic:"Supersonic"})[n]??n},height_band:{valueOrder:["ground","low_air","high_air"],formatValue:n=>({ground:"Ground",low_air:"Low air",high_air:"High air"})[n]??n}};function aG(n){const e=new Set,t=[];for(const i of n??[])e.has(i)||(e.add(i),t.push(i));return t}function om(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function rG(n,e,t=1){return n===void 0||Number.isNaN(n)?"?":e===void 0||Number.isNaN(e)||e<=0?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${(n*100/e).toFixed(t)}%)`}function Tx(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function cd(n,e){return`
${Tx(n)}${Tx(e)}
`}function oG(n,e,t){for(const i of t){const{valueOrder:s}=x_[i],a=s.indexOf(n[i]),r=s.indexOf(e[i]),o=a===-1?Number.MAX_SAFE_INTEGER:a,l=r===-1?Number.MAX_SAFE_INTEGER:r;if(o!==l)return o-l}return 0}function lG(n,e){if(e.length===1){const t=e[0];return x_[t].formatValue(n[t])}return e.map(t=>x_[t].formatValue(n[t])).join(" / ")}function cG(n,e,t){if(e.length===0||!n?.labeled_tracked_time?.entries?.length)return"";const i=new Map,s=n?.labeled_tracked_time?.entries??[];for(const a of s){const r=new Map(a.labels.map(d=>[d.key,d.value])),o={};let l=!0;for(const d of e){const h=r.get(d);if(h===void 0){l=!1;break}o[d]=h}if(!l)continue;const c=e.map(d=>`${d}:${o[d]}`).join("|"),u=i.get(c);u?u.total+=a.value:i.set(c,{values:o,total:a.value})}return[...i.values()].sort((a,r)=>oG(a.values,r.values,e)).map(a=>cd(lG(a.values,e),rG(a.total,t))).join("")}function Mx(n,e={}){const t=n?.tracked_time,i=n&&t&&t>0?n.speed_integral/t:t===0?0:void 0,s=aG(e.breakdownClasses),a=cG(n,s,t);return` + ${cd("Tracked",om(t,1,"s"))} + ${cd("Distance",om(n?.total_distance,0," uu"))} + ${cd("Avg speed",om(i,0," uu/s"))} ${a} - `}const yx="subtr-actor-flip-impulse-overlay-styles",D4=5882879,k4=16761180,tm=260,O4=760,F4=260,N4=2.5;function NE(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function U4(n,e){const t=NE(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function B4(n){return n.split("_").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function z4(n,e){return ve(n,"dodge").flatMap((t,i)=>{const s=t.dodge_impulse;if(!s)return[];const a=U4(e,t.player),r=NE(t.player),o=e.frames[t.frame]?.time??t.time,l=new S(s.estimated_direction[0],s.estimated_direction[1],s.estimated_direction[2]);return l.lengthSq()<=Number.EPSILON&&l.set(1,0,0),l.normalize(),{id:`dodge-impulse:${t.frame}:${r}:${i}`,time:o,frame:t.frame,isTeamZero:t.is_team_0,playerId:r,playerName:a,position:new S(s.start_position[0],s.start_position[1],s.start_position[2]+44),direction:l,magnitude:s.estimated_impulse_magnitude,confidence:s.confidence,directionLabel:s.direction_label}})}function H4(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function V4(){if(document.getElementById(yx))return;const n=document.createElement("style");n.id=yx,n.textContent=` + `}const Ex="subtr-actor-flip-impulse-overlay-styles",uG=5882879,dG=16761180,lm=260,hG=760,fG=260,pG=2.5;function KE(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function mG(n,e){const t=KE(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function _G(n){return n.split("_").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function gG(n,e){return ve(n,"dodge").flatMap((t,i)=>{const s=t.dodge_impulse;if(!s)return[];const a=mG(e,t.player),r=KE(t.player),o=e.frames[t.frame]?.time??t.time,l=new S(s.estimated_direction[0],s.estimated_direction[1],s.estimated_direction[2]);return l.lengthSq()<=Number.EPSILON&&l.set(1,0,0),l.normalize(),{id:`dodge-impulse:${t.frame}:${r}:${i}`,time:o,frame:t.frame,isTeamZero:t.is_team_0,playerId:r,playerName:a,position:new S(s.start_position[0],s.start_position[1],s.start_position[2]+44),direction:l,magnitude:s.estimated_impulse_magnitude,confidence:s.confidence,directionLabel:s.direction_label}})}function yG(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function vG(){if(document.getElementById(Ex))return;const n=document.createElement("style");n.id=Ex,n.textContent=` .sap-flip-impulse-overlay-root { position: absolute; inset: 0; @@ -5676,7 +5741,7 @@ void main() { border-color: rgba(255, 193, 92, 0.5); background: rgba(76, 41, 7, 0.84); } - `,document.head.append(n)}function G4(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class $4{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;labelOffset=new S(0,0,F4);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=N4;constructor(e,t,i,s){V4(),this.scene=e,this.container=t,this.markers=z4(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="flip-impulse-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-flip-impulse-overlay-root",this.container.append(this.labelRoot)}update(e){const t=H4(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.arrow.removeFromParent(),a.arrow.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.24+.72*r,c=tm+Math.min(1,s.magnitude/450)*(O4-tm);o.arrow.position.copy(s.position),o.arrow.setDirection(s.direction),o.arrow.setLength(c,70,38),o.arrow.cone.material.opacity=l,o.arrow.line.material.opacity=l,this.worldPosition.copy(s.position).add(this.labelOffset);const u=G4(this.worldPosition,this.scene.camera,this.container,this.projectedPosition);o.label.style.display=u?"block":"none",u&&(o.label.style.left=`${this.projectedPosition.x}px`,o.label.style.top=`${this.projectedPosition.y}px`,o.label.style.opacity=`${.42+.58*r}`)}}dispose(){for(const e of this.views.values())e.arrow.removeFromParent(),e.arrow.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=e.isTeamZero?D4:k4,s=new Tg(e.direction,e.position,tm,i);s.renderOrder=35,s.line.material=new Rt({color:i,transparent:!0,opacity:.9,depthWrite:!1,depthTest:!1}),s.cone.material=new Ye({color:i,transparent:!0,opacity:.9,depthWrite:!1,depthTest:!1}),this.group.add(s);const a=document.createElement("div");a.className=`sap-flip-impulse-overlay-label ${e.isTeamZero?"sap-flip-impulse-overlay-label-blue":"sap-flip-impulse-overlay-label-orange"}`,a.textContent=`${e.playerName} ${B4(e.directionLabel)} ${Math.round(e.confidence*100)}%`,this.labelRoot.append(a);const r={marker:e,arrow:s,label:a};return this.views.set(e.id,r),r}}const vx="subtr-actor-speed-flip-overlay-styles",W4=5882879,X4=16761180,K4=16185075,q4=150,Y4=230,j4=220,Z4=4;function UE(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function J4(n,e){const t=UE(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function Q4(n,e){return ve(n,"speed_flip").map(t=>{const i=J4(e,t.player),s=UE(t.player),a=e.frames[t.frame]?.time??t.time,r=t.confidence;return{id:`speed-flip:${t.frame}:${s}:${Math.round(r*1e3)}`,time:a,frame:t.frame,isTeamZero:t.is_team_0,playerId:s,playerName:i,position:{x:t.start_position[0],y:t.start_position[1],z:t.start_position[2]},quality:r,qualityLabel:`${Math.round(r*100)}%`}})}function eG(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function tG(){if(document.getElementById(vx))return;const n=document.createElement("style");n.id=vx,n.textContent=` + `,document.head.append(n)}function bG(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class xG{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;labelOffset=new S(0,0,fG);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=pG;constructor(e,t,i,s){vG(),this.scene=e,this.container=t,this.markers=gG(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="flip-impulse-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-flip-impulse-overlay-root",this.container.append(this.labelRoot)}update(e){const t=yG(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.arrow.removeFromParent(),a.arrow.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.24+.72*r,c=lm+Math.min(1,s.magnitude/450)*(hG-lm);o.arrow.position.copy(s.position),o.arrow.setDirection(s.direction),o.arrow.setLength(c,70,38),o.arrow.cone.material.opacity=l,o.arrow.line.material.opacity=l,this.worldPosition.copy(s.position).add(this.labelOffset);const u=bG(this.worldPosition,this.scene.camera,this.container,this.projectedPosition);o.label.style.display=u?"block":"none",u&&(o.label.style.left=`${this.projectedPosition.x}px`,o.label.style.top=`${this.projectedPosition.y}px`,o.label.style.opacity=`${.42+.58*r}`)}}dispose(){for(const e of this.views.values())e.arrow.removeFromParent(),e.arrow.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=e.isTeamZero?uG:dG,s=new Ig(e.direction,e.position,lm,i);s.renderOrder=35,s.line.material=new Rt({color:i,transparent:!0,opacity:.9,depthWrite:!1,depthTest:!1}),s.cone.material=new Ye({color:i,transparent:!0,opacity:.9,depthWrite:!1,depthTest:!1}),this.group.add(s);const a=document.createElement("div");a.className=`sap-flip-impulse-overlay-label ${e.isTeamZero?"sap-flip-impulse-overlay-label-blue":"sap-flip-impulse-overlay-label-orange"}`,a.textContent=`${e.playerName} ${_G(e.directionLabel)} ${Math.round(e.confidence*100)}%`,this.labelRoot.append(a);const r={marker:e,arrow:s,label:a};return this.views.set(e.id,r),r}}const Cx="subtr-actor-speed-flip-overlay-styles",wG=5882879,SG=16761180,TG=16185075,MG=150,EG=230,CG=220,AG=4;function qE(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function RG(n,e){const t=qE(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function PG(n,e){return ve(n,"speed_flip").map(t=>{const i=RG(e,t.player),s=qE(t.player),a=e.frames[t.frame]?.time??t.time,r=t.confidence;return{id:`speed-flip:${t.frame}:${s}:${Math.round(r*1e3)}`,time:a,frame:t.frame,isTeamZero:t.is_team_0,playerId:s,playerName:i,position:{x:t.start_position[0],y:t.start_position[1],z:t.start_position[2]},quality:r,qualityLabel:`${Math.round(r*100)}%`}})}function IG(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function LG(){if(document.getElementById(Cx))return;const n=document.createElement("style");n.id=Cx,n.textContent=` .sap-speed-flip-overlay-root { position: absolute; inset: 0; @@ -5713,7 +5778,7 @@ void main() { border-color: rgba(255, 193, 92, 0.5); background: rgba(76, 41, 7, 0.84); } - `,document.head.append(n)}function nG(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class iG{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;labelOffset=new S(0,0,j4);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=Z4;constructor(e,t,i,s){tG(),this.scene=e,this.container=t,this.markers=Q4(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="speed-flip-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-speed-flip-overlay-root",this.container.append(this.labelRoot)}update(e){const t=eG(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.ring.removeFromParent(),a.ring.geometry.dispose(),a.material.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.16+.56*r,c=.96+(1-r)*.22;o.material.opacity=l,o.ring.position.set(s.position.x,s.position.y,s.position.z+14),o.ring.scale.setScalar(c+s.quality*.08),this.worldPosition.set(s.position.x,s.position.y,s.position.z).add(this.labelOffset);const u=nG(this.worldPosition,this.scene.camera,this.container,this.projectedPosition);o.label.style.display=u?"block":"none",u&&(o.label.style.left=`${this.projectedPosition.x}px`,o.label.style.top=`${this.projectedPosition.y}px`,o.label.style.opacity=`${.42+.58*r}`)}}dispose(){for(const e of this.views.values())e.ring.removeFromParent(),e.ring.geometry.dispose(),e.material.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=new Ye({color:e.quality>=.75?K4:e.isTeamZero?W4:X4,transparent:!0,opacity:.8,side:ct,depthWrite:!1,depthTest:!1}),s=new ni(q4,Y4,48),a=new we(s,i);a.renderOrder=30,this.group.add(a);const r=document.createElement("div");r.className=`sap-speed-flip-overlay-label ${e.isTeamZero?"sap-speed-flip-overlay-label-blue":"sap-speed-flip-overlay-label-orange"}`,r.textContent=`${e.playerName} speed flip ${e.qualityLabel}`,this.labelRoot.append(r);const o={marker:e,ring:a,material:i,label:r};return this.views.set(e.id,o),o}}const Du=[{value:"big",label:"Big pads"},{value:"small",label:"Small pads"},{value:"ambiguous",label:"Ambiguous pads"}],nm=[{value:"both",label:"Both detectors"},{value:"inferred_only",label:"Inferred only"},{value:"reported_only",label:"Reported only"}],ku=[{value:"active",label:"Active play"},{value:"inactive",label:"Inactive play"},{value:"unknown",label:"Unknown activity"}],Ou=[{value:"own",label:"Own half"},{value:"opponent",label:"Opponent half"},{value:"unknown",label:"Unknown half"}];function sG(n,e){return n===e||n==="ambiguous"}function aG(n,e){const t=e?rG(e,ve(e,"boost_pickup")):[];return t.length===0?null:t.find(i=>At(i.player_id)===n.player.id&&i.detection!=="inferred_only"&&i.frame===n.event.frame&&sG(i.pad_type,n.pad.size))??null}function rG(n,e){if(e.length>0)return e;const t=n.events?.boost_pickups;return Array.isArray(t)?t:e}function BE(n={}){let e=null,t=null,i=null,s=null,a=null,r=null;const o=new Set(Du.map(M=>M.value)),l=new Set(nm.map(M=>M.value)),c=new Set(ku.map(M=>M.value)),u=new Set(Ou.map(M=>M.value));let d=null,h=!1;function f(M,C,w,E){const R=document.createElement("div");R.className="boost-pickup-filter-group";const D=document.createElement("p");D.className="module-settings-group-title",D.textContent=M;const O=document.createElement("div");O.className="boost-pickup-filter-options";for(const k of C){const U=document.createElement("label");U.className="toggle";const F=document.createElement("input");F.type="checkbox",F.dataset.boostPickupFilter=E,F.dataset.boostPickupValue=k.value,F.addEventListener("change",()=>{F.checked?w.add(k.value):w.delete(k.value),_(a),n.refreshTimelineRanges?.(),n.rerenderCurrentState?.(),n.requestConfigSync?.()});const W=document.createElement("span");W.textContent=k.label,U.append(F,W),O.append(U)}return R.append(D,O),R}function p(){const M=document.createElement("div");M.className="boost-pickup-filter-group boost-pickup-filter-group-wide",i=M;const C=document.createElement("p");return C.className="module-settings-group-title",C.textContent="Player",s=document.createElement("div"),s.className="boost-pickup-filter-options",M.append(C,s),M}function g(M){if(s&&(s.replaceChildren(),i&&(i.hidden=!M||M.players.length===0),!!M))for(const C of M.players){const w=document.createElement("label");w.className="toggle";const E=document.createElement("input");E.type="checkbox",E.dataset.boostPickupPlayerId=C.id,E.addEventListener("change",()=>{d||(d=new Set(M.players.map(D=>D.id))),E.checked?d.add(C.id):d.delete(C.id),_(M),n.refreshTimelineRanges?.(),n.rerenderCurrentState?.(),n.requestConfigSync?.()});const R=document.createElement("span");R.textContent=`${C.name} (${C.isTeamZero?"Blue":"Orange"})`,w.append(E,R),s.append(w)}}function _(M){if(e){for(const C of e.querySelectorAll("input[data-boost-pickup-filter][data-boost-pickup-value]")){const w=C.dataset.boostPickupFilter,E=C.dataset.boostPickupValue;C.checked=m(w,E)}for(const C of e.querySelectorAll("input[data-boost-pickup-player-id]")){const w=C.dataset.boostPickupPlayerId;C.checked=w?d?.has(w)??!0:!1}t&&(t.textContent=v(M))}}function m(M,C){if(!C)return!1;switch(M){case"pad-type":return o.has(C);case"detection":return l.has(C);case"activity":return c.has(C);case"field-half":return u.has(C);default:return!1}}function v(M){const C=M?.players.length??0,w=d?d.size:C;if(o.size===0||l.size===0||c.size===0||u.size===0||d!==null&&d.size===0)return"Hidden";const R=[o.sizeR.value));for(const R of w)typeof R=="string"&&E.has(R)&&M.add(R)}function T(){return{padTypes:[...o],detections:[...l],activities:[...c],fieldHalves:[...u],playerIds:d?[...d]:null}}function x(M){if(!M||typeof M!="object"||Array.isArray(M))return;const C=M;b(o,Du,C.padTypes),b(l,nm,C.detections),b(c,ku,C.activities),b(u,Ou,C.fieldHalves),d=Array.isArray(C.playerIds)?new Set(C.playerIds.filter(w=>typeof w=="string")):null,h=a===null&&d!==null,_(a),n.refreshTimelineRanges?.(),n.rerenderCurrentState?.(),n.requestConfigSync?.()}return{setup(M){a!==M.replay&&(a=M.replay,h?h=!1:d=null),r=M.statsTimeline,_(M.replay)},teardown(){},getConfig:T,applyConfig:x,getTimelineRangeOptions(){const M={padTypes:o,detections:l,activities:c,fieldHalves:u};return d&&(M.playerIds=d),M},includePickup:y,renderSettings(M,C){if(!e){e=document.createElement("div"),e.className="boost-pickup-filter-panel";const w=document.createElement("div");w.className="boost-pickup-filter-summary",t=document.createElement("strong"),t.className="metric-readout",w.append(t);const E=document.createElement("div");E.className="boost-pickup-filter-grid",E.append(f("Pad type",Du,o,"pad-type"),f("Activity",ku,c,"activity"),f("Field half",Ou,u,"field-half"),p()),(C.showHeader??!1)&&e.append(w),e.append(E)}return g(M?.replay??null),_(M?.replay??null),e}}}function ai(n){return{id:n.id,label:n.label,setup(){},teardown(){},onBeforeRender(){},getTimelineEvents:n.getTimelineEvents,getTimelineRanges:n.getTimelineRanges,renderStats(e,t){const i=zt(t.statsFrameLookup,e);return i?si(i.players,s=>Tn(s.name,s.is_team_0,n.render(n.select(s),s))):""},renderFocusedPlayerStats(e,t,i){const s=wn(i,t,e);return s?n.render(n.select(s),s):""}}}function Ui(n){return n==null?"?":Qh(n).toFixed(0)}function oG(n,e){const t=Ui(n);if(n==null||e==null)return t;const i=Ui(n+e);return`${t} (${i})`}function im(n){n&&typeof n=="object"&&"dispose"in n&&typeof n.dispose=="function"&&n.dispose()}function lG(n){n&&(n.removeFromParent(),n.traverse(e=>{const t="geometry"in e?e.geometry:null;im(t);const i="material"in e?e.material:null;if(Array.isArray(i))for(const s of i)im(s);else im(i)}))}function cG(){let n=0,e=null;return{acquire(t){e||(e=DV(t.player.sceneState.replayRoot,t.fieldScale)),n+=1},release(){n<=0||(n-=1,n===0&&(lG(e),e=null))}}}const bx=cG();function nt(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function Le(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function m_(n,e=0){return Le(n,e,"%")}function zE(n,e,t=1,i=0){if(n===void 0||Number.isNaN(n))return m_(e,i);const s=Le(n,t,"s");return e===void 0||Number.isNaN(e)?s:`${s} (${m_(e,i)})`}function za(n,e,t=1,i=0){const s=n!==void 0&&e!==void 0&&!Number.isNaN(n)&&!Number.isNaN(e)&&e>0?n*100/e:void 0;return zE(n,s,t,i)}function bt(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function ds(n){const e=bt(n);return e===void 0?void 0:e*100}function HE(n){return bt(n?.tracked_time)}function uG(n,e,t){const i=bt(n?.[e]);if(i!==void 0)return i;const s=HE(n),a=bt(n?.[t]);if(!(s===void 0||s<=0||a===void 0))return a*100/s}function An(n,e,t){return zE(bt(n?.[t]),uG(n,e,t))}function xx(n,e,t){const i=bt(n?.[e]);if(i!==void 0)return i;const s=HE(n),a=bt(n?.[t]);if(!(s===void 0||s<=0||a===void 0))return a/s}function wx(n){return` + `,document.head.append(n)}function kG(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class DG{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;labelOffset=new S(0,0,CG);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=AG;constructor(e,t,i,s){LG(),this.scene=e,this.container=t,this.markers=PG(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="speed-flip-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-speed-flip-overlay-root",this.container.append(this.labelRoot)}update(e){const t=IG(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.ring.removeFromParent(),a.ring.geometry.dispose(),a.material.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.16+.56*r,c=.96+(1-r)*.22;o.material.opacity=l,o.ring.position.set(s.position.x,s.position.y,s.position.z+14),o.ring.scale.setScalar(c+s.quality*.08),this.worldPosition.set(s.position.x,s.position.y,s.position.z).add(this.labelOffset);const u=kG(this.worldPosition,this.scene.camera,this.container,this.projectedPosition);o.label.style.display=u?"block":"none",u&&(o.label.style.left=`${this.projectedPosition.x}px`,o.label.style.top=`${this.projectedPosition.y}px`,o.label.style.opacity=`${.42+.58*r}`)}}dispose(){for(const e of this.views.values())e.ring.removeFromParent(),e.ring.geometry.dispose(),e.material.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=new Ye({color:e.quality>=.75?TG:e.isTeamZero?wG:SG,transparent:!0,opacity:.8,side:ct,depthWrite:!1,depthTest:!1}),s=new ni(MG,EG,48),a=new we(s,i);a.renderOrder=30,this.group.add(a);const r=document.createElement("div");r.className=`sap-speed-flip-overlay-label ${e.isTeamZero?"sap-speed-flip-overlay-label-blue":"sap-speed-flip-overlay-label-orange"}`,r.textContent=`${e.playerName} speed flip ${e.qualityLabel}`,this.labelRoot.append(r);const o={marker:e,ring:a,material:i,label:r};return this.views.set(e.id,o),o}}const Nu=[{value:"big",label:"Big pads"},{value:"small",label:"Small pads"},{value:"ambiguous",label:"Ambiguous pads"}],cm=[{value:"both",label:"Both detectors"},{value:"inferred_only",label:"Inferred only"},{value:"reported_only",label:"Reported only"}],Uu=[{value:"active",label:"Active play"},{value:"inactive",label:"Inactive play"},{value:"unknown",label:"Unknown activity"}],Bu=[{value:"own",label:"Own half"},{value:"opponent",label:"Opponent half"},{value:"unknown",label:"Unknown half"}];function OG(n,e){return n===e||n==="ambiguous"}function FG(n,e){const t=e?NG(e,ve(e,"boost_pickup")):[];return t.length===0?null:t.find(i=>At(i.player_id)===n.player.id&&i.detection!=="inferred_only"&&i.frame===n.event.frame&&OG(i.pad_type,n.pad.size))??null}function NG(n,e){if(e.length>0)return e;const t=n.events?.boost_pickups;return Array.isArray(t)?t:e}function YE(n={}){let e=null,t=null,i=null,s=null,a=null,r=null;const o=new Set(Nu.map(M=>M.value)),l=new Set(cm.map(M=>M.value)),c=new Set(Uu.map(M=>M.value)),u=new Set(Bu.map(M=>M.value));let d=null,h=!1;function f(M,C,w,E){const R=document.createElement("div");R.className="boost-pickup-filter-group";const k=document.createElement("p");k.className="module-settings-group-title",k.textContent=M;const O=document.createElement("div");O.className="boost-pickup-filter-options";for(const D of C){const U=document.createElement("label");U.className="toggle";const F=document.createElement("input");F.type="checkbox",F.dataset.boostPickupFilter=E,F.dataset.boostPickupValue=D.value,F.addEventListener("change",()=>{F.checked?w.add(D.value):w.delete(D.value),_(a),n.refreshTimelineRanges?.(),n.rerenderCurrentState?.(),n.requestConfigSync?.()});const W=document.createElement("span");W.textContent=D.label,U.append(F,W),O.append(U)}return R.append(k,O),R}function p(){const M=document.createElement("div");M.className="boost-pickup-filter-group boost-pickup-filter-group-wide",i=M;const C=document.createElement("p");return C.className="module-settings-group-title",C.textContent="Player",s=document.createElement("div"),s.className="boost-pickup-filter-options",M.append(C,s),M}function g(M){if(s&&(s.replaceChildren(),i&&(i.hidden=!M||M.players.length===0),!!M))for(const C of M.players){const w=document.createElement("label");w.className="toggle";const E=document.createElement("input");E.type="checkbox",E.dataset.boostPickupPlayerId=C.id,E.addEventListener("change",()=>{d||(d=new Set(M.players.map(k=>k.id))),E.checked?d.add(C.id):d.delete(C.id),_(M),n.refreshTimelineRanges?.(),n.rerenderCurrentState?.(),n.requestConfigSync?.()});const R=document.createElement("span");R.textContent=`${C.name} (${C.isTeamZero?"Blue":"Orange"})`,w.append(E,R),s.append(w)}}function _(M){if(e){for(const C of e.querySelectorAll("input[data-boost-pickup-filter][data-boost-pickup-value]")){const w=C.dataset.boostPickupFilter,E=C.dataset.boostPickupValue;C.checked=m(w,E)}for(const C of e.querySelectorAll("input[data-boost-pickup-player-id]")){const w=C.dataset.boostPickupPlayerId;C.checked=w?d?.has(w)??!0:!1}t&&(t.textContent=v(M))}}function m(M,C){if(!C)return!1;switch(M){case"pad-type":return o.has(C);case"detection":return l.has(C);case"activity":return c.has(C);case"field-half":return u.has(C);default:return!1}}function v(M){const C=M?.players.length??0,w=d?d.size:C;if(o.size===0||l.size===0||c.size===0||u.size===0||d!==null&&d.size===0)return"Hidden";const R=[o.sizeR.value));for(const R of w)typeof R=="string"&&E.has(R)&&M.add(R)}function T(){return{padTypes:[...o],detections:[...l],activities:[...c],fieldHalves:[...u],playerIds:d?[...d]:null}}function x(M){if(!M||typeof M!="object"||Array.isArray(M))return;const C=M;b(o,Nu,C.padTypes),b(l,cm,C.detections),b(c,Uu,C.activities),b(u,Bu,C.fieldHalves),d=Array.isArray(C.playerIds)?new Set(C.playerIds.filter(w=>typeof w=="string")):null,h=a===null&&d!==null,_(a),n.refreshTimelineRanges?.(),n.rerenderCurrentState?.(),n.requestConfigSync?.()}return{setup(M){a!==M.replay&&(a=M.replay,h?h=!1:d=null),r=M.statsTimeline,_(M.replay)},teardown(){},getConfig:T,applyConfig:x,getTimelineRangeOptions(){const M={padTypes:o,detections:l,activities:c,fieldHalves:u};return d&&(M.playerIds=d),M},includePickup:y,renderSettings(M,C){if(!e){e=document.createElement("div"),e.className="boost-pickup-filter-panel";const w=document.createElement("div");w.className="boost-pickup-filter-summary",t=document.createElement("strong"),t.className="metric-readout",w.append(t);const E=document.createElement("div");E.className="boost-pickup-filter-grid",E.append(f("Pad type",Nu,o,"pad-type"),f("Activity",Uu,c,"activity"),f("Field half",Bu,u,"field-half"),p()),(C.showHeader??!1)&&e.append(w),e.append(E)}return g(M?.replay??null),_(M?.replay??null),e}}}function ai(n){return{id:n.id,label:n.label,setup(){},teardown(){},onBeforeRender(){},getTimelineEvents:n.getTimelineEvents,getTimelineRanges:n.getTimelineRanges,renderStats(e,t){const i=zt(t.statsFrameLookup,e);return i?si(i.players,s=>Tn(s.name,s.is_team_0,n.render(n.select(s),s))):""},renderFocusedPlayerStats(e,t,i){const s=wn(i,t,e);return s?n.render(n.select(s),s):""}}}function Bi(n){return n==null?"?":rf(n).toFixed(0)}function UG(n,e){const t=Bi(n);if(n==null||e==null)return t;const i=Bi(n+e);return`${t} (${i})`}function um(n){n&&typeof n=="object"&&"dispose"in n&&typeof n.dispose=="function"&&n.dispose()}function BG(n){n&&(n.removeFromParent(),n.traverse(e=>{const t="geometry"in e?e.geometry:null;um(t);const i="material"in e?e.material:null;if(Array.isArray(i))for(const s of i)um(s);else um(i)}))}function zG(){let n=0,e=null;return{acquire(t){e||(e=u5(t.player.sceneState.replayRoot,t.fieldScale)),n+=1},release(){n<=0||(n-=1,n===0&&(BG(e),e=null))}}}const Ax=zG();function nt(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function Le(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function w_(n,e=0){return Le(n,e,"%")}function jE(n,e,t=1,i=0){if(n===void 0||Number.isNaN(n))return w_(e,i);const s=Le(n,t,"s");return e===void 0||Number.isNaN(e)?s:`${s} (${w_(e,i)})`}function Ha(n,e,t=1,i=0){const s=n!==void 0&&e!==void 0&&!Number.isNaN(n)&&!Number.isNaN(e)&&e>0?n*100/e:void 0;return jE(n,s,t,i)}function bt(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function ds(n){const e=bt(n);return e===void 0?void 0:e*100}function ZE(n){return bt(n?.tracked_time)}function HG(n,e,t){const i=bt(n?.[e]);if(i!==void 0)return i;const s=ZE(n),a=bt(n?.[t]);if(!(s===void 0||s<=0||a===void 0))return a*100/s}function An(n,e,t){return jE(bt(n?.[t]),HG(n,e,t))}function Rx(n,e,t){const i=bt(n?.[e]);if(i!==void 0)return i;const s=ZE(n),a=bt(n?.[t]);if(!(s===void 0||s<=0||a===void 0))return a/s}function Px(n){return`
Most back${An(n,"percent_most_back","time_most_back")}
Most forward${An(n,"percent_most_forward","time_most_forward")}
Mid role${An(n,"percent_mid_role","time_mid_role")}
@@ -5725,59 +5790,59 @@ void main() {
Behind ball${An(n,"percent_behind_ball","time_behind_ball")}
Level with ball${An(n,"percent_level_with_ball","time_level_with_ball")}
In front of ball${An(n,"percent_in_front_of_ball","time_in_front_of_ball")}
- `}function Sx(n){return` + `}function Ix(n){return`
Defensive zone${An(n,"percent_defensive_third","time_defensive_third")}
Neutral zone${An(n,"percent_neutral_third","time_neutral_third")}
Offensive zone${An(n,"percent_offensive_third","time_offensive_third")}
Defensive half${An(n,"percent_defensive_half","time_defensive_half")}
Offensive half${An(n,"percent_offensive_half","time_offensive_half")}
-
To teammates${Le(xx(n,"average_distance_to_teammates","sum_distance_to_teammates"),0)}
-
To ball${Le(xx(n,"average_distance_to_ball","sum_distance_to_ball"),0)}
- `}function Fu(n,e){return za(bt(n?.[e]),bt(n?.active_game_time))}function dG(n){return n?n.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "):"?"}function hG(n){const e=n&&n.first_man_stint_count>0?n.time_first_man/n.first_man_stint_count:void 0;return` -
Current role${dG(n?.current_role_state)}
-
First man${Fu(n,"time_first_man")}
+
To teammates${Le(Rx(n,"average_distance_to_teammates","sum_distance_to_teammates"),0)}
+
To ball${Le(Rx(n,"average_distance_to_ball","sum_distance_to_ball"),0)}
+ `}function zu(n,e){return Ha(bt(n?.[e]),bt(n?.active_game_time))}function VG(n){return n?n.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "):"?"}function GG(n){const e=n&&n.first_man_stint_count>0?n.time_first_man/n.first_man_stint_count:void 0;return` +
Current role${VG(n?.current_role_state)}
+
First man${zu(n,"time_first_man")}
First stints${nt(n?.first_man_stint_count)}
Avg first stint${Le(e,2,"s")}
Longest first stint${Le(n?.longest_first_man_stint_time,2,"s")}
-
Second man${Fu(n,"time_second_man")}
-
Third man${Fu(n,"time_third_man")}
-
Ambiguous${Fu(n,"time_ambiguous_role")}
+
Second man${zu(n,"time_second_man")}
+
Third man${zu(n,"time_third_man")}
+
Ambiguous${zu(n,"time_ambiguous_role")}
Became first${nt(n?.became_first_man_count)}
Lost first${nt(n?.lost_first_man_count)}
- `}function fG(n){const e=n&&n.shots>0?n.goals*100/n.shots:void 0;return` + `}function $G(n){const e=n&&n.shots>0?n.goals*100/n.shots:void 0;return`
Score${nt(n?.score)}
Goals${nt(n?.goals)}
Assists${nt(n?.assists)}
Saves${nt(n?.saves)}
Shots${nt(n?.shots)}
-
Shooting %${m_(e)}
- `}function pG(n){return` +
Shooting %${w_(e)}
+ `}function WG(n){return`
Hits${nt(n?.count)}
Since last${Le(bt(n?.time_since_last_backboard),2,"s")}
- `}function mG(n){return` + `}function XG(n){return`
Count${nt(n?.count)}
Since last${Le(bt(n?.time_since_last_double_tap),2,"s")}
- `}function _G(n){const e=n&&n.completed_pass_count>0?n.total_pass_distance/n.completed_pass_count:void 0,t=n&&n.completed_pass_count>0?n.total_pass_advance/n.completed_pass_count:void 0;return` + `}function KG(n){const e=n&&n.completed_pass_count>0?n.total_pass_distance/n.completed_pass_count:void 0,t=n&&n.completed_pass_count>0?n.total_pass_advance/n.completed_pass_count:void 0;return`
Completed${nt(n?.completed_pass_count)}
Received${nt(n?.received_pass_count)}
Avg distance${Le(e,0)}
Avg advance${Le(t,0)}
Longest${Le(n?.longest_pass_distance,0)}
Since last${Le(bt(n?.time_since_last_completed_pass),2,"s")}
- `}function gG(n){const e=n&&n.count>0?n.total_ball_speed/n.count:void 0,t=n&&n.count>0?n.total_pass_distance/n.count:void 0;return` + `}function qG(n){const e=n&&n.count>0?n.total_ball_speed/n.count:void 0,t=n&&n.count>0?n.total_pass_distance/n.count:void 0;return`
Attempts${nt(n?.count)}
Avg speed${Le(e,0)}
Fastest${Le(n?.fastest_ball_speed,0)}
Avg pass distance${Le(t,0)}
Since last${Le(bt(n?.time_since_last_one_timer),2,"s")}
- `}function Tx(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0;return` + `}function Lx(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0;return`
Attempts${nt(n?.count)}
High conf${nt(n?.high_confidence_count)}
Last quality${Le(bt(n?.last_confidence),0,"%")}
Avg quality${Le(e,0,"%")}
Best quality${Le(bt(n?.best_confidence),0,"%")}
Since last${Le(bt(n?.time_since_last_ceiling_shot),2,"s")}
- `}function Mx(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0,t=ds(e),i=n&&n.count>0?n.cumulative_setup_duration/n.count:void 0,s=n&&n.count>0?n.cumulative_takeoff_to_touch_time/n.count:void 0,a=n&&n.count>0?n.cumulative_touch_height/n.count:void 0;return` + `}function kx(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0,t=ds(e),i=n&&n.count>0?n.cumulative_setup_duration/n.count:void 0,s=n&&n.count>0?n.cumulative_takeoff_to_touch_time/n.count:void 0,a=n&&n.count>0?n.cumulative_touch_height/n.count:void 0;return`
Plays${nt(n?.count)}
High conf${nt(n?.high_confidence_count)}
Last quality${Le(ds(n?.last_confidence),0,"%")}
@@ -5786,7 +5851,7 @@ void main() {
Avg takeoff${Le(s,2,"s")}
Avg height${Le(a,0)}
Since last${Le(bt(n?.time_since_last_wall_aerial),2,"s")}
- `}function Ex(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0,t=n&&n.count>0?n.cumulative_takeoff_to_shot_time/n.count:void 0,i=n&&n.count>0?n.cumulative_shot_height/n.count:void 0;return` + `}function Dx(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0,t=n&&n.count>0?n.cumulative_takeoff_to_shot_time/n.count:void 0,i=n&&n.count>0?n.cumulative_shot_height/n.count:void 0;return`
Shots${nt(n?.count)}
High conf${nt(n?.high_confidence_count)}
Last quality${Le(ds(n?.last_confidence),0,"%")}
@@ -5794,13 +5859,13 @@ void main() {
Avg takeoff${Le(t,2,"s")}
Avg height${Le(i,0)}
Since last${Le(bt(n?.time_since_last_wall_aerial_shot),2,"s")}
- `}function yG(n){const e=n&&n.carry_count>0?n.average_horizontal_gap_sum/n.carry_count:void 0;return` + `}function YG(n){const e=n&&n.carry_count>0?n.average_horizontal_gap_sum/n.carry_count:void 0;return`
Carries${nt(n?.carry_count)}
Total time${Le(n?.total_carry_time,1,"s")}
Longest${Le(n?.longest_carry_time,1,"s")}
Furthest${Le(n?.furthest_carry_distance,0)}
Avg gap${Le(e,0)}
- `}function vG(n){const e=n&&n.count>0?n.average_horizontal_gap_sum/n.count:void 0,t=n&&n.count>0?n.total_touch_count/n.count:void 0;return` + `}function jG(n){const e=n&&n.count>0?n.average_horizontal_gap_sum/n.count:void 0,t=n&&n.count>0?n.total_touch_count/n.count:void 0;return`
Air dribbles${nt(n?.count)}
Ground to air${nt(n?.ground_to_air_count)}
Wall to air${nt(n?.wall_to_air_count)}
@@ -5810,11 +5875,11 @@ void main() {
Longest${Le(n?.longest_time,1,"s")}
Furthest${Le(n?.furthest_distance,0)}
Avg gap${Le(e,0)}
- `}function bG(n){const e=n&&n.press_count>0?n.total_duration/n.press_count:void 0;return` + `}function ZG(n){const e=n&&n.press_count>0?n.total_duration/n.press_count:void 0;return`
Presses${nt(n?.press_count)}
Total time${Le(n?.total_duration,1,"s")}
Avg duration${Le(e,2,"s")}
- `}function xG(n){const e=n&&n.whiff_count>0?n.cumulative_closest_approach_distance/n.whiff_count:void 0;return` + `}function JG(n){const e=n&&n.whiff_count>0?n.cumulative_closest_approach_distance/n.whiff_count:void 0;return`
Whiffs${nt(n?.whiff_count)}
Beaten to ball${nt(n?.beaten_to_ball_count)}
Grounded${nt(n?.grounded_whiff_count)}
@@ -5824,10 +5889,10 @@ void main() {
Best closest${Le(bt(n?.best_closest_approach_distance),0)}
Avg closest${Le(e,0)}
Since last${Le(bt(n?.time_since_last_whiff),2,"s")}
- `}function wG(n){return` + `}function QG(n){return`
Inflicted${nt(n?.demos_inflicted)}
Taken${nt(n?.demos_taken)}
- `}function SG(n){const e=n&&n.bumps_inflicted>0?n.cumulative_bump_strength/n.bumps_inflicted:void 0;return` + `}function e$(n){const e=n&&n.bumps_inflicted>0?n.cumulative_bump_strength/n.bumps_inflicted:void 0;return`
Inflicted${nt(n?.bumps_inflicted)}
Taken${nt(n?.bumps_taken)}
Team inflicted${nt(n?.team_bumps_inflicted)}
@@ -5835,14 +5900,14 @@ void main() {
Last strength${Le(bt(n?.last_bump_strength),0)}
Max strength${Le(bt(n?.max_bump_strength),0)}
Avg strength${Le(e,0)}
- `}function TG(n){return` + `}function t$(n){return`
Refreshes${nt(n?.count)}
On ball${nt(n?.on_ball_count)}
- `}function MG(n){const e=n&&n.count>0?n.total_time_to_use/n.count:void 0;return` + `}function n$(n){const e=n&&n.count>0?n.total_time_to_use/n.count:void 0;return`
Confirmed${nt(n?.count)}
Avg use${Le(e,2,"s")}
Fastest use${Le(bt(n?.min_time_to_use),2,"s")}
- `}function Cx(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0,t=n&&n.count>0?n.cumulative_setup_duration/n.count:void 0,i=n&&n.count>0?n.cumulative_ball_speed_change/n.count:void 0;return` + `}function Ox(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0,t=n&&n.count>0?n.cumulative_setup_duration/n.count:void 0,i=n&&n.count>0?n.cumulative_ball_speed_change/n.count:void 0;return`
Attempts${nt(n?.count)}
High conf${nt(n?.high_confidence_count)}
Last quality${Le(bt(n?.last_confidence),0,"%")}
@@ -5850,56 +5915,56 @@ void main() {
Avg setup${Le(t,2,"s")}
Avg impulse${Le(i,0,"uu/s")}
Since last${Le(bt(n?.time_since_last_flick),2,"s")}
- `}function Ax(n){const e=n&&n.count>0?n.cumulative_quality/n.count:void 0;return` + `}function Fx(n){const e=n&&n.count>0?n.cumulative_quality/n.count:void 0;return`
Attempts${nt(n?.count)}
High conf${nt(n?.high_confidence_count)}
Last quality${Le(bt(n?.last_quality),0,"%")}
Avg quality${Le(e,0,"%")}
Best quality${Le(bt(n?.best_quality),0,"%")}
Since last${Le(bt(n?.time_since_last_speed_flip),2,"s")}
- `}function Rx(n){const e=n&&n.count>0?n.cumulative_quality/n.count:void 0,t=ds(n?.last_quality),i=ds(e),s=ds(n?.best_quality);return` + `}function Nx(n){const e=n&&n.count>0?n.cumulative_quality/n.count:void 0,t=ds(n?.last_quality),i=ds(e),s=ds(n?.best_quality);return`
Attempts${nt(n?.count)}
High conf${nt(n?.high_confidence_count)}
Last quality${Le(t,0,"%")}
Avg quality${Le(i,0,"%")}
Best quality${Le(s,0,"%")}
Since last${Le(bt(n?.time_since_last_half_flip),2,"s")}
- `}function Px(n){const e=n&&n.count>0?n.cumulative_quality/n.count:void 0,t=ds(n?.last_quality),i=ds(e),s=ds(n?.best_quality);return` + `}function Ux(n){const e=n&&n.count>0?n.cumulative_quality/n.count:void 0,t=ds(n?.last_quality),i=ds(e),s=ds(n?.best_quality);return`
Attempts${nt(n?.count)}
High conf${nt(n?.high_confidence_count)}
Last quality${Le(t,0,"%")}
Avg quality${Le(i,0,"%")}
Best quality${Le(s,0,"%")}
Since last${Le(bt(n?.time_since_last_wavedash),2,"s")}
- `}function Ix(n){const e=n&&n.tracked_time>0?Qh(n.boost_integral/n.tracked_time).toFixed(0):"?",t=bt(n?.tracked_time);return` -
Collected${oG(n?.amount_collected,n?.amount_respawned)}
-
Inactive collected${Ui(n?.amount_collected_inactive)}
-
Big pads amt${Ui(n?.amount_collected_big)}
-
Small pads amt${Ui(n?.amount_collected_small)}
-
Respawns${Ui(n?.amount_respawned)}
-
Overfill${Ui(n?.overfill_total)}
-
Used${Ui(n?.amount_used)}
-
Used ground${Ui(n?.amount_used_while_grounded)}
-
Used air${Ui(n?.amount_used_while_airborne)}
+ `}function Bx(n){const e=n&&n.tracked_time>0?rf(n.boost_integral/n.tracked_time).toFixed(0):"?",t=bt(n?.tracked_time);return` +
Collected${UG(n?.amount_collected,n?.amount_respawned)}
+
Inactive collected${Bi(n?.amount_collected_inactive)}
+
Big pads amt${Bi(n?.amount_collected_big)}
+
Small pads amt${Bi(n?.amount_collected_small)}
+
Respawns${Bi(n?.amount_respawned)}
+
Overfill${Bi(n?.overfill_total)}
+
Used${Bi(n?.amount_used)}
+
Used ground${Bi(n?.amount_used_while_grounded)}
+
Used air${Bi(n?.amount_used_while_airborne)}
Big pads${n?.big_pads_collected??"?"}
Small pads${n?.small_pads_collected??"?"}
Inactive big pads${n?.big_pads_collected_inactive??"?"}
Inactive small pads${n?.small_pads_collected_inactive??"?"}
-
Stolen${Ui(n?.amount_stolen)}
+
Stolen${Bi(n?.amount_stolen)}
Avg boost${e}
-
Time @ 0${za(bt(n?.time_zero_boost),t)}
-
Time 0-25${za(bt(n?.time_boost_0_25),t)}
-
Time 25-50${za(bt(n?.time_boost_25_50),t)}
-
Time 50-75${za(bt(n?.time_boost_50_75),t)}
-
Time 75-100${za(bt(n?.time_boost_75_100),t)}
-
Time @ 100${za(bt(n?.time_hundred_boost),t)}
- `}const __={kind:{label:"Kind",valueOrder:["control","medium_hit","hard_hit"],formatValue:n=>({control:"Control",medium_hit:"Medium",hard_hit:"Hard"})[n]??n},height_band:{label:"Height",valueOrder:["ground","low_air","high_air"],formatValue:n=>({ground:"Ground",low_air:"Low air",high_air:"High air"})[n]??n},surface:{label:"Surface",valueOrder:["ground","air","wall"],formatValue:n=>({ground:"Ground",air:"Air",wall:"Wall"})[n]??n},dodge_state:{label:"Dodge",valueOrder:["no_dodge","dodge"],formatValue:n=>({no_dodge:"No dodge",dodge:"Dodge"})[n]??n}};function EG(n){const e=new Set,t=[];for(const i of n??[])e.has(i)||(e.add(i),t.push(i));return t}function Qs(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function sm(n,e=0,t=""){return n===void 0||!Number.isFinite(n)?"?":`${n.toFixed(e)}${t}`}function Lx(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Xi(n,e){return`
${Lx(n)}${Lx(e)}
`}function CG(n,e,t){for(const i of t){const{valueOrder:s}=__[i],a=s.indexOf(n[i]),r=s.indexOf(e[i]),o=a===-1?Number.MAX_SAFE_INTEGER:a,l=r===-1?Number.MAX_SAFE_INTEGER:r;if(o!==l)return o-l}return 0}function AG(n,e){if(e.length===1){const t=e[0];return __[t].formatValue(n[t])}return e.map(t=>__[t].formatValue(n[t])).join(" / ")}function RG(n){return(n?.labeled_touch_counts?.entries??[]).map(e=>({labels:e.labels,count:e.count}))}function PG(n,e){if(e.length===0||n.length===0)return"";const t=new Map;for(const i of n){const s=new Map(i.labels.map(c=>[c.key,c.value])),a={};let r=!0;for(const c of e){const u=s.get(c);if(u===void 0){r=!1;break}a[c]=u}if(!r)continue;const o=e.map(c=>`${c}:${a[c]}`).join("|"),l=t.get(o);l?l.count+=i.count:t.set(o,{values:a,count:i.count})}return[...t.values()].sort((i,s)=>CG(i.values,s.values,e)).map(i=>Xi(AG(i.values,e),Qs(i.count))).join("")}function IG(n,e){if(!n||e.length!==1)return"";const[t]=e;if(t==="kind")return[Xi("Control",Qs(n.control_touch_count)),Xi("Medium",Qs(n.medium_hit_count)),Xi("Hard",Qs(n.hard_hit_count))].join("");if(t==="height_band"){const i=n.high_aerial_touch_count??0,s=(n.aerial_touch_count??0)-i,a=(n.touch_count??0)-(n.aerial_touch_count??0);return[Xi("Ground",Qs(a)),Xi("Low air",Qs(s)),Xi("High air",Qs(i))].join("")}return""}function Dx(n,e={}){const t=EG(e.breakdownClasses),i=RG(n),s=PG(i,t)||IG(n,t);return` - ${Xi("Touches",Qs(n?.touch_count))} - ${Xi("Ball advanced",sm(n?.total_ball_advance_distance,0," uu"))} - ${Xi("Ball traveled",sm(n?.total_ball_travel_distance,0," uu"))} - ${Xi("Ball retreated",sm(n?.total_ball_retreat_distance,0," uu"))} +
Time @ 0${Ha(bt(n?.time_zero_boost),t)}
+
Time 0-25${Ha(bt(n?.time_boost_0_25),t)}
+
Time 25-50${Ha(bt(n?.time_boost_25_50),t)}
+
Time 50-75${Ha(bt(n?.time_boost_50_75),t)}
+
Time 75-100${Ha(bt(n?.time_boost_75_100),t)}
+
Time @ 100${Ha(bt(n?.time_hundred_boost),t)}
+ `}const S_={kind:{label:"Kind",valueOrder:["control","medium_hit","hard_hit"],formatValue:n=>({control:"Control",medium_hit:"Medium",hard_hit:"Hard"})[n]??n},height_band:{label:"Height",valueOrder:["ground","low_air","high_air"],formatValue:n=>({ground:"Ground",low_air:"Low air",high_air:"High air"})[n]??n},surface:{label:"Surface",valueOrder:["ground","air","wall"],formatValue:n=>({ground:"Ground",air:"Air",wall:"Wall"})[n]??n},dodge_state:{label:"Dodge",valueOrder:["no_dodge","dodge"],formatValue:n=>({no_dodge:"No dodge",dodge:"Dodge"})[n]??n}};function i$(n){const e=new Set,t=[];for(const i of n??[])e.has(i)||(e.add(i),t.push(i));return t}function Qs(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function dm(n,e=0,t=""){return n===void 0||!Number.isFinite(n)?"?":`${n.toFixed(e)}${t}`}function zx(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Ki(n,e){return`
${zx(n)}${zx(e)}
`}function s$(n,e,t){for(const i of t){const{valueOrder:s}=S_[i],a=s.indexOf(n[i]),r=s.indexOf(e[i]),o=a===-1?Number.MAX_SAFE_INTEGER:a,l=r===-1?Number.MAX_SAFE_INTEGER:r;if(o!==l)return o-l}return 0}function a$(n,e){if(e.length===1){const t=e[0];return S_[t].formatValue(n[t])}return e.map(t=>S_[t].formatValue(n[t])).join(" / ")}function r$(n){return(n?.labeled_touch_counts?.entries??[]).map(e=>({labels:e.labels,count:e.count}))}function o$(n,e){if(e.length===0||n.length===0)return"";const t=new Map;for(const i of n){const s=new Map(i.labels.map(c=>[c.key,c.value])),a={};let r=!0;for(const c of e){const u=s.get(c);if(u===void 0){r=!1;break}a[c]=u}if(!r)continue;const o=e.map(c=>`${c}:${a[c]}`).join("|"),l=t.get(o);l?l.count+=i.count:t.set(o,{values:a,count:i.count})}return[...t.values()].sort((i,s)=>s$(i.values,s.values,e)).map(i=>Ki(a$(i.values,e),Qs(i.count))).join("")}function l$(n,e){if(!n||e.length!==1)return"";const[t]=e;if(t==="kind")return[Ki("Control",Qs(n.control_touch_count)),Ki("Medium",Qs(n.medium_hit_count)),Ki("Hard",Qs(n.hard_hit_count))].join("");if(t==="height_band"){const i=n.high_aerial_touch_count??0,s=(n.aerial_touch_count??0)-i,a=(n.touch_count??0)-(n.aerial_touch_count??0);return[Ki("Ground",Qs(a)),Ki("Low air",Qs(s)),Ki("High air",Qs(i))].join("")}return""}function Hx(n,e={}){const t=i$(e.breakdownClasses),i=r$(n),s=o$(i,t)||l$(n,t);return` + ${Ki("Touches",Qs(n?.touch_count))} + ${Ki("Ball advanced",dm(n?.total_ball_advance_distance,0," uu"))} + ${Ki("Ball traveled",dm(n?.total_ball_travel_distance,0," uu"))} + ${Ki("Ball retreated",dm(n?.total_ball_retreat_distance,0," uu"))} ${s} - `}const g_="subtr-actor:touch-color-modes-change",LG=[{title:"Team",mode:"team"},{title:"Intention",mode:"intention"},{title:"Hit strength",mode:"kind"},{title:"Height",mode:"height_band"},{title:"Surface",mode:"surface"},{title:"Dodge",mode:"dodge_state"},{title:"Flags",mode:"flag"}];function DG(n){return LG.find(e=>e.title===n)?.mode??"team"}function kG(n){return`#${n.toString(16).padStart(6,"0")}`}function VE(n,e){n.replaceChildren();const t=ho(e),i=new Set(t),s=document.createElement("div");s.className="touch-color-legend-explainer";const a=document.createElement("span");a.textContent="Toggle sections to add or remove rings";const r=document.createElement("span");r.textContent="The outermost enabled ring sets the label tint",s.append(a,r),n.append(s);for(const o of BH){const l=DG(o.title),c=i.has(l),u=document.createElement("section");u.className="touch-color-legend-group",u.dataset.active=c?"true":"false";const d=document.createElement("button");d.type="button",d.className="touch-color-legend-heading",d.dataset.colorMode=l,d.dataset.active=c?"true":"false",d.textContent=o.title,d.addEventListener("click",()=>{const f=new Set(i);f.has(l)?f.delete(l):f.add(l);const p=NH.filter(g=>f.has(g));n.dispatchEvent(new CustomEvent(g_,{bubbles:!0,detail:{colorModes:p}})),VE(n,p)});const h=document.createElement("div");h.className="touch-color-legend-list";for(const f of o.entries){const p=document.createElement("div");p.className="touch-color-legend-item";const g=document.createElement("span");g.className="touch-color-legend-swatch",g.style.background=kG(f.color);const _=document.createElement("span");_.textContent=f.label,p.append(g,_),h.append(p)}u.append(d,h),n.append(u)}}function OG(n){let e=null,t=5,i="advancement",s=["team"],a=null,r=null,o=null,l=null,c=null;const u=new Set,d=["kind","height_band","surface","dodge_state"];return{id:"touch",label:"Touch",setup(g){e=new ZH(g.player.sceneState,g.player.container,g.replay,g.statsTimeline,{mode:i,colorModes:s}),e.setDecaySeconds(t),c=_=>{if(!(_ instanceof CustomEvent))return;const m=_.detail?.colorModes;Array.isArray(m)&&p(m.filter(ed))},window.addEventListener(g_,c),h()},teardown(){c&&(window.removeEventListener(g_,c),c=null),e?.dispose(),e=null},onBeforeRender(g){e?.update(g.currentTime)},getTimelineEvents(g){return I5(g.statsTimeline,g.replay)},getConfig(){return{decaySeconds:t,overlayMode:i,overlayColorModes:s,breakdownClasses:f()}},applyConfig(g){if(g&&typeof g=="object"&&!Array.isArray(g)){const _=g;if(typeof _.decaySeconds=="number"&&Number.isFinite(_.decaySeconds)&&(t=Math.max(1,Math.min(10,_.decaySeconds)),e?.setDecaySeconds(t)),(_.overlayMode==="markers"||_.overlayMode==="advancement")&&(i=_.overlayMode,e?.setMode(i)),Array.isArray(_.overlayColorModes)?(s=ho(_.overlayColorModes.filter(ed)),e?.setColorModes(s)):ed(_.overlayColorMode)&&(s=ho(_.overlayColorMode),e?.setColorModes(s)),u.clear(),Array.isArray(_.breakdownClasses))for(const m of _.breakdownClasses)d.includes(m)&&u.add(m)}h(),n.rerenderCurrentState()},renderStats(g,_){const m=zt(_.statsFrameLookup,g);return m?si(m.players,v=>Tn(v.name,v.is_team_0,Dx(v.touch,{breakdownClasses:f()}),v.touch?.is_last_touch?'Last Touch':"")):""},renderFocusedPlayerStats(g,_,m){const v=wn(m,_,g);return v?Dx(v.touch,{breakdownClasses:f()}):""},renderSettings(){if(!a){a=document.createElement("div"),a.className="module-settings-card";const g=document.createElement("div");g.className="module-settings-header";const _=document.createElement("div"),m=document.createElement("p");m.className="module-settings-eyebrow",m.textContent="Touch markers";const v=document.createElement("h3");v.textContent="Touch decay",_.append(m,v),r=document.createElement("strong"),r.className="metric-readout",g.append(_,r);const y=document.createElement("label"),b=document.createElement("span");b.className="label",b.textContent="Keep each marker visible after the touch";const T=document.createElement("input");T.type="range",T.min="1",T.max="10",T.step="0.5",T.value=`${t}`,T.addEventListener("input",()=>{const H=Number(T.value);t=Number.isFinite(H)?Math.max(1,Math.min(10,H)):t,e?.setDecaySeconds(t),h(t),n.requestConfigSync?.()}),y.append(b,T);const x=document.createElement("div");x.className="module-settings-subgroup";const M=document.createElement("div");M.className="module-settings-header";const C=document.createElement("div"),w=document.createElement("p");w.className="module-settings-eyebrow",w.textContent="Overlay";const E=document.createElement("h3");E.textContent="Touch mode",C.append(w,E),o=document.createElement("strong"),o.className="metric-readout",M.append(C,o);const R=document.createElement("div");R.className="module-settings-options";for(const H of[{mode:"markers",label:"Markers"},{mode:"advancement",label:"Advancement"}]){const ne=document.createElement("label");ne.className="toggle";const oe=document.createElement("input");oe.type="radio",oe.name="touch-overlay-mode",oe.dataset.overlayMode=H.mode,oe.addEventListener("change",()=>{oe.checked&&(i=H.mode,e?.setMode(i),h(),n.requestConfigSync?.())});const pe=document.createElement("span");pe.textContent=H.label,ne.append(oe,pe),R.append(ne)}x.append(M,R);const D=document.createElement("div");D.className="module-settings-subgroup";const O=document.createElement("div");O.className="module-settings-header";const k=document.createElement("div"),U=document.createElement("p");U.className="module-settings-eyebrow",U.textContent="Stat display";const F=document.createElement("h3");F.textContent="Touch breakdown",k.append(U,F),l=document.createElement("strong"),l.className="metric-readout",O.append(k,l);const W=document.createElement("div");W.className="module-settings-options";for(const H of[{className:"kind",label:"Kind"},{className:"height_band",label:"Height"},{className:"surface",label:"Surface"},{className:"dodge_state",label:"Dodge"}]){const ne=document.createElement("label");ne.className="toggle";const oe=document.createElement("input");oe.type="checkbox",oe.dataset.breakdownClass=H.className,oe.addEventListener("change",()=>{oe.checked?u.add(H.className):u.delete(H.className),h(),n.rerenderCurrentState(),n.requestConfigSync?.()});const pe=document.createElement("span");pe.textContent=H.label,ne.append(oe,pe),W.append(ne)}D.append(O,W),a.append(g,y,x,D)}return h(),a}};function h(g){if(!a)return;const _=g??t,m=a.querySelector("input");m instanceof HTMLInputElement&&(m.value=`${_}`),r&&(r.textContent=`${_.toFixed(1)}s`);for(const v of a.querySelectorAll("input[data-overlay-mode]"))v.checked=v.dataset.overlayMode===i;o&&(o.textContent=i==="advancement"?"Advancement":"Markers");for(const v of a.querySelectorAll("input[data-breakdown-class]")){const y=v.dataset.breakdownClass;v.checked=y?u.has(y):!1}if(l){const v=f();l.textContent=v.length>0?v.map(y=>({kind:"Kind",height_band:"Height",surface:"Surface",dodge_state:"Dodge"})[y]).join(" + "):"Total only"}}function f(){return d.filter(g=>u.has(g))}function p(g){s=ho(g),e?.setColorModes(s),h(),n.requestConfigSync?.()}}function FG(n,e=BE({refreshTimelineRanges:n.refreshTimelineRanges,rerenderCurrentState:n.rerenderCurrentState})){return{id:"boost",label:"Boost",setup(t){e.setup(t)},teardown(){e.teardown()},onBeforeRender(){},getTimelineRanges(t){return m4(t.statsTimeline,t.replay,e.getTimelineRangeOptions())},getConfig(){return e.getConfig()},applyConfig(t){e.applyConfig(t)},includeBoostPickupAnimationPickup(t){return e.includePickup(t)},renderStats(t,i){const s=zt(i.statsFrameLookup,t);return s?si(s.players,a=>Tn(a.name,a.is_team_0,Ix(a.boost))):""},renderFocusedPlayerStats(t,i,s){const a=wn(s,i,t);return a?Ix(a.boost):""},renderSettings(t){return e.renderSettings(t,{showHeader:!0})}}}function NG(){return ai({id:"core",label:"Core",select:n=>n.core,render:n=>fG(n)})}function UG(){return ai({id:"backboard",label:"Backboard",select:n=>n.backboard,render:n=>pG(n),getTimelineEvents(n){return L5(n.statsTimeline,n.replay)}})}function BG(){let n=null;return{id:"ceiling-shot",label:"Ceiling Shot",setup(e){n=new w5(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},renderStats(e,t){const i=zt(t.statsFrameLookup,e);return i?si(i.players,s=>Tn(s.name,s.is_team_0,Tx(s.ceiling_shot),s.ceiling_shot?.is_last_ceiling_shot?'Last Ceiling Shot':"")):""},renderFocusedPlayerStats(e,t,i){const s=wn(i,t,e);return s?Tx(s.ceiling_shot):""}}}function zG(){return{id:"wall-aerial",label:"Wall-to-Air Setup",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Mx(i.wall_aerial),i.wall_aerial?.is_last_wall_aerial?'Last Wall-to-Air Setup':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Mx(i.wall_aerial):""}}}function HG(){return{id:"wall-aerial-shot",label:"Wall Shot",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Ex(i.wall_aerial_shot),i.wall_aerial_shot?.is_last_wall_aerial_shot?'Last Wall Shot':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Ex(i.wall_aerial_shot):""}}}function VG(){return ai({id:"ball-carry",label:"Ball Carry",select:n=>n.ball_carry,render:n=>yG(n)})}function GG(){return ai({id:"air-dribble",label:"Air Dribble",select:n=>n.air_dribble,render:n=>vG(n)})}function $G(){return ai({id:"dodge-reset",label:"Dodge Refresh",select:n=>n.dodge_reset,render:n=>TG(n)})}function WG(){return ai({id:"flip-reset",label:"Flip Reset",select:n=>n.flip_reset,render:n=>MG(n)})}function XG(){return ai({id:"double-tap",label:"Double Tap",select:n=>n.double_tap,render:n=>mG(n)})}function KG(){return ai({id:"pass",label:"Pass",select:n=>n.pass,render:n=>_G(n)})}function qG(){return ai({id:"one-timer",label:"One-timer",select:n=>n.one_timer,render:n=>gG(n)})}function YG(){return{id:"flick",label:"Flick",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Cx(i.flick),i.flick?.is_last_flick?'Last Flick':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Cx(i.flick):""}}}function jG(){let n=null;return{id:"speed-flip",label:"Speed Flip",setup(e){n=new iG(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},renderStats(e,t){const i=zt(t.statsFrameLookup,e);return i?si(i.players,s=>Tn(s.name,s.is_team_0,Ax(s.speed_flip),s.speed_flip?.is_last_speed_flip?'Last Speed Flip':"")):""},renderFocusedPlayerStats(e,t,i){const s=wn(i,t,e);return s?Ax(s.speed_flip):""}}}function ZG(){let n=null;return{id:"dodge",label:"Dodge",setup(e){n=new $4(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},getTimelineEvents(e){return W5(e.statsTimeline,e.replay)},renderStats(e,t){const i=new Map;for(const a of t.replay.players)i.set(a.id,{name:a.name,isTeamZero:a.isTeamZero,count:0});for(const a of ve(t.statsTimeline,"dodge")){const r=At(a.player),o=t.replay.players.find(c=>c.id===r)??null,l=i.get(r)??{name:o?.name??r,isTeamZero:a.is_team_0,count:0};l.count+=1,i.set(r,l)}const s=[...i.values()].filter(a=>a.count>0);return s.length===0?"":`
${[!0,!1].map(a=>{const r=s.filter(l=>l.isTeamZero===a);if(r.length===0)return"";const o=a?"Blue":"Orange";return`
+ `}const T_="subtr-actor:touch-color-modes-change",c$=[{title:"Team",mode:"team"},{title:"Intention",mode:"intention"},{title:"Hit strength",mode:"kind"},{title:"Height",mode:"height_band"},{title:"Surface",mode:"surface"},{title:"Dodge",mode:"dodge_state"},{title:"Flags",mode:"flag"}];function u$(n){return c$.find(e=>e.title===n)?.mode??"team"}function d$(n){return`#${n.toString(16).padStart(6,"0")}`}function JE(n,e){n.replaceChildren();const t=po(e),i=new Set(t),s=document.createElement("div");s.className="touch-color-legend-explainer";const a=document.createElement("span");a.textContent="Toggle sections to add or remove rings";const r=document.createElement("span");r.textContent="The outermost enabled ring sets the label tint",s.append(a,r),n.append(s);for(const o of _V){const l=u$(o.title),c=i.has(l),u=document.createElement("section");u.className="touch-color-legend-group",u.dataset.active=c?"true":"false";const d=document.createElement("button");d.type="button",d.className="touch-color-legend-heading",d.dataset.colorMode=l,d.dataset.active=c?"true":"false",d.textContent=o.title,d.addEventListener("click",()=>{const f=new Set(i);f.has(l)?f.delete(l):f.add(l);const p=pV.filter(g=>f.has(g));n.dispatchEvent(new CustomEvent(T_,{bubbles:!0,detail:{colorModes:p}})),JE(n,p)});const h=document.createElement("div");h.className="touch-color-legend-list";for(const f of o.entries){const p=document.createElement("div");p.className="touch-color-legend-item";const g=document.createElement("span");g.className="touch-color-legend-swatch",g.style.background=d$(f.color);const _=document.createElement("span");_.textContent=f.label,p.append(g,_),h.append(p)}u.append(d,h),n.append(u)}}function h$(n){let e=null,t=5,i="advancement",s=["team"],a=null,r=null,o=null,l=null,c=null;const u=new Set,d=["kind","height_band","surface","dodge_state"];return{id:"touch",label:"Touch",setup(g){e=new AV(g.player.sceneState,g.player.container,g.replay,g.statsTimeline,{mode:i,colorModes:s}),e.setDecaySeconds(t),c=_=>{if(!(_ instanceof CustomEvent))return;const m=_.detail?.colorModes;Array.isArray(m)&&p(m.filter(ad))},window.addEventListener(T_,c),h()},teardown(){c&&(window.removeEventListener(T_,c),c=null),e?.dispose(),e=null},onBeforeRender(g){e?.update(g.currentTime)},getTimelineEvents(g){return l4(g.statsTimeline,g.replay)},getConfig(){return{decaySeconds:t,overlayMode:i,overlayColorModes:s,breakdownClasses:f()}},applyConfig(g){if(g&&typeof g=="object"&&!Array.isArray(g)){const _=g;if(typeof _.decaySeconds=="number"&&Number.isFinite(_.decaySeconds)&&(t=Math.max(1,Math.min(10,_.decaySeconds)),e?.setDecaySeconds(t)),(_.overlayMode==="markers"||_.overlayMode==="advancement")&&(i=_.overlayMode,e?.setMode(i)),Array.isArray(_.overlayColorModes)?(s=po(_.overlayColorModes.filter(ad)),e?.setColorModes(s)):ad(_.overlayColorMode)&&(s=po(_.overlayColorMode),e?.setColorModes(s)),u.clear(),Array.isArray(_.breakdownClasses))for(const m of _.breakdownClasses)d.includes(m)&&u.add(m)}h(),n.rerenderCurrentState()},renderStats(g,_){const m=zt(_.statsFrameLookup,g);return m?si(m.players,v=>Tn(v.name,v.is_team_0,Hx(v.touch,{breakdownClasses:f()}),v.touch?.is_last_touch?'Last Touch':"")):""},renderFocusedPlayerStats(g,_,m){const v=wn(m,_,g);return v?Hx(v.touch,{breakdownClasses:f()}):""},renderSettings(){if(!a){a=document.createElement("div"),a.className="module-settings-card";const g=document.createElement("div");g.className="module-settings-header";const _=document.createElement("div"),m=document.createElement("p");m.className="module-settings-eyebrow",m.textContent="Touch markers";const v=document.createElement("h3");v.textContent="Touch decay",_.append(m,v),r=document.createElement("strong"),r.className="metric-readout",g.append(_,r);const y=document.createElement("label"),b=document.createElement("span");b.className="label",b.textContent="Keep each marker visible after the touch";const T=document.createElement("input");T.type="range",T.min="1",T.max="10",T.step="0.5",T.value=`${t}`,T.addEventListener("input",()=>{const H=Number(T.value);t=Number.isFinite(H)?Math.max(1,Math.min(10,H)):t,e?.setDecaySeconds(t),h(t),n.requestConfigSync?.()}),y.append(b,T);const x=document.createElement("div");x.className="module-settings-subgroup";const M=document.createElement("div");M.className="module-settings-header";const C=document.createElement("div"),w=document.createElement("p");w.className="module-settings-eyebrow",w.textContent="Overlay";const E=document.createElement("h3");E.textContent="Touch mode",C.append(w,E),o=document.createElement("strong"),o.className="metric-readout",M.append(C,o);const R=document.createElement("div");R.className="module-settings-options";for(const H of[{mode:"markers",label:"Markers"},{mode:"advancement",label:"Advancement"}]){const ne=document.createElement("label");ne.className="toggle";const oe=document.createElement("input");oe.type="radio",oe.name="touch-overlay-mode",oe.dataset.overlayMode=H.mode,oe.addEventListener("change",()=>{oe.checked&&(i=H.mode,e?.setMode(i),h(),n.requestConfigSync?.())});const pe=document.createElement("span");pe.textContent=H.label,ne.append(oe,pe),R.append(ne)}x.append(M,R);const k=document.createElement("div");k.className="module-settings-subgroup";const O=document.createElement("div");O.className="module-settings-header";const D=document.createElement("div"),U=document.createElement("p");U.className="module-settings-eyebrow",U.textContent="Stat display";const F=document.createElement("h3");F.textContent="Touch breakdown",D.append(U,F),l=document.createElement("strong"),l.className="metric-readout",O.append(D,l);const W=document.createElement("div");W.className="module-settings-options";for(const H of[{className:"kind",label:"Kind"},{className:"height_band",label:"Height"},{className:"surface",label:"Surface"},{className:"dodge_state",label:"Dodge"}]){const ne=document.createElement("label");ne.className="toggle";const oe=document.createElement("input");oe.type="checkbox",oe.dataset.breakdownClass=H.className,oe.addEventListener("change",()=>{oe.checked?u.add(H.className):u.delete(H.className),h(),n.rerenderCurrentState(),n.requestConfigSync?.()});const pe=document.createElement("span");pe.textContent=H.label,ne.append(oe,pe),W.append(ne)}k.append(O,W),a.append(g,y,x,k)}return h(),a}};function h(g){if(!a)return;const _=g??t,m=a.querySelector("input");m instanceof HTMLInputElement&&(m.value=`${_}`),r&&(r.textContent=`${_.toFixed(1)}s`);for(const v of a.querySelectorAll("input[data-overlay-mode]"))v.checked=v.dataset.overlayMode===i;o&&(o.textContent=i==="advancement"?"Advancement":"Markers");for(const v of a.querySelectorAll("input[data-breakdown-class]")){const y=v.dataset.breakdownClass;v.checked=y?u.has(y):!1}if(l){const v=f();l.textContent=v.length>0?v.map(y=>({kind:"Kind",height_band:"Height",surface:"Surface",dodge_state:"Dodge"})[y]).join(" + "):"Total only"}}function f(){return d.filter(g=>u.has(g))}function p(g){s=po(g),e?.setColorModes(s),h(),n.requestConfigSync?.()}}function f$(n,e=YE({refreshTimelineRanges:n.refreshTimelineRanges,rerenderCurrentState:n.rerenderCurrentState})){return{id:"boost",label:"Boost",setup(t){e.setup(t)},teardown(){e.teardown()},onBeforeRender(){},getTimelineRanges(t){return X4(t.statsTimeline,t.replay,e.getTimelineRangeOptions())},getConfig(){return e.getConfig()},applyConfig(t){e.applyConfig(t)},includeBoostPickupAnimationPickup(t){return e.includePickup(t)},renderStats(t,i){const s=zt(i.statsFrameLookup,t);return s?si(s.players,a=>Tn(a.name,a.is_team_0,Bx(a.boost))):""},renderFocusedPlayerStats(t,i,s){const a=wn(s,i,t);return a?Bx(a.boost):""},renderSettings(t){return e.renderSettings(t,{showHeader:!0})}}}function p$(){return ai({id:"core",label:"Core",select:n=>n.core,render:n=>$G(n)})}function m$(){return ai({id:"backboard",label:"Backboard",select:n=>n.backboard,render:n=>WG(n),getTimelineEvents(n){return c4(n.statsTimeline,n.replay)}})}function _$(){let n=null;return{id:"ceiling-shot",label:"Ceiling Shot",setup(e){n=new Q5(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},renderStats(e,t){const i=zt(t.statsFrameLookup,e);return i?si(i.players,s=>Tn(s.name,s.is_team_0,Lx(s.ceiling_shot),s.ceiling_shot?.is_last_ceiling_shot?'Last Ceiling Shot':"")):""},renderFocusedPlayerStats(e,t,i){const s=wn(i,t,e);return s?Lx(s.ceiling_shot):""}}}function g$(){return{id:"wall-aerial",label:"Wall-to-Air Setup",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,kx(i.wall_aerial),i.wall_aerial?.is_last_wall_aerial?'Last Wall-to-Air Setup':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?kx(i.wall_aerial):""}}}function y$(){return{id:"wall-aerial-shot",label:"Wall Shot",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Dx(i.wall_aerial_shot),i.wall_aerial_shot?.is_last_wall_aerial_shot?'Last Wall Shot':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Dx(i.wall_aerial_shot):""}}}function v$(){return ai({id:"ball-carry",label:"Ball Carry",select:n=>n.ball_carry,render:n=>YG(n)})}function b$(){return ai({id:"air-dribble",label:"Air Dribble",select:n=>n.air_dribble,render:n=>jG(n)})}function x$(){return ai({id:"dodge-reset",label:"Dodge Refresh",select:n=>n.dodge_reset,render:n=>t$(n)})}function w$(){return ai({id:"flip-reset",label:"Flip Reset",select:n=>n.flip_reset,render:n=>n$(n)})}function S$(){return ai({id:"double-tap",label:"Double Tap",select:n=>n.double_tap,render:n=>XG(n)})}function T$(){return ai({id:"pass",label:"Pass",select:n=>n.pass,render:n=>KG(n)})}function M$(){return ai({id:"one-timer",label:"One-timer",select:n=>n.one_timer,render:n=>qG(n)})}function E$(){return{id:"flick",label:"Flick",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Ox(i.flick),i.flick?.is_last_flick?'Last Flick':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Ox(i.flick):""}}}function C$(){let n=null;return{id:"speed-flip",label:"Speed Flip",setup(e){n=new DG(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},renderStats(e,t){const i=zt(t.statsFrameLookup,e);return i?si(i.players,s=>Tn(s.name,s.is_team_0,Fx(s.speed_flip),s.speed_flip?.is_last_speed_flip?'Last Speed Flip':"")):""},renderFocusedPlayerStats(e,t,i){const s=wn(i,t,e);return s?Fx(s.speed_flip):""}}}function A$(){let n=null;return{id:"dodge",label:"Dodge",setup(e){n=new xG(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},getTimelineEvents(e){return w4(e.statsTimeline,e.replay)},renderStats(e,t){const i=new Map;for(const a of t.replay.players)i.set(a.id,{name:a.name,isTeamZero:a.isTeamZero,count:0});for(const a of ve(t.statsTimeline,"dodge")){const r=At(a.player),o=t.replay.players.find(c=>c.id===r)??null,l=i.get(r)??{name:o?.name??r,isTeamZero:a.is_team_0,count:0};l.count+=1,i.set(r,l)}const s=[...i.values()].filter(a=>a.count>0);return s.length===0?"":`
${[!0,!1].map(a=>{const r=s.filter(l=>l.isTeamZero===a);if(r.length===0)return"";const o=a?"Blue":"Orange";return`

${o} team

${r.length} player${r.length===1?"":"s"} @@ -5907,7 +5972,7 @@ void main() {
${r.map(l=>Tn(l.name,l.isTeamZero,`
Events${l.count}
`)).join("")}
-
`}).join("")}
`},renderFocusedPlayerStats(e,t,i){return`
Events${ve(i.statsTimeline,"dodge").filter(a=>At(a.player)===e).length}
`}}}function JG(){return{id:"half-flip",label:"Half Flip",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Rx(i.half_flip),i.half_flip?.is_last_half_flip?'Last Half Flip':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Rx(i.half_flip):""}}}function QG(){return{id:"wavedash",label:"Wavedash",setup(){},teardown(){},onBeforeRender(){},getTimelineEvents(n){return K5(n.statsTimeline,n.replay)},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Px(i.wavedash),i.wavedash?.is_last_wavedash?'Last Wavedash':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Px(i.wavedash):""}}}function e$(){return ai({id:"whiff",label:"Whiff",select:n=>n.whiff,render:n=>xG(n),getTimelineEvents(n){return J5(n.statsTimeline,n.replay)}})}function t$(n){let e=null,t=null;const i=new Set,s=["speed_band","height_band"];return{id:"movement",label:"Movement",setup(){a()},teardown(){},onBeforeRender(){},getConfig(){return{breakdownClasses:r()}},applyConfig(o){if(i.clear(),o&&typeof o=="object"&&!Array.isArray(o)){const l=o.breakdownClasses;if(Array.isArray(l))for(const c of l)s.includes(c)&&i.add(c)}a(),n.rerenderCurrentState()},renderStats(o,l){const c=zt(l.statsFrameLookup,o);return c?si(c.players,u=>Tn(u.name,u.is_team_0,gx(u.movement,{breakdownClasses:r()}))):""},renderFocusedPlayerStats(o,l,c){const u=wn(c,l,o);return u?gx(u.movement,{breakdownClasses:r()}):""},renderSettings(){if(!e){e=document.createElement("div"),e.className="module-settings-card";const o=document.createElement("div");o.className="module-settings-header";const l=document.createElement("div"),c=document.createElement("p");c.className="module-settings-eyebrow",c.textContent="Stat display";const u=document.createElement("h3");u.textContent="Movement breakdown",l.append(c,u),t=document.createElement("strong"),t.className="metric-readout",o.append(l,t);const d=document.createElement("div");d.className="module-settings-options";for(const h of[{className:"speed_band",label:"Speed band"},{className:"height_band",label:"Height band"}]){const f=document.createElement("label");f.className="toggle";const p=document.createElement("input");p.type="checkbox",p.dataset.breakdownClass=h.className,p.addEventListener("change",()=>{p.checked?i.add(h.className):i.delete(h.className),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const g=document.createElement("span");g.textContent=h.label,f.append(p,g),d.append(f)}e.append(o,d)}return a(),e}};function a(){if(e){for(const o of e.querySelectorAll("input[data-breakdown-class]")){const l=o.dataset.breakdownClass;o.checked=l?i.has(l):!1}if(t){const o=r();t.textContent=o.length>0?o.map(l=>({speed_band:"Speed band",height_band:"Height band"})[l]).join(" + "):"Total only"}}}function r(){return s.filter(o=>i.has(o))}}function n$(){return ai({id:"powerslide",label:"Powerslide",select:n=>n.powerslide,render:n=>bG(n),getTimelineEvents(n){return G5(n.statsTimeline,n.replay)}})}function i$(){return ai({id:"rotation",label:"Rotation",select:n=>n.rotation,render:n=>hG(n)})}function s$(){return ai({id:"demo",label:"Demo",select:n=>n.demo,render:n=>wG(n)})}function a$(){return ai({id:"bump",label:"Bump",select:n=>n.bump,render:n=>SG(n),getTimelineEvents(n){return q5(n.statsTimeline,n.replay)}})}function r$(){let n=null,e=1;return{id:OE,label:"Relative Positioning",setup(t){e=t.fieldScale,n=new PV(t.player.sceneState.replayRoot,t.replay,e)},teardown(){n?.dispose(),n=null},onBeforeRender(t){n?.update(t,e)},renderStats(t,i){const s=zt(i.statsFrameLookup,t);return s?si(s.players,a=>{const r=w4(i.replay,At(a.player_id),t),o=x4[r];return Tn(a.name,a.is_team_0,wx(a.positioning),`${o}`)}):""},renderFocusedPlayerStats(t,i,s){const a=wn(s,i,t);return a?wx(a.positioning):""}}}function o$(){return{id:"absolute-positioning",label:"Absolute Positioning",setup(n){bx.acquire(n)},teardown(){bx.release()},onBeforeRender(){},getTimelineRanges(n){return b4(n.statsTimeline,n.replay)},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Sx(i.positioning))):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Sx(i.positioning):""}}}function l$(n,e={}){return[NG(),UG(),BG(),zG(),HG(),XG(),qG(),KG(),S4(n),T4(),M4(),E4(),C4(),r$(),o$(),i$(),ZG(),jG(),JG(),QG(),OG(n),e$(),YG(),$G(),WG(),GG(),FG(n,e.boostPickupFilters),VG(),t$(n),n$(),s$(),a$()]}const c$=new Set(["player_id","name","is_team_0"]),u$=["is_last_","time_since_last_","frames_since_last_"];function d$(n){return n===null||typeof n=="number"||typeof n=="string"||typeof n=="boolean"||Array.isArray(n)}function h$(n,e){let t=n;for(const i of e){if(!t||typeof t!="object"||Array.isArray(t))return;t=t[i]}return t}function f$(n){return n==null?"--":typeof n=="number"?Number.isFinite(n)?Number.isInteger(n)?`${n}`:`${Number(n.toFixed(3))}`:"--":typeof n=="boolean"?n?"true":"false":Array.isArray(n)?n.length===0?"[]":JSON.stringify(n):`${n}`}function p$(n,e){if(u$.some(a=>n.startsWith(a)))return!0;const t=n.match(/^last_(.+)_time$/),i=n.match(/^last_(.+)_frame$/),s=t?.[1]??i?.[1];return s?`is_last_${s}`in e||`time_since_last_${s}`in e||`frames_since_last_${s}`in e:!1}function y_(n,e,t,i){if(!n||typeof n!="object"||Array.isArray(n))return;const s=n;for(const[a,r]of Object.entries(s)){if(e==="player"&&t.length===0&&c$.has(a)||p$(a,s))continue;const o=[...t,a];if(d$(r)){const l=`${e}:${o.join(".")}`;i.push({id:l,label:o.join("."),category:o[0]??e,scope:e,path:o,read(c){return h$(c,o)},format:f$});continue}y_(r,e,o,i)}}function m$(n){const e=new Set;return n.filter(t=>e.has(t.id)?!1:(e.add(t.id),!0))}function _$(n,e){const t=[];return n&&y_(n,"player",[],t),e&&y_(e,"team",[],t),m$(t).sort((i,s)=>i.label.localeCompare(s.label))}function g$(){return _$(eE(),Yl())}function Jl(n){return g$()}function GE(n){return n.toLowerCase().replace(/[_/.-]+/g," ").replace(/\s+/g," ").trim()}function y$(n){return GE(n).split(" ").filter(Boolean)}function v$(n,e){const t=y$(e);if(t.length===0)return 0;const i=GE([n.scope,n.category,n.label,n.id,...n.path].join(" "));let s=0;for(const a of t){const r=i.indexOf(a);if(r<0)return null;s+=r}return s+i.length/1e3}function b$(n,e){return n.map((t,i)=>({definition:t,index:i,score:v$(t,e)})).filter(t=>t.score!==null).sort((t,i)=>t.score-i.score||t.index-i.index).map(t=>t.definition)}function ss(n){if(!Number.isFinite(n))return"--";const e=Math.floor(Math.max(0,n)/60),t=Math.max(0,n)-e*60;return`${e}:${t.toFixed(1).padStart(4,"0")}`}class x${constructor(e){this.options=e}statsWindows=new Map;nextStatsWindowId=1;getConfigs(){return[...this.statsWindows.values()].map(e=>({id:e.id,kind:e.kind,placement:this.options.readWindowPlacement(e.element),playerId:e.playerId,team:e.team,entries:e.entries.map(t=>({statId:t.statId,targetId:t.targetId}))}))}clear(){for(const e of this.statsWindows.values())e.element.remove();this.statsWindows.clear(),this.nextStatsWindowId=1}replaceFromConfig(e){this.clear();for(const t of e)this.create(t.kind,t)}render(e=this.options.getReplayPlayer()?.getState().frameIndex??0,t={}){for(const i of this.statsWindows.values())t.preserveOpenPickers&&(i.pickerOpen||i.element.contains(document.activeElement))||this.renderStatsWindow(i,e)}create(e,t){const i=t?.id??`stats-${this.nextStatsWindowId++}`,s=Number.parseInt(i.replace(/^stats-/,""),10);Number.isFinite(s)&&(this.nextStatsWindowId=Math.max(this.nextStatsWindowId,s+1));const{x:a,y:r}=this.getStatsWindowDefaultPosition(),o=document.createElement("section");o.className="stats-window",o.dataset.windowId=i,o.style.setProperty("--window-x",`${a}px`),o.style.setProperty("--window-y",`${r}px`),t&&this.options.applyWindowPlacement(o,t.placement);const l=document.createElement("header");l.className="stats-window-header";const c=document.createElement("div");c.className="stats-window-actions";const u=document.createElement("button");if(u.type="button",u.className="stats-window-action",u.textContent="Hide",c.append(u),this.hasStatsWindowScopeSelector(e))l.classList.add("stats-window-header-actions-only"),l.append(c);else{const f=document.createElement("h2");f.textContent=this.getStatsWindowTitle(e),l.append(f,c)}const d=document.createElement("div");d.className="stats-window-body",o.append(l,d),this.options.layer.append(o);const h={id:i,kind:e,entries:t?.entries.map(f=>({key:`${i}:${f.statId}:${f.targetId??"scope"}`,statId:f.statId,targetId:f.targetId}))??[],playerId:t?.playerId??this.options.getReplayPlayer()?.replay.players[0]?.id??null,team:t?.team??"blue",pickerOpen:!1,query:"",element:o,body:d};return u.addEventListener("click",()=>{o.hidden=!0,this.options.requestConfigSync()}),this.statsWindows.set(i,h),t||this.options.bringWindowToFront(o),this.options.setLauncherOpen(!1),this.renderStatsWindow(h),this.options.requestConfigSync(),h}getStatById(e){return this.options.getStatRegistry().find(t=>t.id===e)??null}getCurrentStatsFrame(e){const t=this.options.getStatsFrameLookup();return t?zt(t,e):null}getTeamSnapshot(e,t){return t==="blue"?e.team_zero??null:e.team_one??null}getTeamLabel(e){return e==="blue"?"Blue":"Orange"}getPlayerTeamClass(e){const t=this.options.getReplayPlayer()?.replay.players.find(i=>i.id===e);return t?ta(t.isTeamZero):null}getTeamScopeClass(e){return ta(e==="blue")}appendGroupedPlayerOptions(e,t){const i=this.options.getReplayPlayer()?.replay.players??[];for(const s of["blue","orange"]){const a=i.filter(o=>o.isTeamZero===(s==="blue"));if(a.length===0)continue;const r=document.createElement("optgroup");r.label=`${this.getTeamLabel(s)} team`;for(const o of a)r.append(new Option(o.name,o.id,o.id===t,o.id===t));e.append(r)}}getStatsWindowScopeTeamClass(e){return e.kind==="player"?this.getPlayerTeamClass(e.playerId):e.kind==="team"?this.getTeamScopeClass(e.team??"blue"):null}getStatTargetTeamClass(e,t){return e.scope==="player"?this.getPlayerTeamClass(t):this.getTeamScopeClass(t==="orange"?"orange":"blue")}getStatsWindowTitle(e){switch(e){case"player":return"Player stats";case"team":return"Team stats";case"all-players":return"All players stats";case"all-teams":return"All teams stats";case"kickoff-overview":return"Kickoff details";case"goals-overview":return"Goal labels";case"ad-hoc":return"Ad hoc stats"}}hasStatsWindowScopeSelector(e){return e==="player"||e==="team"}hasStatsWindowStatPicker(e){return e!=="goals-overview"&&e!=="kickoff-overview"}getStatsWindowAllowedScope(e){switch(e){case"player":case"all-players":return"player";case"team":case"all-teams":return"team";case"kickoff-overview":return null;case"goals-overview":return null;case"ad-hoc":return null}}getStatsWindowDefaultPosition(){const e=this.statsWindows.size*18;return{x:Math.max(12,Math.min(window.innerWidth-360,96+e)),y:Math.max(64,Math.min(window.innerHeight-240,96+e))}}renderStatsWindow(e,t=this.options.getReplayPlayer()?.getState().frameIndex??0){const i=document.activeElement,s=i instanceof HTMLInputElement&&i.dataset.statsWindowSearch===e.id,a=s?i.selectionStart:null,r=s?i.selectionEnd:null,o=s?i.selectionDirection:null;if(e.body.replaceChildren(),this.renderStatsWindowScope(e),this.hasStatsWindowStatPicker(e.kind)&&(this.renderStatsWindowAddControl(e),this.renderStatsWindowPicker(e)),this.renderStatsWindowEntries(e,t),s){const l=e.body.querySelector(`input[data-stats-window-search="${e.id}"]`);l?.focus({preventScroll:!0}),l&&a!==null&&r!==null&&l.setSelectionRange(a,r,o??"none")}}renderStatsWindowScope(e){if(e.kind!=="player"&&e.kind!=="team")return;const t=document.createElement("div");t.className="stats-window-scope-row";const i=document.createElement("select");i.className="stats-window-scope-select";const s=this.getStatsWindowScopeTeamClass(e);s&&i.classList.add(s),i.setAttribute("aria-label",e.kind==="player"?"Player stats target":"Team stats target"),e.kind==="player"?(this.appendGroupedPlayerOptions(i,e.playerId),i.value=e.playerId??"",i.addEventListener("change",()=>{e.playerId=i.value||null,this.renderStatsWindow(e),this.options.requestConfigSync()})):(i.append(new Option("Blue","blue",e.team==="blue",e.team==="blue"),new Option("Orange","orange",e.team==="orange",e.team==="orange")),i.value=e.team??"blue",i.addEventListener("change",()=>{e.team=i.value==="orange"?"orange":"blue",this.renderStatsWindow(e),this.options.requestConfigSync()})),t.append(i),e.body.append(t)}renderStatsWindowAddControl(e){const t=document.createElement("button");if(t.type="button",t.className="stats-window-add-button",t.textContent="+",t.title="Add stat",t.setAttribute("aria-label","Add stat"),t.setAttribute("aria-expanded",String(e.pickerOpen)),this.activateButton(t,()=>{e.pickerOpen=!e.pickerOpen,this.renderStatsWindow(e)}),this.hasStatsWindowScopeSelector(e.kind)){e.body.querySelector(".stats-window-scope-row")?.append(t);return}const i=document.createElement("div");i.className="stats-window-toolbar",i.append(t),e.body.append(i)}activateButton(e,t){let i=!1;e.addEventListener("pointerdown",s=>{e.disabled||(i=!0,s.preventDefault(),t())}),e.addEventListener("click",()=>{if(i){i=!1;return}e.disabled||t()})}renderStatsWindowPicker(e){const t=document.createElement("div");if(t.className="stats-window-picker",t.hidden=!e.pickerOpen,t.hidden){e.body.append(t);return}const i=this.getStatsWindowAllowedScope(e.kind),s=document.createElement("input");s.type="search",s.placeholder="Search stats",s.value=e.query,s.dataset.statsWindowSearch=e.id;const a=document.createElement("div");a.className="stats-window-picker-list",s.addEventListener("input",()=>{e.query=s.value,this.renderStatsWindowPickerList(e,a,i)}),this.renderStatsWindowPickerList(e,a,i),t.append(s,a),e.body.append(t)}renderStatsWindowPickerList(e,t,i){t.replaceChildren();const s=this.options.getStatRegistry(),a=i?s.filter(l=>l.scope===i):s,r=b$(a,e.query),o=new Map;for(const l of r){const c=o.get(l.category)??[];c.push(l),o.set(l.category,c)}for(const[l,c]of o){if(c.length<2)continue;const u=document.createElement("button");u.type="button",u.className="stats-window-picker-item",u.innerHTML=`Add all ${l}${c.length}`,this.activateButton(u,()=>{for(const d of c)this.addStatToWindow(e,d);this.renderStatsWindow(e),this.options.requestConfigSync()}),t.append(u)}for(const l of r){const c=document.createElement("button");c.type="button",c.className="stats-window-picker-item",c.innerHTML=`${l.label}${l.scope}`,c.disabled=e.kind!=="ad-hoc"&&e.entries.some(u=>u.statId===l.id),this.activateButton(c,()=>{this.addStatToWindow(e,l),this.renderStatsWindow(e),this.options.requestConfigSync()}),t.append(c)}if(r.length===0){const l=document.createElement("p");l.className="stat-window-empty",l.textContent=s.length===0?"No stats available.":"No matching stats.",t.append(l)}}addStatToWindow(e,t){const i=e.kind==="ad-hoc"?this.getDefaultAdHocTargetId(t):void 0;e.entries.some(s=>s.statId===t.id&&s.targetId===i)||e.entries.push({key:`${e.id}:${t.id}:${i??"scope"}`,statId:t.id,targetId:i})}getDefaultAdHocTargetId(e){return e.scope==="player"?this.options.getReplayPlayer()?.replay.players[0]?.id??"":"blue"}removeStatFromWindow(e,t){const i=e.entries.findIndex(s=>s.key===t);i>=0&&e.entries.splice(i,1)}renderStatsWindowEntries(e,t){if(e.kind==="goals-overview"){this.renderGoalLabelsOverview(e);return}if(e.kind==="kickoff-overview"){this.renderKickoffOverview(e,t);return}const i=this.getStatsWindowAllowedScope(e.kind),s=e.entries.map(r=>({entry:r,definition:this.getStatById(r.statId)})).filter(r=>r.definition!==null&&(!i||r.definition.scope===i));if(s.length===0){const r=document.createElement("p");r.className="stat-window-empty",r.textContent="No stats added.",e.body.append(r);return}const a=this.getCurrentStatsFrame(t);if(!a){const r=document.createElement("p");r.className="stat-window-empty",r.textContent="Load a replay to show stats.",e.body.append(r);return}if(e.kind==="all-players"){this.renderAllPlayersStats(e,a,s);return}if(e.kind==="all-teams"){this.renderAllTeamsStats(e,a,s);return}if(e.kind==="player"){const r=e.playerId?a.players.find(o=>At(o.player_id)===e.playerId)??null:null;this.renderScopedStatList(e,r,s);return}if(e.kind==="team"){this.renderScopedStatList(e,this.getTeamSnapshot(a,e.team??"blue"),s);return}e.kind==="ad-hoc"&&this.renderAdHocStats(e,a,s)}renderGoalLabelsOverview(e){const t=this.options.getStatsTimeline(),i=this.options.getReplayPlayer()?.replay??null;if(!t||!i){this.appendStatsWindowEmpty(e,"Load a replay to show goal labels.");return}const s=[...ve(t,"goal_context")].sort((o,l)=>o.time-l.time),a=s.map((o,l)=>l);if(a.length===0){this.appendStatsWindowEmpty(e,"No goals loaded.");return}const r=document.createElement("div");r.className="goal-label-list";for(const o of a){const l=s[o]??null,c=[...l?.tags??[]].sort((M,C)=>M.kind.localeCompare(C.kind)||C.metadata.confidence-M.metadata.confidence),u=l?.time??0,d=l?.scorer??null,h=d?At(d):null,f=d?i.players.find(M=>M.id===h)?.name??h:"Unknown scorer",p=l?.scoring_team_is_team_0??null,g=document.createElement("section");g.className="goal-label-item",p!==null&&g.classList.add(ta(p));const _=document.createElement("header"),m=document.createElement("h3");m.textContent=`Goal ${o+1}`;const v=document.createElement("span");v.textContent=`${ss(u)} · ${f}`,_.append(m,v);const y=document.createElement("div");if(y.className="goal-label-tags",c.length===0){const M=document.createElement("span");M.className="goal-label-tag goal-label-tag-empty",M.textContent="Unlabeled",y.append(M)}else for(const M of c){const C=document.createElement("span");C.className="goal-label-tag";const w=M5(M);C.textContent=`${Ci(M.kind)} ${Math.round(M.metadata.confidence*100)}%${w?` - ${w}`:""}`,y.append(C)}const b=document.createElement("div");b.className="goal-label-actions";const T=document.createElement("button");T.type="button",T.className="goal-label-watch",T.textContent="Watch",T.addEventListener("click",()=>{this.options.watchGoalReplay(u,h)});const x=document.createElement("button");x.type="button",x.textContent="Cue",x.addEventListener("click",()=>{this.options.cueGoalReplay(u)}),b.append(T,x),g.append(_,y,b),r.append(g)}e.body.append(r)}renderKickoffOverview(e,t){const i=this.options.getStatsTimeline(),s=this.options.getReplayPlayer()?.replay??null;if(!i||!s){this.appendStatsWindowEmpty(e,"Load a replay to show kickoff details.");return}const a=this.getClosestKickoffEvent(i,t);if(!a){this.appendStatsWindowEmpty(e,"No kickoff events loaded.");return}const r=a.payload.payload,o=document.createElement("section");o.className="kickoff-overview";const l=document.createElement("header");l.className="kickoff-overview-hero";const c=document.createElement("div"),u=document.createElement("h3");u.textContent=this.formatKickoffTitle(a);const d=document.createElement("span");d.textContent=`Nearest kickoff · resolved at ${ss(r.end_time)}`,c.append(u,d);const h=document.createElement("strong"),f=this.teamClassFromNullable(r.winning_team_is_team_0);h.className="kickoff-overview-victor",f&&h.classList.add(f),h.textContent=this.formatOutcome(r),l.append(c,h);const p=document.createElement("div");p.className="kickoff-overview-summary",p.append(this.renderKickoffMetric("Win strength",`${this.formatNullableNumber(r.win_strength,2)} · ${this.formatKickoffLabelValue("kickoff_win_strength",r.win_strength_band)}`),this.renderKickoffMetric("First touch",this.formatFirstTouch(r)),this.renderKickoffMetric("Advantage",this.formatAdvantage(r)),this.renderKickoffMetric("Contested",this.formatContested(r)));const g=document.createElement("div");g.className="kickoff-detail-grid",g.append(this.renderKickoffDetail("Kickoff start",ss(r.start_time)),this.renderKickoffDetail("Movement start",ss(r.movement_start_time)),this.renderKickoffDetail("Live action",r.live_action_start_time===null?"--":ss(r.live_action_start_time)),this.renderKickoffDetail("First touch",r.first_touch_time===null?"--":ss(r.first_touch_time)),this.renderKickoffDetail("Resolution",ss(r.end_time)),this.renderKickoffDetail("After first touch",this.formatSeconds(r.advantage_seconds_after_first_touch)));const _=document.createElement("div");_.className="kickoff-strategy-list",_.append(this.renderKickoffTeamStrategy("Blue",r.team_zero_taker,r.team_zero_non_takers),this.renderKickoffTeamStrategy("Orange",r.team_one_taker,r.team_one_non_takers)),o.append(l,p,g,_),e.body.append(o)}getClosestKickoffEvent(e,t){return jl(e).filter(s=>s.payload.kind==="kickoff").sort((s,a)=>{const r=this.kickoffFrameDistance(s.payload.payload,t),o=this.kickoffFrameDistance(a.payload.payload,t);return r!==o?r-o:s.payload.payload.start_frame-a.payload.payload.start_frame})[0]??null}kickoffFrameDistance(e,t){return t>=e.start_frame&&t<=e.end_frame?0:Math.min(Math.abs(t-e.start_frame),Math.abs(t-e.end_frame))}renderKickoffMetric(e,t){const i=document.createElement("div");i.className="kickoff-metric";const s=document.createElement("span");s.textContent=e;const a=document.createElement("strong");return a.textContent=t,i.append(s,a),i}renderKickoffDetail(e,t){const i=document.createElement("div");i.className="kickoff-detail-row";const s=document.createElement("span");s.textContent=e;const a=document.createElement("strong");return a.textContent=t,i.append(s,a),i}renderKickoffTeamStrategy(e,t,i){const s=document.createElement("section");s.className=`kickoff-strategy-team ${e==="Blue"?"team-blue":"team-orange"}`;const a=document.createElement("h4");a.textContent=e,s.append(a);const r=document.createElement("p");if(r.className="kickoff-strategy-line",r.textContent=t?`${this.getPlayerName(t.player)}: ${this.formatKickoffLabelValue("kickoff_approach",t.approach)} from ${this.formatKickoffLabelValue("kickoff_spawn",t.spawn_position)} (${this.formatKickoffLabelValue("taker_outcome",t.outcome)}, ${this.formatSeconds(t.time_to_ball)})`:"No taker detected",s.append(r),i.length>0){const o=document.createElement("ul");o.className="kickoff-support-list";for(const l of i){const c=document.createElement("li");c.textContent=`${this.getPlayerName(l.player)}: ${this.formatKickoffLabelValue("support_behavior",l.support_behavior)} from ${this.formatKickoffLabelValue("kickoff_spawn",l.spawn_position)}`,o.append(c)}s.append(o)}return s}formatOutcome(e){return e.winning_team_is_team_0===!0?"Blue wins":e.winning_team_is_team_0===!1?"Orange wins":e.outcome==="neutral"?"Neutral":"Unknown"}formatFirstTouch(e){if(!e.first_touch_player)return"--";const t=e.first_touch_team_is_team_0===!0?"Blue":e.first_touch_team_is_team_0===!1?"Orange":"Unknown",i=e.first_touch_time===null?"--":ss(e.first_touch_time);return`${t} · ${this.getPlayerName(e.first_touch_player)} · ${i}`}formatAdvantage(e){if(e.advantage==="no_advantage")return"No advantage";const t=e.advantage_team_is_team_0===!0?"Blue":e.advantage_team_is_team_0===!1?"Orange":"Unknown",i=e.advantage.replace(/^team_(zero|one)_/,""),s=e.advantage_player?` · ${this.getPlayerName(e.advantage_player)}`:"",a=e.advantage_time===null?"":` · ${ss(e.advantage_time)}`;return`${t} ${this.formatKickoffLabelValue("kickoff_advantage",i)}${s}${a}`}formatContested(e){return e.kickoff_possession_outcome==="contested"?"Yes":e.kickoff_possession_team_is_team_0===!0?`No · Blue ${this.formatPossessionOutcome(e.kickoff_possession_outcome)}`:e.kickoff_possession_team_is_team_0===!1?`No · Orange ${this.formatPossessionOutcome(e.kickoff_possession_outcome)}`:`No · ${this.formatPossessionOutcome(e.kickoff_possession_outcome)}`}formatPossessionOutcome(e){return e.endsWith("_advantage")?"advantage":e.endsWith("_possession")?"possession":this.formatKickoffLabelValue("kickoff_possession_outcome",e)}formatKickoffType(e){return this.formatKickoffLabelValue("kickoff_type",e)}formatKickoffTitle(e){const t=e.payload.payload,i=this.formatKickoffDirection(t.kickoff_direction),s=[this.formatKickoffType(t.kickoff_type),i].filter(Boolean).join(" ");return[e.meta.label,s].filter(Boolean).join(" · ")}formatKickoffDirection(e){return e==="unknown"?"":`(${this.formatKickoffLabelValue("kickoff_direction",e)})`}formatNullableNumber(e,t){return e===null||!Number.isFinite(e)?"--":e.toFixed(t)}formatSeconds(e){return e===null||!Number.isFinite(e)?"--":`${e.toFixed(2)}s`}formatLabel(e){return e.replace(/^team_zero_/,"blue_").replace(/^team_one_/,"orange_").replaceAll("_"," ").replace(/\b\w/g,t=>t.toUpperCase())}formatKickoffLabelValue(e,t){const i=t.replace(/^team_zero_/,"blue_").replace(/^team_one_/,"orange_");return e==="kickoff_advantage"?this.formatLabel(i.replace(/^blue_/,"").replace(/^orange_/,"")):e==="kickoff_possession_outcome"?this.formatLabel(i.replace(/^blue_/,"Blue ").replace(/^orange_/,"Orange ")):this.formatLabel(i)}teamClassFromNullable(e){return e===null?null:ta(e)}getPlayerName(e){const t=At(e);return this.options.getReplayPlayer()?.replay.players.find(i=>i.id===t)?.name??t}appendStatsWindowEmpty(e,t){const i=document.createElement("p");i.className="stat-window-empty",i.textContent=t,e.body.append(i)}renderScopedStatList(e,t,i){const s=document.createElement("div");s.className="stats-window-stat-list";for(const{entry:a,definition:r}of i)s.append(this.renderStatRow(e,a,r,t?r.format(r.read(t)):"--"));e.body.append(s)}renderAllPlayersStats(e,t,i){const s=document.createElement("div");s.className="stats-window-team-list";for(const a of["blue","orange"]){const r=t.players.filter(h=>h.is_team_0===(a==="blue"));if(r.length===0)continue;const o=document.createElement("section");o.className=`stats-window-team-group ${this.getTeamScopeClass(a)}`;const l=document.createElement("header");l.className="stats-window-team-header";const c=document.createElement("h3");c.textContent=`${this.getTeamLabel(a)} team`;const u=document.createElement("span");u.textContent=`${r.length} player${r.length===1?"":"s"}`,l.append(c,u),o.append(l);const d=document.createElement("div");d.className="stats-window-entity-list";for(const h of r){const f=document.createElement("section");f.className=`stats-window-entity ${ta(h.is_team_0)}`;const p=document.createElement("h4");p.className="stats-window-entity-title",p.textContent=h.name,f.append(p);for(const{entry:g,definition:_}of i)f.append(this.renderStatRow(e,g,_,_.format(_.read(h))));d.append(f)}o.append(d),s.append(o)}e.body.append(s)}renderAllTeamsStats(e,t,i){const s=document.createElement("div");s.className="stats-window-entity-list";for(const a of["blue","orange"]){const r=this.getTeamSnapshot(t,a),o=document.createElement("section");o.className=`stats-window-entity ${this.getTeamScopeClass(a)}`;const l=document.createElement("h3");l.className="stats-window-entity-title",l.textContent=this.getTeamLabel(a),o.append(l);for(const{entry:c,definition:u}of i)o.append(this.renderStatRow(e,c,u,r?u.format(u.read(r)):"--"));s.append(o)}e.body.append(s)}renderAdHocStats(e,t,i){const s=document.createElement("div");s.className="stats-window-stat-list";for(const{entry:a,definition:r}of i){const o=this.getAdHocTarget(t,r,a.targetId);s.append(this.renderStatRow(e,a,r,o?r.format(r.read(o)):"--"))}e.body.append(s)}getAdHocTarget(e,t,i){return t.scope==="player"?e.players.find(s=>At(s.player_id)===i)??e.players[0]??null:this.getTeamSnapshot(e,i==="orange"?"orange":"blue")}renderStatRow(e,t,i,s){const a=document.createElement("div");a.className="stats-window-stat-row";const r=document.createElement("span");if(r.className="stats-window-stat-name",r.textContent=i.label,e.kind==="ad-hoc"){const c=document.createElement("select");c.className="stats-window-stat-target";const u=this.getStatTargetTeamClass(i,t.targetId);u&&c.classList.add(u),i.scope==="player"?this.appendGroupedPlayerOptions(c,t.targetId):c.append(new Option("Blue","blue",t.targetId==="blue",t.targetId==="blue"),new Option("Orange","orange",t.targetId==="orange",t.targetId==="orange")),c.value=t.targetId??"",c.addEventListener("change",()=>{const d=c.value;if(e.entries.some(f=>f!==t&&f.statId===t.statId&&f.targetId===d)){this.renderStatsWindow(e);return}const h=e.entries.findIndex(f=>f.key===t.key);h>=0&&(e.entries[h]={key:`${e.id}:${t.statId}:${d}`,statId:t.statId,targetId:d}),this.renderStatsWindow(e),this.options.requestConfigSync()}),r.append(" ",c)}const o=document.createElement("span");o.className="stats-window-stat-value",o.textContent=s;const l=document.createElement("button");return l.type="button",l.className="stats-window-stat-remove",l.textContent="x",l.addEventListener("click",()=>{this.removeStatFromWindow(e,t.key),this.renderStatsWindow(e),this.options.requestConfigSync()}),a.append(r,o,l),a}}function w$(n){return new x$(n)}const S$=new Set(["module:dodge","module:touch","module:powerslide"]),T$=["stats-stream:"],ih=["#3b82f6","#06b6d4","#22c55e","#a855f7","#f97316","#ef4444","#f59e0b","#ec4899"],af="#d1d9e0",Gg=ih[0],$g=ih[4],M$=[{id:"core",label:"Shots, saves, assists",buildEvents(n){return n.replay.timelineEvents.filter(e=>e.kind==="shot"||e.kind==="save"||e.kind==="assist")}},{id:"demo",label:"Demos",buildEvents(n){return n.replay.timelineEvents.filter(e=>e.kind==="demo")}}],E$=[];function $E(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function WE(n){if(typeof n=="string"&&n.length>0)return n;if(!$E(n))return null;const[e,t]=Object.entries(n)[0]??[];return!e||t==null?null:typeof t=="string"||typeof t=="number"?`${e}:${t}`:`${e}:${JSON.stringify(t)}`}function XE(n){return n.split(/[_-]+/).filter(e=>e.length>0).map(e=>e.slice(0,1).toUpperCase()).join("").slice(0,3)||"E"}function C$(n){if(typeof n!="number"||!Number.isFinite(n))return null;const e=Math.abs(n)<1?2:1;return`${n.toFixed(e).replace(/\.0+$/,"").replace(/(\.\d*[1-9])0+$/,"$1")}s`}function $i(n){return typeof n!="string"||n.length===0?null:n.split(/[_-]+/).filter(e=>e.length>0).map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1)}`).join(" ")}function A$(n){return n==="team_zero_side"?"Blue side":n==="team_one_side"?"Orange side":n==="neutral"?"Neutral zone":$i(n)}function R$(n){const e=$i(n);return e?`${e.toLowerCase()} third`:null}function P$(n){return n==="team_zero_third"?"Blue third":n==="team_one_third"?"Orange third":n==="neutral_third"?"Neutral third":$i(n)}function I$(n){return n==="team_zero"?"Blue":n==="team_one"?"Orange":n==="neutral"?"Neutral":$i(n)}function ad(n){return $E(n.payload.payload)?n.payload.payload:{}}function KE(n){return n===!0?Gg:n===!1?$g:null}function L$(n){return n==="team_zero_side"?Gg:n==="team_one_side"?$g:n==="neutral"?af:null}function D$(n){return n==="team_zero"?Gg:n==="team_one"?$g:n==="neutral"?af:null}function k$(n){return typeof n=="boolean"?KE(n):null}const O$={ball_half(n){return L$(ad(n).field_half)},possession(n){return D$(ad(n).possession_state)},player_possession(n){return k$(ad(n).is_team_0)}};function qE(n,e,t){return O$[n]?.(e)??KE(t)??af}function ui(n){return n.filter(e=>!!e).join(" | ")}function F$({event:n,playerName:e,streamLabel:t,teamLabel:i}){const s=ad(n),a=C$(s.duration);if(n.payload.kind==="ball_half"){const r=A$(s.field_half),o=s.active===!1?"Ball half inactive":r?`Ball on ${r.toLowerCase()}`:null;return ui([o??t,a])}if(n.payload.kind==="ball_third"){const r=P$(s.field_third),o=s.active===!1?"Ball third inactive":r?`Ball in ${r.toLowerCase()}`:null;return ui([o??t,a])}if(n.payload.kind==="territorial_pressure"){const r=$i(s.end_reason),o=`${i??""} territorial pressure`.trim();return ui([r?`${o} ended: ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="possession"){const r=I$(s.possession_state),o=R$(s.field_third),l=r?`${r} possession`:t;return ui([l,o,a])}if(n.payload.kind==="controlled_play"){const r=e?`${e} controlled play`:t;return ui([r,a])}if(n.payload.kind==="ball_carry"){const r=e?`${e} ${t.toLowerCase()}`:t;return ui([r,a])}if(n.payload.kind==="player_activity"){const r=$i(s.state),o=e?`${e} positioning`:t;return ui([r?`${o} ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="field_third"){const r=$i(s.state),o=e?`${e} positioning`:t;return ui([r?`${o} in ${r.toLowerCase()} third`:o,a])}if(n.payload.kind==="field_half"){const r=$i(s.state),o=e?`${e} positioning`:t;return ui([r?`${o} in ${r.toLowerCase()} half`:o,a])}if(n.payload.kind==="ball_depth"){const r=$i(s.state),o=e?`${e} ball depth`:t;return ui([r?`${o}: ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="depth_role"){const r=$i(s.state),o=e?`${e} depth role`:t;return ui([r?`${o}: ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="shadow_defense"){const r=e?`${e} shadow defense`:t;return ui([r,a])}if(n.payload.kind==="rotation_role"){const r=$i(s.state),o=e?`${e} rotation`:t;return ui([r?`${o}: ${r.toLowerCase()}`:o,a])}return e?`${e} ${t.toLowerCase()}`:t}function N$(n,e,t){const i=Ci(e),s=new Map(n.replay.players.map(a=>[a.id,a.name]));return t.flatMap((a,r)=>{const o=a.meta.timing.type==="moment"?{time:a.meta.timing.time,frame:a.meta.timing.frame}:{time:a.meta.timing.end_time,frame:a.meta.timing.end_frame},l=WE(a.meta.primary_player),c=l?s.get(l)??l:null,u=a.meta.team_is_team_0??null,d=u==null?null:u?"Blue":"Orange",h=a.meta.id||`${e}:${o.frame??o.time}:${r}`,f=qE(e,a,u);return[{id:`stats-stream:${h}`,time:n.replay.frames[o.frame??-1]?.time??o.time,frame:o.frame,kind:e,label:F$({event:a,playerName:c,streamLabel:i,teamLabel:d}),shortLabel:XE(e),playerId:l,playerName:c,isTeamZero:u,color:f}]})}function U$(n,e,t){const i=Ci(e),s=new Map(n.replay.players.map(a=>[a.id,a.name]));return t.flatMap((a,r)=>{if(a.meta.timing.type!=="span")return[];const o={startTime:a.meta.timing.start_time,endTime:a.meta.timing.end_time,startFrame:a.meta.timing.start_frame,endFrame:a.meta.timing.end_frame},l=a.meta.team_is_team_0??null,c=l==null?null:l?"Blue":"Orange",u=WE(a.meta.primary_player),d=u?s.get(u)??u:null,h=qE(e,a,l),f=a.meta.id||`${e}:${o.startFrame??o.startTime}:${o.endFrame??o.endTime}:${r}`,p=d?`${d} ${i.toLowerCase()}`:c?`${c} ${i.toLowerCase()}`:i;let g=`stats-stream:${e}`,_=i;return a.meta.scope==="player"&&u?(g=`stats-stream:${e}:player:${u}`,_=d?`${d} ${i.toLowerCase()}`:i):a.meta.scope==="team"&&l!=null&&(g=`stats-stream:${e}:team:${l?"0":"1"}`,_=c?`${c} ${i.toLowerCase()}`:i),[{id:`stats-stream:${f}`,startTime:n.replay.frames[o.startFrame??-1]?.time??o.startTime,endTime:Math.max(n.replay.frames[o.startFrame??-1]?.time??o.startTime,n.replay.frames[o.endFrame??-1]?.time??o.endTime),lane:g,laneLabel:_,label:p,shortLabel:XE(e),isTeamZero:l,color:h}]}).sort((a,r)=>a.startTime!==r.startTime?a.startTime-r.startTime:(a.id??"").localeCompare(r.id??""))}function B$(n,e,t,i){return[...new Set([...FT,...jl(n.statsTimeline).map(a=>a.meta.stream)])].flatMap(a=>{const r=jl(n.statsTimeline).filter(u=>u.meta.stream===a);if(i.has(a)&&r.length>0)return[];const o=r.some(u=>u.meta.timing.type==="span"),l=o?U$(n,a,r):[],c=N$(n,a,r);return[{id:`stats-stream:${a}`,playlistId:`stats-stream:${a}`,timelineKey:`stats-stream:${a}`,timelineId:`stats-stream:${a}`,group:"Event streams",label:Ci(a),count:o?l.length:c.length,active:e.has(`stats-stream:${a}`),buildTimelineEvents(){return o?[]:c},buildPlaylistEvents(){return c},buildTimelineRanges:o?()=>l:void 0,setActive(u){t(`stats-stream:${a}`,u)}}]})}function z$(n){return new Set([...n.filter(e=>e.getTimelineEvents).map(e=>e.id),...CE])}function H$(){return[...CE].sort((n,e)=>Ci(n).localeCompare(Ci(e)))}function V$({ctx:n,modules:e,activeTimelineEventSourceIds:t,activeMechanicTimelineKinds:i,toggleEventSource:s,setMechanicTimelineKind:a}){if(!n)return[];const r=[];for(const o of M$){const l=o.buildEvents(n),c=l.length;r.push({id:o.id,playlistId:`replay:${o.id}`,timelineKey:`events:${o.id}`,timelineId:`events:${o.id}`,group:"Replay",label:o.label,count:c,active:t.has(o.id),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){s(o.id,u)}})}for(const o of e.filter(l=>l.getTimelineEvents)){const l=o.getTimelineEvents?.(n)??[],c=l.length;r.push({id:o.id,playlistId:`module:${o.id}`,timelineKey:`module:${o.id}`,timelineId:`module:${o.id}`,group:"Stats",label:o.label,count:c,active:t.has(o.id),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){s(o.id,u)}})}for(const o of E$){const l=o.buildEvents(n),c=l.length;r.push({id:o.id,playlistId:`extra:${o.id}`,timelineKey:`extra:${o.id}`,timelineId:`extra:${o.id}`,group:"Stats",label:o.label,count:c,active:t.has(o.id),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){s(o.id,u)}})}r.push(...B$(n,t,s,z$(e)));for(const o of H$()){const l=EE[o](n.statsTimeline,n.replay),c=l.length;r.push({id:`mechanic:${o}`,playlistId:`mechanic:${o}`,timelineKey:`mechanic:${o}`,timelineId:`mechanic:${o}`,group:"Event types",label:Ci(o),count:c,active:i.has(o),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){a(o,u)}})}return r.sort((o,l)=>o.label.localeCompare(l.label))}function G$(n,e){if(!n)return[];const t=[{id:"replay:goals",group:"Replay",label:"Goals",events:n.replay.timelineEvents.filter(s=>s.kind==="goal")}],i=e.map(s=>({id:s.playlistId,group:s.group,label:s.label,events:s.buildPlaylistEvents()}));return[...t,...i]}function v_(n,e){const t=n.map(i=>i.id);return e===null?new Set(t.filter(i=>!S$.has(i)&&!T$.some(s=>i.startsWith(s)))):new Set(t.filter(i=>e.has(i)))}function $$(n,e){const t=n.playerId??null,i=t?e.findIndex(s=>s.id===t):-1;return i>=0?ih[i%ih.length]:n.color??af}function W$({sources:n,activeSourceIds:e,replayPlayers:t}){const i=v_(n,e);return n.filter(s=>i.has(s.id)).flatMap(s=>s.events.map((a,r)=>({key:`${s.id}:${a.id??`${a.kind}:${a.time}:${r}`}`,sourceId:s.id,sourceLabel:s.label,event:a,color:$$(a,t)}))).sort((s,a)=>s.event.time!==a.event.time?s.event.time-a.event.time:(s.event.label??s.sourceLabel).localeCompare(a.event.label??a.sourceLabel))}class X${constructor(e){this.options=e}getSources(e=this.options.getContext()){return V$({ctx:e,modules:this.options.modules,activeTimelineEventSourceIds:this.options.getActiveTimelineEventSourceIds(),activeMechanicTimelineKinds:this.options.getActiveMechanicTimelineKinds(),toggleEventSource:this.options.toggleEventSource,setMechanicTimelineKind:this.options.setMechanicTimelineKind})}countVisibleSources(e){return e.replay.timelineEvents.filter(i=>i.kind==="goal").length+this.getSources(e).filter(i=>i.active).reduce((i,s)=>i+s.count,0)}render(){const{body:e}=this.options;e.replaceChildren();const t=this.getSources();if(t.length===0){const d=document.createElement("p");d.className="stat-window-empty",d.textContent="No events loaded.",e.append(d);return}const i=document.createElement("div");i.className="mechanics-actions";const s=document.createElement("button");s.type="button",s.className="module-summary-item",s.addEventListener("click",()=>{for(const d of t)d.setActive(!0);this.options.setupActiveModules(),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.render(),this.options.renderModuleSummary(),this.options.renderModuleSettings(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()});const a=document.createElement("span");a.textContent="All events";const r=document.createElement("strong");r.textContent=`${t.length}`,s.append(a,r);const o=document.createElement("button");o.type="button",o.className="module-summary-item",o.addEventListener("click",()=>{for(const d of t)d.setActive(!1);this.options.setupActiveModules(),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.render(),this.options.renderModuleSummary(),this.options.renderModuleSettings(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()});const l=document.createElement("span");l.textContent="No events";const c=document.createElement("strong");c.textContent="Off",o.append(l,c),i.append(s,o),e.append(i);const u=this.renderSourceList(t);u&&e.append(u)}renderSourceList(e){if(e.length===0)return null;const t=document.createElement("div");t.className="module-list mechanics-list mechanics-event-list",t.style.setProperty("--event-source-columns",`${K$(e.length)}`);for(const i of e){const s=document.createElement("button");s.type="button",s.className="module-summary-item",s.dataset.active=i.active?"true":"false",s.setAttribute("aria-pressed",i.active?"true":"false"),s.addEventListener("click",()=>{i.setActive(!i.active),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.render(),this.options.renderTimelineEventCount()});const a=document.createElement("span");a.textContent=i.label;const r=document.createElement("strong");r.textContent=`${i.active?"On":"Off"} ${i.count}`,s.append(a,r),t.append(s)}return t}}function K$(n){return window.innerWidth<640?1:window.innerWidth<900?n>=7?2:1:n>=13?3:n>=7?2:1}function q$(n){return new X$(n)}const Y$=new Set(["ceiling-shot","fifty-fifty","ball_half",OE,"absolute-positioning","dodge","speed-flip","touch"]),kx="touch";class j${constructor(e){this.options=e}renderSummary(){const{summary:e}=this.options.elements;e.replaceChildren();const t=this.options.getTimelineSources(),i=t.map(o=>this.renderTimelineSourceToggle(o)),s=[],a=[],r=this.options.getContext();for(const o of this.options.modules){const l=Y$.has(o.id);!o.getTimelineEvents&&!o.getTimelineRanges&&!l||(t.length===0&&o.getTimelineEvents&&i.push(this.renderCapabilityToggle(o.id,rm(o,"events"),"events")),o.getTimelineRanges&&s.push(this.renderCapabilityToggle(o.id,rm(o,"ranges"),"ranges",r?o.getTimelineRanges(r).length:void 0)),l&&a.push(this.renderCapabilityToggle(o.id,rm(o,"effects"),"effects")))}a.push(this.renderBoostPickupAnimationToggle()),e.append(am("Timeline markers",i),am("Timeline ranges",s),am("In-game visualizations",a))}renderSettings(){const{settings:e}=this.options.elements;e.replaceChildren();const t=this.options.getContext(),i=this.options.getActiveModules().filter(s=>s.id!=="boost"&&s.id!==kx).map(s=>s.renderSettings?.(t)??null).filter(s=>s instanceof HTMLElement);if(i.length===0){e.hidden=!0,this.renderBoostPickupFiltersWindow(),this.renderTouchControlsWindow();return}e.hidden=!1,e.append(...i),this.renderBoostPickupFiltersWindow(),this.renderTouchControlsWindow()}renderBoostPickupAnimationToggle(){const e=this.options.getBoostPickupAnimationEnabled(),t=document.createElement("button");t.type="button",t.className="module-summary-item",t.dataset.active=e?"true":"false",t.setAttribute("aria-pressed",e?"true":"false"),t.addEventListener("click",this.options.toggleBoostPickupAnimation);const i=document.createElement("span");i.textContent="Boost pickup animation";const s=document.createElement("strong");return s.textContent=e?"On":"Off",t.append(i,s),t}renderCapabilityToggle(e,t,i,s){const r=this.options.getActiveCapabilityIds(i).has(e),o=document.createElement("button");o.type="button",o.className="module-summary-item",o.dataset.active=r?"true":"false",o.setAttribute("aria-pressed",r?"true":"false"),o.addEventListener("click",()=>{this.options.toggleCapability(e,i,!this.options.getActiveCapabilityIds(i).has(e))});const l=document.createElement("span");l.textContent=t;const c=document.createElement("strong");return c.textContent=Ox(r,s),o.append(l,c),o}renderTimelineSourceToggle(e){const t=document.createElement("button");t.type="button",t.className="module-summary-item",t.dataset.active=e.active?"true":"false",t.setAttribute("aria-pressed",e.active?"true":"false"),t.addEventListener("click",()=>{e.setActive(!e.active),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.options.renderTimelineEventCount(),this.options.requestConfigSync(),this.renderSummary()});const i=document.createElement("span");i.textContent=Z$(e);const s=document.createElement("strong");return s.textContent=Ox(e.active,e.count),t.append(i,s),t}renderBoostPickupFiltersWindow(){const e=this.options.getContext(),t=this.options.boostPickupFilters.renderSettings(e,{showHeader:!1});this.options.elements.boostPickupFilters.replaceChildren(t)}renderTouchControlsWindow(){const e=this.options.getContext(),i=this.options.modules.find(s=>s.id===kx)?.renderSettings?.(e)??null;this.options.elements.touchControls.replaceChildren(),i instanceof HTMLElement&&this.options.elements.touchControls.append(i)}}function am(n,e){const t=document.createElement("section");t.className="module-summary-group";const i=document.createElement("h3");i.textContent=n;const s=document.createElement("div");return s.className="module-list",s.append(...e),t.append(i,s),t}function Ox(n,e){const t=n?"On":"Off";return e==null?t:`${t} ${e}`}function Z$(n){return n.group==="Replay"?n.label:`${n.label} events`}function rm(n,e){const t={"absolute-positioning:ranges":"Position zones","backboard:events":"Backboard","ball-carry:events":"Ball carry","boost:ranges":"Boost pickup timeline","bump:events":"Bump","ceiling-shot:events":"Ceiling shot","demo:events":"Demo","dodge-reset:events":"Dodge refresh","double-tap:events":"Double tap","fifty-fifty:events":"50/50","fifty-fifty:ranges":"50/50","dodge:events":"Dodge","half-flip:events":"Half flip","possession:ranges":"Possession","powerslide:events":"Powerslide","powerslide:ranges":"Powerslide","ball_half:ranges":"Half control","ball_third:ranges":"Third control","rush:ranges":"Rush","speed-flip:events":"Speed flip","touch:events":"Touch","wavedash:events":"Wavedash"},i={"absolute-positioning":"Position zones","ceiling-shot":"Ceiling shot labels","fifty-fifty":"50/50 labels",dodge:"Dodge impulse arrows",ball_half:"Half control","relative-positioning":"Player roles","speed-flip":"Speed flip labels",touch:"Touch labels"};return e==="effects"?i[n.id]??n.label:t[`${n.id}:${e}`]??`${n.label} timeline`}function J$(n){return new j$(n)}var gn=Uint8Array,fi=Uint16Array,Wg=Int32Array,rf=new gn([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),of=new gn([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),b_=new gn([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),YE=function(n,e){for(var t=new fi(31),i=0;i<31;++i)t[i]=e+=1<>1|(Ut&21845)<<1;Zs=(Zs&52428)>>2|(Zs&13107)<<2,Zs=(Zs&61680)>>4|(Zs&3855)<<4,w_[Ut]=((Zs&65280)>>8|(Zs&255)<<8)>>1}var hs=(function(n,e,t){for(var i=n.length,s=0,a=new fi(e);s>l]=c}else for(o=new fi(i),s=0;s>15-n[s]);return o}),da=new gn(288);for(var Ut=0;Ut<144;++Ut)da[Ut]=8;for(var Ut=144;Ut<256;++Ut)da[Ut]=9;for(var Ut=256;Ut<280;++Ut)da[Ut]=7;for(var Ut=280;Ut<288;++Ut)da[Ut]=8;var Ql=new gn(32);for(var Ut=0;Ut<32;++Ut)Ql[Ut]=5;var eW=hs(da,9,0),tW=hs(da,9,1),nW=hs(Ql,5,0),iW=hs(Ql,5,1),om=function(n){for(var e=n[0],t=1;te&&(e=n[t]);return e},Fi=function(n,e,t){var i=e/8|0;return(n[i]|n[i+1]<<8)>>(e&7)&t},lm=function(n,e){var t=e/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},Xg=function(n){return(n+7)/8|0},lf=function(n,e,t){return(e==null||e<0)&&(e=0),(t==null||t>n.length)&&(t=n.length),new gn(n.subarray(e,t))},sW=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],os=function(n,e,t){var i=new Error(e||sW[n]);if(i.code=n,Error.captureStackTrace&&Error.captureStackTrace(i,os),!t)throw i;return i},aW=function(n,e,t,i){var s=n.length,a=0;if(!s||e.f&&!e.l)return t||new gn(0);var r=!t,o=r||e.i!=2,l=e.i;r&&(t=new gn(s*3));var c=function(xe){var Ae=t.length;if(xe>Ae){var L=new gn(Math.max(Ae*2,xe));L.set(t),t=L}},u=e.f||0,d=e.p||0,h=e.b||0,f=e.l,p=e.d,g=e.m,_=e.n,m=s*8;do{if(!f){u=Fi(n,d,1);var v=Fi(n,d+1,3);if(d+=3,v)if(v==1)f=tW,p=iW,g=9,_=5;else if(v==2){var x=Fi(n,d,31)+257,M=Fi(n,d+10,15)+4,C=x+Fi(n,d+5,31)+1;d+=14;for(var w=new gn(C),E=new gn(19),R=0;R>4;if(y<16)w[R++]=y;else{var F=0,W=0;for(y==16?(W=3+Fi(n,d,3),d+=2,F=w[R-1]):y==17?(W=3+Fi(n,d,7),d+=3):y==18&&(W=11+Fi(n,d,127),d+=7);W--;)w[R++]=F}}var H=w.subarray(0,x),ne=w.subarray(x);g=om(H),_=om(ne),f=hs(H,g,1),p=hs(ne,_,1)}else os(1);else{var y=Xg(d)+4,b=n[y-4]|n[y-3]<<8,T=y+b;if(T>s){l&&os(0);break}o&&c(h+b),t.set(n.subarray(y,T),h),e.b=h+=b,e.p=d=T*8,e.f=u;continue}if(d>m){l&&os(0);break}}o&&c(h+131072);for(var oe=(1<>4;if(d+=F&15,d>m){l&&os(0);break}if(F||os(2),De<256)t[h++]=De;else if(De==256){Ie=d,f=null;break}else{var Xe=De-254;if(De>264){var R=De-257,ke=rf[R];Xe=Fi(n,d,(1<>4;Z||os(3),d+=Z&15;var ne=Q$[se];if(se>3){var ke=of[se];ne+=lm(n,d)&(1<m){l&&os(0);break}o&&c(h+131072);var Se=h+Xe;if(h>8},rl=function(n,e,t){t<<=e&7;var i=e/8|0;n[i]|=t,n[i+1]|=t>>8,n[i+2]|=t>>16},cm=function(n,e){for(var t=[],i=0;ih&&(h=a[i].s);var f=new fi(h+1),p=S_(t[u-1],f,0);if(p>e){var i=0,g=0,_=p-e,m=1<<_;for(a.sort(function(x,M){return f[M.s]-f[x.s]||x.f-M.f});ie)g+=m-(1<>=_;g>0;){var y=a[i].s;f[y]=0&&g;--i){var b=a[i].s;f[b]==e&&(--f[b],++g)}p=e}return{t:new gn(f),l:p}},S_=function(n,e,t){return n.s==-1?Math.max(S_(n.l,e,t+1),S_(n.r,e,t+1)):e[n.s]=t},Nx=function(n){for(var e=n.length;e&&!n[--e];);for(var t=new fi(++e),i=0,s=n[0],a=1,r=function(l){t[i++]=l},o=1;o<=e;++o)if(n[o]==s&&o!=e)++a;else{if(!s&&a>2){for(;a>138;a-=138)r(32754);a>2&&(r(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(r(s),--a;a>6;a-=6)r(8304);a>2&&(r(a-3<<5|8208),a=0)}for(;a--;)r(s);a=1,s=n[o]}return{c:t.subarray(0,i),n:e}},ol=function(n,e){for(var t=0,i=0;i>8,n[s+2]=n[s]^255,n[s+3]=n[s+1]^255;for(var a=0;a4&&!E[b_[D-1]];--D);var O=c+5<<3,k=ol(s,da)+ol(a,Ql)+r,U=ol(s,h)+ol(a,g)+r+14+3*D+ol(M,E)+2*M[16]+3*M[17]+7*M[18];if(l>=0&&O<=k&&O<=U)return QE(e,u,n.subarray(l,l+c));var F,W,H,ne;if(Es(e,u,1+(U15&&(Es(e,u,De[C]>>5&127),u+=De[C]>>12)}}else F=eW,W=da,H=nW,ne=Ql;for(var C=0;C255){var Xe=ke>>18&31;rl(e,u,F[Xe+257]),u+=W[Xe+257],Xe>7&&(Es(e,u,ke>>23&31),u+=rf[Xe]);var Z=ke&31;rl(e,u,H[Z]),u+=ne[Z],Z>3&&(rl(e,u,ke>>5&8191),u+=of[Z])}else rl(e,u,F[ke]),u+=W[ke]}return rl(e,u,F[256]),u+W[256]},rW=new Wg([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),e1=new gn(0),oW=function(n,e,t,i,s,a){var r=a.z||n.length,o=new gn(i+r+5*(1+Math.ceil(r/7e3))+s),l=o.subarray(i,o.length-s),c=a.l,u=(a.r||0)&7;if(e){u&&(l[0]=a.r>>3);for(var d=rW[e-1],h=d>>13,f=d&8191,p=(1<7e3||E>24576)&&(F>423||!c)){u=Ux(n,l,0,b,T,x,C,E,D,w-D,u),E=M=C=0,D=w;for(var W=0;W<286;++W)T[W]=0;for(var W=0;W<30;++W)x[W]=0}var H=2,ne=0,oe=f,pe=k-U&32767;if(F>2&&O==y(w-pe))for(var Ie=Math.min(h,F)-1,De=Math.min(32767,w),Xe=Math.min(258,F);pe<=De&&--oe&&k!=U;){if(n[w+H]==n[w+H-pe]){for(var ke=0;keH){if(H=ke,ne=pe,ke>Ie)break;for(var Z=Math.min(pe,ke-2),se=0,W=0;Wse&&(se=ie,U=Se)}}}k=U,U=g[k],pe+=k-U&32767}if(ne){b[E++]=268435456|x_[H]<<18|Fx[ne];var xe=x_[H]&31,Ae=Fx[ne]&31;C+=rf[xe]+of[Ae],++T[257+xe],++x[Ae],R=w+H,++M}else b[E++]=n[w],++T[n[w]]}}for(w=Math.max(w,R);w=r&&(l[u/8|0]=c,L=r),u=QE(l,u+1,n.subarray(w,L))}a.i=r}return lf(o,0,i+Xg(u)+s)},lW=function(n,e,t,i,s){if(!s&&(s={l:1},e.dictionary)){var a=e.dictionary.subarray(-32768),r=new gn(a.length+n.length);r.set(a),r.set(n,a.length),n=r,s.w=a.length}return oW(n,e.level==null?6:e.level,e.mem==null?s.l?Math.ceil(Math.max(8,Math.min(13,Math.log(n.length)))*1.5):20:12+e.mem,t,i,s)};function cW(n,e){return lW(n,e||{},0,0)}function t1(n,e){return aW(n,{i:2},e,e)}var Bx=typeof TextEncoder<"u"&&new TextEncoder,T_=typeof TextDecoder<"u"&&new TextDecoder,uW=0;try{T_.decode(e1,{stream:!0}),uW=1}catch{}var dW=function(n){for(var e="",t=0;;){var i=n[t++],s=(i>127)+(i>223)+(i>239);if(t+s>n.length)return{s:e,r:lf(n,t-1)};s?s==3?(i=((i&15)<<18|(n[t++]&63)<<12|(n[t++]&63)<<6|n[t++]&63)-65536,e+=String.fromCharCode(55296|i>>10,56320|i&1023)):s&1?e+=String.fromCharCode((i&31)<<6|n[t++]&63):e+=String.fromCharCode((i&15)<<12|(n[t++]&63)<<6|n[t++]&63):e+=String.fromCharCode(i)}};function hW(n,e){var t;if(Bx)return Bx.encode(n);for(var i=n.length,s=new gn(n.length+(n.length>>1)),a=0,r=function(c){s[a++]=c},t=0;ts.length){var o=new gn(a+8+(i-t<<1));o.set(s),s=o}var l=n.charCodeAt(t);l<128||e?r(l):l<2048?(r(192|l>>6),r(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|n.charCodeAt(++t)&1023,r(240|l>>18),r(128|l>>12&63),r(128|l>>6&63),r(128|l&63)):(r(224|l>>12),r(128|l>>6&63),r(128|l&63))}return lf(s,0,a)}function n1(n,e){var t;if(T_)return T_.decode(n);var i=dW(n),s=i.s,t=i.r;return t.length&&os(8),s}const M_=1,E_="cfg",zx="cfgDebug";function fW(n){let e="";for(const t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function pW(n){const e=n.replaceAll("-","+").replaceAll("_","/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=atob(t),s=new Uint8Array(i.length);for(let a=0;a!Ai(e)||!PW(e.id)?null:{id:e.id,placement:s1(e.placement)}).filter(e=>e!==null):[]}function AW(n){return Array.isArray(n)?n.map(e=>!Ai(e)||typeof e.id!="string"||!IW(e.kind)?null:{id:e.id,kind:e.kind,placement:s1(e.placement),playerId:a1(e.playerId)??null,team:e.team==="orange"?"orange":e.team==="blue"?"blue":null,entries:RW(e.entries)}).filter(e=>e!==null):[]}function RW(n){return Array.isArray(n)?n.map(e=>!Ai(e)||typeof e.statId!="string"?null:{statId:e.statId,targetId:typeof e.targetId=="string"?e.targetId:void 0}).filter(e=>e!==null):[]}function s1(n){const e=Ai(n)?n:{},t=Ai(e.viewport)?e.viewport:{};return{x:Rn(e.x)??8,y:Rn(e.y)??8,viewport:{width:sh(t.width)??1,height:sh(t.height)??1},zIndex:Rn(e.zIndex),visible:Zn(e.visible)??!0}}function PW(n){return n==="camera"||n==="scoreboard"||n==="playback"||n==="recording"||n==="mechanics"||n==="event-playlist"||n==="mechanics-review"||n==="replay-loading"||n==="boost-pickups"||n==="touch-controls"||n==="touch-legend"||n==="shot-visualization"||n==="missed-events"}function IW(n){return n==="player"||n==="team"||n==="all-players"||n==="all-teams"||n==="kickoff-overview"||n==="goals-overview"||n==="ad-hoc"}function Ai(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Rn(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function sh(n){const e=Rn(n);return e!==void 0&&e>0?e:void 0}function Zn(n){return typeof n=="boolean"?n:void 0}function a1(n){return n===null?null:typeof n=="string"?n:void 0}function ll(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"):[]}function Hx(n,e,t){return Math.min(t,Math.max(e,n))}const LW=["camera","scoreboard","playback","recording","mechanics","event-playlist","mechanics-review","replay-loading","boost-pickups","touch-controls","touch-legend","shot-visualization","missed-events"];class DW{constructor(e){this.options=e}nextZIndex=30;reset(){this.nextZIndex=30}bringToFront(e){e.style.zIndex=`${this.nextZIndex++}`}show(e){const t=this.mustWindow(e);t.hidden=!1,this.bringToFront(t),this.options.requestConfigSync()}toggle(e){const t=this.mustWindow(e);t.hidden=!t.hidden,t.hidden||this.bringToFront(t),this.options.requestConfigSync()}hide(e){const t=this.mustWindow(e);t.hidden=!0,this.options.requestConfigSync()}readPlacement(e){const t=Number.parseInt(e.style.zIndex,10);return{x:this.readCoordinate(e,"--window-x"),y:this.readCoordinate(e,"--window-y"),viewport:Vx(),zIndex:Number.isFinite(t)?t:void 0,visible:!e.hidden}}applyPlacement(e,t){const i=bW(t,Vx());e.style.setProperty("--window-x",`${i.x}px`),e.style.setProperty("--window-y",`${i.y}px`),e.hidden=!t.visible,t.zIndex!==void 0&&(e.style.zIndex=`${t.zIndex}`,this.nextZIndex=Math.max(this.nextZIndex,t.zIndex+1))}getSingletonConfigs(){const e=[],t=this.options.getRoot();for(const i of LW){const s=t.querySelector(`[data-window-id="${i}"]`);s&&e.push({id:i,placement:this.readPlacement(s)})}return e}applySingletonConfigs(e){const t=this.options.getRoot();for(const i of e){const s=t.querySelector(`[data-window-id="${i.id}"]`);s&&this.applyPlacement(s,i.placement)}}installDragging(e,t){e.addEventListener("pointerdown",i=>{if(!(i.target instanceof HTMLElement)||kW(i.target))return;const s=i.target.closest("[data-window-id]");if(!s||s.hidden)return;this.bringToFront(s);const a=i.clientX,r=i.clientY,o=s.getBoundingClientRect(),l=i.pointerId;s.setPointerCapture(l),i.preventDefault();const c=d=>{const h=Math.max(8,Math.min(window.innerWidth-120,o.left+d.clientX-a)),f=Math.max(8,Math.min(window.innerHeight-100,o.top+d.clientY-r));s.style.setProperty("--window-x",`${h}px`),s.style.setProperty("--window-y",`${f}px`)},u=()=>{s.releasePointerCapture(l),s.removeEventListener("pointermove",c),s.removeEventListener("pointerup",u),s.removeEventListener("pointercancel",u),this.options.requestConfigSync()};s.addEventListener("pointermove",c),s.addEventListener("pointerup",u),s.addEventListener("pointercancel",u)},{signal:t})}mustWindow(e){const t=this.options.getRoot().querySelector(`[data-window-id="${e}"]`);if(!t)throw new Error(`Missing window for id: ${e}`);return t}readCoordinate(e,t){const i=e.style.getPropertyValue(t).trim(),s=getComputedStyle(e).getPropertyValue(t).trim(),a=i||s,r=Number.parseFloat(a);if(Number.isFinite(r))return r;const o=e.getBoundingClientRect();return t==="--window-y"?o.top:o.left}}function Vx(){return{width:Math.max(1,window.innerWidth),height:Math.max(1,window.innerHeight)}}function kW(n){return n instanceof Element&&!!n.closest("button, input, select, textarea, option, label, a, [data-no-drag]")}function OW(n){return new DW(n)}class FW{constructor(e){this.options=e}activeSourceIds=null;autoFollow=!0;lastActiveKey=null;activeItem=null;renderedItems=[];reset(){this.activeSourceIds=null,this.lastActiveKey=null,this.activeItem=null,this.renderedItems=[]}render(){this.options.body.replaceChildren(),this.lastActiveKey=null,this.activeItem=null,this.renderedItems=[];const e=this.options.getSources();if(e.length===0){const _=document.createElement("p");_.className="stat-window-empty",_.textContent=this.options.getReplayPlayer()?"No events loaded.":"Load a replay to see events.",this.options.body.append(_);return}const t=v_(e,this.activeSourceIds),i=W$({sources:e,activeSourceIds:this.activeSourceIds,replayPlayers:this.options.getReplayPlayer()?.replay.players??[]}),s=document.createElement("div");s.className="event-playlist-toolbar";const a=document.createElement("details");a.className="event-playlist-filter",a.dataset.noDrag="true";const r=document.createElement("summary");r.textContent=`Filters ${t.size}/${e.length}`,a.append(r);const o=document.createElement("div");o.className="event-playlist-filter-panel";const l=document.createElement("div");l.className="event-playlist-filter-actions";const c=document.createElement("button");c.type="button",c.textContent="All",c.addEventListener("click",()=>{this.activeSourceIds=new Set(e.map(m=>m.id)),this.lastActiveKey=null,this.render();const _=this.options.getReplayPlayer()?.getState();_&&this.syncTimeline(_)});const u=document.createElement("button");u.type="button",u.textContent="None",u.addEventListener("click",()=>{this.activeSourceIds=new Set,this.lastActiveKey=null,this.render()}),l.append(c,u),o.append(l);const d=new Map;for(const _ of e){const m=d.get(_.group)??[];m.push(_),d.set(_.group,m)}for(const[_,m]of d){const v=document.createElement("section");v.className="event-playlist-filter-group";const y=document.createElement("h3");y.textContent=_,v.append(y);for(const b of m){const T=document.createElement("label");T.className="toggle event-playlist-filter-option";const x=document.createElement("input");x.type="checkbox",x.checked=t.has(b.id),x.addEventListener("change",()=>{this.setSourceSelection(e,C=>{x.checked?C.add(b.id):C.delete(b.id)})});const M=document.createElement("span");M.textContent=`${b.label} (${b.events.length})`,T.append(x,M),v.append(T)}o.append(v)}a.append(o);const h=document.createElement("label");h.className="toggle event-playlist-follow";const f=document.createElement("input");f.type="checkbox",f.checked=this.autoFollow,f.addEventListener("change",()=>{this.autoFollow=f.checked;const _=this.options.getReplayPlayer()?.getState();_&&this.syncTimeline(_,{forceScroll:!0})});const p=document.createElement("span");p.textContent="Auto-follow",h.append(f,p),s.append(a,h);const g=document.createElement("div");if(g.className="event-playlist-list",g.dataset.noDrag="true",i.length===0){const _=document.createElement("p");_.className="stat-window-empty",t.size===0?_.textContent="No event types selected.":_.textContent="No events in selected event types.",g.append(_)}else for(const _ of i){const m=document.createElement("button");m.type="button",m.className="event-playlist-item",m.dataset.eventKey=_.key,m.dataset.eventTime=`${_.event.time}`,m.style.setProperty("--event-color",_.color),Number.isFinite(_.event.time)&&this.renderedItems.push({key:_.key,time:_.event.time,element:m}),m.addEventListener("click",()=>{this.options.cueTimelineEvent(_.event)});const v=document.createElement("span");v.className="event-playlist-time",v.textContent=this.options.formatTime(_.event.time);const y=document.createElement("span");y.className="event-playlist-main";const b=document.createElement("strong");b.textContent=_.event.label??_.sourceLabel;const T=document.createElement("span");T.textContent=[_.event.playerName??null,_.event.frame!==void 0?`frame ${_.event.frame}`:null,_.sourceLabel].filter(x=>!!x).join(" · "),y.append(b,T),m.append(v,y),g.append(m)}this.options.body.append(s,g)}syncTimeline(e,t={}){if(!this.options.body.querySelector(".event-playlist-list"))return;const s=this.getActiveItem(e.currentTime),a=s?.dataset.eventKey??null;a===this.lastActiveKey&&!t.forceScroll||(this.activeItem?.isConnected?this.activeItem.dataset.active="false":this.activeItem&&(this.activeItem=null),s?(s.dataset.active="true",this.activeItem=s,(this.autoFollow||t.forceScroll)&&s.scrollIntoView({block:"nearest"})):this.activeItem=null,this.lastActiveKey=a)}setSourceSelection(e,t){const i=v_(e,this.activeSourceIds);t(i),this.activeSourceIds=i,this.lastActiveKey=null,this.render();const s=this.options.getReplayPlayer()?.getState();s&&this.syncTimeline(s)}getActiveItem(e){const t=this.renderedItems;if(t.length===0)return null;let i=0,s=t.length-1;for(;ie.getConfig||e.applyConfig).map(e=>{const t={id:e.id};return e.id==="boost"&&(t.aliases=["boost-pickup-animation"]),e.getConfig&&(t.getConfig=()=>e.getConfig?.()),e.applyConfig&&(t.applyConfig=i=>e.applyConfig?.(i)),t})}function KW(n){return HW(o1(n))}function qW({replayPlayer:n,playbackRate:e,skipPostGoalTransitions:t,skipKickoffs:i}){const s=n?.getState();return{currentTime:s?.currentTime,playing:s?.playing,rate:s?.speed??cf(Number(e?.value??1)),skipPostGoalTransitions:n?s?.skipPostGoalTransitionsEnabled:t.checked,skipKickoffs:n?s?.skipKickoffsEnabled:i.checked}}function YW({replayPlayer:n,cameraControlsController:e}){const t=n?.getState(),i=t?sE(t):e?.ballCamMode;return{mode:t?.cameraViewMode,freePreset:e?.freeCameraPreset??null,attachedPlayerId:t?.attachedPlayerId,ballCam:i===void 0?void 0:i==="on",useReplayBallCam:i===void 0?void 0:i==="player",usePlayerCameraSettings:t?.customCameraSettings===null,autoPossession:e?.autoPossessionEnabled,customSettings:t?.customCameraSettings,nameplateLiftUu:e?.nameplateLiftUu}}function jW({playback:n,camera:e,activeTimelineEventSourceIds:t,activeTimelineRangeModuleIds:i,activeMechanicTimelineKinds:s,activeRenderEffectModuleIds:a,initialConfig:r,replayPlayer:o,boostPadOverlayEnabled:l,recording:c,singletonWindows:u,statsWindows:d,moduleConfigs:h}){return{version:M_,playback:n,camera:e,overlays:{timelineEvents:[...t],timelineRanges:[...i],mechanics:[...s],renderEffects:[...a],...r?.overlays.pluginRenderEffects!==void 0?{pluginRenderEffects:[...r.overlays.pluginRenderEffects]}:{},...r?.overlays.pluginHudOverlay!==void 0?{pluginHudOverlay:r.overlays.pluginHudOverlay}:{},followedPlayerHud:!1,boostPads:l,boostPickupAnimation:o?.getState().boostPickupAnimationEnabled??!1,hitboxWireframes:o?.getState().hitboxWireframesEnabled??!1,hitboxOnlyMode:o?.getState().hitboxOnlyModeEnabled??!1},recording:c,singletonWindows:u,statsWindows:d,moduleConfigs:h}}function ZW(n,e,t){return{currentTime:n.currentTime,playing:n.playing,speed:n.rate,customCameraSettings:r1(e),cameraViewMode:e.mode,attachedPlayerId:e.attachedPlayerId,...Vb(e)==="player"?{useReplayBallCam:!0}:{ballCamEnabled:Vb(e)==="on"},boostPickupAnimationEnabled:t.overlays.boostPickupAnimation,hitboxWireframesEnabled:t.overlays.hitboxWireframes,hitboxOnlyModeEnabled:t.overlays.hitboxOnlyMode,skipPostGoalTransitionsEnabled:n.skipPostGoalTransitions,skipKickoffsEnabled:n.skipKickoffs}}function JW(n,e,t){console.groupCollapsed("[subtr-actor] stats player cfg load"),console.log("location.href",window.location.href),console.log("location.search",n.search||"(empty)"),console.log("location.hash",n.hash||"(empty)"),console.table([...n.searchParams.map(([i,s])=>({source:"search",name:i,value:s})),...n.hashParams.map(([i,s])=>({source:"hash",name:i,value:s}))]),console.log("cfg selected source",n.selectedSource??"(none)"),console.log("cfg selected raw text",n.selectedValue??"(none)"),console.log("cfg selected raw length",n.selectedValue?.length??0),console.log("cfg search values",n.searchValues),console.log("cfg hash values",n.hashValues),n.hashValues.length>0&&n.searchValues.length>0&&console.warn("Both hash and search contain cfg; hash cfg is used."),e&&(console.log("cfg normalized JSON",JSON.stringify(e,null,2)),console.log("cfg normalized object",e)),t&&console.error("cfg decode/apply error",t),console.groupEnd()}function Gx(n,e){const{style:t}=n.renderer.domElement;t.visibility=e?"hidden":"",t.pointerEvents=e?"none":""}function $x(n,e={}){const t=e.destroyPlayer??!0,i=e.clearPlayerPluginHandles??!0,s=n.getUnsubscribe();s&&(s(),n.setUnsubscribe(null)),n.teardownActiveModules(),t&&(n.getReplayPlayer()?.destroy(),n.setReplayPlayer(null)),i&&(n.setCanvasRecorder(null),n.setTimelineOverlay(null)),n.setLoadedReplayName(null),n.setStatsTimeline(null),n.setStatsFrameLookup(null),n.setStatRegistry(Jl()),n.clearTimelineEventSources(),n.clearTimelineRangeSources(),n.clearStandalonePlugins(),n.clearRenderCaches(),n.resetEventPlaylistWindow(),n.renderModuleSummary(),n.renderScoreboard(),n.renderTimelineEventCount(),n.renderMechanicsTimelineControls(),n.renderEventPlaylistWindow(),n.renderModuleSettings(),n.syncRecordingWindow()}async function QW(n,e,t){const{elements:i}=t;let s=null;i.statusReadout.textContent=n.preparingStatus,i.fileInput.disabled=!0,t.getReplayLoadModal()?.show(n.name,n.preparingStatus),t.setTransportEnabled(!1),t.getCameraControlsController()?.syncAvailability(),i.emptyState.hidden=t.getReplayPlayer()!==null,t.getReplayPlayer()?.pause();try{i.statusReadout.textContent="Parsing replay...",t.getReplayLoadModal()?.show(n.name,"Parsing replay...");const a=await e,{replay:r}=a,o=t.getReplayPlayer();if(o){$x(t,{destroyPlayer:!1,clearPlayerPluginHandles:!1});const h=new xw(a.raw);await o.replaceReplay(h,r,{preservePlayback:!1}),t.setStatsTimeline(a.statsTimeline),t.setStatsFrameLookup(a.statsFrameLookup),t.setStatRegistry(Jl(null)),t.setReplayPlayer(o),t.syncBoostPadOverlayPlugin(),t.setupActiveModules(),t.setUnsubscribe(o.subscribe(t.renderSnapshot));const f=t.getInitialConfig();if(f){t.setApplyingConfig(!0);try{t.applyConfigToReplayPlayer(f)}finally{t.setApplyingConfig(!1)}}t.getCameraControlsController()?.populateAttachedPlayerOptions(r.players),i.emptyState.hidden=!0,i.statusReadout.textContent=`Loaded ${n.name}`,t.setLoadedReplayName(n.name),i.playersReadout.textContent=r.players.map(p=>p.name).join(", "),i.framesReadout.textContent=`${r.frameCount}`,t.renderModuleSummary(),t.renderTimelineEventCount(),t.renderMechanicsTimelineControls(),t.resetEventPlaylistWindow(),t.renderEventPlaylistWindow(),t.setTransportEnabled(!0),t.getCameraControlsController()?.syncAvailability(o.getState()),t.renderSnapshot(o.getState()),t.renderStatsWindows(o.getState().frameIndex),t.renderScoreboard(o.getState().frameIndex),t.syncEventPlaylistTimeline(o.getState(),{forceScroll:!0}),t.renderModuleSettings(),t.syncRecordingWindow(),t.getReplayLoadModal()?.hide();return}const l=QN({replayEventsLabel:"Replay",replayEvents:h=>t.withTimelineEventSeekTimes(t.getReplayTimelineEvents(h.replay))}),c=kN({onStatusChange:t.syncRecordingWindow});t.setCanvasRecorder(c);const u=t.getInitialConfig(),d=e3(i.viewport,a,{initialPlaybackRate:u?.playback.rate,initialCustomCameraSettings:r1(u?.camera),initialAttachedPlayerId:u?.camera.attachedPlayerId??null,initialCameraViewMode:u?.camera.mode,initialBoostPickupAnimationEnabled:u?.overlays.boostPickupAnimation??!1,initialHitboxWireframesEnabled:u?.overlays.hitboxWireframes??i.hitboxWireframes.checked,initialHitboxOnlyModeEnabled:u?.overlays.hitboxOnlyMode??i.hitboxOnlyMode.checked,initialSkipPostGoalTransitionsEnabled:i.skipPostGoalTransitions.checked,initialSkipKickoffsEnabled:i.skipKickoffs.checked,plugins:[cN({onSample:({renderFps:h,replayFps:f})=>{const p=document.getElementById("render-fps-readout"),g=document.getElementById("replay-fps-readout");p&&(p.textContent=`${h.toFixed(0)} fps`),g&&(g.textContent=`${f.toFixed(0)} fps`)}}),bu(u3({floatingLiftUu:()=>t.getCameraControlsController()?.nameplateLiftUu})),bu(RN({includePickup:t.includeBoostPickupAnimationPickup})),bu(c),bu(l)]});if(s=d,Gx(d,!0),await d.ready,$x(t),s=null,Gx(d,!1),t.setStatsTimeline(a.statsTimeline),t.setStatsFrameLookup(a.statsFrameLookup),t.setStatRegistry(Jl(null)),t.setTimelineOverlay(l),t.setReplayPlayer(d),t.syncBoostPadOverlayPlugin(),t.setupActiveModules(),t.setUnsubscribe(d.subscribe(t.renderSnapshot)),u){t.setApplyingConfig(!0);try{t.applyConfigToReplayPlayer(u)}finally{t.setApplyingConfig(!1)}}t.getCameraControlsController()?.populateAttachedPlayerOptions(r.players),i.emptyState.hidden=!0,i.statusReadout.textContent=`Loaded ${n.name}`,t.setLoadedReplayName(n.name),i.playersReadout.textContent=r.players.map(h=>h.name).join(", "),i.framesReadout.textContent=`${r.frameCount}`,t.renderModuleSummary(),t.renderTimelineEventCount(),t.renderMechanicsTimelineControls(),t.resetEventPlaylistWindow(),t.renderEventPlaylistWindow(),t.setTransportEnabled(!0),t.getCameraControlsController()?.syncAvailability(d.getState()),t.renderSnapshot(d.getState()),t.renderStatsWindows(d.getState().frameIndex),t.renderScoreboard(d.getState().frameIndex),t.syncEventPlaylistTimeline(d.getState(),{forceScroll:!0}),t.renderModuleSettings(),t.syncRecordingWindow(),t.getReplayLoadModal()?.hide()}catch(a){throw t.getReplayLoadModal()?.hide(),s?.destroy(),t.getReplayPlayer()||(i.emptyState.hidden=!1,t.setCanvasRecorder(null)),t.syncRecordingWindow(),a}finally{i.fileInput.disabled=!1}}function e8(n){if(n<=0)return"--";const e=["B","KB","MB","GB"];let t=n,i=0;for(;t>=1024&&i=10?1:2;return`${t.toFixed(s)} ${e[i]}`}function t8(n){if(!n)return"No replay";if(n.error)return n.error;switch(n.state){case"idle":return"Idle";case"recording":return"Recording";case"stopping":return"Stopping";case"ready":return"Ready";case"error":return"Error"}}function n8({fpsValue:n,playbackRateValue:e}){const t=Number(n),i=Number(e);return{fps:Number.isFinite(t)?Math.max(1,Math.min(120,Math.trunc(t))):60,playbackRate:Number.isFinite(i)?Math.max(.1,i):1}}function i8(n,e=new Date){const i=(n?.replace(/\.replay$/i,"")||"replay").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,""),s=e.toISOString().replace(/[:.]/g,"-");return`${i||"replay"}-${s}.webm`}function s8(n,e){const t=URL.createObjectURL(n),i=document.createElement("a");i.href=t,i.download=e,document.body.append(i),i.click(),i.remove(),window.setTimeout(()=>URL.revokeObjectURL(t),0)}class a8{constructor(e){this.options=e}getConfigSnapshot(){const{elements:e}=this.options;return{fps:Number(e.fps.value),playbackRate:Number(e.playbackRate.value)}}applyConfig(e){const{elements:t}=this.options;e.fps!==void 0&&(t.fps.value=`${e.fps}`),e.playbackRate!==void 0&&(t.playbackRate.value=`${e.playbackRate}`)}sync(e=this.options.getCanvasRecorder()?.getStatus()??null){const{elements:t}=this.options,i=this.options.getCanvasRecorder()!==null&&this.options.getReplayPlayer()!==null,s=e?.state??"idle",a=s==="recording"||s==="stopping",r=(this.options.getCanvasRecorder()?.getRecording()??null)!==null;t.status.textContent=t8(e),t.elapsed.textContent=`${(e?.elapsedSeconds??0).toFixed(1)}s`,t.size.textContent=e8(e?.sizeBytes??0),t.type.textContent=e?.mimeType||"WebM",t.start.disabled=!i||a,t.fullReplay.disabled=!i||a,t.stop.disabled=!i||!a,t.download.disabled=!r||a,t.clear.disabled=!r||a,t.fps.disabled=a,t.playbackRate.disabled=a}installEventListeners(e){const{elements:t}=this.options;t.start.addEventListener("click",()=>{const i=this.options.getCanvasRecorder();if(i)try{const{fps:s}=this.getRecordingOptions();i.start({fps:s}),this.sync()}catch(s){console.error("Failed to start recording:",s),this.options.setStatus(s instanceof Error?s.message:"Failed to start recording"),this.sync(i.getStatus())}},{signal:e}),t.fullReplay.addEventListener("click",()=>{const i=this.options.getCanvasRecorder();if(!i)return;const{fps:s,playbackRate:a}=this.getRecordingOptions();i.recordFullReplay({fps:s,playbackRate:a,restorePlaybackState:!0}).catch(r=>{console.error("Failed to record replay:",r),this.options.setStatus(r instanceof Error?r.message:"Failed to record replay"),this.sync(this.options.getCanvasRecorder()?.getStatus()??null)}),this.sync()},{signal:e}),t.stop.addEventListener("click",()=>{this.options.getCanvasRecorder()?.stop().catch(i=>{console.error("Failed to stop recording:",i),this.options.setStatus(i instanceof Error?i.message:"Failed to stop recording")}),this.sync()},{signal:e}),t.download.addEventListener("click",()=>{const i=this.options.getCanvasRecorder()?.getRecording();i&&s8(i,i8(this.options.getLoadedReplayName()))},{signal:e}),t.clear.addEventListener("click",()=>{try{this.options.getCanvasRecorder()?.clear(),this.sync()}catch(i){console.error("Failed to clear recording:",i)}},{signal:e}),t.fps.addEventListener("change",this.options.requestConfigSync,{signal:e}),t.playbackRate.addEventListener("change",this.options.requestConfigSync,{signal:e})}getRecordingOptions(){const{elements:e}=this.options;return n8({fpsValue:e.fps.value,playbackRateValue:e.playbackRate.value})}}function r8(n){return new a8(n)}class o8{constructor(e){this.options=e}render(e=this.options.getReplayPlayer()?.getState().frameIndex??0){const{body:t}=this.options;t.replaceChildren();const i=this.options.getStatsFrameLookup(),s=i?zt(i,e):null,a=this.options.getReplayPlayer()?.replay??null;if(!s||!a){const o=document.createElement("p");o.className="scoreboard-empty",o.textContent="Load a replay to show the scoreboard.",t.append(o);return}const r=document.createElement("div");r.className="scoreboard-scoreline",r.append(Wx(s.team_zero?.core.goals,!0),c8(),Wx(s.team_one?.core.goals,!1)),t.append(r)}}function l8(n){return typeof n=="number"&&Number.isFinite(n)?`${Math.round(n)}`:"--"}function c8(){const n=document.createElement("span");return n.className="scoreboard-divider",n.textContent="-",n}function Wx(n,e){const t=document.createElement("strong");return t.className=`scoreboard-goal-value ${ta(e)}`,t.textContent=l8(n),t}function u8(n){return new o8(n)}class d8{constructor(e){this.options=e}setTransportEnabled(e,t){const{elements:i}=this.options;i.togglePlayback.disabled=!e,i.previousFrame.disabled=!e,i.nextFrame.disabled=!e,i.playbackRate.disabled=!e,i.skipPostGoalTransitions.disabled=!e,i.skipKickoffs.disabled=!e,i.hitboxWireframes.disabled=!e,i.hitboxOnlyMode.disabled=!e,this.options.getCameraControlsController()?.setTransportEnabled(e,t)}renderSnapshot(e){const{elements:t}=this.options;t.timeReadout.textContent=`${e.currentTime.toFixed(2)}s`,t.frameReadout.textContent=`${e.frameIndex}`,t.durationReadout.textContent=`${e.duration.toFixed(2)}s`,t.playbackStatusReadout.textContent=e.playing?"Playing":"Paused",t.togglePlayback.textContent=e.playing?"Pause":"Play";const i=Math.max(0,this.options.getFrameCount()-1);t.previousFrame.disabled=e.frameIndex<=0,t.nextFrame.disabled=e.frameIndex>=i;const s=cf(e.speed);t.playbackRate.value=`${s}`,t.playbackRateReadout.textContent=qg(s),this.options.getCameraControlsController()?.syncState(e),t.skipPostGoalTransitions.checked=e.skipPostGoalTransitionsEnabled,t.skipKickoffs.checked=e.skipKickoffsEnabled,t.hitboxWireframes.checked=e.hitboxWireframesEnabled,t.hitboxOnlyMode.checked=e.hitboxOnlyModeEnabled,t.emptyState.hidden=!0}}function h8(n){return new d8(n)}function f8({elements:n,signal:e,setLauncherOpen:t,openReplayFilePicker:i,getElementWindowId:s,toggleWindow:a,hideWindow:r,createStatsWindow:o,loadReplayFile:l,togglePlayback:c,stepFrames:u,setPlaybackRate:d,setSkipPostGoalTransitionsEnabled:h,setSkipKickoffsEnabled:f,setHitboxWireframesEnabled:p,setHitboxOnlyModeEnabled:g}){n.launcherToggle.addEventListener("click",()=>{t(n.launcherMenu.hidden)},{signal:e}),n.root.addEventListener("click",m=>{m.target instanceof Element&&(m.target.closest(".top-chrome")||t(!1))},{signal:e}),n.loadReplayAction.addEventListener("click",i,{signal:e}),n.emptyLoadReplay.addEventListener("click",i,{signal:e}),n.root.querySelectorAll("[data-window-toggle]").forEach(m=>{m.addEventListener("click",()=>{const v=m.dataset.windowToggle;v&&(a(v),t(!1))},{signal:e})}),n.root.querySelectorAll("[data-window-hide]").forEach(m=>{m.addEventListener("click",()=>{const v=m.dataset.windowHide??s(m);v&&r(v)},{signal:e})}),n.root.querySelectorAll("[data-create-stats-window]").forEach(m=>{m.addEventListener("click",()=>{o(m.dataset.createStatsWindow)},{signal:e})}),n.fileInput.addEventListener("change",()=>{const m=n.fileInput.files?.[0];m&&l(m)},{signal:e}),n.togglePlayback.addEventListener("click",c,{signal:e}),n.previousFrame.addEventListener("click",()=>u(-1),{signal:e}),n.nextFrame.addEventListener("click",()=>u(1),{signal:e});const _=()=>{const m=cf(Number(n.playbackRate.value));n.playbackRate.value=`${m}`,n.playbackRateReadout.textContent=qg(m),d(m)};n.playbackRate.addEventListener("input",_,{signal:e}),n.playbackRate.addEventListener("change",_,{signal:e}),n.skipPostGoalTransitions.addEventListener("change",()=>{h(n.skipPostGoalTransitions.checked)},{signal:e}),n.skipKickoffs.addEventListener("change",()=>{f(n.skipKickoffs.checked)},{signal:e}),n.hitboxWireframes.addEventListener("change",()=>{p(n.hitboxWireframes.checked)},{signal:e}),n.hitboxOnlyMode.addEventListener("change",()=>{g(n.hitboxOnlyMode.checked)},{signal:e})}const p8=3500;function m8(){const n=document.activeElement;if(!(n instanceof HTMLElement))return!1;if(n.isContentEditable)return!0;const e=n.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"}function _8(n){const{getReplayPlayer:e,signal:t}=n,i={forward:!1,backward:!1,left:!1,right:!1,up:!1,down:!1},s=()=>{i.forward=!1,i.backward=!1,i.left=!1,i.right=!1,i.up=!1,i.down=!1},a=(g,_)=>{switch(g){case"KeyW":return i.forward=_,!0;case"KeyS":return i.backward=_,!0;case"KeyA":return i.left=_,!0;case"KeyD":return i.right=_,!0;case"Space":return i.up=_,!0;case"ShiftLeft":case"ShiftRight":return i.down=_,!0;default:return!1}},r=g=>{g.ctrlKey||g.metaKey||g.altKey||m8()||a(g.code,!0)&&g.preventDefault()},o=g=>{a(g.code,!1)};window.addEventListener("keydown",r,{signal:t}),window.addEventListener("keyup",o,{signal:t}),window.addEventListener("blur",s,{signal:t});const l=new S,c=new S,u=new S,d=new S(0,1,0);let h=null,f=0;const p=g=>{f=requestAnimationFrame(p);const _=h===null?0:Math.min(.1,(g-h)/1e3);h=g;const m=(i.forward?1:0)-(i.backward?1:0),v=(i.right?1:0)-(i.left?1:0),y=(i.up?1:0)-(i.down?1:0);if(_===0||m===0&&v===0&&y===0)return;const b=e();if(!b||b.getState().cameraViewMode!=="free")return;const T=b.camera,x=b.controls;T.getWorldDirection(l),c.set(1,0,0).applyQuaternion(T.quaternion),u.set(0,0,0).addScaledVector(l,m).addScaledVector(c,v).addScaledVector(d,y),u.lengthSq()!==0&&(u.normalize().multiplyScalar(p8*_),T.position.add(u),x.target.add(u))};f=requestAnimationFrame(p),t.addEventListener("abort",()=>{cancelAnimationFrame(f)})}function g8(n,e){const t=new URLSearchParams(n),s=(t.get("replayId")??t.get("replay-id")??e??"").trim();return s.length>0?s:null}function y8(){const n=new URLSearchParams(window.location.search),e=n.get("reviewToken")??n.get("token")??window.localStorage.getItem("rocket_sense_access_token");return e?{Authorization:`Bearer ${e}`}:{}}function v8(n){if(!n.replayId)return null;const e={replay_id:n.replayId,reviewed_mechanic:n.mechanic,reviewed_event_frame:n.frame,reviewed_event_time:n.time,confidence:n.confidence,status:"confirmed"};return n.subjectKind&&n.subjectId&&(e.reviewed_subject_kind=n.subjectKind,e.reviewed_subject_id=n.subjectId),n.startFrame!==null&&(e.reviewed_start_frame=n.startFrame),n.endFrame!==null&&(e.reviewed_end_frame=n.endFrame),n.notes&&n.notes.trim()&&(e.notes=n.notes.trim()),Object.keys(n.context).length>0&&(e.context=n.context),e}function b8(n,e){const t=n.getState(),i=Math.max(0,Math.round(t.frameIndex??0)),s=t.currentTime??0,a=t.attachedPlayerId??null,r=a?n.replay.players.find(o=>o.id===a)?.name??null:null;return{localId:e.localId,mechanic:e.mechanic,frame:i,time:s,subjectKind:a?"player":null,subjectId:a,playerName:r,startFrame:null,endFrame:null,notes:e.notes?.trim()?e.notes.trim():null,confidence:1,replayId:e.replayId,context:{capturedFrom:"stat-evaluation-player",attachedPlayerId:a,playerName:r,durationSeconds:n.replay.duration??null}}}async function x8(n,e="/api/v1/events/reviews"){const t=v8(n);if(!t)return{record:n,ok:!1,message:"No replay id — cannot upload (export JSON instead)."};try{const i=await fetch(e,{method:"POST",headers:{"content-type":"application/json",...y8()},credentials:"same-origin",body:JSON.stringify(t)});if(!i.ok){let s=`${i.status}${i.statusText?` ${i.statusText}`:""}`;try{const a=await i.json();typeof a.error=="string"&&(s=a.error)}catch{}return{record:n,ok:!1,message:s}}return{record:n,ok:!0,message:"uploaded"}}catch(i){return{record:n,ok:!1,message:i instanceof Error?i.message:String(i)}}}const w8=["flick","whiff","double_tap","ceiling_shot","wall_aerial","flip_reset","one_timer","speed_flip","half_flip","wavedash","demo"],S8="m";function T8(){const n=document.activeElement;if(!(n instanceof HTMLElement))return!1;if(n.isContentEditable)return!0;const e=n.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"}function M8(n,e){const t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),i=URL.createObjectURL(t),s=document.createElement("a");s.href=i,s.download=n,document.body.appendChild(s),s.click(),s.remove(),URL.revokeObjectURL(i)}class E8{constructor(e){this.options=e}records=[];localIdSeq=0;installEventListeners(e){const{elements:t}=this.options;for(const i of w8){const s=document.createElement("option");s.value=i,s.textContent=i.replaceAll("_"," "),t.mechanic.appendChild(s)}t.capture.addEventListener("click",()=>this.capture(),{signal:e}),t.export.addEventListener("click",()=>this.exportJson(),{signal:e}),t.upload.addEventListener("click",()=>{this.uploadAll()},{signal:e}),t.clear.addEventListener("click",()=>{this.records.length=0,this.render(),this.setStatus("Cleared.")},{signal:e}),window.addEventListener("keydown",i=>{i.key.toLowerCase()!==S8||i.repeat||i.metaKey||i.ctrlKey||i.altKey||T8()||(i.preventDefault(),this.capture())},{signal:e}),this.render()}capture(){const e=this.options.getReplayPlayer();if(!e){this.setStatus("No replay loaded.");return}this.localIdSeq+=1;const t=b8(e,{mechanic:this.options.elements.mechanic.value||"flick",replayId:this.resolveReplayId(),localId:`missed-${this.localIdSeq}`});this.records.push(t),this.options.showWindow(),this.render(),this.setStatus(`Captured ${t.mechanic} @ ${t.time.toFixed(2)}s`+(t.replayId?".":" (no replay id — export only)."))}exportJson(){if(this.records.length===0){this.setStatus("Nothing to export.");return}M8("missed-events.json",{capturedFrom:"stat-evaluation-player",replayId:this.resolveReplayId(),missedEvents:this.records}),this.setStatus(`Exported ${this.records.length}.`)}async uploadAll(){if(this.records.length===0){this.setStatus("Nothing to upload.");return}let e=0;const t=[];for(const i of[...this.records]){const s=await x8(i);if(s.ok){e+=1;const a=this.records.findIndex(r=>r.localId===i.localId);a>=0&&this.records.splice(a,1)}else t.push(`${i.mechanic}@${i.time.toFixed(1)}s: ${s.message}`)}this.render(),this.setStatus(t.length===0?`Uploaded ${e}.`:`Uploaded ${e}, ${t.length} failed — ${t[0]}`)}render(){const{list:e}=this.options.elements;e.replaceChildren();for(const t of this.records){const i=document.createElement("li"),s=t.playerName??t.subjectId??"no subject",a=document.createElement("span");a.className="missed-event-row",a.textContent=`${t.mechanic} @ ${t.time.toFixed(2)}s · f${t.frame} · ${s}`+(t.replayId?"":" · no replay id");const r=document.createElement("button");r.type="button",r.textContent="✕",r.title="Remove",r.addEventListener("click",()=>{const o=this.records.findIndex(l=>l.localId===t.localId);o>=0&&(this.records.splice(o,1),this.render())}),i.append(a,r),e.appendChild(i)}}setStatus(e){this.options.elements.status.textContent=e}resolveReplayId(){return g8(window.location.search,this.options.getReplayId?.()??null)}}function C8(n){return new E8(n)}class A8{constructor(e){this.options=e}activeModules=[];activeTimelineEventSourceIds=new Set;activeTimelineRangeModuleIds=new Set;activeMechanicTimelineKinds=new Set;activeRenderEffectModuleIds=new Set;removeRenderHook=null;timelineSourceRemovers=new Map;timelineRangeSourceRemovers=new Map;getActiveModules(){return this.activeModules}getActiveTimelineEventSourceIds(){return this.activeTimelineEventSourceIds}getActiveTimelineRangeModuleIds(){return this.activeTimelineRangeModuleIds}getActiveMechanicTimelineKinds(){return this.activeMechanicTimelineKinds}getActiveRenderEffectModuleIds(){return this.activeRenderEffectModuleIds}getActiveCapabilityIds(e){return e==="events"?this.activeTimelineEventSourceIds:e==="ranges"?this.activeTimelineRangeModuleIds:this.activeRenderEffectModuleIds}getBoostPadOverlayEnabled(){return!0}getTimelineEventSourceIds(){return[...this.activeTimelineEventSourceIds]}getTimelineRangeModuleIds(){return[...this.activeTimelineRangeModuleIds]}getMechanicTimelineKinds(){return[...this.activeMechanicTimelineKinds]}getRenderEffectModuleIds(){return[...this.activeRenderEffectModuleIds]}applyOverlayConfig({timelineEvents:e,timelineRanges:t,mechanics:i,renderEffects:s,boostPads:a}){this.activeTimelineEventSourceIds=new Set(e),this.activeTimelineRangeModuleIds=new Set(t),this.activeMechanicTimelineKinds=new Set(i),this.activeRenderEffectModuleIds=new Set(s)}reset(){this.teardownActiveModules(),this.clearStandalonePlugins(),this.activeModules=[],this.activeTimelineEventSourceIds=new Set,this.activeTimelineRangeModuleIds=new Set,this.activeMechanicTimelineKinds=new Set,this.activeRenderEffectModuleIds=new Set,this.removeRenderHook=null}setupActiveModules(){this.teardownActiveModules();const e=this.options.getContext();if(!e)return;const t=this.getActiveModuleIds();this.activeModules=this.options.modules.filter(i=>t.has(i.id)),this.options.boostPickupFilters.setup(e);for(const i of this.activeModules)i.setup(e);this.removeRenderHook=e.player.onBeforeRender(i=>{for(const s of this.activeModules)this.activeRenderEffectModuleIds.has(s.id)&&s.onBeforeRender(i)}),this.syncTimelineEvents(),this.syncTimelineRanges()}teardownActiveModules(){this.removeRenderHook?.(),this.removeRenderHook=null,this.clearTimelineEventSources(),this.clearTimelineRangeSources();for(const e of this.activeModules)e.teardown();this.activeModules=[]}toggleCapability(e,t,i){const s=this.getMutableActiveCapabilityIds(t);i?s.add(e):s.delete(e),this.setupActiveModules(),this.options.renderModuleSummary(),this.options.renderModuleSettings(),this.options.renderStatsWindows(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()}setMechanicTimelineKind(e,t){t?this.activeMechanicTimelineKinds.add(e):this.activeMechanicTimelineKinds.delete(e),this.options.requestConfigSync()}activateMechanicTimelineKind(e){this.activeMechanicTimelineKinds.add(e),this.syncTimelineEvents(),this.syncTimelineRanges(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()}clearTimelineEventSources(){for(const e of this.timelineSourceRemovers.values())e();this.timelineSourceRemovers.clear()}clearTimelineRangeSources(){for(const e of this.timelineRangeSourceRemovers.values())e();this.timelineRangeSourceRemovers.clear()}clearStandalonePlugins(){}syncBoostPadOverlayPlugin(){}toggleBoostPadOverlay(){this.options.renderModuleSummary(),this.options.requestConfigSync()}syncTimelineEvents(){this.clearTimelineEventSources();const e=this.options.getContext(),t=this.options.getTimelineOverlay();if(!(!t||!e)){for(const i of this.options.getEventTimelineSources(e)){if(!i.active)continue;const s=i.buildTimelineEvents();s.length!==0&&this.timelineSourceRemovers.set(i.timelineKey,t.addEventSource(this.options.withTimelineEventSeekTimes(s),{id:i.timelineId,label:i.label}))}t.refreshEvents()}}syncTimelineRanges(){this.clearTimelineRangeSources();const e=this.options.getContext(),t=this.options.getTimelineOverlay();if(!(!t||!e)){for(const i of this.activeModules)!this.activeTimelineRangeModuleIds.has(i.id)||!i.getTimelineRanges||this.timelineRangeSourceRemovers.set(i.id,t.addRangeSource(()=>i.getTimelineRanges?.(e)??[]));for(const i of this.options.getEventTimelineSources(e)){if(!i.active||!i.buildTimelineRanges)continue;const s=i.buildTimelineRanges();s.length!==0&&this.timelineRangeSourceRemovers.set(i.timelineKey,t.addRangeSource(s))}t.refreshRanges()}}getActiveModuleIds(){return new Set([...this.activeTimelineEventSourceIds,...this.activeTimelineRangeModuleIds,...this.activeRenderEffectModuleIds])}getMutableActiveCapabilityIds(e){return e==="events"?this.activeTimelineEventSourceIds:e==="ranges"?this.activeTimelineRangeModuleIds:this.activeRenderEffectModuleIds}}function R8(n){return new A8(n)}function Jn(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Xx(n){return Jn(n)&&(n.kind==="time"||n.kind==="frame")&&typeof n.value=="number"&&Number.isFinite(n.value)?{kind:n.kind,value:n.value}:null}function Nu(n,e){if(n!=null){if(typeof n!="number"||!Number.isInteger(n)||!Number.isFinite(n)||n<0)throw new Error(`Review playlist page ${e} must be a non-negative integer.`);return n}}function Kx(n,e){if(n!=null){if(typeof n!="string")throw new Error(`Review playlist page ${e} must be a string.`);return n}}function P8(n){if(n!=null){if(!Jn(n))throw new Error("Review playlist page must be an object.");return{next:Kx(n.next,"next"),previous:Kx(n.previous,"previous"),total:Nu(n.total,"total"),count:Nu(n.count,"count"),limit:Nu(n.limit,"limit"),offset:Nu(n.offset,"offset")}}}function I8(n){if(n!=null){if(!Jn(n))throw new Error("Review playlist playback must be an object.");if(n.timeBase!==void 0&&n.timeBase!=="playback"&&n.timeBase!=="rawReplay")throw new Error('Review playlist playback timeBase must be "playback" or "rawReplay".');return{...n,timeBase:n.timeBase}}}function L8(n,e){if(n==null)return;if(!Jn(n))throw new Error(`Review item ${e} perspective must be an object.`);if(n.kind!=="player")throw new Error(`Review item ${e} perspective kind must be "player".`);const t=typeof n.playerId=="string"&&n.playerId.trim()?n.playerId.trim():void 0,i=typeof n.playerName=="string"&&n.playerName.trim()?n.playerName.trim():void 0;if(!t&&!i)throw new Error(`Review item ${e} player perspective needs playerId or playerName.`);if(n.ballCam!==void 0&&n.ballCam!=="off"&&n.ballCam!=="on"&&n.ballCam!=="player")throw new Error(`Review item ${e} perspective ballCam must be off, on, or player.`);if(n.usePlayerCameraSettings!==void 0&&typeof n.usePlayerCameraSettings!="boolean")throw new Error(`Review item ${e} perspective usePlayerCameraSettings must be boolean.`);return{kind:"player",playerId:t,playerName:i,ballCam:n.ballCam,usePlayerCameraSettings:n.usePlayerCameraSettings}}function D8(n){if(!Jn(n)||!Array.isArray(n.items))throw new Error("Review playlist must contain an items array.");const e=n.items.map((i,s)=>{if(!Jn(i)||typeof i.replay!="string")throw new Error(`Invalid review item at index ${s}.`);const a=Xx(i.start),r=Xx(i.end);if(!a||!r)throw new Error(`Review item ${s+1} has invalid start or end.`);return{id:typeof i.id=="string"?i.id:void 0,replay:i.replay,start:a,end:r,label:typeof i.label=="string"?i.label:void 0,perspective:L8(i.perspective,s+1),meta:Jn(i.meta)?i.meta:void 0}}),t=Array.isArray(n.replays)?n.replays.map(i=>!Jn(i)||typeof i.id!="string"?null:{id:i.id,path:typeof i.path=="string"?i.path:void 0,label:typeof i.label=="string"?i.label:void 0,locator:Jn(i.locator)?i.locator:void 0,meta:Jn(i.meta)?i.meta:void 0}).filter(i=>i!==null):void 0;return{label:typeof n.label=="string"?n.label:void 0,replays:t,items:e,page:P8(n.page),playback:I8(n.playback),meta:n.meta}}function qx(n){let e;try{e=JSON.parse(n)}catch(t){throw new Error(`Invalid review playlist JSON: ${t instanceof Error?t.message:String(t)}`)}return D8(e)}function k8(){const n=new URLSearchParams(window.location.search);return n.get("reviewPlaylist")?.trim()||n.get("review")?.trim()||n.get("playlist")?.trim()||n.get("playlistUrl")?.trim()||null}function O8(n){return/^\/(?:home|Users|tmp|var\/tmp|mnt|media|run\/user|nix\/store)\//.test(n)}function l1(n,e){const t=n.startsWith("path:")?n.slice(5):n;if(/^https?:\/\//i.test(t)||t.startsWith("/@fs/"))return t;if(t.startsWith("/")){if(O8(t))return`/@fs${t}`;if(e){const i=new URL(e,window.location.href);if(i.origin!==window.location.origin)return new URL(t,i.origin).href}return t}return e?new URL(t,e).href:t}function rd(n,e){const t=e.replaysById.get(n.replay);if(t?.path)return t.path;if(Jn(t?.locator)&&t.locator.kind==="path"&&typeof t.locator.path=="string")return t.locator.path;if(/^https?:\/\//i.test(n.replay)||n.replay.startsWith("/")||n.replay.startsWith("/@fs/")||n.replay.startsWith("path:"))return n.replay;throw new Error(`Review replay "${n.replay}" does not include a loadable path.`)}function Yx(n,e){const t=e.replaysById.get(n.replay),s=(t?.path??rd(n,e)).replace(/^path:/,"").split("/").filter(Boolean).pop();return t?.label??s??"review replay"}function od(n){return typeof n=="number"&&Number.isFinite(n)?`${n.toFixed(2)}s`:"--"}function jx(n){return n.kind==="time"?od(n.value):`frame ${Math.trunc(n.value)}`}function Ki(n,e){if(!Jn(n.meta?.target))return null;const t=n.meta.target[e];return typeof t=="number"&&Number.isFinite(t)?t:null}function ld(n,e){if(!Jn(n.meta?.target))return null;const t=n.meta.target[e];return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):null}function F8(n,e){for(const[t,i]of[["eventTime","eventFrame"],["startTime","startFrame"],["endTime","endFrame"]]){const s=Ki(n,t),a=ld(n,i),r=a===null?null:e.frames[a]?.time;if(s!==null&&typeof r=="number"&&Number.isFinite(r))return s-r}return 0}function c1(n,e,t){return t==="playback"?0:t==="rawReplay"&&typeof e.rawStartTime=="number"&&Number.isFinite(e.rawStartTime)?e.rawStartTime:F8(n,e)}function C_(n,e){return Math.min(Math.max(0,n),Math.max(0,e))}function N8(n,e,t,i){if(e.kind==="frame"){const a=Math.max(0,Math.trunc(e.value));return C_(t.frames[a]?.time??0,t.duration)}const s=c1(n,t,i);return C_(e.value-s,t.duration)}function U8(n,e,t){const i=$8(n);return i===null?null:C_(i-c1(n,e,t),e.duration)}function B8(n){const e=n.start.kind==="time"?n.start.value:null,t=n.end.kind==="time"?n.end.value:null,i=[`${jx(n.start)} to ${jx(n.end)}`];e!==null&&t!==null&&i.push(`${Math.max(0,t-e).toFixed(1)}s clip`);const s=Ki(n,"startTime")??Ki(n,"eventTime"),a=Ki(n,"endTime")??Ki(n,"eventTime");return e!==null&&s!==null&&i.push(`${Math.max(0,s-e).toFixed(1)}s preroll`),t!==null&&a!==null&&i.push(`${Math.max(0,t-a).toFixed(1)}s postroll`),i.join(" · ")}function z8(n){const e=Ki(n,"eventTime"),t=Ki(n,"startTime"),i=Ki(n,"endTime"),s=ld(n,"eventFrame"),a=ld(n,"startFrame"),r=ld(n,"endFrame"),o=t!==null&&i!==null&&Math.abs(i-t)>.001?`${od(t)} to ${od(i)}`:od(e??t??i),l=a!==null&&r!==null&&r!==a?`frames ${a}-${r}`:s!==null?`frame ${s}`:a!==null?`frame ${a}`:null;return[o,l].filter(c=>c&&c!=="--").join(" · ")||"--"}function um(n,e){return n.label??n.meta?.eventTypeLabel??n.meta?.mechanicLabel??`Review item ${e+1}`}function H8(n){if(typeof n.meta?.playerName=="string"&&n.meta.playerName.trim())return n.meta.playerName.trim();if(Jn(n.meta?.target)&&typeof n.meta.target.playerName=="string"){const e=n.meta.target.playerName.trim();return e||null}return null}function Zx(n,e){if(!n)return null;if(n.playerId){const i=e.find(s=>s.id===n.playerId);if(i)return i}const t=n.playerName?.toLowerCase();return t?e.find(i=>i.name.trim().toLowerCase()===t)??null:null}function Jx(n){if(typeof n.meta?.eventTypeLabel=="string"&&n.meta.eventTypeLabel.trim())return n.meta.eventTypeLabel;if(typeof n.meta?.mechanicLabel=="string"&&n.meta.mechanicLabel.trim())return n.meta.mechanicLabel;const e=n.meta?.eventType??n.meta?.mechanic;return typeof e=="string"?Ci(e):"--"}function V8(n){const e=n.meta?.eventCategory;return typeof e=="string"&&e.trim()?Ci(e.trim()):"--"}function G8(n){const e=n.meta?.eventType??n.meta?.mechanic;return typeof e=="string"&&e.trim()?e.trim().replaceAll("-","_"):null}function $8(n){return Ki(n,"eventTime")??Ki(n,"startTime")??Ki(n,"endTime")}class W8{constructor(e){this.options=e}createReplaySource(e,t,i){const s=rd(e,t),a=l1(s,t.sourceUrl);return{name:Yx(e,t),preparingStatus:"Loading review replay...",async readBytes(){const r=await fetch(a,{signal:i});if(!r.ok){const o=r.statusText?` ${r.statusText}`:"";throw new Error(`Failed to fetch review replay from ${a} (${r.status}${o})`)}return new Uint8Array(await r.arrayBuffer())}}}initialize(e){const t=this.getReplayClipCounts(e);for(const[i,s]of this.getReplayItems(e)){let a="",r=i;try{a=rd(s,e),r=Yx(s,e)}catch{r=e.replaysById.get(i)?.label??i}e.replayLoadStates.set(i,{replayId:i,label:r,path:a,clipCount:t.get(i)??0,status:"idle",progress:null,error:null})}}preload(e,t){if(e.preloading)return;const i=this.getNextReplayItems(e,t);i.length!==0&&(e.preloading=!0,(async()=>{try{for(const s of i){const a=s.replay,r=e.replayLoadStates.get(a);if(!(r?.status==="loaded"||r?.status==="loading"))try{await this.loadBundle(s,e)}catch{}}}finally{e.preloading=!1}})())}loadBundle(e,t){const i=t.replayLoadCache.get(e.replay);if(i)return i;const s=this.createReplaySource(e,t);this.updateLoadState(t,e.replay,{label:s.name,path:rd(e,t),status:"loading",progress:null,error:null});const a=Promise.resolve().then(async()=>{const r=await s.readBytes();return iE(r,{reportEveryNFrames:100,onProgress:o=>{this.updateLoadState(t,e.replay,{status:"loading",progress:o,error:null})}})}).then(r=>(this.updateLoadState(t,e.replay,{status:"loaded",progress:null,error:null}),r)).catch(r=>{throw t.replayLoadCache.delete(e.replay),this.updateLoadState(t,e.replay,{status:"error",error:r instanceof Error?r.message:String(r)}),r});return t.replayLoadCache.set(e.replay,a),a}render(e){const{reviewSummary:t,loadingSummary:i,loadingActive:s,loadingList:a}=this.options.elements,r=e?Array.from(e.replayLoadStates.values()):[],o=r.filter(h=>h.status==="loaded").length,l=r.filter(h=>h.status==="loading").length,c=r.filter(h=>h.status==="error").length,u=r.filter(h=>h.status==="idle").length,d=r.length===0?"0 replays":`${o}/${r.length} loaded${l>0?`, ${l} loading`:""}${c>0?`, ${c} failed`:""}`;if(t.textContent=d,i.textContent=d,s.textContent=r.length===0?"No playlist":l>0?`${l} active, ${u} pending`:c>0?`${c} failed`:e?.preloading?`Background queue, ${u} pending`:o===r.length?"Complete":`${u} pending`,a.replaceChildren(),!e||r.length===0){const h=document.createElement("p");h.className="stat-window-empty",h.textContent="No replay sources.",a.append(h);return}for(const h of r){const f=document.createElement("div");f.className=`mechanics-review-replay-load ${h.status}`;const p=document.createElement("div");p.className="mechanics-review-replay-load-main";const g=document.createElement("span");g.className="mechanics-review-replay-load-title",g.textContent=h.label;const _=document.createElement("span");_.className="mechanics-review-replay-load-meta",_.textContent=[h.replayId,`${h.clipCount} ${h.clipCount===1?"clip":"clips"}`,h.path].filter(Boolean).join(" · "),p.append(g,_);const m=document.createElement("strong");m.className="mechanics-review-replay-load-status",m.textContent=this.replayLoadStatusText(h);const v=document.createElement("div");v.className="mechanics-review-replay-load-progress";const y=document.createElement("span");y.style.width=`${Math.round(this.replayLoadProgressValue(h)*100)}%`,v.append(y),f.append(p,m,v),a.append(f)}}updateLoadState(e,t,i){const s=e.replayLoadStates.get(t)??{replayId:t,label:t,path:"",clipCount:0,status:"idle",progress:null,error:null};e.replayLoadStates.set(t,{...s,...i});const a=e.manifest.items[e.currentIndex];e.loading&&a?.replay===t&&i.progress&&this.options.onActiveLoadProgress(i.progress),this.options.isActiveReview(e)&&this.render(e)}getReplayItems(e){const t=new Map;for(const i of e.manifest.items)t.has(i.replay)||t.set(i.replay,i);return t}getReplayClipCounts(e){const t=new Map;for(const i of e.manifest.items)t.set(i.replay,(t.get(i.replay)??0)+1);return t}getNextReplayItems(e,t){const i=e.manifest.items[t]?.replay,s=new Set(i?[i]:[]),a=[];for(let r=t+1;r{const i=t.file.files?.[0];if(i)try{const s=qx(await i.text());await this.loadPlaylist(s,null)}catch(s){console.error("Failed to load review playlist:",s),this.setStatus(s instanceof Error?s.message:"Failed to load review playlist")}finally{t.file.value=""}},{signal:e}),t.loadUrl.addEventListener("click",()=>{this.loadPlaylistFromUrl(t.url.value.trim()).catch(i=>{console.error("Failed to load review playlist URL:",i),this.setStatus(i instanceof Error?i.message:"Failed to load review playlist URL")})},{signal:e}),t.previous.addEventListener("click",()=>{const i=this.activeReview;i&&this.activateItem(Math.max(0,i.currentIndex-1))},{signal:e}),t.replay.addEventListener("click",()=>this.replayClip(),{signal:e}),t.next.addEventListener("click",()=>{const i=this.activeReview;i&&this.activateItem(Math.min(i.manifest.items.length-1,i.currentIndex+1))},{signal:e}),t.confirm.addEventListener("click",()=>{this.submitDecision("confirmed")},{signal:e}),t.reject.addEventListener("click",()=>{this.submitDecision("rejected")},{signal:e}),t.uncertain.addEventListener("click",()=>{this.submitDecision("uncertain")},{signal:e})}render(){const{elements:e}=this.options,t=this.activeReview,i=t?.manifest.items??[],s=t?i[t.currentIndex]??null:null,a=i.length>0;e.count.textContent=`${i.length} item${i.length===1?"":"s"}`,e.index.textContent=a&&t?`${t.currentIndex+1} / ${i.length}`:"0 / 0",e.title.textContent=s?um(s,t?.currentIndex??0):"No candidate selected",e.mechanic.textContent=s?Jx(s):"--",e.player.textContent=s?this.getPlayerName(s):"--",e.clip.textContent=s?B8(s):"--",e.event.textContent=s?z8(s):"--",e.reason.textContent=s?.meta?.reason??"--",e.previous.disabled=!t||t.loading||t.currentIndex<=0,e.replay.disabled=!t||t.loading||!t.currentClip,e.next.disabled=!t||t.loading||t.currentIndex>=i.length-1;const r=!t||t.loading||Qx(s)===null;if(e.confirm.disabled=r,e.reject.disabled=r,e.uncertain.disabled=r,this.options.replayLoads.render(t),e.list.replaceChildren(),!t||i.length===0){const o=document.createElement("p");o.className="stat-window-empty",o.textContent="No review playlist loaded.",e.list.append(o);return}i.forEach((o,l)=>{const c=document.createElement("button");c.type="button",c.className="mechanics-review-item",c.dataset.active=l===t.currentIndex?"true":"false",c.disabled=t.loading,c.addEventListener("click",()=>{this.activateItem(l)});const u=document.createElement("span");u.textContent=um(o,l);const d=document.createElement("strong");d.textContent=[V8(o),Jx(o),this.getPlayerName(o),dm(o.meta?.reviewStatus)].filter(h=>h&&h!=="--").join(" · ")||"--",c.append(u,d),e.list.append(c)})}async loadPlaylist(e,t){const i=new Map;for(const s of e.replays??[])i.set(s.id,s);this.activeReview={manifest:e,sourceUrl:t,replaysById:i,replayLoadStates:new Map,replayLoadCache:new Map,currentIndex:0,loading:!1,preloading:!1,currentReplayId:null,currentClip:null},this.options.replayLoads.initialize(this.activeReview),this.options.showReplayLoadingWindow(),this.setStatus(e.label?`Loaded ${e.label}.`:"Loaded review playlist."),this.render(),e.items.length>0&&await this.activateItem(0)}async loadPlaylistFromUrl(e){if(!e){this.setStatus("Enter a review playlist URL.");return}const t=l1(e,window.location.href);this.setStatus("Loading review playlist...");const i=await fetch(t);if(!i.ok){const a=i.statusText?` ${i.statusText}`:"";throw new Error(`Failed to fetch review playlist from ${t} (${i.status}${a})`)}const s=qx(await i.text());await this.loadPlaylist(s,i.url||t)}async activateItem(e){const t=this.activeReview,i=t?.manifest.items[e];if(!(!t||!i||t.loading)){t.loading=!0,t.currentIndex=e,this.render(),this.setStatus(`Loading ${um(i,e)}...`);try{if(!this.options.getReplayPlayer()||t.currentReplayId!==i.replay){const d=this.options.replayLoads.createReplaySource(i,t),h=this.options.replayLoads.loadBundle(i,t);await this.options.loadReplayBundleForDisplay(d,h),t.currentReplayId=i.replay}this.options.replayLoads.preload(t,e);const a=t.manifest.playback?.timeBase,r=Math.max(0,this.getBoundTime(i,i.start,a)),o=Math.min(this.options.getReplayPlayer()?.getState().duration??Number.POSITIVE_INFINITY,Math.max(r,this.getBoundTime(i,i.end,a)));if(!Number.isFinite(r)||!Number.isFinite(o)||o<=r)throw new Error("Review item has an empty playback range.");const l=this.options.getReplayPlayer(),c=l?Zx(i.perspective,l.replay.players):null;c&&this.options.applyClipPerspective({playerId:c.id,ballCam:i.perspective?.ballCam,usePlayerCameraSettings:i.perspective?.usePlayerCameraSettings}),this.options.resetReplayTransitionControls();const u=l===null?null:U8(i,l.replay,a);t.currentClip={startTime:r,endTime:o,targetTime:u},this.options.activateTimelineSource(i),this.options.getReplayPlayer()?.setState({currentTime:r,playing:!0,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),this.setStatus(u===null?`Playing ${r.toFixed(2)}s to ${o.toFixed(2)}s`:`Playing ${r.toFixed(2)}s to ${o.toFixed(2)}s; target ${u.toFixed(2)}s`)}catch(s){console.error("Failed to activate mechanics review item:",s),t.currentClip=null,this.setStatus(s instanceof Error?s.message:"Failed to load review item")}finally{t.loading=!1,this.render()}}}replayClip(){const e=this.activeReview?.currentClip,t=this.options.getReplayPlayer();!e||!t||t.setState({currentTime:e.startTime,playing:!0,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1})}async submitDecision(e){const t=this.activeReview,i=t?.manifest.items[t.currentIndex]??null,s=Qx(i);if(!t||!i||!s){this.setStatus("Current review item has no review endpoint.");return}this.setStatus(`Submitting ${dm(e)}...`);const a=await fetch(s,{method:"POST",headers:{"content-type":"application/json",...q8()},credentials:"same-origin",body:JSON.stringify({status:e})});if(!a.ok){let r=`${a.status}${a.statusText?` ${a.statusText}`:""}`;try{const o=await a.json();typeof o.error=="string"&&(r=o.error)}catch{}this.setStatus(`Review failed: ${r}`);return}i.meta=i.meta??{},i.meta.reviewStatus=e,this.setStatus(`Marked ${dm(e)}.`),this.render()}enforceClipBoundary(e){const t=this.activeReview?.currentClip,i=this.options.getReplayPlayer();if(!t||!i||this.boundaryGuard)return!1;const s=e.currentTime=t.endTime-.025;if(!s&&!a)return!1;this.boundaryGuard=!0;try{i.setState({currentTime:s?t.startTime:t.endTime,playing:!1,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),a&&this.setStatus(`Finished clip at ${t.endTime.toFixed(2)}s`)}finally{this.boundaryGuard=!1}return!0}getBoundTime(e,t,i){const s=this.options.getReplayPlayer();return s?N8(e,t,s.replay,i):t.kind==="time"?t.value:0}getPlayerName(e){const t=H8(e);if(t)return t;const i=this.options.getReplayPlayer()?.replay.players??[];return Zx(e.perspective,i)?.name??"--"}}function dm(n){return typeof n=="string"&&n.trim()?n.replaceAll("_"," "):"unreviewed"}function Qx(n){if(!n)return null;if(typeof n.meta?.reviewEndpoint=="string"&&n.meta.reviewEndpoint)return n.meta.reviewEndpoint;const e=typeof n.meta?.eventId=="string"&&n.meta.eventId?n.meta.eventId:n.id;return e?`/api/v1/events/${encodeURIComponent(e)}/reviews`:null}function q8(){const n=new URLSearchParams(window.location.search),e=n.get("reviewToken")??n.get("token")??window.localStorage.getItem("rocket_sense_access_token");return e?{Authorization:`Bearer ${e}`}:{}}function Y8(n){return new K8(n)}const j8=["replayUrl","replay_url","replay"],Z8=["r","replayUrlZ","replay_url_z"],J8=["ballchasing","ballchasingId","ballchasingUuid","ballchasingReplay"];function Q8(n){const e=n.replaceAll("-","+").replaceAll("_","/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=atob(t),s=new Uint8Array(i.length);for(let a=0;a{n.signal.aborted||(console.error("Failed to load replay URL:",t),n.statusReadout.textContent=t instanceof Error?t.message:"Failed to load replay URL")})}function r6(n){n.initialBundle?n.loadReplayBundleForDisplay({name:n.initialReplayName??"replay",preparingStatus:"Preparing replay...",async readBytes(){throw new Error("Replay bytes are not available for this preloaded replay")}},Promise.resolve(n.initialBundle)).catch(i=>{n.signal.aborted||(console.error("Failed to load preprocessed replay bundle:",i),n.statusReadout.textContent=i instanceof Error?i.message:"Failed to load preprocessed replay bundle")}):n.loadFromLocation!==!1&&a6(n);const e=k8();if(!e)return;const t=n.getMechanicsReviewController();t?.setUrl(e),n.showMechanicsReviewWindow(),t?.loadPlaylistFromUrl(e).catch(i=>{n.signal.aborted||(console.error("Failed to load mechanics review playlist from URL:",i),t?.setStatus(i instanceof Error?i.message:"Failed to load mechanics review playlist from URL"))})}function o6(n){const e=()=>{n.getSkipPostGoalTransitions().checked=!1,n.getSkipKickoffs().checked=!1},t=(i,s)=>{const a=n.getReplayPlayer();!a||!Number.isFinite(i)||(n.getMechanicsReviewController()?.clearCurrentClip(),e(),a.setState({currentTime:Math.max(0,i-n.goalWatchLeadSeconds),playing:s,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),n.scheduleConfigUrlUpdate())};return{watchGoalReplay(i,s){const a=n.getReplayPlayer();if(!a||!Number.isFinite(i))return;if(n.getMechanicsReviewController()?.clearCurrentClip(),s!==null&&a.replay.players.some(o=>o.id===s)){a.setAttachedPlayer(s),a.setCameraViewMode("follow");const o=n.getCameraControlsController();o&&(o.freeCameraPreset=null)}e(),a.setState({currentTime:Math.max(0,i-n.goalWatchLeadSeconds),playing:!0,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),n.scheduleConfigUrlUpdate()},cueGoalReplay(i){t(i,!1)},cueTimelineEvent(i){const s=n.getReplayPlayer();s&&(n.getMechanicsReviewController()?.clearCurrentClip(),e(),s.setState({currentTime:Pg(i),skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),n.scheduleConfigUrlUpdate())},applyConfigToReplayPlayer(i){const s=n.getReplayPlayer();if(!s)return;s.setState(ZW(i.playback,i.camera,i));const a=n.getCameraControlsController();a&&(a.freeCameraPreset=i.camera.freePreset??null),i.camera.mode==="free"&&i.camera.freePreset&&s.setFreeCameraPreset(i.camera.freePreset),n.syncBoostPadOverlayPlugin(),n.setupActiveModules(),n.renderModuleSummary(),n.renderModuleSettings(),n.renderStatsWindows(s.getState().frameIndex)}}}function l6(n){let e=!1,t=null;const i=()=>n.getFloatingWindowController()?.getSingletonConfigs()??[],s=()=>n.getStatsWindowsController()?.getConfigs()??[],a=()=>{const o=n.getActiveModulesRuntime(),l=n.getReplayPlayer();return jW({playback:qW({replayPlayer:l,playbackRate:n.playbackRate,skipPostGoalTransitions:n.skipPostGoalTransitions,skipKickoffs:n.skipKickoffs}),camera:YW({replayPlayer:l,cameraControlsController:n.getCameraControlsController()}),activeTimelineEventSourceIds:o.getActiveTimelineEventSourceIds(),activeTimelineRangeModuleIds:o.getActiveTimelineRangeModuleIds(),activeMechanicTimelineKinds:o.getActiveMechanicTimelineKinds(),activeRenderEffectModuleIds:o.getActiveRenderEffectModuleIds(),initialConfig:n.getInitialConfig(),replayPlayer:l,boostPadOverlayEnabled:o.getBoostPadOverlayEnabled(),recording:n.getRecordingWindowController()?.getConfigSnapshot()??{},singletonWindows:i(),statsWindows:s(),moduleConfigs:KW(n.modules)})},r=o=>{VW(o1(n.modules),o)};return{setApplyingConfig(o){e=o},reset(){t!==null&&(window.clearTimeout(t),t=null),e=!1},scheduleConfigUrlUpdate(){e||(t!==null&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null;const o=vW(new URL(window.location.href),a());window.history.replaceState(window.history.state,"",o)},150))},applyConfigToStaticControls(o){if(n.getActiveModulesRuntime().applyOverlayConfig(o.overlays),n.skipPostGoalTransitions.checked=o.playback.skipPostGoalTransitions??n.skipPostGoalTransitions.checked,n.skipKickoffs.checked=o.playback.skipKickoffs??n.skipKickoffs.checked,n.hitboxWireframes.checked=o.overlays.hitboxWireframes,n.hitboxOnlyMode.checked=o.overlays.hitboxOnlyMode,n.getCameraControlsController()?.applyNameplateLiftUu(o.camera.nameplateLiftUu),n.getCameraControlsController()?.setAutoPossessionEnabled(o.camera.autoPossession??!1,{requestConfigSync:!1}),o.playback.rate!==void 0){const l=cf(o.playback.rate);n.playbackRate.value=`${l}`,n.playbackRateReadout.textContent=qg(l)}n.getRecordingWindowController()?.applyConfig(o.recording),r(o.moduleConfigs),n.getFloatingWindowController()?.applySingletonConfigs(o.singletonWindows),n.getStatsWindowsController()?.replaceFromConfig(o.statsWindows),n.renderModuleSummary(),n.renderModuleSettings(),n.renderTimelineEventCount()}}}function c6(n){const e=t=>{const i=n.getLauncherToggle();n.getLauncherMenu().hidden=!t,i.setAttribute("aria-label",t?"Close menu":"Open menu"),i.setAttribute("aria-expanded",t?"true":"false")};return{bringWindowToFront(t){n.getFloatingWindowController()?.bringToFront(t)},showWindow(t){n.getFloatingWindowController()?.show(t)},toggleWindow(t){n.getFloatingWindowController()?.toggle(t)},hideWindow(t){n.getFloatingWindowController()?.hide(t)},setLauncherOpen:e,openReplayFilePicker(){n.getFileInput().click(),e(!1)},installWindowDragging(t,i){n.getFloatingWindowController()?.installDragging(t,i)},getElementWindowId(t){return t.closest("[data-window-id]")?.dataset.windowId??null}}}const A_=4096,hr=5120,u6=893,d6=642,qi=1/105;class h6{constructor(e){this.options=e,this.options.body.innerHTML=` +
`}).join("")}
`},renderFocusedPlayerStats(e,t,i){return`
Events${ve(i.statsTimeline,"dodge").filter(a=>At(a.player)===e).length}
`}}}function R$(){return{id:"half-flip",label:"Half Flip",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Nx(i.half_flip),i.half_flip?.is_last_half_flip?'Last Half Flip':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Nx(i.half_flip):""}}}function P$(){return{id:"wavedash",label:"Wavedash",setup(){},teardown(){},onBeforeRender(){},getTimelineEvents(n){return T4(n.statsTimeline,n.replay)},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Ux(i.wavedash),i.wavedash?.is_last_wavedash?'Last Wavedash':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Ux(i.wavedash):""}}}function I$(){return ai({id:"whiff",label:"Whiff",select:n=>n.whiff,render:n=>JG(n),getTimelineEvents(n){return R4(n.statsTimeline,n.replay)}})}function L$(n){let e=null,t=null;const i=new Set,s=["speed_band","height_band"];return{id:"movement",label:"Movement",setup(){a()},teardown(){},onBeforeRender(){},getConfig(){return{breakdownClasses:r()}},applyConfig(o){if(i.clear(),o&&typeof o=="object"&&!Array.isArray(o)){const l=o.breakdownClasses;if(Array.isArray(l))for(const c of l)s.includes(c)&&i.add(c)}a(),n.rerenderCurrentState()},renderStats(o,l){const c=zt(l.statsFrameLookup,o);return c?si(c.players,u=>Tn(u.name,u.is_team_0,Mx(u.movement,{breakdownClasses:r()}))):""},renderFocusedPlayerStats(o,l,c){const u=wn(c,l,o);return u?Mx(u.movement,{breakdownClasses:r()}):""},renderSettings(){if(!e){e=document.createElement("div"),e.className="module-settings-card";const o=document.createElement("div");o.className="module-settings-header";const l=document.createElement("div"),c=document.createElement("p");c.className="module-settings-eyebrow",c.textContent="Stat display";const u=document.createElement("h3");u.textContent="Movement breakdown",l.append(c,u),t=document.createElement("strong"),t.className="metric-readout",o.append(l,t);const d=document.createElement("div");d.className="module-settings-options";for(const h of[{className:"speed_band",label:"Speed band"},{className:"height_band",label:"Height band"}]){const f=document.createElement("label");f.className="toggle";const p=document.createElement("input");p.type="checkbox",p.dataset.breakdownClass=h.className,p.addEventListener("change",()=>{p.checked?i.add(h.className):i.delete(h.className),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const g=document.createElement("span");g.textContent=h.label,f.append(p,g),d.append(f)}e.append(o,d)}return a(),e}};function a(){if(e){for(const o of e.querySelectorAll("input[data-breakdown-class]")){const l=o.dataset.breakdownClass;o.checked=l?i.has(l):!1}if(t){const o=r();t.textContent=o.length>0?o.map(l=>({speed_band:"Speed band",height_band:"Height band"})[l]).join(" + "):"Total only"}}}function r(){return s.filter(o=>i.has(o))}}function k$(){return ai({id:"powerslide",label:"Powerslide",select:n=>n.powerslide,render:n=>ZG(n),getTimelineEvents(n){return b4(n.statsTimeline,n.replay)}})}function D$(){return ai({id:"rotation",label:"Rotation",select:n=>n.rotation,render:n=>GG(n)})}function O$(){return ai({id:"demo",label:"Demo",select:n=>n.demo,render:n=>QG(n)})}function F$(){return ai({id:"bump",label:"Bump",select:n=>n.bump,render:n=>e$(n),getTimelineEvents(n){return M4(n.statsTimeline,n.replay)}})}function N$(){let n=null,e=1;return{id:WE,label:"Relative Positioning",setup(t){e=t.fieldScale,n=new o5(t.player.sceneState.replayRoot,t.replay,e)},teardown(){n?.dispose(),n=null},onBeforeRender(t){n?.update(t,e)},renderStats(t,i){const s=zt(i.statsFrameLookup,t);return s?si(s.players,a=>{const r=Q4(i.replay,At(a.player_id),t),o=J4[r];return Tn(a.name,a.is_team_0,Px(a.positioning),`${o}`)}):""},renderFocusedPlayerStats(t,i,s){const a=wn(s,i,t);return a?Px(a.positioning):""}}}function U$(){return{id:"absolute-positioning",label:"Absolute Positioning",setup(n){Ax.acquire(n)},teardown(){Ax.release()},onBeforeRender(){},getTimelineRanges(n){return Z4(n.statsTimeline,n.replay)},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Ix(i.positioning))):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Ix(i.positioning):""}}}function B$(n,e={}){return[p$(),m$(),_$(),g$(),y$(),S$(),M$(),T$(),eG(n),tG(),nG(),iG(),sG(),N$(),U$(),D$(),A$(),C$(),R$(),P$(),h$(n),I$(),E$(),x$(),w$(),b$(),f$(n,e.boostPickupFilters),v$(),L$(n),k$(),O$(),F$()]}const z$=new Set(["player_id","name","is_team_0"]),H$=["is_last_","time_since_last_","frames_since_last_"];function V$(n){return n===null||typeof n=="number"||typeof n=="string"||typeof n=="boolean"||Array.isArray(n)}function G$(n,e){let t=n;for(const i of e){if(!t||typeof t!="object"||Array.isArray(t))return;t=t[i]}return t}function $$(n){return n==null?"--":typeof n=="number"?Number.isFinite(n)?Number.isInteger(n)?`${n}`:`${Number(n.toFixed(3))}`:"--":typeof n=="boolean"?n?"true":"false":Array.isArray(n)?n.length===0?"[]":JSON.stringify(n):`${n}`}function W$(n,e){if(H$.some(a=>n.startsWith(a)))return!0;const t=n.match(/^last_(.+)_time$/),i=n.match(/^last_(.+)_frame$/),s=t?.[1]??i?.[1];return s?`is_last_${s}`in e||`time_since_last_${s}`in e||`frames_since_last_${s}`in e:!1}function M_(n,e,t,i){if(!n||typeof n!="object"||Array.isArray(n))return;const s=n;for(const[a,r]of Object.entries(s)){if(e==="player"&&t.length===0&&z$.has(a)||W$(a,s))continue;const o=[...t,a];if(V$(r)){const l=`${e}:${o.join(".")}`;i.push({id:l,label:o.join("."),category:o[0]??e,scope:e,path:o,read(c){return G$(c,o)},format:$$});continue}M_(r,e,o,i)}}function X$(n){const e=new Set;return n.filter(t=>e.has(t.id)?!1:(e.add(t.id),!0))}function K$(n,e){const t=[];return n&&M_(n,"player",[],t),e&&M_(e,"team",[],t),X$(t).sort((i,s)=>i.label.localeCompare(s.label))}function q$(){return K$(uE(),Ql())}function nc(n){return q$()}function QE(n){return n.toLowerCase().replace(/[_/.-]+/g," ").replace(/\s+/g," ").trim()}function Y$(n){return QE(n).split(" ").filter(Boolean)}function j$(n,e){const t=Y$(e);if(t.length===0)return 0;const i=QE([n.scope,n.category,n.label,n.id,...n.path].join(" "));let s=0;for(const a of t){const r=i.indexOf(a);if(r<0)return null;s+=r}return s+i.length/1e3}function Z$(n,e){return n.map((t,i)=>({definition:t,index:i,score:j$(t,e)})).filter(t=>t.score!==null).sort((t,i)=>t.score-i.score||t.index-i.index).map(t=>t.definition)}function wi(n){if(!Number.isFinite(n))return"--";const e=Math.floor(Math.max(0,n)/60),t=Math.max(0,n)-e*60;return`${e}:${t.toFixed(1).padStart(4,"0")}`}class J${constructor(e){this.options=e}statsWindows=new Map;nextStatsWindowId=1;getConfigs(){return[...this.statsWindows.values()].map(e=>({id:e.id,kind:e.kind,placement:this.options.readWindowPlacement(e.element),playerId:e.playerId,team:e.team,entries:e.entries.map(t=>({statId:t.statId,targetId:t.targetId}))}))}clear(){for(const e of this.statsWindows.values())e.element.remove();this.statsWindows.clear(),this.nextStatsWindowId=1}replaceFromConfig(e){this.clear();for(const t of e)this.create(t.kind,t)}render(e=this.options.getReplayPlayer()?.getState().frameIndex??0,t={}){for(const i of this.statsWindows.values())t.preserveOpenPickers&&(i.pickerOpen||i.element.contains(document.activeElement))||this.renderStatsWindow(i,e)}create(e,t){const i=t?.id??`stats-${this.nextStatsWindowId++}`,s=Number.parseInt(i.replace(/^stats-/,""),10);Number.isFinite(s)&&(this.nextStatsWindowId=Math.max(this.nextStatsWindowId,s+1));const{x:a,y:r}=this.getStatsWindowDefaultPosition(),o=document.createElement("section");o.className="stats-window",o.dataset.windowId=i,o.style.setProperty("--window-x",`${a}px`),o.style.setProperty("--window-y",`${r}px`),t&&this.options.applyWindowPlacement(o,t.placement);const l=document.createElement("header");l.className="stats-window-header";const c=document.createElement("div");c.className="stats-window-actions";const u=document.createElement("button");if(u.type="button",u.className="stats-window-action",u.textContent="Hide",c.append(u),this.hasStatsWindowScopeSelector(e))l.classList.add("stats-window-header-actions-only"),l.append(c);else{const f=document.createElement("h2");f.textContent=this.getStatsWindowTitle(e),l.append(f,c)}const d=document.createElement("div");d.className="stats-window-body",o.append(l,d),this.options.layer.append(o);const h={id:i,kind:e,entries:t?.entries.map(f=>({key:`${i}:${f.statId}:${f.targetId??"scope"}`,statId:f.statId,targetId:f.targetId}))??[],playerId:t?.playerId??this.options.getReplayPlayer()?.replay.players[0]?.id??null,team:t?.team??"blue",pickerOpen:!1,query:"",element:o,body:d};return u.addEventListener("click",()=>{o.hidden=!0,this.options.requestConfigSync()}),this.statsWindows.set(i,h),t||this.options.bringWindowToFront(o),this.options.setLauncherOpen(!1),this.renderStatsWindow(h),this.options.requestConfigSync(),h}getStatById(e){return this.options.getStatRegistry().find(t=>t.id===e)??null}getCurrentStatsFrame(e){const t=this.options.getStatsFrameLookup();return t?zt(t,e):null}getTeamSnapshot(e,t){return t==="blue"?e.team_zero??null:e.team_one??null}getTeamLabel(e){return e==="blue"?"Blue":"Orange"}getPlayerTeamClass(e){const t=this.options.getReplayPlayer()?.replay.players.find(i=>i.id===e);return t?na(t.isTeamZero):null}getTeamScopeClass(e){return na(e==="blue")}appendGroupedPlayerOptions(e,t){const i=this.options.getReplayPlayer()?.replay.players??[];for(const s of["blue","orange"]){const a=i.filter(o=>o.isTeamZero===(s==="blue"));if(a.length===0)continue;const r=document.createElement("optgroup");r.label=`${this.getTeamLabel(s)} team`;for(const o of a)r.append(new Option(o.name,o.id,o.id===t,o.id===t));e.append(r)}}getStatsWindowScopeTeamClass(e){return e.kind==="player"?this.getPlayerTeamClass(e.playerId):e.kind==="team"?this.getTeamScopeClass(e.team??"blue"):null}getStatTargetTeamClass(e,t){return e.scope==="player"?this.getPlayerTeamClass(t):this.getTeamScopeClass(t==="orange"?"orange":"blue")}getStatsWindowTitle(e){switch(e){case"player":return"Player stats";case"team":return"Team stats";case"all-players":return"All players stats";case"all-teams":return"All teams stats";case"kickoff-overview":return"Kickoff details";case"goals-overview":return"Goal labels";case"ad-hoc":return"Ad hoc stats"}}hasStatsWindowScopeSelector(e){return e==="player"||e==="team"}hasStatsWindowStatPicker(e){return e!=="goals-overview"&&e!=="kickoff-overview"}getStatsWindowAllowedScope(e){switch(e){case"player":case"all-players":return"player";case"team":case"all-teams":return"team";case"kickoff-overview":return null;case"goals-overview":return null;case"ad-hoc":return null}}getStatsWindowDefaultPosition(){const e=this.statsWindows.size*18;return{x:Math.max(12,Math.min(window.innerWidth-360,96+e)),y:Math.max(64,Math.min(window.innerHeight-240,96+e))}}renderStatsWindow(e,t=this.options.getReplayPlayer()?.getState().frameIndex??0){const i=document.activeElement,s=i instanceof HTMLInputElement&&i.dataset.statsWindowSearch===e.id,a=s?i.selectionStart:null,r=s?i.selectionEnd:null,o=s?i.selectionDirection:null;if(e.body.replaceChildren(),this.renderStatsWindowScope(e),this.hasStatsWindowStatPicker(e.kind)&&(this.renderStatsWindowAddControl(e),this.renderStatsWindowPicker(e)),this.renderStatsWindowEntries(e,t),s){const l=e.body.querySelector(`input[data-stats-window-search="${e.id}"]`);l?.focus({preventScroll:!0}),l&&a!==null&&r!==null&&l.setSelectionRange(a,r,o??"none")}}renderStatsWindowScope(e){if(e.kind!=="player"&&e.kind!=="team")return;const t=document.createElement("div");t.className="stats-window-scope-row";const i=document.createElement("select");i.className="stats-window-scope-select";const s=this.getStatsWindowScopeTeamClass(e);s&&i.classList.add(s),i.setAttribute("aria-label",e.kind==="player"?"Player stats target":"Team stats target"),e.kind==="player"?(this.appendGroupedPlayerOptions(i,e.playerId),i.value=e.playerId??"",i.addEventListener("change",()=>{e.playerId=i.value||null,this.renderStatsWindow(e),this.options.requestConfigSync()})):(i.append(new Option("Blue","blue",e.team==="blue",e.team==="blue"),new Option("Orange","orange",e.team==="orange",e.team==="orange")),i.value=e.team??"blue",i.addEventListener("change",()=>{e.team=i.value==="orange"?"orange":"blue",this.renderStatsWindow(e),this.options.requestConfigSync()})),t.append(i),e.body.append(t)}renderStatsWindowAddControl(e){const t=document.createElement("button");if(t.type="button",t.className="stats-window-add-button",t.textContent="+",t.title="Add stat",t.setAttribute("aria-label","Add stat"),t.setAttribute("aria-expanded",String(e.pickerOpen)),this.activateButton(t,()=>{e.pickerOpen=!e.pickerOpen,this.renderStatsWindow(e)}),this.hasStatsWindowScopeSelector(e.kind)){e.body.querySelector(".stats-window-scope-row")?.append(t);return}const i=document.createElement("div");i.className="stats-window-toolbar",i.append(t),e.body.append(i)}activateButton(e,t){let i=!1;e.addEventListener("pointerdown",s=>{e.disabled||(i=!0,s.preventDefault(),t())}),e.addEventListener("click",()=>{if(i){i=!1;return}e.disabled||t()})}renderStatsWindowPicker(e){const t=document.createElement("div");if(t.className="stats-window-picker",t.hidden=!e.pickerOpen,t.hidden){e.body.append(t);return}const i=this.getStatsWindowAllowedScope(e.kind),s=document.createElement("input");s.type="search",s.placeholder="Search stats",s.value=e.query,s.dataset.statsWindowSearch=e.id;const a=document.createElement("div");a.className="stats-window-picker-list",s.addEventListener("input",()=>{e.query=s.value,this.renderStatsWindowPickerList(e,a,i)}),this.renderStatsWindowPickerList(e,a,i),t.append(s,a),e.body.append(t)}renderStatsWindowPickerList(e,t,i){t.replaceChildren();const s=this.options.getStatRegistry(),a=i?s.filter(l=>l.scope===i):s,r=Z$(a,e.query),o=new Map;for(const l of r){const c=o.get(l.category)??[];c.push(l),o.set(l.category,c)}for(const[l,c]of o){if(c.length<2)continue;const u=document.createElement("button");u.type="button",u.className="stats-window-picker-item",u.innerHTML=`Add all ${l}${c.length}`,this.activateButton(u,()=>{for(const d of c)this.addStatToWindow(e,d);this.renderStatsWindow(e),this.options.requestConfigSync()}),t.append(u)}for(const l of r){const c=document.createElement("button");c.type="button",c.className="stats-window-picker-item",c.innerHTML=`${l.label}${l.scope}`,c.disabled=e.kind!=="ad-hoc"&&e.entries.some(u=>u.statId===l.id),this.activateButton(c,()=>{this.addStatToWindow(e,l),this.renderStatsWindow(e),this.options.requestConfigSync()}),t.append(c)}if(r.length===0){const l=document.createElement("p");l.className="stat-window-empty",l.textContent=s.length===0?"No stats available.":"No matching stats.",t.append(l)}}addStatToWindow(e,t){const i=e.kind==="ad-hoc"?this.getDefaultAdHocTargetId(t):void 0;e.entries.some(s=>s.statId===t.id&&s.targetId===i)||e.entries.push({key:`${e.id}:${t.id}:${i??"scope"}`,statId:t.id,targetId:i})}getDefaultAdHocTargetId(e){return e.scope==="player"?this.options.getReplayPlayer()?.replay.players[0]?.id??"":"blue"}removeStatFromWindow(e,t){const i=e.entries.findIndex(s=>s.key===t);i>=0&&e.entries.splice(i,1)}renderStatsWindowEntries(e,t){if(e.kind==="goals-overview"){this.renderGoalLabelsOverview(e);return}if(e.kind==="kickoff-overview"){this.renderKickoffOverview(e,t);return}const i=this.getStatsWindowAllowedScope(e.kind),s=e.entries.map(r=>({entry:r,definition:this.getStatById(r.statId)})).filter(r=>r.definition!==null&&(!i||r.definition.scope===i));if(s.length===0){const r=document.createElement("p");r.className="stat-window-empty",r.textContent="No stats added.",e.body.append(r);return}const a=this.getCurrentStatsFrame(t);if(!a){const r=document.createElement("p");r.className="stat-window-empty",r.textContent="Load a replay to show stats.",e.body.append(r);return}if(e.kind==="all-players"){this.renderAllPlayersStats(e,a,s);return}if(e.kind==="all-teams"){this.renderAllTeamsStats(e,a,s);return}if(e.kind==="player"){const r=e.playerId?a.players.find(o=>At(o.player_id)===e.playerId)??null:null;this.renderScopedStatList(e,r,s);return}if(e.kind==="team"){this.renderScopedStatList(e,this.getTeamSnapshot(a,e.team??"blue"),s);return}e.kind==="ad-hoc"&&this.renderAdHocStats(e,a,s)}renderGoalLabelsOverview(e){const t=this.options.getStatsTimeline(),i=this.options.getReplayPlayer()?.replay??null;if(!t||!i){this.appendStatsWindowEmpty(e,"Load a replay to show goal labels.");return}const s=[...ve(t,"goal_context")].sort((o,l)=>o.time-l.time),a=s.map((o,l)=>l);if(a.length===0){this.appendStatsWindowEmpty(e,"No goals loaded.");return}const r=document.createElement("div");r.className="goal-label-list";for(const o of a){const l=s[o]??null,c=[...l?.tags??[]].sort((M,C)=>M.kind.localeCompare(C.kind)||C.metadata.confidence-M.metadata.confidence),u=l?.time??0,d=l?.scorer??null,h=d?At(d):null,f=d?i.players.find(M=>M.id===h)?.name??h:"Unknown scorer",p=l?.scoring_team_is_team_0??null,g=document.createElement("section");g.className="goal-label-item",p!==null&&g.classList.add(na(p));const _=document.createElement("header"),m=document.createElement("h3");m.textContent=`Goal ${o+1}`;const v=document.createElement("span");v.textContent=`${wi(u)} · ${f}`,_.append(m,v);const y=document.createElement("div");if(y.className="goal-label-tags",c.length===0){const M=document.createElement("span");M.className="goal-label-tag goal-label-tag-empty",M.textContent="Unlabeled",y.append(M)}else for(const M of c){const C=document.createElement("span");C.className="goal-label-tag";const w=n4(M);C.textContent=`${Ai(M.kind)} ${Math.round(M.metadata.confidence*100)}%${w?` - ${w}`:""}`,y.append(C)}const b=document.createElement("div");b.className="goal-label-actions";const T=document.createElement("button");T.type="button",T.className="goal-label-watch",T.textContent="Watch",T.addEventListener("click",()=>{this.options.watchGoalReplay(u,h)});const x=document.createElement("button");x.type="button",x.textContent="Cue",x.addEventListener("click",()=>{this.options.cueGoalReplay(u)}),b.append(T,x),g.append(_,y,b),r.append(g)}e.body.append(r)}renderKickoffOverview(e,t){const i=this.options.getStatsTimeline(),s=this.options.getReplayPlayer()?.replay??null;if(!i||!s){this.appendStatsWindowEmpty(e,"Load a replay to show kickoff details.");return}const a=this.getClosestKickoffEvent(i,t);if(!a){this.appendStatsWindowEmpty(e,"No kickoff events loaded.");return}const r=a.payload.payload,o=document.createElement("section");o.className="kickoff-overview";const l=document.createElement("header");l.className="kickoff-overview-hero";const c=document.createElement("div"),u=document.createElement("h3");u.textContent=this.formatKickoffTitle(a);const d=document.createElement("span");d.textContent=`Nearest kickoff · resolved at ${wi(r.end_time)}`,c.append(u,d);const h=document.createElement("strong"),f=this.teamClassFromNullable(r.winning_team_is_team_0);h.className="kickoff-overview-victor",f&&h.classList.add(f),h.textContent=this.formatOutcome(r),l.append(c,h);const p=document.createElement("div");p.className="kickoff-overview-summary",p.append(this.renderKickoffMetric("Win strength",`${this.formatNullableNumber(r.win_strength,2)} · ${this.formatKickoffLabelValue("kickoff_win_strength",r.win_strength_band)}`),this.renderKickoffMetric("First touch",this.formatFirstTouch(r)),this.renderKickoffMetric("Advantage",this.formatAdvantage(r)),this.renderKickoffMetric("Contested",this.formatContested(r)));const g=document.createElement("div");g.className="kickoff-detail-grid",g.append(this.renderKickoffDetail("Kickoff start",wi(r.start_time)),this.renderKickoffDetail("Movement start",wi(r.movement_start_time)),this.renderKickoffDetail("Live action",r.live_action_start_time===null?"--":wi(r.live_action_start_time)),this.renderKickoffDetail("First touch",r.first_touch_time===null?"--":wi(r.first_touch_time)),this.renderKickoffDetail("Resolution",wi(r.end_time)),this.renderKickoffDetail("After first touch",this.formatSeconds(r.advantage_seconds_after_first_touch)));const _=document.createElement("div");_.className="kickoff-strategy-list",_.append(this.renderKickoffTeamStrategy("Blue",r.team_zero_taker,r.team_zero_non_takers),this.renderKickoffTeamStrategy("Orange",r.team_one_taker,r.team_one_non_takers)),o.append(l,p,g,_),e.body.append(o)}getClosestKickoffEvent(e,t){return ec(e).filter(s=>s.payload.kind==="kickoff").sort((s,a)=>{const r=this.kickoffFrameDistance(s.payload.payload,t),o=this.kickoffFrameDistance(a.payload.payload,t);return r!==o?r-o:s.payload.payload.start_frame-a.payload.payload.start_frame})[0]??null}kickoffFrameDistance(e,t){return t>=e.start_frame&&t<=e.end_frame?0:Math.min(Math.abs(t-e.start_frame),Math.abs(t-e.end_frame))}renderKickoffMetric(e,t){const i=document.createElement("div");i.className="kickoff-metric";const s=document.createElement("span");s.textContent=e;const a=document.createElement("strong");return a.textContent=t,i.append(s,a),i}renderKickoffDetail(e,t){const i=document.createElement("div");i.className="kickoff-detail-row";const s=document.createElement("span");s.textContent=e;const a=document.createElement("strong");return a.textContent=t,i.append(s,a),i}renderKickoffTeamStrategy(e,t,i){const s=document.createElement("section");s.className=`kickoff-strategy-team ${e==="Blue"?"team-blue":"team-orange"}`;const a=document.createElement("h4");a.textContent=e,s.append(a);const r=document.createElement("p");if(r.className="kickoff-strategy-line",r.textContent=t?`${this.getPlayerName(t.player)}: ${this.formatKickoffLabelValue("kickoff_approach",t.approach)} from ${this.formatKickoffLabelValue("kickoff_spawn",t.spawn_position)} (${this.formatKickoffLabelValue("taker_outcome",t.outcome)}, ${this.formatSeconds(t.time_to_ball)})`:"No taker detected",s.append(r),i.length>0){const o=document.createElement("ul");o.className="kickoff-support-list";for(const l of i){const c=document.createElement("li");c.textContent=`${this.getPlayerName(l.player)}: ${this.formatKickoffLabelValue("support_behavior",l.support_behavior)} from ${this.formatKickoffLabelValue("kickoff_spawn",l.spawn_position)}`,o.append(c)}s.append(o)}return s}formatOutcome(e){return e.winning_team_is_team_0===!0?"Blue wins":e.winning_team_is_team_0===!1?"Orange wins":e.outcome==="neutral"?"Neutral":"Unknown"}formatFirstTouch(e){if(!e.first_touch_player)return"--";const t=e.first_touch_team_is_team_0===!0?"Blue":e.first_touch_team_is_team_0===!1?"Orange":"Unknown",i=e.first_touch_time===null?"--":wi(e.first_touch_time);return`${t} · ${this.getPlayerName(e.first_touch_player)} · ${i}`}formatAdvantage(e){if(e.advantage==="no_advantage")return"No advantage";const t=e.advantage_team_is_team_0===!0?"Blue":e.advantage_team_is_team_0===!1?"Orange":"Unknown",i=e.advantage.replace(/^team_(zero|one)_/,""),s=e.advantage_player?` · ${this.getPlayerName(e.advantage_player)}`:"",a=e.advantage_time===null?"":` · ${wi(e.advantage_time)}`;return`${t} ${this.formatKickoffLabelValue("kickoff_advantage",i)}${s}${a}`}formatContested(e){return e.kickoff_possession_outcome==="contested"?"Yes":e.kickoff_possession_team_is_team_0===!0?`No · Blue ${this.formatPossessionOutcome(e.kickoff_possession_outcome)}`:e.kickoff_possession_team_is_team_0===!1?`No · Orange ${this.formatPossessionOutcome(e.kickoff_possession_outcome)}`:`No · ${this.formatPossessionOutcome(e.kickoff_possession_outcome)}`}formatPossessionOutcome(e){return e.endsWith("_advantage")?"advantage":e.endsWith("_possession")?"possession":this.formatKickoffLabelValue("kickoff_possession_outcome",e)}formatKickoffType(e){return this.formatKickoffLabelValue("kickoff_type",e)}formatKickoffTitle(e){const t=e.payload.payload,i=this.formatKickoffDirection(t.kickoff_direction),s=[this.formatKickoffType(t.kickoff_type),i].filter(Boolean).join(" ");return[e.meta.label,s].filter(Boolean).join(" · ")}formatKickoffDirection(e){return e==="unknown"?"":`(${this.formatKickoffLabelValue("kickoff_direction",e)})`}formatNullableNumber(e,t){return e===null||!Number.isFinite(e)?"--":e.toFixed(t)}formatSeconds(e){return e===null||!Number.isFinite(e)?"--":`${e.toFixed(2)}s`}formatLabel(e){return e.replace(/^team_zero_/,"blue_").replace(/^team_one_/,"orange_").replaceAll("_"," ").replace(/\b\w/g,t=>t.toUpperCase())}formatKickoffLabelValue(e,t){const i=t.replace(/^team_zero_/,"blue_").replace(/^team_one_/,"orange_");return e==="kickoff_advantage"?this.formatLabel(i.replace(/^blue_/,"").replace(/^orange_/,"")):e==="kickoff_possession_outcome"?this.formatLabel(i.replace(/^blue_/,"Blue ").replace(/^orange_/,"Orange ")):this.formatLabel(i)}teamClassFromNullable(e){return e===null?null:na(e)}getPlayerName(e){const t=At(e);return this.options.getReplayPlayer()?.replay.players.find(i=>i.id===t)?.name??t}appendStatsWindowEmpty(e,t){const i=document.createElement("p");i.className="stat-window-empty",i.textContent=t,e.body.append(i)}renderScopedStatList(e,t,i){const s=document.createElement("div");s.className="stats-window-stat-list";for(const{entry:a,definition:r}of i)s.append(this.renderStatRow(e,a,r,t?r.format(r.read(t)):"--"));e.body.append(s)}renderAllPlayersStats(e,t,i){const s=document.createElement("div");s.className="stats-window-team-list";for(const a of["blue","orange"]){const r=t.players.filter(h=>h.is_team_0===(a==="blue"));if(r.length===0)continue;const o=document.createElement("section");o.className=`stats-window-team-group ${this.getTeamScopeClass(a)}`;const l=document.createElement("header");l.className="stats-window-team-header";const c=document.createElement("h3");c.textContent=`${this.getTeamLabel(a)} team`;const u=document.createElement("span");u.textContent=`${r.length} player${r.length===1?"":"s"}`,l.append(c,u),o.append(l);const d=document.createElement("div");d.className="stats-window-entity-list";for(const h of r){const f=document.createElement("section");f.className=`stats-window-entity ${na(h.is_team_0)}`;const p=document.createElement("h4");p.className="stats-window-entity-title",p.textContent=h.name,f.append(p);for(const{entry:g,definition:_}of i)f.append(this.renderStatRow(e,g,_,_.format(_.read(h))));d.append(f)}o.append(d),s.append(o)}e.body.append(s)}renderAllTeamsStats(e,t,i){const s=document.createElement("div");s.className="stats-window-entity-list";for(const a of["blue","orange"]){const r=this.getTeamSnapshot(t,a),o=document.createElement("section");o.className=`stats-window-entity ${this.getTeamScopeClass(a)}`;const l=document.createElement("h3");l.className="stats-window-entity-title",l.textContent=this.getTeamLabel(a),o.append(l);for(const{entry:c,definition:u}of i)o.append(this.renderStatRow(e,c,u,r?u.format(u.read(r)):"--"));s.append(o)}e.body.append(s)}renderAdHocStats(e,t,i){const s=document.createElement("div");s.className="stats-window-stat-list";for(const{entry:a,definition:r}of i){const o=this.getAdHocTarget(t,r,a.targetId);s.append(this.renderStatRow(e,a,r,o?r.format(r.read(o)):"--"))}e.body.append(s)}getAdHocTarget(e,t,i){return t.scope==="player"?e.players.find(s=>At(s.player_id)===i)??e.players[0]??null:this.getTeamSnapshot(e,i==="orange"?"orange":"blue")}renderStatRow(e,t,i,s){const a=document.createElement("div");a.className="stats-window-stat-row";const r=document.createElement("span");if(r.className="stats-window-stat-name",r.textContent=i.label,e.kind==="ad-hoc"){const c=document.createElement("select");c.className="stats-window-stat-target";const u=this.getStatTargetTeamClass(i,t.targetId);u&&c.classList.add(u),i.scope==="player"?this.appendGroupedPlayerOptions(c,t.targetId):c.append(new Option("Blue","blue",t.targetId==="blue",t.targetId==="blue"),new Option("Orange","orange",t.targetId==="orange",t.targetId==="orange")),c.value=t.targetId??"",c.addEventListener("change",()=>{const d=c.value;if(e.entries.some(f=>f!==t&&f.statId===t.statId&&f.targetId===d)){this.renderStatsWindow(e);return}const h=e.entries.findIndex(f=>f.key===t.key);h>=0&&(e.entries[h]={key:`${e.id}:${t.statId}:${d}`,statId:t.statId,targetId:d}),this.renderStatsWindow(e),this.options.requestConfigSync()}),r.append(" ",c)}const o=document.createElement("span");o.className="stats-window-stat-value",o.textContent=s;const l=document.createElement("button");return l.type="button",l.className="stats-window-stat-remove",l.textContent="x",l.addEventListener("click",()=>{this.removeStatFromWindow(e,t.key),this.renderStatsWindow(e),this.options.requestConfigSync()}),a.append(r,o,l),a}}function Q$(n){return new J$(n)}const eW=new Set(["module:dodge","module:touch","module:powerslide"]),tW=["stats-stream:"],ch=["#3b82f6","#06b6d4","#22c55e","#a855f7","#f97316","#ef4444","#f59e0b","#ec4899"],df="#d1d9e0",jg=ch[0],Zg=ch[4],nW=[{id:"core",label:"Shots, saves, assists",buildEvents(n){return n.replay.timelineEvents.filter(e=>e.kind==="shot"||e.kind==="save"||e.kind==="assist")}},{id:"demo",label:"Demos",buildEvents(n){return n.replay.timelineEvents.filter(e=>e.kind==="demo")}}],iW=[];function e1(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function t1(n){if(typeof n=="string"&&n.length>0)return n;if(!e1(n))return null;const[e,t]=Object.entries(n)[0]??[];return!e||t==null?null:typeof t=="string"||typeof t=="number"?`${e}:${t}`:`${e}:${JSON.stringify(t)}`}function n1(n){return n.split(/[_-]+/).filter(e=>e.length>0).map(e=>e.slice(0,1).toUpperCase()).join("").slice(0,3)||"E"}function sW(n){if(typeof n!="number"||!Number.isFinite(n))return null;const e=Math.abs(n)<1?2:1;return`${n.toFixed(e).replace(/\.0+$/,"").replace(/(\.\d*[1-9])0+$/,"$1")}s`}function Wi(n){return typeof n!="string"||n.length===0?null:n.split(/[_-]+/).filter(e=>e.length>0).map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1)}`).join(" ")}function aW(n){return n==="team_zero_side"?"Blue side":n==="team_one_side"?"Orange side":n==="neutral"?"Neutral zone":Wi(n)}function rW(n){const e=Wi(n);return e?`${e.toLowerCase()} third`:null}function oW(n){return n==="team_zero_third"?"Blue third":n==="team_one_third"?"Orange third":n==="neutral_third"?"Neutral third":Wi(n)}function lW(n){return n==="team_zero"?"Blue":n==="team_one"?"Orange":n==="neutral"?"Neutral":Wi(n)}function ud(n){return e1(n.payload.payload)?n.payload.payload:{}}function i1(n){return n===!0?jg:n===!1?Zg:null}function cW(n){return n==="team_zero_side"?jg:n==="team_one_side"?Zg:n==="neutral"?df:null}function uW(n){return n==="team_zero"?jg:n==="team_one"?Zg:n==="neutral"?df:null}function dW(n){return typeof n=="boolean"?i1(n):null}const hW={ball_half(n){return cW(ud(n).field_half)},possession(n){return uW(ud(n).possession_state)},player_possession(n){return dW(ud(n).is_team_0)}};function s1(n,e,t){return hW[n]?.(e)??i1(t)??df}function ui(n){return n.filter(e=>!!e).join(" | ")}function fW({event:n,playerName:e,streamLabel:t,teamLabel:i}){const s=ud(n),a=sW(s.duration);if(n.payload.kind==="ball_half"){const r=aW(s.field_half),o=s.active===!1?"Ball half inactive":r?`Ball on ${r.toLowerCase()}`:null;return ui([o??t,a])}if(n.payload.kind==="ball_third"){const r=oW(s.field_third),o=s.active===!1?"Ball third inactive":r?`Ball in ${r.toLowerCase()}`:null;return ui([o??t,a])}if(n.payload.kind==="territorial_pressure"){const r=Wi(s.end_reason),o=`${i??""} territorial pressure`.trim();return ui([r?`${o} ended: ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="possession"){const r=lW(s.possession_state),o=rW(s.field_third),l=r?`${r} possession`:t;return ui([l,o,a])}if(n.payload.kind==="controlled_play"){const r=e?`${e} controlled play`:t;return ui([r,a])}if(n.payload.kind==="ball_carry"){const r=e?`${e} ${t.toLowerCase()}`:t;return ui([r,a])}if(n.payload.kind==="player_activity"){const r=Wi(s.state),o=e?`${e} positioning`:t;return ui([r?`${o} ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="field_third"){const r=Wi(s.state),o=e?`${e} positioning`:t;return ui([r?`${o} in ${r.toLowerCase()} third`:o,a])}if(n.payload.kind==="field_half"){const r=Wi(s.state),o=e?`${e} positioning`:t;return ui([r?`${o} in ${r.toLowerCase()} half`:o,a])}if(n.payload.kind==="ball_depth"){const r=Wi(s.state),o=e?`${e} ball depth`:t;return ui([r?`${o}: ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="depth_role"){const r=Wi(s.state),o=e?`${e} depth role`:t;return ui([r?`${o}: ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="shadow_defense"){const r=e?`${e} shadow defense`:t;return ui([r,a])}if(n.payload.kind==="rotation_role"){const r=Wi(s.state),o=e?`${e} rotation`:t;return ui([r?`${o}: ${r.toLowerCase()}`:o,a])}return e?`${e} ${t.toLowerCase()}`:t}function pW(n,e,t){const i=Ai(e),s=new Map(n.replay.players.map(a=>[a.id,a.name]));return t.flatMap((a,r)=>{const o=a.meta.timing.type==="moment"?{time:a.meta.timing.time,frame:a.meta.timing.frame}:{time:a.meta.timing.end_time,frame:a.meta.timing.end_frame},l=t1(a.meta.primary_player),c=l?s.get(l)??l:null,u=a.meta.team_is_team_0??null,d=u==null?null:u?"Blue":"Orange",h=a.meta.id||`${e}:${o.frame??o.time}:${r}`,f=s1(e,a,u);return[{id:`stats-stream:${h}`,time:n.replay.frames[o.frame??-1]?.time??o.time,frame:o.frame,kind:e,label:fW({event:a,playerName:c,streamLabel:i,teamLabel:d}),shortLabel:n1(e),playerId:l,playerName:c,isTeamZero:u,color:f}]})}function mW(n,e,t){const i=Ai(e),s=new Map(n.replay.players.map(a=>[a.id,a.name]));return t.flatMap((a,r)=>{if(a.meta.timing.type!=="span")return[];const o={startTime:a.meta.timing.start_time,endTime:a.meta.timing.end_time,startFrame:a.meta.timing.start_frame,endFrame:a.meta.timing.end_frame},l=a.meta.team_is_team_0??null,c=l==null?null:l?"Blue":"Orange",u=t1(a.meta.primary_player),d=u?s.get(u)??u:null,h=s1(e,a,l),f=a.meta.id||`${e}:${o.startFrame??o.startTime}:${o.endFrame??o.endTime}:${r}`,p=d?`${d} ${i.toLowerCase()}`:c?`${c} ${i.toLowerCase()}`:i;let g=`stats-stream:${e}`,_=i;return a.meta.scope==="player"&&u?(g=`stats-stream:${e}:player:${u}`,_=d?`${d} ${i.toLowerCase()}`:i):a.meta.scope==="team"&&l!=null&&(g=`stats-stream:${e}:team:${l?"0":"1"}`,_=c?`${c} ${i.toLowerCase()}`:i),[{id:`stats-stream:${f}`,startTime:n.replay.frames[o.startFrame??-1]?.time??o.startTime,endTime:Math.max(n.replay.frames[o.startFrame??-1]?.time??o.startTime,n.replay.frames[o.endFrame??-1]?.time??o.endTime),lane:g,laneLabel:_,label:p,shortLabel:n1(e),isTeamZero:l,color:h}]}).sort((a,r)=>a.startTime!==r.startTime?a.startTime-r.startTime:(a.id??"").localeCompare(r.id??""))}function _W(n,e,t,i){return[...new Set([...XT,...ec(n.statsTimeline).map(a=>a.meta.stream)])].flatMap(a=>{const r=ec(n.statsTimeline).filter(u=>u.meta.stream===a);if(i.has(a)&&r.length>0)return[];const o=r.some(u=>u.meta.timing.type==="span"),l=o?mW(n,a,r):[],c=pW(n,a,r);return[{id:`stats-stream:${a}`,playlistId:`stats-stream:${a}`,timelineKey:`stats-stream:${a}`,timelineId:`stats-stream:${a}`,group:"Event streams",label:Ai(a),count:o?l.length:c.length,active:e.has(`stats-stream:${a}`),buildTimelineEvents(){return o?[]:c},buildPlaylistEvents(){return c},buildTimelineRanges:o?()=>l:void 0,setActive(u){t(`stats-stream:${a}`,u)}}]})}function gW(n){return new Set([...n.filter(e=>e.getTimelineEvents).map(e=>e.id),...NE])}function yW(){return[...NE].sort((n,e)=>Ai(n).localeCompare(Ai(e)))}function vW({ctx:n,modules:e,activeTimelineEventSourceIds:t,activeMechanicTimelineKinds:i,toggleEventSource:s,setMechanicTimelineKind:a}){if(!n)return[];const r=[];for(const o of nW){const l=o.buildEvents(n),c=l.length;r.push({id:o.id,playlistId:`replay:${o.id}`,timelineKey:`events:${o.id}`,timelineId:`events:${o.id}`,group:"Replay",label:o.label,count:c,active:t.has(o.id),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){s(o.id,u)}})}for(const o of e.filter(l=>l.getTimelineEvents)){const l=o.getTimelineEvents?.(n)??[],c=l.length;r.push({id:o.id,playlistId:`module:${o.id}`,timelineKey:`module:${o.id}`,timelineId:`module:${o.id}`,group:"Stats",label:o.label,count:c,active:t.has(o.id),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){s(o.id,u)}})}for(const o of iW){const l=o.buildEvents(n),c=l.length;r.push({id:o.id,playlistId:`extra:${o.id}`,timelineKey:`extra:${o.id}`,timelineId:`extra:${o.id}`,group:"Stats",label:o.label,count:c,active:t.has(o.id),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){s(o.id,u)}})}r.push(..._W(n,t,s,gW(e)));for(const o of yW()){const l=FE[o](n.statsTimeline,n.replay),c=l.length;r.push({id:`mechanic:${o}`,playlistId:`mechanic:${o}`,timelineKey:`mechanic:${o}`,timelineId:`mechanic:${o}`,group:"Event types",label:Ai(o),count:c,active:i.has(o),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){a(o,u)}})}return r.sort((o,l)=>o.label.localeCompare(l.label))}function bW(n,e){if(!n)return[];const t=[{id:"replay:goals",group:"Replay",label:"Goals",events:n.replay.timelineEvents.filter(s=>s.kind==="goal")}],i=e.map(s=>({id:s.playlistId,group:s.group,label:s.label,events:s.buildPlaylistEvents()}));return[...t,...i]}function E_(n,e){const t=n.map(i=>i.id);return e===null?new Set(t.filter(i=>!eW.has(i)&&!tW.some(s=>i.startsWith(s)))):new Set(t.filter(i=>e.has(i)))}function xW(n,e){const t=n.playerId??null,i=t?e.findIndex(s=>s.id===t):-1;return i>=0?ch[i%ch.length]:n.color??df}function wW({sources:n,activeSourceIds:e,replayPlayers:t}){const i=E_(n,e);return n.filter(s=>i.has(s.id)).flatMap(s=>s.events.map((a,r)=>({key:`${s.id}:${a.id??`${a.kind}:${a.time}:${r}`}`,sourceId:s.id,sourceLabel:s.label,event:a,color:xW(a,t)}))).sort((s,a)=>s.event.time!==a.event.time?s.event.time-a.event.time:(s.event.label??s.sourceLabel).localeCompare(a.event.label??a.sourceLabel))}class SW{constructor(e){this.options=e}getSources(e=this.options.getContext()){return vW({ctx:e,modules:this.options.modules,activeTimelineEventSourceIds:this.options.getActiveTimelineEventSourceIds(),activeMechanicTimelineKinds:this.options.getActiveMechanicTimelineKinds(),toggleEventSource:this.options.toggleEventSource,setMechanicTimelineKind:this.options.setMechanicTimelineKind})}countVisibleSources(e){return e.replay.timelineEvents.filter(i=>i.kind==="goal").length+this.getSources(e).filter(i=>i.active).reduce((i,s)=>i+s.count,0)}render(){const{body:e}=this.options;e.replaceChildren();const t=this.getSources();if(t.length===0){const d=document.createElement("p");d.className="stat-window-empty",d.textContent="No events loaded.",e.append(d);return}const i=document.createElement("div");i.className="mechanics-actions";const s=document.createElement("button");s.type="button",s.className="module-summary-item",s.addEventListener("click",()=>{for(const d of t)d.setActive(!0);this.options.setupActiveModules(),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.render(),this.options.renderModuleSummary(),this.options.renderModuleSettings(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()});const a=document.createElement("span");a.textContent="All events";const r=document.createElement("strong");r.textContent=`${t.length}`,s.append(a,r);const o=document.createElement("button");o.type="button",o.className="module-summary-item",o.addEventListener("click",()=>{for(const d of t)d.setActive(!1);this.options.setupActiveModules(),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.render(),this.options.renderModuleSummary(),this.options.renderModuleSettings(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()});const l=document.createElement("span");l.textContent="No events";const c=document.createElement("strong");c.textContent="Off",o.append(l,c),i.append(s,o),e.append(i);const u=this.renderSourceList(t);u&&e.append(u)}renderSourceList(e){if(e.length===0)return null;const t=document.createElement("div");t.className="module-list mechanics-list mechanics-event-list",t.style.setProperty("--event-source-columns",`${TW(e.length)}`);for(const i of e){const s=document.createElement("button");s.type="button",s.className="module-summary-item",s.dataset.active=i.active?"true":"false",s.setAttribute("aria-pressed",i.active?"true":"false"),s.addEventListener("click",()=>{i.setActive(!i.active),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.render(),this.options.renderTimelineEventCount()});const a=document.createElement("span");a.textContent=i.label;const r=document.createElement("strong");r.textContent=`${i.active?"On":"Off"} ${i.count}`,s.append(a,r),t.append(s)}return t}}function TW(n){return window.innerWidth<640?1:window.innerWidth<900?n>=7?2:1:n>=13?3:n>=7?2:1}function MW(n){return new SW(n)}const EW=new Set(["ceiling-shot","fifty-fifty","ball_half",WE,"absolute-positioning","dodge","speed-flip","touch"]),Vx="touch";class CW{constructor(e){this.options=e}renderSummary(){const{summary:e}=this.options.elements;e.replaceChildren();const t=this.options.getTimelineSources(),i=t.map(o=>this.renderTimelineSourceToggle(o)),s=[],a=[],r=this.options.getContext();for(const o of this.options.modules){const l=EW.has(o.id);!o.getTimelineEvents&&!o.getTimelineRanges&&!l||(t.length===0&&o.getTimelineEvents&&i.push(this.renderCapabilityToggle(o.id,fm(o,"events"),"events")),o.getTimelineRanges&&s.push(this.renderCapabilityToggle(o.id,fm(o,"ranges"),"ranges",r?o.getTimelineRanges(r).length:void 0)),l&&a.push(this.renderCapabilityToggle(o.id,fm(o,"effects"),"effects")))}a.push(this.renderBoostPickupAnimationToggle()),e.append(hm("Timeline markers",i),hm("Timeline ranges",s),hm("In-game visualizations",a))}renderSettings(){const{settings:e}=this.options.elements;e.replaceChildren();const t=this.options.getContext(),i=this.options.getActiveModules().filter(s=>s.id!=="boost"&&s.id!==Vx).map(s=>s.renderSettings?.(t)??null).filter(s=>s instanceof HTMLElement);if(i.length===0){e.hidden=!0,this.renderBoostPickupFiltersWindow(),this.renderTouchControlsWindow();return}e.hidden=!1,e.append(...i),this.renderBoostPickupFiltersWindow(),this.renderTouchControlsWindow()}renderBoostPickupAnimationToggle(){const e=this.options.getBoostPickupAnimationEnabled(),t=document.createElement("button");t.type="button",t.className="module-summary-item",t.dataset.active=e?"true":"false",t.setAttribute("aria-pressed",e?"true":"false"),t.addEventListener("click",this.options.toggleBoostPickupAnimation);const i=document.createElement("span");i.textContent="Boost pickup animation";const s=document.createElement("strong");return s.textContent=e?"On":"Off",t.append(i,s),t}renderCapabilityToggle(e,t,i,s){const r=this.options.getActiveCapabilityIds(i).has(e),o=document.createElement("button");o.type="button",o.className="module-summary-item",o.dataset.active=r?"true":"false",o.setAttribute("aria-pressed",r?"true":"false"),o.addEventListener("click",()=>{this.options.toggleCapability(e,i,!this.options.getActiveCapabilityIds(i).has(e))});const l=document.createElement("span");l.textContent=t;const c=document.createElement("strong");return c.textContent=Gx(r,s),o.append(l,c),o}renderTimelineSourceToggle(e){const t=document.createElement("button");t.type="button",t.className="module-summary-item",t.dataset.active=e.active?"true":"false",t.setAttribute("aria-pressed",e.active?"true":"false"),t.addEventListener("click",()=>{e.setActive(!e.active),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.options.renderTimelineEventCount(),this.options.requestConfigSync(),this.renderSummary()});const i=document.createElement("span");i.textContent=AW(e);const s=document.createElement("strong");return s.textContent=Gx(e.active,e.count),t.append(i,s),t}renderBoostPickupFiltersWindow(){const e=this.options.getContext(),t=this.options.boostPickupFilters.renderSettings(e,{showHeader:!1});this.options.elements.boostPickupFilters.replaceChildren(t)}renderTouchControlsWindow(){const e=this.options.getContext(),i=this.options.modules.find(s=>s.id===Vx)?.renderSettings?.(e)??null;this.options.elements.touchControls.replaceChildren(),i instanceof HTMLElement&&this.options.elements.touchControls.append(i)}}function hm(n,e){const t=document.createElement("section");t.className="module-summary-group";const i=document.createElement("h3");i.textContent=n;const s=document.createElement("div");return s.className="module-list",s.append(...e),t.append(i,s),t}function Gx(n,e){const t=n?"On":"Off";return e==null?t:`${t} ${e}`}function AW(n){return n.group==="Replay"?n.label:`${n.label} events`}function fm(n,e){const t={"absolute-positioning:ranges":"Position zones","backboard:events":"Backboard","ball-carry:events":"Ball carry","boost:ranges":"Boost pickup timeline","bump:events":"Bump","ceiling-shot:events":"Ceiling shot","demo:events":"Demo","dodge-reset:events":"Dodge refresh","double-tap:events":"Double tap","fifty-fifty:events":"50/50","fifty-fifty:ranges":"50/50","dodge:events":"Dodge","half-flip:events":"Half flip","possession:ranges":"Possession","powerslide:events":"Powerslide","powerslide:ranges":"Powerslide","ball_half:ranges":"Half control","ball_third:ranges":"Third control","rush:ranges":"Rush","speed-flip:events":"Speed flip","touch:events":"Touch","wavedash:events":"Wavedash"},i={"absolute-positioning":"Position zones","ceiling-shot":"Ceiling shot labels","fifty-fifty":"50/50 labels",dodge:"Dodge impulse arrows",ball_half:"Half control","relative-positioning":"Player roles","speed-flip":"Speed flip labels",touch:"Touch labels"};return e==="effects"?i[n.id]??n.label:t[`${n.id}:${e}`]??`${n.label} timeline`}function RW(n){return new CW(n)}var gn=Uint8Array,fi=Uint16Array,Jg=Int32Array,hf=new gn([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ff=new gn([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),C_=new gn([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a1=function(n,e){for(var t=new fi(31),i=0;i<31;++i)t[i]=e+=1<>1|(Ut&21845)<<1;Zs=(Zs&52428)>>2|(Zs&13107)<<2,Zs=(Zs&61680)>>4|(Zs&3855)<<4,R_[Ut]=((Zs&65280)>>8|(Zs&255)<<8)>>1}var hs=(function(n,e,t){for(var i=n.length,s=0,a=new fi(e);s>l]=c}else for(o=new fi(i),s=0;s>15-n[s]);return o}),ha=new gn(288);for(var Ut=0;Ut<144;++Ut)ha[Ut]=8;for(var Ut=144;Ut<256;++Ut)ha[Ut]=9;for(var Ut=256;Ut<280;++Ut)ha[Ut]=7;for(var Ut=280;Ut<288;++Ut)ha[Ut]=8;var ic=new gn(32);for(var Ut=0;Ut<32;++Ut)ic[Ut]=5;var IW=hs(ha,9,0),LW=hs(ha,9,1),kW=hs(ic,5,0),DW=hs(ic,5,1),pm=function(n){for(var e=n[0],t=1;te&&(e=n[t]);return e},Ni=function(n,e,t){var i=e/8|0;return(n[i]|n[i+1]<<8)>>(e&7)&t},mm=function(n,e){var t=e/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},Qg=function(n){return(n+7)/8|0},pf=function(n,e,t){return(e==null||e<0)&&(e=0),(t==null||t>n.length)&&(t=n.length),new gn(n.subarray(e,t))},OW=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],os=function(n,e,t){var i=new Error(e||OW[n]);if(i.code=n,Error.captureStackTrace&&Error.captureStackTrace(i,os),!t)throw i;return i},FW=function(n,e,t,i){var s=n.length,a=0;if(!s||e.f&&!e.l)return t||new gn(0);var r=!t,o=r||e.i!=2,l=e.i;r&&(t=new gn(s*3));var c=function(xe){var Ae=t.length;if(xe>Ae){var L=new gn(Math.max(Ae*2,xe));L.set(t),t=L}},u=e.f||0,d=e.p||0,h=e.b||0,f=e.l,p=e.d,g=e.m,_=e.n,m=s*8;do{if(!f){u=Ni(n,d,1);var v=Ni(n,d+1,3);if(d+=3,v)if(v==1)f=LW,p=DW,g=9,_=5;else if(v==2){var x=Ni(n,d,31)+257,M=Ni(n,d+10,15)+4,C=x+Ni(n,d+5,31)+1;d+=14;for(var w=new gn(C),E=new gn(19),R=0;R>4;if(y<16)w[R++]=y;else{var F=0,W=0;for(y==16?(W=3+Ni(n,d,3),d+=2,F=w[R-1]):y==17?(W=3+Ni(n,d,7),d+=3):y==18&&(W=11+Ni(n,d,127),d+=7);W--;)w[R++]=F}}var H=w.subarray(0,x),ne=w.subarray(x);g=pm(H),_=pm(ne),f=hs(H,g,1),p=hs(ne,_,1)}else os(1);else{var y=Qg(d)+4,b=n[y-4]|n[y-3]<<8,T=y+b;if(T>s){l&&os(0);break}o&&c(h+b),t.set(n.subarray(y,T),h),e.b=h+=b,e.p=d=T*8,e.f=u;continue}if(d>m){l&&os(0);break}}o&&c(h+131072);for(var oe=(1<>4;if(d+=F&15,d>m){l&&os(0);break}if(F||os(2),ke<256)t[h++]=ke;else if(ke==256){Ie=d,f=null;break}else{var Xe=ke-254;if(ke>264){var R=ke-257,De=hf[R];Xe=Ni(n,d,(1<>4;Z||os(3),d+=Z&15;var ne=PW[ae];if(ae>3){var De=ff[ae];ne+=mm(n,d)&(1<m){l&&os(0);break}o&&c(h+131072);var Se=h+Xe;if(h>8},cl=function(n,e,t){t<<=e&7;var i=e/8|0;n[i]|=t,n[i+1]|=t>>8,n[i+2]|=t>>16},_m=function(n,e){for(var t=[],i=0;ih&&(h=a[i].s);var f=new fi(h+1),p=P_(t[u-1],f,0);if(p>e){var i=0,g=0,_=p-e,m=1<<_;for(a.sort(function(x,M){return f[M.s]-f[x.s]||x.f-M.f});ie)g+=m-(1<>=_;g>0;){var y=a[i].s;f[y]=0&&g;--i){var b=a[i].s;f[b]==e&&(--f[b],++g)}p=e}return{t:new gn(f),l:p}},P_=function(n,e,t){return n.s==-1?Math.max(P_(n.l,e,t+1),P_(n.r,e,t+1)):e[n.s]=t},Wx=function(n){for(var e=n.length;e&&!n[--e];);for(var t=new fi(++e),i=0,s=n[0],a=1,r=function(l){t[i++]=l},o=1;o<=e;++o)if(n[o]==s&&o!=e)++a;else{if(!s&&a>2){for(;a>138;a-=138)r(32754);a>2&&(r(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(r(s),--a;a>6;a-=6)r(8304);a>2&&(r(a-3<<5|8208),a=0)}for(;a--;)r(s);a=1,s=n[o]}return{c:t.subarray(0,i),n:e}},ul=function(n,e){for(var t=0,i=0;i>8,n[s+2]=n[s]^255,n[s+3]=n[s+1]^255;for(var a=0;a4&&!E[C_[k-1]];--k);var O=c+5<<3,D=ul(s,ha)+ul(a,ic)+r,U=ul(s,h)+ul(a,g)+r+14+3*k+ul(M,E)+2*M[16]+3*M[17]+7*M[18];if(l>=0&&O<=D&&O<=U)return c1(e,u,n.subarray(l,l+c));var F,W,H,ne;if(Es(e,u,1+(U15&&(Es(e,u,ke[C]>>5&127),u+=ke[C]>>12)}}else F=IW,W=ha,H=kW,ne=ic;for(var C=0;C255){var Xe=De>>18&31;cl(e,u,F[Xe+257]),u+=W[Xe+257],Xe>7&&(Es(e,u,De>>23&31),u+=hf[Xe]);var Z=De&31;cl(e,u,H[Z]),u+=ne[Z],Z>3&&(cl(e,u,De>>5&8191),u+=ff[Z])}else cl(e,u,F[De]),u+=W[De]}return cl(e,u,F[256]),u+W[256]},NW=new Jg([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),u1=new gn(0),UW=function(n,e,t,i,s,a){var r=a.z||n.length,o=new gn(i+r+5*(1+Math.ceil(r/7e3))+s),l=o.subarray(i,o.length-s),c=a.l,u=(a.r||0)&7;if(e){u&&(l[0]=a.r>>3);for(var d=NW[e-1],h=d>>13,f=d&8191,p=(1<7e3||E>24576)&&(F>423||!c)){u=Xx(n,l,0,b,T,x,C,E,k,w-k,u),E=M=C=0,k=w;for(var W=0;W<286;++W)T[W]=0;for(var W=0;W<30;++W)x[W]=0}var H=2,ne=0,oe=f,pe=D-U&32767;if(F>2&&O==y(w-pe))for(var Ie=Math.min(h,F)-1,ke=Math.min(32767,w),Xe=Math.min(258,F);pe<=ke&&--oe&&D!=U;){if(n[w+H]==n[w+H-pe]){for(var De=0;DeH){if(H=De,ne=pe,De>Ie)break;for(var Z=Math.min(pe,De-2),ae=0,W=0;Wae&&(ae=ie,U=Se)}}}D=U,U=g[D],pe+=D-U&32767}if(ne){b[E++]=268435456|A_[H]<<18|$x[ne];var xe=A_[H]&31,Ae=$x[ne]&31;C+=hf[xe]+ff[Ae],++T[257+xe],++x[Ae],R=w+H,++M}else b[E++]=n[w],++T[n[w]]}}for(w=Math.max(w,R);w=r&&(l[u/8|0]=c,L=r),u=c1(l,u+1,n.subarray(w,L))}a.i=r}return pf(o,0,i+Qg(u)+s)},BW=function(n,e,t,i,s){if(!s&&(s={l:1},e.dictionary)){var a=e.dictionary.subarray(-32768),r=new gn(a.length+n.length);r.set(a),r.set(n,a.length),n=r,s.w=a.length}return UW(n,e.level==null?6:e.level,e.mem==null?s.l?Math.ceil(Math.max(8,Math.min(13,Math.log(n.length)))*1.5):20:12+e.mem,t,i,s)};function zW(n,e){return BW(n,e||{},0,0)}function d1(n,e){return FW(n,{i:2},e,e)}var Kx=typeof TextEncoder<"u"&&new TextEncoder,I_=typeof TextDecoder<"u"&&new TextDecoder,HW=0;try{I_.decode(u1,{stream:!0}),HW=1}catch{}var VW=function(n){for(var e="",t=0;;){var i=n[t++],s=(i>127)+(i>223)+(i>239);if(t+s>n.length)return{s:e,r:pf(n,t-1)};s?s==3?(i=((i&15)<<18|(n[t++]&63)<<12|(n[t++]&63)<<6|n[t++]&63)-65536,e+=String.fromCharCode(55296|i>>10,56320|i&1023)):s&1?e+=String.fromCharCode((i&31)<<6|n[t++]&63):e+=String.fromCharCode((i&15)<<12|(n[t++]&63)<<6|n[t++]&63):e+=String.fromCharCode(i)}};function GW(n,e){var t;if(Kx)return Kx.encode(n);for(var i=n.length,s=new gn(n.length+(n.length>>1)),a=0,r=function(c){s[a++]=c},t=0;ts.length){var o=new gn(a+8+(i-t<<1));o.set(s),s=o}var l=n.charCodeAt(t);l<128||e?r(l):l<2048?(r(192|l>>6),r(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|n.charCodeAt(++t)&1023,r(240|l>>18),r(128|l>>12&63),r(128|l>>6&63),r(128|l&63)):(r(224|l>>12),r(128|l>>6&63),r(128|l&63))}return pf(s,0,a)}function h1(n,e){var t;if(I_)return I_.decode(n);var i=VW(n),s=i.s,t=i.r;return t.length&&os(8),s}const L_=1,k_="cfg",qx="cfgDebug";function $W(n){let e="";for(const t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function WW(n){const e=n.replaceAll("-","+").replaceAll("_","/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=atob(t),s=new Uint8Array(i.length);for(let a=0;a!Ri(e)||!o8(e.id)?null:{id:e.id,placement:p1(e.placement)}).filter(e=>e!==null):[]}function a8(n){return Array.isArray(n)?n.map(e=>!Ri(e)||typeof e.id!="string"||!l8(e.kind)?null:{id:e.id,kind:e.kind,placement:p1(e.placement),playerId:m1(e.playerId)??null,team:e.team==="orange"?"orange":e.team==="blue"?"blue":null,entries:r8(e.entries)}).filter(e=>e!==null):[]}function r8(n){return Array.isArray(n)?n.map(e=>!Ri(e)||typeof e.statId!="string"?null:{statId:e.statId,targetId:typeof e.targetId=="string"?e.targetId:void 0}).filter(e=>e!==null):[]}function p1(n){const e=Ri(n)?n:{},t=Ri(e.viewport)?e.viewport:{};return{x:Rn(e.x)??8,y:Rn(e.y)??8,viewport:{width:uh(t.width)??1,height:uh(t.height)??1},zIndex:Rn(e.zIndex),visible:Zn(e.visible)??!0}}function o8(n){return n==="camera"||n==="scoreboard"||n==="playback"||n==="recording"||n==="training-pack"||n==="mechanics"||n==="event-playlist"||n==="mechanics-review"||n==="replay-loading"||n==="boost-pickups"||n==="touch-controls"||n==="touch-legend"||n==="shot-visualization"||n==="missed-events"}function l8(n){return n==="player"||n==="team"||n==="all-players"||n==="all-teams"||n==="kickoff-overview"||n==="goals-overview"||n==="ad-hoc"}function Ri(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Rn(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function uh(n){const e=Rn(n);return e!==void 0&&e>0?e:void 0}function Zn(n){return typeof n=="boolean"?n:void 0}function m1(n){return n===null?null:typeof n=="string"?n:void 0}function dl(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"):[]}function Yx(n,e,t){return Math.min(t,Math.max(e,n))}const c8=["camera","scoreboard","playback","recording","training-pack","mechanics","event-playlist","mechanics-review","replay-loading","boost-pickups","touch-controls","touch-legend","shot-visualization","missed-events"];class u8{constructor(e){this.options=e}nextZIndex=30;reset(){this.nextZIndex=30}bringToFront(e){e.style.zIndex=`${this.nextZIndex++}`}show(e){const t=this.mustWindow(e);t.hidden=!1,this.bringToFront(t),this.options.requestConfigSync()}toggle(e){const t=this.mustWindow(e);t.hidden=!t.hidden,t.hidden||this.bringToFront(t),this.options.requestConfigSync()}hide(e){const t=this.mustWindow(e);t.hidden=!0,this.options.requestConfigSync()}readPlacement(e){const t=Number.parseInt(e.style.zIndex,10);return{x:this.readCoordinate(e,"--window-x"),y:this.readCoordinate(e,"--window-y"),viewport:jx(),zIndex:Number.isFinite(t)?t:void 0,visible:!e.hidden}}applyPlacement(e,t){const i=ZW(t,jx());e.style.setProperty("--window-x",`${i.x}px`),e.style.setProperty("--window-y",`${i.y}px`),e.hidden=!t.visible,t.zIndex!==void 0&&(e.style.zIndex=`${t.zIndex}`,this.nextZIndex=Math.max(this.nextZIndex,t.zIndex+1))}getSingletonConfigs(){const e=[],t=this.options.getRoot();for(const i of c8){const s=t.querySelector(`[data-window-id="${i}"]`);s&&e.push({id:i,placement:this.readPlacement(s)})}return e}applySingletonConfigs(e){const t=this.options.getRoot();for(const i of e){const s=t.querySelector(`[data-window-id="${i.id}"]`);s&&this.applyPlacement(s,i.placement)}}installDragging(e,t){e.addEventListener("pointerdown",i=>{if(!(i.target instanceof HTMLElement)||d8(i.target))return;const s=i.target.closest("[data-window-id]");if(!s||s.hidden)return;this.bringToFront(s);const a=i.clientX,r=i.clientY,o=s.getBoundingClientRect(),l=i.pointerId;s.setPointerCapture(l),i.preventDefault();const c=d=>{const h=Math.max(8,Math.min(window.innerWidth-120,o.left+d.clientX-a)),f=Math.max(8,Math.min(window.innerHeight-100,o.top+d.clientY-r));s.style.setProperty("--window-x",`${h}px`),s.style.setProperty("--window-y",`${f}px`)},u=()=>{s.releasePointerCapture(l),s.removeEventListener("pointermove",c),s.removeEventListener("pointerup",u),s.removeEventListener("pointercancel",u),this.options.requestConfigSync()};s.addEventListener("pointermove",c),s.addEventListener("pointerup",u),s.addEventListener("pointercancel",u)},{signal:t})}mustWindow(e){const t=this.options.getRoot().querySelector(`[data-window-id="${e}"]`);if(!t)throw new Error(`Missing window for id: ${e}`);return t}readCoordinate(e,t){const i=e.style.getPropertyValue(t).trim(),s=getComputedStyle(e).getPropertyValue(t).trim(),a=i||s,r=Number.parseFloat(a);if(Number.isFinite(r))return r;const o=e.getBoundingClientRect();return t==="--window-y"?o.top:o.left}}function jx(){return{width:Math.max(1,window.innerWidth),height:Math.max(1,window.innerHeight)}}function d8(n){return n instanceof Element&&!!n.closest("button, input, select, textarea, option, label, a, [data-no-drag]")}function h8(n){return new u8(n)}class f8{constructor(e){this.options=e}activeSourceIds=null;autoFollow=!0;lastActiveKey=null;activeItem=null;renderedItems=[];reset(){this.activeSourceIds=null,this.lastActiveKey=null,this.activeItem=null,this.renderedItems=[]}render(){this.options.body.replaceChildren(),this.lastActiveKey=null,this.activeItem=null,this.renderedItems=[];const e=this.options.getSources();if(e.length===0){const _=document.createElement("p");_.className="stat-window-empty",_.textContent=this.options.getReplayPlayer()?"No events loaded.":"Load a replay to see events.",this.options.body.append(_);return}const t=E_(e,this.activeSourceIds),i=wW({sources:e,activeSourceIds:this.activeSourceIds,replayPlayers:this.options.getReplayPlayer()?.replay.players??[]}),s=document.createElement("div");s.className="event-playlist-toolbar";const a=document.createElement("details");a.className="event-playlist-filter",a.dataset.noDrag="true";const r=document.createElement("summary");r.textContent=`Filters ${t.size}/${e.length}`,a.append(r);const o=document.createElement("div");o.className="event-playlist-filter-panel";const l=document.createElement("div");l.className="event-playlist-filter-actions";const c=document.createElement("button");c.type="button",c.textContent="All",c.addEventListener("click",()=>{this.activeSourceIds=new Set(e.map(m=>m.id)),this.lastActiveKey=null,this.render();const _=this.options.getReplayPlayer()?.getState();_&&this.syncTimeline(_)});const u=document.createElement("button");u.type="button",u.textContent="None",u.addEventListener("click",()=>{this.activeSourceIds=new Set,this.lastActiveKey=null,this.render()}),l.append(c,u),o.append(l);const d=new Map;for(const _ of e){const m=d.get(_.group)??[];m.push(_),d.set(_.group,m)}for(const[_,m]of d){const v=document.createElement("section");v.className="event-playlist-filter-group";const y=document.createElement("h3");y.textContent=_,v.append(y);for(const b of m){const T=document.createElement("label");T.className="toggle event-playlist-filter-option";const x=document.createElement("input");x.type="checkbox",x.checked=t.has(b.id),x.addEventListener("change",()=>{this.setSourceSelection(e,C=>{x.checked?C.add(b.id):C.delete(b.id)})});const M=document.createElement("span");M.textContent=`${b.label} (${b.events.length})`,T.append(x,M),v.append(T)}o.append(v)}a.append(o);const h=document.createElement("label");h.className="toggle event-playlist-follow";const f=document.createElement("input");f.type="checkbox",f.checked=this.autoFollow,f.addEventListener("change",()=>{this.autoFollow=f.checked;const _=this.options.getReplayPlayer()?.getState();_&&this.syncTimeline(_,{forceScroll:!0})});const p=document.createElement("span");p.textContent="Auto-follow",h.append(f,p),s.append(a,h);const g=document.createElement("div");if(g.className="event-playlist-list",g.dataset.noDrag="true",i.length===0){const _=document.createElement("p");_.className="stat-window-empty",t.size===0?_.textContent="No event types selected.":_.textContent="No events in selected event types.",g.append(_)}else for(const _ of i){const m=document.createElement("button");m.type="button",m.className="event-playlist-item",m.dataset.eventKey=_.key,m.dataset.eventTime=`${_.event.time}`,m.style.setProperty("--event-color",_.color),Number.isFinite(_.event.time)&&this.renderedItems.push({key:_.key,time:_.event.time,element:m}),m.addEventListener("click",()=>{this.options.cueTimelineEvent(_.event)});const v=document.createElement("span");v.className="event-playlist-time",v.textContent=this.options.formatTime(_.event.time);const y=document.createElement("span");y.className="event-playlist-main";const b=document.createElement("strong");b.textContent=_.event.label??_.sourceLabel;const T=document.createElement("span");T.textContent=[_.event.playerName??null,_.event.frame!==void 0?`frame ${_.event.frame}`:null,_.sourceLabel].filter(x=>!!x).join(" · "),y.append(b,T),m.append(v,y),g.append(m)}this.options.body.append(s,g)}syncTimeline(e,t={}){if(!this.options.body.querySelector(".event-playlist-list"))return;const s=this.getActiveItem(e.currentTime),a=s?.dataset.eventKey??null;a===this.lastActiveKey&&!t.forceScroll||(this.activeItem?.isConnected?this.activeItem.dataset.active="false":this.activeItem&&(this.activeItem=null),s?(s.dataset.active="true",this.activeItem=s,(this.autoFollow||t.forceScroll)&&s.scrollIntoView({block:"nearest"})):this.activeItem=null,this.lastActiveKey=a)}setSourceSelection(e,t){const i=E_(e,this.activeSourceIds);t(i),this.activeSourceIds=i,this.lastActiveKey=null,this.render();const s=this.options.getReplayPlayer()?.getState();s&&this.syncTimeline(s)}getActiveItem(e){const t=this.renderedItems;if(t.length===0)return null;let i=0,s=t.length-1;for(;ie.getConfig||e.applyConfig).map(e=>{const t={id:e.id};return e.id==="boost"&&(t.aliases=["boost-pickup-animation"]),e.getConfig&&(t.getConfig=()=>e.getConfig?.()),e.applyConfig&&(t.applyConfig=i=>e.applyConfig?.(i)),t})}function T8(n){return y8(g1(n))}function M8({replayPlayer:n,playbackRate:e,skipPostGoalTransitions:t,skipKickoffs:i}){const s=n?.getState();return{currentTime:s?.currentTime,playing:s?.playing,rate:s?.speed??mf(Number(e?.value??1)),skipPostGoalTransitions:n?s?.skipPostGoalTransitionsEnabled:t.checked,skipKickoffs:n?s?.skipKickoffsEnabled:i.checked}}function E8({replayPlayer:n,cameraControlsController:e}){const t=n?.getState(),i=t?pE(t):e?.ballCamMode;return{mode:t?.cameraViewMode,freePreset:e?.freeCameraPreset??null,attachedPlayerId:t?.attachedPlayerId,ballCam:i===void 0?void 0:i==="on",useReplayBallCam:i===void 0?void 0:i==="player",usePlayerCameraSettings:t?.customCameraSettings===null,autoPossession:e?.autoPossessionEnabled,customSettings:t?.customCameraSettings,nameplateLiftUu:e?.nameplateLiftUu}}function C8({playback:n,camera:e,activeTimelineEventSourceIds:t,activeTimelineRangeModuleIds:i,activeMechanicTimelineKinds:s,activeRenderEffectModuleIds:a,initialConfig:r,replayPlayer:o,boostPadOverlayEnabled:l,recording:c,singletonWindows:u,statsWindows:d,moduleConfigs:h}){return{version:L_,playback:n,camera:e,overlays:{timelineEvents:[...t],timelineRanges:[...i],mechanics:[...s],renderEffects:[...a],...r?.overlays.pluginRenderEffects!==void 0?{pluginRenderEffects:[...r.overlays.pluginRenderEffects]}:{},...r?.overlays.pluginHudOverlay!==void 0?{pluginHudOverlay:r.overlays.pluginHudOverlay}:{},followedPlayerHud:!1,boostPads:l,boostPickupAnimation:o?.getState().boostPickupAnimationEnabled??!1,hitboxWireframes:o?.getState().hitboxWireframesEnabled??!1,hitboxOnlyMode:o?.getState().hitboxOnlyModeEnabled??!1},recording:c,singletonWindows:u,statsWindows:d,moduleConfigs:h}}function A8(n,e,t){return{currentTime:n.currentTime,playing:n.playing,speed:n.rate,customCameraSettings:_1(e),cameraViewMode:e.mode,attachedPlayerId:e.attachedPlayerId,...jb(e)==="player"?{useReplayBallCam:!0}:{ballCamEnabled:jb(e)==="on"},boostPickupAnimationEnabled:t.overlays.boostPickupAnimation,hitboxWireframesEnabled:t.overlays.hitboxWireframes,hitboxOnlyModeEnabled:t.overlays.hitboxOnlyMode,skipPostGoalTransitionsEnabled:n.skipPostGoalTransitions,skipKickoffsEnabled:n.skipKickoffs}}function R8(n,e,t){console.groupCollapsed("[subtr-actor] stats player cfg load"),console.log("location.href",window.location.href),console.log("location.search",n.search||"(empty)"),console.log("location.hash",n.hash||"(empty)"),console.table([...n.searchParams.map(([i,s])=>({source:"search",name:i,value:s})),...n.hashParams.map(([i,s])=>({source:"hash",name:i,value:s}))]),console.log("cfg selected source",n.selectedSource??"(none)"),console.log("cfg selected raw text",n.selectedValue??"(none)"),console.log("cfg selected raw length",n.selectedValue?.length??0),console.log("cfg search values",n.searchValues),console.log("cfg hash values",n.hashValues),n.hashValues.length>0&&n.searchValues.length>0&&console.warn("Both hash and search contain cfg; hash cfg is used."),e&&(console.log("cfg normalized JSON",JSON.stringify(e,null,2)),console.log("cfg normalized object",e)),t&&console.error("cfg decode/apply error",t),console.groupEnd()}function Zx(n,e){const{style:t}=n.renderer.domElement;t.visibility=e?"hidden":"",t.pointerEvents=e?"none":""}function Jx(n,e={}){const t=e.destroyPlayer??!0,i=e.clearPlayerPluginHandles??!0,s=n.getUnsubscribe();s&&(s(),n.setUnsubscribe(null)),n.teardownActiveModules(),t&&(n.getReplayPlayer()?.destroy(),n.setReplayPlayer(null)),i&&(n.setCanvasRecorder(null),n.setTimelineOverlay(null)),n.setLoadedReplayName(null),n.setStatsTimeline(null),n.setStatsFrameLookup(null),n.setStatRegistry(nc()),n.clearTimelineEventSources(),n.clearTimelineRangeSources(),n.clearStandalonePlugins(),n.clearRenderCaches(),n.resetEventPlaylistWindow(),n.renderModuleSummary(),n.renderScoreboard(),n.renderTimelineEventCount(),n.renderMechanicsTimelineControls(),n.renderEventPlaylistWindow(),n.renderModuleSettings(),n.syncRecordingWindow()}async function P8(n,e,t){const{elements:i}=t;let s=null;i.statusReadout.textContent=n.preparingStatus,i.fileInput.disabled=!0,t.getReplayLoadModal()?.show(n.name,n.preparingStatus),t.setTransportEnabled(!1),t.getCameraControlsController()?.syncAvailability(),i.emptyState.hidden=t.getReplayPlayer()!==null,t.getReplayPlayer()?.pause();try{i.statusReadout.textContent="Parsing replay...",t.getReplayLoadModal()?.show(n.name,"Parsing replay...");const a=await e,{replay:r}=a,o=t.getReplayPlayer();if(o){Jx(t,{destroyPlayer:!1,clearPlayerPluginHandles:!1});const h=new Rw(a.raw);await o.replaceReplay(h,r,{preservePlayback:!1}),t.setStatsTimeline(a.statsTimeline),t.setStatsFrameLookup(a.statsFrameLookup),t.setStatRegistry(nc(null)),t.setReplayPlayer(o),t.syncBoostPadOverlayPlugin(),t.setupActiveModules(),t.setUnsubscribe(o.subscribe(t.renderSnapshot));const f=t.getInitialConfig();if(f){t.setApplyingConfig(!0);try{t.applyConfigToReplayPlayer(f)}finally{t.setApplyingConfig(!1)}}t.getCameraControlsController()?.populateAttachedPlayerOptions(r.players),i.emptyState.hidden=!0,i.statusReadout.textContent=`Loaded ${n.name}`,t.setLoadedReplayName(n.name),i.playersReadout.textContent=r.players.map(p=>p.name).join(", "),i.framesReadout.textContent=`${r.frameCount}`,t.renderModuleSummary(),t.renderTimelineEventCount(),t.renderMechanicsTimelineControls(),t.resetEventPlaylistWindow(),t.renderEventPlaylistWindow(),t.setTransportEnabled(!0),t.getCameraControlsController()?.syncAvailability(o.getState()),t.renderSnapshot(o.getState()),t.renderStatsWindows(o.getState().frameIndex),t.renderScoreboard(o.getState().frameIndex),t.syncEventPlaylistTimeline(o.getState(),{forceScroll:!0}),t.renderModuleSettings(),t.syncRecordingWindow(),t.getReplayLoadModal()?.hide();return}const l=u3({replayEventsLabel:"Replay",replayEvents:h=>t.withTimelineEventSeekTimes(t.getReplayTimelineEvents(h.replay))}),c=WN({onStatusChange:t.syncRecordingWindow});t.setCanvasRecorder(c);const u=t.getInitialConfig(),d=d3(i.viewport,a,{initialPlaybackRate:u?.playback.rate,initialCustomCameraSettings:_1(u?.camera),initialAttachedPlayerId:u?.camera.attachedPlayerId??null,initialCameraViewMode:u?.camera.mode,initialBoostPickupAnimationEnabled:u?.overlays.boostPickupAnimation??!1,initialHitboxWireframesEnabled:u?.overlays.hitboxWireframes??i.hitboxWireframes.checked,initialHitboxOnlyModeEnabled:u?.overlays.hitboxOnlyMode??i.hitboxOnlyMode.checked,initialSkipPostGoalTransitionsEnabled:i.skipPostGoalTransitions.checked,initialSkipKickoffsEnabled:i.skipKickoffs.checked,plugins:[bN({onSample:({renderFps:h,replayFps:f})=>{const p=document.getElementById("render-fps-readout"),g=document.getElementById("replay-fps-readout");p&&(p.textContent=`${h.toFixed(0)} fps`),g&&(g.textContent=`${f.toFixed(0)} fps`)}}),Tu(x3({floatingLiftUu:()=>t.getCameraControlsController()?.nameplateLiftUu})),Tu(zN({includePickup:t.includeBoostPickupAnimationPickup})),Tu(c),Tu(l)]});if(s=d,Zx(d,!0),await d.ready,Jx(t),s=null,Zx(d,!1),t.setStatsTimeline(a.statsTimeline),t.setStatsFrameLookup(a.statsFrameLookup),t.setStatRegistry(nc(null)),t.setTimelineOverlay(l),t.setReplayPlayer(d),t.syncBoostPadOverlayPlugin(),t.setupActiveModules(),t.setUnsubscribe(d.subscribe(t.renderSnapshot)),u){t.setApplyingConfig(!0);try{t.applyConfigToReplayPlayer(u)}finally{t.setApplyingConfig(!1)}}t.getCameraControlsController()?.populateAttachedPlayerOptions(r.players),i.emptyState.hidden=!0,i.statusReadout.textContent=`Loaded ${n.name}`,t.setLoadedReplayName(n.name),i.playersReadout.textContent=r.players.map(h=>h.name).join(", "),i.framesReadout.textContent=`${r.frameCount}`,t.renderModuleSummary(),t.renderTimelineEventCount(),t.renderMechanicsTimelineControls(),t.resetEventPlaylistWindow(),t.renderEventPlaylistWindow(),t.setTransportEnabled(!0),t.getCameraControlsController()?.syncAvailability(d.getState()),t.renderSnapshot(d.getState()),t.renderStatsWindows(d.getState().frameIndex),t.renderScoreboard(d.getState().frameIndex),t.syncEventPlaylistTimeline(d.getState(),{forceScroll:!0}),t.renderModuleSettings(),t.syncRecordingWindow(),t.getReplayLoadModal()?.hide()}catch(a){throw t.getReplayLoadModal()?.hide(),s?.destroy(),t.getReplayPlayer()||(i.emptyState.hidden=!1,t.setCanvasRecorder(null)),t.syncRecordingWindow(),a}finally{i.fileInput.disabled=!1}}function I8(n){if(n<=0)return"--";const e=["B","KB","MB","GB"];let t=n,i=0;for(;t>=1024&&i=10?1:2;return`${t.toFixed(s)} ${e[i]}`}function L8(n){if(!n)return"No replay";if(n.error)return n.error;switch(n.state){case"idle":return"Idle";case"recording":return"Recording";case"stopping":return"Stopping";case"ready":return"Ready";case"error":return"Error"}}function k8({fpsValue:n,playbackRateValue:e}){const t=Number(n),i=Number(e);return{fps:Number.isFinite(t)?Math.max(1,Math.min(120,Math.trunc(t))):60,playbackRate:Number.isFinite(i)?Math.max(.1,i):1}}function D8(n,e=new Date){const i=(n?.replace(/\.replay$/i,"")||"replay").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,""),s=e.toISOString().replace(/[:.]/g,"-");return`${i||"replay"}-${s}.webm`}function O8(n,e){const t=URL.createObjectURL(n),i=document.createElement("a");i.href=t,i.download=e,document.body.append(i),i.click(),i.remove(),window.setTimeout(()=>URL.revokeObjectURL(t),0)}class F8{constructor(e){this.options=e}getConfigSnapshot(){const{elements:e}=this.options;return{fps:Number(e.fps.value),playbackRate:Number(e.playbackRate.value)}}applyConfig(e){const{elements:t}=this.options;e.fps!==void 0&&(t.fps.value=`${e.fps}`),e.playbackRate!==void 0&&(t.playbackRate.value=`${e.playbackRate}`)}sync(e=this.options.getCanvasRecorder()?.getStatus()??null){const{elements:t}=this.options,i=this.options.getCanvasRecorder()!==null&&this.options.getReplayPlayer()!==null,s=e?.state??"idle",a=s==="recording"||s==="stopping",r=(this.options.getCanvasRecorder()?.getRecording()??null)!==null;t.status.textContent=L8(e),t.elapsed.textContent=`${(e?.elapsedSeconds??0).toFixed(1)}s`,t.size.textContent=I8(e?.sizeBytes??0),t.type.textContent=e?.mimeType||"WebM",t.start.disabled=!i||a,t.fullReplay.disabled=!i||a,t.stop.disabled=!i||!a,t.download.disabled=!r||a,t.clear.disabled=!r||a,t.fps.disabled=a,t.playbackRate.disabled=a}installEventListeners(e){const{elements:t}=this.options;t.start.addEventListener("click",()=>{const i=this.options.getCanvasRecorder();if(i)try{const{fps:s}=this.getRecordingOptions();i.start({fps:s}),this.sync()}catch(s){console.error("Failed to start recording:",s),this.options.setStatus(s instanceof Error?s.message:"Failed to start recording"),this.sync(i.getStatus())}},{signal:e}),t.fullReplay.addEventListener("click",()=>{const i=this.options.getCanvasRecorder();if(!i)return;const{fps:s,playbackRate:a}=this.getRecordingOptions();i.recordFullReplay({fps:s,playbackRate:a,restorePlaybackState:!0}).catch(r=>{console.error("Failed to record replay:",r),this.options.setStatus(r instanceof Error?r.message:"Failed to record replay"),this.sync(this.options.getCanvasRecorder()?.getStatus()??null)}),this.sync()},{signal:e}),t.stop.addEventListener("click",()=>{this.options.getCanvasRecorder()?.stop().catch(i=>{console.error("Failed to stop recording:",i),this.options.setStatus(i instanceof Error?i.message:"Failed to stop recording")}),this.sync()},{signal:e}),t.download.addEventListener("click",()=>{const i=this.options.getCanvasRecorder()?.getRecording();i&&O8(i,D8(this.options.getLoadedReplayName()))},{signal:e}),t.clear.addEventListener("click",()=>{try{this.options.getCanvasRecorder()?.clear(),this.sync()}catch(i){console.error("Failed to clear recording:",i)}},{signal:e}),t.fps.addEventListener("change",this.options.requestConfigSync,{signal:e}),t.playbackRate.addEventListener("change",this.options.requestConfigSync,{signal:e})}getRecordingOptions(){const{elements:e}=this.options;return k8({fpsValue:e.fps.value,playbackRateValue:e.playbackRate.value})}}function N8(n){return new F8(n)}class U8{constructor(e){this.options=e}render(e=this.options.getReplayPlayer()?.getState().frameIndex??0){const{body:t}=this.options;t.replaceChildren();const i=this.options.getStatsFrameLookup(),s=i?zt(i,e):null,a=this.options.getReplayPlayer()?.replay??null;if(!s||!a){const o=document.createElement("p");o.className="scoreboard-empty",o.textContent="Load a replay to show the scoreboard.",t.append(o);return}const r=document.createElement("div");r.className="scoreboard-scoreline",r.append(Qx(s.team_zero?.core.goals,!0),z8(),Qx(s.team_one?.core.goals,!1)),t.append(r)}}function B8(n){return typeof n=="number"&&Number.isFinite(n)?`${Math.round(n)}`:"--"}function z8(){const n=document.createElement("span");return n.className="scoreboard-divider",n.textContent="-",n}function Qx(n,e){const t=document.createElement("strong");return t.className=`scoreboard-goal-value ${na(e)}`,t.textContent=B8(n),t}function H8(n){return new U8(n)}class V8{constructor(e){this.options=e}setTransportEnabled(e,t){const{elements:i}=this.options;i.togglePlayback.disabled=!e,i.previousFrame.disabled=!e,i.nextFrame.disabled=!e,i.playbackRate.disabled=!e,i.skipPostGoalTransitions.disabled=!e,i.skipKickoffs.disabled=!e,i.hitboxWireframes.disabled=!e,i.hitboxOnlyMode.disabled=!e,this.options.getCameraControlsController()?.setTransportEnabled(e,t)}renderSnapshot(e){const{elements:t}=this.options;t.timeReadout.textContent=`${e.currentTime.toFixed(2)}s`,t.frameReadout.textContent=`${e.frameIndex}`,t.durationReadout.textContent=`${e.duration.toFixed(2)}s`,t.playbackStatusReadout.textContent=e.playing?"Playing":"Paused",t.togglePlayback.textContent=e.playing?"Pause":"Play";const i=Math.max(0,this.options.getFrameCount()-1);t.previousFrame.disabled=e.frameIndex<=0,t.nextFrame.disabled=e.frameIndex>=i;const s=mf(e.speed);t.playbackRate.value=`${s}`,t.playbackRateReadout.textContent=ty(s),this.options.getCameraControlsController()?.syncState(e),t.skipPostGoalTransitions.checked=e.skipPostGoalTransitionsEnabled,t.skipKickoffs.checked=e.skipKickoffsEnabled,t.hitboxWireframes.checked=e.hitboxWireframesEnabled,t.hitboxOnlyMode.checked=e.hitboxOnlyModeEnabled,t.emptyState.hidden=!0}}function G8(n){return new V8(n)}function $8({elements:n,signal:e,setLauncherOpen:t,openReplayFilePicker:i,getElementWindowId:s,toggleWindow:a,hideWindow:r,createStatsWindow:o,loadReplayFile:l,togglePlayback:c,stepFrames:u,setPlaybackRate:d,setSkipPostGoalTransitionsEnabled:h,setSkipKickoffsEnabled:f,setHitboxWireframesEnabled:p,setHitboxOnlyModeEnabled:g}){n.launcherToggle.addEventListener("click",()=>{t(n.launcherMenu.hidden)},{signal:e}),n.root.addEventListener("click",m=>{m.target instanceof Element&&(m.target.closest(".top-chrome")||t(!1))},{signal:e}),n.loadReplayAction.addEventListener("click",i,{signal:e}),n.emptyLoadReplay.addEventListener("click",i,{signal:e}),n.root.querySelectorAll("[data-window-toggle]").forEach(m=>{m.addEventListener("click",()=>{const v=m.dataset.windowToggle;v&&(a(v),t(!1))},{signal:e})}),n.root.querySelectorAll("[data-window-hide]").forEach(m=>{m.addEventListener("click",()=>{const v=m.dataset.windowHide??s(m);v&&r(v)},{signal:e})}),n.root.querySelectorAll("[data-create-stats-window]").forEach(m=>{m.addEventListener("click",()=>{o(m.dataset.createStatsWindow)},{signal:e})}),n.fileInput.addEventListener("change",()=>{const m=n.fileInput.files?.[0];m&&l(m)},{signal:e}),n.togglePlayback.addEventListener("click",c,{signal:e}),n.previousFrame.addEventListener("click",()=>u(-1),{signal:e}),n.nextFrame.addEventListener("click",()=>u(1),{signal:e});const _=()=>{const m=mf(Number(n.playbackRate.value));n.playbackRate.value=`${m}`,n.playbackRateReadout.textContent=ty(m),d(m)};n.playbackRate.addEventListener("input",_,{signal:e}),n.playbackRate.addEventListener("change",_,{signal:e}),n.skipPostGoalTransitions.addEventListener("change",()=>{h(n.skipPostGoalTransitions.checked)},{signal:e}),n.skipKickoffs.addEventListener("change",()=>{f(n.skipKickoffs.checked)},{signal:e}),n.hitboxWireframes.addEventListener("change",()=>{p(n.hitboxWireframes.checked)},{signal:e}),n.hitboxOnlyMode.addEventListener("change",()=>{g(n.hitboxOnlyMode.checked)},{signal:e})}const W8=3500;function X8(){const n=document.activeElement;if(!(n instanceof HTMLElement))return!1;if(n.isContentEditable)return!0;const e=n.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"}function K8(n){const{getReplayPlayer:e,signal:t}=n,i={forward:!1,backward:!1,left:!1,right:!1,up:!1,down:!1},s=()=>{i.forward=!1,i.backward=!1,i.left=!1,i.right=!1,i.up=!1,i.down=!1},a=(g,_)=>{switch(g){case"KeyW":return i.forward=_,!0;case"KeyS":return i.backward=_,!0;case"KeyA":return i.left=_,!0;case"KeyD":return i.right=_,!0;case"Space":return i.up=_,!0;case"ShiftLeft":case"ShiftRight":return i.down=_,!0;default:return!1}},r=g=>{g.ctrlKey||g.metaKey||g.altKey||X8()||a(g.code,!0)&&g.preventDefault()},o=g=>{a(g.code,!1)};window.addEventListener("keydown",r,{signal:t}),window.addEventListener("keyup",o,{signal:t}),window.addEventListener("blur",s,{signal:t});const l=new S,c=new S,u=new S,d=new S(0,1,0);let h=null,f=0;const p=g=>{f=requestAnimationFrame(p);const _=h===null?0:Math.min(.1,(g-h)/1e3);h=g;const m=(i.forward?1:0)-(i.backward?1:0),v=(i.right?1:0)-(i.left?1:0),y=(i.up?1:0)-(i.down?1:0);if(_===0||m===0&&v===0&&y===0)return;const b=e();if(!b||b.getState().cameraViewMode!=="free")return;const T=b.camera,x=b.controls;T.getWorldDirection(l),c.set(1,0,0).applyQuaternion(T.quaternion),u.set(0,0,0).addScaledVector(l,m).addScaledVector(c,v).addScaledVector(d,y),u.lengthSq()!==0&&(u.normalize().multiplyScalar(W8*_),T.position.add(u),x.target.add(u))};f=requestAnimationFrame(p),t.addEventListener("abort",()=>{cancelAnimationFrame(f)})}function q8(n,e){const t=new URLSearchParams(n),s=(t.get("replayId")??t.get("replay-id")??e??"").trim();return s.length>0?s:null}function Y8(){const n=new URLSearchParams(window.location.search),e=n.get("reviewToken")??n.get("token")??window.localStorage.getItem("rocket_sense_access_token");return e?{Authorization:`Bearer ${e}`}:{}}function j8(n){if(!n.replayId)return null;const e={replay_id:n.replayId,reviewed_mechanic:n.mechanic,reviewed_event_frame:n.frame,reviewed_event_time:n.time,confidence:n.confidence,status:"confirmed"};return n.subjectKind&&n.subjectId&&(e.reviewed_subject_kind=n.subjectKind,e.reviewed_subject_id=n.subjectId),n.startFrame!==null&&(e.reviewed_start_frame=n.startFrame),n.endFrame!==null&&(e.reviewed_end_frame=n.endFrame),n.notes&&n.notes.trim()&&(e.notes=n.notes.trim()),Object.keys(n.context).length>0&&(e.context=n.context),e}function Z8(n,e){const t=n.getState(),i=Math.max(0,Math.round(t.frameIndex??0)),s=t.currentTime??0,a=t.attachedPlayerId??null,r=a?n.replay.players.find(o=>o.id===a)?.name??null:null;return{localId:e.localId,mechanic:e.mechanic,frame:i,time:s,subjectKind:a?"player":null,subjectId:a,playerName:r,startFrame:null,endFrame:null,notes:e.notes?.trim()?e.notes.trim():null,confidence:1,replayId:e.replayId,context:{capturedFrom:"stat-evaluation-player",attachedPlayerId:a,playerName:r,durationSeconds:n.replay.duration??null}}}async function J8(n,e="/api/v1/events/reviews"){const t=j8(n);if(!t)return{record:n,ok:!1,message:"No replay id — cannot upload (export JSON instead)."};try{const i=await fetch(e,{method:"POST",headers:{"content-type":"application/json",...Y8()},credentials:"same-origin",body:JSON.stringify(t)});if(!i.ok){let s=`${i.status}${i.statusText?` ${i.statusText}`:""}`;try{const a=await i.json();typeof a.error=="string"&&(s=a.error)}catch{}return{record:n,ok:!1,message:s}}return{record:n,ok:!0,message:"uploaded"}}catch(i){return{record:n,ok:!1,message:i instanceof Error?i.message:String(i)}}}const Q8=["flick","whiff","double_tap","ceiling_shot","wall_aerial","flip_reset","one_timer","speed_flip","half_flip","wavedash","demo"],e6="m";function t6(){const n=document.activeElement;if(!(n instanceof HTMLElement))return!1;if(n.isContentEditable)return!0;const e=n.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"}function n6(n,e){const t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),i=URL.createObjectURL(t),s=document.createElement("a");s.href=i,s.download=n,document.body.appendChild(s),s.click(),s.remove(),URL.revokeObjectURL(i)}class i6{constructor(e){this.options=e}records=[];localIdSeq=0;installEventListeners(e){const{elements:t}=this.options;for(const i of Q8){const s=document.createElement("option");s.value=i,s.textContent=i.replaceAll("_"," "),t.mechanic.appendChild(s)}t.capture.addEventListener("click",()=>this.capture(),{signal:e}),t.export.addEventListener("click",()=>this.exportJson(),{signal:e}),t.upload.addEventListener("click",()=>{this.uploadAll()},{signal:e}),t.clear.addEventListener("click",()=>{this.records.length=0,this.render(),this.setStatus("Cleared.")},{signal:e}),window.addEventListener("keydown",i=>{i.key.toLowerCase()!==e6||i.repeat||i.metaKey||i.ctrlKey||i.altKey||t6()||(i.preventDefault(),this.capture())},{signal:e}),this.render()}capture(){const e=this.options.getReplayPlayer();if(!e){this.setStatus("No replay loaded.");return}this.localIdSeq+=1;const t=Z8(e,{mechanic:this.options.elements.mechanic.value||"flick",replayId:this.resolveReplayId(),localId:`missed-${this.localIdSeq}`});this.records.push(t),this.options.showWindow(),this.render(),this.setStatus(`Captured ${t.mechanic} @ ${t.time.toFixed(2)}s`+(t.replayId?".":" (no replay id — export only)."))}exportJson(){if(this.records.length===0){this.setStatus("Nothing to export.");return}n6("missed-events.json",{capturedFrom:"stat-evaluation-player",replayId:this.resolveReplayId(),missedEvents:this.records}),this.setStatus(`Exported ${this.records.length}.`)}async uploadAll(){if(this.records.length===0){this.setStatus("Nothing to upload.");return}let e=0;const t=[];for(const i of[...this.records]){const s=await J8(i);if(s.ok){e+=1;const a=this.records.findIndex(r=>r.localId===i.localId);a>=0&&this.records.splice(a,1)}else t.push(`${i.mechanic}@${i.time.toFixed(1)}s: ${s.message}`)}this.render(),this.setStatus(t.length===0?`Uploaded ${e}.`:`Uploaded ${e}, ${t.length} failed — ${t[0]}`)}render(){const{list:e}=this.options.elements;e.replaceChildren();for(const t of this.records){const i=document.createElement("li"),s=t.playerName??t.subjectId??"no subject",a=document.createElement("span");a.className="missed-event-row",a.textContent=`${t.mechanic} @ ${t.time.toFixed(2)}s · f${t.frame} · ${s}`+(t.replayId?"":" · no replay id");const r=document.createElement("button");r.type="button",r.textContent="✕",r.title="Remove",r.addEventListener("click",()=>{const o=this.records.findIndex(l=>l.localId===t.localId);o>=0&&(this.records.splice(o,1),this.render())}),i.append(a,r),e.appendChild(i)}}setStatus(e){this.options.elements.status.textContent=e}resolveReplayId(){return q8(window.location.search,this.options.getReplayId?.()??null)}}function s6(n){return new i6(n)}class mo{constructor(e,t){this.file=e,this.sourceTimes=t}sourceTimes;dirty=!1;static async createNew(e){const t=await ta.create(H3(),e);return new mo(t,[])}static async loadFromBytes(e,t){const i=await ta.load(e,t);return new mo(i,new Array(i.roundCount).fill(null))}get shotCount(){return this.file.roundCount}get hasUnsavedShots(){return this.dirty}shots(){return this.file.rounds.map((e,t)=>({index:t,timeLimit:e.time_limit,sourceReplayTime:this.sourceTimes[t]??null}))}captureShot(e,t=null){const i=N3(this.file,e);return this.sourceTimes[i]=t,this.dirty=!0,i}removeShot(e){this.file.removeRound(e),this.sourceTimes.splice(e,1),this.dirty=!0}setShotTimeLimit(e,t){this.file.setRoundTimeLimit(e,t),this.dirty=!0}downloadFileName(){return z3(this.file.guid)}toBytes(e=Math.floor(Date.now()/1e3)){this.file.updateMetadata({updated_at:BigInt(e)});const t=this.file.toBytes();return this.dirty=!1,t}}function a6(n,e,t,i){const s=`Captured shot ${n} (${e} at ${t})`;return i===null?`${s}.`:`${s}; warning: ${i}.`}function r6(n,e){const t=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),i=new Blob([t],{type:"application/octet-stream"}),s=URL.createObjectURL(i),a=document.createElement("a");a.href=s,a.download=e,document.body.appendChild(a),a.click(),a.remove(),window.setTimeout(()=>URL.revokeObjectURL(s),0)}class o6{constructor(e){this.options=e}session=null;sessionPromise=null;installEventListeners(e){const{elements:t}=this.options;t.capture.addEventListener("click",()=>{this.captureShot()},{signal:e}),t.newPack.addEventListener("click",()=>{this.newPack()},{signal:e}),t.download.addEventListener("click",()=>{this.download()},{signal:e}),t.load.addEventListener("click",()=>t.loadInput.click(),{signal:e}),t.loadInput.addEventListener("change",()=>{const i=t.loadInput.files?.[0]??null;t.loadInput.value="",i&&this.loadPackFile(i)},{signal:e}),t.name.addEventListener("change",()=>this.session?.file.setName(t.name.value||null),{signal:e}),t.creator.addEventListener("change",()=>this.session?.file.setCreatorName(t.creator.value||null),{signal:e}),t.description.addEventListener("change",()=>this.session?.file.setDescription(t.description.value||null),{signal:e}),t.difficulty.addEventListener("change",()=>this.session?.file.setDifficulty(t.difficulty.value),{signal:e}),this.sync()}sync(){const{elements:e}=this.options,t=this.options.getReplayPlayer();e.capture.disabled=!t,e.shooter.disabled=!t,this.populateShooterOptions(t),this.renderShotList()}populateShooterOptions(e){const{shooter:t}=this.options.elements,i=t.value;t.replaceChildren(),t.append(new Option("Followed player (camera)",""));for(const s of e?.replay.players??[])t.append(new Option(s.name,s.id));[...t.options].some(s=>s.value===i)&&(t.value=i)}async ensureSession(){if(this.session)return this.session;this.sessionPromise??=mo.createNew();const e=await this.sessionPromise;return this.session||this.adoptSession(e),this.session??e}adoptSession(e){this.session=e,this.sessionPromise=null;const{elements:t}=this.options;t.name.value=e.file.name??"",t.creator.value=e.file.creatorName??"",t.description.value=e.file.description??"";const i=e.file.difficulty;[...t.difficulty.options].some(s=>s.value===i)&&(t.difficulty.value=i),this.renderShotList()}resolveShooter(e,t){const i=this.options.elements.shooter.value||null,s=e.getState().attachedPlayerId,a=e.replay.players,r=[...a.filter(o=>o.id===(i??s)),...a];for(const o of r){const l=o.frames[t];if(l?.position)return i&&o.id!==i?null:{track:o,sample:l}}return null}timeLimitSeconds(){const e=Number(this.options.elements.timeLimit.value);return!Number.isFinite(e)||e<0?$T:e}async captureShot(){const e=this.options.getReplayPlayer();if(!e){this.setStatus("No replay loaded.");return}const t=e.getState(),i=e.replay.ballFrames[t.frameIndex];if(!i?.position){this.setStatus("No ball state on the current frame.");return}const s=this.resolveShooter(e,t.frameIndex);if(!s){this.setStatus("Selected shooter has no car state on the current frame.");return}const a=await this.ensureSession(),r={position:s.sample.position,rotation:s.sample.rotation,linearVelocity:s.sample.linearVelocity},o=a.captureShot({ball:{position:i.position,linearVelocity:i.linearVelocity},shooter:r,timeLimit:this.timeLimitSeconds()},t.currentTime);this.renderShotList(),this.setStatus(a6(o+1,s.track.name,wi(t.currentTime),k3(r)))}async loadPackFile(e){if(!(this.session?.hasUnsavedShots&&!window.confirm("Discard unsaved captured shots and open this pack?")))try{const t=await mo.loadFromBytes(await e.arrayBuffer());this.adoptSession(t),this.setStatus(`Opened ${e.name} (${t.shotCount} shot${t.shotCount===1?"":"s"}); captures will append.`)}catch(t){console.error("Failed to load training pack:",t),this.setStatus(t instanceof Error?t.message:"Failed to load training pack.")}}async newPack(){if(!(this.session?.hasUnsavedShots&&!window.confirm("Discard unsaved captured shots and start a new pack?")))try{this.adoptSession(await mo.createNew()),this.setStatus("Started a new pack.")}catch(e){console.error("Failed to create training pack:",e),this.setStatus(e instanceof Error?e.message:"Failed to create training pack.")}}async download(){const e=await this.ensureSession();if(e.shotCount===0){this.setStatus("No shots to download; capture one first.");return}try{r6(e.toBytes(),e.downloadFileName()),this.setStatus(`Downloaded ${e.downloadFileName()}.`)}catch(t){console.error("Failed to serialize training pack:",t),this.setStatus(t instanceof Error?t.message:"Failed to serialize pack.")}}renderShotList(){const{shotList:e}=this.options.elements;e.replaceChildren();const t=this.session;if(t)for(const i of t.shots()){const s=document.createElement("li"),a=document.createElement("span"),r=i.sourceReplayTime===null?"loaded":`at ${wi(i.sourceReplayTime)}`,o=i.timeLimit===0?"no limit":`${i.timeLimit}s`;a.textContent=`Shot ${i.index+1} — ${r} — ${o}`;const l=document.createElement("button");l.type="button",l.textContent="Remove",l.addEventListener("click",()=>{t.removeShot(i.index),this.renderShotList(),this.setStatus(`Removed shot ${i.index+1}.`)}),s.append(a,l),e.appendChild(s)}}setStatus(e){this.options.elements.status.textContent=e}}function l6(n){return new o6(n)}class c6{constructor(e){this.options=e}activeModules=[];activeTimelineEventSourceIds=new Set;activeTimelineRangeModuleIds=new Set;activeMechanicTimelineKinds=new Set;activeRenderEffectModuleIds=new Set;removeRenderHook=null;timelineSourceRemovers=new Map;timelineRangeSourceRemovers=new Map;getActiveModules(){return this.activeModules}getActiveTimelineEventSourceIds(){return this.activeTimelineEventSourceIds}getActiveTimelineRangeModuleIds(){return this.activeTimelineRangeModuleIds}getActiveMechanicTimelineKinds(){return this.activeMechanicTimelineKinds}getActiveRenderEffectModuleIds(){return this.activeRenderEffectModuleIds}getActiveCapabilityIds(e){return e==="events"?this.activeTimelineEventSourceIds:e==="ranges"?this.activeTimelineRangeModuleIds:this.activeRenderEffectModuleIds}getBoostPadOverlayEnabled(){return!0}getTimelineEventSourceIds(){return[...this.activeTimelineEventSourceIds]}getTimelineRangeModuleIds(){return[...this.activeTimelineRangeModuleIds]}getMechanicTimelineKinds(){return[...this.activeMechanicTimelineKinds]}getRenderEffectModuleIds(){return[...this.activeRenderEffectModuleIds]}applyOverlayConfig({timelineEvents:e,timelineRanges:t,mechanics:i,renderEffects:s,boostPads:a}){this.activeTimelineEventSourceIds=new Set(e),this.activeTimelineRangeModuleIds=new Set(t),this.activeMechanicTimelineKinds=new Set(i),this.activeRenderEffectModuleIds=new Set(s)}reset(){this.teardownActiveModules(),this.clearStandalonePlugins(),this.activeModules=[],this.activeTimelineEventSourceIds=new Set,this.activeTimelineRangeModuleIds=new Set,this.activeMechanicTimelineKinds=new Set,this.activeRenderEffectModuleIds=new Set,this.removeRenderHook=null}setupActiveModules(){this.teardownActiveModules();const e=this.options.getContext();if(!e)return;const t=this.getActiveModuleIds();this.activeModules=this.options.modules.filter(i=>t.has(i.id)),this.options.boostPickupFilters.setup(e);for(const i of this.activeModules)i.setup(e);this.removeRenderHook=e.player.onBeforeRender(i=>{for(const s of this.activeModules)this.activeRenderEffectModuleIds.has(s.id)&&s.onBeforeRender(i)}),this.syncTimelineEvents(),this.syncTimelineRanges()}teardownActiveModules(){this.removeRenderHook?.(),this.removeRenderHook=null,this.clearTimelineEventSources(),this.clearTimelineRangeSources();for(const e of this.activeModules)e.teardown();this.activeModules=[]}toggleCapability(e,t,i){const s=this.getMutableActiveCapabilityIds(t);i?s.add(e):s.delete(e),this.setupActiveModules(),this.options.renderModuleSummary(),this.options.renderModuleSettings(),this.options.renderStatsWindows(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()}setMechanicTimelineKind(e,t){t?this.activeMechanicTimelineKinds.add(e):this.activeMechanicTimelineKinds.delete(e),this.options.requestConfigSync()}activateMechanicTimelineKind(e){this.activeMechanicTimelineKinds.add(e),this.syncTimelineEvents(),this.syncTimelineRanges(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()}clearTimelineEventSources(){for(const e of this.timelineSourceRemovers.values())e();this.timelineSourceRemovers.clear()}clearTimelineRangeSources(){for(const e of this.timelineRangeSourceRemovers.values())e();this.timelineRangeSourceRemovers.clear()}clearStandalonePlugins(){}syncBoostPadOverlayPlugin(){}toggleBoostPadOverlay(){this.options.renderModuleSummary(),this.options.requestConfigSync()}syncTimelineEvents(){this.clearTimelineEventSources();const e=this.options.getContext(),t=this.options.getTimelineOverlay();if(!(!t||!e)){for(const i of this.options.getEventTimelineSources(e)){if(!i.active)continue;const s=i.buildTimelineEvents();s.length!==0&&this.timelineSourceRemovers.set(i.timelineKey,t.addEventSource(this.options.withTimelineEventSeekTimes(s),{id:i.timelineId,label:i.label}))}t.refreshEvents()}}syncTimelineRanges(){this.clearTimelineRangeSources();const e=this.options.getContext(),t=this.options.getTimelineOverlay();if(!(!t||!e)){for(const i of this.activeModules)!this.activeTimelineRangeModuleIds.has(i.id)||!i.getTimelineRanges||this.timelineRangeSourceRemovers.set(i.id,t.addRangeSource(()=>i.getTimelineRanges?.(e)??[]));for(const i of this.options.getEventTimelineSources(e)){if(!i.active||!i.buildTimelineRanges)continue;const s=i.buildTimelineRanges();s.length!==0&&this.timelineRangeSourceRemovers.set(i.timelineKey,t.addRangeSource(s))}t.refreshRanges()}}getActiveModuleIds(){return new Set([...this.activeTimelineEventSourceIds,...this.activeTimelineRangeModuleIds,...this.activeRenderEffectModuleIds])}getMutableActiveCapabilityIds(e){return e==="events"?this.activeTimelineEventSourceIds:e==="ranges"?this.activeTimelineRangeModuleIds:this.activeRenderEffectModuleIds}}function u6(n){return new c6(n)}function Jn(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function ew(n){return Jn(n)&&(n.kind==="time"||n.kind==="frame")&&typeof n.value=="number"&&Number.isFinite(n.value)?{kind:n.kind,value:n.value}:null}function Hu(n,e){if(n!=null){if(typeof n!="number"||!Number.isInteger(n)||!Number.isFinite(n)||n<0)throw new Error(`Review playlist page ${e} must be a non-negative integer.`);return n}}function tw(n,e){if(n!=null){if(typeof n!="string")throw new Error(`Review playlist page ${e} must be a string.`);return n}}function d6(n){if(n!=null){if(!Jn(n))throw new Error("Review playlist page must be an object.");return{next:tw(n.next,"next"),previous:tw(n.previous,"previous"),total:Hu(n.total,"total"),count:Hu(n.count,"count"),limit:Hu(n.limit,"limit"),offset:Hu(n.offset,"offset")}}}function h6(n){if(n!=null){if(!Jn(n))throw new Error("Review playlist playback must be an object.");if(n.timeBase!==void 0&&n.timeBase!=="playback"&&n.timeBase!=="rawReplay")throw new Error('Review playlist playback timeBase must be "playback" or "rawReplay".');return{...n,timeBase:n.timeBase}}}function f6(n,e){if(n==null)return;if(!Jn(n))throw new Error(`Review item ${e} perspective must be an object.`);if(n.kind!=="player")throw new Error(`Review item ${e} perspective kind must be "player".`);const t=typeof n.playerId=="string"&&n.playerId.trim()?n.playerId.trim():void 0,i=typeof n.playerName=="string"&&n.playerName.trim()?n.playerName.trim():void 0;if(!t&&!i)throw new Error(`Review item ${e} player perspective needs playerId or playerName.`);if(n.ballCam!==void 0&&n.ballCam!=="off"&&n.ballCam!=="on"&&n.ballCam!=="player")throw new Error(`Review item ${e} perspective ballCam must be off, on, or player.`);if(n.usePlayerCameraSettings!==void 0&&typeof n.usePlayerCameraSettings!="boolean")throw new Error(`Review item ${e} perspective usePlayerCameraSettings must be boolean.`);return{kind:"player",playerId:t,playerName:i,ballCam:n.ballCam,usePlayerCameraSettings:n.usePlayerCameraSettings}}function p6(n){if(!Jn(n)||!Array.isArray(n.items))throw new Error("Review playlist must contain an items array.");const e=n.items.map((i,s)=>{if(!Jn(i)||typeof i.replay!="string")throw new Error(`Invalid review item at index ${s}.`);const a=ew(i.start),r=ew(i.end);if(!a||!r)throw new Error(`Review item ${s+1} has invalid start or end.`);return{id:typeof i.id=="string"?i.id:void 0,replay:i.replay,start:a,end:r,label:typeof i.label=="string"?i.label:void 0,perspective:f6(i.perspective,s+1),meta:Jn(i.meta)?i.meta:void 0}}),t=Array.isArray(n.replays)?n.replays.map(i=>!Jn(i)||typeof i.id!="string"?null:{id:i.id,path:typeof i.path=="string"?i.path:void 0,label:typeof i.label=="string"?i.label:void 0,locator:Jn(i.locator)?i.locator:void 0,meta:Jn(i.meta)?i.meta:void 0}).filter(i=>i!==null):void 0;return{label:typeof n.label=="string"?n.label:void 0,replays:t,items:e,page:d6(n.page),playback:h6(n.playback),meta:n.meta}}function nw(n){let e;try{e=JSON.parse(n)}catch(t){throw new Error(`Invalid review playlist JSON: ${t instanceof Error?t.message:String(t)}`)}return p6(e)}function m6(){const n=new URLSearchParams(window.location.search);return n.get("reviewPlaylist")?.trim()||n.get("review")?.trim()||n.get("playlist")?.trim()||n.get("playlistUrl")?.trim()||null}function _6(n){return/^\/(?:home|Users|tmp|var\/tmp|mnt|media|run\/user|nix\/store)\//.test(n)}function y1(n,e){const t=n.startsWith("path:")?n.slice(5):n;if(/^https?:\/\//i.test(t)||t.startsWith("/@fs/"))return t;if(t.startsWith("/")){if(_6(t))return`/@fs${t}`;if(e){const i=new URL(e,window.location.href);if(i.origin!==window.location.origin)return new URL(t,i.origin).href}return t}return e?new URL(t,e).href:t}function dd(n,e){const t=e.replaysById.get(n.replay);if(t?.path)return t.path;if(Jn(t?.locator)&&t.locator.kind==="path"&&typeof t.locator.path=="string")return t.locator.path;if(/^https?:\/\//i.test(n.replay)||n.replay.startsWith("/")||n.replay.startsWith("/@fs/")||n.replay.startsWith("path:"))return n.replay;throw new Error(`Review replay "${n.replay}" does not include a loadable path.`)}function iw(n,e){const t=e.replaysById.get(n.replay),s=(t?.path??dd(n,e)).replace(/^path:/,"").split("/").filter(Boolean).pop();return t?.label??s??"review replay"}function hd(n){return typeof n=="number"&&Number.isFinite(n)?`${n.toFixed(2)}s`:"--"}function sw(n){return n.kind==="time"?hd(n.value):`frame ${Math.trunc(n.value)}`}function qi(n,e){if(!Jn(n.meta?.target))return null;const t=n.meta.target[e];return typeof t=="number"&&Number.isFinite(t)?t:null}function fd(n,e){if(!Jn(n.meta?.target))return null;const t=n.meta.target[e];return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):null}function g6(n,e){for(const[t,i]of[["eventTime","eventFrame"],["startTime","startFrame"],["endTime","endFrame"]]){const s=qi(n,t),a=fd(n,i),r=a===null?null:e.frames[a]?.time;if(s!==null&&typeof r=="number"&&Number.isFinite(r))return s-r}return 0}function v1(n,e,t){return t==="playback"?0:t==="rawReplay"&&typeof e.rawStartTime=="number"&&Number.isFinite(e.rawStartTime)?e.rawStartTime:g6(n,e)}function D_(n,e){return Math.min(Math.max(0,n),Math.max(0,e))}function y6(n,e,t,i){if(e.kind==="frame"){const a=Math.max(0,Math.trunc(e.value));return D_(t.frames[a]?.time??0,t.duration)}const s=v1(n,t,i);return D_(e.value-s,t.duration)}function v6(n,e,t){const i=M6(n);return i===null?null:D_(i-v1(n,e,t),e.duration)}function b6(n){const e=n.start.kind==="time"?n.start.value:null,t=n.end.kind==="time"?n.end.value:null,i=[`${sw(n.start)} to ${sw(n.end)}`];e!==null&&t!==null&&i.push(`${Math.max(0,t-e).toFixed(1)}s clip`);const s=qi(n,"startTime")??qi(n,"eventTime"),a=qi(n,"endTime")??qi(n,"eventTime");return e!==null&&s!==null&&i.push(`${Math.max(0,s-e).toFixed(1)}s preroll`),t!==null&&a!==null&&i.push(`${Math.max(0,t-a).toFixed(1)}s postroll`),i.join(" · ")}function x6(n){const e=qi(n,"eventTime"),t=qi(n,"startTime"),i=qi(n,"endTime"),s=fd(n,"eventFrame"),a=fd(n,"startFrame"),r=fd(n,"endFrame"),o=t!==null&&i!==null&&Math.abs(i-t)>.001?`${hd(t)} to ${hd(i)}`:hd(e??t??i),l=a!==null&&r!==null&&r!==a?`frames ${a}-${r}`:s!==null?`frame ${s}`:a!==null?`frame ${a}`:null;return[o,l].filter(c=>c&&c!=="--").join(" · ")||"--"}function gm(n,e){return n.label??n.meta?.eventTypeLabel??n.meta?.mechanicLabel??`Review item ${e+1}`}function w6(n){if(typeof n.meta?.playerName=="string"&&n.meta.playerName.trim())return n.meta.playerName.trim();if(Jn(n.meta?.target)&&typeof n.meta.target.playerName=="string"){const e=n.meta.target.playerName.trim();return e||null}return null}function aw(n,e){if(!n)return null;if(n.playerId){const i=e.find(s=>s.id===n.playerId);if(i)return i}const t=n.playerName?.toLowerCase();return t?e.find(i=>i.name.trim().toLowerCase()===t)??null:null}function rw(n){if(typeof n.meta?.eventTypeLabel=="string"&&n.meta.eventTypeLabel.trim())return n.meta.eventTypeLabel;if(typeof n.meta?.mechanicLabel=="string"&&n.meta.mechanicLabel.trim())return n.meta.mechanicLabel;const e=n.meta?.eventType??n.meta?.mechanic;return typeof e=="string"?Ai(e):"--"}function S6(n){const e=n.meta?.eventCategory;return typeof e=="string"&&e.trim()?Ai(e.trim()):"--"}function T6(n){const e=n.meta?.eventType??n.meta?.mechanic;return typeof e=="string"&&e.trim()?e.trim().replaceAll("-","_"):null}function M6(n){return qi(n,"eventTime")??qi(n,"startTime")??qi(n,"endTime")}class E6{constructor(e){this.options=e}createReplaySource(e,t,i){const s=dd(e,t),a=y1(s,t.sourceUrl);return{name:iw(e,t),preparingStatus:"Loading review replay...",async readBytes(){const r=await fetch(a,{signal:i});if(!r.ok){const o=r.statusText?` ${r.statusText}`:"";throw new Error(`Failed to fetch review replay from ${a} (${r.status}${o})`)}return new Uint8Array(await r.arrayBuffer())}}}initialize(e){const t=this.getReplayClipCounts(e);for(const[i,s]of this.getReplayItems(e)){let a="",r=i;try{a=dd(s,e),r=iw(s,e)}catch{r=e.replaysById.get(i)?.label??i}e.replayLoadStates.set(i,{replayId:i,label:r,path:a,clipCount:t.get(i)??0,status:"idle",progress:null,error:null})}}preload(e,t){if(e.preloading)return;const i=this.getNextReplayItems(e,t);i.length!==0&&(e.preloading=!0,(async()=>{try{for(const s of i){const a=s.replay,r=e.replayLoadStates.get(a);if(!(r?.status==="loaded"||r?.status==="loading"))try{await this.loadBundle(s,e)}catch{}}}finally{e.preloading=!1}})())}loadBundle(e,t){const i=t.replayLoadCache.get(e.replay);if(i)return i;const s=this.createReplaySource(e,t);this.updateLoadState(t,e.replay,{label:s.name,path:dd(e,t),status:"loading",progress:null,error:null});const a=Promise.resolve().then(async()=>{const r=await s.readBytes();return fE(r,{reportEveryNFrames:100,onProgress:o=>{this.updateLoadState(t,e.replay,{status:"loading",progress:o,error:null})}})}).then(r=>(this.updateLoadState(t,e.replay,{status:"loaded",progress:null,error:null}),r)).catch(r=>{throw t.replayLoadCache.delete(e.replay),this.updateLoadState(t,e.replay,{status:"error",error:r instanceof Error?r.message:String(r)}),r});return t.replayLoadCache.set(e.replay,a),a}render(e){const{reviewSummary:t,loadingSummary:i,loadingActive:s,loadingList:a}=this.options.elements,r=e?Array.from(e.replayLoadStates.values()):[],o=r.filter(h=>h.status==="loaded").length,l=r.filter(h=>h.status==="loading").length,c=r.filter(h=>h.status==="error").length,u=r.filter(h=>h.status==="idle").length,d=r.length===0?"0 replays":`${o}/${r.length} loaded${l>0?`, ${l} loading`:""}${c>0?`, ${c} failed`:""}`;if(t.textContent=d,i.textContent=d,s.textContent=r.length===0?"No playlist":l>0?`${l} active, ${u} pending`:c>0?`${c} failed`:e?.preloading?`Background queue, ${u} pending`:o===r.length?"Complete":`${u} pending`,a.replaceChildren(),!e||r.length===0){const h=document.createElement("p");h.className="stat-window-empty",h.textContent="No replay sources.",a.append(h);return}for(const h of r){const f=document.createElement("div");f.className=`mechanics-review-replay-load ${h.status}`;const p=document.createElement("div");p.className="mechanics-review-replay-load-main";const g=document.createElement("span");g.className="mechanics-review-replay-load-title",g.textContent=h.label;const _=document.createElement("span");_.className="mechanics-review-replay-load-meta",_.textContent=[h.replayId,`${h.clipCount} ${h.clipCount===1?"clip":"clips"}`,h.path].filter(Boolean).join(" · "),p.append(g,_);const m=document.createElement("strong");m.className="mechanics-review-replay-load-status",m.textContent=this.replayLoadStatusText(h);const v=document.createElement("div");v.className="mechanics-review-replay-load-progress";const y=document.createElement("span");y.style.width=`${Math.round(this.replayLoadProgressValue(h)*100)}%`,v.append(y),f.append(p,m,v),a.append(f)}}updateLoadState(e,t,i){const s=e.replayLoadStates.get(t)??{replayId:t,label:t,path:"",clipCount:0,status:"idle",progress:null,error:null};e.replayLoadStates.set(t,{...s,...i});const a=e.manifest.items[e.currentIndex];e.loading&&a?.replay===t&&i.progress&&this.options.onActiveLoadProgress(i.progress),this.options.isActiveReview(e)&&this.render(e)}getReplayItems(e){const t=new Map;for(const i of e.manifest.items)t.has(i.replay)||t.set(i.replay,i);return t}getReplayClipCounts(e){const t=new Map;for(const i of e.manifest.items)t.set(i.replay,(t.get(i.replay)??0)+1);return t}getNextReplayItems(e,t){const i=e.manifest.items[t]?.replay,s=new Set(i?[i]:[]),a=[];for(let r=t+1;r{const i=t.file.files?.[0];if(i)try{const s=nw(await i.text());await this.loadPlaylist(s,null)}catch(s){console.error("Failed to load review playlist:",s),this.setStatus(s instanceof Error?s.message:"Failed to load review playlist")}finally{t.file.value=""}},{signal:e}),t.loadUrl.addEventListener("click",()=>{this.loadPlaylistFromUrl(t.url.value.trim()).catch(i=>{console.error("Failed to load review playlist URL:",i),this.setStatus(i instanceof Error?i.message:"Failed to load review playlist URL")})},{signal:e}),t.previous.addEventListener("click",()=>{const i=this.activeReview;i&&this.activateItem(Math.max(0,i.currentIndex-1))},{signal:e}),t.replay.addEventListener("click",()=>this.replayClip(),{signal:e}),t.next.addEventListener("click",()=>{const i=this.activeReview;i&&this.activateItem(Math.min(i.manifest.items.length-1,i.currentIndex+1))},{signal:e}),t.confirm.addEventListener("click",()=>{this.submitDecision("confirmed")},{signal:e}),t.reject.addEventListener("click",()=>{this.submitDecision("rejected")},{signal:e}),t.uncertain.addEventListener("click",()=>{this.submitDecision("uncertain")},{signal:e})}render(){const{elements:e}=this.options,t=this.activeReview,i=t?.manifest.items??[],s=t?i[t.currentIndex]??null:null,a=i.length>0;e.count.textContent=`${i.length} item${i.length===1?"":"s"}`,e.index.textContent=a&&t?`${t.currentIndex+1} / ${i.length}`:"0 / 0",e.title.textContent=s?gm(s,t?.currentIndex??0):"No candidate selected",e.mechanic.textContent=s?rw(s):"--",e.player.textContent=s?this.getPlayerName(s):"--",e.clip.textContent=s?b6(s):"--",e.event.textContent=s?x6(s):"--",e.reason.textContent=s?.meta?.reason??"--",e.previous.disabled=!t||t.loading||t.currentIndex<=0,e.replay.disabled=!t||t.loading||!t.currentClip,e.next.disabled=!t||t.loading||t.currentIndex>=i.length-1;const r=!t||t.loading||ow(s)===null;if(e.confirm.disabled=r,e.reject.disabled=r,e.uncertain.disabled=r,this.options.replayLoads.render(t),e.list.replaceChildren(),!t||i.length===0){const o=document.createElement("p");o.className="stat-window-empty",o.textContent="No review playlist loaded.",e.list.append(o);return}i.forEach((o,l)=>{const c=document.createElement("button");c.type="button",c.className="mechanics-review-item",c.dataset.active=l===t.currentIndex?"true":"false",c.disabled=t.loading,c.addEventListener("click",()=>{this.activateItem(l)});const u=document.createElement("span");u.textContent=gm(o,l);const d=document.createElement("strong");d.textContent=[S6(o),rw(o),this.getPlayerName(o),ym(o.meta?.reviewStatus)].filter(h=>h&&h!=="--").join(" · ")||"--",c.append(u,d),e.list.append(c)})}async loadPlaylist(e,t){const i=new Map;for(const s of e.replays??[])i.set(s.id,s);this.activeReview={manifest:e,sourceUrl:t,replaysById:i,replayLoadStates:new Map,replayLoadCache:new Map,currentIndex:0,loading:!1,preloading:!1,currentReplayId:null,currentClip:null},this.options.replayLoads.initialize(this.activeReview),this.options.showReplayLoadingWindow(),this.setStatus(e.label?`Loaded ${e.label}.`:"Loaded review playlist."),this.render(),e.items.length>0&&await this.activateItem(0)}async loadPlaylistFromUrl(e){if(!e){this.setStatus("Enter a review playlist URL.");return}const t=y1(e,window.location.href);this.setStatus("Loading review playlist...");const i=await fetch(t);if(!i.ok){const a=i.statusText?` ${i.statusText}`:"";throw new Error(`Failed to fetch review playlist from ${t} (${i.status}${a})`)}const s=nw(await i.text());await this.loadPlaylist(s,i.url||t)}async activateItem(e){const t=this.activeReview,i=t?.manifest.items[e];if(!(!t||!i||t.loading)){t.loading=!0,t.currentIndex=e,this.render(),this.setStatus(`Loading ${gm(i,e)}...`);try{if(!this.options.getReplayPlayer()||t.currentReplayId!==i.replay){const d=this.options.replayLoads.createReplaySource(i,t),h=this.options.replayLoads.loadBundle(i,t);await this.options.loadReplayBundleForDisplay(d,h),t.currentReplayId=i.replay}this.options.replayLoads.preload(t,e);const a=t.manifest.playback?.timeBase,r=Math.max(0,this.getBoundTime(i,i.start,a)),o=Math.min(this.options.getReplayPlayer()?.getState().duration??Number.POSITIVE_INFINITY,Math.max(r,this.getBoundTime(i,i.end,a)));if(!Number.isFinite(r)||!Number.isFinite(o)||o<=r)throw new Error("Review item has an empty playback range.");const l=this.options.getReplayPlayer(),c=l?aw(i.perspective,l.replay.players):null;c&&this.options.applyClipPerspective({playerId:c.id,ballCam:i.perspective?.ballCam,usePlayerCameraSettings:i.perspective?.usePlayerCameraSettings}),this.options.resetReplayTransitionControls();const u=l===null?null:v6(i,l.replay,a);t.currentClip={startTime:r,endTime:o,targetTime:u},this.options.activateTimelineSource(i),this.options.getReplayPlayer()?.setState({currentTime:r,playing:!0,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),this.setStatus(u===null?`Playing ${r.toFixed(2)}s to ${o.toFixed(2)}s`:`Playing ${r.toFixed(2)}s to ${o.toFixed(2)}s; target ${u.toFixed(2)}s`)}catch(s){console.error("Failed to activate mechanics review item:",s),t.currentClip=null,this.setStatus(s instanceof Error?s.message:"Failed to load review item")}finally{t.loading=!1,this.render()}}}replayClip(){const e=this.activeReview?.currentClip,t=this.options.getReplayPlayer();!e||!t||t.setState({currentTime:e.startTime,playing:!0,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1})}async submitDecision(e){const t=this.activeReview,i=t?.manifest.items[t.currentIndex]??null,s=ow(i);if(!t||!i||!s){this.setStatus("Current review item has no review endpoint.");return}this.setStatus(`Submitting ${ym(e)}...`);const a=await fetch(s,{method:"POST",headers:{"content-type":"application/json",...R6()},credentials:"same-origin",body:JSON.stringify({status:e})});if(!a.ok){let r=`${a.status}${a.statusText?` ${a.statusText}`:""}`;try{const o=await a.json();typeof o.error=="string"&&(r=o.error)}catch{}this.setStatus(`Review failed: ${r}`);return}i.meta=i.meta??{},i.meta.reviewStatus=e,this.setStatus(`Marked ${ym(e)}.`),this.render()}enforceClipBoundary(e){const t=this.activeReview?.currentClip,i=this.options.getReplayPlayer();if(!t||!i||this.boundaryGuard)return!1;const s=e.currentTime=t.endTime-.025;if(!s&&!a)return!1;this.boundaryGuard=!0;try{i.setState({currentTime:s?t.startTime:t.endTime,playing:!1,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),a&&this.setStatus(`Finished clip at ${t.endTime.toFixed(2)}s`)}finally{this.boundaryGuard=!1}return!0}getBoundTime(e,t,i){const s=this.options.getReplayPlayer();return s?y6(e,t,s.replay,i):t.kind==="time"?t.value:0}getPlayerName(e){const t=w6(e);if(t)return t;const i=this.options.getReplayPlayer()?.replay.players??[];return aw(e.perspective,i)?.name??"--"}}function ym(n){return typeof n=="string"&&n.trim()?n.replaceAll("_"," "):"unreviewed"}function ow(n){if(!n)return null;if(typeof n.meta?.reviewEndpoint=="string"&&n.meta.reviewEndpoint)return n.meta.reviewEndpoint;const e=typeof n.meta?.eventId=="string"&&n.meta.eventId?n.meta.eventId:n.id;return e?`/api/v1/events/${encodeURIComponent(e)}/reviews`:null}function R6(){const n=new URLSearchParams(window.location.search),e=n.get("reviewToken")??n.get("token")??window.localStorage.getItem("rocket_sense_access_token");return e?{Authorization:`Bearer ${e}`}:{}}function P6(n){return new A6(n)}const I6=["replayUrl","replay_url","replay"],L6=["r","replayUrlZ","replay_url_z"],k6=["ballchasing","ballchasingId","ballchasingUuid","ballchasingReplay"];function D6(n){const e=n.replaceAll("-","+").replaceAll("_","/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=atob(t),s=new Uint8Array(i.length);for(let a=0;a{n.signal.aborted||(console.error("Failed to load replay URL:",t),n.statusReadout.textContent=t instanceof Error?t.message:"Failed to load replay URL")})}function H6(n){n.initialBundle?n.loadReplayBundleForDisplay({name:n.initialReplayName??"replay",preparingStatus:"Preparing replay...",async readBytes(){throw new Error("Replay bytes are not available for this preloaded replay")}},Promise.resolve(n.initialBundle)).catch(i=>{n.signal.aborted||(console.error("Failed to load preprocessed replay bundle:",i),n.statusReadout.textContent=i instanceof Error?i.message:"Failed to load preprocessed replay bundle")}):n.loadFromLocation!==!1&&z6(n);const e=m6();if(!e)return;const t=n.getMechanicsReviewController();t?.setUrl(e),n.showMechanicsReviewWindow(),t?.loadPlaylistFromUrl(e).catch(i=>{n.signal.aborted||(console.error("Failed to load mechanics review playlist from URL:",i),t?.setStatus(i instanceof Error?i.message:"Failed to load mechanics review playlist from URL"))})}function V6(n){const e=()=>{n.getSkipPostGoalTransitions().checked=!1,n.getSkipKickoffs().checked=!1},t=(i,s)=>{const a=n.getReplayPlayer();!a||!Number.isFinite(i)||(n.getMechanicsReviewController()?.clearCurrentClip(),e(),a.setState({currentTime:Math.max(0,i-n.goalWatchLeadSeconds),playing:s,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),n.scheduleConfigUrlUpdate())};return{watchGoalReplay(i,s){const a=n.getReplayPlayer();if(!a||!Number.isFinite(i))return;if(n.getMechanicsReviewController()?.clearCurrentClip(),s!==null&&a.replay.players.some(o=>o.id===s)){a.setAttachedPlayer(s),a.setCameraViewMode("follow");const o=n.getCameraControlsController();o&&(o.freeCameraPreset=null)}e(),a.setState({currentTime:Math.max(0,i-n.goalWatchLeadSeconds),playing:!0,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),n.scheduleConfigUrlUpdate()},cueGoalReplay(i){t(i,!1)},cueTimelineEvent(i){const s=n.getReplayPlayer();s&&(n.getMechanicsReviewController()?.clearCurrentClip(),e(),s.setState({currentTime:Ng(i),skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),n.scheduleConfigUrlUpdate())},applyConfigToReplayPlayer(i){const s=n.getReplayPlayer();if(!s)return;s.setState(A8(i.playback,i.camera,i));const a=n.getCameraControlsController();a&&(a.freeCameraPreset=i.camera.freePreset??null),i.camera.mode==="free"&&i.camera.freePreset&&s.setFreeCameraPreset(i.camera.freePreset),n.syncBoostPadOverlayPlugin(),n.setupActiveModules(),n.renderModuleSummary(),n.renderModuleSettings(),n.renderStatsWindows(s.getState().frameIndex)}}}function G6(n){let e=!1,t=null;const i=()=>n.getFloatingWindowController()?.getSingletonConfigs()??[],s=()=>n.getStatsWindowsController()?.getConfigs()??[],a=()=>{const o=n.getActiveModulesRuntime(),l=n.getReplayPlayer();return C8({playback:M8({replayPlayer:l,playbackRate:n.playbackRate,skipPostGoalTransitions:n.skipPostGoalTransitions,skipKickoffs:n.skipKickoffs}),camera:E8({replayPlayer:l,cameraControlsController:n.getCameraControlsController()}),activeTimelineEventSourceIds:o.getActiveTimelineEventSourceIds(),activeTimelineRangeModuleIds:o.getActiveTimelineRangeModuleIds(),activeMechanicTimelineKinds:o.getActiveMechanicTimelineKinds(),activeRenderEffectModuleIds:o.getActiveRenderEffectModuleIds(),initialConfig:n.getInitialConfig(),replayPlayer:l,boostPadOverlayEnabled:o.getBoostPadOverlayEnabled(),recording:n.getRecordingWindowController()?.getConfigSnapshot()??{},singletonWindows:i(),statsWindows:s(),moduleConfigs:T8(n.modules)})},r=o=>{v8(g1(n.modules),o)};return{setApplyingConfig(o){e=o},reset(){t!==null&&(window.clearTimeout(t),t=null),e=!1},scheduleConfigUrlUpdate(){e||(t!==null&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null;const o=jW(new URL(window.location.href),a());window.history.replaceState(window.history.state,"",o)},150))},applyConfigToStaticControls(o){if(n.getActiveModulesRuntime().applyOverlayConfig(o.overlays),n.skipPostGoalTransitions.checked=o.playback.skipPostGoalTransitions??n.skipPostGoalTransitions.checked,n.skipKickoffs.checked=o.playback.skipKickoffs??n.skipKickoffs.checked,n.hitboxWireframes.checked=o.overlays.hitboxWireframes,n.hitboxOnlyMode.checked=o.overlays.hitboxOnlyMode,n.getCameraControlsController()?.applyNameplateLiftUu(o.camera.nameplateLiftUu),n.getCameraControlsController()?.setAutoPossessionEnabled(o.camera.autoPossession??!1,{requestConfigSync:!1}),o.playback.rate!==void 0){const l=mf(o.playback.rate);n.playbackRate.value=`${l}`,n.playbackRateReadout.textContent=ty(l)}n.getRecordingWindowController()?.applyConfig(o.recording),r(o.moduleConfigs),n.getFloatingWindowController()?.applySingletonConfigs(o.singletonWindows),n.getStatsWindowsController()?.replaceFromConfig(o.statsWindows),n.renderModuleSummary(),n.renderModuleSettings(),n.renderTimelineEventCount()}}}function $6(n){const e=t=>{const i=n.getLauncherToggle();n.getLauncherMenu().hidden=!t,i.setAttribute("aria-label",t?"Close menu":"Open menu"),i.setAttribute("aria-expanded",t?"true":"false")};return{bringWindowToFront(t){n.getFloatingWindowController()?.bringToFront(t)},showWindow(t){n.getFloatingWindowController()?.show(t)},toggleWindow(t){n.getFloatingWindowController()?.toggle(t)},hideWindow(t){n.getFloatingWindowController()?.hide(t)},setLauncherOpen:e,openReplayFilePicker(){n.getFileInput().click(),e(!1)},installWindowDragging(t,i){n.getFloatingWindowController()?.installDragging(t,i)},getElementWindowId(t){return t.closest("[data-window-id]")?.dataset.windowId??null}}}const O_=4096,fr=5120,W6=893,X6=642,Yi=1/105;class K6{constructor(e){this.options=e,this.options.body.innerHTML=`
@@ -5920,4 +5985,4 @@ void main() {

Load a replay with shot events.

- `,this.chartCanvas=this.mustElement("#shot-chart-canvas"),this.shotList=this.mustElement("#shot-list"),this.summary=this.mustElement("#shot-visualization-summary"),this.details=this.mustElement("#shot-details"),this.sceneRoot=this.mustElement("#shot-demo-scene"),this.emptyState=this.mustElement("#shot-visualization-empty"),this.chartCanvas.addEventListener("click",t=>this.handleChartClick(t))}chartCanvas;shotList;summary;details;sceneRoot;emptyState;renderer=null;scene=null;camera=null;resizeObserver=null;selectedShotId=null;cachedReplay=null;cachedShots=[];lastShotsSignature="";lastListSelectionKey=null;lastSelectedShotKey=null;shotButtons=new Map;destroy(){this.resizeObserver?.disconnect(),this.renderer?.dispose(),this.renderer=null,this.scene=null,this.camera=null}render(e=this.options.getReplayPlayer()?.getState()??null){const t=this.shotEvents(),i=e?.currentTime??null;this.findSelectedShot(t)||(this.selectedShotId=t[0]?this.shotKey(t[0],0):null);const s=this.findSelectedShot(t),a=s?.key??null,r=this.shotsSignature(t),o=r!==this.lastShotsSignature;this.emptyState.hidden=t.length>0,o&&(this.summary.textContent=this.summaryText(t)),o||a!==this.lastListSelectionKey?(this.renderShotList(t,i,a),this.lastListSelectionKey=a):this.updateShotListActiveState(t,i),this.renderChart(t,i),(o||a!==this.lastSelectedShotKey)&&(this.renderSelectedShot(s?.shot??null),this.lastSelectedShotKey=a),this.lastShotsSignature=r}shotEvents(){const e=this.options.getReplayPlayer()?.replay;return e?e===this.cachedReplay?this.cachedShots:(this.cachedReplay=e,this.cachedShots=e.timelineEvents.filter(f6),this.cachedShots):(this.cachedReplay=null,this.cachedShots=[],[])}summaryText(e){if(e.length===0)return"No shots";const t=e.filter(a=>a.shot.resulting_save).length,i=e.map(a=>a.shot.ball_speed).filter(a=>Number.isFinite(a)),s=i.length===0?null:i.reduce((a,r)=>a+r,0)/i.length;return`${e.length} shots | ${t} saved | avg ${Uu(s)}`}renderShotList(e,t,i){this.shotButtons.clear(),this.shotList.replaceChildren(...e.map((s,a)=>{const r=this.shotKey(s,a),o=document.createElement("button");o.type="button",o.className="shot-list-item",o.dataset.selected=String(r===i),o.dataset.active=String(hm(s,t)),o.addEventListener("click",()=>{this.selectedShotId=r,this.options.cueTimelineEvent(s),this.render()});const l=document.createElement("span");l.className="shot-list-title",l.textContent=s.playerName??s.playerId??`Shot ${a+1}`;const c=document.createElement("span");return c.className="shot-list-meta",c.textContent=`${nw(s.time)} | ${Uu(s.shot.ball_speed)} | ${s.shot.resulting_save?"saved":"unsaved"}`,o.append(l,c),this.shotButtons.set(r,o),o}))}updateShotListActiveState(e,t){e.forEach((i,s)=>{const a=this.shotButtons.get(this.shotKey(i,s));a&&(a.dataset.active=String(hm(i,t)))})}renderChart(e,t){const i=this.chartCanvas.getContext("2d");if(!i)return;const s=window.devicePixelRatio||1,a=this.chartCanvas.getBoundingClientRect(),r=Math.max(320,Math.round(a.width*s)),o=Math.max(220,Math.round(a.height*s));(this.chartCanvas.width!==r||this.chartCanvas.height!==o)&&(this.chartCanvas.width=r,this.chartCanvas.height=o),i.setTransform(s,0,0,s,0,0);const l=r/s,c=o/s;i.clearRect(0,0,l,c),p6(i,l,c),e.forEach((u,d)=>{const h=u.shot.shot_touch_position??u.shot.ball_position,f=ah(h,l,c),p=!!u.shot.resulting_save,g=hm(u,t),_=this.shotKey(u,d)===this.selectedShotId,m=_?6:g?5:4;i.beginPath(),i.arc(f.x,f.y,m,0,Math.PI*2),i.fillStyle=p?"#f2c14e":"#62d2a2",i.fill(),i.lineWidth=_?2.5:1.25,i.strokeStyle=_?"#f8fafc":g?"#e11d48":"rgba(4, 12, 20, 0.85)",i.stroke()})}renderSelectedShot(e){if(!e){this.details.replaceChildren(),this.clearThreeScene();return}this.details.replaceChildren(cl("Player",e.playerName??e.playerId??"--"),cl("Speed",Uu(e.shot.ball_speed)),cl("Toward goal",Uu(e.shot.ball_speed_toward_goal)),cl("Touch",_6(e.shot.shot_touch_position??e.shot.ball_position)),cl("Save",e.shot.resulting_save?nw(e.shot.resulting_save.time):"--")),this.renderThreeScene(e)}renderThreeScene(e){const t=this.ensureRenderer(),i=this.scene,s=this.camera;i.clear(),i.add(new dc(16777215,1.2));const a=new Do(16777215,1.7);a.position.set(18,28,22),i.add(a);const r=new we(new Dn(A_*2*qi,hr*2*qi),new Ye({color:1520422,side:ct}));r.rotation.x=-Math.PI/2,i.add(r);const o=new Rt({color:14280674,transparent:!0,opacity:.55});i.add(new Ln(new Bh(r.geometry),o)),i.add(ew(!0)),i.add(ew(!1));const l=tw(e.shot.shot_touch_position??e.shot.ball_position),c=tw(e.shot.target_goal_position),u=e.shot.ball_velocity,d=u?l.clone().add(m6(u).normalize().multiplyScalar(22)):c.clone(),h=new sg([l,l.clone().lerp(d,.45).setY(Math.max(l.y,d.y)+2.8),d]),f=new Ge().setFromPoints(h.getPoints(36));i.add(new In(f,new Rt({color:e.shot.resulting_save?15909198:6476450,linewidth:2})));const p=new we(new yn(.9,24,16),new Pn({color:16317180,roughness:.36}));p.position.copy(l),i.add(p);const g=new we(new ni(1.05,1.45,32),new Ye({color:8892372,side:ct}));g.position.copy(c),g.rotation.y=Math.PI/2,i.add(g),s.position.set(0,54,72),s.lookAt(0,0,0),t.render(i,s)}ensureRenderer(){if(this.renderer&&this.scene&&this.camera)return this.resizeThreeScene(),this.renderer;const e=new Eg({antialias:!0,alpha:!0,preserveDrawingBuffer:!0});return e.setPixelRatio(window.devicePixelRatio||1),this.sceneRoot.replaceChildren(e.domElement),this.renderer=e,this.scene=new ac,this.scene.background=new ue(463132),this.camera=new Jt(42,1,.1,500),this.resizeObserver=new ResizeObserver(()=>{this.resizeThreeScene();const t=this.shotEvents().find(i=>i.id===this.selectedShotId)??null;t&&this.renderThreeScene(t)}),this.resizeObserver.observe(this.sceneRoot),this.resizeThreeScene(),e}resizeThreeScene(){if(!this.renderer||!this.camera)return;const e=this.sceneRoot.getBoundingClientRect(),t=Math.max(240,Math.round(e.width)),i=Math.max(170,Math.round(e.height));this.camera.aspect=t/i,this.camera.updateProjectionMatrix(),this.renderer.setSize(t,i,!1)}clearThreeScene(){this.sceneRoot.replaceChildren(),this.renderer?.dispose(),this.renderer=null,this.scene=null,this.camera=null}handleChartClick(e){const t=this.shotEvents(),i=this.chartCanvas.getBoundingClientRect(),s={x:e.clientX-i.left,y:e.clientY-i.top};let a=null,r=Number.POSITIVE_INFINITY;for(const o of t){const l=ah(o.shot.shot_touch_position??o.shot.ball_position,i.width,i.height),c=Math.hypot(l.x-s.x,l.y-s.y);c`${this.shotKey(t,i)}:${t.time}:${t.shot.ball_speed}`).join("|")}}function f6(n){return n.kind==="shot"&&!!n.shot}function hm(n,e){return e!==null&&Math.abs(e-n.time)<1.5}function p6(n,e,t){n.fillStyle="#0f2b24",n.fillRect(0,0,e,t),n.strokeStyle="rgba(226, 241, 236, 0.74)",n.lineWidth=1.2,n.strokeRect(18,18,e-36,t-36),n.beginPath(),n.moveTo(18,t/2),n.lineTo(e-18,t/2),n.stroke(),n.beginPath(),n.arc(e/2,t/2,34,0,Math.PI*2),n.stroke();const s=ah({x:0,y:-hr},e,t),a=ah({x:0,y:hr},e,t);n.fillStyle="#4fa3ff",n.fillRect(s.x-28,s.y-4,56,8),n.fillStyle="#ff8a4c",n.fillRect(a.x-28,a.y-4,56,8)}function ah(n,e,t){const s=e-36,a=t-36;return{x:18+(n.x+A_)/(A_*2)*s,y:18+(1-(n.y+hr)/(hr*2))*a}}function ew(n){const e=new Mt,t=new Rt({color:n?16747084:5219327}),i=(n?hr:-hr)*qi,s=u6*qi,a=d6*qi,r=[new S(-s,0,i),new S(-s,a,i),new S(s,a,i),new S(s,0,i)];return e.add(new In(new Ge().setFromPoints(r),t)),e}function tw(n){return new S(n.x*qi,n.z*qi,n.y*qi)}function m6(n){return new S(n.x*qi,n.z*qi,n.y*qi)}function cl(n,e){const t=document.createElement("div"),i=document.createElement("dt");i.textContent=n;const s=document.createElement("dd");return s.textContent=e,t.append(i,s),t}function nw(n){return Number.isFinite(n)?`${n.toFixed(2)}s`:"--"}function Uu(n){return Number.isFinite(n)?`${Math.round(n)} uu/s`:"--"}function _6(n){return n?`${Math.round(n.x)}, ${Math.round(n.y)}, ${Math.round(n.z)}`:"--"}const g6=4,y6=100;let ot=null,Yg=null,rh=null,fo=null,po=null,oh=null,iw=0,Va=null;const uf=BE({refreshTimelineRanges(){hh()},rerenderCurrentState(){ot&&ot.setBoostPickupAnimationEnabled(ot.getState().boostPickupAnimationEnabled)},requestConfigSync(){mn()}}),cd=l$({rerenderCurrentState(){if(!ot)return;const n=ot.getState();pc(n.frameIndex)},refreshTimelineRanges(){hh()},requestConfigSync(){mn()}},{boostPickupFilters:uf}),_n=R8({modules:cd,boostPickupFilters:uf,getContext:_o,getReplayPlayer:()=>ot,getTimelineOverlay:()=>Yg,getEventTimelineSources:jg,withTimelineEventSeekTimes:m1,renderModuleSummary:Ja,renderModuleSettings:Qa,renderStatsWindows(){ot&&pc(ot.getState().frameIndex)},renderTimelineEventCount:Qr,requestConfigSync:mn}),vl=o6({goalWatchLeadSeconds:g6,getReplayPlayer:()=>ot,getCameraControlsController:()=>Bi,getMechanicsReviewController:()=>zi,getSkipPostGoalTransitions:()=>Ga,getSkipKickoffs:()=>$a,syncBoostPadOverlayPlugin:p1,setupActiveModules:dh,renderModuleSummary:Ja,renderModuleSettings:Qa,renderStatsWindows(n){pc(n)},scheduleConfigUrlUpdate:mn}),bi=c6({getFloatingWindowController:()=>aa,getLauncherMenu:()=>I_,getLauncherToggle:()=>P_,getFileInput:()=>lh});let bl=null,lh,u1,R_,sw,P_,I_,aw,rw,ow,lw,cw,uw,fm,pm,mm,_m,Bu,zu,dw,hw,fw,pw,ea,d1,h1,L_,Ga,Jr=null,$a,xl,wl,Hu=null,D_=Jl(),Bi=null,Sl=null,mw=null,mo=null,ec=null,tc=null,ch=null,zi=null,aa=null,k_=null,uh=null,ud=null,na=null,O_=null,As=null;function v6(n){return _n.getActiveCapabilityIds(n)}function b6(){}function _o(){return!ot||!fo||!po?null:{player:ot,replay:ot.replay,statsTimeline:fo,statsFrameLookup:po,fieldScale:1}}function dh(){_n.setupActiveModules()}function f1(){_n.teardownActiveModules()}function _w(n,e,t){_n.toggleCapability(n,e,t)}function x6(){_n.clearTimelineEventSources()}function w6(){_n.clearTimelineRangeSources()}function S6(){_n.clearStandalonePlugins()}function p1(){_n.syncBoostPadOverlayPlugin()}function gw(){_n.syncTimelineEvents()}function hh(){_n.syncTimelineRanges()}function Qr(){const n=_o();if(!n){L_.textContent="--";return}L_.textContent=`${T6(n)}`}function T6(n){return tc?.countVisibleSources(n)??0}function ae(n,e){const t=n.querySelector(e);if(!(t instanceof HTMLElement))throw new Error(`Missing element for selector: ${e}`);return t}function M6(n){if(!aa)throw new Error("Floating windows are not initialized.");return aa.readPlacement(n)}function E6(n,e){aa?.applyPlacement(n,e)}function pc(n=ot?.getState().frameIndex??0,e={}){mo?.render(n,e)}function C6(n){mo?.create(n)}function A6(){mo?.clear()}function mn(){na?.scheduleConfigUrlUpdate()}function R6(n){na?.applyConfigToStaticControls(n)}function m1(n){return n.map(e=>({...e,seekTime:Pg(e)}))}function Ja(){ch?.renderSummary()}function _1(){tc?.render()}function jg(n){return tc?.getSources(n)??[]}function P6(){const n=_o();return G$(n,jg(n))}function Zg(){ec?.render()}function Jg(n){const e=bl?.querySelector(`[data-window-id="${n}"]`);return!!(e&&!e.hidden)}function Qg(n,e={}){!e.forceScroll&&!Jg("event-playlist")||ec?.syncTimeline(n,e)}function g1(){ec?.reset()}function I6(n){const e=G8(n);e&&(_n.activateMechanicTimelineKind(e),_1())}function L6(n){return zi?.enforceClipBoundary(n)??!1}function Qa(){ch?.renderSettings()}function ey(n=ot?.getState().frameIndex??0){k_?.render(n)}function y1(n=ot?.getState()??null){Jg("shot-visualization")&&ud?.render(n)}function D6(n){if(bi.toggleWindow(n),!!Jg(n)){if(n==="event-playlist"){Zg();const e=ot?.getState();e&&Qg(e,{forceScroll:!0})}n==="shot-visualization"&&y1(ot?.getState()??null)}}function k6(n){uh?.setTransportEnabled(n,ot?.getState())}function v1(n=rh?.getStatus()??null){Sl?.sync(n)}function O6(n){if(L6(n))return;const e=performance.now();n.playing&&e-iwzW(n,e=>{ea.textContent=tf(e),Jr?.update(e)})))}async function F_(n,e){await QW(n,e,{elements:{fileInput:lh,viewport:u1,emptyState:R_,statusReadout:ea,playersReadout:d1,framesReadout:h1,skipPostGoalTransitions:Ga,skipKickoffs:$a,hitboxWireframes:xl,hitboxOnlyMode:wl},getReplayLoadModal:()=>Jr,getReplayPlayer:()=>ot,setReplayPlayer(t){ot=t,Va?.syncSource()},getUnsubscribe:()=>oh,setUnsubscribe(t){oh=t},setCanvasRecorder(t){rh=t},setLoadedReplayName(t){O_=t},setTimelineOverlay(t){Yg=t},setStatsTimeline(t){fo=t,Va?.syncSource()},setStatsFrameLookup(t){po=t},setStatRegistry(t){D_=t},getInitialConfig:()=>As,setApplyingConfig(t){na?.setApplyingConfig(t)},getReplayTimelineEvents(t){return A5(t,_n.getActiveTimelineEventSourceIds())},withTimelineEventSeekTimes:m1,includeBoostPickupAnimationPickup:F6,syncRecordingWindow:v1,setTransportEnabled:k6,teardownActiveModules:f1,clearTimelineEventSources:x6,clearTimelineRangeSources:w6,clearStandalonePlugins:S6,clearRenderCaches:b6,resetEventPlaylistWindow:g1,renderModuleSummary:Ja,renderScoreboard:ey,renderTimelineEventCount:Qr,renderMechanicsTimelineControls:_1,renderEventPlaylistWindow:Zg,renderModuleSettings:Qa,syncBoostPadOverlayPlugin:p1,setupActiveModules:dh,renderSnapshot:O6,applyConfigToReplayPlayer:vl.applyConfigToReplayPlayer,renderStatsWindows:pc,syncEventPlaylistTimeline:Qg,getCameraControlsController:()=>Bi})}function U6(n,e={}){Hu?.(),n.innerHTML=d3(),bl=n,Jr=IH(n),aa=OW({getRoot:()=>bl??document,requestConfigSync:mn}),lh=ae(n,"#replay-file"),u1=ae(n,"#viewport"),R_=ae(n,"#empty-state"),sw=ae(n,"#empty-load-replay"),P_=ae(n,"#launcher-toggle"),I_=ae(n,"#launcher-menu"),aw=ae(n,"#load-replay-action"),rw=ae(n,"#floating-window-layer"),k_=u8({body:ae(n,"#scoreboard-window-body"),getReplayPlayer:()=>ot,getStatsFrameLookup:()=>po});const t=ae(n,"#mechanics-timeline-window-body");tc=q$({body:t,modules:cd,getContext:_o,getActiveTimelineEventSourceIds:()=>_n.getActiveTimelineEventSourceIds(),getActiveMechanicTimelineKinds:()=>_n.getActiveMechanicTimelineKinds(),toggleEventSource(d,h){_w(d,"events",h)},setMechanicTimelineKind(d,h){_n.setMechanicTimelineKind(d,h)},setupActiveModules:dh,syncTimelineEvents:gw,syncTimelineRanges:hh,renderModuleSummary:Ja,renderModuleSettings:Qa,renderTimelineEventCount:Qr,requestConfigSync:mn}),ow=ae(n,"#event-playlist-window-body"),ec=NW({body:ow,getReplayPlayer:()=>ot,getSources:P6,cueTimelineEvent:vl.cueTimelineEvent,formatTime:ss}),ud=new h6({body:ae(n,"#shot-visualization-window-body"),getReplayPlayer:()=>ot,cueTimelineEvent:vl.cueTimelineEvent}),lw=ae(n,"#replay-loading-summary"),cw=ae(n,"#replay-loading-active"),uw=ae(n,"#replay-loading-list");const i=X8({elements:{reviewSummary:ae(n,"#mechanics-review-replay-load-summary"),loadingSummary:lw,loadingActive:cw,loadingList:uw},isActiveReview(d){return zi?.review===d},onActiveLoadProgress(d){ea.textContent=tf(d),Jr?.update(d)}});zi=Y8({elements:{file:ae(n,"#mechanics-review-file"),url:ae(n,"#mechanics-review-url"),loadUrl:ae(n,"#mechanics-review-load-url"),status:ae(n,"#mechanics-review-status"),index:ae(n,"#mechanics-review-index"),title:ae(n,"#mechanics-review-title"),mechanic:ae(n,"#mechanics-review-mechanic"),player:ae(n,"#mechanics-review-player"),clip:ae(n,"#mechanics-review-clip"),event:ae(n,"#mechanics-review-event"),reason:ae(n,"#mechanics-review-reason"),previous:ae(n,"#mechanics-review-prev"),replay:ae(n,"#mechanics-review-replay"),next:ae(n,"#mechanics-review-next"),confirm:ae(n,"#mechanics-review-confirm"),reject:ae(n,"#mechanics-review-reject"),uncertain:ae(n,"#mechanics-review-uncertain"),count:ae(n,"#mechanics-review-count"),list:ae(n,"#mechanics-review-list")},replayLoads:i,getReplayPlayer:()=>ot,resetReplayTransitionControls(){Ga.checked=!1,$a.checked=!1},activateTimelineSource:I6,loadReplayBundleForDisplay:F_,applyClipPerspective(d){Bi?.followPlayerWithReplayCamera(d.playerId,{ballCam:d.ballCam,usePlayerCameraSettings:d.usePlayerCameraSettings})},showReplayLoadingWindow(){bi.showWindow("replay-loading")}});const s=ae(n,"#boost-pickup-filters-window-body"),a=ae(n,"#touch-controls-window-body");fm=ae(n,"#stats-window-layer"),mo=w$({layer:fm,getReplayPlayer:()=>ot,getStatsTimeline:()=>fo,getStatsFrameLookup:()=>po,getStatRegistry:()=>D_,readWindowPlacement:M6,applyWindowPlacement:E6,bringWindowToFront:bi.bringWindowToFront,setLauncherOpen:bi.setLauncherOpen,requestConfigSync:mn,watchGoalReplay:vl.watchGoalReplay,cueGoalReplay:vl.cueGoalReplay}),pm=ae(n,"#toggle-playback"),mm=ae(n,"#previous-frame"),_m=ae(n,"#next-frame"),Bu=ae(n,"#playback-rate"),Bi=DH({elements:{attachedPlayer:ae(n,"#attached-player"),cameraViewFreeButton:ae(n,"#camera-view-free"),cameraViewFollowButton:ae(n,"#camera-view-follow"),cameraViewAutoPossession:ae(n,"#camera-view-auto-possession"),cameraViewOverheadButton:ae(n,"#camera-view-overhead"),cameraViewSideButton:ae(n,"#camera-view-side"),usePlayerCameraSettings:ae(n,"#use-player-camera-settings"),cameraSettingsControls:ae(n,"#camera-settings-controls"),customCameraFov:ae(n,"#custom-camera-fov"),customCameraHeight:ae(n,"#custom-camera-height"),customCameraPitch:ae(n,"#custom-camera-pitch"),customCameraDistance:ae(n,"#custom-camera-distance"),customCameraStiffness:ae(n,"#custom-camera-stiffness"),customCameraSwivelSpeed:ae(n,"#custom-camera-swivel-speed"),customCameraTransitionSpeed:ae(n,"#custom-camera-transition-speed"),customCameraFovReadout:ae(n,"#custom-camera-fov-readout"),customCameraHeightReadout:ae(n,"#custom-camera-height-readout"),customCameraPitchReadout:ae(n,"#custom-camera-pitch-readout"),customCameraDistanceReadout:ae(n,"#custom-camera-distance-readout"),customCameraStiffnessReadout:ae(n,"#custom-camera-stiffness-readout"),customCameraSwivelSpeedReadout:ae(n,"#custom-camera-swivel-speed-readout"),customCameraTransitionSpeedReadout:ae(n,"#custom-camera-transition-speed-readout"),ballCamOffButton:ae(n,"#ball-cam-off"),ballCamOnButton:ae(n,"#ball-cam-on"),ballCamPlayerButton:ae(n,"#ball-cam-player"),nameplateLift:ae(n,"#custom-nameplate-lift"),nameplateLiftReadout:ae(n,"#custom-nameplate-lift-readout"),cameraProfileReadout:ae(n,"#camera-profile-readout"),cameraFovReadout:ae(n,"#camera-fov-readout"),cameraHeightReadout:ae(n,"#camera-height-readout"),cameraPitchReadout:ae(n,"#camera-pitch-readout"),cameraBaseDistanceReadout:ae(n,"#camera-base-distance-readout"),cameraStiffnessReadout:ae(n,"#camera-stiffness-readout")},getReplayPlayer:()=>ot,requestConfigSync:mn,onAutoPossessionChange(d){Va?.syncSource(),d&&Va?.syncCurrentFrame()}}),Va=rV({getReplayPlayer:()=>ot,getStatsTimeline:()=>fo,getCameraControlsController:()=>Bi}),VE(ae(n,"#touch-color-legend-body"),["team"]),ch=J$({elements:{summary:ae(n,"#module-summary"),settings:ae(n,"#module-settings"),boostPickupFilters:s,touchControls:a},modules:cd,boostPickupFilters:uf,getContext:_o,getTimelineSources:()=>jg(_o()),getActiveModules:()=>_n.getActiveModules(),getActiveCapabilityIds:v6,getBoostPickupAnimationEnabled:()=>ot?.getState().boostPickupAnimationEnabled??!1,toggleCapability:_w,toggleBoostPickupAnimation(){const d=!(ot?.getState().boostPickupAnimationEnabled??!1);ot?.setBoostPickupAnimationEnabled(d),dh(),Ja(),Qa(),mn()},syncTimelineEvents:gw,syncTimelineRanges:hh,renderTimelineEventCount:Qr,requestConfigSync:mn}),dw=ae(n,"#time-readout"),hw=ae(n,"#frame-readout"),fw=ae(n,"#duration-readout"),pw=ae(n,"#playback-status-readout"),ea=ae(n,"#status-readout"),d1=ae(n,"#players-readout"),h1=ae(n,"#frames-readout"),L_=ae(n,"#events-readout"),zu=ae(n,"#playback-rate-readout"),Ga=ae(n,"#skip-post-goal-transitions"),$a=ae(n,"#skip-kickoffs"),xl=ae(n,"#hitbox-wireframes"),wl=ae(n,"#hitbox-only-mode"),uh=h8({elements:{togglePlayback:pm,previousFrame:mm,nextFrame:_m,playbackRate:Bu,playbackRateReadout:zu,skipPostGoalTransitions:Ga,skipKickoffs:$a,hitboxWireframes:xl,hitboxOnlyMode:wl,emptyState:R_,timeReadout:dw,frameReadout:hw,durationReadout:fw,playbackStatusReadout:pw},getFrameCount:()=>ot?.replay.frameCount??0,getCameraControlsController:()=>Bi}),Sl=r8({elements:{fps:ae(n,"#recording-fps"),playbackRate:ae(n,"#recording-playback-rate"),start:ae(n,"#recording-start"),fullReplay:ae(n,"#recording-full-replay"),stop:ae(n,"#recording-stop"),download:ae(n,"#recording-download"),clear:ae(n,"#recording-clear"),status:ae(n,"#recording-status"),elapsed:ae(n,"#recording-elapsed"),size:ae(n,"#recording-size"),type:ae(n,"#recording-type")},getCanvasRecorder:()=>rh,getReplayPlayer:()=>ot,getLoadedReplayName:()=>O_,setStatus(d){ea.textContent=d},requestConfigSync:mn}),mw=C8({elements:{mechanic:ae(n,"#missed-event-mechanic"),capture:ae(n,"#missed-event-capture"),list:ae(n,"#missed-event-list"),export:ae(n,"#missed-event-export"),upload:ae(n,"#missed-event-upload"),clear:ae(n,"#missed-event-clear"),status:ae(n,"#missed-event-status")},getReplayPlayer:()=>ot,showWindow:()=>bi.showWindow("missed-events")}),na=l6({modules:cd,playbackRate:Bu,playbackRateReadout:zu,skipPostGoalTransitions:Ga,skipKickoffs:$a,hitboxWireframes:xl,hitboxOnlyMode:wl,getReplayPlayer:()=>ot,getCameraControlsController:()=>Bi,getRecordingWindowController:()=>Sl,getFloatingWindowController:()=>aa,getStatsWindowsController:()=>mo,getActiveModulesRuntime:()=>_n,getInitialConfig:()=>As,renderModuleSummary:Ja,renderModuleSettings:Qa,renderTimelineEventCount:Qr});const r=i1(window.location),o=yW(window.location);let l=null;if(e.initialConfig!==void 0)As=e.initialConfig;else{try{As=gW(window.location)}catch(d){l=d,console.error("Invalid stats player config:",d),ea.textContent=d instanceof Error?d.message:"Invalid stats player config",As=null}o&&JW(r,As,l)}const c=new AbortController;bi.installWindowDragging(rw,c.signal),bi.installWindowDragging(fm,c.signal);const u=()=>{c.abort(),oh?.(),oh=null,f1(),ot?.destroy(),ot=null,rh=null,Yg=null,fo=null,po=null,D_=Jl(),A6(),mo=null,_n.reset(),Jr?.destroy(),Jr=null,g1(),tc=null,ec=null,zi?.reset(),zi=null,O_=null,Va?.reset(),Va=null,Bi=null,Sl=null,ch=null,k_=null,uh=null,ud?.destroy(),ud=null,As=null,na?.reset(),na=null,aa?.reset(),aa=null,bl===n&&(bl=null,n.replaceChildren()),Hu===u&&(Hu=null)};if(Hu=u,As){na?.setApplyingConfig(!0);try{R6(As)}finally{na?.setApplyingConfig(!1)}}return f8({elements:{root:n,launcherToggle:P_,launcherMenu:I_,loadReplayAction:aw,emptyLoadReplay:sw,fileInput:lh,togglePlayback:pm,previousFrame:mm,nextFrame:_m,playbackRate:Bu,playbackRateReadout:zu,skipPostGoalTransitions:Ga,skipKickoffs:$a,hitboxWireframes:xl,hitboxOnlyMode:wl},signal:c.signal,setLauncherOpen:bi.setLauncherOpen,openReplayFilePicker:bi.openReplayFilePicker,getElementWindowId:bi.getElementWindowId,toggleWindow:D6,hideWindow:bi.hideWindow,createStatsWindow:C6,async loadReplayFile(d){try{zi?.clearCurrentClip({resetReplayId:!0,render:!0}),await yw(UW(d))}catch(h){console.error("Failed to load replay:",h),ea.textContent=h instanceof Error?h.message:"Failed to load replay"}},togglePlayback(){ot?.togglePlayback(),mn()},stepFrames(d){ot?.stepFrames(d),mn()},setPlaybackRate(d){ot?.setPlaybackRate(d),mn()},setSkipPostGoalTransitionsEnabled(d){ot?.setSkipPostGoalTransitionsEnabled(d),mn()},setSkipKickoffsEnabled(d){ot?.setSkipKickoffsEnabled(d),mn()},setHitboxWireframesEnabled(d){ot?.setHitboxWireframesEnabled(d),mn()},setHitboxOnlyModeEnabled(d){ot?.setHitboxOnlyModeEnabled(d),mn()}}),zi?.installEventListeners(c.signal),Sl?.installEventListeners(c.signal),mw?.installEventListeners(c.signal),Bi?.installEventListeners(c.signal),_8({getReplayPlayer:()=>ot,signal:c.signal}),window.addEventListener("message",d=>{if(d.origin!==window.location.origin)return;const h=d.data;!h||typeof h!="object"||h.source!=="rocket-sense"||h.type==="activateReviewItem"&&typeof h.index=="number"&&Number.isInteger(h.index)&&zi?.activateItem(h.index)},{signal:c.signal}),Ja(),Qa(),ey(),Bi?.renderProfile(),Bi?.syncModeButtons(),v1(),Qr(),zi?.render(),Zg(),r6({signal:c.signal,location:window.location,statusReadout:ea,initialBundle:e.initialBundle,initialReplayName:e.initialReplayName,loadFromLocation:e.loadFromLocation,loadReplay:yw,loadReplayBundleForDisplay:F_,getMechanicsReviewController:()=>zi,showMechanicsReviewWindow(){bi.showWindow("mechanics-review")}}),{root:n,destroy:u}}export{U6 as mountStatEvaluationPlayer}; + `,this.chartCanvas=this.mustElement("#shot-chart-canvas"),this.shotList=this.mustElement("#shot-list"),this.summary=this.mustElement("#shot-visualization-summary"),this.details=this.mustElement("#shot-details"),this.sceneRoot=this.mustElement("#shot-demo-scene"),this.emptyState=this.mustElement("#shot-visualization-empty"),this.chartCanvas.addEventListener("click",t=>this.handleChartClick(t))}chartCanvas;shotList;summary;details;sceneRoot;emptyState;renderer=null;scene=null;camera=null;resizeObserver=null;selectedShotId=null;cachedReplay=null;cachedShots=[];lastShotsSignature="";lastListSelectionKey=null;lastSelectedShotKey=null;shotButtons=new Map;destroy(){this.resizeObserver?.disconnect(),this.renderer?.dispose(),this.renderer=null,this.scene=null,this.camera=null}render(e=this.options.getReplayPlayer()?.getState()??null){const t=this.shotEvents(),i=e?.currentTime??null;this.findSelectedShot(t)||(this.selectedShotId=t[0]?this.shotKey(t[0],0):null);const s=this.findSelectedShot(t),a=s?.key??null,r=this.shotsSignature(t),o=r!==this.lastShotsSignature;this.emptyState.hidden=t.length>0,o&&(this.summary.textContent=this.summaryText(t)),o||a!==this.lastListSelectionKey?(this.renderShotList(t,i,a),this.lastListSelectionKey=a):this.updateShotListActiveState(t,i),this.renderChart(t,i),(o||a!==this.lastSelectedShotKey)&&(this.renderSelectedShot(s?.shot??null),this.lastSelectedShotKey=a),this.lastShotsSignature=r}shotEvents(){const e=this.options.getReplayPlayer()?.replay;return e?e===this.cachedReplay?this.cachedShots:(this.cachedReplay=e,this.cachedShots=e.timelineEvents.filter(q6),this.cachedShots):(this.cachedReplay=null,this.cachedShots=[],[])}summaryText(e){if(e.length===0)return"No shots";const t=e.filter(a=>a.shot.resulting_save).length,i=e.map(a=>a.shot.ball_speed).filter(a=>Number.isFinite(a)),s=i.length===0?null:i.reduce((a,r)=>a+r,0)/i.length;return`${e.length} shots | ${t} saved | avg ${Vu(s)}`}renderShotList(e,t,i){this.shotButtons.clear(),this.shotList.replaceChildren(...e.map((s,a)=>{const r=this.shotKey(s,a),o=document.createElement("button");o.type="button",o.className="shot-list-item",o.dataset.selected=String(r===i),o.dataset.active=String(vm(s,t)),o.addEventListener("click",()=>{this.selectedShotId=r,this.options.cueTimelineEvent(s),this.render()});const l=document.createElement("span");l.className="shot-list-title",l.textContent=s.playerName??s.playerId??`Shot ${a+1}`;const c=document.createElement("span");return c.className="shot-list-meta",c.textContent=`${uw(s.time)} | ${Vu(s.shot.ball_speed)} | ${s.shot.resulting_save?"saved":"unsaved"}`,o.append(l,c),this.shotButtons.set(r,o),o}))}updateShotListActiveState(e,t){e.forEach((i,s)=>{const a=this.shotButtons.get(this.shotKey(i,s));a&&(a.dataset.active=String(vm(i,t)))})}renderChart(e,t){const i=this.chartCanvas.getContext("2d");if(!i)return;const s=window.devicePixelRatio||1,a=this.chartCanvas.getBoundingClientRect(),r=Math.max(320,Math.round(a.width*s)),o=Math.max(220,Math.round(a.height*s));(this.chartCanvas.width!==r||this.chartCanvas.height!==o)&&(this.chartCanvas.width=r,this.chartCanvas.height=o),i.setTransform(s,0,0,s,0,0);const l=r/s,c=o/s;i.clearRect(0,0,l,c),Y6(i,l,c),e.forEach((u,d)=>{const h=u.shot.shot_touch_position??u.shot.ball_position,f=dh(h,l,c),p=!!u.shot.resulting_save,g=vm(u,t),_=this.shotKey(u,d)===this.selectedShotId,m=_?6:g?5:4;i.beginPath(),i.arc(f.x,f.y,m,0,Math.PI*2),i.fillStyle=p?"#f2c14e":"#62d2a2",i.fill(),i.lineWidth=_?2.5:1.25,i.strokeStyle=_?"#f8fafc":g?"#e11d48":"rgba(4, 12, 20, 0.85)",i.stroke()})}renderSelectedShot(e){if(!e){this.details.replaceChildren(),this.clearThreeScene();return}this.details.replaceChildren(hl("Player",e.playerName??e.playerId??"--"),hl("Speed",Vu(e.shot.ball_speed)),hl("Toward goal",Vu(e.shot.ball_speed_toward_goal)),hl("Touch",Z6(e.shot.shot_touch_position??e.shot.ball_position)),hl("Save",e.shot.resulting_save?uw(e.shot.resulting_save.time):"--")),this.renderThreeScene(e)}renderThreeScene(e){const t=this.ensureRenderer(),i=this.scene,s=this.camera;i.clear(),i.add(new mc(16777215,1.2));const a=new Fo(16777215,1.7);a.position.set(18,28,22),i.add(a);const r=new we(new kn(O_*2*Yi,fr*2*Yi),new Ye({color:1520422,side:ct}));r.rotation.x=-Math.PI/2,i.add(r);const o=new Rt({color:14280674,transparent:!0,opacity:.55});i.add(new Ln(new Wh(r.geometry),o)),i.add(lw(!0)),i.add(lw(!1));const l=cw(e.shot.shot_touch_position??e.shot.ball_position),c=cw(e.shot.target_goal_position),u=e.shot.ball_velocity,d=u?l.clone().add(j6(u).normalize().multiplyScalar(22)):c.clone(),h=new dg([l,l.clone().lerp(d,.45).setY(Math.max(l.y,d.y)+2.8),d]),f=new Ge().setFromPoints(h.getPoints(36));i.add(new In(f,new Rt({color:e.shot.resulting_save?15909198:6476450,linewidth:2})));const p=new we(new yn(.9,24,16),new Pn({color:16317180,roughness:.36}));p.position.copy(l),i.add(p);const g=new we(new ni(1.05,1.45,32),new Ye({color:8892372,side:ct}));g.position.copy(c),g.rotation.y=Math.PI/2,i.add(g),s.position.set(0,54,72),s.lookAt(0,0,0),t.render(i,s)}ensureRenderer(){if(this.renderer&&this.scene&&this.camera)return this.resizeThreeScene(),this.renderer;const e=new kg({antialias:!0,alpha:!0,preserveDrawingBuffer:!0});return e.setPixelRatio(window.devicePixelRatio||1),this.sceneRoot.replaceChildren(e.domElement),this.renderer=e,this.scene=new cc,this.scene.background=new ue(463132),this.camera=new Jt(42,1,.1,500),this.resizeObserver=new ResizeObserver(()=>{this.resizeThreeScene();const t=this.shotEvents().find(i=>i.id===this.selectedShotId)??null;t&&this.renderThreeScene(t)}),this.resizeObserver.observe(this.sceneRoot),this.resizeThreeScene(),e}resizeThreeScene(){if(!this.renderer||!this.camera)return;const e=this.sceneRoot.getBoundingClientRect(),t=Math.max(240,Math.round(e.width)),i=Math.max(170,Math.round(e.height));this.camera.aspect=t/i,this.camera.updateProjectionMatrix(),this.renderer.setSize(t,i,!1)}clearThreeScene(){this.sceneRoot.replaceChildren(),this.renderer?.dispose(),this.renderer=null,this.scene=null,this.camera=null}handleChartClick(e){const t=this.shotEvents(),i=this.chartCanvas.getBoundingClientRect(),s={x:e.clientX-i.left,y:e.clientY-i.top};let a=null,r=Number.POSITIVE_INFINITY;for(const o of t){const l=dh(o.shot.shot_touch_position??o.shot.ball_position,i.width,i.height),c=Math.hypot(l.x-s.x,l.y-s.y);c`${this.shotKey(t,i)}:${t.time}:${t.shot.ball_speed}`).join("|")}}function q6(n){return n.kind==="shot"&&!!n.shot}function vm(n,e){return e!==null&&Math.abs(e-n.time)<1.5}function Y6(n,e,t){n.fillStyle="#0f2b24",n.fillRect(0,0,e,t),n.strokeStyle="rgba(226, 241, 236, 0.74)",n.lineWidth=1.2,n.strokeRect(18,18,e-36,t-36),n.beginPath(),n.moveTo(18,t/2),n.lineTo(e-18,t/2),n.stroke(),n.beginPath(),n.arc(e/2,t/2,34,0,Math.PI*2),n.stroke();const s=dh({x:0,y:-fr},e,t),a=dh({x:0,y:fr},e,t);n.fillStyle="#4fa3ff",n.fillRect(s.x-28,s.y-4,56,8),n.fillStyle="#ff8a4c",n.fillRect(a.x-28,a.y-4,56,8)}function dh(n,e,t){const s=e-36,a=t-36;return{x:18+(n.x+O_)/(O_*2)*s,y:18+(1-(n.y+fr)/(fr*2))*a}}function lw(n){const e=new Mt,t=new Rt({color:n?16747084:5219327}),i=(n?fr:-fr)*Yi,s=W6*Yi,a=X6*Yi,r=[new S(-s,0,i),new S(-s,a,i),new S(s,a,i),new S(s,0,i)];return e.add(new In(new Ge().setFromPoints(r),t)),e}function cw(n){return new S(n.x*Yi,n.z*Yi,n.y*Yi)}function j6(n){return new S(n.x*Yi,n.z*Yi,n.y*Yi)}function hl(n,e){const t=document.createElement("div"),i=document.createElement("dt");i.textContent=n;const s=document.createElement("dd");return s.textContent=e,t.append(i,s),t}function uw(n){return Number.isFinite(n)?`${n.toFixed(2)}s`:"--"}function Vu(n){return Number.isFinite(n)?`${Math.round(n)} uu/s`:"--"}function Z6(n){return n?`${Math.round(n.x)}, ${Math.round(n.y)}, ${Math.round(n.z)}`:"--"}const J6=4,Q6=100;let st=null,ny=null,hh=null,_o=null,go=null,fh=null,dw=0,Ga=null;const _f=YE({refreshTimelineRanges(){yh()},rerenderCurrentState(){st&&st.setBoostPickupAnimationEnabled(st.getState().boostPickupAnimationEnabled)},requestConfigSync(){mn()}}),pd=B$({rerenderCurrentState(){if(!st)return;const n=st.getState();yc(n.frameIndex)},refreshTimelineRanges(){yh()},requestConfigSync(){mn()}},{boostPickupFilters:_f}),_n=u6({modules:pd,boostPickupFilters:_f,getContext:vo,getReplayPlayer:()=>st,getTimelineOverlay:()=>ny,getEventTimelineSources:iy,withTimelineEventSeekTimes:M1,renderModuleSummary:Qa,renderModuleSettings:er,renderStatsWindows(){st&&yc(st.getState().frameIndex)},renderTimelineEventCount:to,requestConfigSync:mn}),wl=V6({goalWatchLeadSeconds:J6,getReplayPlayer:()=>st,getCameraControlsController:()=>zi,getMechanicsReviewController:()=>Hi,getSkipPostGoalTransitions:()=>$a,getSkipKickoffs:()=>Wa,syncBoostPadOverlayPlugin:T1,setupActiveModules:gh,renderModuleSummary:Qa,renderModuleSettings:er,renderStatsWindows(n){yc(n)},scheduleConfigUrlUpdate:mn}),bi=$6({getFloatingWindowController:()=>ra,getLauncherMenu:()=>U_,getLauncherToggle:()=>N_,getFileInput:()=>ph});let Sl=null,ph,b1,F_,hw,N_,U_,fw,pw,mw,_w,gw,yw,bm,xm,wm,Sm,Gu,$u,vw,bw,xw,ww,ea,x1,w1,B_,$a,eo=null,Wa,Tl,Ml,Wu=null,z_=nc(),zi=null,El=null,Sw=null,md=null,yo=null,sc=null,ac=null,mh=null,Hi=null,ra=null,H_=null,_h=null,_d=null,ia=null,V_=null,As=null;function e9(n){return _n.getActiveCapabilityIds(n)}function t9(){}function vo(){return!st||!_o||!go?null:{player:st,replay:st.replay,statsTimeline:_o,statsFrameLookup:go,fieldScale:1}}function gh(){_n.setupActiveModules()}function S1(){_n.teardownActiveModules()}function Tw(n,e,t){_n.toggleCapability(n,e,t)}function n9(){_n.clearTimelineEventSources()}function i9(){_n.clearTimelineRangeSources()}function s9(){_n.clearStandalonePlugins()}function T1(){_n.syncBoostPadOverlayPlugin()}function Mw(){_n.syncTimelineEvents()}function yh(){_n.syncTimelineRanges()}function to(){const n=vo();if(!n){B_.textContent="--";return}B_.textContent=`${a9(n)}`}function a9(n){return ac?.countVisibleSources(n)??0}function se(n,e){const t=n.querySelector(e);if(!(t instanceof HTMLElement))throw new Error(`Missing element for selector: ${e}`);return t}function r9(n){if(!ra)throw new Error("Floating windows are not initialized.");return ra.readPlacement(n)}function o9(n,e){ra?.applyPlacement(n,e)}function yc(n=st?.getState().frameIndex??0,e={}){yo?.render(n,e)}function l9(n){yo?.create(n)}function c9(){yo?.clear()}function mn(){ia?.scheduleConfigUrlUpdate()}function u9(n){ia?.applyConfigToStaticControls(n)}function M1(n){return n.map(e=>({...e,seekTime:Ng(e)}))}function Qa(){mh?.renderSummary()}function E1(){ac?.render()}function iy(n){return ac?.getSources(n)??[]}function d9(){const n=vo();return bW(n,iy(n))}function sy(){sc?.render()}function ay(n){const e=Sl?.querySelector(`[data-window-id="${n}"]`);return!!(e&&!e.hidden)}function ry(n,e={}){!e.forceScroll&&!ay("event-playlist")||sc?.syncTimeline(n,e)}function C1(){sc?.reset()}function h9(n){const e=T6(n);e&&(_n.activateMechanicTimelineKind(e),E1())}function f9(n){return Hi?.enforceClipBoundary(n)??!1}function er(){mh?.renderSettings()}function oy(n=st?.getState().frameIndex??0){H_?.render(n)}function A1(n=st?.getState()??null){ay("shot-visualization")&&_d?.render(n)}function p9(n){if(bi.toggleWindow(n),!!ay(n)){if(n==="event-playlist"){sy();const e=st?.getState();e&&ry(e,{forceScroll:!0})}n==="shot-visualization"&&A1(st?.getState()??null)}}function m9(n){_h?.setTransportEnabled(n,st?.getState())}function R1(n=hh?.getStatus()??null){El?.sync(n),md?.sync()}function _9(n){if(f9(n))return;const e=performance.now();n.playing&&e-dwg8(n,e=>{ea.textContent=lf(e),eo?.update(e)})))}async function G_(n,e){await P8(n,e,{elements:{fileInput:ph,viewport:b1,emptyState:F_,statusReadout:ea,playersReadout:x1,framesReadout:w1,skipPostGoalTransitions:$a,skipKickoffs:Wa,hitboxWireframes:Tl,hitboxOnlyMode:Ml},getReplayLoadModal:()=>eo,getReplayPlayer:()=>st,setReplayPlayer(t){st=t,Ga?.syncSource()},getUnsubscribe:()=>fh,setUnsubscribe(t){fh=t},setCanvasRecorder(t){hh=t},setLoadedReplayName(t){V_=t},setTimelineOverlay(t){ny=t},setStatsTimeline(t){_o=t,Ga?.syncSource()},setStatsFrameLookup(t){go=t},setStatRegistry(t){z_=t},getInitialConfig:()=>As,setApplyingConfig(t){ia?.setApplyingConfig(t)},getReplayTimelineEvents(t){return a4(t,_n.getActiveTimelineEventSourceIds())},withTimelineEventSeekTimes:M1,includeBoostPickupAnimationPickup:g9,syncRecordingWindow:R1,setTransportEnabled:m9,teardownActiveModules:S1,clearTimelineEventSources:n9,clearTimelineRangeSources:i9,clearStandalonePlugins:s9,clearRenderCaches:t9,resetEventPlaylistWindow:C1,renderModuleSummary:Qa,renderScoreboard:oy,renderTimelineEventCount:to,renderMechanicsTimelineControls:E1,renderEventPlaylistWindow:sy,renderModuleSettings:er,syncBoostPadOverlayPlugin:T1,setupActiveModules:gh,renderSnapshot:_9,applyConfigToReplayPlayer:wl.applyConfigToReplayPlayer,renderStatsWindows:yc,syncEventPlaylistTimeline:ry,getCameraControlsController:()=>zi})}function b9(n,e={}){Wu?.(),n.innerHTML=V3(),Sl=n,eo=lV(n),ra=h8({getRoot:()=>Sl??document,requestConfigSync:mn}),ph=se(n,"#replay-file"),b1=se(n,"#viewport"),F_=se(n,"#empty-state"),hw=se(n,"#empty-load-replay"),N_=se(n,"#launcher-toggle"),U_=se(n,"#launcher-menu"),fw=se(n,"#load-replay-action"),pw=se(n,"#floating-window-layer"),H_=H8({body:se(n,"#scoreboard-window-body"),getReplayPlayer:()=>st,getStatsFrameLookup:()=>go});const t=se(n,"#mechanics-timeline-window-body");ac=MW({body:t,modules:pd,getContext:vo,getActiveTimelineEventSourceIds:()=>_n.getActiveTimelineEventSourceIds(),getActiveMechanicTimelineKinds:()=>_n.getActiveMechanicTimelineKinds(),toggleEventSource(d,h){Tw(d,"events",h)},setMechanicTimelineKind(d,h){_n.setMechanicTimelineKind(d,h)},setupActiveModules:gh,syncTimelineEvents:Mw,syncTimelineRanges:yh,renderModuleSummary:Qa,renderModuleSettings:er,renderTimelineEventCount:to,requestConfigSync:mn}),mw=se(n,"#event-playlist-window-body"),sc=p8({body:mw,getReplayPlayer:()=>st,getSources:d9,cueTimelineEvent:wl.cueTimelineEvent,formatTime:wi}),_d=new K6({body:se(n,"#shot-visualization-window-body"),getReplayPlayer:()=>st,cueTimelineEvent:wl.cueTimelineEvent}),_w=se(n,"#replay-loading-summary"),gw=se(n,"#replay-loading-active"),yw=se(n,"#replay-loading-list");const i=C6({elements:{reviewSummary:se(n,"#mechanics-review-replay-load-summary"),loadingSummary:_w,loadingActive:gw,loadingList:yw},isActiveReview(d){return Hi?.review===d},onActiveLoadProgress(d){ea.textContent=lf(d),eo?.update(d)}});Hi=P6({elements:{file:se(n,"#mechanics-review-file"),url:se(n,"#mechanics-review-url"),loadUrl:se(n,"#mechanics-review-load-url"),status:se(n,"#mechanics-review-status"),index:se(n,"#mechanics-review-index"),title:se(n,"#mechanics-review-title"),mechanic:se(n,"#mechanics-review-mechanic"),player:se(n,"#mechanics-review-player"),clip:se(n,"#mechanics-review-clip"),event:se(n,"#mechanics-review-event"),reason:se(n,"#mechanics-review-reason"),previous:se(n,"#mechanics-review-prev"),replay:se(n,"#mechanics-review-replay"),next:se(n,"#mechanics-review-next"),confirm:se(n,"#mechanics-review-confirm"),reject:se(n,"#mechanics-review-reject"),uncertain:se(n,"#mechanics-review-uncertain"),count:se(n,"#mechanics-review-count"),list:se(n,"#mechanics-review-list")},replayLoads:i,getReplayPlayer:()=>st,resetReplayTransitionControls(){$a.checked=!1,Wa.checked=!1},activateTimelineSource:h9,loadReplayBundleForDisplay:G_,applyClipPerspective(d){zi?.followPlayerWithReplayCamera(d.playerId,{ballCam:d.ballCam,usePlayerCameraSettings:d.usePlayerCameraSettings})},showReplayLoadingWindow(){bi.showWindow("replay-loading")}});const s=se(n,"#boost-pickup-filters-window-body"),a=se(n,"#touch-controls-window-body");bm=se(n,"#stats-window-layer"),yo=Q$({layer:bm,getReplayPlayer:()=>st,getStatsTimeline:()=>_o,getStatsFrameLookup:()=>go,getStatRegistry:()=>z_,readWindowPlacement:r9,applyWindowPlacement:o9,bringWindowToFront:bi.bringWindowToFront,setLauncherOpen:bi.setLauncherOpen,requestConfigSync:mn,watchGoalReplay:wl.watchGoalReplay,cueGoalReplay:wl.cueGoalReplay}),xm=se(n,"#toggle-playback"),wm=se(n,"#previous-frame"),Sm=se(n,"#next-frame"),Gu=se(n,"#playback-rate"),zi=uV({elements:{attachedPlayer:se(n,"#attached-player"),cameraViewFreeButton:se(n,"#camera-view-free"),cameraViewFollowButton:se(n,"#camera-view-follow"),cameraViewAutoPossession:se(n,"#camera-view-auto-possession"),cameraViewOverheadButton:se(n,"#camera-view-overhead"),cameraViewSideButton:se(n,"#camera-view-side"),usePlayerCameraSettings:se(n,"#use-player-camera-settings"),cameraSettingsControls:se(n,"#camera-settings-controls"),customCameraFov:se(n,"#custom-camera-fov"),customCameraHeight:se(n,"#custom-camera-height"),customCameraPitch:se(n,"#custom-camera-pitch"),customCameraDistance:se(n,"#custom-camera-distance"),customCameraStiffness:se(n,"#custom-camera-stiffness"),customCameraSwivelSpeed:se(n,"#custom-camera-swivel-speed"),customCameraTransitionSpeed:se(n,"#custom-camera-transition-speed"),customCameraFovReadout:se(n,"#custom-camera-fov-readout"),customCameraHeightReadout:se(n,"#custom-camera-height-readout"),customCameraPitchReadout:se(n,"#custom-camera-pitch-readout"),customCameraDistanceReadout:se(n,"#custom-camera-distance-readout"),customCameraStiffnessReadout:se(n,"#custom-camera-stiffness-readout"),customCameraSwivelSpeedReadout:se(n,"#custom-camera-swivel-speed-readout"),customCameraTransitionSpeedReadout:se(n,"#custom-camera-transition-speed-readout"),ballCamOffButton:se(n,"#ball-cam-off"),ballCamOnButton:se(n,"#ball-cam-on"),ballCamPlayerButton:se(n,"#ball-cam-player"),nameplateLift:se(n,"#custom-nameplate-lift"),nameplateLiftReadout:se(n,"#custom-nameplate-lift-readout"),cameraProfileReadout:se(n,"#camera-profile-readout"),cameraFovReadout:se(n,"#camera-fov-readout"),cameraHeightReadout:se(n,"#camera-height-readout"),cameraPitchReadout:se(n,"#camera-pitch-readout"),cameraBaseDistanceReadout:se(n,"#camera-base-distance-readout"),cameraStiffnessReadout:se(n,"#camera-stiffness-readout")},getReplayPlayer:()=>st,requestConfigSync:mn,onAutoPossessionChange(d){Ga?.syncSource(),d&&Ga?.syncCurrentFrame()}}),Ga=NV({getReplayPlayer:()=>st,getStatsTimeline:()=>_o,getCameraControlsController:()=>zi}),JE(se(n,"#touch-color-legend-body"),["team"]),mh=RW({elements:{summary:se(n,"#module-summary"),settings:se(n,"#module-settings"),boostPickupFilters:s,touchControls:a},modules:pd,boostPickupFilters:_f,getContext:vo,getTimelineSources:()=>iy(vo()),getActiveModules:()=>_n.getActiveModules(),getActiveCapabilityIds:e9,getBoostPickupAnimationEnabled:()=>st?.getState().boostPickupAnimationEnabled??!1,toggleCapability:Tw,toggleBoostPickupAnimation(){const d=!(st?.getState().boostPickupAnimationEnabled??!1);st?.setBoostPickupAnimationEnabled(d),gh(),Qa(),er(),mn()},syncTimelineEvents:Mw,syncTimelineRanges:yh,renderTimelineEventCount:to,requestConfigSync:mn}),vw=se(n,"#time-readout"),bw=se(n,"#frame-readout"),xw=se(n,"#duration-readout"),ww=se(n,"#playback-status-readout"),ea=se(n,"#status-readout"),x1=se(n,"#players-readout"),w1=se(n,"#frames-readout"),B_=se(n,"#events-readout"),$u=se(n,"#playback-rate-readout"),$a=se(n,"#skip-post-goal-transitions"),Wa=se(n,"#skip-kickoffs"),Tl=se(n,"#hitbox-wireframes"),Ml=se(n,"#hitbox-only-mode"),_h=G8({elements:{togglePlayback:xm,previousFrame:wm,nextFrame:Sm,playbackRate:Gu,playbackRateReadout:$u,skipPostGoalTransitions:$a,skipKickoffs:Wa,hitboxWireframes:Tl,hitboxOnlyMode:Ml,emptyState:F_,timeReadout:vw,frameReadout:bw,durationReadout:xw,playbackStatusReadout:ww},getFrameCount:()=>st?.replay.frameCount??0,getCameraControlsController:()=>zi}),El=N8({elements:{fps:se(n,"#recording-fps"),playbackRate:se(n,"#recording-playback-rate"),start:se(n,"#recording-start"),fullReplay:se(n,"#recording-full-replay"),stop:se(n,"#recording-stop"),download:se(n,"#recording-download"),clear:se(n,"#recording-clear"),status:se(n,"#recording-status"),elapsed:se(n,"#recording-elapsed"),size:se(n,"#recording-size"),type:se(n,"#recording-type")},getCanvasRecorder:()=>hh,getReplayPlayer:()=>st,getLoadedReplayName:()=>V_,setStatus(d){ea.textContent=d},requestConfigSync:mn}),Sw=s6({elements:{mechanic:se(n,"#missed-event-mechanic"),capture:se(n,"#missed-event-capture"),list:se(n,"#missed-event-list"),export:se(n,"#missed-event-export"),upload:se(n,"#missed-event-upload"),clear:se(n,"#missed-event-clear"),status:se(n,"#missed-event-status")},getReplayPlayer:()=>st,showWindow:()=>bi.showWindow("missed-events")}),md=l6({elements:{name:se(n,"#training-pack-name"),creator:se(n,"#training-pack-creator"),description:se(n,"#training-pack-description"),difficulty:se(n,"#training-pack-difficulty"),shooter:se(n,"#training-pack-shooter"),timeLimit:se(n,"#training-pack-time-limit"),capture:se(n,"#training-pack-capture"),load:se(n,"#training-pack-load"),loadInput:se(n,"#training-pack-load-input"),newPack:se(n,"#training-pack-new"),download:se(n,"#training-pack-download"),shotList:se(n,"#training-pack-shots"),status:se(n,"#training-pack-status")},getReplayPlayer:()=>st}),ia=G6({modules:pd,playbackRate:Gu,playbackRateReadout:$u,skipPostGoalTransitions:$a,skipKickoffs:Wa,hitboxWireframes:Tl,hitboxOnlyMode:Ml,getReplayPlayer:()=>st,getCameraControlsController:()=>zi,getRecordingWindowController:()=>El,getFloatingWindowController:()=>ra,getStatsWindowsController:()=>yo,getActiveModulesRuntime:()=>_n,getInitialConfig:()=>As,renderModuleSummary:Qa,renderModuleSettings:er,renderTimelineEventCount:to});const r=f1(window.location),o=YW(window.location);let l=null;if(e.initialConfig!==void 0)As=e.initialConfig;else{try{As=qW(window.location)}catch(d){l=d,console.error("Invalid stats player config:",d),ea.textContent=d instanceof Error?d.message:"Invalid stats player config",As=null}o&&R8(r,As,l)}const c=new AbortController;bi.installWindowDragging(pw,c.signal),bi.installWindowDragging(bm,c.signal);const u=()=>{c.abort(),fh?.(),fh=null,S1(),st?.destroy(),st=null,hh=null,ny=null,_o=null,go=null,z_=nc(),c9(),yo=null,_n.reset(),eo?.destroy(),eo=null,C1(),ac=null,sc=null,Hi?.reset(),Hi=null,V_=null,Ga?.reset(),Ga=null,zi=null,El=null,md=null,mh=null,H_=null,_h=null,_d?.destroy(),_d=null,As=null,ia?.reset(),ia=null,ra?.reset(),ra=null,Sl===n&&(Sl=null,n.replaceChildren()),Wu===u&&(Wu=null)};if(Wu=u,As){ia?.setApplyingConfig(!0);try{u9(As)}finally{ia?.setApplyingConfig(!1)}}return $8({elements:{root:n,launcherToggle:N_,launcherMenu:U_,loadReplayAction:fw,emptyLoadReplay:hw,fileInput:ph,togglePlayback:xm,previousFrame:wm,nextFrame:Sm,playbackRate:Gu,playbackRateReadout:$u,skipPostGoalTransitions:$a,skipKickoffs:Wa,hitboxWireframes:Tl,hitboxOnlyMode:Ml},signal:c.signal,setLauncherOpen:bi.setLauncherOpen,openReplayFilePicker:bi.openReplayFilePicker,getElementWindowId:bi.getElementWindowId,toggleWindow:p9,hideWindow:bi.hideWindow,createStatsWindow:l9,async loadReplayFile(d){try{Hi?.clearCurrentClip({resetReplayId:!0,render:!0}),await Ew(m8(d))}catch(h){console.error("Failed to load replay:",h),ea.textContent=h instanceof Error?h.message:"Failed to load replay"}},togglePlayback(){st?.togglePlayback(),mn()},stepFrames(d){st?.stepFrames(d),mn()},setPlaybackRate(d){st?.setPlaybackRate(d),mn()},setSkipPostGoalTransitionsEnabled(d){st?.setSkipPostGoalTransitionsEnabled(d),mn()},setSkipKickoffsEnabled(d){st?.setSkipKickoffsEnabled(d),mn()},setHitboxWireframesEnabled(d){st?.setHitboxWireframesEnabled(d),mn()},setHitboxOnlyModeEnabled(d){st?.setHitboxOnlyModeEnabled(d),mn()}}),Hi?.installEventListeners(c.signal),El?.installEventListeners(c.signal),Sw?.installEventListeners(c.signal),md?.installEventListeners(c.signal),zi?.installEventListeners(c.signal),K8({getReplayPlayer:()=>st,signal:c.signal}),window.addEventListener("message",d=>{if(d.origin!==window.location.origin)return;const h=d.data;!h||typeof h!="object"||h.source!=="rocket-sense"||h.type==="activateReviewItem"&&typeof h.index=="number"&&Number.isInteger(h.index)&&Hi?.activateItem(h.index)},{signal:c.signal}),Qa(),er(),oy(),zi?.renderProfile(),zi?.syncModeButtons(),R1(),to(),Hi?.render(),sy(),H6({signal:c.signal,location:window.location,statusReadout:ea,initialBundle:e.initialBundle,initialReplayName:e.initialReplayName,loadFromLocation:e.loadFromLocation,loadReplay:Ew,loadReplayBundleForDisplay:G_,getMechanicsReviewController:()=>Hi,showMechanicsReviewWindow(){bi.showWindow("mechanics-review")}}),{root:n,destroy:u}}export{b9 as mountStatEvaluationPlayer}; diff --git a/crates/rocket-sense-server/static/subtr-actor/assets/preload-helper-PPVm8Dsz.js b/crates/rocket-sense-server/static/subtr-actor/assets/preload-helper-PPVm8Dsz.js new file mode 100644 index 00000000..f5001933 --- /dev/null +++ b/crates/rocket-sense-server/static/subtr-actor/assets/preload-helper-PPVm8Dsz.js @@ -0,0 +1 @@ +const p="modulepreload",y=function(u,i){return new URL(u,i).href},v={},w=function(i,a,f){let d=Promise.resolve();if(a&&a.length>0){let E=function(e){return Promise.all(e.map(o=>Promise.resolve(o).then(s=>({status:"fulfilled",value:s}),s=>({status:"rejected",reason:s}))))};const r=document.getElementsByTagName("link"),t=document.querySelector("meta[property=csp-nonce]"),m=t?.nonce||t?.getAttribute("nonce");d=E(a.map(e=>{if(e=y(e,f),e in v)return;v[e]=!0;const o=e.endsWith(".css"),s=o?'[rel="stylesheet"]':"";if(f)for(let c=r.length-1;c>=0;c--){const l=r[c];if(l.href===e&&(!o||l.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${e}"]${s}`))return;const n=document.createElement("link");if(n.rel=o?"stylesheet":p,o||(n.as="script"),n.crossOrigin="",n.href=e,m&&n.setAttribute("nonce",m),document.head.appendChild(n),o)return new Promise((c,l)=>{n.addEventListener("load",c),n.addEventListener("error",()=>l(new Error(`Unable to preload CSS for ${e}`)))})}))}function h(r){const t=new Event("vite:preloadError",{cancelable:!0});if(t.payload=r,window.dispatchEvent(t),!t.defaultPrevented)throw r}return d.then(r=>{for(const t of r||[])t.status==="rejected"&&h(t.reason);return i().catch(h)})};export{w as _}; diff --git a/crates/rocket-sense-server/static/subtr-actor/assets/replayLoader.worker-BOmyAjmY.js b/crates/rocket-sense-server/static/subtr-actor/assets/replayLoader.worker-BOmyAjmY.js new file mode 100644 index 00000000..34a9e71b --- /dev/null +++ b/crates/rocket-sense-server/static/subtr-actor/assets/replayLoader.worker-BOmyAjmY.js @@ -0,0 +1,2 @@ +(function(){"use strict";function be(e,t,n,r){const o=pe(e,u.__wbindgen_malloc),i=x,a=u.get_replay_bundle_json_parts_with_progress(o,i,t,k(n)?4294967297:n>>>0,k(r)?4294967297:r>>>0);if(a[2])throw G(a[1]);return G(a[0])}function ge(){return{__proto__:null,"./rl_replay_subtr_actor_bg.js":{__proto__:null,__wbg_Error_8c4e43fe74559d73:function(t,n){return Error(P(t,n))},__wbg_Number_04624de7d0e8332d:function(t){return Number(t)},__wbg_String_8f0eb39a4a4c2f66:function(t,n){const r=String(n),o=F(r,u.__wbindgen_malloc,u.__wbindgen_realloc),i=x;y().setInt32(t+4,i,!0),y().setInt32(t+0,o,!0)},__wbg___wbindgen_bigint_get_as_i64_8fcf4ce7f1ca72a2:function(t,n){const r=n,o=typeof r=="bigint"?r:void 0;y().setBigInt64(t+8,k(o)?BigInt(0):o,!0),y().setInt32(t+0,!k(o),!0)},__wbg___wbindgen_boolean_get_bbbb1c18aa2f5e25:function(t){const n=t,r=typeof n=="boolean"?n:void 0;return k(r)?16777215:r?1:0},__wbg___wbindgen_debug_string_0bc8482c6e3508ae:function(t,n){const r=U(n),o=F(r,u.__wbindgen_malloc,u.__wbindgen_realloc),i=x;y().setInt32(t+4,i,!0),y().setInt32(t+0,o,!0)},__wbg___wbindgen_in_47fa6863be6f2f25:function(t,n){return t in n},__wbg___wbindgen_is_bigint_31b12575b56f32fc:function(t){return typeof t=="bigint"},__wbg___wbindgen_is_function_0095a73b8b156f76:function(t){return typeof t=="function"},__wbg___wbindgen_is_object_5ae8e5880f2c1fbd:function(t){const n=t;return typeof n=="object"&&n!==null},__wbg___wbindgen_is_string_cd444516edc5b180:function(t){return typeof t=="string"},__wbg___wbindgen_is_undefined_9e4d92534c42d778:function(t){return t===void 0},__wbg___wbindgen_jsval_eq_11888390b0186270:function(t,n){return t===n},__wbg___wbindgen_jsval_loose_eq_9dd77d8cd6671811:function(t,n){return t==n},__wbg___wbindgen_number_get_8ff4255516ccad3e:function(t,n){const r=n,o=typeof r=="number"?r:void 0;y().setFloat64(t+8,k(o)?0:o,!0),y().setInt32(t+0,!k(o),!0)},__wbg___wbindgen_string_get_72fb696202c56729:function(t,n){const r=n,o=typeof r=="string"?r:void 0;var i=k(o)?0:F(o,u.__wbindgen_malloc,u.__wbindgen_realloc),a=x;y().setInt32(t+4,a,!0),y().setInt32(t+0,i,!0)},__wbg___wbindgen_throw_be289d5034ed271b:function(t,n){throw new Error(P(t,n))},__wbg_call_389efe28435a9388:function(){return E(function(t,n){return t.call(n)},arguments)},__wbg_call_4708e0c13bdc8e95:function(){return E(function(t,n,r){return t.call(n,r)},arguments)},__wbg_done_57b39ecd9addfe81:function(t){return t.done},__wbg_entries_58c7934c745daac7:function(t){return Object.entries(t)},__wbg_error_7534b8e9a36f1ab4:function(t,n){let r,o;try{r=t,o=n,console.error(P(t,n))}finally{u.__wbindgen_free(r,o,1)}},__wbg_get_9b94d73e6221f75c:function(t,n){return t[n>>>0]},__wbg_get_b3ed3ad4be2bc8ac:function(){return E(function(t,n){return Reflect.get(t,n)},arguments)},__wbg_get_with_ref_key_1dc361bd10053bfe:function(t,n){return t[n]},__wbg_instanceof_ArrayBuffer_c367199e2fa2aa04:function(t){let n;try{n=t instanceof ArrayBuffer}catch{n=!1}return n},__wbg_instanceof_Map_53af74335dec57f4:function(t){let n;try{n=t instanceof Map}catch{n=!1}return n},__wbg_instanceof_Uint8Array_9b9075935c74707c:function(t){let n;try{n=t instanceof Uint8Array}catch{n=!1}return n},__wbg_isArray_d314bb98fcf08331:function(t){return Array.isArray(t)},__wbg_isSafeInteger_bfbc7332a9768d2a:function(t){return Number.isSafeInteger(t)},__wbg_iterator_6ff6560ca1568e55:function(){return Symbol.iterator},__wbg_length_32ed9a279acd054c:function(t){return t.length},__wbg_length_35a7bace40f36eac:function(t){return t.length},__wbg_log_f1a1b5cd3f9c7822:function(t,n){console.log(P(t,n))},__wbg_new_361308b2356cecd0:function(){return new Object},__wbg_new_3eb36ae241fe6f44:function(){return new Array},__wbg_new_8a6f238a6ece86ea:function(){return new Error},__wbg_new_dca287b076112a51:function(){return new Map},__wbg_new_dd2b680c8bf6ae29:function(t){return new Uint8Array(t)},__wbg_new_from_slice_a3d2629dc1826784:function(t,n){return new Uint8Array(Z(t,n))},__wbg_next_3482f54c49e8af19:function(){return E(function(t){return t.next()},arguments)},__wbg_next_418f80d8f5303233:function(t){return t.next},__wbg_prototypesetcall_bdcdcc5842e4d77d:function(t,n,r){Uint8Array.prototype.set.call(Z(t,n),r)},__wbg_push_8ffdcb2063340ba5:function(t,n){return t.push(n)},__wbg_set_1eb0999cf5d27fc8:function(t,n,r){return t.set(n,r)},__wbg_set_3f1d0b984ed272ed:function(t,n,r){t[n]=r},__wbg_set_6cb8631f80447a67:function(){return E(function(t,n,r){return Reflect.set(t,n,r)},arguments)},__wbg_set_f43e577aea94465b:function(t,n,r){t[n>>>0]=r},__wbg_stack_0ed75d68575b0f3c:function(t,n){const r=n.stack,o=F(r,u.__wbindgen_malloc,u.__wbindgen_realloc),i=x;y().setInt32(t+4,i,!0),y().setInt32(t+0,o,!0)},__wbg_value_0546255b415e96c1:function(t){return t.value},__wbindgen_cast_0000000000000001:function(t){return t},__wbindgen_cast_0000000000000002:function(t){return t},__wbindgen_cast_0000000000000003:function(t,n){return P(t,n)},__wbindgen_cast_0000000000000004:function(t){return BigInt.asUintN(64,t)},__wbindgen_init_externref_table:function(){const t=u.__wbindgen_externrefs,n=t.grow(4);t.set(0,void 0),t.set(n+0,void 0),t.set(n+1,null),t.set(n+2,!0),t.set(n+3,!1)}}}}function ye(e){const t=u.__externref_table_alloc();return u.__wbindgen_externrefs.set(t,e),t}function U(e){const t=typeof e;if(t=="number"||t=="boolean"||e==null)return`${e}`;if(t=="string")return`"${e}"`;if(t=="symbol"){const o=e.description;return o==null?"Symbol":`Symbol(${o})`}if(t=="function"){const o=e.name;return typeof o=="string"&&o.length>0?`Function(${o})`:"Function"}if(Array.isArray(e)){const o=e.length;let i="[";o>0&&(i+=U(e[0]));for(let a=1;a1)r=n[1];else return toString.call(e);if(r=="Object")try{return"Object("+JSON.stringify(e)+")"}catch{return"Object"}return e instanceof Error?`${e.name}: ${e.message} +${e.stack}`:r}function Z(e,t){return e=e>>>0,O().subarray(e/1,e/1+t)}let T=null;function y(){return(T===null||T.buffer.detached===!0||T.buffer.detached===void 0&&T.buffer!==u.memory.buffer)&&(T=new DataView(u.memory.buffer)),T}function P(e,t){return e=e>>>0,we(e,t)}let B=null;function O(){return(B===null||B.byteLength===0)&&(B=new Uint8Array(u.memory.buffer)),B}function E(e,t){try{return e.apply(this,t)}catch(n){const r=ye(n);u.__wbindgen_exn_store(r)}}function k(e){return e==null}function pe(e,t){const n=t(e.length*1,1)>>>0;return O().set(e,n/1),x=e.length,n}function F(e,t,n){if(n===void 0){const s=D.encode(e),l=t(s.length,1)>>>0;return O().subarray(l,l+s.length).set(s),x=s.length,l}let r=e.length,o=t(r,1)>>>0;const i=O();let a=0;for(;a127)break;i[o+a]=s}if(a!==r){a!==0&&(e=e.slice(a)),o=n(o,r,r=a+e.length*3,1)>>>0;const s=O().subarray(o+a,o+r),l=D.encodeInto(e,s);a+=l.written,o=n(o,r,a,1)>>>0}return x=a,o}function G(e){const t=u.__wbindgen_externrefs.get(e);return u.__externref_table_dealloc(e),t}let z=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});z.decode();const he=2146435072;let H=0;function we(e,t){return H+=t,H>=he&&(z=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),z.decode(),H=t),z.decode(O().subarray(e,e+t))}const D=new TextEncoder;"encodeInto"in D||(D.encodeInto=function(e,t){const n=D.encode(e);return t.set(n),{read:e.length,written:n.length}});let x=0,u;function ke(e,t){return u=e.exports,T=null,B=null,u.__wbindgen_start(),u}async function xe(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(o){if(e.ok&&n(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",o);else throw o}const r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{const r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}async function Ae(e){if(u!==void 0)return u;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0&&(e=new URL(""+new URL("rl_replay_subtr_actor_bg-BjSK7HJ9.wasm",self.location.href).href,self.location.href));const t=ge();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));const{instance:n,module:r}=await xe(await e,t);return ke(n)}const q="octane",Te={breakout:{kind:"breakout",label:"Breakout",length:131.4924,width:80.521,height:30.3,slopeDegrees:-.9795,groundHeightFront:43.8976,groundHeightBack:46.1454,offset:13.88,elevation:17.05},dominus:{kind:"dominus",label:"Dominus",length:127.9268,width:83.27995,height:31.3,slopeDegrees:-.9635,groundHeightFront:47.2238,groundHeightBack:49.3749,offset:13.88,elevation:17.05},hybrid:{kind:"hybrid",label:"Hybrid",length:127.0192,width:82.18787,height:34.15907,slopeDegrees:-.5499,groundHeightFront:54.0982,groundHeightBack:55.3173,offset:13.88,elevation:17.05},merc:{kind:"merc",label:"Merc",length:120.72,width:76.71,height:41.66,slopeDegrees:.28,groundHeightFront:60.76,groundHeightBack:61.35,offset:13.88,elevation:17.05},octane:{kind:"octane",label:"Octane",length:118.0074,width:84.19941,height:36.15907,slopeDegrees:-.5518,groundHeightFront:55.1449,groundHeightBack:56.2814,offset:13.88,elevation:17.05},plank:{kind:"plank",label:"Plank",length:128.8198,width:84.67036,height:29.3944,slopeDegrees:-.3447,groundHeightFront:44.998,groundHeightBack:45.773,offset:13.88,elevation:17.05}},Se={"16batmobile":"plank","70dodgechargerrt":"dominus","89batmobile":"dominus","99nissanskylinegtrr34":"hybrid",aftershock:"dominus",animusgp:"breakout",artemis:"plank",artemisg1:"plank",artemisgxt:"plank",astonmartinvalhalla:"breakout",backfire:"octane",backtothefuturetimemachine:"dominus",batmobile1989:"dominus",battlebus:"merc",breakout:"breakout",breakouttypes:"breakout",centio:"plank",centiov17:"plank",cyclone:"breakout",deloreantimemachine:"dominus",diestro:"dominus",dominus:"dominus",dominusgt:"dominus",endo:"hybrid",esper:"hybrid",fast4wd:"octane",fennec:"octane",gazellagt:"dominus",gizmo:"octane",grog:"octane",guardian:"dominus",guardiang1:"dominus",guardiangxt:"dominus",hotshot:"dominus",icecharger:"dominus",imperatordt5:"dominus",jager619rs:"hybrid",jurassicjeepwrangler:"octane",mantis:"plank",marauder:"octane",masamune:"dominus",maverick:"dominus",maverickg1:"dominus",maverickgxt:"dominus",mclaren570s:"dominus",merc:"merc",mr11:"dominus",nimbus:"hybrid",octane:"octane",octanezsr:"octane",paladin:"plank",proteus:"octane",ripper:"dominus",roadhog:"octane",roadhogxl:"octane",samurai:"breakout",scarab:"octane",takumi:"octane",takumirxt:"octane",thedarkknightstumbler:"octane",thedarkknightrisestumbler:"octane",triton:"octane",twinmilliii:"plank",twinzer:"octane",venom:"hybrid",vulcan:"octane",werewolf:"dominus",xdevil:"hybrid",xdevilmk2:"hybrid",zippy:"octane","1966cadillacdeville":"breakout",ace:"breakout",admiral:"dominus",azura:"breakout",behemoth:"merc",beskar:"hybrid",bmwm3e30:"dominus",bmwm2racing:"dominus",bmwm4gt3evo:"dominus",bmw1series:"octane",bmw1seriesrle:"octane",bmwm240i:"dominus",bugatticentodieci:"plank",bumblebee:"dominus",bumblebeecar:"dominus",chevroletastro:"merc",chevroletcorvettestingray:"breakout",chevroletcorvettezr1:"breakout",chryslerpacifica:"hybrid",corlay:"octane",cyberpunkquadra:"breakout",defenderd7xr:"merc",diesel:"breakout",dodgechargerdaytonascatpack:"dominus",dodgerchargerdaytonascatpack:"dominus",dominusneon:"dominus",emperor:"breakout",emperorii:"breakout",emperoriifrozen:"breakout",emperoriiscorched:"breakout",fastfuriousdodgecharger:"dominus",fastandfuriousdodgecharger:"dominus",fastandfuriousdodgechargersrthellcat:"dominus",fastfuriousmazdarx7:"breakout",fastandfuriousmazdarx7:"breakout",fastfuriousnissanskyline:"hybrid",fastandfuriousnissanskyline:"hybrid",fastfuriouspontiacfiero:"hybrid",fastandfuriouspontiacfiero:"hybrid",fenneczrf:"octane",ferrari296gtb:"dominus",ferrarif40:"breakout",fordbroncoraptorrle:"merc",fordf150rle:"octane",fordmustanggtd:"dominus",fordmustangshelbygt500:"dominus",fordmustangmacherle:"octane",fordmustangshelbygt350rrle:"dominus",formula12021:"plank",formula12022:"plank",fuse:"breakout",havoc:"breakout",hearse:"hybrid",homerscar:"dominus",hondacivictyper:"octane",hondacivictyperle:"octane",jackal:"octane",jeepwranglerrubicon:"octane",kitt:"dominus",knightindustries2000:"dominus",komodo:"breakout",lamborghinicountachlpi8004:"dominus",lamborghinihuracansto:"dominus",lamborghiniurus:"hybrid",lamborghiniurusse:"hybrid",lightningmcqueen:"dominus",lightningmcqueencar:"dominus",lockjaw:"dominus",luiginsr:"octane",maestro:"dominus",magnifique:"dominus",magnifiquegxt:"dominus",mako:"breakout",mamba:"dominus",mario:"octane",marionsr:"octane",maven:"dominus",mclaren765lt:"dominus",mclarenp1:"dominus",mclarensenna:"breakout",megastar:"breakout",mercedesamggt63s:"dominus",mercedesbenzcla:"dominus",mudcat:"octane",mudcatg1:"octane",mudcatgxt:"octane",nissan350z:"dominus",nissanfairladyz:"dominus",nissanfairladyzrle:"dominus",nissansilvia:"hybrid",nissansilviarle:"hybrid",nissanskylinegtr:"hybrid",nissanskylinegtrr32:"hybrid",nissanzperformance:"dominus",nissanzperformancecar:"dominus",outlaw:"octane",outlawgxt:"octane",pattywagon:"octane",pizzaplanetdeliverytruck:"merc",pontiacfirebird:"breakout",porsche918spyder:"breakout",porsche911gt3rs:"dominus",porsche911turbo:"dominus",porsche911turborle:"dominus",primo:"hybrid",psyclops:"octane",quadraturbor:"breakout",ram1500rho:"hybrid",recoilav:"merc",redline:"breakout",revolver:"breakout",rivianr1s:"hybrid",scorpion:"dominus",shokunin:"octane",shokuningxt:"octane",stampede:"merc",teslacybertruck:"hybrid",themysterymachine:"merc",theincredibile:"breakout",turtlevan:"merc",voidburn:"hybrid",volkswagengolfgti:"octane",volkswagengolfgtirle:"octane",xentari:"octane",zefira:"dominus",breakoutx:"breakout",nexus:"breakout",nexussc:"breakout",whiplash:"breakout","007sastonmartindbs":"dominus","007sastonmartinvalhalla":"dominus",batmobile2022:"dominus",chikara:"dominus",chikarag1:"dominus",chikaragxt:"dominus",ecto1:"dominus",ecto1ghostbusters:"dominus",fastfuriousdodgechargersrthellcat:"dominus",gazellagthotwheels:"dominus",kittknightrider:"dominus",lamborghinihuracnsto:"dominus",mr11hotwheels:"dominus",nascarchevroletcamaro:"dominus",nascarfordmustang:"dominus",nascartoyotacamry:"dominus",nascarnextgenchevroletcamaro:"dominus",nascarnextgenchevroletcamaro2022:"dominus",nascarnextgenfordmustang:"dominus",nascarnextgenfordmustang2022:"dominus",nascarnextgentoyotacamry:"dominus",nascarnextgentoyotacamry2022:"dominus",nemesis:"dominus",peregrinett:"dominus",perigrinett:"dominus",ronin:"dominus",roning1:"dominus",roningxt:"dominus",samusgunship:"dominus",samusgunshipnintendoexclusive:"dominus",tyranno:"dominus",tyrannogxt:"dominus",insidio:"hybrid",jager619:"hybrid",jger619:"hybrid",jger619rs:"hybrid",r3mx:"hybrid",r3mxgxt:"hybrid",tygris:"hybrid",nomad:"merc",nomadgxt:"merc","007sastonmartindb5":"octane",armadillo:"octane",armadilloxboxexclusive:"octane",boneshaker:"octane",dingo:"octane",fast4wdhotwheels:"octane",harbinger:"octane",harbingergxt:"octane",hogsticker:"octane",hogstickerxboxexclusive:"octane",sweettooth:"octane",sweettoothplaystationexclusive:"octane",thedarkknighttumbler:"octane",batmobile2016:"plank",sentinel:"plank"};function ve(e){const t={};for(const[n,r]of e)for(const o of n)t[o]=r;return t}const Oe=ve([[[22,1416,1894,1932,3031,3311,6243,6489,7651,7696,7890,7901,8006,8360,8361,8565,8566,8669,9357,10697,10698,10817,10822,11038,11394,11505,11677,11800,11933,11949,12173,12315,12361,12484],"breakout"],[[29,403,597,600,1018,1171,1286,1675,1689,1883,2070,2268,2666,2950,2951,3155,3156,3157,3265,3426,3875,3879,3880,4014,4155,4367,4472,4473,4745,4770,4781,4861,4864,5709,5773,5823,5858,5964,5979,6122,6244,6247,6260,6836,7211,7337,7338,7341,7343,7415,7512,7532,7593,7772,8454,9053,9088,9089,9140,9388,9894,10094,10440,10441,10694,10695,11016,11095,11315,11336,11534,11941,11996,12106,12142,12262,12286,12325,12382,12563,12669],"dominus"],[[28,31,1159,1317,1624,1856,2269,3451,3582,3702,5470,5488,5879,7012,9084,9085,9427,10044,10805,11138,11141,11379,11932,12569,12652],"hybrid"],[[30,4780,7336,7477,7815,7979,10689,11098,11736,11905,11950,12318,12335],"merc"],[[21,23,25,26,27,402,404,523,607,625,723,1172,1295,1300,1475,1478,1533,1568,1623,2665,2853,2919,2949,4284,4318,4319,4320,4782,4906,5020,5039,5188,5361,5547,5713,5837,5951,6939,7947,7948,8383,8806,8807,10896,10897,10900,10901,11314,11603,12104,12105],"octane"],[[24,803,1603,1691,1919,3594,3614,3622,4268,5265,7052,8524],"plank"]]);function J(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function Q(e){if(!e)return null;switch(J(e)){case"breakout":return"breakout";case"dominus":return"dominus";case"hybrid":return"hybrid";case"merc":return"merc";case"octane":return"octane";case"batmobile":case"plank":return"plank";default:return null}}function ee(e){return e?Se[J(e)]??null:null}function Ie(e){return Q(e)??ee(e)}function Pe(e){return Te[e]}function Y(e,t){if(!(!e||typeof e!="object")){if("Str"in e&&typeof e.Str=="string"){t.push(e.Str);return}if("Name"in e&&typeof e.Name=="string"){t.push(e.Name);return}if("Byte"in e&&e.Byte&&typeof e.Byte=="object"){const n=e.Byte;typeof n.kind=="string"&&t.push(n.kind),typeof n.value=="string"&&t.push(n.value);return}if("Struct"in e&&e.Struct&&typeof e.Struct=="object"){const n=e.Struct;if(typeof n.name=="string"&&t.push(n.name),Array.isArray(n.fields))for(const r of n.fields)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),Y(r[1],t));return}if("Array"in e&&Array.isArray(e.Array)){for(const n of e.Array)if(Array.isArray(n))for(const r of n)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),Y(r[1],t))}}}function Be(e){const t=Q(e?.car_hitbox_family);if(t)return t;const n=e?.car_body_id;if(typeof n=="number"){const a=Oe[n];if(a)return a}const r=ee(e?.car_body_name);if(r)return r;const o=e?.stats;if(!o)return q;const i=[];for(const[a,s]of Object.entries(o))i.push(a),Y(s,i);for(const a of i){const s=Ie(a);if(s)return s}return q}function A(e){const[t,n]=Object.entries(e)[0]??["Unknown","unknown"];return typeof n=="string"||typeof n=="number"?`${t}:${n}`:n&&typeof n=="object"?`${t}:${JSON.stringify(n)}`:`${t}:${JSON.stringify(n)}`}function N(e,t){return Math.max(0,e-t)}function te(e){return new Map(e.map(t=>[t.id,t]))}const p=70,ne=73,Ee=3072,De=4096,Ne=1792,Me=4184,Re=940,Fe=3308,ze=2816,re=3584,Ce=2484,je=1788,Le=2300,Ve=2048,Ue=1036,He=1024,Ye=1024,$e=4240,oe=34;function C(e,t,n,r,o){e.push({index:e.length,padId:null,size:o,position:{x:t,y:n,z:r},events:[]})}function j(e,t,n,r,o){C(e,-t,n,r,o),C(e,t,n,r,o)}function $(e,t,n,r,o){C(e,t,-n,r,o),C(e,t,n,r,o)}function I(e,t,n,r,o){j(e,t,-n,r,o),j(e,t,n,r,o)}function Xe(){const e=[];return $(e,0,$e,p,"small"),I(e,Ne,Me,p,"small"),I(e,Ee,De,ne,"big"),I(e,Re,Fe,p,"small"),$(e,0,ze,p,"small"),I(e,re,Ce,p,"small"),I(e,je,Le,p,"small"),I(e,Ve,Ue,p,"small"),$(e,0,Ye,p,"small"),j(e,re,0,ne,"big"),j(e,He,0,p,"small"),e}function X(e){if(e==="Available")return!0;if(e&&typeof e=="object"){if("Available"in e)return!0;if("PickedUp"in e)return!1;const t=e.kind;if(t==="Available")return!0;if(t==="PickedUp")return!1}return null}function We(e){return e==="big"||e==="Big"?"big":e==="small"||e==="Small"?"small":null}function Ke(e){let t=null;for(const n of e){const r=X(n.kind);if(r===!1){t=n.time;continue}if(r===!0&&t!==null)return n.time-t>=7?"big":"small"}return null}function Ze(e,t,n,r){const o=te(t),i=new Map;for(const c of e.boost_pad_events??[]){if(X(c.kind)===null){r?.advance();continue}const d=i.get(c.pad_id);d?d.push(c):i.set(c.pad_id,[c]),r?.advance()}const a=e.boost_pads;if(!a||a.length===0)return r?.advance(oe),Xe();const s=[...a].sort((c,f)=>c.index-f.index),l=new Array(s.length);for(let c=0;c=72?"big":"small"),h=g.sort((_,w)=>_.time-w.time),m=new Array(h.length);for(let _=0;_=0?e.frame:null}function Ge(e,t){if(typeof e.time=="number"&&Number.isFinite(e.time))return e.time;const n=W(e);if(n===null)return null;const r=t.frame_data.metadata_frames[n]?.time;return typeof r=="number"&&Number.isFinite(r)?r:null}function qe(e,t){return`bookmark:${W(e)??"unknown"}:${e.description||"tick-mark"}:${t}`}function Je(e,t,n){return(e.replay_tick_marks??[]).flatMap((r,o)=>{n?.advance();const i=Ge(r,e);return i===null?[]:[{id:qe(r,o),description:r.description,frame:W(r),time:N(i,t)}]})}function Qe(e){const t=e.description.trim()||"Replay bookmark";return{id:e.id,time:e.time,seekTime:e.time,frame:e.frame??void 0,kind:"bookmark",label:t,shortLabel:"BM",iconName:"bookmark"}}const S={distance:270,height:100,pitch:-4,fov:110},et=.005,tt=Number.POSITIVE_INFINITY,nt=!0,rt=.15,ot=10,at=.1,it=10;function ae(e){const t=Math.hypot(e.x,e.y,e.z);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t}}function ie(e){const t=Math.hypot(e.x,e.y,e.z,e.w);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t,w:e.w/t}}function se(e,t){return{w:e.w*t.w-e.x*t.x-e.y*t.y-e.z*t.z,x:e.w*t.x+e.x*t.w+e.y*t.z-e.z*t.y,y:e.w*t.y-e.x*t.z+e.y*t.w+e.z*t.x,z:e.w*t.z+e.x*t.y-e.y*t.x+e.z*t.w}}function ce(e,t){const n=se(se(t,{x:e.x,y:e.y,z:e.z,w:0}),{x:-t.x,y:-t.y,z:-t.z,w:t.w});return{x:n.x,y:n.y,z:n.z}}function st(e){if(e==="Empty")return{position:null,linearVelocity:null,angularVelocity:null,rotation:null};const t=e.Data.rigid_body;return{position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:ie(t.rotation)}}function ue(e){return e==null?null:Math.max(-1,Math.min(1,(e-128)/128))}function le(e){return e==null?null:(e>127?e-256:e)*Math.PI/128}function de(e){return e?{x:e[0],y:e[1],z:e[2]}:null}const ct={cameraPitch:null,cameraYaw:null,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null};function ut(e){if(e==="Empty")return{isPresent:!1,position:null,linearVelocity:null,angularVelocity:null,rotation:null,forward:null,up:null,boostAmount:0,boostFraction:0,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,...ct};const t=e.Data.rigid_body,n=ie(t.rotation),r=n?ae(ce({x:1,y:0,z:0},n)):null,o=n?ae(ce({x:0,y:0,z:1},n)):null,i=e.Data.camera,a=e.Data.input;return{isPresent:!0,position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:n,forward:r,up:o,boostAmount:e.Data.boost_amount,boostFraction:Math.max(0,Math.min(1,e.Data.boost_amount/255)),boostActive:e.Data.boost_active,powerslideActive:e.Data.powerslide_active,jumpActive:e.Data.jump_active,doubleJumpActive:e.Data.double_jump_active,dodgeActive:e.Data.dodge_active,cameraPitch:le(i?.pitch),cameraYaw:le(i?.yaw),throttle:ue(a?.throttle),steer:ue(a?.steer),dodgeImpulse:de(a?.dodge_impulse),dodgeTorque:de(a?.dodge_torque)}}function lt(e){return e.position!==null}function dt(e){return{...e,isPresent:!1,linearVelocity:null,angularVelocity:null,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null}}function ft(e){let t=null,n=null;for(let r=0;r=t.length-1)return;let o=M(t[r].position);for(let i=r+1;iat){o=M(s.position);continue}if(mt(o,s.position)>it){o=M(s.position);continue}const d={x:(a.linearVelocity.x+s.linearVelocity.x)/2,y:(a.linearVelocity.y+s.linearVelocity.y)/2,z:(a.linearVelocity.z+s.linearVelocity.z)/2},g={x:o.x+d.x*f,y:o.y+d.y*f,z:o.z+d.z*f},b=(i-r)%n.smoothingAnchorInterval===0?.5:n.smoothingBlendFactor;o={x:g.x*(1-b)+s.position.x*b,y:g.y*(1-b)+s.position.y*b,z:g.z*(1-b)+s.position.z*b},s.position=M(o)}}function _t(e){return{motionSmoothing:e.motionSmoothing??nt,smoothingBlendFactor:e.smoothingBlendFactor??rt,smoothingAnchorInterval:Math.max(1,e.smoothingAnchorInterval??ot)}}function _e(){return typeof performance>"u"?Date.now():performance.now()}function bt(e){const t=e.meta.team_zero.length+e.meta.team_one.length,n=e.frame_data.players.reduce((a,[,s])=>a+s.frames.length,0),r=e.boost_pads?.length??oe,o=e.boost_pad_events?.length??0,i=(e.goal_events?.length??0)+(e.player_stat_events?.length??0)+(e.demolish_infos?.length??0)+(e.replay_tick_marks?.length??0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,n),Math.max(1,e.frame_data.ball_data.frames.length),Math.max(1,r+o),Math.max(1,i)].reduce((a,s)=>a+s,0)}function gt(e){const t=e.frame_data.players.reduce((n,[,r])=>n+r.frames.length,0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,e.frame_data.ball_data.frames.length)].reduce((n,r)=>n+r,0)}function yt(e,t,n={}){const r=bt(e),o=gt(e);let i=0,a=0,s=-1,l=-1,c=_e();const f=n.yieldEveryMs??Number.POSITIVE_INFINITY,d=n.progressReportMinDelta??et,g=Math.max(1,n.progressReportFrameInterval??tt),b=()=>{if(!t)return!1;const m=Math.max(0,Math.min(1,i/r));if(m<=s)return!1;const w=a-l>=g;return m>=1||m-s>=d||w?(s=m,l=a,t(m,{progress:m,processedFrames:Math.min(a,o),totalFrames:o,processedUnits:i,totalUnits:r}),!0):!1},h=(m=!1)=>{const _=_e();return!m&&_-cr===t)?.[1];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function kt(e){const t=wt(e?.stats);return{fov:v(t,"CameraFOV")??S.fov,height:v(t,"CameraHeight")??S.height,pitch:v(t,"CameraPitch")??S.pitch,distance:v(t,"CameraDistance")??S.distance,stiffness:v(t,"CameraStiffness")??S.stiffness,swivelSpeed:v(t,"CameraSwivelSpeed")??S.swivelSpeed,transitionSpeed:v(t,"CameraTransitionSpeed")??S.transitionSpeed}}function xt(e,t){const n=new Map,r=new Map,o=[...e.meta.team_zero,...e.meta.team_one];if(o.length===0)return t?.advance(),{byId:n,byName:r};for(const i of o)r.set(i.name,i),i.remote_id&&n.set(A(i.remote_id),i),t?.advance();return{byId:n,byName:r}}function At(e){const t=new Map;for(const[n,r]of e.player_camera_events??[])t.set(A(n),r.map(o=>({frame:o.frame,ballCamActive:o.ball_cam_active,behindViewActive:o.behind_view_active,driving:o.driving})));return t}function Tt(e,t){const n=new Set(e.meta.team_zero.map(l=>l.name)),r=new Set(e.meta.team_one.map(l=>l.name)),o=xt(e,t),i=At(e),a=[];let s=0;for(const[l,c]of e.frame_data.players){const f=new Array(c.frames.length);let d;for(let m=0;mt.time!==n.time?t.time-n.time:(t.frame??0)-(n.frame??0))}function Ot(e,t,n){const r=e.player?A(e.player):null,o=r?t.get(r)?.name??r:null,i=o?`${o} scored`:"Goal";return{id:K("goal",e.frame,r??"team"),time:N(e.time,n),frame:e.frame,kind:"goal",label:i,shortLabel:"G",playerId:r,playerName:o,isTeamZero:e.scoring_team_is_team_0}}function It(e,t,n){const r=A(e.player),o=t.get(r)?.name??r,i=e.kind.toLowerCase(),a=e.kind==="Shot"?"shot":e.kind==="Save"?"save":"assist",s=e.kind==="Shot"?"SH":e.kind==="Save"?"SV":"A";return{id:K(i,e.frame,r),time:N(e.time,n),frame:e.frame,kind:i,label:`${o} ${a}`,shortLabel:s,playerId:r,playerName:o,location:e.shot?.shot_touch_position??e.shot?.ball_position??null,shot:e.shot??null,isTeamZero:e.is_team_0}}function Pt(e,t,n){const r=A(e.attacker),o=A(e.victim),i=t.get(r),a=t.get(o);return{id:K("demo",e.frame,`${r}:${o}`),time:N(e.time,n),frame:e.frame,kind:"demo",label:`${i?.name??r} demoed ${a?.name??o}`,shortLabel:"D",playerId:r,playerName:i?.name??r,secondaryPlayerId:o,secondaryPlayerName:a?.name??o,location:e.victim_location,isTeamZero:i?.isTeamZero??null}}function Bt(e,t,n,r,o){const i=te(t),a=[];for(const s of e.goal_events??[])a.push(Ot(s,i,r)),o?.advance();for(const s of e.player_stat_events??[])a.push(It(s,i,r)),o?.advance();for(const s of e.demolish_infos??[])a.push(Pt(s,i,r)),o?.advance();for(const s of n)a.push(Qe(s));return a.length===0&&o?.advance(),vt(a)}function Et(e,t={}){const n=yt(e,t.onProgress,{progressReportMinDelta:t.progressReportMinDelta,progressReportFrameInterval:t.progressReportFrameInterval}),r=e.frame_data.metadata_frames[0]?.time??0,o=pt(e,n),i=Tt(e,n),a=St(e,n),s=_t(t);me(o,a,s);for(const d of i)me(o,d.frames,s);const l=Ze(e,i,r,n),c=Je(e,r,n),f=Bt(e,i,c,r,n);return n.finish(),{frameCount:o.length,duration:o.at(-1)?.time??0,rawStartTime:r,frames:o,ballFrames:a,boostPads:l,players:i,tickMarks:c,timelineEvents:f,teamZeroNames:e.meta.team_zero.map(d=>d.name),teamOneNames:e.meta.team_one.map(d=>d.name)}}function L(e){if(e instanceof Map)return Object.fromEntries(Array.from(e.entries()).map(([t,n])=>[t,L(n)]));if(Array.isArray(e))return e.map(t=>L(t));if(e&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=L(r);return t}return e}async function Dt(){const e=Ae;typeof e=="function"&&await e()}function R(e){self.postMessage(e)}self.onmessage=async e=>{if(e.data.type==="load-replay")try{await Dt();const t=new Uint8Array(e.data.bytes);R({type:"progress",progress:{stage:"validating",progress:0}});const n=be(t,c=>{R({type:"progress",progress:L(c)})},e.data.reportEveryNFrames,32*1024*1024);R({type:"progress",progress:{stage:"normalizing",progress:0}});const r=JSON.parse(new TextDecoder().decode(n.rawReplayData)),o=Et(r,{progressReportFrameInterval:e.data.reportEveryNFrames,onProgress(c){R({type:"progress",progress:{stage:"normalizing",progress:c}})}}),i=new TextEncoder().encode(JSON.stringify(o)),a=n.rawReplayData,s=a.byteOffset===0&&a.byteLength===a.buffer.byteLength?a.buffer:a.slice().buffer,l=Array.from(n.statsTimelineParts.frameChunks,c=>c.buffer);self.postMessage({type:"done",replayBuffer:i.buffer,rawReplayBuffer:s,statsTimelineParts:{configBuffer:n.statsTimelineParts.config.buffer,replayMetaBuffer:n.statsTimelineParts.replayMeta.buffer,eventsBuffer:n.statsTimelineParts.events.buffer,activitySummaryBuffer:n.statsTimelineParts.activitySummary.buffer,positioningSummaryBuffer:n.statsTimelineParts.positioningSummary.buffer,accumulationTracksBuffer:n.statsTimelineParts.accumulationTracks.buffer,frameChunkBuffers:l}},[i.buffer,s,n.statsTimelineParts.config.buffer,n.statsTimelineParts.replayMeta.buffer,n.statsTimelineParts.events.buffer,n.statsTimelineParts.activitySummary.buffer,n.statsTimelineParts.positioningSummary.buffer,n.statsTimelineParts.accumulationTracks.buffer,...l])}catch(t){R({type:"error",error:t instanceof Error?t.message:String(t)})}}})(); diff --git a/crates/rocket-sense-server/static/subtr-actor/assets/replayLoader.worker-D3pjMe81.js b/crates/rocket-sense-server/static/subtr-actor/assets/replayLoader.worker-D3pjMe81.js deleted file mode 100644 index 1217437e..00000000 --- a/crates/rocket-sense-server/static/subtr-actor/assets/replayLoader.worker-D3pjMe81.js +++ /dev/null @@ -1 +0,0 @@ -(function(){"use strict";function fe(e,t,n,r){const o=ge(e,m.__wbindgen_malloc),i=x,a=m.get_replay_bundle_json_parts_with_progress(o,i,t,L(n)?4294967297:n>>>0,L(r)?4294967297:r>>>0);if(a[2])throw K(a[1]);return K(a[0])}function be(){return{__proto__:null,"./rl_replay_subtr_actor_bg.js":{__proto__:null,__wbg_Error_8c4e43fe74559d73:function(t,n){return Error(I(t,n))},__wbg_String_8f0eb39a4a4c2f66:function(t,n){const r=String(n),o=V(r,m.__wbindgen_malloc,m.__wbindgen_realloc),i=x;T().setInt32(t+4,i,!0),T().setInt32(t+0,o,!0)},__wbg___wbindgen_is_string_cd444516edc5b180:function(t){return typeof t=="string"},__wbg___wbindgen_string_get_72fb696202c56729:function(t,n){const r=n,o=typeof r=="string"?r:void 0;var i=L(o)?0:V(o,m.__wbindgen_malloc,m.__wbindgen_realloc),a=x;T().setInt32(t+4,a,!0),T().setInt32(t+0,i,!0)},__wbg___wbindgen_throw_be289d5034ed271b:function(t,n){throw new Error(I(t,n))},__wbg_call_4708e0c13bdc8e95:function(){return W(function(t,n,r){return t.call(n,r)},arguments)},__wbg_error_7534b8e9a36f1ab4:function(t,n){let r,o;try{r=t,o=n,console.error(I(t,n))}finally{m.__wbindgen_free(r,o,1)}},__wbg_log_d095c16a726a937c:function(t,n){console.log(I(t,n))},__wbg_new_361308b2356cecd0:function(){return new Object},__wbg_new_3eb36ae241fe6f44:function(){return new Array},__wbg_new_8a6f238a6ece86ea:function(){return new Error},__wbg_new_dca287b076112a51:function(){return new Map},__wbg_new_from_slice_a3d2629dc1826784:function(t,n){return new Uint8Array(ye(t,n))},__wbg_push_8ffdcb2063340ba5:function(t,n){return t.push(n)},__wbg_set_1eb0999cf5d27fc8:function(t,n,r){return t.set(n,r)},__wbg_set_3f1d0b984ed272ed:function(t,n,r){t[n]=r},__wbg_set_6cb8631f80447a67:function(){return W(function(t,n,r){return Reflect.set(t,n,r)},arguments)},__wbg_set_f43e577aea94465b:function(t,n,r){t[n>>>0]=r},__wbg_stack_0ed75d68575b0f3c:function(t,n){const r=n.stack,o=V(r,m.__wbindgen_malloc,m.__wbindgen_realloc),i=x;T().setInt32(t+4,i,!0),T().setInt32(t+0,o,!0)},__wbindgen_cast_0000000000000001:function(t){return t},__wbindgen_cast_0000000000000002:function(t){return t},__wbindgen_cast_0000000000000003:function(t,n){return I(t,n)},__wbindgen_cast_0000000000000004:function(t){return BigInt.asUintN(64,t)},__wbindgen_init_externref_table:function(){const t=m.__wbindgen_externrefs,n=t.grow(4);t.set(0,void 0),t.set(n+0,void 0),t.set(n+1,null),t.set(n+2,!0),t.set(n+3,!1)}}}}function _e(e){const t=m.__externref_table_alloc();return m.__wbindgen_externrefs.set(t,e),t}function ye(e,t){return e=e>>>0,S().subarray(e/1,e/1+t)}let w=null;function T(){return(w===null||w.buffer.detached===!0||w.buffer.detached===void 0&&w.buffer!==m.memory.buffer)&&(w=new DataView(m.memory.buffer)),w}function I(e,t){return e=e>>>0,he(e,t)}let P=null;function S(){return(P===null||P.byteLength===0)&&(P=new Uint8Array(m.memory.buffer)),P}function W(e,t){try{return e.apply(this,t)}catch(n){const r=_e(n);m.__wbindgen_exn_store(r)}}function L(e){return e==null}function ge(e,t){const n=t(e.length*1,1)>>>0;return S().set(e,n/1),x=e.length,n}function V(e,t,n){if(n===void 0){const s=B.encode(e),l=t(s.length,1)>>>0;return S().subarray(l,l+s.length).set(s),x=s.length,l}let r=e.length,o=t(r,1)>>>0;const i=S();let a=0;for(;a127)break;i[o+a]=s}if(a!==r){a!==0&&(e=e.slice(a)),o=n(o,r,r=a+e.length*3,1)>>>0;const s=S().subarray(o+a,o+r),l=B.encodeInto(e,s);a+=l.written,o=n(o,r,a,1)>>>0}return x=a,o}function K(e){const t=m.__wbindgen_externrefs.get(e);return m.__externref_table_dealloc(e),t}let M=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});M.decode();const pe=2146435072;let j=0;function he(e,t){return j+=t,j>=pe&&(M=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),M.decode(),j=t),M.decode(S().subarray(e,e+t))}const B=new TextEncoder;"encodeInto"in B||(B.encodeInto=function(e,t){const n=B.encode(e);return t.set(n),{read:e.length,written:n.length}});let x=0,m;function ke(e,t){return m=e.exports,w=null,P=null,m.__wbindgen_start(),m}async function we(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(o){if(e.ok&&n(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",o);else throw o}const r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{const r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}async function xe(e){if(m!==void 0)return m;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0&&(e=new URL(""+new URL("rl_replay_subtr_actor_bg-Xy9_Ya42.wasm",self.location.href).href,self.location.href));const t=be();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));const{instance:n,module:r}=await we(await e,t);return ke(n)}const Z="octane",Ae={breakout:{kind:"breakout",label:"Breakout",length:131.4924,width:80.521,height:30.3,slopeDegrees:-.9795,groundHeightFront:43.8976,groundHeightBack:46.1454,offset:13.88,elevation:17.05},dominus:{kind:"dominus",label:"Dominus",length:127.9268,width:83.27995,height:31.3,slopeDegrees:-.9635,groundHeightFront:47.2238,groundHeightBack:49.3749,offset:13.88,elevation:17.05},hybrid:{kind:"hybrid",label:"Hybrid",length:127.0192,width:82.18787,height:34.15907,slopeDegrees:-.5499,groundHeightFront:54.0982,groundHeightBack:55.3173,offset:13.88,elevation:17.05},merc:{kind:"merc",label:"Merc",length:120.72,width:76.71,height:41.66,slopeDegrees:.28,groundHeightFront:60.76,groundHeightBack:61.35,offset:13.88,elevation:17.05},octane:{kind:"octane",label:"Octane",length:118.0074,width:84.19941,height:36.15907,slopeDegrees:-.5518,groundHeightFront:55.1449,groundHeightBack:56.2814,offset:13.88,elevation:17.05},plank:{kind:"plank",label:"Plank",length:128.8198,width:84.67036,height:29.3944,slopeDegrees:-.3447,groundHeightFront:44.998,groundHeightBack:45.773,offset:13.88,elevation:17.05}},ve={"16batmobile":"plank","70dodgechargerrt":"dominus","89batmobile":"dominus","99nissanskylinegtrr34":"hybrid",aftershock:"dominus",animusgp:"breakout",artemis:"plank",artemisg1:"plank",artemisgxt:"plank",astonmartinvalhalla:"breakout",backfire:"octane",backtothefuturetimemachine:"dominus",batmobile1989:"dominus",battlebus:"merc",breakout:"breakout",breakouttypes:"breakout",centio:"plank",centiov17:"plank",cyclone:"breakout",deloreantimemachine:"dominus",diestro:"dominus",dominus:"dominus",dominusgt:"dominus",endo:"hybrid",esper:"hybrid",fast4wd:"octane",fennec:"octane",gazellagt:"dominus",gizmo:"octane",grog:"octane",guardian:"dominus",guardiang1:"dominus",guardiangxt:"dominus",hotshot:"dominus",icecharger:"dominus",imperatordt5:"dominus",jager619rs:"hybrid",jurassicjeepwrangler:"octane",mantis:"plank",marauder:"octane",masamune:"dominus",maverick:"dominus",maverickg1:"dominus",maverickgxt:"dominus",mclaren570s:"dominus",merc:"merc",mr11:"dominus",nimbus:"hybrid",octane:"octane",octanezsr:"octane",paladin:"plank",proteus:"octane",ripper:"dominus",roadhog:"octane",roadhogxl:"octane",samurai:"breakout",scarab:"octane",takumi:"octane",takumirxt:"octane",thedarkknightstumbler:"octane",thedarkknightrisestumbler:"octane",triton:"octane",twinmilliii:"plank",twinzer:"octane",venom:"hybrid",vulcan:"octane",werewolf:"dominus",xdevil:"hybrid",xdevilmk2:"hybrid",zippy:"octane","1966cadillacdeville":"breakout",ace:"breakout",admiral:"dominus",azura:"breakout",behemoth:"merc",beskar:"hybrid",bmwm3e30:"dominus",bmwm2racing:"dominus",bmwm4gt3evo:"dominus",bmw1series:"octane",bmw1seriesrle:"octane",bmwm240i:"dominus",bugatticentodieci:"plank",bumblebee:"dominus",bumblebeecar:"dominus",chevroletastro:"merc",chevroletcorvettestingray:"breakout",chevroletcorvettezr1:"breakout",chryslerpacifica:"hybrid",corlay:"octane",cyberpunkquadra:"breakout",defenderd7xr:"merc",diesel:"breakout",dodgechargerdaytonascatpack:"dominus",dodgerchargerdaytonascatpack:"dominus",dominusneon:"dominus",emperor:"breakout",emperorii:"breakout",emperoriifrozen:"breakout",emperoriiscorched:"breakout",fastfuriousdodgecharger:"dominus",fastandfuriousdodgecharger:"dominus",fastandfuriousdodgechargersrthellcat:"dominus",fastfuriousmazdarx7:"breakout",fastandfuriousmazdarx7:"breakout",fastfuriousnissanskyline:"hybrid",fastandfuriousnissanskyline:"hybrid",fastfuriouspontiacfiero:"hybrid",fastandfuriouspontiacfiero:"hybrid",fenneczrf:"octane",ferrari296gtb:"dominus",ferrarif40:"breakout",fordbroncoraptorrle:"merc",fordf150rle:"octane",fordmustanggtd:"dominus",fordmustangshelbygt500:"dominus",fordmustangmacherle:"octane",fordmustangshelbygt350rrle:"dominus",formula12021:"plank",formula12022:"plank",fuse:"breakout",havoc:"breakout",hearse:"hybrid",homerscar:"dominus",hondacivictyper:"octane",hondacivictyperle:"octane",jackal:"octane",jeepwranglerrubicon:"octane",kitt:"dominus",knightindustries2000:"dominus",komodo:"breakout",lamborghinicountachlpi8004:"dominus",lamborghinihuracansto:"dominus",lamborghiniurus:"hybrid",lamborghiniurusse:"hybrid",lightningmcqueen:"dominus",lightningmcqueencar:"dominus",lockjaw:"dominus",luiginsr:"octane",maestro:"dominus",magnifique:"dominus",magnifiquegxt:"dominus",mako:"breakout",mamba:"dominus",mario:"octane",marionsr:"octane",maven:"dominus",mclaren765lt:"dominus",mclarenp1:"dominus",mclarensenna:"breakout",megastar:"breakout",mercedesamggt63s:"dominus",mercedesbenzcla:"dominus",mudcat:"octane",mudcatg1:"octane",mudcatgxt:"octane",nissan350z:"dominus",nissanfairladyz:"dominus",nissanfairladyzrle:"dominus",nissansilvia:"hybrid",nissansilviarle:"hybrid",nissanskylinegtr:"hybrid",nissanskylinegtrr32:"hybrid",nissanzperformance:"dominus",nissanzperformancecar:"dominus",outlaw:"octane",outlawgxt:"octane",pattywagon:"octane",pizzaplanetdeliverytruck:"merc",pontiacfirebird:"breakout",porsche918spyder:"breakout",porsche911gt3rs:"dominus",porsche911turbo:"dominus",porsche911turborle:"dominus",primo:"hybrid",psyclops:"octane",quadraturbor:"breakout",ram1500rho:"hybrid",recoilav:"merc",redline:"breakout",revolver:"breakout",rivianr1s:"hybrid",scorpion:"dominus",shokunin:"octane",shokuningxt:"octane",stampede:"merc",teslacybertruck:"hybrid",themysterymachine:"merc",theincredibile:"breakout",turtlevan:"merc",voidburn:"hybrid",volkswagengolfgti:"octane",volkswagengolfgtirle:"octane",xentari:"octane",zefira:"dominus",breakoutx:"breakout",nexus:"breakout",nexussc:"breakout",whiplash:"breakout","007sastonmartindbs":"dominus","007sastonmartinvalhalla":"dominus",batmobile2022:"dominus",chikara:"dominus",chikarag1:"dominus",chikaragxt:"dominus",ecto1:"dominus",ecto1ghostbusters:"dominus",fastfuriousdodgechargersrthellcat:"dominus",gazellagthotwheels:"dominus",kittknightrider:"dominus",lamborghinihuracnsto:"dominus",mr11hotwheels:"dominus",nascarchevroletcamaro:"dominus",nascarfordmustang:"dominus",nascartoyotacamry:"dominus",nascarnextgenchevroletcamaro:"dominus",nascarnextgenchevroletcamaro2022:"dominus",nascarnextgenfordmustang:"dominus",nascarnextgenfordmustang2022:"dominus",nascarnextgentoyotacamry:"dominus",nascarnextgentoyotacamry2022:"dominus",nemesis:"dominus",peregrinett:"dominus",perigrinett:"dominus",ronin:"dominus",roning1:"dominus",roningxt:"dominus",samusgunship:"dominus",samusgunshipnintendoexclusive:"dominus",tyranno:"dominus",tyrannogxt:"dominus",insidio:"hybrid",jager619:"hybrid",jger619:"hybrid",jger619rs:"hybrid",r3mx:"hybrid",r3mxgxt:"hybrid",tygris:"hybrid",nomad:"merc",nomadgxt:"merc","007sastonmartindb5":"octane",armadillo:"octane",armadilloxboxexclusive:"octane",boneshaker:"octane",dingo:"octane",fast4wdhotwheels:"octane",harbinger:"octane",harbingergxt:"octane",hogsticker:"octane",hogstickerxboxexclusive:"octane",sweettooth:"octane",sweettoothplaystationexclusive:"octane",thedarkknighttumbler:"octane",batmobile2016:"plank",sentinel:"plank"};function Te(e){const t={};for(const[n,r]of e)for(const o of n)t[o]=r;return t}const Se=Te([[[22,1416,1894,1932,3031,3311,6243,6489,7651,7696,7890,7901,8006,8360,8361,8565,8566,8669,9357,10697,10698,10817,10822,11038,11394,11505,11677,11800,11933,11949,12173,12315,12361,12484],"breakout"],[[29,403,597,600,1018,1171,1286,1675,1689,1883,2070,2268,2666,2950,2951,3155,3156,3157,3265,3426,3875,3879,3880,4014,4155,4367,4472,4473,4745,4770,4781,4861,4864,5709,5773,5823,5858,5964,5979,6122,6244,6247,6260,6836,7211,7337,7338,7341,7343,7415,7512,7532,7593,7772,8454,9053,9088,9089,9140,9388,9894,10094,10440,10441,10694,10695,11016,11095,11315,11336,11534,11941,11996,12106,12142,12262,12286,12325,12382,12563,12669],"dominus"],[[28,31,1159,1317,1624,1856,2269,3451,3582,3702,5470,5488,5879,7012,9084,9085,9427,10044,10805,11138,11141,11379,11932,12569,12652],"hybrid"],[[30,4780,7336,7477,7815,7979,10689,11098,11736,11905,11950,12318,12335],"merc"],[[21,23,25,26,27,402,404,523,607,625,723,1172,1295,1300,1475,1478,1533,1568,1623,2665,2853,2919,2949,4284,4318,4319,4320,4782,4906,5020,5039,5188,5361,5547,5713,5837,5951,6939,7947,7948,8383,8806,8807,10896,10897,10900,10901,11314,11603,12104,12105],"octane"],[[24,803,1603,1691,1919,3594,3614,3622,4268,5265,7052,8524],"plank"]]);function G(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function q(e){if(!e)return null;switch(G(e)){case"breakout":return"breakout";case"dominus":return"dominus";case"hybrid":return"hybrid";case"merc":return"merc";case"octane":return"octane";case"batmobile":case"plank":return"plank";default:return null}}function J(e){return e?ve[G(e)]??null:null}function Oe(e){return q(e)??J(e)}function Ie(e){return Ae[e]}function H(e,t){if(!(!e||typeof e!="object")){if("Str"in e&&typeof e.Str=="string"){t.push(e.Str);return}if("Name"in e&&typeof e.Name=="string"){t.push(e.Name);return}if("Byte"in e&&e.Byte&&typeof e.Byte=="object"){const n=e.Byte;typeof n.kind=="string"&&t.push(n.kind),typeof n.value=="string"&&t.push(n.value);return}if("Struct"in e&&e.Struct&&typeof e.Struct=="object"){const n=e.Struct;if(typeof n.name=="string"&&t.push(n.name),Array.isArray(n.fields))for(const r of n.fields)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),H(r[1],t));return}if("Array"in e&&Array.isArray(e.Array)){for(const n of e.Array)if(Array.isArray(n))for(const r of n)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),H(r[1],t))}}}function Pe(e){const t=q(e?.car_hitbox_family);if(t)return t;const n=e?.car_body_id;if(typeof n=="number"){const a=Se[n];if(a)return a}const r=J(e?.car_body_name);if(r)return r;const o=e?.stats;if(!o)return Z;const i=[];for(const[a,s]of Object.entries(o))i.push(a),H(s,i);for(const a of i){const s=Oe(a);if(s)return s}return Z}function k(e){const[t,n]=Object.entries(e)[0]??["Unknown","unknown"];return typeof n=="string"||typeof n=="number"?`${t}:${n}`:n&&typeof n=="object"?`${t}:${JSON.stringify(n)}`:`${t}:${JSON.stringify(n)}`}function E(e,t){return Math.max(0,e-t)}function Q(e){return new Map(e.map(t=>[t.id,t]))}const g=70,ee=73,Be=3072,Ee=4096,De=1792,Re=4184,Me=940,Ne=3308,ze=2816,te=3584,Fe=2484,Ce=1788,Le=2300,Ve=2048,je=1036,He=1024,Ue=1024,Ye=4240,ne=34;function N(e,t,n,r,o){e.push({index:e.length,padId:null,size:o,position:{x:t,y:n,z:r},events:[]})}function z(e,t,n,r,o){N(e,-t,n,r,o),N(e,t,n,r,o)}function U(e,t,n,r,o){N(e,t,-n,r,o),N(e,t,n,r,o)}function O(e,t,n,r,o){z(e,t,-n,r,o),z(e,t,n,r,o)}function $e(){const e=[];return U(e,0,Ye,g,"small"),O(e,De,Re,g,"small"),O(e,Be,Ee,ee,"big"),O(e,Me,Ne,g,"small"),U(e,0,ze,g,"small"),O(e,te,Fe,g,"small"),O(e,Ce,Le,g,"small"),O(e,Ve,je,g,"small"),U(e,0,Ue,g,"small"),z(e,te,0,ee,"big"),z(e,He,0,g,"small"),e}function Y(e){if(e==="Available")return!0;if(e&&typeof e=="object"){if("Available"in e)return!0;if("PickedUp"in e)return!1;const t=e.kind;if(t==="Available")return!0;if(t==="PickedUp")return!1}return null}function Xe(e){return e==="big"||e==="Big"?"big":e==="small"||e==="Small"?"small":null}function We(e){let t=null;for(const n of e){const r=Y(n.kind);if(r===!1){t=n.time;continue}if(r===!0&&t!==null)return n.time-t>=7?"big":"small"}return null}function Ke(e,t,n,r){const o=Q(t),i=new Map;for(const c of e.boost_pad_events??[]){if(Y(c.kind)===null){r?.advance();continue}const u=i.get(c.pad_id);u?u.push(c):i.set(c.pad_id,[c]),r?.advance()}const a=e.boost_pads;if(!a||a.length===0)return r?.advance(ne),$e();const s=[...a].sort((c,d)=>c.index-d.index),l=new Array(s.length);for(let c=0;c=72?"big":"small"),p=y.sort((b,h)=>b.time-h.time),f=new Array(p.length);for(let b=0;b=0?e.frame:null}function Ze(e,t){if(typeof e.time=="number"&&Number.isFinite(e.time))return e.time;const n=$(e);if(n===null)return null;const r=t.frame_data.metadata_frames[n]?.time;return typeof r=="number"&&Number.isFinite(r)?r:null}function Ge(e,t){return`bookmark:${$(e)??"unknown"}:${e.description||"tick-mark"}:${t}`}function qe(e,t,n){return(e.replay_tick_marks??[]).flatMap((r,o)=>{n?.advance();const i=Ze(r,e);return i===null?[]:[{id:Ge(r,o),description:r.description,frame:$(r),time:E(i,t)}]})}function Je(e){const t=e.description.trim()||"Replay bookmark";return{id:e.id,time:e.time,seekTime:e.time,frame:e.frame??void 0,kind:"bookmark",label:t,shortLabel:"BM",iconName:"bookmark"}}const A={distance:270,height:100,pitch:-4,fov:110},Qe=.005,et=Number.POSITIVE_INFINITY,tt=!0,nt=.15,rt=10,ot=.1,at=10;function re(e){const t=Math.hypot(e.x,e.y,e.z);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t}}function oe(e){const t=Math.hypot(e.x,e.y,e.z,e.w);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t,w:e.w/t}}function ae(e,t){return{w:e.w*t.w-e.x*t.x-e.y*t.y-e.z*t.z,x:e.w*t.x+e.x*t.w+e.y*t.z-e.z*t.y,y:e.w*t.y-e.x*t.z+e.y*t.w+e.z*t.x,z:e.w*t.z+e.x*t.y-e.y*t.x+e.z*t.w}}function ie(e,t){const n=ae(ae(t,{x:e.x,y:e.y,z:e.z,w:0}),{x:-t.x,y:-t.y,z:-t.z,w:t.w});return{x:n.x,y:n.y,z:n.z}}function it(e){if(e==="Empty")return{position:null,linearVelocity:null,angularVelocity:null,rotation:null};const t=e.Data.rigid_body;return{position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:oe(t.rotation)}}function se(e){return e==null?null:Math.max(-1,Math.min(1,(e-128)/128))}function ce(e){return e==null?null:(e>127?e-256:e)*Math.PI/128}function le(e){return e?{x:e[0],y:e[1],z:e[2]}:null}const st={cameraPitch:null,cameraYaw:null,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null};function ct(e){if(e==="Empty")return{isPresent:!1,position:null,linearVelocity:null,angularVelocity:null,rotation:null,forward:null,up:null,boostAmount:0,boostFraction:0,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,...st};const t=e.Data.rigid_body,n=oe(t.rotation),r=n?re(ie({x:1,y:0,z:0},n)):null,o=n?re(ie({x:0,y:0,z:1},n)):null,i=e.Data.camera,a=e.Data.input;return{isPresent:!0,position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:n,forward:r,up:o,boostAmount:e.Data.boost_amount,boostFraction:Math.max(0,Math.min(1,e.Data.boost_amount/255)),boostActive:e.Data.boost_active,powerslideActive:e.Data.powerslide_active,jumpActive:e.Data.jump_active,doubleJumpActive:e.Data.double_jump_active,dodgeActive:e.Data.dodge_active,cameraPitch:ce(i?.pitch),cameraYaw:ce(i?.yaw),throttle:se(a?.throttle),steer:se(a?.steer),dodgeImpulse:le(a?.dodge_impulse),dodgeTorque:le(a?.dodge_torque)}}function lt(e){return e.position!==null}function ut(e){return{...e,isPresent:!1,linearVelocity:null,angularVelocity:null,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null}}function mt(e){let t=null,n=null;for(let r=0;r=t.length-1)return;let o=D(t[r].position);for(let i=r+1;iot){o=D(s.position);continue}if(dt(o,s.position)>at){o=D(s.position);continue}const u={x:(a.linearVelocity.x+s.linearVelocity.x)/2,y:(a.linearVelocity.y+s.linearVelocity.y)/2,z:(a.linearVelocity.z+s.linearVelocity.z)/2},y={x:o.x+u.x*d,y:o.y+u.y*d,z:o.z+u.z*d},_=(i-r)%n.smoothingAnchorInterval===0?.5:n.smoothingBlendFactor;o={x:y.x*(1-_)+s.position.x*_,y:y.y*(1-_)+s.position.y*_,z:y.z*(1-_)+s.position.z*_},s.position=D(o)}}function ft(e){return{motionSmoothing:e.motionSmoothing??tt,smoothingBlendFactor:e.smoothingBlendFactor??nt,smoothingAnchorInterval:Math.max(1,e.smoothingAnchorInterval??rt)}}function de(){return typeof performance>"u"?Date.now():performance.now()}function bt(e){const t=e.meta.team_zero.length+e.meta.team_one.length,n=e.frame_data.players.reduce((a,[,s])=>a+s.frames.length,0),r=e.boost_pads?.length??ne,o=e.boost_pad_events?.length??0,i=(e.goal_events?.length??0)+(e.player_stat_events?.length??0)+(e.demolish_infos?.length??0)+(e.replay_tick_marks?.length??0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,n),Math.max(1,e.frame_data.ball_data.frames.length),Math.max(1,r+o),Math.max(1,i)].reduce((a,s)=>a+s,0)}function _t(e){const t=e.frame_data.players.reduce((n,[,r])=>n+r.frames.length,0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,e.frame_data.ball_data.frames.length)].reduce((n,r)=>n+r,0)}function yt(e,t,n={}){const r=bt(e),o=_t(e);let i=0,a=0,s=-1,l=-1,c=de();const d=n.yieldEveryMs??Number.POSITIVE_INFINITY,u=n.progressReportMinDelta??Qe,y=Math.max(1,n.progressReportFrameInterval??et),_=()=>{if(!t)return!1;const f=Math.max(0,Math.min(1,i/r));if(f<=s)return!1;const h=a-l>=y;return f>=1||f-s>=u||h?(s=f,l=a,t(f,{progress:f,processedFrames:Math.min(a,o),totalFrames:o,processedUnits:i,totalUnits:r}),!0):!1},p=(f=!1)=>{const b=de();return!f&&b-cr===t)?.[1];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function kt(e){const t=ht(e?.stats);return{fov:v(t,"CameraFOV")??A.fov,height:v(t,"CameraHeight")??A.height,pitch:v(t,"CameraPitch")??A.pitch,distance:v(t,"CameraDistance")??A.distance,stiffness:v(t,"CameraStiffness")??A.stiffness,swivelSpeed:v(t,"CameraSwivelSpeed")??A.swivelSpeed,transitionSpeed:v(t,"CameraTransitionSpeed")??A.transitionSpeed}}function wt(e,t){const n=new Map,r=new Map,o=[...e.meta.team_zero,...e.meta.team_one];if(o.length===0)return t?.advance(),{byId:n,byName:r};for(const i of o)r.set(i.name,i),i.remote_id&&n.set(k(i.remote_id),i),t?.advance();return{byId:n,byName:r}}function xt(e){const t=new Map;for(const[n,r]of e.player_camera_events??[])t.set(k(n),r.map(o=>({frame:o.frame,ballCamActive:o.ball_cam_active,behindViewActive:o.behind_view_active,driving:o.driving})));return t}function At(e,t){const n=new Set(e.meta.team_zero.map(l=>l.name)),r=new Set(e.meta.team_one.map(l=>l.name)),o=wt(e,t),i=xt(e),a=[];let s=0;for(const[l,c]of e.frame_data.players){const d=new Array(c.frames.length);let u;for(let f=0;ft.time!==n.time?t.time-n.time:(t.frame??0)-(n.frame??0))}function St(e,t,n){const r=e.player?k(e.player):null,o=r?t.get(r)?.name??r:null,i=o?`${o} scored`:"Goal";return{id:X("goal",e.frame,r??"team"),time:E(e.time,n),frame:e.frame,kind:"goal",label:i,shortLabel:"G",playerId:r,playerName:o,isTeamZero:e.scoring_team_is_team_0}}function Ot(e,t,n){const r=k(e.player),o=t.get(r)?.name??r,i=e.kind.toLowerCase(),a=e.kind==="Shot"?"shot":e.kind==="Save"?"save":"assist",s=e.kind==="Shot"?"SH":e.kind==="Save"?"SV":"A";return{id:X(i,e.frame,r),time:E(e.time,n),frame:e.frame,kind:i,label:`${o} ${a}`,shortLabel:s,playerId:r,playerName:o,location:e.shot?.shot_touch_position??e.shot?.ball_position??null,shot:e.shot??null,isTeamZero:e.is_team_0}}function It(e,t,n){const r=k(e.attacker),o=k(e.victim),i=t.get(r),a=t.get(o);return{id:X("demo",e.frame,`${r}:${o}`),time:E(e.time,n),frame:e.frame,kind:"demo",label:`${i?.name??r} demoed ${a?.name??o}`,shortLabel:"D",playerId:r,playerName:i?.name??r,secondaryPlayerId:o,secondaryPlayerName:a?.name??o,location:e.victim_location,isTeamZero:i?.isTeamZero??null}}function Pt(e,t,n,r,o){const i=Q(t),a=[];for(const s of e.goal_events??[])a.push(St(s,i,r)),o?.advance();for(const s of e.player_stat_events??[])a.push(Ot(s,i,r)),o?.advance();for(const s of e.demolish_infos??[])a.push(It(s,i,r)),o?.advance();for(const s of n)a.push(Je(s));return a.length===0&&o?.advance(),Tt(a)}function Bt(e,t={}){const n=yt(e,t.onProgress,{progressReportMinDelta:t.progressReportMinDelta,progressReportFrameInterval:t.progressReportFrameInterval}),r=e.frame_data.metadata_frames[0]?.time??0,o=gt(e,n),i=At(e,n),a=vt(e,n),s=ft(t);me(o,a,s);for(const u of i)me(o,u.frames,s);const l=Ke(e,i,r,n),c=qe(e,r,n),d=Pt(e,i,c,r,n);return n.finish(),{frameCount:o.length,duration:o.at(-1)?.time??0,rawStartTime:r,frames:o,ballFrames:a,boostPads:l,players:i,tickMarks:c,timelineEvents:d,teamZeroNames:e.meta.team_zero.map(u=>u.name),teamOneNames:e.meta.team_one.map(u=>u.name)}}function F(e){if(e instanceof Map)return Object.fromEntries(Array.from(e.entries()).map(([t,n])=>[t,F(n)]));if(Array.isArray(e))return e.map(t=>F(t));if(e&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=F(r);return t}return e}async function Et(){const e=xe;typeof e=="function"&&await e()}function R(e){self.postMessage(e)}self.onmessage=async e=>{if(e.data.type==="load-replay")try{await Et();const t=new Uint8Array(e.data.bytes);R({type:"progress",progress:{stage:"validating",progress:0}});const n=fe(t,c=>{R({type:"progress",progress:F(c)})},e.data.reportEveryNFrames,32*1024*1024);R({type:"progress",progress:{stage:"normalizing",progress:0}});const r=JSON.parse(new TextDecoder().decode(n.rawReplayData)),o=Bt(r,{progressReportFrameInterval:e.data.reportEveryNFrames,onProgress(c){R({type:"progress",progress:{stage:"normalizing",progress:c}})}}),i=new TextEncoder().encode(JSON.stringify(o)),a=n.rawReplayData,s=a.byteOffset===0&&a.byteLength===a.buffer.byteLength?a.buffer:a.slice().buffer,l=Array.from(n.statsTimelineParts.frameChunks,c=>c.buffer);self.postMessage({type:"done",replayBuffer:i.buffer,rawReplayBuffer:s,statsTimelineParts:{configBuffer:n.statsTimelineParts.config.buffer,replayMetaBuffer:n.statsTimelineParts.replayMeta.buffer,eventsBuffer:n.statsTimelineParts.events.buffer,activitySummaryBuffer:n.statsTimelineParts.activitySummary.buffer,positioningSummaryBuffer:n.statsTimelineParts.positioningSummary.buffer,accumulationTracksBuffer:n.statsTimelineParts.accumulationTracks.buffer,frameChunkBuffers:l}},[i.buffer,s,n.statsTimelineParts.config.buffer,n.statsTimelineParts.replayMeta.buffer,n.statsTimelineParts.events.buffer,n.statsTimelineParts.activitySummary.buffer,n.statsTimelineParts.positioningSummary.buffer,n.statsTimelineParts.accumulationTracks.buffer,...l])}catch(t){R({type:"error",error:t instanceof Error?t.message:String(t)})}}})(); diff --git a/crates/rocket-sense-server/static/subtr-actor/assets/rl_replay_subtr_actor-Cnltgw4Z.js b/crates/rocket-sense-server/static/subtr-actor/assets/rl_replay_subtr_actor-Cnltgw4Z.js new file mode 100644 index 00000000..d2cb4f7d --- /dev/null +++ b/crates/rocket-sense-server/static/subtr-actor/assets/rl_replay_subtr_actor-Cnltgw4Z.js @@ -0,0 +1,2 @@ +function U(r,n){var e=g(r)?0:k(r,_.__wbindgen_malloc),t=a,i=g(n)?0:k(n,_.__wbindgen_malloc),c=a;const o=_.get_column_headers(e,t,i,c);if(o[2])throw s(o[1]);return s(o[0])}function B(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.get_legacy_stats_timeline_json(n,e);if(t[3])throw s(t[2]);var i=v(t[0],t[1]).slice();return _.__wbindgen_free(t[0],t[1]*1,1),i}function D(r,n,e,t){const i=w(r,_.__wbindgen_malloc),c=a;var o=g(n)?0:k(n,_.__wbindgen_malloc),l=a,f=g(e)?0:k(e,_.__wbindgen_malloc),u=a;const p=_.get_ndarray_with_info(i,c,o,l,f,u,g(t)?4294967297:Math.fround(t));if(p[2])throw s(p[1]);return s(p[0])}function N(r,n,e,t){const i=w(r,_.__wbindgen_malloc),c=a,o=_.get_replay_bundle_json_parts_with_progress(i,c,n,g(e)?4294967297:e>>>0,g(t)?4294967297:t>>>0);if(o[2])throw s(o[1]);return s(o[0])}function L(r,n,e){const t=w(r,_.__wbindgen_malloc),i=a,c=_.get_replay_bundle_json_with_progress(t,i,n,g(e)?4294967297:e>>>0);if(c[2])throw s(c[1]);return s(c[0])}function $(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.get_replay_frames_data(n,e);if(t[2])throw s(t[1]);return s(t[0])}function V(r,n,e){const t=w(r,_.__wbindgen_malloc),i=a,c=_.get_replay_frames_data_json_with_progress(t,i,n,g(e)?4294967297:e>>>0);if(c[3])throw s(c[2]);var o=v(c[0],c[1]).slice();return _.__wbindgen_free(c[0],c[1]*1,1),o}function q(r,n,e){const t=w(r,_.__wbindgen_malloc),i=a,c=_.get_replay_frames_data_with_progress(t,i,n,g(e)?4294967297:e>>>0);if(c[2])throw s(c[1]);return s(c[0])}function z(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.get_replay_info(n,e);if(t[2])throw s(t[1]);return s(t[0])}function C(r,n,e){const t=w(r,_.__wbindgen_malloc),i=a;var c=g(n)?0:k(n,_.__wbindgen_malloc),o=a,l=g(e)?0:k(e,_.__wbindgen_malloc),f=a;const u=_.get_replay_meta(t,i,c,o,l,f);if(u[2])throw s(u[1]);return s(u[0])}function J(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.get_stats_timeline(n,e);if(t[2])throw s(t[1]);return s(t[0])}function P(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.get_stats_timeline_json(n,e);if(t[3])throw s(t[2]);var i=v(t[0],t[1]).slice();return _.__wbindgen_free(t[0],t[1]*1,1),i}function H(r,n){const e=w(r,_.__wbindgen_malloc),t=a,i=_.get_stats_timeline_json_parts(e,t,g(n)?4294967297:n>>>0);if(i[2])throw s(i[1]);return s(i[0])}function K(){_.main()}function X(r){let n,e;try{const c=_.new_training_pack(r);var t=c[0],i=c[1];if(c[3])throw t=0,i=0,s(c[2]);return n=t,e=i,b(t,i)}finally{_.__wbindgen_free(n,e,1)}}function Y(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.parse_replay(n,e);if(t[2])throw s(t[1]);return s(t[0])}function G(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.parse_training_pack(n,e);if(t[2])throw s(t[1]);return s(t[0])}function Q(r){let n,e;try{const c=w(r,_.__wbindgen_malloc),o=a,l=_.parse_training_pack_lossless(c,o);var t=l[0],i=l[1];if(l[3])throw t=0,i=0,s(l[2]);return n=t,e=i,b(t,i)}finally{_.__wbindgen_free(n,e,1)}}function Z(r){const n=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),e=a,t=_.serialize_training_pack(n,e);if(t[3])throw s(t[2]);var i=v(t[0],t[1]).slice();return _.__wbindgen_free(t[0],t[1]*1,1),i}function nn(r,n){let e,t;try{const o=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),l=a,f=_.training_pack_add_round(o,l,n);var i=f[0],c=f[1];if(f[3])throw i=0,c=0,s(f[2]);return e=i,t=c,b(i,c)}finally{_.__wbindgen_free(e,t,1)}}function en(r,n,e){let t,i;try{const l=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),f=a,u=_.training_pack_add_round_archetype(l,f,n,e);var c=u[0],o=u[1];if(u[3])throw c=0,o=0,s(u[2]);return t=c,i=o,b(c,o)}finally{_.__wbindgen_free(t,i,1)}}function tn(r,n){let e,t;try{const o=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),l=a,f=d(n,_.__wbindgen_malloc,_.__wbindgen_realloc),u=a,p=_.training_pack_append_rounds(o,l,f,u);var i=p[0],c=p[1];if(p[3])throw i=0,c=0,s(p[2]);return e=i,t=c,b(i,c)}finally{_.__wbindgen_free(e,t,1)}}function rn(r,n){let e,t;try{const o=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),l=a,f=_.training_pack_duplicate_round(o,l,n);var i=f[0],c=f[1];if(f[3])throw i=0,c=0,s(f[2]);return e=i,t=c,b(i,c)}finally{_.__wbindgen_free(e,t,1)}}function _n(r){const n=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),e=a,t=_.training_pack_from_lossless(n,e);if(t[2])throw s(t[1]);return s(t[0])}function cn(r,n,e){let t,i;try{const l=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),f=a,u=_.training_pack_insert_round(l,f,n,e);var c=u[0],o=u[1];if(u[3])throw c=0,o=0,s(u[2]);return t=c,i=o,b(c,o)}finally{_.__wbindgen_free(t,i,1)}}function on(r,n,e){let t,i;try{const l=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),f=a,u=_.training_pack_move_round(l,f,n,e);var c=u[0],o=u[1];if(u[3])throw c=0,o=0,s(u[2]);return t=c,i=o,b(c,o)}finally{_.__wbindgen_free(t,i,1)}}function sn(r,n){let e,t;try{const o=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),l=a,f=_.training_pack_remove_round(o,l,n);var i=f[0],c=f[1];if(f[3])throw i=0,c=0,s(f[2]);return e=i,t=c,b(i,c)}finally{_.__wbindgen_free(e,t,1)}}function an(r,n,e){let t,i;try{const l=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),f=a,u=_.training_pack_remove_round_archetype(l,f,n,e);var c=u[0],o=u[1];if(u[3])throw c=0,o=0,s(u[2]);return t=c,i=o,b(c,o)}finally{_.__wbindgen_free(t,i,1)}}function fn(r,n){const e=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),t=a,i=_.training_pack_round_archetypes(e,t,n);if(i[2])throw s(i[1]);return s(i[0])}function ln(r,n,e,t){let i,c;try{const f=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),u=a,p=_.training_pack_set_round_archetype(f,u,n,e,t);var o=p[0],l=p[1];if(p[3])throw o=0,l=0,s(p[2]);return i=o,c=l,b(o,l)}finally{_.__wbindgen_free(i,c,1)}}function un(r,n,e){let t,i;try{const l=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),f=a,u=_.training_pack_set_round_ball(l,f,n,e);var c=u[0],o=u[1];if(u[3])throw c=0,o=0,s(u[2]);return t=c,i=o,b(c,o)}finally{_.__wbindgen_free(t,i,1)}}function dn(r,n,e){let t,i;try{const l=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),f=a,u=_.training_pack_set_round_time_limit(l,f,n,e);var c=u[0],o=u[1];if(u[3])throw c=0,o=0,s(u[2]);return t=c,i=o,b(c,o)}finally{_.__wbindgen_free(t,i,1)}}function gn(r,n){let e,t;try{const o=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),l=a,f=_.update_training_pack_metadata(o,l,n);var i=f[0],c=f[1];if(f[3])throw i=0,c=0,s(f[2]);return e=i,t=c,b(i,c)}finally{_.__wbindgen_free(e,t,1)}}function bn(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.validate_replay(n,e);if(t[2])throw s(t[1]);return s(t[0])}function O(){return{__proto__:null,"./rl_replay_subtr_actor_bg.js":{__proto__:null,__wbg_Error_8c4e43fe74559d73:function(n,e){return Error(b(n,e))},__wbg_Number_04624de7d0e8332d:function(n){return Number(n)},__wbg_String_8f0eb39a4a4c2f66:function(n,e){const t=String(e),i=d(t,_.__wbindgen_malloc,_.__wbindgen_realloc),c=a;y().setInt32(n+4,c,!0),y().setInt32(n+0,i,!0)},__wbg___wbindgen_bigint_get_as_i64_8fcf4ce7f1ca72a2:function(n,e){const t=e,i=typeof t=="bigint"?t:void 0;y().setBigInt64(n+8,g(i)?BigInt(0):i,!0),y().setInt32(n+0,!g(i),!0)},__wbg___wbindgen_boolean_get_bbbb1c18aa2f5e25:function(n){const e=n,t=typeof e=="boolean"?e:void 0;return g(t)?16777215:t?1:0},__wbg___wbindgen_debug_string_0bc8482c6e3508ae:function(n,e){const t=M(e),i=d(t,_.__wbindgen_malloc,_.__wbindgen_realloc),c=a;y().setInt32(n+4,c,!0),y().setInt32(n+0,i,!0)},__wbg___wbindgen_in_47fa6863be6f2f25:function(n,e){return n in e},__wbg___wbindgen_is_bigint_31b12575b56f32fc:function(n){return typeof n=="bigint"},__wbg___wbindgen_is_function_0095a73b8b156f76:function(n){return typeof n=="function"},__wbg___wbindgen_is_object_5ae8e5880f2c1fbd:function(n){const e=n;return typeof e=="object"&&e!==null},__wbg___wbindgen_is_string_cd444516edc5b180:function(n){return typeof n=="string"},__wbg___wbindgen_is_undefined_9e4d92534c42d778:function(n){return n===void 0},__wbg___wbindgen_jsval_eq_11888390b0186270:function(n,e){return n===e},__wbg___wbindgen_jsval_loose_eq_9dd77d8cd6671811:function(n,e){return n==e},__wbg___wbindgen_number_get_8ff4255516ccad3e:function(n,e){const t=e,i=typeof t=="number"?t:void 0;y().setFloat64(n+8,g(i)?0:i,!0),y().setInt32(n+0,!g(i),!0)},__wbg___wbindgen_string_get_72fb696202c56729:function(n,e){const t=e,i=typeof t=="string"?t:void 0;var c=g(i)?0:d(i,_.__wbindgen_malloc,_.__wbindgen_realloc),o=a;y().setInt32(n+4,o,!0),y().setInt32(n+0,c,!0)},__wbg___wbindgen_throw_be289d5034ed271b:function(n,e){throw new Error(b(n,e))},__wbg_call_389efe28435a9388:function(){return A(function(n,e){return n.call(e)},arguments)},__wbg_call_4708e0c13bdc8e95:function(){return A(function(n,e,t){return n.call(e,t)},arguments)},__wbg_done_57b39ecd9addfe81:function(n){return n.done},__wbg_entries_58c7934c745daac7:function(n){return Object.entries(n)},__wbg_error_7534b8e9a36f1ab4:function(n,e){let t,i;try{t=n,i=e,console.error(b(n,e))}finally{_.__wbindgen_free(t,i,1)}},__wbg_get_9b94d73e6221f75c:function(n,e){return n[e>>>0]},__wbg_get_b3ed3ad4be2bc8ac:function(){return A(function(n,e){return Reflect.get(n,e)},arguments)},__wbg_get_with_ref_key_1dc361bd10053bfe:function(n,e){return n[e]},__wbg_instanceof_ArrayBuffer_c367199e2fa2aa04:function(n){let e;try{e=n instanceof ArrayBuffer}catch{e=!1}return e},__wbg_instanceof_Map_53af74335dec57f4:function(n){let e;try{e=n instanceof Map}catch{e=!1}return e},__wbg_instanceof_Uint8Array_9b9075935c74707c:function(n){let e;try{e=n instanceof Uint8Array}catch{e=!1}return e},__wbg_isArray_d314bb98fcf08331:function(n){return Array.isArray(n)},__wbg_isSafeInteger_bfbc7332a9768d2a:function(n){return Number.isSafeInteger(n)},__wbg_iterator_6ff6560ca1568e55:function(){return Symbol.iterator},__wbg_length_32ed9a279acd054c:function(n){return n.length},__wbg_length_35a7bace40f36eac:function(n){return n.length},__wbg_log_f1a1b5cd3f9c7822:function(n,e){console.log(b(n,e))},__wbg_new_361308b2356cecd0:function(){return new Object},__wbg_new_3eb36ae241fe6f44:function(){return new Array},__wbg_new_8a6f238a6ece86ea:function(){return new Error},__wbg_new_dca287b076112a51:function(){return new Map},__wbg_new_dd2b680c8bf6ae29:function(n){return new Uint8Array(n)},__wbg_new_from_slice_a3d2629dc1826784:function(n,e){return new Uint8Array(v(n,e))},__wbg_next_3482f54c49e8af19:function(){return A(function(n){return n.next()},arguments)},__wbg_next_418f80d8f5303233:function(n){return n.next},__wbg_prototypesetcall_bdcdcc5842e4d77d:function(n,e,t){Uint8Array.prototype.set.call(v(n,e),t)},__wbg_push_8ffdcb2063340ba5:function(n,e){return n.push(e)},__wbg_set_1eb0999cf5d27fc8:function(n,e,t){return n.set(e,t)},__wbg_set_3f1d0b984ed272ed:function(n,e,t){n[e]=t},__wbg_set_6cb8631f80447a67:function(){return A(function(n,e,t){return Reflect.set(n,e,t)},arguments)},__wbg_set_f43e577aea94465b:function(n,e,t){n[e>>>0]=t},__wbg_stack_0ed75d68575b0f3c:function(n,e){const t=e.stack,i=d(t,_.__wbindgen_malloc,_.__wbindgen_realloc),c=a;y().setInt32(n+4,c,!0),y().setInt32(n+0,i,!0)},__wbg_value_0546255b415e96c1:function(n){return n.value},__wbindgen_cast_0000000000000001:function(n){return n},__wbindgen_cast_0000000000000002:function(n){return n},__wbindgen_cast_0000000000000003:function(n,e){return b(n,e)},__wbindgen_cast_0000000000000004:function(n){return BigInt.asUintN(64,n)},__wbindgen_init_externref_table:function(){const n=_.__wbindgen_externrefs,e=n.grow(4);n.set(0,void 0),n.set(e+0,void 0),n.set(e+1,null),n.set(e+2,!0),n.set(e+3,!1)}}}}function W(r){const n=_.__externref_table_alloc();return _.__wbindgen_externrefs.set(n,r),n}function M(r){const n=typeof r;if(n=="number"||n=="boolean"||r==null)return`${r}`;if(n=="string")return`"${r}"`;if(n=="symbol"){const i=r.description;return i==null?"Symbol":`Symbol(${i})`}if(n=="function"){const i=r.name;return typeof i=="string"&&i.length>0?`Function(${i})`:"Function"}if(Array.isArray(r)){const i=r.length;let c="[";i>0&&(c+=M(r[0]));for(let o=1;o1)t=e[1];else return toString.call(r);if(t=="Object")try{return"Object("+JSON.stringify(r)+")"}catch{return"Object"}return r instanceof Error?`${r.name}: ${r.message} +${r.stack}`:t}function v(r,n){return r=r>>>0,h().subarray(r/1,r/1+n)}let m=null;function y(){return(m===null||m.buffer.detached===!0||m.buffer.detached===void 0&&m.buffer!==_.memory.buffer)&&(m=new DataView(_.memory.buffer)),m}function b(r,n){return r=r>>>0,F(r,n)}let j=null;function h(){return(j===null||j.byteLength===0)&&(j=new Uint8Array(_.memory.buffer)),j}function A(r,n){try{return r.apply(this,n)}catch(e){const t=W(e);_.__wbindgen_exn_store(t)}}function g(r){return r==null}function w(r,n){const e=n(r.length*1,1)>>>0;return h().set(r,e/1),a=r.length,e}function k(r,n){const e=n(r.length*4,4)>>>0;for(let t=0;t>>0;return h().subarray(f,f+l.length).set(l),a=l.length,f}let t=r.length,i=n(t,1)>>>0;const c=h();let o=0;for(;o127)break;c[i+o]=l}if(o!==t){o!==0&&(r=r.slice(o)),i=e(i,t,t=o+r.length*3,1)>>>0;const l=h().subarray(i+o,i+t),f=x.encodeInto(r,l);o+=f.written,i=e(i,t,o,1)>>>0}return a=o,i}function s(r){const n=_.__wbindgen_externrefs.get(r);return _.__externref_table_dealloc(r),n}let I=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});I.decode();const T=2146435072;let S=0;function F(r,n){return S+=n,S>=T&&(I=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),I.decode(),S=n),I.decode(h().subarray(r,r+n))}const x=new TextEncoder;"encodeInto"in x||(x.encodeInto=function(r,n){const e=x.encode(r);return n.set(e),{read:r.length,written:e.length}});let a=0,_;function E(r,n){return _=r.exports,m=null,j=null,_.__wbindgen_start(),_}async function R(r,n){if(typeof Response=="function"&&r instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(r,n)}catch(i){if(r.ok&&e(r.type)&&r.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",i);else throw i}const t=await r.arrayBuffer();return await WebAssembly.instantiate(t,n)}else{const t=await WebAssembly.instantiate(r,n);return t instanceof WebAssembly.Instance?{instance:t,module:r}:t}function e(t){switch(t){case"basic":case"cors":case"default":return!0}return!1}}function wn(r){if(_!==void 0)return _;r!==void 0&&(Object.getPrototypeOf(r)===Object.prototype?{module:r}=r:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));const n=O();r instanceof WebAssembly.Module||(r=new WebAssembly.Module(r));const e=new WebAssembly.Instance(r,n);return E(e)}async function pn(r){if(_!==void 0)return _;r!==void 0&&(Object.getPrototypeOf(r)===Object.prototype?{module_or_path:r}=r:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),r===void 0&&(r=new URL(""+new URL("rl_replay_subtr_actor_bg-BjSK7HJ9.wasm",import.meta.url).href,import.meta.url));const n=O();(typeof r=="string"||typeof Request=="function"&&r instanceof Request||typeof URL=="function"&&r instanceof URL)&&(r=fetch(r));const{instance:e,module:t}=await R(await r,n);return E(e)}export{pn as default,U as get_column_headers,B as get_legacy_stats_timeline_json,D as get_ndarray_with_info,N as get_replay_bundle_json_parts_with_progress,L as get_replay_bundle_json_with_progress,$ as get_replay_frames_data,V as get_replay_frames_data_json_with_progress,q as get_replay_frames_data_with_progress,z as get_replay_info,C as get_replay_meta,J as get_stats_timeline,P as get_stats_timeline_json,H as get_stats_timeline_json_parts,wn as initSync,K as main,X as new_training_pack,Y as parse_replay,G as parse_training_pack,Q as parse_training_pack_lossless,Z as serialize_training_pack,nn as training_pack_add_round,en as training_pack_add_round_archetype,tn as training_pack_append_rounds,rn as training_pack_duplicate_round,_n as training_pack_from_lossless,cn as training_pack_insert_round,on as training_pack_move_round,sn as training_pack_remove_round,an as training_pack_remove_round_archetype,fn as training_pack_round_archetypes,ln as training_pack_set_round_archetype,un as training_pack_set_round_ball,dn as training_pack_set_round_time_limit,gn as update_training_pack_metadata,bn as validate_replay}; diff --git a/crates/rocket-sense-server/static/subtr-actor/assets/rl_replay_subtr_actor_bg-Xy9_Ya42.wasm b/crates/rocket-sense-server/static/subtr-actor/assets/rl_replay_subtr_actor_bg-BjSK7HJ9.wasm similarity index 50% rename from crates/rocket-sense-server/static/subtr-actor/assets/rl_replay_subtr_actor_bg-Xy9_Ya42.wasm rename to crates/rocket-sense-server/static/subtr-actor/assets/rl_replay_subtr_actor_bg-BjSK7HJ9.wasm index 28187c21..140cd489 100644 Binary files a/crates/rocket-sense-server/static/subtr-actor/assets/rl_replay_subtr_actor_bg-Xy9_Ya42.wasm and b/crates/rocket-sense-server/static/subtr-actor/assets/rl_replay_subtr_actor_bg-BjSK7HJ9.wasm differ diff --git a/crates/rocket-sense-server/static/subtr-actor/assets/wasm.worker-Bj4v8ZR2.js b/crates/rocket-sense-server/static/subtr-actor/assets/wasm.worker-Bj4v8ZR2.js deleted file mode 100644 index 5e7d7d50..00000000 --- a/crates/rocket-sense-server/static/subtr-actor/assets/wasm.worker-Bj4v8ZR2.js +++ /dev/null @@ -1 +0,0 @@ -(function(){"use strict";function ge(e,t,n){const r=G(e,c.__wbindgen_malloc),o=w,a=c.get_replay_frames_data_json_with_progress(r,o,t,Z(n)?4294967297:n>>>0);if(a[3])throw V(a[2]);var i=W(a[0],a[1]).slice();return c.__wbindgen_free(a[0],a[1]*1,1),i}function be(e){const t=G(e,c.__wbindgen_malloc),n=w,r=c.validate_replay(t,n);if(r[2])throw V(r[1]);return V(r[0])}function ye(){return{__proto__:null,"./rl_replay_subtr_actor_bg.js":{__proto__:null,__wbg_Error_8c4e43fe74559d73:function(t,n){return Error(I(t,n))},__wbg_String_8f0eb39a4a4c2f66:function(t,n){const r=String(n),o=L(r,c.__wbindgen_malloc,c.__wbindgen_realloc),a=w;O().setInt32(t+4,a,!0),O().setInt32(t+0,o,!0)},__wbg___wbindgen_is_string_cd444516edc5b180:function(t){return typeof t=="string"},__wbg___wbindgen_string_get_72fb696202c56729:function(t,n){const r=n,o=typeof r=="string"?r:void 0;var a=Z(o)?0:L(o,c.__wbindgen_malloc,c.__wbindgen_realloc),i=w;O().setInt32(t+4,i,!0),O().setInt32(t+0,a,!0)},__wbg___wbindgen_throw_be289d5034ed271b:function(t,n){throw new Error(I(t,n))},__wbg_call_4708e0c13bdc8e95:function(){return K(function(t,n,r){return t.call(n,r)},arguments)},__wbg_error_7534b8e9a36f1ab4:function(t,n){let r,o;try{r=t,o=n,console.error(I(t,n))}finally{c.__wbindgen_free(r,o,1)}},__wbg_log_d095c16a726a937c:function(t,n){console.log(I(t,n))},__wbg_new_361308b2356cecd0:function(){return new Object},__wbg_new_3eb36ae241fe6f44:function(){return new Array},__wbg_new_8a6f238a6ece86ea:function(){return new Error},__wbg_new_dca287b076112a51:function(){return new Map},__wbg_new_from_slice_a3d2629dc1826784:function(t,n){return new Uint8Array(W(t,n))},__wbg_push_8ffdcb2063340ba5:function(t,n){return t.push(n)},__wbg_set_1eb0999cf5d27fc8:function(t,n,r){return t.set(n,r)},__wbg_set_3f1d0b984ed272ed:function(t,n,r){t[n]=r},__wbg_set_6cb8631f80447a67:function(){return K(function(t,n,r){return Reflect.set(t,n,r)},arguments)},__wbg_set_f43e577aea94465b:function(t,n,r){t[n>>>0]=r},__wbg_stack_0ed75d68575b0f3c:function(t,n){const r=n.stack,o=L(r,c.__wbindgen_malloc,c.__wbindgen_realloc),a=w;O().setInt32(t+4,a,!0),O().setInt32(t+0,o,!0)},__wbindgen_cast_0000000000000001:function(t){return t},__wbindgen_cast_0000000000000002:function(t){return t},__wbindgen_cast_0000000000000003:function(t,n){return I(t,n)},__wbindgen_cast_0000000000000004:function(t){return BigInt.asUintN(64,t)},__wbindgen_init_externref_table:function(){const t=c.__wbindgen_externrefs,n=t.grow(4);t.set(0,void 0),t.set(n+0,void 0),t.set(n+1,null),t.set(n+2,!0),t.set(n+3,!1)}}}}function pe(e){const t=c.__externref_table_alloc();return c.__wbindgen_externrefs.set(t,e),t}function W(e,t){return e=e>>>0,S().subarray(e/1,e/1+t)}let x=null;function O(){return(x===null||x.buffer.detached===!0||x.buffer.detached===void 0&&x.buffer!==c.memory.buffer)&&(x=new DataView(c.memory.buffer)),x}function I(e,t){return e=e>>>0,we(e,t)}let E=null;function S(){return(E===null||E.byteLength===0)&&(E=new Uint8Array(c.memory.buffer)),E}function K(e,t){try{return e.apply(this,t)}catch(n){const r=pe(n);c.__wbindgen_exn_store(r)}}function Z(e){return e==null}function G(e,t){const n=t(e.length*1,1)>>>0;return S().set(e,n/1),w=e.length,n}function L(e,t,n){if(n===void 0){const s=D.encode(e),f=t(s.length,1)>>>0;return S().subarray(f,f+s.length).set(s),w=s.length,f}let r=e.length,o=t(r,1)>>>0;const a=S();let i=0;for(;i127)break;a[o+i]=s}if(i!==r){i!==0&&(e=e.slice(i)),o=n(o,r,r=i+e.length*3,1)>>>0;const s=S().subarray(o+i,o+r),f=D.encodeInto(e,s);i+=f.written,o=n(o,r,i,1)>>>0}return w=i,o}function V(e){const t=c.__wbindgen_externrefs.get(e);return c.__externref_table_dealloc(e),t}let R=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});R.decode();const he=2146435072;let j=0;function we(e,t){return j+=t,j>=he&&(R=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),R.decode(),j=t),R.decode(S().subarray(e,e+t))}const D=new TextEncoder;"encodeInto"in D||(D.encodeInto=function(e,t){const n=D.encode(e);return t.set(n),{read:e.length,written:n.length}});let w=0,c;function ke(e,t){return c=e.exports,x=null,E=null,c.__wbindgen_start(),c}async function xe(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(o){if(e.ok&&n(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",o);else throw o}const r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{const r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}async function Ae(e){if(c!==void 0)return c;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0&&(e=new URL(""+new URL("rl_replay_subtr_actor_bg-Xy9_Ya42.wasm",self.location.href).href,self.location.href));const t=ye();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));const{instance:n,module:r}=await xe(await e,t);return ke(n)}const q="octane",ve={breakout:{kind:"breakout",label:"Breakout",length:131.4924,width:80.521,height:30.3,slopeDegrees:-.9795,groundHeightFront:43.8976,groundHeightBack:46.1454,offset:13.88,elevation:17.05},dominus:{kind:"dominus",label:"Dominus",length:127.9268,width:83.27995,height:31.3,slopeDegrees:-.9635,groundHeightFront:47.2238,groundHeightBack:49.3749,offset:13.88,elevation:17.05},hybrid:{kind:"hybrid",label:"Hybrid",length:127.0192,width:82.18787,height:34.15907,slopeDegrees:-.5499,groundHeightFront:54.0982,groundHeightBack:55.3173,offset:13.88,elevation:17.05},merc:{kind:"merc",label:"Merc",length:120.72,width:76.71,height:41.66,slopeDegrees:.28,groundHeightFront:60.76,groundHeightBack:61.35,offset:13.88,elevation:17.05},octane:{kind:"octane",label:"Octane",length:118.0074,width:84.19941,height:36.15907,slopeDegrees:-.5518,groundHeightFront:55.1449,groundHeightBack:56.2814,offset:13.88,elevation:17.05},plank:{kind:"plank",label:"Plank",length:128.8198,width:84.67036,height:29.3944,slopeDegrees:-.3447,groundHeightFront:44.998,groundHeightBack:45.773,offset:13.88,elevation:17.05}},Oe={"16batmobile":"plank","70dodgechargerrt":"dominus","89batmobile":"dominus","99nissanskylinegtrr34":"hybrid",aftershock:"dominus",animusgp:"breakout",artemis:"plank",artemisg1:"plank",artemisgxt:"plank",astonmartinvalhalla:"breakout",backfire:"octane",backtothefuturetimemachine:"dominus",batmobile1989:"dominus",battlebus:"merc",breakout:"breakout",breakouttypes:"breakout",centio:"plank",centiov17:"plank",cyclone:"breakout",deloreantimemachine:"dominus",diestro:"dominus",dominus:"dominus",dominusgt:"dominus",endo:"hybrid",esper:"hybrid",fast4wd:"octane",fennec:"octane",gazellagt:"dominus",gizmo:"octane",grog:"octane",guardian:"dominus",guardiang1:"dominus",guardiangxt:"dominus",hotshot:"dominus",icecharger:"dominus",imperatordt5:"dominus",jager619rs:"hybrid",jurassicjeepwrangler:"octane",mantis:"plank",marauder:"octane",masamune:"dominus",maverick:"dominus",maverickg1:"dominus",maverickgxt:"dominus",mclaren570s:"dominus",merc:"merc",mr11:"dominus",nimbus:"hybrid",octane:"octane",octanezsr:"octane",paladin:"plank",proteus:"octane",ripper:"dominus",roadhog:"octane",roadhogxl:"octane",samurai:"breakout",scarab:"octane",takumi:"octane",takumirxt:"octane",thedarkknightstumbler:"octane",thedarkknightrisestumbler:"octane",triton:"octane",twinmilliii:"plank",twinzer:"octane",venom:"hybrid",vulcan:"octane",werewolf:"dominus",xdevil:"hybrid",xdevilmk2:"hybrid",zippy:"octane","1966cadillacdeville":"breakout",ace:"breakout",admiral:"dominus",azura:"breakout",behemoth:"merc",beskar:"hybrid",bmwm3e30:"dominus",bmwm2racing:"dominus",bmwm4gt3evo:"dominus",bmw1series:"octane",bmw1seriesrle:"octane",bmwm240i:"dominus",bugatticentodieci:"plank",bumblebee:"dominus",bumblebeecar:"dominus",chevroletastro:"merc",chevroletcorvettestingray:"breakout",chevroletcorvettezr1:"breakout",chryslerpacifica:"hybrid",corlay:"octane",cyberpunkquadra:"breakout",defenderd7xr:"merc",diesel:"breakout",dodgechargerdaytonascatpack:"dominus",dodgerchargerdaytonascatpack:"dominus",dominusneon:"dominus",emperor:"breakout",emperorii:"breakout",emperoriifrozen:"breakout",emperoriiscorched:"breakout",fastfuriousdodgecharger:"dominus",fastandfuriousdodgecharger:"dominus",fastandfuriousdodgechargersrthellcat:"dominus",fastfuriousmazdarx7:"breakout",fastandfuriousmazdarx7:"breakout",fastfuriousnissanskyline:"hybrid",fastandfuriousnissanskyline:"hybrid",fastfuriouspontiacfiero:"hybrid",fastandfuriouspontiacfiero:"hybrid",fenneczrf:"octane",ferrari296gtb:"dominus",ferrarif40:"breakout",fordbroncoraptorrle:"merc",fordf150rle:"octane",fordmustanggtd:"dominus",fordmustangshelbygt500:"dominus",fordmustangmacherle:"octane",fordmustangshelbygt350rrle:"dominus",formula12021:"plank",formula12022:"plank",fuse:"breakout",havoc:"breakout",hearse:"hybrid",homerscar:"dominus",hondacivictyper:"octane",hondacivictyperle:"octane",jackal:"octane",jeepwranglerrubicon:"octane",kitt:"dominus",knightindustries2000:"dominus",komodo:"breakout",lamborghinicountachlpi8004:"dominus",lamborghinihuracansto:"dominus",lamborghiniurus:"hybrid",lamborghiniurusse:"hybrid",lightningmcqueen:"dominus",lightningmcqueencar:"dominus",lockjaw:"dominus",luiginsr:"octane",maestro:"dominus",magnifique:"dominus",magnifiquegxt:"dominus",mako:"breakout",mamba:"dominus",mario:"octane",marionsr:"octane",maven:"dominus",mclaren765lt:"dominus",mclarenp1:"dominus",mclarensenna:"breakout",megastar:"breakout",mercedesamggt63s:"dominus",mercedesbenzcla:"dominus",mudcat:"octane",mudcatg1:"octane",mudcatgxt:"octane",nissan350z:"dominus",nissanfairladyz:"dominus",nissanfairladyzrle:"dominus",nissansilvia:"hybrid",nissansilviarle:"hybrid",nissanskylinegtr:"hybrid",nissanskylinegtrr32:"hybrid",nissanzperformance:"dominus",nissanzperformancecar:"dominus",outlaw:"octane",outlawgxt:"octane",pattywagon:"octane",pizzaplanetdeliverytruck:"merc",pontiacfirebird:"breakout",porsche918spyder:"breakout",porsche911gt3rs:"dominus",porsche911turbo:"dominus",porsche911turborle:"dominus",primo:"hybrid",psyclops:"octane",quadraturbor:"breakout",ram1500rho:"hybrid",recoilav:"merc",redline:"breakout",revolver:"breakout",rivianr1s:"hybrid",scorpion:"dominus",shokunin:"octane",shokuningxt:"octane",stampede:"merc",teslacybertruck:"hybrid",themysterymachine:"merc",theincredibile:"breakout",turtlevan:"merc",voidburn:"hybrid",volkswagengolfgti:"octane",volkswagengolfgtirle:"octane",xentari:"octane",zefira:"dominus",breakoutx:"breakout",nexus:"breakout",nexussc:"breakout",whiplash:"breakout","007sastonmartindbs":"dominus","007sastonmartinvalhalla":"dominus",batmobile2022:"dominus",chikara:"dominus",chikarag1:"dominus",chikaragxt:"dominus",ecto1:"dominus",ecto1ghostbusters:"dominus",fastfuriousdodgechargersrthellcat:"dominus",gazellagthotwheels:"dominus",kittknightrider:"dominus",lamborghinihuracnsto:"dominus",mr11hotwheels:"dominus",nascarchevroletcamaro:"dominus",nascarfordmustang:"dominus",nascartoyotacamry:"dominus",nascarnextgenchevroletcamaro:"dominus",nascarnextgenchevroletcamaro2022:"dominus",nascarnextgenfordmustang:"dominus",nascarnextgenfordmustang2022:"dominus",nascarnextgentoyotacamry:"dominus",nascarnextgentoyotacamry2022:"dominus",nemesis:"dominus",peregrinett:"dominus",perigrinett:"dominus",ronin:"dominus",roning1:"dominus",roningxt:"dominus",samusgunship:"dominus",samusgunshipnintendoexclusive:"dominus",tyranno:"dominus",tyrannogxt:"dominus",insidio:"hybrid",jager619:"hybrid",jger619:"hybrid",jger619rs:"hybrid",r3mx:"hybrid",r3mxgxt:"hybrid",tygris:"hybrid",nomad:"merc",nomadgxt:"merc","007sastonmartindb5":"octane",armadillo:"octane",armadilloxboxexclusive:"octane",boneshaker:"octane",dingo:"octane",fast4wdhotwheels:"octane",harbinger:"octane",harbingergxt:"octane",hogsticker:"octane",hogstickerxboxexclusive:"octane",sweettooth:"octane",sweettoothplaystationexclusive:"octane",thedarkknighttumbler:"octane",batmobile2016:"plank",sentinel:"plank"};function Se(e){const t={};for(const[n,r]of e)for(const o of n)t[o]=r;return t}const Te=Se([[[22,1416,1894,1932,3031,3311,6243,6489,7651,7696,7890,7901,8006,8360,8361,8565,8566,8669,9357,10697,10698,10817,10822,11038,11394,11505,11677,11800,11933,11949,12173,12315,12361,12484],"breakout"],[[29,403,597,600,1018,1171,1286,1675,1689,1883,2070,2268,2666,2950,2951,3155,3156,3157,3265,3426,3875,3879,3880,4014,4155,4367,4472,4473,4745,4770,4781,4861,4864,5709,5773,5823,5858,5964,5979,6122,6244,6247,6260,6836,7211,7337,7338,7341,7343,7415,7512,7532,7593,7772,8454,9053,9088,9089,9140,9388,9894,10094,10440,10441,10694,10695,11016,11095,11315,11336,11534,11941,11996,12106,12142,12262,12286,12325,12382,12563,12669],"dominus"],[[28,31,1159,1317,1624,1856,2269,3451,3582,3702,5470,5488,5879,7012,9084,9085,9427,10044,10805,11138,11141,11379,11932,12569,12652],"hybrid"],[[30,4780,7336,7477,7815,7979,10689,11098,11736,11905,11950,12318,12335],"merc"],[[21,23,25,26,27,402,404,523,607,625,723,1172,1295,1300,1475,1478,1533,1568,1623,2665,2853,2919,2949,4284,4318,4319,4320,4782,4906,5020,5039,5188,5361,5547,5713,5837,5951,6939,7947,7948,8383,8806,8807,10896,10897,10900,10901,11314,11603,12104,12105],"octane"],[[24,803,1603,1691,1919,3594,3614,3622,4268,5265,7052,8524],"plank"]]);function J(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function Q(e){if(!e)return null;switch(J(e)){case"breakout":return"breakout";case"dominus":return"dominus";case"hybrid":return"hybrid";case"merc":return"merc";case"octane":return"octane";case"batmobile":case"plank":return"plank";default:return null}}function ee(e){return e?Oe[J(e)]??null:null}function Ie(e){return Q(e)??ee(e)}function Ee(e){return ve[e]}function H(e,t){if(!(!e||typeof e!="object")){if("Str"in e&&typeof e.Str=="string"){t.push(e.Str);return}if("Name"in e&&typeof e.Name=="string"){t.push(e.Name);return}if("Byte"in e&&e.Byte&&typeof e.Byte=="object"){const n=e.Byte;typeof n.kind=="string"&&t.push(n.kind),typeof n.value=="string"&&t.push(n.value);return}if("Struct"in e&&e.Struct&&typeof e.Struct=="object"){const n=e.Struct;if(typeof n.name=="string"&&t.push(n.name),Array.isArray(n.fields))for(const r of n.fields)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),H(r[1],t));return}if("Array"in e&&Array.isArray(e.Array)){for(const n of e.Array)if(Array.isArray(n))for(const r of n)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),H(r[1],t))}}}function De(e){const t=Q(e?.car_hitbox_family);if(t)return t;const n=e?.car_body_id;if(typeof n=="number"){const i=Te[n];if(i)return i}const r=ee(e?.car_body_name);if(r)return r;const o=e?.stats;if(!o)return q;const a=[];for(const[i,s]of Object.entries(o))a.push(i),H(s,a);for(const i of a){const s=Ie(i);if(s)return s}return q}function k(e){const[t,n]=Object.entries(e)[0]??["Unknown","unknown"];return typeof n=="string"||typeof n=="number"?`${t}:${n}`:n&&typeof n=="object"?`${t}:${JSON.stringify(n)}`:`${t}:${JSON.stringify(n)}`}function B(e,t){return Math.max(0,e-t)}function te(e){return new Map(e.map(t=>[t.id,t]))}const y=70,ne=73,Be=3072,Pe=4096,Ne=1792,Re=4184,ze=940,Me=3308,Fe=2816,re=3584,Ce=2484,Le=1788,Ve=2300,je=2048,He=1036,Ue=1024,Ye=1024,$e=4240,oe=34;function z(e,t,n,r,o){e.push({index:e.length,padId:null,size:o,position:{x:t,y:n,z:r},events:[]})}function M(e,t,n,r,o){z(e,-t,n,r,o),z(e,t,n,r,o)}function U(e,t,n,r,o){z(e,t,-n,r,o),z(e,t,n,r,o)}function T(e,t,n,r,o){M(e,t,-n,r,o),M(e,t,n,r,o)}function Xe(){const e=[];return U(e,0,$e,y,"small"),T(e,Ne,Re,y,"small"),T(e,Be,Pe,ne,"big"),T(e,ze,Me,y,"small"),U(e,0,Fe,y,"small"),T(e,re,Ce,y,"small"),T(e,Le,Ve,y,"small"),T(e,je,He,y,"small"),U(e,0,Ye,y,"small"),M(e,re,0,ne,"big"),M(e,Ue,0,y,"small"),e}function Y(e){if(e==="Available")return!0;if(e&&typeof e=="object"){if("Available"in e)return!0;if("PickedUp"in e)return!1;const t=e.kind;if(t==="Available")return!0;if(t==="PickedUp")return!1}return null}function We(e){return e==="big"||e==="Big"?"big":e==="small"||e==="Small"?"small":null}function Ke(e){let t=null;for(const n of e){const r=Y(n.kind);if(r===!1){t=n.time;continue}if(r===!0&&t!==null)return n.time-t>=7?"big":"small"}return null}function Ze(e,t,n,r){const o=te(t),a=new Map;for(const l of e.boost_pad_events??[]){if(Y(l.kind)===null){r?.advance();continue}const u=a.get(l.pad_id);u?u.push(l):a.set(l.pad_id,[l]),r?.advance()}const i=e.boost_pads;if(!i||i.length===0)return r?.advance(oe),Xe();const s=[...i].sort((l,d)=>l.index-d.index),f=new Array(s.length);for(let l=0;l=72?"big":"small"),p=b.sort((_,h)=>_.time-h.time),m=new Array(p.length);for(let _=0;_=0?e.frame:null}function Ge(e,t){if(typeof e.time=="number"&&Number.isFinite(e.time))return e.time;const n=$(e);if(n===null)return null;const r=t.frame_data.metadata_frames[n]?.time;return typeof r=="number"&&Number.isFinite(r)?r:null}function qe(e,t){return`bookmark:${$(e)??"unknown"}:${e.description||"tick-mark"}:${t}`}function Je(e,t,n){return(e.replay_tick_marks??[]).flatMap((r,o)=>{n?.advance();const a=Ge(r,e);return a===null?[]:[{id:qe(r,o),description:r.description,frame:$(r),time:B(a,t)}]})}function Qe(e){const t=e.description.trim()||"Replay bookmark";return{id:e.id,time:e.time,seekTime:e.time,frame:e.frame??void 0,kind:"bookmark",label:t,shortLabel:"BM",iconName:"bookmark"}}const A={distance:270,height:100,pitch:-4,fov:110},et=.005,tt=Number.POSITIVE_INFINITY,nt=!0,rt=.15,ot=10,at=.1,it=10;function ae(e){const t=Math.hypot(e.x,e.y,e.z);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t}}function ie(e){const t=Math.hypot(e.x,e.y,e.z,e.w);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t,w:e.w/t}}function se(e,t){return{w:e.w*t.w-e.x*t.x-e.y*t.y-e.z*t.z,x:e.w*t.x+e.x*t.w+e.y*t.z-e.z*t.y,y:e.w*t.y-e.x*t.z+e.y*t.w+e.z*t.x,z:e.w*t.z+e.x*t.y-e.y*t.x+e.z*t.w}}function ce(e,t){const n=se(se(t,{x:e.x,y:e.y,z:e.z,w:0}),{x:-t.x,y:-t.y,z:-t.z,w:t.w});return{x:n.x,y:n.y,z:n.z}}function st(e){if(e==="Empty")return{position:null,linearVelocity:null,angularVelocity:null,rotation:null};const t=e.Data.rigid_body;return{position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:ie(t.rotation)}}function le(e){return e==null?null:Math.max(-1,Math.min(1,(e-128)/128))}function ue(e){return e==null?null:(e>127?e-256:e)*Math.PI/128}function de(e){return e?{x:e[0],y:e[1],z:e[2]}:null}const ct={cameraPitch:null,cameraYaw:null,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null};function lt(e){if(e==="Empty")return{isPresent:!1,position:null,linearVelocity:null,angularVelocity:null,rotation:null,forward:null,up:null,boostAmount:0,boostFraction:0,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,...ct};const t=e.Data.rigid_body,n=ie(t.rotation),r=n?ae(ce({x:1,y:0,z:0},n)):null,o=n?ae(ce({x:0,y:0,z:1},n)):null,a=e.Data.camera,i=e.Data.input;return{isPresent:!0,position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:n,forward:r,up:o,boostAmount:e.Data.boost_amount,boostFraction:Math.max(0,Math.min(1,e.Data.boost_amount/255)),boostActive:e.Data.boost_active,powerslideActive:e.Data.powerslide_active,jumpActive:e.Data.jump_active,doubleJumpActive:e.Data.double_jump_active,dodgeActive:e.Data.dodge_active,cameraPitch:ue(a?.pitch),cameraYaw:ue(a?.yaw),throttle:le(i?.throttle),steer:le(i?.steer),dodgeImpulse:de(i?.dodge_impulse),dodgeTorque:de(i?.dodge_torque)}}function ut(e){return e.position!==null}function dt(e){return{...e,isPresent:!1,linearVelocity:null,angularVelocity:null,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null}}function mt(e){let t=null,n=null;for(let r=0;r=t.length-1)return;let o=P(t[r].position);for(let a=r+1;aat){o=P(s.position);continue}if(ft(o,s.position)>it){o=P(s.position);continue}const u={x:(i.linearVelocity.x+s.linearVelocity.x)/2,y:(i.linearVelocity.y+s.linearVelocity.y)/2,z:(i.linearVelocity.z+s.linearVelocity.z)/2},b={x:o.x+u.x*d,y:o.y+u.y*d,z:o.z+u.z*d},g=(a-r)%n.smoothingAnchorInterval===0?.5:n.smoothingBlendFactor;o={x:b.x*(1-g)+s.position.x*g,y:b.y*(1-g)+s.position.y*g,z:b.z*(1-g)+s.position.z*g},s.position=P(o)}}function _t(e){return{motionSmoothing:e.motionSmoothing??nt,smoothingBlendFactor:e.smoothingBlendFactor??rt,smoothingAnchorInterval:Math.max(1,e.smoothingAnchorInterval??ot)}}function _e(){return typeof performance>"u"?Date.now():performance.now()}function gt(e){const t=e.meta.team_zero.length+e.meta.team_one.length,n=e.frame_data.players.reduce((i,[,s])=>i+s.frames.length,0),r=e.boost_pads?.length??oe,o=e.boost_pad_events?.length??0,a=(e.goal_events?.length??0)+(e.player_stat_events?.length??0)+(e.demolish_infos?.length??0)+(e.replay_tick_marks?.length??0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,n),Math.max(1,e.frame_data.ball_data.frames.length),Math.max(1,r+o),Math.max(1,a)].reduce((i,s)=>i+s,0)}function bt(e){const t=e.frame_data.players.reduce((n,[,r])=>n+r.frames.length,0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,e.frame_data.ball_data.frames.length)].reduce((n,r)=>n+r,0)}function yt(e,t,n={}){const r=gt(e),o=bt(e);let a=0,i=0,s=-1,f=-1,l=_e();const d=n.yieldEveryMs??Number.POSITIVE_INFINITY,u=n.progressReportMinDelta??et,b=Math.max(1,n.progressReportFrameInterval??tt),g=()=>{if(!t)return!1;const m=Math.max(0,Math.min(1,a/r));if(m<=s)return!1;const h=i-f>=b;return m>=1||m-s>=u||h?(s=m,f=i,t(m,{progress:m,processedFrames:Math.min(i,o),totalFrames:o,processedUnits:a,totalUnits:r}),!0):!1},p=(m=!1)=>{const _=_e();return!m&&_-lr===t)?.[1];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function kt(e){const t=wt(e?.stats);return{fov:v(t,"CameraFOV")??A.fov,height:v(t,"CameraHeight")??A.height,pitch:v(t,"CameraPitch")??A.pitch,distance:v(t,"CameraDistance")??A.distance,stiffness:v(t,"CameraStiffness")??A.stiffness,swivelSpeed:v(t,"CameraSwivelSpeed")??A.swivelSpeed,transitionSpeed:v(t,"CameraTransitionSpeed")??A.transitionSpeed}}function xt(e,t){const n=new Map,r=new Map,o=[...e.meta.team_zero,...e.meta.team_one];if(o.length===0)return t?.advance(),{byId:n,byName:r};for(const a of o)r.set(a.name,a),a.remote_id&&n.set(k(a.remote_id),a),t?.advance();return{byId:n,byName:r}}function At(e){const t=new Map;for(const[n,r]of e.player_camera_events??[])t.set(k(n),r.map(o=>({frame:o.frame,ballCamActive:o.ball_cam_active,behindViewActive:o.behind_view_active,driving:o.driving})));return t}function vt(e,t){const n=new Set(e.meta.team_zero.map(f=>f.name)),r=new Set(e.meta.team_one.map(f=>f.name)),o=xt(e,t),a=At(e),i=[];let s=0;for(const[f,l]of e.frame_data.players){const d=new Array(l.frames.length);let u;for(let m=0;mt.time!==n.time?t.time-n.time:(t.frame??0)-(n.frame??0))}function Tt(e,t,n){const r=e.player?k(e.player):null,o=r?t.get(r)?.name??r:null,a=o?`${o} scored`:"Goal";return{id:X("goal",e.frame,r??"team"),time:B(e.time,n),frame:e.frame,kind:"goal",label:a,shortLabel:"G",playerId:r,playerName:o,isTeamZero:e.scoring_team_is_team_0}}function It(e,t,n){const r=k(e.player),o=t.get(r)?.name??r,a=e.kind.toLowerCase(),i=e.kind==="Shot"?"shot":e.kind==="Save"?"save":"assist",s=e.kind==="Shot"?"SH":e.kind==="Save"?"SV":"A";return{id:X(a,e.frame,r),time:B(e.time,n),frame:e.frame,kind:a,label:`${o} ${i}`,shortLabel:s,playerId:r,playerName:o,location:e.shot?.shot_touch_position??e.shot?.ball_position??null,shot:e.shot??null,isTeamZero:e.is_team_0}}function Et(e,t,n){const r=k(e.attacker),o=k(e.victim),a=t.get(r),i=t.get(o);return{id:X("demo",e.frame,`${r}:${o}`),time:B(e.time,n),frame:e.frame,kind:"demo",label:`${a?.name??r} demoed ${i?.name??o}`,shortLabel:"D",playerId:r,playerName:a?.name??r,secondaryPlayerId:o,secondaryPlayerName:i?.name??o,location:e.victim_location,isTeamZero:a?.isTeamZero??null}}function Dt(e,t,n,r,o){const a=te(t),i=[];for(const s of e.goal_events??[])i.push(Tt(s,a,r)),o?.advance();for(const s of e.player_stat_events??[])i.push(It(s,a,r)),o?.advance();for(const s of e.demolish_infos??[])i.push(Et(s,a,r)),o?.advance();for(const s of n)i.push(Qe(s));return i.length===0&&o?.advance(),St(i)}function Bt(e,t={}){const n=yt(e,t.onProgress,{progressReportMinDelta:t.progressReportMinDelta,progressReportFrameInterval:t.progressReportFrameInterval}),r=e.frame_data.metadata_frames[0]?.time??0,o=pt(e,n),a=vt(e,n),i=Ot(e,n),s=_t(t);fe(o,i,s);for(const u of a)fe(o,u.frames,s);const f=Ze(e,a,r,n),l=Je(e,r,n),d=Dt(e,a,l,r,n);return n.finish(),{frameCount:o.length,duration:o.at(-1)?.time??0,rawStartTime:r,frames:o,ballFrames:i,boostPads:f,players:a,tickMarks:l,timelineEvents:d,teamZeroNames:e.meta.team_zero.map(u=>u.name),teamOneNames:e.meta.team_one.map(u=>u.name)}}function F(e){if(e instanceof Map)return Object.fromEntries(Array.from(e.entries()).map(([t,n])=>[t,F(n)]));if(Array.isArray(e))return e.map(t=>F(t));if(e&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=F(r);return t}return e}async function Pt(){const e=Ae;typeof e=="function"&&await e()}function N(e){self.postMessage(e)}self.onmessage=async e=>{if(e.data.type==="load-replay")try{await Pt();const t=new Uint8Array(e.data.bytes);N({type:"progress",progress:{stage:"validating",progress:0}});const n=F(be(t));if(!n.valid)throw new Error(n.error??"Replay validation failed");const r=ge(t,s=>{N({type:"progress",progress:s})},e.data.reportEveryNFrames);N({type:"progress",progress:{stage:"normalizing",progress:0}});const o=JSON.parse(new TextDecoder().decode(r)),a=Bt(o,{motionSmoothing:e.data.motionSmoothing,smoothingBlendFactor:e.data.smoothingBlendFactor,smoothingAnchorInterval:e.data.smoothingAnchorInterval,progressReportFrameInterval:e.data.reportEveryNFrames,onProgress(s){N({type:"progress",progress:{stage:"normalizing",progress:s}})}}),i=new TextEncoder().encode(JSON.stringify(a));self.postMessage({type:"done",rawBuffer:r.buffer,replayBuffer:i.buffer},[r.buffer,i.buffer])}catch(t){N({type:"error",error:t instanceof Error?t.message:String(t)})}}})(); diff --git a/crates/rocket-sense-server/static/subtr-actor/assets/wasm.worker-zm5sJFWS.js b/crates/rocket-sense-server/static/subtr-actor/assets/wasm.worker-zm5sJFWS.js new file mode 100644 index 00000000..1f671e38 --- /dev/null +++ b/crates/rocket-sense-server/static/subtr-actor/assets/wasm.worker-zm5sJFWS.js @@ -0,0 +1,2 @@ +(function(){"use strict";function ge(e,t,n){const r=q(e,c.__wbindgen_malloc),o=p,a=c.get_replay_frames_data_json_with_progress(r,o,t,v(n)?4294967297:n>>>0);if(a[3])throw Y(a[2]);var i=H(a[0],a[1]).slice();return c.__wbindgen_free(a[0],a[1]*1,1),i}function ye(e){const t=q(e,c.__wbindgen_malloc),n=p,r=c.validate_replay(t,n);if(r[2])throw Y(r[1]);return Y(r[0])}function pe(){return{__proto__:null,"./rl_replay_subtr_actor_bg.js":{__proto__:null,__wbg_Error_8c4e43fe74559d73:function(t,n){return Error(E(t,n))},__wbg_Number_04624de7d0e8332d:function(t){return Number(t)},__wbg_String_8f0eb39a4a4c2f66:function(t,n){const r=String(n),o=M(r,c.__wbindgen_malloc,c.__wbindgen_realloc),a=p;y().setInt32(t+4,a,!0),y().setInt32(t+0,o,!0)},__wbg___wbindgen_bigint_get_as_i64_8fcf4ce7f1ca72a2:function(t,n){const r=n,o=typeof r=="bigint"?r:void 0;y().setBigInt64(t+8,v(o)?BigInt(0):o,!0),y().setInt32(t+0,!v(o),!0)},__wbg___wbindgen_boolean_get_bbbb1c18aa2f5e25:function(t){const n=t,r=typeof n=="boolean"?n:void 0;return v(r)?16777215:r?1:0},__wbg___wbindgen_debug_string_0bc8482c6e3508ae:function(t,n){const r=U(n),o=M(r,c.__wbindgen_malloc,c.__wbindgen_realloc),a=p;y().setInt32(t+4,a,!0),y().setInt32(t+0,o,!0)},__wbg___wbindgen_in_47fa6863be6f2f25:function(t,n){return t in n},__wbg___wbindgen_is_bigint_31b12575b56f32fc:function(t){return typeof t=="bigint"},__wbg___wbindgen_is_function_0095a73b8b156f76:function(t){return typeof t=="function"},__wbg___wbindgen_is_object_5ae8e5880f2c1fbd:function(t){const n=t;return typeof n=="object"&&n!==null},__wbg___wbindgen_is_string_cd444516edc5b180:function(t){return typeof t=="string"},__wbg___wbindgen_is_undefined_9e4d92534c42d778:function(t){return t===void 0},__wbg___wbindgen_jsval_eq_11888390b0186270:function(t,n){return t===n},__wbg___wbindgen_jsval_loose_eq_9dd77d8cd6671811:function(t,n){return t==n},__wbg___wbindgen_number_get_8ff4255516ccad3e:function(t,n){const r=n,o=typeof r=="number"?r:void 0;y().setFloat64(t+8,v(o)?0:o,!0),y().setInt32(t+0,!v(o),!0)},__wbg___wbindgen_string_get_72fb696202c56729:function(t,n){const r=n,o=typeof r=="string"?r:void 0;var a=v(o)?0:M(o,c.__wbindgen_malloc,c.__wbindgen_realloc),i=p;y().setInt32(t+4,i,!0),y().setInt32(t+0,a,!0)},__wbg___wbindgen_throw_be289d5034ed271b:function(t,n){throw new Error(E(t,n))},__wbg_call_389efe28435a9388:function(){return D(function(t,n){return t.call(n)},arguments)},__wbg_call_4708e0c13bdc8e95:function(){return D(function(t,n,r){return t.call(n,r)},arguments)},__wbg_done_57b39ecd9addfe81:function(t){return t.done},__wbg_entries_58c7934c745daac7:function(t){return Object.entries(t)},__wbg_error_7534b8e9a36f1ab4:function(t,n){let r,o;try{r=t,o=n,console.error(E(t,n))}finally{c.__wbindgen_free(r,o,1)}},__wbg_get_9b94d73e6221f75c:function(t,n){return t[n>>>0]},__wbg_get_b3ed3ad4be2bc8ac:function(){return D(function(t,n){return Reflect.get(t,n)},arguments)},__wbg_get_with_ref_key_1dc361bd10053bfe:function(t,n){return t[n]},__wbg_instanceof_ArrayBuffer_c367199e2fa2aa04:function(t){let n;try{n=t instanceof ArrayBuffer}catch{n=!1}return n},__wbg_instanceof_Map_53af74335dec57f4:function(t){let n;try{n=t instanceof Map}catch{n=!1}return n},__wbg_instanceof_Uint8Array_9b9075935c74707c:function(t){let n;try{n=t instanceof Uint8Array}catch{n=!1}return n},__wbg_isArray_d314bb98fcf08331:function(t){return Array.isArray(t)},__wbg_isSafeInteger_bfbc7332a9768d2a:function(t){return Number.isSafeInteger(t)},__wbg_iterator_6ff6560ca1568e55:function(){return Symbol.iterator},__wbg_length_32ed9a279acd054c:function(t){return t.length},__wbg_length_35a7bace40f36eac:function(t){return t.length},__wbg_log_f1a1b5cd3f9c7822:function(t,n){console.log(E(t,n))},__wbg_new_361308b2356cecd0:function(){return new Object},__wbg_new_3eb36ae241fe6f44:function(){return new Array},__wbg_new_8a6f238a6ece86ea:function(){return new Error},__wbg_new_dca287b076112a51:function(){return new Map},__wbg_new_dd2b680c8bf6ae29:function(t){return new Uint8Array(t)},__wbg_new_from_slice_a3d2629dc1826784:function(t,n){return new Uint8Array(H(t,n))},__wbg_next_3482f54c49e8af19:function(){return D(function(t){return t.next()},arguments)},__wbg_next_418f80d8f5303233:function(t){return t.next},__wbg_prototypesetcall_bdcdcc5842e4d77d:function(t,n,r){Uint8Array.prototype.set.call(H(t,n),r)},__wbg_push_8ffdcb2063340ba5:function(t,n){return t.push(n)},__wbg_set_1eb0999cf5d27fc8:function(t,n,r){return t.set(n,r)},__wbg_set_3f1d0b984ed272ed:function(t,n,r){t[n]=r},__wbg_set_6cb8631f80447a67:function(){return D(function(t,n,r){return Reflect.set(t,n,r)},arguments)},__wbg_set_f43e577aea94465b:function(t,n,r){t[n>>>0]=r},__wbg_stack_0ed75d68575b0f3c:function(t,n){const r=n.stack,o=M(r,c.__wbindgen_malloc,c.__wbindgen_realloc),a=p;y().setInt32(t+4,a,!0),y().setInt32(t+0,o,!0)},__wbg_value_0546255b415e96c1:function(t){return t.value},__wbindgen_cast_0000000000000001:function(t){return t},__wbindgen_cast_0000000000000002:function(t){return t},__wbindgen_cast_0000000000000003:function(t,n){return E(t,n)},__wbindgen_cast_0000000000000004:function(t){return BigInt.asUintN(64,t)},__wbindgen_init_externref_table:function(){const t=c.__wbindgen_externrefs,n=t.grow(4);t.set(0,void 0),t.set(n+0,void 0),t.set(n+1,null),t.set(n+2,!0),t.set(n+3,!1)}}}}function he(e){const t=c.__externref_table_alloc();return c.__wbindgen_externrefs.set(t,e),t}function U(e){const t=typeof e;if(t=="number"||t=="boolean"||e==null)return`${e}`;if(t=="string")return`"${e}"`;if(t=="symbol"){const o=e.description;return o==null?"Symbol":`Symbol(${o})`}if(t=="function"){const o=e.name;return typeof o=="string"&&o.length>0?`Function(${o})`:"Function"}if(Array.isArray(e)){const o=e.length;let a="[";o>0&&(a+=U(e[0]));for(let i=1;i1)r=n[1];else return toString.call(e);if(r=="Object")try{return"Object("+JSON.stringify(e)+")"}catch{return"Object"}return e instanceof Error?`${e.name}: ${e.message} +${e.stack}`:r}function H(e,t){return e=e>>>0,I().subarray(e/1,e/1+t)}let A=null;function y(){return(A===null||A.buffer.detached===!0||A.buffer.detached===void 0&&A.buffer!==c.memory.buffer)&&(A=new DataView(c.memory.buffer)),A}function E(e,t){return e=e>>>0,ke(e,t)}let B=null;function I(){return(B===null||B.byteLength===0)&&(B=new Uint8Array(c.memory.buffer)),B}function D(e,t){try{return e.apply(this,t)}catch(n){const r=he(n);c.__wbindgen_exn_store(r)}}function v(e){return e==null}function q(e,t){const n=t(e.length*1,1)>>>0;return I().set(e,n/1),p=e.length,n}function M(e,t,n){if(n===void 0){const s=N.encode(e),m=t(s.length,1)>>>0;return I().subarray(m,m+s.length).set(s),p=s.length,m}let r=e.length,o=t(r,1)>>>0;const a=I();let i=0;for(;i127)break;a[o+i]=s}if(i!==r){i!==0&&(e=e.slice(i)),o=n(o,r,r=i+e.length*3,1)>>>0;const s=I().subarray(o+i,o+r),m=N.encodeInto(e,s);i+=m.written,o=n(o,r,i,1)>>>0}return p=i,o}function Y(e){const t=c.__wbindgen_externrefs.get(e);return c.__externref_table_dealloc(e),t}let z=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});z.decode();const we=2146435072;let $=0;function ke(e,t){return $+=t,$>=we&&(z=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),z.decode(),$=t),z.decode(I().subarray(e,e+t))}const N=new TextEncoder;"encodeInto"in N||(N.encodeInto=function(e,t){const n=N.encode(e);return t.set(n),{read:e.length,written:n.length}});let p=0,c;function xe(e,t){return c=e.exports,A=null,B=null,c.__wbindgen_start(),c}async function Ae(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(o){if(e.ok&&n(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",o);else throw o}const r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{const r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}async function ve(e){if(c!==void 0)return c;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0&&(e=new URL(""+new URL("rl_replay_subtr_actor_bg-BjSK7HJ9.wasm",self.location.href).href,self.location.href));const t=pe();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));const{instance:n,module:r}=await Ae(await e,t);return xe(n)}const J="octane",Se={breakout:{kind:"breakout",label:"Breakout",length:131.4924,width:80.521,height:30.3,slopeDegrees:-.9795,groundHeightFront:43.8976,groundHeightBack:46.1454,offset:13.88,elevation:17.05},dominus:{kind:"dominus",label:"Dominus",length:127.9268,width:83.27995,height:31.3,slopeDegrees:-.9635,groundHeightFront:47.2238,groundHeightBack:49.3749,offset:13.88,elevation:17.05},hybrid:{kind:"hybrid",label:"Hybrid",length:127.0192,width:82.18787,height:34.15907,slopeDegrees:-.5499,groundHeightFront:54.0982,groundHeightBack:55.3173,offset:13.88,elevation:17.05},merc:{kind:"merc",label:"Merc",length:120.72,width:76.71,height:41.66,slopeDegrees:.28,groundHeightFront:60.76,groundHeightBack:61.35,offset:13.88,elevation:17.05},octane:{kind:"octane",label:"Octane",length:118.0074,width:84.19941,height:36.15907,slopeDegrees:-.5518,groundHeightFront:55.1449,groundHeightBack:56.2814,offset:13.88,elevation:17.05},plank:{kind:"plank",label:"Plank",length:128.8198,width:84.67036,height:29.3944,slopeDegrees:-.3447,groundHeightFront:44.998,groundHeightBack:45.773,offset:13.88,elevation:17.05}},Oe={"16batmobile":"plank","70dodgechargerrt":"dominus","89batmobile":"dominus","99nissanskylinegtrr34":"hybrid",aftershock:"dominus",animusgp:"breakout",artemis:"plank",artemisg1:"plank",artemisgxt:"plank",astonmartinvalhalla:"breakout",backfire:"octane",backtothefuturetimemachine:"dominus",batmobile1989:"dominus",battlebus:"merc",breakout:"breakout",breakouttypes:"breakout",centio:"plank",centiov17:"plank",cyclone:"breakout",deloreantimemachine:"dominus",diestro:"dominus",dominus:"dominus",dominusgt:"dominus",endo:"hybrid",esper:"hybrid",fast4wd:"octane",fennec:"octane",gazellagt:"dominus",gizmo:"octane",grog:"octane",guardian:"dominus",guardiang1:"dominus",guardiangxt:"dominus",hotshot:"dominus",icecharger:"dominus",imperatordt5:"dominus",jager619rs:"hybrid",jurassicjeepwrangler:"octane",mantis:"plank",marauder:"octane",masamune:"dominus",maverick:"dominus",maverickg1:"dominus",maverickgxt:"dominus",mclaren570s:"dominus",merc:"merc",mr11:"dominus",nimbus:"hybrid",octane:"octane",octanezsr:"octane",paladin:"plank",proteus:"octane",ripper:"dominus",roadhog:"octane",roadhogxl:"octane",samurai:"breakout",scarab:"octane",takumi:"octane",takumirxt:"octane",thedarkknightstumbler:"octane",thedarkknightrisestumbler:"octane",triton:"octane",twinmilliii:"plank",twinzer:"octane",venom:"hybrid",vulcan:"octane",werewolf:"dominus",xdevil:"hybrid",xdevilmk2:"hybrid",zippy:"octane","1966cadillacdeville":"breakout",ace:"breakout",admiral:"dominus",azura:"breakout",behemoth:"merc",beskar:"hybrid",bmwm3e30:"dominus",bmwm2racing:"dominus",bmwm4gt3evo:"dominus",bmw1series:"octane",bmw1seriesrle:"octane",bmwm240i:"dominus",bugatticentodieci:"plank",bumblebee:"dominus",bumblebeecar:"dominus",chevroletastro:"merc",chevroletcorvettestingray:"breakout",chevroletcorvettezr1:"breakout",chryslerpacifica:"hybrid",corlay:"octane",cyberpunkquadra:"breakout",defenderd7xr:"merc",diesel:"breakout",dodgechargerdaytonascatpack:"dominus",dodgerchargerdaytonascatpack:"dominus",dominusneon:"dominus",emperor:"breakout",emperorii:"breakout",emperoriifrozen:"breakout",emperoriiscorched:"breakout",fastfuriousdodgecharger:"dominus",fastandfuriousdodgecharger:"dominus",fastandfuriousdodgechargersrthellcat:"dominus",fastfuriousmazdarx7:"breakout",fastandfuriousmazdarx7:"breakout",fastfuriousnissanskyline:"hybrid",fastandfuriousnissanskyline:"hybrid",fastfuriouspontiacfiero:"hybrid",fastandfuriouspontiacfiero:"hybrid",fenneczrf:"octane",ferrari296gtb:"dominus",ferrarif40:"breakout",fordbroncoraptorrle:"merc",fordf150rle:"octane",fordmustanggtd:"dominus",fordmustangshelbygt500:"dominus",fordmustangmacherle:"octane",fordmustangshelbygt350rrle:"dominus",formula12021:"plank",formula12022:"plank",fuse:"breakout",havoc:"breakout",hearse:"hybrid",homerscar:"dominus",hondacivictyper:"octane",hondacivictyperle:"octane",jackal:"octane",jeepwranglerrubicon:"octane",kitt:"dominus",knightindustries2000:"dominus",komodo:"breakout",lamborghinicountachlpi8004:"dominus",lamborghinihuracansto:"dominus",lamborghiniurus:"hybrid",lamborghiniurusse:"hybrid",lightningmcqueen:"dominus",lightningmcqueencar:"dominus",lockjaw:"dominus",luiginsr:"octane",maestro:"dominus",magnifique:"dominus",magnifiquegxt:"dominus",mako:"breakout",mamba:"dominus",mario:"octane",marionsr:"octane",maven:"dominus",mclaren765lt:"dominus",mclarenp1:"dominus",mclarensenna:"breakout",megastar:"breakout",mercedesamggt63s:"dominus",mercedesbenzcla:"dominus",mudcat:"octane",mudcatg1:"octane",mudcatgxt:"octane",nissan350z:"dominus",nissanfairladyz:"dominus",nissanfairladyzrle:"dominus",nissansilvia:"hybrid",nissansilviarle:"hybrid",nissanskylinegtr:"hybrid",nissanskylinegtrr32:"hybrid",nissanzperformance:"dominus",nissanzperformancecar:"dominus",outlaw:"octane",outlawgxt:"octane",pattywagon:"octane",pizzaplanetdeliverytruck:"merc",pontiacfirebird:"breakout",porsche918spyder:"breakout",porsche911gt3rs:"dominus",porsche911turbo:"dominus",porsche911turborle:"dominus",primo:"hybrid",psyclops:"octane",quadraturbor:"breakout",ram1500rho:"hybrid",recoilav:"merc",redline:"breakout",revolver:"breakout",rivianr1s:"hybrid",scorpion:"dominus",shokunin:"octane",shokuningxt:"octane",stampede:"merc",teslacybertruck:"hybrid",themysterymachine:"merc",theincredibile:"breakout",turtlevan:"merc",voidburn:"hybrid",volkswagengolfgti:"octane",volkswagengolfgtirle:"octane",xentari:"octane",zefira:"dominus",breakoutx:"breakout",nexus:"breakout",nexussc:"breakout",whiplash:"breakout","007sastonmartindbs":"dominus","007sastonmartinvalhalla":"dominus",batmobile2022:"dominus",chikara:"dominus",chikarag1:"dominus",chikaragxt:"dominus",ecto1:"dominus",ecto1ghostbusters:"dominus",fastfuriousdodgechargersrthellcat:"dominus",gazellagthotwheels:"dominus",kittknightrider:"dominus",lamborghinihuracnsto:"dominus",mr11hotwheels:"dominus",nascarchevroletcamaro:"dominus",nascarfordmustang:"dominus",nascartoyotacamry:"dominus",nascarnextgenchevroletcamaro:"dominus",nascarnextgenchevroletcamaro2022:"dominus",nascarnextgenfordmustang:"dominus",nascarnextgenfordmustang2022:"dominus",nascarnextgentoyotacamry:"dominus",nascarnextgentoyotacamry2022:"dominus",nemesis:"dominus",peregrinett:"dominus",perigrinett:"dominus",ronin:"dominus",roning1:"dominus",roningxt:"dominus",samusgunship:"dominus",samusgunshipnintendoexclusive:"dominus",tyranno:"dominus",tyrannogxt:"dominus",insidio:"hybrid",jager619:"hybrid",jger619:"hybrid",jger619rs:"hybrid",r3mx:"hybrid",r3mxgxt:"hybrid",tygris:"hybrid",nomad:"merc",nomadgxt:"merc","007sastonmartindb5":"octane",armadillo:"octane",armadilloxboxexclusive:"octane",boneshaker:"octane",dingo:"octane",fast4wdhotwheels:"octane",harbinger:"octane",harbingergxt:"octane",hogsticker:"octane",hogstickerxboxexclusive:"octane",sweettooth:"octane",sweettoothplaystationexclusive:"octane",thedarkknighttumbler:"octane",batmobile2016:"plank",sentinel:"plank"};function Ie(e){const t={};for(const[n,r]of e)for(const o of n)t[o]=r;return t}const Te=Ie([[[22,1416,1894,1932,3031,3311,6243,6489,7651,7696,7890,7901,8006,8360,8361,8565,8566,8669,9357,10697,10698,10817,10822,11038,11394,11505,11677,11800,11933,11949,12173,12315,12361,12484],"breakout"],[[29,403,597,600,1018,1171,1286,1675,1689,1883,2070,2268,2666,2950,2951,3155,3156,3157,3265,3426,3875,3879,3880,4014,4155,4367,4472,4473,4745,4770,4781,4861,4864,5709,5773,5823,5858,5964,5979,6122,6244,6247,6260,6836,7211,7337,7338,7341,7343,7415,7512,7532,7593,7772,8454,9053,9088,9089,9140,9388,9894,10094,10440,10441,10694,10695,11016,11095,11315,11336,11534,11941,11996,12106,12142,12262,12286,12325,12382,12563,12669],"dominus"],[[28,31,1159,1317,1624,1856,2269,3451,3582,3702,5470,5488,5879,7012,9084,9085,9427,10044,10805,11138,11141,11379,11932,12569,12652],"hybrid"],[[30,4780,7336,7477,7815,7979,10689,11098,11736,11905,11950,12318,12335],"merc"],[[21,23,25,26,27,402,404,523,607,625,723,1172,1295,1300,1475,1478,1533,1568,1623,2665,2853,2919,2949,4284,4318,4319,4320,4782,4906,5020,5039,5188,5361,5547,5713,5837,5951,6939,7947,7948,8383,8806,8807,10896,10897,10900,10901,11314,11603,12104,12105],"octane"],[[24,803,1603,1691,1919,3594,3614,3622,4268,5265,7052,8524],"plank"]]);function Q(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function ee(e){if(!e)return null;switch(Q(e)){case"breakout":return"breakout";case"dominus":return"dominus";case"hybrid":return"hybrid";case"merc":return"merc";case"octane":return"octane";case"batmobile":case"plank":return"plank";default:return null}}function te(e){return e?Oe[Q(e)]??null:null}function Ee(e){return ee(e)??te(e)}function Be(e){return Se[e]}function X(e,t){if(!(!e||typeof e!="object")){if("Str"in e&&typeof e.Str=="string"){t.push(e.Str);return}if("Name"in e&&typeof e.Name=="string"){t.push(e.Name);return}if("Byte"in e&&e.Byte&&typeof e.Byte=="object"){const n=e.Byte;typeof n.kind=="string"&&t.push(n.kind),typeof n.value=="string"&&t.push(n.value);return}if("Struct"in e&&e.Struct&&typeof e.Struct=="object"){const n=e.Struct;if(typeof n.name=="string"&&t.push(n.name),Array.isArray(n.fields))for(const r of n.fields)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),X(r[1],t));return}if("Array"in e&&Array.isArray(e.Array)){for(const n of e.Array)if(Array.isArray(n))for(const r of n)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),X(r[1],t))}}}function De(e){const t=ee(e?.car_hitbox_family);if(t)return t;const n=e?.car_body_id;if(typeof n=="number"){const i=Te[n];if(i)return i}const r=te(e?.car_body_name);if(r)return r;const o=e?.stats;if(!o)return J;const a=[];for(const[i,s]of Object.entries(o))a.push(i),X(s,a);for(const i of a){const s=Ee(i);if(s)return s}return J}function x(e){const[t,n]=Object.entries(e)[0]??["Unknown","unknown"];return typeof n=="string"||typeof n=="number"?`${t}:${n}`:n&&typeof n=="object"?`${t}:${JSON.stringify(n)}`:`${t}:${JSON.stringify(n)}`}function P(e,t){return Math.max(0,e-t)}function ne(e){return new Map(e.map(t=>[t.id,t]))}const h=70,re=73,Ne=3072,Pe=4096,Fe=1792,Re=4184,Me=940,ze=3308,Ce=2816,oe=3584,je=2484,Le=1788,Ve=2300,Ue=2048,He=1036,Ye=1024,$e=1024,Xe=4240,ae=34;function C(e,t,n,r,o){e.push({index:e.length,padId:null,size:o,position:{x:t,y:n,z:r},events:[]})}function j(e,t,n,r,o){C(e,-t,n,r,o),C(e,t,n,r,o)}function W(e,t,n,r,o){C(e,t,-n,r,o),C(e,t,n,r,o)}function T(e,t,n,r,o){j(e,t,-n,r,o),j(e,t,n,r,o)}function We(){const e=[];return W(e,0,Xe,h,"small"),T(e,Fe,Re,h,"small"),T(e,Ne,Pe,re,"big"),T(e,Me,ze,h,"small"),W(e,0,Ce,h,"small"),T(e,oe,je,h,"small"),T(e,Le,Ve,h,"small"),T(e,Ue,He,h,"small"),W(e,0,$e,h,"small"),j(e,oe,0,re,"big"),j(e,Ye,0,h,"small"),e}function K(e){if(e==="Available")return!0;if(e&&typeof e=="object"){if("Available"in e)return!0;if("PickedUp"in e)return!1;const t=e.kind;if(t==="Available")return!0;if(t==="PickedUp")return!1}return null}function Ke(e){return e==="big"||e==="Big"?"big":e==="small"||e==="Small"?"small":null}function Ze(e){let t=null;for(const n of e){const r=K(n.kind);if(r===!1){t=n.time;continue}if(r===!0&&t!==null)return n.time-t>=7?"big":"small"}return null}function Ge(e,t,n,r){const o=ne(t),a=new Map;for(const u of e.boost_pad_events??[]){if(K(u.kind)===null){r?.advance();continue}const l=a.get(u.pad_id);l?l.push(u):a.set(u.pad_id,[u]),r?.advance()}const i=e.boost_pads;if(!i||i.length===0)return r?.advance(ae),We();const s=[...i].sort((u,d)=>u.index-d.index),m=new Array(s.length);for(let u=0;u=72?"big":"small"),w=g.sort((_,k)=>_.time-k.time),f=new Array(w.length);for(let _=0;_=0?e.frame:null}function qe(e,t){if(typeof e.time=="number"&&Number.isFinite(e.time))return e.time;const n=Z(e);if(n===null)return null;const r=t.frame_data.metadata_frames[n]?.time;return typeof r=="number"&&Number.isFinite(r)?r:null}function Je(e,t){return`bookmark:${Z(e)??"unknown"}:${e.description||"tick-mark"}:${t}`}function Qe(e,t,n){return(e.replay_tick_marks??[]).flatMap((r,o)=>{n?.advance();const a=qe(r,e);return a===null?[]:[{id:Je(r,o),description:r.description,frame:Z(r),time:P(a,t)}]})}function et(e){const t=e.description.trim()||"Replay bookmark";return{id:e.id,time:e.time,seekTime:e.time,frame:e.frame??void 0,kind:"bookmark",label:t,shortLabel:"BM",iconName:"bookmark"}}const S={distance:270,height:100,pitch:-4,fov:110},tt=.005,nt=Number.POSITIVE_INFINITY,rt=!0,ot=.15,at=10,it=.1,st=10;function ie(e){const t=Math.hypot(e.x,e.y,e.z);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t}}function se(e){const t=Math.hypot(e.x,e.y,e.z,e.w);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t,w:e.w/t}}function ce(e,t){return{w:e.w*t.w-e.x*t.x-e.y*t.y-e.z*t.z,x:e.w*t.x+e.x*t.w+e.y*t.z-e.z*t.y,y:e.w*t.y-e.x*t.z+e.y*t.w+e.z*t.x,z:e.w*t.z+e.x*t.y-e.y*t.x+e.z*t.w}}function ue(e,t){const n=ce(ce(t,{x:e.x,y:e.y,z:e.z,w:0}),{x:-t.x,y:-t.y,z:-t.z,w:t.w});return{x:n.x,y:n.y,z:n.z}}function ct(e){if(e==="Empty")return{position:null,linearVelocity:null,angularVelocity:null,rotation:null};const t=e.Data.rigid_body;return{position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:se(t.rotation)}}function le(e){return e==null?null:Math.max(-1,Math.min(1,(e-128)/128))}function de(e){return e==null?null:(e>127?e-256:e)*Math.PI/128}function fe(e){return e?{x:e[0],y:e[1],z:e[2]}:null}const ut={cameraPitch:null,cameraYaw:null,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null};function lt(e){if(e==="Empty")return{isPresent:!1,position:null,linearVelocity:null,angularVelocity:null,rotation:null,forward:null,up:null,boostAmount:0,boostFraction:0,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,...ut};const t=e.Data.rigid_body,n=se(t.rotation),r=n?ie(ue({x:1,y:0,z:0},n)):null,o=n?ie(ue({x:0,y:0,z:1},n)):null,a=e.Data.camera,i=e.Data.input;return{isPresent:!0,position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:n,forward:r,up:o,boostAmount:e.Data.boost_amount,boostFraction:Math.max(0,Math.min(1,e.Data.boost_amount/255)),boostActive:e.Data.boost_active,powerslideActive:e.Data.powerslide_active,jumpActive:e.Data.jump_active,doubleJumpActive:e.Data.double_jump_active,dodgeActive:e.Data.dodge_active,cameraPitch:de(a?.pitch),cameraYaw:de(a?.yaw),throttle:le(i?.throttle),steer:le(i?.steer),dodgeImpulse:fe(i?.dodge_impulse),dodgeTorque:fe(i?.dodge_torque)}}function dt(e){return e.position!==null}function ft(e){return{...e,isPresent:!1,linearVelocity:null,angularVelocity:null,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null}}function mt(e){let t=null,n=null;for(let r=0;r=t.length-1)return;let o=F(t[r].position);for(let a=r+1;ait){o=F(s.position);continue}if(_t(o,s.position)>st){o=F(s.position);continue}const l={x:(i.linearVelocity.x+s.linearVelocity.x)/2,y:(i.linearVelocity.y+s.linearVelocity.y)/2,z:(i.linearVelocity.z+s.linearVelocity.z)/2},g={x:o.x+l.x*d,y:o.y+l.y*d,z:o.z+l.z*d},b=(a-r)%n.smoothingAnchorInterval===0?.5:n.smoothingBlendFactor;o={x:g.x*(1-b)+s.position.x*b,y:g.y*(1-b)+s.position.y*b,z:g.z*(1-b)+s.position.z*b},s.position=F(o)}}function bt(e){return{motionSmoothing:e.motionSmoothing??rt,smoothingBlendFactor:e.smoothingBlendFactor??ot,smoothingAnchorInterval:Math.max(1,e.smoothingAnchorInterval??at)}}function be(){return typeof performance>"u"?Date.now():performance.now()}function gt(e){const t=e.meta.team_zero.length+e.meta.team_one.length,n=e.frame_data.players.reduce((i,[,s])=>i+s.frames.length,0),r=e.boost_pads?.length??ae,o=e.boost_pad_events?.length??0,a=(e.goal_events?.length??0)+(e.player_stat_events?.length??0)+(e.demolish_infos?.length??0)+(e.replay_tick_marks?.length??0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,n),Math.max(1,e.frame_data.ball_data.frames.length),Math.max(1,r+o),Math.max(1,a)].reduce((i,s)=>i+s,0)}function yt(e){const t=e.frame_data.players.reduce((n,[,r])=>n+r.frames.length,0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,e.frame_data.ball_data.frames.length)].reduce((n,r)=>n+r,0)}function pt(e,t,n={}){const r=gt(e),o=yt(e);let a=0,i=0,s=-1,m=-1,u=be();const d=n.yieldEveryMs??Number.POSITIVE_INFINITY,l=n.progressReportMinDelta??tt,g=Math.max(1,n.progressReportFrameInterval??nt),b=()=>{if(!t)return!1;const f=Math.max(0,Math.min(1,a/r));if(f<=s)return!1;const k=i-m>=g;return f>=1||f-s>=l||k?(s=f,m=i,t(f,{progress:f,processedFrames:Math.min(i,o),totalFrames:o,processedUnits:a,totalUnits:r}),!0):!1},w=(f=!1)=>{const _=be();return!f&&_-ur===t)?.[1];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function xt(e){const t=kt(e?.stats);return{fov:O(t,"CameraFOV")??S.fov,height:O(t,"CameraHeight")??S.height,pitch:O(t,"CameraPitch")??S.pitch,distance:O(t,"CameraDistance")??S.distance,stiffness:O(t,"CameraStiffness")??S.stiffness,swivelSpeed:O(t,"CameraSwivelSpeed")??S.swivelSpeed,transitionSpeed:O(t,"CameraTransitionSpeed")??S.transitionSpeed}}function At(e,t){const n=new Map,r=new Map,o=[...e.meta.team_zero,...e.meta.team_one];if(o.length===0)return t?.advance(),{byId:n,byName:r};for(const a of o)r.set(a.name,a),a.remote_id&&n.set(x(a.remote_id),a),t?.advance();return{byId:n,byName:r}}function vt(e){const t=new Map;for(const[n,r]of e.player_camera_events??[])t.set(x(n),r.map(o=>({frame:o.frame,ballCamActive:o.ball_cam_active,behindViewActive:o.behind_view_active,driving:o.driving})));return t}function St(e,t){const n=new Set(e.meta.team_zero.map(m=>m.name)),r=new Set(e.meta.team_one.map(m=>m.name)),o=At(e,t),a=vt(e),i=[];let s=0;for(const[m,u]of e.frame_data.players){const d=new Array(u.frames.length);let l;for(let f=0;ft.time!==n.time?t.time-n.time:(t.frame??0)-(n.frame??0))}function Tt(e,t,n){const r=e.player?x(e.player):null,o=r?t.get(r)?.name??r:null,a=o?`${o} scored`:"Goal";return{id:G("goal",e.frame,r??"team"),time:P(e.time,n),frame:e.frame,kind:"goal",label:a,shortLabel:"G",playerId:r,playerName:o,isTeamZero:e.scoring_team_is_team_0}}function Et(e,t,n){const r=x(e.player),o=t.get(r)?.name??r,a=e.kind.toLowerCase(),i=e.kind==="Shot"?"shot":e.kind==="Save"?"save":"assist",s=e.kind==="Shot"?"SH":e.kind==="Save"?"SV":"A";return{id:G(a,e.frame,r),time:P(e.time,n),frame:e.frame,kind:a,label:`${o} ${i}`,shortLabel:s,playerId:r,playerName:o,location:e.shot?.shot_touch_position??e.shot?.ball_position??null,shot:e.shot??null,isTeamZero:e.is_team_0}}function Bt(e,t,n){const r=x(e.attacker),o=x(e.victim),a=t.get(r),i=t.get(o);return{id:G("demo",e.frame,`${r}:${o}`),time:P(e.time,n),frame:e.frame,kind:"demo",label:`${a?.name??r} demoed ${i?.name??o}`,shortLabel:"D",playerId:r,playerName:a?.name??r,secondaryPlayerId:o,secondaryPlayerName:i?.name??o,location:e.victim_location,isTeamZero:a?.isTeamZero??null}}function Dt(e,t,n,r,o){const a=ne(t),i=[];for(const s of e.goal_events??[])i.push(Tt(s,a,r)),o?.advance();for(const s of e.player_stat_events??[])i.push(Et(s,a,r)),o?.advance();for(const s of e.demolish_infos??[])i.push(Bt(s,a,r)),o?.advance();for(const s of n)i.push(et(s));return i.length===0&&o?.advance(),It(i)}function Nt(e,t={}){const n=pt(e,t.onProgress,{progressReportMinDelta:t.progressReportMinDelta,progressReportFrameInterval:t.progressReportFrameInterval}),r=e.frame_data.metadata_frames[0]?.time??0,o=ht(e,n),a=St(e,n),i=Ot(e,n),s=bt(t);_e(o,i,s);for(const l of a)_e(o,l.frames,s);const m=Ge(e,a,r,n),u=Qe(e,r,n),d=Dt(e,a,u,r,n);return n.finish(),{frameCount:o.length,duration:o.at(-1)?.time??0,rawStartTime:r,frames:o,ballFrames:i,boostPads:m,players:a,tickMarks:u,timelineEvents:d,teamZeroNames:e.meta.team_zero.map(l=>l.name),teamOneNames:e.meta.team_one.map(l=>l.name)}}function L(e){if(e instanceof Map)return Object.fromEntries(Array.from(e.entries()).map(([t,n])=>[t,L(n)]));if(Array.isArray(e))return e.map(t=>L(t));if(e&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=L(r);return t}return e}async function Pt(){const e=ve;typeof e=="function"&&await e()}function R(e){self.postMessage(e)}self.onmessage=async e=>{if(e.data.type==="load-replay")try{await Pt();const t=new Uint8Array(e.data.bytes);R({type:"progress",progress:{stage:"validating",progress:0}});const n=L(ye(t));if(!n.valid)throw new Error(n.error??"Replay validation failed");const r=ge(t,s=>{R({type:"progress",progress:s})},e.data.reportEveryNFrames);R({type:"progress",progress:{stage:"normalizing",progress:0}});const o=JSON.parse(new TextDecoder().decode(r)),a=Nt(o,{motionSmoothing:e.data.motionSmoothing,smoothingBlendFactor:e.data.smoothingBlendFactor,smoothingAnchorInterval:e.data.smoothingAnchorInterval,progressReportFrameInterval:e.data.reportEveryNFrames,onProgress(s){R({type:"progress",progress:{stage:"normalizing",progress:s}})}}),i=new TextEncoder().encode(JSON.stringify(a));self.postMessage({type:"done",rawBuffer:r.buffer,replayBuffer:i.buffer},[r.buffer,i.buffer])}catch(t){R({type:"error",error:t instanceof Error?t.message:String(t)})}}})(); diff --git a/crates/rocket-sense-server/static/subtr-actor/index.html b/crates/rocket-sense-server/static/subtr-actor/index.html index 3f930690..132f6a76 100644 --- a/crates/rocket-sense-server/static/subtr-actor/index.html +++ b/crates/rocket-sense-server/static/subtr-actor/index.html @@ -5,7 +5,8 @@ stat evaluation player - + +
diff --git a/crates/rocket-sense-server/static/subtr-actor/review/assets/index-Bi0g-Y6P.js b/crates/rocket-sense-server/static/subtr-actor/review/assets/index-Bi0g-Y6P.js new file mode 100644 index 00000000..61ada380 --- /dev/null +++ b/crates/rocket-sense-server/static/subtr-actor/review/assets/index-Bi0g-Y6P.js @@ -0,0 +1,2 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./main-DhIgxjyS.js","./preload-helper-PPVm8Dsz.js","./main-BmO1EVHp.css"])))=>i.map(i=>d[i]); +import{_ as u}from"./preload-helper-PPVm8Dsz.js";(function(){const r=document.createElement("link").relList;if(r&&r.supports&&r.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))n(e);new MutationObserver(e=>{for(const t of e)if(t.type==="childList")for(const o of t.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function c(e){const t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?t.credentials="include":e.crossOrigin==="anonymous"?t.credentials="omit":t.credentials="same-origin",t}function n(e){if(e.ep)return;e.ep=!0;const t=c(e);fetch(e.href,t)}})();const s=document.querySelector("#app");if(!(s instanceof HTMLElement))throw new Error("Missing #app mount element");const{mountStatEvaluationPlayer:a}=await u(async()=>{const{mountStatEvaluationPlayer:i}=await import("./main-DhIgxjyS.js");return{mountStatEvaluationPlayer:i}},__vite__mapDeps([0,1,2]),import.meta.url);a(s); diff --git a/crates/rocket-sense-server/static/subtr-actor/review/assets/index-DqmYE4Q0.js b/crates/rocket-sense-server/static/subtr-actor/review/assets/index-DqmYE4Q0.js deleted file mode 100644 index 061c93a6..00000000 --- a/crates/rocket-sense-server/static/subtr-actor/review/assets/index-DqmYE4Q0.js +++ /dev/null @@ -1,2 +0,0 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./main-DHjpjWsc.js","./main-D554jl9D.css"])))=>i.map(i=>d[i]); -(function(){const i=document.createElement("link").relList;if(i&&i.supports&&i.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))u(e);new MutationObserver(e=>{for(const t of e)if(t.type==="childList")for(const r of t.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&u(r)}).observe(document,{childList:!0,subtree:!0});function a(e){const t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?t.credentials="include":e.crossOrigin==="anonymous"?t.credentials="omit":t.credentials="same-origin",t}function u(e){if(e.ep)return;e.ep=!0;const t=a(e);fetch(e.href,t)}})();const g="modulepreload",v=function(l,i){return new URL(l,i).href},h={},P=function(i,a,u){let e=Promise.resolve();if(a&&a.length>0){let E=function(n){return Promise.all(n.map(c=>Promise.resolve(c).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}))))};const r=document.getElementsByTagName("link"),o=document.querySelector("meta[property=csp-nonce]"),p=o?.nonce||o?.getAttribute("nonce");e=E(a.map(n=>{if(n=v(n,u),n in h)return;h[n]=!0;const c=n.endsWith(".css"),f=c?'[rel="stylesheet"]':"";if(u)for(let d=r.length-1;d>=0;d--){const m=r[d];if(m.href===n&&(!c||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${n}"]${f}`))return;const s=document.createElement("link");if(s.rel=c?"stylesheet":g,c||(s.as="script"),s.crossOrigin="",s.href=n,p&&s.setAttribute("nonce",p),document.head.appendChild(s),c)return new Promise((d,m)=>{s.addEventListener("load",d),s.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${n}`)))})}))}function t(r){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=r,window.dispatchEvent(o),!o.defaultPrevented)throw r}return e.then(r=>{for(const o of r||[])o.status==="rejected"&&t(o.reason);return i().catch(t)})},y=document.querySelector("#app");if(!(y instanceof HTMLElement))throw new Error("Missing #app mount element");const{mountStatEvaluationPlayer:w}=await P(async()=>{const{mountStatEvaluationPlayer:l}=await import("./main-DHjpjWsc.js");return{mountStatEvaluationPlayer:l}},__vite__mapDeps([0,1]),import.meta.url);w(y); diff --git a/crates/rocket-sense-server/static/subtr-actor/review/assets/main-D554jl9D.css b/crates/rocket-sense-server/static/subtr-actor/review/assets/main-BmO1EVHp.css similarity index 98% rename from crates/rocket-sense-server/static/subtr-actor/review/assets/main-D554jl9D.css rename to crates/rocket-sense-server/static/subtr-actor/review/assets/main-BmO1EVHp.css index b8d95020..17d9fd0b 100644 --- a/crates/rocket-sense-server/static/subtr-actor/review/assets/main-D554jl9D.css +++ b/crates/rocket-sense-server/static/subtr-actor/review/assets/main-BmO1EVHp.css @@ -1 +1 @@ -:root{color-scheme:dark;font-family:IBM Plex Sans,Avenir Next,sans-serif;font-size:13px;--surface: rgba(8, 20, 30, .82);--surface-strong: rgba(7, 16, 24, .94);--surface-soft: rgba(12, 28, 40, .72);--border: rgba(167, 199, 222, .14);--text: #edf5fa;--muted: #9eb4c6;--blue: #4b94ff;--blue-soft: rgba(75, 148, 255, .18);--orange: #f39a37;--orange-soft: rgba(243, 154, 55, .18);--ui-gap-xs: .22rem;--ui-gap-sm: .34rem;--ui-gap-md: .5rem;--ui-panel-padding: .52rem;--ui-control-font-size: .72rem;--ui-control-line-height: 1.15;--ui-control-padding-block: .22rem;--ui-control-padding-inline: .38rem;--ui-control-height: 1.55rem;--ui-radius-sm: .36rem;--ui-radius-md: .5rem;--ui-radius-lg: .72rem;--ui-radius-pill: 999px;--ui-border-subtle: rgba(255, 255, 255, .1);--ui-border-hover: rgba(255, 255, 255, .18);--ui-overlay-bg: rgba(4, 12, 18, .82);--ui-overlay-bg-strong: rgba(4, 12, 18, .9);background:radial-gradient(circle at top left,rgba(73,112,158,.28),transparent 32%),radial-gradient(circle at top right,rgba(243,154,55,.12),transparent 24%),linear-gradient(180deg,#071018,#0b1721);color:var(--text)}*,*:before,*:after{box-sizing:border-box}html,body,#app{width:100%;height:100%;overflow:hidden}body{margin:0}button,select,input{font:inherit}.shell{min-height:100dvh;height:100dvh;padding:0;display:block}.workspace{height:100%;display:block;min-height:0}.panel h2,.stats-panel h2{margin:0}.panel-copy{color:#bdd0de}.viewport-panel,.panel,.stats-panel{position:relative;border:1px solid var(--border);border-radius:1.4rem;background:var(--surface);box-shadow:0 22px 56px #0000003d;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}.viewport-panel{width:100%;height:100%;min-height:100dvh;overflow:hidden;border:0;border-radius:0;background:#061019;box-shadow:none}.viewport{position:absolute;inset:0}.top-chrome{position:absolute;top:.8rem;left:.8rem;z-index:20}.launcher-toggle{width:2.65rem;min-width:0;aspect-ratio:1;display:grid;place-items:center;padding:0;border-color:transparent;border-radius:var(--ui-radius-md);background:#050e16ad;box-shadow:0 12px 30px #0000004d;-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px)}.launcher-toggle:hover,.launcher-toggle[aria-expanded=true]{border-color:#ffffff29;background:#081824d1}.launcher-toggle-bars,.launcher-toggle-bars:before,.launcher-toggle-bars:after{display:block;width:1.18rem;height:.12rem;border-radius:var(--ui-radius-pill);background:#edf5fa}.launcher-toggle-bars{position:relative}.launcher-toggle-bars:before,.launcher-toggle-bars:after{content:"";position:absolute;left:0}.launcher-toggle-bars:before{top:-.38rem}.launcher-toggle-bars:after{top:.38rem}.launcher-menu{position:absolute;top:calc(100% + .55rem);left:0;width:min(22rem,calc(100vw - 1.6rem));max-height:calc(100dvh - 7.5rem);overflow:auto;display:grid;gap:var(--ui-gap-md);padding:var(--ui-panel-padding);border:1px solid rgba(255,255,255,.12);border-radius:var(--ui-radius-lg);background:var(--ui-overlay-bg-strong);box-shadow:0 18px 54px #0000005c;-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px)}.launcher-menu[hidden]{display:none}.launcher-section{display:grid;gap:var(--ui-gap-xs)}.launcher-section h2{margin:0;color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase}.launcher-section button{width:100%;text-align:left}.hidden-file-input,.visually-hidden{position:fixed;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap}.team-blue{--team-accent: var(--blue);--team-soft: var(--blue-soft)}.team-orange{--team-accent: var(--orange);--team-soft: var(--orange-soft)}.floating-window-layer,.stats-window-layer{position:absolute;inset:0;z-index:12;pointer-events:none}.floating-window,.stats-window,.scoreboard-window{position:absolute;left:clamp(.8rem,var(--window-x, 1rem),calc(100vw - 18rem));top:clamp(.8rem,var(--window-y, 1rem),calc(100dvh - 12rem));width:min(26rem,calc(100vw - 1.6rem));overflow:visible;display:grid;gap:var(--ui-gap-md);padding:var(--ui-panel-padding);border:1px solid rgba(255,255,255,.12);border-radius:var(--ui-radius-lg);background:var(--ui-overlay-bg);box-shadow:0 16px 44px #00000052;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);pointer-events:auto;-webkit-user-select:none;user-select:none}.floating-window[hidden],.stats-window[hidden],.scoreboard-window[hidden]{display:none}.scoreboard-window{left:50%;top:.7rem;width:auto;min-width:4.4rem;transform:translate(-50%);gap:var(--ui-gap-sm);padding:.34rem .62rem;border-radius:999px}.scoreboard-window-body{display:grid;gap:.42rem}.scoreboard-scoreline{display:grid;grid-template-columns:minmax(1.2rem,auto) auto minmax(1.2rem,auto);align-items:center;justify-content:center;gap:.3rem;min-width:0;font-variant-numeric:tabular-nums}.scoreboard-goal-value{color:var(--team-accent);font-size:1rem;font-weight:850;line-height:1;text-align:center}.scoreboard-divider{color:var(--muted);font-size:1rem;font-weight:800;line-height:1}.scoreboard-empty{margin:0;color:var(--muted);font-size:.74rem;text-align:center}@media(max-width:900px){.scoreboard-window{top:3.25rem}}@media(max-width:640px){.scoreboard-window{min-width:4rem;padding:.32rem .56rem}.scoreboard-scoreline{gap:.24rem}.scoreboard-goal-value{font-size:.92rem}}.floating-window-camera{width:min(26rem,calc(100vw - 1.6rem))}.floating-window-recording{--window-x: calc(100vw - 27rem) ;width:min(26rem,calc(100vw - 1.6rem))}.floating-window-playback{--window-x: calc(100vw - 23rem) ;width:min(21rem,calc(100vw - 1.6rem))}.floating-window-mechanics{width:auto;min-width:min(18rem,calc(100vw - 1.6rem));max-width:min(42rem,calc(100vw - 1.6rem))}.mechanics-timeline-window-body{display:grid;gap:var(--ui-gap-sm);max-height:min(72dvh,42rem);overflow:auto}.floating-window-event-playlist{width:min(27rem,calc(100vw - 1.6rem))}.floating-window-mechanics-review{width:min(30rem,calc(100vw - 1.6rem))}.floating-window-replay-loading{width:min(32rem,calc(100vw - 1.6rem))}.floating-window-boost-pickups{width:min(34rem,calc(100vw - 1.6rem))}.floating-window-touch-controls,.floating-window-touch-legend{width:min(24rem,calc(100vw - 1.6rem))}.floating-window-shot-visualization{width:min(38rem,calc(100vw - 1.6rem))}.floating-window-header,.stats-window-header{display:flex;align-items:start;justify-content:space-between;gap:var(--ui-gap-md);cursor:grab}.stats-window-header-actions-only{justify-content:end}.floating-window:active .floating-window-header,.stats-window:active .stats-window-header{cursor:grabbing}.floating-window-header h2,.stats-window-header h2{margin:0;color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase}.floating-window-hide,.stats-window-action{flex-shrink:0;padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border-radius:var(--ui-radius-md);font-size:var(--ui-control-font-size)}.mechanics-review-window-body{display:grid;gap:var(--ui-gap-md);max-height:min(74dvh,42rem);min-height:0;overflow:hidden auto;scrollbar-width:thin}.event-playlist-window-body{display:grid;gap:var(--ui-gap-sm);min-height:0}.touch-color-legend-body{display:grid;gap:var(--ui-gap-md);max-height:min(70dvh,38rem);overflow:auto;scrollbar-width:thin}.touch-color-legend-explainer{display:grid;gap:var(--ui-gap-xs);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);color:#c3d3df;font-size:.78rem;background:#ffffff0a}.touch-color-legend-group{display:grid;gap:var(--ui-gap-xs)}.touch-color-legend-heading{width:100%;min-height:1.45rem;margin:0;padding:.12rem .32rem;border-radius:var(--ui-radius-sm);color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.1em;text-align:left;text-transform:uppercase}.touch-color-legend-heading[data-active=true]{border-color:#8ec5ff6b;background:#21476b94;color:#f3f8fc}.touch-color-legend-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-xs)}.touch-color-legend-item{min-width:0;display:flex;align-items:center;gap:var(--ui-gap-xs);color:#e8f0f7;font-size:.76rem}.touch-color-legend-swatch{flex:0 0 auto;width:.78rem;height:.78rem;border:1px solid rgba(255,255,255,.35);border-radius:50%;box-shadow:0 0 0 1px #00000038}.event-playlist-toolbar{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm)}.event-playlist-filter{position:relative;min-width:0}.event-playlist-filter summary{display:inline-flex;align-items:center;min-height:var(--ui-control-height);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);background:#ffffff0a;color:var(--text);font-size:var(--ui-control-font-size);cursor:pointer;list-style:none}.event-playlist-filter summary::-webkit-details-marker{display:none}.event-playlist-filter-panel{position:absolute;z-index:5;top:calc(100% + .4rem);left:0;width:min(22rem,calc(100vw - 3rem));max-height:min(28rem,calc(100dvh - 10rem));overflow:auto;display:grid;gap:var(--ui-gap-md);padding:.85rem;border:1px solid rgba(255,255,255,.14);border-radius:var(--ui-radius-md);background:#090e16fa;box-shadow:0 16px 34px #00000057}.event-playlist-filter-actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem}.event-playlist-filter-group{display:grid;gap:.45rem}.event-playlist-filter-group h3{margin:0;color:#87afd4;font-size:.64rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase}.event-playlist-filter-option{min-width:0}.event-playlist-follow{flex-shrink:0}.event-playlist-list{max-height:min(31rem,calc(100dvh - 11rem));overflow:auto;display:grid;gap:.45rem;padding-right:.15rem;scrollbar-width:thin}.event-playlist-item{--event-color: #d1d9e0;appearance:none;width:100%;display:grid;grid-template-columns:3.4rem minmax(0,1fr);gap:.7rem;align-items:start;padding:.6rem .7rem;border:1px solid rgba(255,255,255,.09);border-left:.28rem solid var(--event-color);border-radius:var(--ui-radius-md);background:#ffffff09;color:var(--text);font:inherit;text-align:left;cursor:pointer}.event-playlist-item:hover,.event-playlist-item[data-active=true]{border-color:color-mix(in srgb,var(--event-color) 48%,rgba(255,255,255,.12));background:color-mix(in srgb,var(--event-color) 15%,rgba(255,255,255,.045))}.event-playlist-time{color:var(--muted);font-size:.72rem;font-variant-numeric:tabular-nums;line-height:1.35}.event-playlist-main{min-width:0;display:grid;gap:.15rem}.shot-visualization{display:grid;gap:var(--ui-gap-md);min-height:0}.shot-visualization-summary{color:var(--text);font-size:.78rem;font-weight:700;font-variant-numeric:tabular-nums}.shot-chart-canvas{width:100%;aspect-ratio:16 / 10;display:block;border:1px solid rgba(255,255,255,.1);border-radius:var(--ui-radius-md);background:#0f2b24}.shot-visualization-layout{display:grid;grid-template-columns:minmax(10rem,.78fr) minmax(15rem,1.22fr);gap:var(--ui-gap-md);min-height:0}.shot-list{display:grid;align-content:start;gap:.45rem;max-height:18rem;overflow:auto;padding-right:.15rem;scrollbar-width:thin}.shot-list-item{appearance:none;width:100%;display:grid;gap:.15rem;min-height:3.1rem;padding:.52rem .62rem;border:1px solid rgba(255,255,255,.09);border-left:.24rem solid #62d2a2;border-radius:var(--ui-radius-md);background:#ffffff09;color:var(--text);font:inherit;text-align:left;cursor:pointer}.shot-list-item[data-selected=true]{border-color:#f8fafcb8;background:#87afd429}.shot-list-item[data-active=true]{border-left-color:#e11d48}.shot-list-title{min-width:0;overflow:hidden;color:var(--text);font-size:.78rem;font-weight:800;text-overflow:ellipsis;white-space:nowrap}.shot-list-meta{color:var(--muted);font-size:.68rem;font-variant-numeric:tabular-nums;white-space:nowrap}.shot-demo-panel{display:grid;gap:var(--ui-gap-sm);min-width:0}.shot-demo-scene{width:100%;height:12rem;overflow:hidden;border:1px solid rgba(255,255,255,.1);border-radius:var(--ui-radius-md);background:#07111c}.shot-demo-scene canvas{width:100%;height:100%;display:block}.shot-details{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem;margin:0}.shot-details div{min-width:0;padding:.48rem .56rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:#ffffff09}.shot-details dt{color:var(--muted);font-size:.62rem;font-weight:700;text-transform:uppercase}.shot-details dd{min-width:0;margin:.14rem 0 0;overflow:hidden;color:var(--text);font-size:.76rem;font-variant-numeric:tabular-nums;text-overflow:ellipsis;white-space:nowrap}.shot-visualization-empty{margin:0;color:var(--muted);font-size:.78rem}.event-playlist-main strong{min-width:0;overflow-wrap:anywhere;font-size:.82rem;line-height:1.3}.event-playlist-main span{min-width:0;overflow-wrap:anywhere;color:var(--muted);font-size:.68rem;line-height:1.35}.mechanics-review-load-row{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:var(--ui-gap-sm);align-items:center}.mechanics-review-file{display:inline-grid;align-items:center;min-height:var(--ui-control-height);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);background:#ffffff0e;color:var(--text);cursor:pointer}.mechanics-review-file input{position:fixed;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap}.mechanics-review-url{min-width:0}.mechanics-review-status{min-height:1.2rem;color:var(--muted);font-size:.78rem}.mechanics-review-current{display:grid;gap:var(--ui-gap-sm);padding:.55rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:#ffffff09}.mechanics-review-index{color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase}.mechanics-review-current h3{margin:0;font-size:.96rem;line-height:1.2}.mechanics-review-fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-sm);margin:0}.mechanics-review-fields div{min-width:0}.mechanics-review-fields dt{color:var(--muted);font-size:.68rem;text-transform:uppercase}.mechanics-review-fields dd{margin:.1rem 0 0;overflow-wrap:anywhere}.mechanics-review-wide{grid-column:1 / -1}.mechanics-review-actions,.mechanics-review-decision-actions,.mechanics-review-list-header{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm)}.mechanics-review-actions button,.mechanics-review-decision-actions button{flex:1 1 0}#mechanics-review-confirm{border-color:#4caf7885}#mechanics-review-reject{border-color:#dc5f5f94}.mechanics-review-list-header{color:var(--muted);font-size:.72rem;font-weight:700;text-transform:uppercase}.mechanics-review-replays{display:grid;gap:var(--ui-gap-xs)}.replay-loading-window-body{display:grid;gap:var(--ui-gap-sm);max-height:min(72dvh,40rem);min-height:0}.replay-loading-summary{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm);color:var(--muted);font-size:.72rem;font-weight:700;text-transform:uppercase}.replay-loading-list{max-height:min(38rem,calc(100dvh - 9rem));overflow:auto;display:grid;gap:var(--ui-gap-xs);padding-right:.15rem;scrollbar-width:thin}.mechanics-review-replay-load{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.35rem var(--ui-gap-sm);min-width:0;padding:.5rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:#ffffff09}.mechanics-review-replay-load.loaded{border-color:#4caf786b}.mechanics-review-replay-load.error{border-color:#dc5f5f94}.mechanics-review-replay-load-main{display:grid;min-width:0;gap:.16rem}.mechanics-review-replay-load-title,.mechanics-review-replay-load-meta{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-replay-load-title{color:var(--text);font-size:.78rem;font-weight:700}.mechanics-review-replay-load-meta{color:var(--muted);font-size:.68rem}.mechanics-review-replay-load-status{max-width:11rem;overflow:hidden;color:var(--muted);font-size:.68rem;text-align:right;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-replay-load.loaded .mechanics-review-replay-load-status{color:#83d4a4}.mechanics-review-replay-load.error .mechanics-review-replay-load-status{color:#ff9b9b}.mechanics-review-replay-load-progress{grid-column:1 / -1;height:.25rem;overflow:hidden;border-radius:999px;background:#ffffff14}.mechanics-review-replay-load-progress span{display:block;width:0;height:100%;border-radius:inherit;background:#77a9ff;transition:width .14s ease}.mechanics-review-replay-load.loaded .mechanics-review-replay-load-progress span{background:#4caf78}.mechanics-review-replay-load.error .mechanics-review-replay-load-progress span{background:#dc5f5f}.mechanics-review-list{max-height:min(22rem,calc(100dvh - 27rem));display:grid;gap:var(--ui-gap-xs);overflow:auto;padding-right:.15rem;scrollbar-width:thin}.mechanics-review-item{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--ui-gap-sm);align-items:center;width:100%;min-height:2rem;text-align:left}.mechanics-review-item span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-item strong{color:var(--muted);font-size:.72rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-item[data-active=true]{border-color:#4b94ff6b;background:#4b94ff29}.viewport canvas{display:block;width:100%;height:100%}.replay-load-modal{position:fixed;inset:0;z-index:100;display:grid;place-items:center;padding:1.25rem;background:radial-gradient(circle at top,rgba(89,157,219,.18),transparent 30%),#040b12c2;-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px)}.replay-load-modal[hidden]{display:none}.replay-load-modal__dialog{width:min(32rem,100%);display:grid;gap:.75rem;padding:1.4rem 1.45rem;border-radius:1.35rem;border:1px solid rgba(255,255,255,.12);background:linear-gradient(180deg,#0b1724f5,#070f18f0);box-shadow:0 24px 70px #0006}.replay-load-modal__eyebrow{margin:0;font-size:.72rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase;color:#87afd4}.replay-load-modal__title,.replay-load-modal__status,.replay-load-modal__meta{margin:0}.replay-load-modal__title{font-size:clamp(1.45rem,4vw,2.1rem);line-height:1.1;color:#f3f8fc}.replay-load-modal__status{color:#e6f0f7;font-size:1rem}.replay-load-modal__phase-list{display:grid;gap:.52rem}.replay-load-modal__phase-row{display:grid;gap:.28rem}.replay-load-modal__phase-label{margin:0;font-size:.82rem;letter-spacing:.04em;color:#9eb4c6}.replay-load-modal__phase-row[data-state=active] .replay-load-modal__phase-label{color:#edf5fa}.replay-load-modal__phase-row[data-state=complete] .replay-load-modal__phase-label{color:#c5d9e7}.replay-load-modal__phase-bar{overflow:hidden;height:.58rem;border-radius:999px;background:#ffffff1a}.replay-load-modal__phase-fill{width:0%;height:100%;border-radius:inherit;background:linear-gradient(90deg,#4b94ff,#8ec5ff 55%,#f39a37);transition:width .14s ease}.replay-load-modal__phase-row[data-state=complete] .replay-load-modal__phase-fill{opacity:.95}.replay-load-modal__phase-fill[data-indeterminate=true]{width:100%!important;background:linear-gradient(90deg,#4b94ff40,#4b94ffcc 28%,#8ec5fff2,#f39a37cc 72%,#f39a3740);background-size:180% 100%;animation:replay-load-phase-indeterminate 1.1s linear infinite}@keyframes replay-load-phase-indeterminate{0%{background-position:0% 0%}to{background-position:180% 0%}}.replay-load-modal__meta{color:#9eb4c6;font-size:.92rem}.empty-state{position:absolute;left:50%;top:50%;z-index:10;display:grid;gap:.55rem;min-width:min(20rem,calc(100vw - 2rem));transform:translate(-50%,-50%);padding:.85rem .95rem;border-radius:1rem;border:1px solid rgba(169,201,226,.14);background:#040c12d1;color:#bfd2de;text-align:center;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}.empty-state[hidden]{display:none}.empty-state p{margin:0}.stats-panel{padding:1.15rem 1.15rem 1rem}.panel-heading{display:flex;justify-content:space-between;align-items:start;gap:1rem;margin-bottom:1rem}.player-stats-stack{display:grid;gap:.9rem}.player-team-stack{display:grid;gap:.85rem}.player-team-group{display:grid;gap:.7rem;padding:.75rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:linear-gradient(180deg,var(--team-soft),rgba(255,255,255,.025)),#ffffff08}.player-team-header{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-md);padding-bottom:.42rem;border-bottom:1px solid color-mix(in srgb,var(--team-accent) 36%,transparent)}.player-team-header h3{margin:0;color:#edf5fa;font-size:.76rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.player-team-header span{flex-shrink:0;color:color-mix(in srgb,var(--team-accent) 62%,#edf5fa);font-size:.68rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase}.player-stats-grid{display:flex;gap:.7rem;flex-wrap:wrap}.player-card{flex:1 1 13rem;min-width:12rem;padding:.85rem;border-radius:1rem;border:1px solid rgba(255,255,255,.08);background:#ffffff09}.player-card.team-blue{background:var(--blue-soft);border-color:#4b94ff42}.player-card.team-orange{background:var(--orange-soft);border-color:#f39a3747}.player-card.shared{background:linear-gradient(180deg,#ffffff0f,#ffffff06),#ffffff09;border-color:#ffffff1f}.player-card-header{display:flex;justify-content:space-between;align-items:center;gap:.4rem;margin-bottom:.45rem}.player-name{font-size:.85rem;font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stat-row{display:flex;justify-content:space-between;gap:.5rem;padding:.15rem 0;font-size:.8rem}.label,.detail-grid dt,.stat-row .label{color:#89a4ba}.stat-row .value,.detail-grid dd{font-variant-numeric:tabular-nums}.role-indicator,.depth-indicator{flex-shrink:0;padding:.18rem .45rem;border-radius:999px;font-size:.64rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase}.role-back,.depth-last{background:#ea55552e;color:#ff9b9b}.role-forward,.depth-upfield{background:#4ac6762e;color:#9ce5a8}.role-other,.depth-level{background:#8495a82e;color:#c0cbd6}.role-mid,.depth-mid{background:#f39a372e;color:#ffc680}.stat-module-section{display:grid;gap:.45rem}.stat-module-label{font-size:.72rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase;color:#6f889d}.sidebar{min-height:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));align-content:start;align-items:start;gap:1rem}.stat-window-empty{margin:0;color:#9eb4c6;font-size:.88rem}.stats-window-toolbar,.stats-window-scope-row,.stats-window-actions{display:flex;align-items:center;gap:var(--ui-gap-sm);flex-wrap:wrap}.stats-window-toolbar{justify-content:end}.stats-window-scope-select{min-width:min(100%,13rem)}.stats-window-add-button{width:var(--ui-control-height);min-width:var(--ui-control-height);padding:0;font-size:1rem;font-weight:800;line-height:1}.stats-window-add-button[aria-expanded=true]{border-color:var(--ui-border-hover);background:#ffffff1a}.stats-window-scope-select.team-blue,.stats-window-scope-select.team-orange,.stats-window-stat-target.team-blue,.stats-window-stat-target.team-orange{border-color:var(--team-accent);box-shadow:inset .22rem 0 0 var(--team-accent)}.stats-window-picker{display:grid;gap:var(--ui-gap-sm);padding:var(--ui-panel-padding);border-radius:var(--ui-radius-md);border:1px solid rgba(255,255,255,.08);background:#ffffff0a}.stats-window-picker[hidden]{display:none}.stats-window-picker-list{display:grid;gap:var(--ui-gap-xs);overflow:visible}.stats-window-picker-item{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.45rem;align-items:center;width:100%;padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);text-align:left}.stats-window-picker-item span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stats-window-picker-item strong{color:#87afd4;font-size:.62rem;letter-spacing:.08em;text-transform:uppercase}.stats-window-stat-list,.stats-window-entity-list,.stats-window-team-list{display:grid;gap:var(--ui-gap-sm)}.stats-window-team-group{display:grid;gap:var(--ui-gap-sm);padding:.48rem .5rem .55rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:linear-gradient(180deg,var(--team-soft),rgba(255,255,255,.025)),#ffffff08}.stats-window-team-header{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-md);padding-bottom:.34rem;border-bottom:1px solid color-mix(in srgb,var(--team-accent) 36%,transparent)}.stats-window-team-header h3{margin:0;color:#edf5fa;font-size:.76rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.stats-window-team-header span{flex-shrink:0;color:color-mix(in srgb,var(--team-accent) 62%,#edf5fa);font-size:.68rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase}.stats-window-entity{display:grid;gap:var(--ui-gap-xs);padding-left:.5rem;border-left:2px solid rgba(255,255,255,.12)}.stats-window-entity.team-blue,.stats-window-entity.team-orange{border-left-color:var(--team-accent);background:linear-gradient(90deg,var(--team-soft),transparent 70%)}.stats-window-entity-title{margin:0;color:#edf5fa;font-size:.82rem;font-weight:800}.stats-window-stat-row{display:grid;grid-template-columns:minmax(0,1fr) auto auto;gap:var(--ui-gap-sm);align-items:center;min-height:1.45rem;font-size:.8rem}.stats-window-stat-name{min-width:0;color:#9eb4c6;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stats-window-stat-target{max-width:7rem;margin-left:.35rem;padding:.16rem .3rem;border-radius:var(--ui-radius-sm);font-size:.7rem}.stats-window-stat-value{color:#edf5fa;font-variant-numeric:tabular-nums}.stats-window-stat-remove{padding:.18rem .36rem;border-radius:var(--ui-radius-sm);font-size:.7rem}.goal-label-list{display:grid;gap:var(--ui-gap-sm);min-width:min(26rem,72vw)}.goal-label-item{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--ui-gap-sm);align-items:center;padding:.56rem .62rem;border-left:2px solid rgba(255,255,255,.14);border-radius:var(--ui-radius-md);background:#ffffff09}.goal-label-item.team-blue,.goal-label-item.team-orange{border-left-color:var(--team-accent);background:linear-gradient(90deg,var(--team-soft),rgba(255,255,255,.03))}.goal-label-item header{min-width:0}.goal-label-item h3{margin:0;color:#edf5fa;font-size:.82rem;font-weight:800}.goal-label-item header span{display:block;margin-top:.12rem;color:#9eb4c6;font-size:.72rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.goal-label-tags{grid-column:1 / -1;display:flex;flex-wrap:wrap;gap:.32rem}.goal-label-tag{padding:.16rem .38rem;border-radius:var(--ui-radius-sm);background:#8ec5ff21;color:#cfe6ff;font-size:.68rem;font-weight:800}.goal-label-tag-empty{background:#8495a829;color:#c0cbd6}.goal-label-actions{justify-self:end;display:flex;gap:.28rem}.goal-label-actions button{min-height:1.8rem;padding:.2rem .48rem;font-size:.72rem}.goal-label-actions .goal-label-watch{border-color:#65d6ad5c;background:#65d6ad2e;color:#d7ffef}.stats-window:has(.kickoff-overview){width:min(34rem,calc(100vw - 1.6rem))}.kickoff-overview{display:grid;gap:var(--ui-gap-md);width:100%;min-width:0}.kickoff-overview-hero{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--ui-gap-md);align-items:start;padding-bottom:.52rem;border-bottom:1px solid rgba(255,255,255,.1)}.kickoff-overview-hero h3{margin:0;color:#edf5fa;font-size:.92rem;font-weight:800}.kickoff-overview-hero span{display:block;margin-top:.12rem;color:#9eb4c6;font-size:.72rem}.kickoff-overview-victor{max-width:9rem;padding:.2rem .46rem;border-radius:var(--ui-radius-sm);background:#8495a82e;color:#d8e5ee;font-size:.72rem;font-weight:800;text-align:center}.kickoff-overview-victor.team-blue,.kickoff-overview-victor.team-orange{background:var(--team-soft);color:color-mix(in srgb,var(--team-accent) 72%,#ffffff)}.kickoff-overview-summary{display:grid;grid-template-columns:1fr;gap:var(--ui-gap-sm)}.kickoff-metric{display:grid;gap:.12rem;min-width:0;padding:.46rem .52rem;border-radius:var(--ui-radius-md);border:1px solid rgba(255,255,255,.08);background:#ffffff09}.kickoff-metric span,.kickoff-detail-row span{color:#89a4ba;font-size:.7rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.kickoff-metric strong{min-width:0;color:#edf5fa;font-size:.78rem;overflow-wrap:anywhere}.kickoff-detail-grid{display:grid;gap:.18rem}.kickoff-detail-row{display:grid;grid-template-columns:minmax(7.5rem,1fr) auto;gap:var(--ui-gap-sm);align-items:baseline;min-height:1.38rem;font-size:.78rem}.kickoff-detail-row strong{color:#edf5fa;font-variant-numeric:tabular-nums}.kickoff-strategy-list{display:grid;grid-template-columns:1fr;gap:var(--ui-gap-sm)}.kickoff-strategy-team{display:grid;gap:.34rem;min-width:0;padding:.54rem .58rem;border-radius:var(--ui-radius-md);border:1px solid color-mix(in srgb,var(--team-accent) 26%,transparent);background:linear-gradient(180deg,var(--team-soft),rgba(255,255,255,.025)),#ffffff08}.kickoff-strategy-team h4{margin:0;color:color-mix(in srgb,var(--team-accent) 62%,#edf5fa);font-size:.72rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.kickoff-strategy-line{margin:0;color:#edf5fa;font-size:.78rem;line-height:1.35;overflow-wrap:anywhere}.kickoff-support-list{display:grid;gap:.22rem;margin:0;padding:0;list-style:none}.kickoff-support-list li{color:#afc4d4;font-size:.74rem;line-height:1.3;overflow-wrap:anywhere}@media(min-width:46rem){.kickoff-overview-summary{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:720px){.kickoff-overview-summary,.kickoff-detail-grid,.kickoff-strategy-list,.kickoff-overview-hero{grid-template-columns:1fr}.kickoff-overview-victor{justify-self:start}}.panel{padding:var(--ui-panel-padding);display:grid;gap:var(--ui-gap-md)}.panel>label,.panel>.detail-grid,.panel>.transport-row,.panel>.module-list{margin-top:0}.panel-copy{margin:0;font-size:.92rem;line-height:1.45}.transport-row{display:flex;gap:var(--ui-gap-sm)}.transport-row>*{flex:1 1 auto}.playback-rate-control{display:grid;gap:var(--ui-gap-xs)}.playback-rate-header{align-items:center;display:flex;justify-content:space-between}.playback-rate-header strong{font-variant-numeric:tabular-nums}.playback-rate-notches{color:var(--ui-muted);display:grid;font-size:.72rem;grid-template-columns:repeat(5,minmax(0,1fr));line-height:1.1;text-align:center}.playback-rate-notches span:first-child{text-align:left}.playback-rate-notches span:last-child{text-align:right}.recording-controls{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-sm)}.camera-presets{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-xs)}.camera-presets button{font-size:var(--ui-control-font-size)}.camera-presets button[data-active=true]{border-color:#8ec5ff6b;background:linear-gradient(180deg,#21476bf5,#0c1b2afa);color:#f3f8fc;box-shadow:inset 0 0 0 1px #8ec5ff1f}.camera-ball-cam{display:grid;gap:var(--ui-gap-xs)}.camera-ball-cam-modes{grid-template-columns:repeat(3,minmax(0,1fr))}.camera-settings-controls{display:grid;gap:var(--ui-gap-sm)}.camera-settings-controls[hidden]{display:none}.camera-setting-label{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-md);font-size:.8rem;color:#9fb3c4}.camera-setting-label strong{color:#e8f0f7;font-variant-numeric:tabular-nums}button,select,input[type=file],input[type=range]{border-radius:var(--ui-radius-md)}button,select,input[type=file]{min-height:var(--ui-control-height);border:1px solid var(--ui-border-subtle);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);background:var(--surface-strong);color:var(--text);font-size:var(--ui-control-font-size);line-height:var(--ui-control-line-height)}button{cursor:pointer}select{appearance:none;padding-right:1.35rem;background-image:linear-gradient(45deg,transparent 50%,var(--muted) 50%),linear-gradient(135deg,var(--muted) 50%,transparent 50%);background-position:calc(100% - .76rem) 50%,calc(100% - .52rem) 50%;background-repeat:no-repeat;background-size:.24rem .24rem}button:hover:not(:disabled),select:hover:not(:disabled){border-color:var(--ui-border-hover)}button:disabled,select:disabled,input:disabled{opacity:.55;cursor:not-allowed}input[type=range]{width:100%;margin-top:var(--ui-gap-xs);accent-color:var(--blue)}.metric-readout{font-size:.88rem;font-weight:700;font-variant-numeric:tabular-nums}.toggle{display:inline-flex;align-items:center;gap:.4rem;color:#bfd0dd}.detail-grid{margin:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.55rem .7rem}.detail-grid dt,.detail-grid dd{margin:0}.detail-grid dt{font-size:.68rem;margin-bottom:.12rem}.detail-grid dd{font-size:.84rem;color:var(--text);overflow-wrap:anywhere}.module-groups{display:grid;gap:var(--ui-gap-md)}.module-summary-group{display:grid;gap:var(--ui-gap-xs)}.module-summary-group h3{margin:0;color:#87afd4;font-size:.64rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase}.module-list{display:flex;flex-wrap:wrap;gap:.5rem}.mechanics-actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem;margin-bottom:.65rem}.mechanics-event-list{display:grid;grid-template-columns:repeat(var(--event-source-columns, 1),minmax(9.5rem,1fr));align-items:stretch}.module-settings{display:grid;gap:.75rem}.module-settings-card{display:grid;gap:.75rem;padding:.85rem .9rem;border-radius:1rem;border:1px solid rgba(255,255,255,.08);background:#ffffff09}.module-settings-subgroup{display:grid;gap:.65rem;padding-top:.15rem;border-top:1px solid rgba(255,255,255,.06)}.module-settings-options{display:grid;gap:.45rem}.module-settings-group-title{margin:0;color:#d7e5ef;font-size:.78rem;font-weight:800}.module-settings-header{display:flex;align-items:start;justify-content:space-between;gap:.8rem}.module-settings-header h3{margin:.1rem 0 0;font-size:.96rem}.module-settings-eyebrow{margin:0;font-size:.66rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase;color:#87afd4}.boost-pickup-filter-panel{display:grid;gap:.65rem}.boost-pickup-filter-summary{display:flex;justify-content:end}.boost-pickup-filter-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.75rem 1rem}.boost-pickup-filter-group{display:grid;align-content:start;gap:.35rem;min-width:0}.boost-pickup-filter-group[hidden]{display:none}.boost-pickup-filter-group-wide{grid-column:1 / -1}.boost-pickup-filter-options{display:flex;flex-wrap:wrap;gap:.35rem .8rem;min-width:0}.boost-pickup-filter-options .toggle{min-width:0}.module-summary-item{appearance:none;display:inline-flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm);min-height:var(--ui-control-height);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border-radius:var(--ui-radius-pill);border:1px solid var(--ui-border-subtle);background:#ffffff08;color:var(--muted);font:inherit;font-size:var(--ui-control-font-size);line-height:var(--ui-control-line-height);cursor:pointer;transition:border-color .14s ease,background-color .14s ease,color .14s ease}.module-summary-item:hover{border-color:var(--ui-border-hover);color:var(--text)}.module-summary-item strong{font-size:.62rem;letter-spacing:.08em;text-transform:uppercase}.module-summary-item[data-active=true]{border-color:#4b94ff38;background:#4b94ff14;color:#dceafb}@media(max-width:1180px){.sidebar{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:860px){.shell{padding:0}.sidebar{grid-template-columns:1fr}.panel-heading{display:grid}.detail-grid{grid-template-columns:1fr 1fr}.viewport-panel{min-height:100dvh}}@media(max-width:560px){.detail-grid{grid-template-columns:1fr}.transport-row{flex-direction:column}.floating-window,.stats-window{left:.55rem;right:.55rem;width:auto}}@media(max-width:720px){.viewport-panel:has(.floating-window:not([hidden])) .viewport{inset:0 0 52dvh}.floating-window{position:fixed;inset:auto 0 0;width:100%;max-width:none;height:52dvh;max-height:52dvh;overflow:auto;border-width:1px 0 0 0;border-radius:1rem 1rem 0 0;transform:none;z-index:30}.floating-window .floating-window-header{cursor:default}}.missed-event-body{display:flex;flex-direction:column;gap:.5rem;padding:.6rem .7rem;max-height:50vh;font-size:.8rem}.missed-event-controls{display:flex;align-items:center;gap:.4rem}.missed-event-controls select{flex:1 1 auto}.missed-event-list{list-style:none;margin:0;padding:0;overflow-y:auto;display:flex;flex-direction:column;gap:.25rem}.missed-event-list li{display:flex;align-items:center;justify-content:space-between;gap:.4rem;padding:.2rem .3rem;border-radius:.3rem;background:#1c272ee6}.missed-event-status{margin:0;min-height:1rem;color:#9fadb7} +:root{color-scheme:dark;font-family:IBM Plex Sans,Avenir Next,sans-serif;font-size:13px;--surface: rgba(8, 20, 30, .82);--surface-strong: rgba(7, 16, 24, .94);--surface-soft: rgba(12, 28, 40, .72);--border: rgba(167, 199, 222, .14);--text: #edf5fa;--muted: #9eb4c6;--blue: #4b94ff;--blue-soft: rgba(75, 148, 255, .18);--orange: #f39a37;--orange-soft: rgba(243, 154, 55, .18);--ui-gap-xs: .22rem;--ui-gap-sm: .34rem;--ui-gap-md: .5rem;--ui-panel-padding: .52rem;--ui-control-font-size: .72rem;--ui-control-line-height: 1.15;--ui-control-padding-block: .22rem;--ui-control-padding-inline: .38rem;--ui-control-height: 1.55rem;--ui-radius-sm: .36rem;--ui-radius-md: .5rem;--ui-radius-lg: .72rem;--ui-radius-pill: 999px;--ui-border-subtle: rgba(255, 255, 255, .1);--ui-border-hover: rgba(255, 255, 255, .18);--ui-overlay-bg: rgba(4, 12, 18, .82);--ui-overlay-bg-strong: rgba(4, 12, 18, .9);background:radial-gradient(circle at top left,rgba(73,112,158,.28),transparent 32%),radial-gradient(circle at top right,rgba(243,154,55,.12),transparent 24%),linear-gradient(180deg,#071018,#0b1721);color:var(--text)}*,*:before,*:after{box-sizing:border-box}html,body,#app{width:100%;height:100%;overflow:hidden}body{margin:0}button,select,input{font:inherit}.shell{min-height:100dvh;height:100dvh;padding:0;display:block}.workspace{height:100%;display:block;min-height:0}.panel h2,.stats-panel h2{margin:0}.panel-copy{color:#bdd0de}.viewport-panel,.panel,.stats-panel{position:relative;border:1px solid var(--border);border-radius:1.4rem;background:var(--surface);box-shadow:0 22px 56px #0000003d;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}.viewport-panel{width:100%;height:100%;min-height:100dvh;overflow:hidden;border:0;border-radius:0;background:#061019;box-shadow:none}.viewport{position:absolute;inset:0}.top-chrome{position:absolute;top:.8rem;left:.8rem;z-index:20}.launcher-toggle{width:2.65rem;min-width:0;aspect-ratio:1;display:grid;place-items:center;padding:0;border-color:transparent;border-radius:var(--ui-radius-md);background:#050e16ad;box-shadow:0 12px 30px #0000004d;-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px)}.launcher-toggle:hover,.launcher-toggle[aria-expanded=true]{border-color:#ffffff29;background:#081824d1}.launcher-toggle-bars,.launcher-toggle-bars:before,.launcher-toggle-bars:after{display:block;width:1.18rem;height:.12rem;border-radius:var(--ui-radius-pill);background:#edf5fa}.launcher-toggle-bars{position:relative}.launcher-toggle-bars:before,.launcher-toggle-bars:after{content:"";position:absolute;left:0}.launcher-toggle-bars:before{top:-.38rem}.launcher-toggle-bars:after{top:.38rem}.launcher-menu{position:absolute;top:calc(100% + .55rem);left:0;width:min(22rem,calc(100vw - 1.6rem));max-height:calc(100dvh - 7.5rem);overflow:auto;display:grid;gap:var(--ui-gap-md);padding:var(--ui-panel-padding);border:1px solid rgba(255,255,255,.12);border-radius:var(--ui-radius-lg);background:var(--ui-overlay-bg-strong);box-shadow:0 18px 54px #0000005c;-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px)}.launcher-menu[hidden]{display:none}.launcher-section{display:grid;gap:var(--ui-gap-xs)}.launcher-section h2{margin:0;color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase}.launcher-section button{width:100%;text-align:left}.hidden-file-input,.visually-hidden{position:fixed;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap}.team-blue{--team-accent: var(--blue);--team-soft: var(--blue-soft)}.team-orange{--team-accent: var(--orange);--team-soft: var(--orange-soft)}.floating-window-layer,.stats-window-layer{position:absolute;inset:0;z-index:12;pointer-events:none}.floating-window,.stats-window,.scoreboard-window{position:absolute;left:clamp(.8rem,var(--window-x, 1rem),calc(100vw - 18rem));top:clamp(.8rem,var(--window-y, 1rem),calc(100dvh - 12rem));width:min(26rem,calc(100vw - 1.6rem));overflow:visible;display:grid;gap:var(--ui-gap-md);padding:var(--ui-panel-padding);border:1px solid rgba(255,255,255,.12);border-radius:var(--ui-radius-lg);background:var(--ui-overlay-bg);box-shadow:0 16px 44px #00000052;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);pointer-events:auto;-webkit-user-select:none;user-select:none}.floating-window[hidden],.stats-window[hidden],.scoreboard-window[hidden]{display:none}.scoreboard-window{left:50%;top:.7rem;width:auto;min-width:4.4rem;transform:translate(-50%);gap:var(--ui-gap-sm);padding:.34rem .62rem;border-radius:999px}.scoreboard-window-body{display:grid;gap:.42rem}.scoreboard-scoreline{display:grid;grid-template-columns:minmax(1.2rem,auto) auto minmax(1.2rem,auto);align-items:center;justify-content:center;gap:.3rem;min-width:0;font-variant-numeric:tabular-nums}.scoreboard-goal-value{color:var(--team-accent);font-size:1rem;font-weight:850;line-height:1;text-align:center}.scoreboard-divider{color:var(--muted);font-size:1rem;font-weight:800;line-height:1}.scoreboard-empty{margin:0;color:var(--muted);font-size:.74rem;text-align:center}@media(max-width:900px){.scoreboard-window{top:3.25rem}}@media(max-width:640px){.scoreboard-window{min-width:4rem;padding:.32rem .56rem}.scoreboard-scoreline{gap:.24rem}.scoreboard-goal-value{font-size:.92rem}}.floating-window-camera{width:min(26rem,calc(100vw - 1.6rem))}.floating-window-recording{--window-x: calc(100vw - 27rem) ;width:min(26rem,calc(100vw - 1.6rem))}.floating-window-playback{--window-x: calc(100vw - 23rem) ;width:min(21rem,calc(100vw - 1.6rem))}.floating-window-mechanics{width:auto;min-width:min(18rem,calc(100vw - 1.6rem));max-width:min(42rem,calc(100vw - 1.6rem))}.mechanics-timeline-window-body{display:grid;gap:var(--ui-gap-sm);max-height:min(72dvh,42rem);overflow:auto}.floating-window-event-playlist{width:min(27rem,calc(100vw - 1.6rem))}.floating-window-mechanics-review{width:min(30rem,calc(100vw - 1.6rem))}.floating-window-replay-loading{width:min(32rem,calc(100vw - 1.6rem))}.floating-window-boost-pickups{width:min(34rem,calc(100vw - 1.6rem))}.floating-window-touch-controls,.floating-window-touch-legend{width:min(24rem,calc(100vw - 1.6rem))}.floating-window-shot-visualization{width:min(38rem,calc(100vw - 1.6rem))}.floating-window-header,.stats-window-header{display:flex;align-items:start;justify-content:space-between;gap:var(--ui-gap-md);cursor:grab}.stats-window-header-actions-only{justify-content:end}.floating-window:active .floating-window-header,.stats-window:active .stats-window-header{cursor:grabbing}.floating-window-header h2,.stats-window-header h2{margin:0;color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase}.floating-window-hide,.stats-window-action{flex-shrink:0;padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border-radius:var(--ui-radius-md);font-size:var(--ui-control-font-size)}.mechanics-review-window-body{display:grid;gap:var(--ui-gap-md);max-height:min(74dvh,42rem);min-height:0;overflow:hidden auto;scrollbar-width:thin}.event-playlist-window-body{display:grid;gap:var(--ui-gap-sm);min-height:0}.touch-color-legend-body{display:grid;gap:var(--ui-gap-md);max-height:min(70dvh,38rem);overflow:auto;scrollbar-width:thin}.touch-color-legend-explainer{display:grid;gap:var(--ui-gap-xs);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);color:#c3d3df;font-size:.78rem;background:#ffffff0a}.touch-color-legend-group{display:grid;gap:var(--ui-gap-xs)}.touch-color-legend-heading{width:100%;min-height:1.45rem;margin:0;padding:.12rem .32rem;border-radius:var(--ui-radius-sm);color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.1em;text-align:left;text-transform:uppercase}.touch-color-legend-heading[data-active=true]{border-color:#8ec5ff6b;background:#21476b94;color:#f3f8fc}.touch-color-legend-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-xs)}.touch-color-legend-item{min-width:0;display:flex;align-items:center;gap:var(--ui-gap-xs);color:#e8f0f7;font-size:.76rem}.touch-color-legend-swatch{flex:0 0 auto;width:.78rem;height:.78rem;border:1px solid rgba(255,255,255,.35);border-radius:50%;box-shadow:0 0 0 1px #00000038}.event-playlist-toolbar{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm)}.event-playlist-filter{position:relative;min-width:0}.event-playlist-filter summary{display:inline-flex;align-items:center;min-height:var(--ui-control-height);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);background:#ffffff0a;color:var(--text);font-size:var(--ui-control-font-size);cursor:pointer;list-style:none}.event-playlist-filter summary::-webkit-details-marker{display:none}.event-playlist-filter-panel{position:absolute;z-index:5;top:calc(100% + .4rem);left:0;width:min(22rem,calc(100vw - 3rem));max-height:min(28rem,calc(100dvh - 10rem));overflow:auto;display:grid;gap:var(--ui-gap-md);padding:.85rem;border:1px solid rgba(255,255,255,.14);border-radius:var(--ui-radius-md);background:#090e16fa;box-shadow:0 16px 34px #00000057}.event-playlist-filter-actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem}.event-playlist-filter-group{display:grid;gap:.45rem}.event-playlist-filter-group h3{margin:0;color:#87afd4;font-size:.64rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase}.event-playlist-filter-option{min-width:0}.event-playlist-follow{flex-shrink:0}.event-playlist-list{max-height:min(31rem,calc(100dvh - 11rem));overflow:auto;display:grid;gap:.45rem;padding-right:.15rem;scrollbar-width:thin}.event-playlist-item{--event-color: #d1d9e0;appearance:none;width:100%;display:grid;grid-template-columns:3.4rem minmax(0,1fr);gap:.7rem;align-items:start;padding:.6rem .7rem;border:1px solid rgba(255,255,255,.09);border-left:.28rem solid var(--event-color);border-radius:var(--ui-radius-md);background:#ffffff09;color:var(--text);font:inherit;text-align:left;cursor:pointer}.event-playlist-item:hover,.event-playlist-item[data-active=true]{border-color:color-mix(in srgb,var(--event-color) 48%,rgba(255,255,255,.12));background:color-mix(in srgb,var(--event-color) 15%,rgba(255,255,255,.045))}.event-playlist-time{color:var(--muted);font-size:.72rem;font-variant-numeric:tabular-nums;line-height:1.35}.event-playlist-main{min-width:0;display:grid;gap:.15rem}.shot-visualization{display:grid;gap:var(--ui-gap-md);min-height:0}.shot-visualization-summary{color:var(--text);font-size:.78rem;font-weight:700;font-variant-numeric:tabular-nums}.shot-chart-canvas{width:100%;aspect-ratio:16 / 10;display:block;border:1px solid rgba(255,255,255,.1);border-radius:var(--ui-radius-md);background:#0f2b24}.shot-visualization-layout{display:grid;grid-template-columns:minmax(10rem,.78fr) minmax(15rem,1.22fr);gap:var(--ui-gap-md);min-height:0}.shot-list{display:grid;align-content:start;gap:.45rem;max-height:18rem;overflow:auto;padding-right:.15rem;scrollbar-width:thin}.shot-list-item{appearance:none;width:100%;display:grid;gap:.15rem;min-height:3.1rem;padding:.52rem .62rem;border:1px solid rgba(255,255,255,.09);border-left:.24rem solid #62d2a2;border-radius:var(--ui-radius-md);background:#ffffff09;color:var(--text);font:inherit;text-align:left;cursor:pointer}.shot-list-item[data-selected=true]{border-color:#f8fafcb8;background:#87afd429}.shot-list-item[data-active=true]{border-left-color:#e11d48}.shot-list-title{min-width:0;overflow:hidden;color:var(--text);font-size:.78rem;font-weight:800;text-overflow:ellipsis;white-space:nowrap}.shot-list-meta{color:var(--muted);font-size:.68rem;font-variant-numeric:tabular-nums;white-space:nowrap}.shot-demo-panel{display:grid;gap:var(--ui-gap-sm);min-width:0}.shot-demo-scene{width:100%;height:12rem;overflow:hidden;border:1px solid rgba(255,255,255,.1);border-radius:var(--ui-radius-md);background:#07111c}.shot-demo-scene canvas{width:100%;height:100%;display:block}.shot-details{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem;margin:0}.shot-details div{min-width:0;padding:.48rem .56rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:#ffffff09}.shot-details dt{color:var(--muted);font-size:.62rem;font-weight:700;text-transform:uppercase}.shot-details dd{min-width:0;margin:.14rem 0 0;overflow:hidden;color:var(--text);font-size:.76rem;font-variant-numeric:tabular-nums;text-overflow:ellipsis;white-space:nowrap}.shot-visualization-empty{margin:0;color:var(--muted);font-size:.78rem}.event-playlist-main strong{min-width:0;overflow-wrap:anywhere;font-size:.82rem;line-height:1.3}.event-playlist-main span{min-width:0;overflow-wrap:anywhere;color:var(--muted);font-size:.68rem;line-height:1.35}.mechanics-review-load-row{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:var(--ui-gap-sm);align-items:center}.mechanics-review-file{display:inline-grid;align-items:center;min-height:var(--ui-control-height);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);background:#ffffff0e;color:var(--text);cursor:pointer}.mechanics-review-file input{position:fixed;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap}.mechanics-review-url{min-width:0}.mechanics-review-status{min-height:1.2rem;color:var(--muted);font-size:.78rem}.mechanics-review-current{display:grid;gap:var(--ui-gap-sm);padding:.55rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:#ffffff09}.mechanics-review-index{color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase}.mechanics-review-current h3{margin:0;font-size:.96rem;line-height:1.2}.mechanics-review-fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-sm);margin:0}.mechanics-review-fields div{min-width:0}.mechanics-review-fields dt{color:var(--muted);font-size:.68rem;text-transform:uppercase}.mechanics-review-fields dd{margin:.1rem 0 0;overflow-wrap:anywhere}.mechanics-review-wide{grid-column:1 / -1}.mechanics-review-actions,.mechanics-review-decision-actions,.mechanics-review-list-header{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm)}.mechanics-review-actions button,.mechanics-review-decision-actions button{flex:1 1 0}#mechanics-review-confirm{border-color:#4caf7885}#mechanics-review-reject{border-color:#dc5f5f94}.mechanics-review-list-header{color:var(--muted);font-size:.72rem;font-weight:700;text-transform:uppercase}.mechanics-review-replays{display:grid;gap:var(--ui-gap-xs)}.replay-loading-window-body{display:grid;gap:var(--ui-gap-sm);max-height:min(72dvh,40rem);min-height:0}.replay-loading-summary{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm);color:var(--muted);font-size:.72rem;font-weight:700;text-transform:uppercase}.replay-loading-list{max-height:min(38rem,calc(100dvh - 9rem));overflow:auto;display:grid;gap:var(--ui-gap-xs);padding-right:.15rem;scrollbar-width:thin}.mechanics-review-replay-load{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.35rem var(--ui-gap-sm);min-width:0;padding:.5rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:#ffffff09}.mechanics-review-replay-load.loaded{border-color:#4caf786b}.mechanics-review-replay-load.error{border-color:#dc5f5f94}.mechanics-review-replay-load-main{display:grid;min-width:0;gap:.16rem}.mechanics-review-replay-load-title,.mechanics-review-replay-load-meta{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-replay-load-title{color:var(--text);font-size:.78rem;font-weight:700}.mechanics-review-replay-load-meta{color:var(--muted);font-size:.68rem}.mechanics-review-replay-load-status{max-width:11rem;overflow:hidden;color:var(--muted);font-size:.68rem;text-align:right;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-replay-load.loaded .mechanics-review-replay-load-status{color:#83d4a4}.mechanics-review-replay-load.error .mechanics-review-replay-load-status{color:#ff9b9b}.mechanics-review-replay-load-progress{grid-column:1 / -1;height:.25rem;overflow:hidden;border-radius:999px;background:#ffffff14}.mechanics-review-replay-load-progress span{display:block;width:0;height:100%;border-radius:inherit;background:#77a9ff;transition:width .14s ease}.mechanics-review-replay-load.loaded .mechanics-review-replay-load-progress span{background:#4caf78}.mechanics-review-replay-load.error .mechanics-review-replay-load-progress span{background:#dc5f5f}.mechanics-review-list{max-height:min(22rem,calc(100dvh - 27rem));display:grid;gap:var(--ui-gap-xs);overflow:auto;padding-right:.15rem;scrollbar-width:thin}.mechanics-review-item{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--ui-gap-sm);align-items:center;width:100%;min-height:2rem;text-align:left}.mechanics-review-item span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-item strong{color:var(--muted);font-size:.72rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-item[data-active=true]{border-color:#4b94ff6b;background:#4b94ff29}.viewport canvas{display:block;width:100%;height:100%}.replay-load-modal{position:fixed;inset:0;z-index:100;display:grid;place-items:center;padding:1.25rem;background:radial-gradient(circle at top,rgba(89,157,219,.18),transparent 30%),#040b12c2;-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px)}.replay-load-modal[hidden]{display:none}.replay-load-modal__dialog{width:min(32rem,100%);display:grid;gap:.75rem;padding:1.4rem 1.45rem;border-radius:1.35rem;border:1px solid rgba(255,255,255,.12);background:linear-gradient(180deg,#0b1724f5,#070f18f0);box-shadow:0 24px 70px #0006}.replay-load-modal__eyebrow{margin:0;font-size:.72rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase;color:#87afd4}.replay-load-modal__title,.replay-load-modal__status,.replay-load-modal__meta{margin:0}.replay-load-modal__title{font-size:clamp(1.45rem,4vw,2.1rem);line-height:1.1;color:#f3f8fc}.replay-load-modal__status{color:#e6f0f7;font-size:1rem}.replay-load-modal__phase-list{display:grid;gap:.52rem}.replay-load-modal__phase-row{display:grid;gap:.28rem}.replay-load-modal__phase-label{margin:0;font-size:.82rem;letter-spacing:.04em;color:#9eb4c6}.replay-load-modal__phase-row[data-state=active] .replay-load-modal__phase-label{color:#edf5fa}.replay-load-modal__phase-row[data-state=complete] .replay-load-modal__phase-label{color:#c5d9e7}.replay-load-modal__phase-bar{overflow:hidden;height:.58rem;border-radius:999px;background:#ffffff1a}.replay-load-modal__phase-fill{width:0%;height:100%;border-radius:inherit;background:linear-gradient(90deg,#4b94ff,#8ec5ff 55%,#f39a37);transition:width .14s ease}.replay-load-modal__phase-row[data-state=complete] .replay-load-modal__phase-fill{opacity:.95}.replay-load-modal__phase-fill[data-indeterminate=true]{width:100%!important;background:linear-gradient(90deg,#4b94ff40,#4b94ffcc 28%,#8ec5fff2,#f39a37cc 72%,#f39a3740);background-size:180% 100%;animation:replay-load-phase-indeterminate 1.1s linear infinite}@keyframes replay-load-phase-indeterminate{0%{background-position:0% 0%}to{background-position:180% 0%}}.replay-load-modal__meta{color:#9eb4c6;font-size:.92rem}.empty-state{position:absolute;left:50%;top:50%;z-index:10;display:grid;gap:.55rem;min-width:min(20rem,calc(100vw - 2rem));transform:translate(-50%,-50%);padding:.85rem .95rem;border-radius:1rem;border:1px solid rgba(169,201,226,.14);background:#040c12d1;color:#bfd2de;text-align:center;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}.empty-state[hidden]{display:none}.empty-state p{margin:0}.stats-panel{padding:1.15rem 1.15rem 1rem}.panel-heading{display:flex;justify-content:space-between;align-items:start;gap:1rem;margin-bottom:1rem}.player-stats-stack{display:grid;gap:.9rem}.player-team-stack{display:grid;gap:.85rem}.player-team-group{display:grid;gap:.7rem;padding:.75rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:linear-gradient(180deg,var(--team-soft),rgba(255,255,255,.025)),#ffffff08}.player-team-header{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-md);padding-bottom:.42rem;border-bottom:1px solid color-mix(in srgb,var(--team-accent) 36%,transparent)}.player-team-header h3{margin:0;color:#edf5fa;font-size:.76rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.player-team-header span{flex-shrink:0;color:color-mix(in srgb,var(--team-accent) 62%,#edf5fa);font-size:.68rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase}.player-stats-grid{display:flex;gap:.7rem;flex-wrap:wrap}.player-card{flex:1 1 13rem;min-width:12rem;padding:.85rem;border-radius:1rem;border:1px solid rgba(255,255,255,.08);background:#ffffff09}.player-card.team-blue{background:var(--blue-soft);border-color:#4b94ff42}.player-card.team-orange{background:var(--orange-soft);border-color:#f39a3747}.player-card.shared{background:linear-gradient(180deg,#ffffff0f,#ffffff06),#ffffff09;border-color:#ffffff1f}.player-card-header{display:flex;justify-content:space-between;align-items:center;gap:.4rem;margin-bottom:.45rem}.player-name{font-size:.85rem;font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stat-row{display:flex;justify-content:space-between;gap:.5rem;padding:.15rem 0;font-size:.8rem}.label,.detail-grid dt,.stat-row .label{color:#89a4ba}.stat-row .value,.detail-grid dd{font-variant-numeric:tabular-nums}.role-indicator,.depth-indicator{flex-shrink:0;padding:.18rem .45rem;border-radius:999px;font-size:.64rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase}.role-back,.depth-last{background:#ea55552e;color:#ff9b9b}.role-forward,.depth-upfield{background:#4ac6762e;color:#9ce5a8}.role-other,.depth-level{background:#8495a82e;color:#c0cbd6}.role-mid,.depth-mid{background:#f39a372e;color:#ffc680}.stat-module-section{display:grid;gap:.45rem}.stat-module-label{font-size:.72rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase;color:#6f889d}.sidebar{min-height:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));align-content:start;align-items:start;gap:1rem}.stat-window-empty{margin:0;color:#9eb4c6;font-size:.88rem}.stats-window-toolbar,.stats-window-scope-row,.stats-window-actions{display:flex;align-items:center;gap:var(--ui-gap-sm);flex-wrap:wrap}.stats-window-toolbar{justify-content:end}.stats-window-scope-select{min-width:min(100%,13rem)}.stats-window-add-button{width:var(--ui-control-height);min-width:var(--ui-control-height);padding:0;font-size:1rem;font-weight:800;line-height:1}.stats-window-add-button[aria-expanded=true]{border-color:var(--ui-border-hover);background:#ffffff1a}.stats-window-scope-select.team-blue,.stats-window-scope-select.team-orange,.stats-window-stat-target.team-blue,.stats-window-stat-target.team-orange{border-color:var(--team-accent);box-shadow:inset .22rem 0 0 var(--team-accent)}.stats-window-picker{display:grid;gap:var(--ui-gap-sm);padding:var(--ui-panel-padding);border-radius:var(--ui-radius-md);border:1px solid rgba(255,255,255,.08);background:#ffffff0a}.stats-window-picker[hidden]{display:none}.stats-window-picker-list{display:grid;gap:var(--ui-gap-xs);overflow:visible}.stats-window-picker-item{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.45rem;align-items:center;width:100%;padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);text-align:left}.stats-window-picker-item span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stats-window-picker-item strong{color:#87afd4;font-size:.62rem;letter-spacing:.08em;text-transform:uppercase}.stats-window-stat-list,.stats-window-entity-list,.stats-window-team-list{display:grid;gap:var(--ui-gap-sm)}.stats-window-team-group{display:grid;gap:var(--ui-gap-sm);padding:.48rem .5rem .55rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:linear-gradient(180deg,var(--team-soft),rgba(255,255,255,.025)),#ffffff08}.stats-window-team-header{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-md);padding-bottom:.34rem;border-bottom:1px solid color-mix(in srgb,var(--team-accent) 36%,transparent)}.stats-window-team-header h3{margin:0;color:#edf5fa;font-size:.76rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.stats-window-team-header span{flex-shrink:0;color:color-mix(in srgb,var(--team-accent) 62%,#edf5fa);font-size:.68rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase}.stats-window-entity{display:grid;gap:var(--ui-gap-xs);padding-left:.5rem;border-left:2px solid rgba(255,255,255,.12)}.stats-window-entity.team-blue,.stats-window-entity.team-orange{border-left-color:var(--team-accent);background:linear-gradient(90deg,var(--team-soft),transparent 70%)}.stats-window-entity-title{margin:0;color:#edf5fa;font-size:.82rem;font-weight:800}.stats-window-stat-row{display:grid;grid-template-columns:minmax(0,1fr) auto auto;gap:var(--ui-gap-sm);align-items:center;min-height:1.45rem;font-size:.8rem}.stats-window-stat-name{min-width:0;color:#9eb4c6;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stats-window-stat-target{max-width:7rem;margin-left:.35rem;padding:.16rem .3rem;border-radius:var(--ui-radius-sm);font-size:.7rem}.stats-window-stat-value{color:#edf5fa;font-variant-numeric:tabular-nums}.stats-window-stat-remove{padding:.18rem .36rem;border-radius:var(--ui-radius-sm);font-size:.7rem}.goal-label-list{display:grid;gap:var(--ui-gap-sm);min-width:min(26rem,72vw)}.goal-label-item{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--ui-gap-sm);align-items:center;padding:.56rem .62rem;border-left:2px solid rgba(255,255,255,.14);border-radius:var(--ui-radius-md);background:#ffffff09}.goal-label-item.team-blue,.goal-label-item.team-orange{border-left-color:var(--team-accent);background:linear-gradient(90deg,var(--team-soft),rgba(255,255,255,.03))}.goal-label-item header{min-width:0}.goal-label-item h3{margin:0;color:#edf5fa;font-size:.82rem;font-weight:800}.goal-label-item header span{display:block;margin-top:.12rem;color:#9eb4c6;font-size:.72rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.goal-label-tags{grid-column:1 / -1;display:flex;flex-wrap:wrap;gap:.32rem}.goal-label-tag{padding:.16rem .38rem;border-radius:var(--ui-radius-sm);background:#8ec5ff21;color:#cfe6ff;font-size:.68rem;font-weight:800}.goal-label-tag-empty{background:#8495a829;color:#c0cbd6}.goal-label-actions{justify-self:end;display:flex;gap:.28rem}.goal-label-actions button{min-height:1.8rem;padding:.2rem .48rem;font-size:.72rem}.goal-label-actions .goal-label-watch{border-color:#65d6ad5c;background:#65d6ad2e;color:#d7ffef}.stats-window:has(.kickoff-overview){width:min(34rem,calc(100vw - 1.6rem))}.kickoff-overview{display:grid;gap:var(--ui-gap-md);width:100%;min-width:0}.kickoff-overview-hero{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--ui-gap-md);align-items:start;padding-bottom:.52rem;border-bottom:1px solid rgba(255,255,255,.1)}.kickoff-overview-hero h3{margin:0;color:#edf5fa;font-size:.92rem;font-weight:800}.kickoff-overview-hero span{display:block;margin-top:.12rem;color:#9eb4c6;font-size:.72rem}.kickoff-overview-victor{max-width:9rem;padding:.2rem .46rem;border-radius:var(--ui-radius-sm);background:#8495a82e;color:#d8e5ee;font-size:.72rem;font-weight:800;text-align:center}.kickoff-overview-victor.team-blue,.kickoff-overview-victor.team-orange{background:var(--team-soft);color:color-mix(in srgb,var(--team-accent) 72%,#ffffff)}.kickoff-overview-summary{display:grid;grid-template-columns:1fr;gap:var(--ui-gap-sm)}.kickoff-metric{display:grid;gap:.12rem;min-width:0;padding:.46rem .52rem;border-radius:var(--ui-radius-md);border:1px solid rgba(255,255,255,.08);background:#ffffff09}.kickoff-metric span,.kickoff-detail-row span{color:#89a4ba;font-size:.7rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.kickoff-metric strong{min-width:0;color:#edf5fa;font-size:.78rem;overflow-wrap:anywhere}.kickoff-detail-grid{display:grid;gap:.18rem}.kickoff-detail-row{display:grid;grid-template-columns:minmax(7.5rem,1fr) auto;gap:var(--ui-gap-sm);align-items:baseline;min-height:1.38rem;font-size:.78rem}.kickoff-detail-row strong{color:#edf5fa;font-variant-numeric:tabular-nums}.kickoff-strategy-list{display:grid;grid-template-columns:1fr;gap:var(--ui-gap-sm)}.kickoff-strategy-team{display:grid;gap:.34rem;min-width:0;padding:.54rem .58rem;border-radius:var(--ui-radius-md);border:1px solid color-mix(in srgb,var(--team-accent) 26%,transparent);background:linear-gradient(180deg,var(--team-soft),rgba(255,255,255,.025)),#ffffff08}.kickoff-strategy-team h4{margin:0;color:color-mix(in srgb,var(--team-accent) 62%,#edf5fa);font-size:.72rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.kickoff-strategy-line{margin:0;color:#edf5fa;font-size:.78rem;line-height:1.35;overflow-wrap:anywhere}.kickoff-support-list{display:grid;gap:.22rem;margin:0;padding:0;list-style:none}.kickoff-support-list li{color:#afc4d4;font-size:.74rem;line-height:1.3;overflow-wrap:anywhere}@media(min-width:46rem){.kickoff-overview-summary{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:720px){.kickoff-overview-summary,.kickoff-detail-grid,.kickoff-strategy-list,.kickoff-overview-hero{grid-template-columns:1fr}.kickoff-overview-victor{justify-self:start}}.panel{padding:var(--ui-panel-padding);display:grid;gap:var(--ui-gap-md)}.panel>label,.panel>.detail-grid,.panel>.transport-row,.panel>.module-list{margin-top:0}.panel-copy{margin:0;font-size:.92rem;line-height:1.45}.transport-row{display:flex;gap:var(--ui-gap-sm)}.transport-row>*{flex:1 1 auto}.playback-rate-control{display:grid;gap:var(--ui-gap-xs)}.playback-rate-header{align-items:center;display:flex;justify-content:space-between}.playback-rate-header strong{font-variant-numeric:tabular-nums}.playback-rate-notches{color:var(--ui-muted);display:grid;font-size:.72rem;grid-template-columns:repeat(5,minmax(0,1fr));line-height:1.1;text-align:center}.playback-rate-notches span:first-child{text-align:left}.playback-rate-notches span:last-child{text-align:right}.recording-controls{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-sm)}.camera-presets{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-xs)}.camera-presets button{font-size:var(--ui-control-font-size)}.camera-presets button[data-active=true]{border-color:#8ec5ff6b;background:linear-gradient(180deg,#21476bf5,#0c1b2afa);color:#f3f8fc;box-shadow:inset 0 0 0 1px #8ec5ff1f}.camera-ball-cam{display:grid;gap:var(--ui-gap-xs)}.camera-ball-cam-modes{grid-template-columns:repeat(3,minmax(0,1fr))}.camera-settings-controls{display:grid;gap:var(--ui-gap-sm)}.camera-settings-controls[hidden]{display:none}.camera-setting-label{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-md);font-size:.8rem;color:#9fb3c4}.camera-setting-label strong{color:#e8f0f7;font-variant-numeric:tabular-nums}button,select,input[type=file],input[type=range]{border-radius:var(--ui-radius-md)}button,select,input[type=file]{min-height:var(--ui-control-height);border:1px solid var(--ui-border-subtle);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);background:var(--surface-strong);color:var(--text);font-size:var(--ui-control-font-size);line-height:var(--ui-control-line-height)}button{cursor:pointer}select{appearance:none;padding-right:1.35rem;background-image:linear-gradient(45deg,transparent 50%,var(--muted) 50%),linear-gradient(135deg,var(--muted) 50%,transparent 50%);background-position:calc(100% - .76rem) 50%,calc(100% - .52rem) 50%;background-repeat:no-repeat;background-size:.24rem .24rem}button:hover:not(:disabled),select:hover:not(:disabled){border-color:var(--ui-border-hover)}button:disabled,select:disabled,input:disabled{opacity:.55;cursor:not-allowed}input[type=range]{width:100%;margin-top:var(--ui-gap-xs);accent-color:var(--blue)}.metric-readout{font-size:.88rem;font-weight:700;font-variant-numeric:tabular-nums}.toggle{display:inline-flex;align-items:center;gap:.4rem;color:#bfd0dd}.detail-grid{margin:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.55rem .7rem}.detail-grid dt,.detail-grid dd{margin:0}.detail-grid dt{font-size:.68rem;margin-bottom:.12rem}.detail-grid dd{font-size:.84rem;color:var(--text);overflow-wrap:anywhere}.module-groups{display:grid;gap:var(--ui-gap-md)}.module-summary-group{display:grid;gap:var(--ui-gap-xs)}.module-summary-group h3{margin:0;color:#87afd4;font-size:.64rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase}.module-list{display:flex;flex-wrap:wrap;gap:.5rem}.mechanics-actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem;margin-bottom:.65rem}.mechanics-event-list{display:grid;grid-template-columns:repeat(var(--event-source-columns, 1),minmax(9.5rem,1fr));align-items:stretch}.module-settings{display:grid;gap:.75rem}.module-settings-card{display:grid;gap:.75rem;padding:.85rem .9rem;border-radius:1rem;border:1px solid rgba(255,255,255,.08);background:#ffffff09}.module-settings-subgroup{display:grid;gap:.65rem;padding-top:.15rem;border-top:1px solid rgba(255,255,255,.06)}.module-settings-options{display:grid;gap:.45rem}.module-settings-group-title{margin:0;color:#d7e5ef;font-size:.78rem;font-weight:800}.module-settings-header{display:flex;align-items:start;justify-content:space-between;gap:.8rem}.module-settings-header h3{margin:.1rem 0 0;font-size:.96rem}.module-settings-eyebrow{margin:0;font-size:.66rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase;color:#87afd4}.boost-pickup-filter-panel{display:grid;gap:.65rem}.boost-pickup-filter-summary{display:flex;justify-content:end}.boost-pickup-filter-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.75rem 1rem}.boost-pickup-filter-group{display:grid;align-content:start;gap:.35rem;min-width:0}.boost-pickup-filter-group[hidden]{display:none}.boost-pickup-filter-group-wide{grid-column:1 / -1}.boost-pickup-filter-options{display:flex;flex-wrap:wrap;gap:.35rem .8rem;min-width:0}.boost-pickup-filter-options .toggle{min-width:0}.module-summary-item{appearance:none;display:inline-flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm);min-height:var(--ui-control-height);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border-radius:var(--ui-radius-pill);border:1px solid var(--ui-border-subtle);background:#ffffff08;color:var(--muted);font:inherit;font-size:var(--ui-control-font-size);line-height:var(--ui-control-line-height);cursor:pointer;transition:border-color .14s ease,background-color .14s ease,color .14s ease}.module-summary-item:hover{border-color:var(--ui-border-hover);color:var(--text)}.module-summary-item strong{font-size:.62rem;letter-spacing:.08em;text-transform:uppercase}.module-summary-item[data-active=true]{border-color:#4b94ff38;background:#4b94ff14;color:#dceafb}@media(max-width:1180px){.sidebar{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:860px){.shell{padding:0}.sidebar{grid-template-columns:1fr}.panel-heading{display:grid}.detail-grid{grid-template-columns:1fr 1fr}.viewport-panel{min-height:100dvh}}@media(max-width:560px){.detail-grid{grid-template-columns:1fr}.transport-row{flex-direction:column}.floating-window,.stats-window{left:.55rem;right:.55rem;width:auto}}@media(max-width:720px){.viewport-panel:has(.floating-window:not([hidden])) .viewport{inset:0 0 52dvh}.floating-window{position:fixed;inset:auto 0 0;width:100%;max-width:none;height:52dvh;max-height:52dvh;overflow:auto;border-width:1px 0 0 0;border-radius:1rem 1rem 0 0;transform:none;z-index:30}.floating-window .floating-window-header{cursor:default}}.missed-event-body{display:flex;flex-direction:column;gap:.5rem;padding:.6rem .7rem;max-height:50vh;font-size:.8rem}.missed-event-controls{display:flex;align-items:center;gap:.4rem}.missed-event-controls select{flex:1 1 auto}.missed-event-list{list-style:none;margin:0;padding:0;overflow-y:auto;display:flex;flex-direction:column;gap:.25rem}.missed-event-list li{display:flex;align-items:center;justify-content:space-between;gap:.4rem;padding:.2rem .3rem;border-radius:.3rem;background:#1c272ee6}.missed-event-status{margin:0;min-height:1rem;color:#9fadb7}.training-pack-shots{list-style:none;margin:.4rem 0 0;padding:0;overflow-y:auto;max-height:12rem;display:flex;flex-direction:column;gap:.25rem;font-size:.8rem}.training-pack-shots li{display:flex;align-items:center;justify-content:space-between;gap:.4rem;padding:.2rem .3rem;border-radius:.3rem;background:#1c272ee6}.training-pack-status{margin:.4rem 0 0;min-height:1rem;font-size:.8rem;color:#9fadb7} diff --git a/crates/rocket-sense-server/static/subtr-actor/assets/main-DHjpjWsc.js b/crates/rocket-sense-server/static/subtr-actor/review/assets/main-DhIgxjyS.js similarity index 68% rename from crates/rocket-sense-server/static/subtr-actor/assets/main-DHjpjWsc.js rename to crates/rocket-sense-server/static/subtr-actor/review/assets/main-DhIgxjyS.js index 6d6e503a..e501fc2a 100644 --- a/crates/rocket-sense-server/static/subtr-actor/assets/main-DHjpjWsc.js +++ b/crates/rocket-sense-server/static/subtr-actor/review/assets/main-DhIgxjyS.js @@ -1,8 +1,8 @@ -function fh(n,e){if(n.frames.length===0)return 0;let t=0,i=n.frames.length-1;for(;t<=i;){const s=Math.floor((t+i)/2),a=n.frames[s]?.time??0;if(ae)i=s-1;else return s}return Math.max(0,t-1)}class vw{_listeners=new Map;on(e,t){let i=this._listeners.get(e);return i||(i=new Set,this._listeners.set(e,i)),i.add(t),this}once(e,t){const i=(...s)=>{this.off(e,i),t(...s)};return this.on(e,i)}off(e,t){const i=this._listeners.get(e);return i?(t?i.delete(t):i.clear(),i.size===0&&this._listeners.delete(e),this):this}removeListener(e,t){return this.off(e,t)}removeAllListeners(e){return e?this._listeners.delete(e):this._listeners.clear(),this}emit(e,...t){const i=this._listeners.get(e);if(!i||i.size===0)return!1;for(const s of[...i])s(...t);return!0}}function ff(n){return n?{x:n.x,y:n.z,z:n.y}:null}function E1(n){return n?{x:n.x,y:n.z,z:n.y,w:-n.w}:null}function C1(n){return n*100/255}const oy={Octane:{length:118.0074,width:84.19941,height:36.15907,offsetX:13.87566,offsetZ:20.75499},Dominus:{length:127.9268,width:83.27995,height:31.3,offsetX:9,offsetZ:15.75},Plank:{length:128.8198,width:84.67036,height:29.3944,offsetX:9.00857,offsetZ:12.0942},Breakout:{length:131.4924,width:80.521,height:30.3,offsetX:12.5,offsetZ:11.75},Hybrid:{length:127.0192,width:82.18787,height:34.15907,offsetX:13.87566,offsetZ:20.75499},Merc:{length:120.72,width:76.71,height:41.66,offsetX:11.37566,offsetZ:21.504988}},A1={21:{name:"Backfire",hitbox:"Octane"},22:{name:"Breakout",hitbox:"Breakout"},23:{name:"Octane",hitbox:"Octane"},24:{name:"Paladin",hitbox:"Plank"},25:{name:"Road Hog",hitbox:"Octane"},26:{name:"Gizmo",hitbox:"Octane"},28:{name:"X-Devil",hitbox:"Hybrid"},29:{name:"Hotshot",hitbox:"Dominus"},30:{name:"Merc",hitbox:"Merc"},31:{name:"Venom",hitbox:"Hybrid"},402:{name:"Takumi",hitbox:"Octane"},403:{name:"Dominus",hitbox:"Dominus"},404:{name:"Scarab",hitbox:"Octane"},523:{name:"Zippy",hitbox:"Octane"},597:{name:"DeLorean Time Machine",hitbox:"Dominus"},600:{name:"Ripper",hitbox:"Dominus"},607:{name:"Grog",hitbox:"Octane"},1018:{name:"Dominus GT",hitbox:"Dominus"},1159:{name:"X-Devil Mk2",hitbox:"Hybrid"},1171:{name:"Masamune",hitbox:"Dominus"},1172:{name:"Marauder",hitbox:"Octane"},1286:{name:"Aftershock",hitbox:"Dominus"},1295:{name:"Takumi RX-T",hitbox:"Octane"},1300:{name:"Road Hog XL",hitbox:"Octane"},1317:{name:"Esper",hitbox:"Hybrid"},1416:{name:"Breakout Type-S",hitbox:"Breakout"},1475:{name:"Proteus",hitbox:"Octane"},1478:{name:"Triton",hitbox:"Octane"},1533:{name:"Vulcan",hitbox:"Octane"},1568:{name:"Octane ZSR",hitbox:"Octane"},1603:{name:"Twin Mill III",hitbox:"Plank"},1623:{name:"Bone Shaker",hitbox:"Octane"},1624:{name:"Endo",hitbox:"Hybrid"},1675:{name:"Ice Charger",hitbox:"Dominus"},1689:{name:"Nemesis",hitbox:"Dominus"},1691:{name:"Mantis",hitbox:"Plank"},1856:{name:"Jager 619",hitbox:"Hybrid"},1883:{name:"Imperator DT5",hitbox:"Dominus"},1894:{name:"Samurai",hitbox:"Breakout"},1919:{name:"Centio",hitbox:"Plank"},1932:{name:"Animus GP",hitbox:"Breakout"},2070:{name:"Werewolf",hitbox:"Dominus"},2268:{name:"Fast & Furious Dodge Charger",hitbox:"Dominus"},2269:{name:"Fast & Furious Nissan Skyline",hitbox:"Hybrid"},2665:{name:"The Dark Knight's Tumbler",hitbox:"Octane"},2666:{name:"Batmobile (1989)",hitbox:"Dominus"},2853:{name:"Twinzer",hitbox:"Octane"},2919:{name:"Jurassic Jeep Wrangler",hitbox:"Octane"},2949:{name:"Fast 4WD",hitbox:"Octane"},2950:{name:"MR11",hitbox:"Dominus"},2951:{name:"Gazella GT",hitbox:"Dominus"},3031:{name:"Cyclone",hitbox:"Breakout"},3155:{name:"Maverick",hitbox:"Dominus"},3156:{name:"Maverick G1",hitbox:"Dominus"},3157:{name:"Maverick GXT",hitbox:"Dominus"},3265:{name:"McLaren 570S",hitbox:"Dominus"},3311:{name:"Komodo",hitbox:"Breakout"},3426:{name:"Diestro",hitbox:"Dominus"},3451:{name:"Nimbus",hitbox:"Hybrid"},3582:{name:"Insidio",hitbox:"Hybrid"},3594:{name:"Artemis G1",hitbox:"Plank"},3614:{name:"Artemis",hitbox:"Plank"},3622:{name:"Artemis GXT",hitbox:"Plank"},3702:{name:"Tygris",hitbox:"Hybrid"},3875:{name:"Guardian GXT",hitbox:"Dominus"},3879:{name:"Guardian",hitbox:"Dominus"},3880:{name:"Guardian G1",hitbox:"Dominus"},4014:{name:"K.I.T.T.",hitbox:"Dominus"},4155:{name:"Ecto-1",hitbox:"Dominus"},4268:{name:"Sentinel",hitbox:"Plank"},4284:{name:"Fennec",hitbox:"Octane"},4318:{name:"Mudcat",hitbox:"Octane"},4319:{name:"Mudcat G1",hitbox:"Octane"},4320:{name:"Mudcat GXT",hitbox:"Octane"},4367:{name:"Chikara GXT",hitbox:"Dominus"},4472:{name:"Chikara",hitbox:"Dominus"},4473:{name:"Chikara G1",hitbox:"Dominus"},4745:{name:"Ronin GXT",hitbox:"Dominus"},4770:{name:"Dominus",hitbox:"Dominus"},4780:{name:"Battle Bus",hitbox:"Merc"},4781:{name:"Peregrine TT",hitbox:"Dominus"},4782:{name:"Psyclops",hitbox:"Body_Tritip_Handling"},4861:{name:"Ronin",hitbox:"Dominus"},4864:{name:"Ronin G1",hitbox:"Dominus"},4906:{name:"Harbinger",hitbox:"Octane"},5020:{name:"Outlaw",hitbox:"Octane"},5039:{name:"Harbinger GXT",hitbox:"Octane"},5188:{name:"Scarab",hitbox:"Octane"},5265:{name:"Formula 1 2021",hitbox:"Plank"},5361:{name:"Dingo",hitbox:"Octane"},5470:{name:"R3MX",hitbox:"Hybrid"},5488:{name:"R3MX GXT",hitbox:"Hybrid"},5547:{name:"007's Aston Martin DB5",hitbox:"Octane"},5709:{name:"NASCAR Ford Mustang",hitbox:"Dominus"},5713:{name:"Ford F-150 RLE",hitbox:"Octane"},5773:{name:"NASCAR Toyota Camry",hitbox:"Dominus"},5823:{name:"NASCAR Chevrolet Camaro",hitbox:"Dominus"},5837:{name:"Outlaw GXT",hitbox:"Octane"},5858:{name:"Tyranno",hitbox:"Dominus"},5879:{name:"Fast & Furious Pontiac Fiero",hitbox:"Hybrid"},5951:{name:"Jackal",hitbox:"Octane"},5964:{name:"Lamborghini Huracan STO",hitbox:"Dominus"},5979:{name:"Tyranno GXT",hitbox:"Dominus"},6122:{name:"Masamune",hitbox:"Dominus"},6243:{name:"Nexus",hitbox:"Breakout"},6244:{name:"BMW M240i",hitbox:"Dominus"},6247:{name:"McLaren 765LT",hitbox:"Dominus"},6260:{name:"007's Aston Martin Valhalla",hitbox:"Dominus"},6489:{name:"Nexus SC",hitbox:"Breakout"},6836:{name:"Ford Mustang Shelby GT350R RLE",hitbox:"Dominus"},6939:{name:"Ford Mustang Mach-E RLE",hitbox:"Octane"},7012:{name:"Tesla Cybertruck",hitbox:"Hybrid"},7052:{name:"Formula 1 2022",hitbox:"Plank"},7211:{name:"Mamba",hitbox:"Dominus"},7336:{name:"Nomad",hitbox:"Merc"},7337:{name:"NASCAR Next Gen Chevrolet Camaro",hitbox:"Dominus"},7338:{name:"NASCAR Next Gen Ford Mustang",hitbox:"Dominus"},7341:{name:"NASCAR Next Gen Toyota Camry",hitbox:"Dominus"},7343:{name:"007's Aston Martin DBS",hitbox:"Dominus"},7415:{name:"Batmobile (2022)",hitbox:"Dominus"},7477:{name:"Nomad GXT",hitbox:"Merc"},7512:{name:"Lamborghini Countach LPI 800-4",hitbox:"Dominus"},7532:{name:"Maestro",hitbox:"Dominus"},7593:{name:"Nissan Z Performance",hitbox:"Dominus"},7651:{name:"Redline",hitbox:"Breakout"},7696:{name:"Whiplash",hitbox:"Breakout"},7772:{name:"Ferrari 296 GTB",hitbox:"Dominus"},7815:{name:"Ford Bronco Raptor RLE",hitbox:"Merc"},7890:{name:"Fuse",hitbox:"Breakout"},7901:{name:"Fast & Furious Mazda RX-7",hitbox:"Breakout"},7947:{name:"Honda Civic Type R",hitbox:"Octane"},7948:{name:"Honda Civic Type R-LE",hitbox:"Octane"},7979:{name:"Stampede",hitbox:"Merc"},8006:{name:"Mako",hitbox:"Breakout"},8360:{name:"Emperor",hitbox:"Breakout"},8361:{name:"Emperor II",hitbox:"Breakout"},8383:{name:"Xentari",hitbox:"Octane"},8454:{name:"Admiral",hitbox:"Dominus"},8524:{name:"Bugatti Centodieci",hitbox:"Plank"},8565:{name:"Emperor II: Frozen",hitbox:"Breakout"},8566:{name:"Emperor II: Scorched",hitbox:"Breakout"},8669:{name:"Ace",hitbox:"Breakout"},8806:{name:"Volkswagen Golf GTI",hitbox:"Octane"},8807:{name:"Volkswagen Golf GTI RLE",hitbox:"Octane"},9053:{name:"Fast & Furious Dodge Charger SRT Hellcat",hitbox:"Dominus"},9084:{name:"Nissan Silvia",hitbox:"Hybrid"},9085:{name:"Nissan Silvia RLE",hitbox:"Hybrid"},9088:{name:"Porsche 911 Turbo",hitbox:"Dominus"},9089:{name:"Porsche 911 Turbo RLE",hitbox:"Dominus"},9140:{name:"Bumblebee",hitbox:"Dominus"},9357:{name:"Diesel",hitbox:"Breakout"},9388:{name:"Lightning McQueen",hitbox:"Dominus"},9427:{name:"Primo",hitbox:"Hybrid"},9894:{name:"Scorpion",hitbox:"Dominus"},10044:{name:"Beskar",hitbox:"Hybrid"},10094:{name:"Ford Mustang GTD",hitbox:"Dominus"},10440:{name:"Nissan Fairlady Z",hitbox:"Dominus"},10441:{name:"Nissan Fairlady Z RLE",hitbox:"Dominus"},10689:{name:"Behemoth",hitbox:"Merc"},10694:{name:"Lockjaw",hitbox:"Dominus"},10697:{name:"The Incredibile",hitbox:"Breakout"},10698:{name:"1966 Cadillac DeVille",hitbox:"Breakout"},10805:{name:"Nissan Skyline GT-R (R32)",hitbox:"Hybrid"},10817:{name:"Quadra Turbo-R",hitbox:"Breakout"},10822:{name:"McLaren Senna",hitbox:"Breakout"},10896:{name:"BMW 1 Series",hitbox:"Octane"},10897:{name:"BMW 1 Series RLE",hitbox:"Octane"},10900:{name:"Shokunin",hitbox:"Octane"},10901:{name:"Shokunin GXT",hitbox:"Octane"},11016:{name:"Porsche 911 GT3 RS",hitbox:"Dominus"},11038:{name:"Revolver",hitbox:"Breakout"},11095:{name:"Dodge Charger Daytona Scat Pack",hitbox:"Dominus"},11098:{name:"Turtle Van",hitbox:"Merc"},11138:{name:"Void Burn",hitbox:"Hybrid"},11141:{name:"Lamborghini Urus SE",hitbox:"Hybrid"},11314:{name:"Jeep Wrangler Rubicon",hitbox:"Merc"},11315:{name:"Ford Mustang Shelby GT500",hitbox:"Dominus"},11336:{name:"Dominus: Neon",hitbox:"Dominus"},11379:{name:"Ram 1500 RHO",hitbox:"Hybrid"},11394:{name:"Azura",hitbox:"Breakout"},11505:{name:"Breakout X",hitbox:"Breakout"},11534:{name:"BMW M3 (E30)",hitbox:"Dominus"},11603:{name:"Fennec ZR-F",hitbox:"Octane"},11677:{name:"Chevrolet Corvette ZR1",hitbox:"Breakout"},11736:{name:"Recoil AV",hitbox:"Merc"},11800:{name:"Megastar",hitbox:"Breakout"},11905:{name:"The Mystery Machine",hitbox:"Merc"},11932:{name:"Hearse",hitbox:"Hybrid"},11933:{name:"Porsche 918 Spyder",hitbox:"Breakout"},11941:{name:"Mercedes-AMG GT 63 S",hitbox:"Dominus"},11949:{name:"Pontiac Firebird",hitbox:"Breakout"},11950:{name:"Chevrolet Astro",hitbox:"Merc"},12142:{name:"Homer's Car",hitbox:"Dominus"},12173:{name:"Ferrari F40",hitbox:"Breakout"}},R1=A1;function bw(n){const e=R1[String(n)];return e?{name:e.name,hitboxType:e.hitbox}:null}function P1(n){if(!n)return null;const e={fov:n.fov,height:n.height,angle:n.angle,distance:n.distance,stiffness:n.stiffness,swivelSpeed:n.swivel_speed};return n.transition_speed!=null&&(e.transitionSpeed=n.transition_speed),e}const I1=2200,L1=!0,D1=!1,k1=.15,O1=10,F1=.1,N1=10,U1=.1,B1=.15,z1=10;function Uo(n,e){if(n.length===0)return null;let t=0,i=n.length-1;if(e<=n[0].time)return n[0];if(e>=n[i].time)return n[i];for(;t>1;n[s].time<=e?t=s:i=s-1}return n[t]}class H1{position={x:0,y:0,z:0};rotation={x:0,y:0,z:0,w:1};velocity={x:0,y:0,z:0};angularVelocity={x:0,y:0,z:0};sleeping=!1;visible=!0}class V1{constructor(e,t,i){this.isBig=e,this.position=t,this.events=i}isAvailable=!0}class G1 extends vw{constructor(e,t,i,s,a,r=null){super(),this.id=e,this.name=t,this.team=i,this.carName=s,this.hitboxType=a,this.cameraSettings=r}position={x:0,y:0,z:0};rotation={x:0,y:0,z:0,w:1};velocity={x:0,y:0,z:0};angularVelocity={x:0,y:0,z:0};sleeping=!1;steer=0;boost=0;isBoosting=!1;isSupersonic=!1;isKickoffReset=!1;isVisible=!0;isBallCam=!0}class xw extends vw{constructor(e,t={}){super(),this.raw=e,this.options=t,this._compile()}duration=0;playerList=[];frameTimes=[];rawStartTime=0;ball=new H1;players=new Map;boostPads=new Map;_currentTime=0;_ballTimeline=[];_playerTimelines={};_ballFlags=[];_playerFlags={};_playerCameraEvents={};_teams={};_timelineCompaction=null;_compile(){const e=this.raw.frame_data,t=this.raw.meta,i=e.metadata_frames,s=i[0]?.time??0;this.rawStartTime=s;const a=l=>Math.max(0,l-s);this.duration=i.length?a(i[i.length-1].time):0,this.frameTimes=i.map(l=>a(l.time));const r=new Map;t.team_zero.forEach(l=>r.set(this._idKey(l.remote_id),{info:l,team:0})),t.team_one.forEach(l=>r.set(this._idKey(l.remote_id),{info:l,team:1})),e.ball_data.frames.forEach((l,c)=>{if(l==="Empty"||!("Data"in l))return;const u=this._rbToKeyframe(l.Data.rigid_body,a(i[c]?.time??s),c);u&&this._ballTimeline.push(u)}),e.players.forEach(([l,c])=>{const u=this._idKey(l),d=r.get(u);let h=d?.info.name??null,f=d?.team??0;if(!h){for(const T of c.frames)if(T!=="Empty"&&"Data"in T&&T.Data.player_name){h=T.Data.player_name,T.Data.is_team_0!=null&&(f=T.Data.is_team_0?0:1);break}}h||(h=`Player_${u}`);const p=d?.info,g=p?.car_body_id!=null?bw(p.car_body_id):null,_=p?.car_body_name??g?.name??"Octane",m=p?.car_hitbox_family??g?.hitboxType??"Octane",v=[],y=[];c.frames.forEach((T,x)=>{const M=a(i[x]?.time??s);if(T==="Empty"||!("Data"in T))return;const C=this._rbToKeyframe(T.Data.rigid_body,M,x);C&&v.push(C);const w=T.Data.input?.steer;y.push({time:M,boost:C1(T.Data.boost_amount??0),isBoosting:!!T.Data.boost_active,present:!0,steer:w==null?0:Math.max(-1,Math.min(1,(w-128)/128))})});const b=P1(p?.camera_settings);this._playerTimelines[h]=v,this._playerFlags[h]=y,this._teams[h]=f,this.playerList.push({id:u,name:h,team:f,carName:_,hitboxType:m,cameraSettings:b}),this.players.set(h,new G1(u,h,f,_,m,b))});const o=new Map;this.playerList.forEach(l=>o.set(l.id,l.name));for(const[l,c]of this.raw.player_camera_events??[]){const u=o.get(this._idKey(l));u&&(this._playerCameraEvents[u]=c.map(d=>({time:a(i[d.frame]?.time??s),ballCam:d.ball_cam_active})))}this._preprocessMotionTimelines(),this._compileBoostPads(),this.seek(0)}_timelineProcessingOptions(){return{motionSmoothing:this.options.motionSmoothing??L1,smoothingBlendFactor:this.options.smoothingBlendFactor??k1,smoothingAnchorInterval:this.options.smoothingAnchorInterval??O1,timelineCompaction:this.options.timelineCompaction??D1,disableFrameFiltering:this.options.disableFrameFiltering??!1}}_preprocessMotionTimelines(){const e=this._timelineProcessingOptions();e.motionSmoothing&&this._applyVelocityBasedPositionCorrection(e),e.timelineCompaction&&this._applyTimelineCompaction(),e.disableFrameFiltering||this._filterInconsistentFrames()}_applyTimelineCompaction(){const e=this._buildTimelineCompaction();!e||e.gaps.length===0&&e.prematchEndTime===null||(this._timelineCompaction=e,this._ballTimeline=this._compactTimeline(this._ballTimeline,e),Object.entries(this._playerTimelines).forEach(([t,i])=>{this._playerTimelines[t]=this._compactTimeline(i,e)}),Object.entries(this._playerFlags).forEach(([t,i])=>{this._playerFlags[t]=this._compactTimeline(i,e)}),this.frameTimes=this.frameTimes.map(t=>this._compactTime(t,e)),this.duration=e.compactedDuration)}_buildTimelineCompaction(){if(this.frameTimes.length===0)return null;const e=this._detectPostGoalTimeGaps(),t=this._detectFirstKickoffGoTime(),i=t==null?null:Bo(t,e),a=e.reduce((r,o)=>r+o.duration,0)+(i??0);return a<=0?null:{gaps:e,prematchEndTime:i,removedDuration:a,compactedDuration:Math.max(0,this.duration-a)}}_detectPostGoalTimeGaps(){const e=[];for(const t of this.raw.goal_events??[]){const i=t.frame;if(!Number.isInteger(i)||i<0||i>=this.frameTimes.length)continue;const s=this.frameTimes[i];for(let a=i+1;a10)break;const l=o-r;if(l>.3){e.push({beforeFrame:a-1,afterFrame:a,beforeTime:r,afterTime:o,duration:l});break}}}return e}_detectFirstKickoffGoTime(){const e=this.raw.frame_data.metadata_frames;let t=!1;for(let s=0;s0&&(t=!0),t&&a===0)return this.frameTimes[s]??null}const i=e.findIndex(s=>s.replicated_game_state_name===54);return i===-1?null:this.frameTimes[i]??null}_compactTimeline(e,t){const i=this._remapReplayGaps(e,t.gaps);return t.prematchEndTime===null?i:this._remapPrematch(i,t.prematchEndTime)}_remapReplayGaps(e,t){if(t.length===0)return e;const i=[];t.forEach((a,r)=>{const o=e.find(l=>l.time>=a.afterTime);o&&i.push({...o,time:Bo(a.afterTime,t.slice(0,r+1))})});const s=e.filter(a=>!uy(a.time,t)).map(a=>({...a,time:Bo(a.time,t)}));for(const a of i){if(s.some(o=>Math.abs(o.time-a.time)<.001))continue;let r=s.findIndex(o=>o.time>a.time);r===-1&&(r=s.length),s.splice(r,0,a)}return s}_remapPrematch(e,t){let i=null;for(const a of e)if(a.timea.time>=t).map(a=>({...a,time:a.time-t}));return i&&(s.length===0||s[0].time>.001)&&s.unshift({...i,time:0}),s}_compactTime(e,t){const i=Bo(e,t.gaps);return t.prematchEndTime===null?i:Math.max(0,i-t.prematchEndTime)}_applyVelocityBasedPositionCorrection(e){const t=i=>{if(i.length<3)return;let s=0;for(;s=i.length-1)return;let a={...i[s].position};for(let r=s+1;rF1){a={...l.position};continue}if(cy(a,l.position)>N1){a={...l.position};continue}const u={x:(o.velocity.x+l.velocity.x)/2,y:(o.velocity.y+l.velocity.y)/2,z:(o.velocity.z+l.velocity.z)/2},d={x:a.x+u.x*c,y:a.y+u.y*c,z:a.z+u.z*c},h=(r-s)%e.smoothingAnchorInterval===0?.5:e.smoothingBlendFactor;a={x:d.x*(1-h)+l.position.x*h,y:d.y*(1-h)+l.position.y*h,z:d.z*(1-h)+l.position.z*h},l.position={...a}}};t(this._ballTimeline),Object.values(this._playerTimelines).forEach(t)}_filterInconsistentFrames(){this._ballTimeline=this._filterInconsistentTimeline(this._ballTimeline),Object.entries(this._playerTimelines).forEach(([e,t])=>{this._playerTimelines[e]=this._filterInconsistentTimeline(t)})}_filterInconsistentTimeline(e){if(e.length<2)return e;const t=[e[0]];let i=0;for(let s=1;s.001){const u=o*c,d=cy(r.position,a.position),h=Math.abs(d-u)/u;if(Number.isFinite(h)&&h>B1)continue}}t.push(a),i=s}return t}_compileBoostPads(){const e=new Map;(this.raw.boost_pad_events??[]).forEach(t=>{const i=t.kind==="Available"?!0:t.kind&&typeof t.kind=="object"&&"PickedUp"in t.kind?!1:null;if(i===null)return;const s=Math.max(0,t.time-this.rawStartTime);if(this._timelineCompaction&&this._isRemovedByTimelineCompaction(s))return;const a=this._timelineCompaction?this._compactTime(s,this._timelineCompaction):s,r=e.get(t.pad_id);r?r.push({time:a,available:i}):e.set(t.pad_id,[{time:a,available:i}])}),(this.raw.boost_pads??[]).forEach(t=>{const i=(t.pad_id?e.get(t.pad_id):void 0)??[];i.sort((s,a)=>s.time-a.time),this.boostPads.set(t.index,new V1(t.size==="Big",t.position,i))})}_rbToKeyframe(e,t,i){const s=ff(e.location);return s?{time:t,frame:i,position:s,rotation:E1(e.rotation),velocity:ff(e.linear_velocity)??{x:0,y:0,z:0},angularVelocity:ff(e.angular_velocity),sleeping:!!e.sleeping}:null}_isRemovedByTimelineCompaction(e){const t=this._timelineCompaction;if(!t)return!1;if(uy(e,t.gaps))return!0;const i=Bo(e,t.gaps);return t.prematchEndTime!==null&&i=I1}const r=Uo(this._playerFlags[i]??[],e);r&&(s.boost=r.boost,s.isBoosting=r.isBoosting,s.steer=r.steer);const o=Uo(this._playerCameraEvents[i]??[],e);o&&o.ballCam!=null&&(s.isBallCam=o.ballCam);const l=this._playerTimelines[i]??[];s.isVisible=l.length>0&&e>=l[0].time-.001&&e<=l[l.length-1].time+1}for(const i of this.boostPads.values()){if(i.events.length===0)continue;const s=Uo(i.events,e);i.isAvailable=s&&s.time<=e?s.available:!0}}frameIndexAt(e){const t=this.frameTimes;if(t.length===0||e<=t[0])return 0;let i=0,s=t.length-1;if(e>=t[s])return s;for(;i>1;t[a]<=e?i=a:s=a-1}return i}getBall(){return this.ball}getPlayer(e){return this.players.get(e)}getPlayerById(e){for(const t of this.players.values())if(t.id===e)return t}getAllPlayers(){return Array.from(this.players.values())}getPlayerTeams(){return{...this._teams}}getGameTimeMap(){return[]}getCountdownEvents(){return[]}getPlayerStatsTimelines(){return{}}getGameEventTimeline(){return[]}getAdvancedStats(){return null}getEvents(){return[]}getEventsInRange(){return[]}getTextOverlaysAt(){return[]}getGamePhaseAt(){return null}}function ly(n){return Math.sqrt(n.x*n.x+n.y*n.y+n.z*n.z)}function cy(n,e){const t=e.x-n.x,i=e.y-n.y,s=e.z-n.z;return Math.sqrt(t*t+i*i+s*s)}function Bo(n,e){let t=0;for(const i of e){if(n=i.afterTime){t+=i.duration;continue}return i.beforeTime-t}return n-t}function uy(n,e){return e.some(t=>n>t.beforeTime&&n>8&255]+Mn[n>>16&255]+Mn[n>>24&255]+"-"+Mn[e&255]+Mn[e>>8&255]+"-"+Mn[e>>16&15|64]+Mn[e>>24&255]+"-"+Mn[t&63|128]+Mn[t>>8&255]+"-"+Mn[t>>16&255]+Mn[t>>24&255]+Mn[i&255]+Mn[i>>8&255]+Mn[i>>16&255]+Mn[i>>24&255]).toLowerCase()}function Ze(n,e,t){return Math.max(e,Math.min(t,n))}function Z_(n,e){return(n%e+e)%e}function MC(n,e,t,i,s){return i+(n-e)*(s-i)/(t-e)}function EC(n,e,t){return n!==e?(t-n)/(e-n):0}function Al(n,e,t){return(1-t)*n+t*e}function CC(n,e,t,i){return Al(n,e,1-Math.exp(-t*i))}function AC(n,e=1){return e-Math.abs(Z_(n,e*2)-e)}function RC(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*(3-2*n))}function PC(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*n*(n*(n*6-15)+10))}function IC(n,e){return n+Math.floor(Math.random()*(e-n+1))}function LC(n,e){return n+Math.random()*(e-n)}function DC(n){return n*(.5-Math.random())}function kC(n){n!==void 0&&(dy=n);let e=dy+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function OC(n){return n*nr}function FC(n){return n*To}function NC(n){return(n&n-1)===0&&n!==0}function UC(n){return Math.pow(2,Math.ceil(Math.log(n)/Math.LN2))}function BC(n){return Math.pow(2,Math.floor(Math.log(n)/Math.LN2))}function zC(n,e,t,i,s){const a=Math.cos,r=Math.sin,o=a(t/2),l=r(t/2),c=a((e+i)/2),u=r((e+i)/2),d=a((e-i)/2),h=r((e-i)/2),f=a((i-e)/2),p=r((i-e)/2);switch(s){case"XYX":n.set(o*u,l*d,l*h,o*c);break;case"YZY":n.set(l*h,o*u,l*d,o*c);break;case"ZXZ":n.set(l*d,l*h,o*u,o*c);break;case"XZX":n.set(o*u,l*p,l*f,o*c);break;case"YXY":n.set(l*f,o*u,l*p,o*c);break;case"ZYZ":n.set(l*p,l*f,o*u,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+s)}}function zn(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return n/4294967295;case Uint16Array:return n/65535;case Uint8Array:return n/255;case Int32Array:return Math.max(n/2147483647,-1);case Int16Array:return Math.max(n/32767,-1);case Int8Array:return Math.max(n/127,-1);default:throw new Error("Invalid component type.")}}function ut(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return Math.round(n*4294967295);case Uint16Array:return Math.round(n*65535);case Uint8Array:return Math.round(n*255);case Int32Array:return Math.round(n*2147483647);case Int16Array:return Math.round(n*32767);case Int8Array:return Math.round(n*127);default:throw new Error("Invalid component type.")}}const vt={DEG2RAD:nr,RAD2DEG:To,generateUUID:pi,clamp:Ze,euclideanModulo:Z_,mapLinear:MC,inverseLerp:EC,lerp:Al,damp:CC,pingpong:AC,smoothstep:RC,smootherstep:PC,randInt:IC,randFloat:LC,randFloatSpread:DC,seededRandom:kC,degToRad:OC,radToDeg:FC,isPowerOfTwo:NC,ceilPowerOfTwo:UC,floorPowerOfTwo:BC,setQuaternionFromProperEuler:zC,normalize:ut,denormalize:zn};class te{constructor(e=0,t=0){te.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,i=this.y,s=e.elements;return this.x=s[0]*t+s[3]*i+s[6],this.y=s[1]*t+s[4]*i+s[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Ze(this.x,e.x,t.x),this.y=Ze(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Ze(this.x,e,t),this.y=Ze(this.y,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Ze(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Ze(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),s=Math.sin(t),a=this.x-e.x,r=this.y-e.y;return this.x=a*i-r*s+e.x,this.y=a*s+r*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class dt{constructor(e=0,t=0,i=0,s=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=s}static slerpFlat(e,t,i,s,a,r,o){let l=i[s+0],c=i[s+1],u=i[s+2],d=i[s+3];const h=a[r+0],f=a[r+1],p=a[r+2],g=a[r+3];if(o===0){e[t+0]=l,e[t+1]=c,e[t+2]=u,e[t+3]=d;return}if(o===1){e[t+0]=h,e[t+1]=f,e[t+2]=p,e[t+3]=g;return}if(d!==g||l!==h||c!==f||u!==p){let _=1-o;const m=l*h+c*f+u*p+d*g,v=m>=0?1:-1,y=1-m*m;if(y>Number.EPSILON){const T=Math.sqrt(y),x=Math.atan2(T,m*v);_=Math.sin(_*x)/T,o=Math.sin(o*x)/T}const b=o*v;if(l=l*_+h*b,c=c*_+f*b,u=u*_+p*b,d=d*_+g*b,_===1-o){const T=1/Math.sqrt(l*l+c*c+u*u+d*d);l*=T,c*=T,u*=T,d*=T}}e[t]=l,e[t+1]=c,e[t+2]=u,e[t+3]=d}static multiplyQuaternionsFlat(e,t,i,s,a,r){const o=i[s],l=i[s+1],c=i[s+2],u=i[s+3],d=a[r],h=a[r+1],f=a[r+2],p=a[r+3];return e[t]=o*p+u*d+l*f-c*h,e[t+1]=l*p+u*h+c*d-o*f,e[t+2]=c*p+u*f+o*h-l*d,e[t+3]=u*p-o*d-l*h-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,i,s){return this._x=e,this._y=t,this._z=i,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const i=e._x,s=e._y,a=e._z,r=e._order,o=Math.cos,l=Math.sin,c=o(i/2),u=o(s/2),d=o(a/2),h=l(i/2),f=l(s/2),p=l(a/2);switch(r){case"XYZ":this._x=h*u*d+c*f*p,this._y=c*f*d-h*u*p,this._z=c*u*p+h*f*d,this._w=c*u*d-h*f*p;break;case"YXZ":this._x=h*u*d+c*f*p,this._y=c*f*d-h*u*p,this._z=c*u*p-h*f*d,this._w=c*u*d+h*f*p;break;case"ZXY":this._x=h*u*d-c*f*p,this._y=c*f*d+h*u*p,this._z=c*u*p+h*f*d,this._w=c*u*d-h*f*p;break;case"ZYX":this._x=h*u*d-c*f*p,this._y=c*f*d+h*u*p,this._z=c*u*p-h*f*d,this._w=c*u*d+h*f*p;break;case"YZX":this._x=h*u*d+c*f*p,this._y=c*f*d+h*u*p,this._z=c*u*p-h*f*d,this._w=c*u*d-h*f*p;break;case"XZY":this._x=h*u*d-c*f*p,this._y=c*f*d-h*u*p,this._z=c*u*p+h*f*d,this._w=c*u*d+h*f*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+r)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const i=t/2,s=Math.sin(i);return this._x=e.x*s,this._y=e.y*s,this._z=e.z*s,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],s=t[4],a=t[8],r=t[1],o=t[5],l=t[9],c=t[2],u=t[6],d=t[10],h=i+o+d;if(h>0){const f=.5/Math.sqrt(h+1);this._w=.25/f,this._x=(u-l)*f,this._y=(a-c)*f,this._z=(r-s)*f}else if(i>o&&i>d){const f=2*Math.sqrt(1+i-o-d);this._w=(u-l)/f,this._x=.25*f,this._y=(s+r)/f,this._z=(a+c)/f}else if(o>d){const f=2*Math.sqrt(1+o-i-d);this._w=(a-c)/f,this._x=(s+r)/f,this._y=.25*f,this._z=(l+u)/f}else{const f=2*Math.sqrt(1+d-i-o);this._w=(r-s)/f,this._x=(a+c)/f,this._y=(l+u)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<1e-8?(i=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Ze(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(i===0)return this;const s=Math.min(1,t/i);return this.slerp(e,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const i=e._x,s=e._y,a=e._z,r=e._w,o=t._x,l=t._y,c=t._z,u=t._w;return this._x=i*u+r*o+s*c-a*l,this._y=s*u+r*l+a*o-i*c,this._z=a*u+r*c+i*l-s*o,this._w=r*u-i*o-s*l-a*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const i=this._x,s=this._y,a=this._z,r=this._w;let o=r*e._w+i*e._x+s*e._y+a*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=r,this._x=i,this._y=s,this._z=a,this;const l=1-o*o;if(l<=Number.EPSILON){const f=1-t;return this._w=f*r+t*this._w,this._x=f*i+t*this._x,this._y=f*s+t*this._y,this._z=f*a+t*this._z,this.normalize(),this}const c=Math.sqrt(l),u=Math.atan2(c,o),d=Math.sin((1-t)*u)/c,h=Math.sin(t*u)/c;return this._w=r*d+this._w*h,this._x=i*d+this._x*h,this._y=s*d+this._y*h,this._z=a*d+this._z*h,this._onChangeCallback(),this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),s=Math.sqrt(1-i),a=Math.sqrt(i);return this.set(s*Math.sin(e),s*Math.cos(e),a*Math.sin(t),a*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class S{constructor(e=0,t=0,i=0){S.prototype.isVector3=!0,this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(hy.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(hy.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,s=this.z,a=e.elements;return this.x=a[0]*t+a[3]*i+a[6]*s,this.y=a[1]*t+a[4]*i+a[7]*s,this.z=a[2]*t+a[5]*i+a[8]*s,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,s=this.z,a=e.elements,r=1/(a[3]*t+a[7]*i+a[11]*s+a[15]);return this.x=(a[0]*t+a[4]*i+a[8]*s+a[12])*r,this.y=(a[1]*t+a[5]*i+a[9]*s+a[13])*r,this.z=(a[2]*t+a[6]*i+a[10]*s+a[14])*r,this}applyQuaternion(e){const t=this.x,i=this.y,s=this.z,a=e.x,r=e.y,o=e.z,l=e.w,c=2*(r*s-o*i),u=2*(o*t-a*s),d=2*(a*i-r*t);return this.x=t+l*c+r*d-o*u,this.y=i+l*u+o*c-a*d,this.z=s+l*d+a*u-r*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,i=this.y,s=this.z,a=e.elements;return this.x=a[0]*t+a[4]*i+a[8]*s,this.y=a[1]*t+a[5]*i+a[9]*s,this.z=a[2]*t+a[6]*i+a[10]*s,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Ze(this.x,e.x,t.x),this.y=Ze(this.y,e.y,t.y),this.z=Ze(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Ze(this.x,e,t),this.y=Ze(this.y,e,t),this.z=Ze(this.z,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Ze(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const i=e.x,s=e.y,a=e.z,r=t.x,o=t.y,l=t.z;return this.x=s*l-a*o,this.y=a*r-i*l,this.z=i*o-s*r,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return pf.copy(this).projectOnVector(e),this.sub(pf)}reflect(e){return this.sub(pf.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Ze(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,s=this.z-e.z;return t*t+i*i+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){const s=Math.sin(t)*e;return this.x=s*Math.sin(i),this.y=Math.cos(t)*e,this.z=s*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),s=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=s,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(e),this.y=t,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const pf=new S,hy=new dt;class st{constructor(e,t,i,s,a,r,o,l,c){st.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,s,a,r,o,l,c)}set(e,t,i,s,a,r,o,l,c){const u=this.elements;return u[0]=e,u[1]=s,u[2]=o,u[3]=t,u[4]=a,u[5]=l,u[6]=i,u[7]=r,u[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,s=t.elements,a=this.elements,r=i[0],o=i[3],l=i[6],c=i[1],u=i[4],d=i[7],h=i[2],f=i[5],p=i[8],g=s[0],_=s[3],m=s[6],v=s[1],y=s[4],b=s[7],T=s[2],x=s[5],M=s[8];return a[0]=r*g+o*v+l*T,a[3]=r*_+o*y+l*x,a[6]=r*m+o*b+l*M,a[1]=c*g+u*v+d*T,a[4]=c*_+u*y+d*x,a[7]=c*m+u*b+d*M,a[2]=h*g+f*v+p*T,a[5]=h*_+f*y+p*x,a[8]=h*m+f*b+p*M,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[1],s=e[2],a=e[3],r=e[4],o=e[5],l=e[6],c=e[7],u=e[8];return t*r*u-t*o*c-i*a*u+i*o*l+s*a*c-s*r*l}invert(){const e=this.elements,t=e[0],i=e[1],s=e[2],a=e[3],r=e[4],o=e[5],l=e[6],c=e[7],u=e[8],d=u*r-o*c,h=o*l-u*a,f=c*a-r*l,p=t*d+i*h+s*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);const g=1/p;return e[0]=d*g,e[1]=(s*c-u*i)*g,e[2]=(o*i-s*r)*g,e[3]=h*g,e[4]=(u*t-s*l)*g,e[5]=(s*a-o*t)*g,e[6]=f*g,e[7]=(i*l-c*t)*g,e[8]=(r*t-i*a)*g,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,s,a,r,o){const l=Math.cos(a),c=Math.sin(a);return this.set(i*l,i*c,-i*(l*r+c*o)+r+e,-s*c,s*l,-s*(-c*r+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(mf.makeScale(e,t)),this}rotate(e){return this.premultiply(mf.makeRotation(-e)),this}translate(e,t){return this.premultiply(mf.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,i=e.elements;for(let s=0;s<9;s++)if(t[s]!==i[s])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const mf=new st;function cS(n){for(let e=n.length-1;e>=0;--e)if(n[e]>=65535)return!0;return!1}const HC={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function Yr(n,e){return new HC[n](e)}function Hl(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}function uS(){const n=Hl("canvas");return n.style.display="block",n}const fy={};function Vl(n){n in fy||(fy[n]=!0,console.warn(n))}function VC(n,e,t){return new Promise(function(i,s){function a(){switch(n.clientWaitSync(e,n.SYNC_FLUSH_COMMANDS_BIT,0)){case n.WAIT_FAILED:s();break;case n.TIMEOUT_EXPIRED:setTimeout(a,t);break;default:i()}}setTimeout(a,t)})}const py=new st().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),my=new st().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function GC(){const n={enabled:!0,workingColorSpace:xn,spaces:{},convert:function(s,a,r){return this.enabled===!1||a===r||!a||!r||(this.spaces[a].transfer===Pt&&(s.r=Fs(s.r),s.g=Fs(s.g),s.b=Fs(s.b)),this.spaces[a].primaries!==this.spaces[r].primaries&&(s.applyMatrix3(this.spaces[a].toXYZ),s.applyMatrix3(this.spaces[r].fromXYZ)),this.spaces[r].transfer===Pt&&(s.r=to(s.r),s.g=to(s.g),s.b=to(s.b))),s},workingToColorSpace:function(s,a){return this.convert(s,this.workingColorSpace,a)},colorSpaceToWorking:function(s,a){return this.convert(s,a,this.workingColorSpace)},getPrimaries:function(s){return this.spaces[s].primaries},getTransfer:function(s){return s===Ls?Bl:this.spaces[s].transfer},getToneMappingMode:function(s){return this.spaces[s].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(s,a=this.workingColorSpace){return s.fromArray(this.spaces[a].luminanceCoefficients)},define:function(s){Object.assign(this.spaces,s)},_getMatrix:function(s,a,r){return s.copy(this.spaces[a].toXYZ).multiply(this.spaces[r].fromXYZ)},_getDrawingBufferColorSpace:function(s){return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(s=this.workingColorSpace){return this.spaces[s].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(s,a){return Vl("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),n.workingToColorSpace(s,a)},toWorkingColorSpace:function(s,a){return Vl("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),n.colorSpaceToWorking(s,a)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],i=[.3127,.329];return n.define({[xn]:{primaries:e,whitePoint:i,transfer:Bl,toXYZ:py,fromXYZ:my,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:gt},outputColorSpaceConfig:{drawingBufferColorSpace:gt}},[gt]:{primaries:e,whitePoint:i,transfer:Pt,toXYZ:py,fromXYZ:my,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:gt}}}),n}const at=GC();function Fs(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function to(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}let yr;class dS{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{yr===void 0&&(yr=Hl("canvas")),yr.width=e.width,yr.height=e.height;const s=yr.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),i=yr}return i.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=Hl("canvas");t.width=e.width,t.height=e.height;const i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const s=i.getImageData(0,0,e.width,e.height),a=s.data;for(let r=0;r1),this.pmremVersion=0}get width(){return this.source.getSize(gf).x}get height(){return this.source.getSize(gf).y}get depth(){return this.source.getSize(gf).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const i=e[t];if(i===void 0){console.warn(`THREE.Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){console.warn(`THREE.Texture.setValues(): property '${t}' does not exist.`);continue}s&&i&&s.isVector2&&i.isVector2||s&&i&&s.isVector3&&i.isVector3||s&&i&&s.isMatrix3&&i.isMatrix3?s.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),t||(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==mh)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case ps:e.x=e.x-Math.floor(e.x);break;case Hn:e.x=e.x<0?0:1;break;case go:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case ps:e.y=e.y-Math.floor(e.y);break;case Hn:e.y=e.y<0?0:1;break;case go:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}Bt.DEFAULT_IMAGE=null;Bt.DEFAULT_MAPPING=mh;Bt.DEFAULT_ANISOTROPY=1;class qe{constructor(e=0,t=0,i=0,s=1){qe.prototype.isVector4=!0,this.x=e,this.y=t,this.z=i,this.w=s}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,s=this.z,a=this.w,r=e.elements;return this.x=r[0]*t+r[4]*i+r[8]*s+r[12]*a,this.y=r[1]*t+r[5]*i+r[9]*s+r[13]*a,this.z=r[2]*t+r[6]*i+r[10]*s+r[14]*a,this.w=r[3]*t+r[7]*i+r[11]*s+r[15]*a,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,i,s,a;const l=e.elements,c=l[0],u=l[4],d=l[8],h=l[1],f=l[5],p=l[9],g=l[2],_=l[6],m=l[10];if(Math.abs(u-h)<.01&&Math.abs(d-g)<.01&&Math.abs(p-_)<.01){if(Math.abs(u+h)<.1&&Math.abs(d+g)<.1&&Math.abs(p+_)<.1&&Math.abs(c+f+m-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const y=(c+1)/2,b=(f+1)/2,T=(m+1)/2,x=(u+h)/4,M=(d+g)/4,C=(p+_)/4;return y>b&&y>T?y<.01?(i=0,s=.707106781,a=.707106781):(i=Math.sqrt(y),s=x/i,a=M/i):b>T?b<.01?(i=.707106781,s=0,a=.707106781):(s=Math.sqrt(b),i=x/s,a=C/s):T<.01?(i=.707106781,s=.707106781,a=0):(a=Math.sqrt(T),i=M/a,s=C/a),this.set(i,s,a,t),this}let v=Math.sqrt((_-p)*(_-p)+(d-g)*(d-g)+(h-u)*(h-u));return Math.abs(v)<.001&&(v=1),this.x=(_-p)/v,this.y=(d-g)/v,this.z=(h-u)/v,this.w=Math.acos((c+f+m-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Ze(this.x,e.x,t.x),this.y=Ze(this.y,e.y,t.y),this.z=Ze(this.z,e.z,t.z),this.w=Ze(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Ze(this.x,e,t),this.y=Ze(this.y,e,t),this.z=Ze(this.z,e,t),this.w=Ze(this.w,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Ze(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class J_ extends gs{constructor(e=1,t=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Vt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},i),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=i.depth,this.scissor=new qe(0,0,e,t),this.scissorTest=!1,this.viewport=new qe(0,0,e,t);const s={width:e,height:t,depth:i.depth},a=new Bt(s);this.textures=[];const r=i.count;for(let o=0;o1;this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,i=e.textures.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Ii),Ii.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(zo),yc.subVectors(this.max,zo),vr.subVectors(e.a,zo),br.subVectors(e.b,zo),xr.subVectors(e.c,zo),Vs.subVectors(br,vr),Gs.subVectors(xr,br),ga.subVectors(vr,xr);let t=[0,-Vs.z,Vs.y,0,-Gs.z,Gs.y,0,-ga.z,ga.y,Vs.z,0,-Vs.x,Gs.z,0,-Gs.x,ga.z,0,-ga.x,-Vs.y,Vs.x,0,-Gs.y,Gs.x,0,-ga.y,ga.x,0];return!yf(t,vr,br,xr,yc)||(t=[1,0,0,0,1,0,0,0,1],!yf(t,vr,br,xr,yc))?!1:(vc.crossVectors(Vs,Gs),t=[vc.x,vc.y,vc.z],yf(t,vr,br,xr,yc))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Ii).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Ii).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(vs[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),vs[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),vs[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),vs[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),vs[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),vs[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),vs[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),vs[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(vs),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const vs=[new S,new S,new S,new S,new S,new S,new S,new S],Ii=new S,gc=new vn,vr=new S,br=new S,xr=new S,Vs=new S,Gs=new S,ga=new S,zo=new S,yc=new S,vc=new S,ya=new S;function yf(n,e,t,i,s){for(let a=0,r=n.length-3;a<=r;a+=3){ya.fromArray(n,a);const o=s.x*Math.abs(ya.x)+s.y*Math.abs(ya.y)+s.z*Math.abs(ya.z),l=e.dot(ya),c=t.dot(ya),u=i.dot(ya);if(Math.max(-Math.max(l,c,u),Math.min(l,c,u))>o)return!1}return!0}const qC=new vn,Ho=new S,vf=new S;class bn{constructor(e=new S,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const i=this.center;t!==void 0?i.copy(t):qC.setFromPoints(e).getCenter(i);let s=0;for(let a=0,r=e.length;athis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Ho.subVectors(e,this.center);const t=Ho.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),s=(i-this.radius)*.5;this.center.addScaledVector(Ho,s/i),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(vf.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Ho.copy(e.center).add(vf)),this.expandByPoint(Ho.copy(e.center).sub(vf))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}const bs=new S,bf=new S,bc=new S,$s=new S,xf=new S,xc=new S,wf=new S;class fr{constructor(e=new S,t=new S(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,bs)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=bs.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(bs.copy(this.origin).addScaledVector(this.direction,t),bs.distanceToSquared(e))}distanceSqToSegment(e,t,i,s){bf.copy(e).add(t).multiplyScalar(.5),bc.copy(t).sub(e).normalize(),$s.copy(this.origin).sub(bf);const a=e.distanceTo(t)*.5,r=-this.direction.dot(bc),o=$s.dot(this.direction),l=-$s.dot(bc),c=$s.lengthSq(),u=Math.abs(1-r*r);let d,h,f,p;if(u>0)if(d=r*l-o,h=r*o-l,p=a*u,d>=0)if(h>=-p)if(h<=p){const g=1/u;d*=g,h*=g,f=d*(d+r*h+2*o)+h*(r*d+h+2*l)+c}else h=a,d=Math.max(0,-(r*h+o)),f=-d*d+h*(h+2*l)+c;else h=-a,d=Math.max(0,-(r*h+o)),f=-d*d+h*(h+2*l)+c;else h<=-p?(d=Math.max(0,-(-r*a+o)),h=d>0?-a:Math.min(Math.max(-a,-l),a),f=-d*d+h*(h+2*l)+c):h<=p?(d=0,h=Math.min(Math.max(-a,-l),a),f=h*(h+2*l)+c):(d=Math.max(0,-(r*a+o)),h=d>0?a:Math.min(Math.max(-a,-l),a),f=-d*d+h*(h+2*l)+c);else h=r>0?-a:a,d=Math.max(0,-(r*h+o)),f=-d*d+h*(h+2*l)+c;return i&&i.copy(this.origin).addScaledVector(this.direction,d),s&&s.copy(bf).addScaledVector(bc,h),f}intersectSphere(e,t){bs.subVectors(e.center,this.origin);const i=bs.dot(this.direction),s=bs.dot(bs)-i*i,a=e.radius*e.radius;if(s>a)return null;const r=Math.sqrt(a-s),o=i-r,l=i+r;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,s,a,r,o,l;const c=1/this.direction.x,u=1/this.direction.y,d=1/this.direction.z,h=this.origin;return c>=0?(i=(e.min.x-h.x)*c,s=(e.max.x-h.x)*c):(i=(e.max.x-h.x)*c,s=(e.min.x-h.x)*c),u>=0?(a=(e.min.y-h.y)*u,r=(e.max.y-h.y)*u):(a=(e.max.y-h.y)*u,r=(e.min.y-h.y)*u),i>r||a>s||((a>i||isNaN(i))&&(i=a),(r=0?(o=(e.min.z-h.z)*d,l=(e.max.z-h.z)*d):(o=(e.max.z-h.z)*d,l=(e.min.z-h.z)*d),i>l||o>s)||((o>i||i!==i)&&(i=o),(l=0?i:s,t)}intersectsBox(e){return this.intersectBox(e,bs)!==null}intersectTriangle(e,t,i,s,a){xf.subVectors(t,e),xc.subVectors(i,e),wf.crossVectors(xf,xc);let r=this.direction.dot(wf),o;if(r>0){if(s)return null;o=1}else if(r<0)o=-1,r=-r;else return null;$s.subVectors(this.origin,e);const l=o*this.direction.dot(xc.crossVectors($s,xc));if(l<0)return null;const c=o*this.direction.dot(xf.cross($s));if(c<0||l+c>r)return null;const u=-o*$s.dot(wf);return u<0?null:this.at(u/r,a)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Me{constructor(e,t,i,s,a,r,o,l,c,u,d,h,f,p,g,_){Me.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,i,s,a,r,o,l,c,u,d,h,f,p,g,_)}set(e,t,i,s,a,r,o,l,c,u,d,h,f,p,g,_){const m=this.elements;return m[0]=e,m[4]=t,m[8]=i,m[12]=s,m[1]=a,m[5]=r,m[9]=o,m[13]=l,m[2]=c,m[6]=u,m[10]=d,m[14]=h,m[3]=f,m[7]=p,m[11]=g,m[15]=_,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Me().fromArray(this.elements)}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(e){const t=this.elements,i=e.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,i){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(e,t,i){return this.set(e.x,t.x,i.x,0,e.y,t.y,i.y,0,e.z,t.z,i.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,i=e.elements,s=1/wr.setFromMatrixColumn(e,0).length(),a=1/wr.setFromMatrixColumn(e,1).length(),r=1/wr.setFromMatrixColumn(e,2).length();return t[0]=i[0]*s,t[1]=i[1]*s,t[2]=i[2]*s,t[3]=0,t[4]=i[4]*a,t[5]=i[5]*a,t[6]=i[6]*a,t[7]=0,t[8]=i[8]*r,t[9]=i[9]*r,t[10]=i[10]*r,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,i=e.x,s=e.y,a=e.z,r=Math.cos(i),o=Math.sin(i),l=Math.cos(s),c=Math.sin(s),u=Math.cos(a),d=Math.sin(a);if(e.order==="XYZ"){const h=r*u,f=r*d,p=o*u,g=o*d;t[0]=l*u,t[4]=-l*d,t[8]=c,t[1]=f+p*c,t[5]=h-g*c,t[9]=-o*l,t[2]=g-h*c,t[6]=p+f*c,t[10]=r*l}else if(e.order==="YXZ"){const h=l*u,f=l*d,p=c*u,g=c*d;t[0]=h+g*o,t[4]=p*o-f,t[8]=r*c,t[1]=r*d,t[5]=r*u,t[9]=-o,t[2]=f*o-p,t[6]=g+h*o,t[10]=r*l}else if(e.order==="ZXY"){const h=l*u,f=l*d,p=c*u,g=c*d;t[0]=h-g*o,t[4]=-r*d,t[8]=p+f*o,t[1]=f+p*o,t[5]=r*u,t[9]=g-h*o,t[2]=-r*c,t[6]=o,t[10]=r*l}else if(e.order==="ZYX"){const h=r*u,f=r*d,p=o*u,g=o*d;t[0]=l*u,t[4]=p*c-f,t[8]=h*c+g,t[1]=l*d,t[5]=g*c+h,t[9]=f*c-p,t[2]=-c,t[6]=o*l,t[10]=r*l}else if(e.order==="YZX"){const h=r*l,f=r*c,p=o*l,g=o*c;t[0]=l*u,t[4]=g-h*d,t[8]=p*d+f,t[1]=d,t[5]=r*u,t[9]=-o*u,t[2]=-c*u,t[6]=f*d+p,t[10]=h-g*d}else if(e.order==="XZY"){const h=r*l,f=r*c,p=o*l,g=o*c;t[0]=l*u,t[4]=-d,t[8]=c*u,t[1]=h*d+g,t[5]=r*u,t[9]=f*d-p,t[2]=p*d-f,t[6]=o*u,t[10]=g*d+h}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(YC,e,jC)}lookAt(e,t,i){const s=this.elements;return li.subVectors(e,t),li.lengthSq()===0&&(li.z=1),li.normalize(),Ws.crossVectors(i,li),Ws.lengthSq()===0&&(Math.abs(i.z)===1?li.x+=1e-4:li.z+=1e-4,li.normalize(),Ws.crossVectors(i,li)),Ws.normalize(),wc.crossVectors(li,Ws),s[0]=Ws.x,s[4]=wc.x,s[8]=li.x,s[1]=Ws.y,s[5]=wc.y,s[9]=li.y,s[2]=Ws.z,s[6]=wc.z,s[10]=li.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,s=t.elements,a=this.elements,r=i[0],o=i[4],l=i[8],c=i[12],u=i[1],d=i[5],h=i[9],f=i[13],p=i[2],g=i[6],_=i[10],m=i[14],v=i[3],y=i[7],b=i[11],T=i[15],x=s[0],M=s[4],C=s[8],w=s[12],E=s[1],R=s[5],D=s[9],O=s[13],k=s[2],U=s[6],F=s[10],W=s[14],H=s[3],ne=s[7],oe=s[11],pe=s[15];return a[0]=r*x+o*E+l*k+c*H,a[4]=r*M+o*R+l*U+c*ne,a[8]=r*C+o*D+l*F+c*oe,a[12]=r*w+o*O+l*W+c*pe,a[1]=u*x+d*E+h*k+f*H,a[5]=u*M+d*R+h*U+f*ne,a[9]=u*C+d*D+h*F+f*oe,a[13]=u*w+d*O+h*W+f*pe,a[2]=p*x+g*E+_*k+m*H,a[6]=p*M+g*R+_*U+m*ne,a[10]=p*C+g*D+_*F+m*oe,a[14]=p*w+g*O+_*W+m*pe,a[3]=v*x+y*E+b*k+T*H,a[7]=v*M+y*R+b*U+T*ne,a[11]=v*C+y*D+b*F+T*oe,a[15]=v*w+y*O+b*W+T*pe,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[4],s=e[8],a=e[12],r=e[1],o=e[5],l=e[9],c=e[13],u=e[2],d=e[6],h=e[10],f=e[14],p=e[3],g=e[7],_=e[11],m=e[15];return p*(+a*l*d-s*c*d-a*o*h+i*c*h+s*o*f-i*l*f)+g*(+t*l*f-t*c*h+a*r*h-s*r*f+s*c*u-a*l*u)+_*(+t*c*d-t*o*f-a*r*d+i*r*f+a*o*u-i*c*u)+m*(-s*o*u-t*l*d+t*o*h+s*r*d-i*r*h+i*l*u)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,i){const s=this.elements;return e.isVector3?(s[12]=e.x,s[13]=e.y,s[14]=e.z):(s[12]=e,s[13]=t,s[14]=i),this}invert(){const e=this.elements,t=e[0],i=e[1],s=e[2],a=e[3],r=e[4],o=e[5],l=e[6],c=e[7],u=e[8],d=e[9],h=e[10],f=e[11],p=e[12],g=e[13],_=e[14],m=e[15],v=d*_*c-g*h*c+g*l*f-o*_*f-d*l*m+o*h*m,y=p*h*c-u*_*c-p*l*f+r*_*f+u*l*m-r*h*m,b=u*g*c-p*d*c+p*o*f-r*g*f-u*o*m+r*d*m,T=p*d*l-u*g*l-p*o*h+r*g*h+u*o*_-r*d*_,x=t*v+i*y+s*b+a*T;if(x===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const M=1/x;return e[0]=v*M,e[1]=(g*h*a-d*_*a-g*s*f+i*_*f+d*s*m-i*h*m)*M,e[2]=(o*_*a-g*l*a+g*s*c-i*_*c-o*s*m+i*l*m)*M,e[3]=(d*l*a-o*h*a-d*s*c+i*h*c+o*s*f-i*l*f)*M,e[4]=y*M,e[5]=(u*_*a-p*h*a+p*s*f-t*_*f-u*s*m+t*h*m)*M,e[6]=(p*l*a-r*_*a-p*s*c+t*_*c+r*s*m-t*l*m)*M,e[7]=(r*h*a-u*l*a+u*s*c-t*h*c-r*s*f+t*l*f)*M,e[8]=b*M,e[9]=(p*d*a-u*g*a-p*i*f+t*g*f+u*i*m-t*d*m)*M,e[10]=(r*g*a-p*o*a+p*i*c-t*g*c-r*i*m+t*o*m)*M,e[11]=(u*o*a-r*d*a-u*i*c+t*d*c+r*i*f-t*o*f)*M,e[12]=T*M,e[13]=(u*g*s-p*d*s+p*i*h-t*g*h-u*i*_+t*d*_)*M,e[14]=(p*o*s-r*g*s-p*i*l+t*g*l+r*i*_-t*o*_)*M,e[15]=(r*d*s-u*o*s+u*i*l-t*d*l-r*i*h+t*o*h)*M,this}scale(e){const t=this.elements,i=e.x,s=e.y,a=e.z;return t[0]*=i,t[4]*=s,t[8]*=a,t[1]*=i,t[5]*=s,t[9]*=a,t[2]*=i,t[6]*=s,t[10]*=a,t[3]*=i,t[7]*=s,t[11]*=a,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],s=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,s))}makeTranslation(e,t,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const i=Math.cos(t),s=Math.sin(t),a=1-i,r=e.x,o=e.y,l=e.z,c=a*r,u=a*o;return this.set(c*r+i,c*o-s*l,c*l+s*o,0,c*o+s*l,u*o+i,u*l-s*r,0,c*l-s*o,u*l+s*r,a*l*l+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,s,a,r){return this.set(1,i,a,0,e,1,r,0,t,s,1,0,0,0,0,1),this}compose(e,t,i){const s=this.elements,a=t._x,r=t._y,o=t._z,l=t._w,c=a+a,u=r+r,d=o+o,h=a*c,f=a*u,p=a*d,g=r*u,_=r*d,m=o*d,v=l*c,y=l*u,b=l*d,T=i.x,x=i.y,M=i.z;return s[0]=(1-(g+m))*T,s[1]=(f+b)*T,s[2]=(p-y)*T,s[3]=0,s[4]=(f-b)*x,s[5]=(1-(h+m))*x,s[6]=(_+v)*x,s[7]=0,s[8]=(p+y)*M,s[9]=(_-v)*M,s[10]=(1-(h+g))*M,s[11]=0,s[12]=e.x,s[13]=e.y,s[14]=e.z,s[15]=1,this}decompose(e,t,i){const s=this.elements;let a=wr.set(s[0],s[1],s[2]).length();const r=wr.set(s[4],s[5],s[6]).length(),o=wr.set(s[8],s[9],s[10]).length();this.determinant()<0&&(a=-a),e.x=s[12],e.y=s[13],e.z=s[14],Li.copy(this);const c=1/a,u=1/r,d=1/o;return Li.elements[0]*=c,Li.elements[1]*=c,Li.elements[2]*=c,Li.elements[4]*=u,Li.elements[5]*=u,Li.elements[6]*=u,Li.elements[8]*=d,Li.elements[9]*=d,Li.elements[10]*=d,t.setFromRotationMatrix(Li),i.x=a,i.y=r,i.z=o,this}makePerspective(e,t,i,s,a,r,o=hi,l=!1){const c=this.elements,u=2*a/(t-e),d=2*a/(i-s),h=(t+e)/(t-e),f=(i+s)/(i-s);let p,g;if(l)p=a/(r-a),g=r*a/(r-a);else if(o===hi)p=-(r+a)/(r-a),g=-2*r*a/(r-a);else if(o===So)p=-r/(r-a),g=-r*a/(r-a);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return c[0]=u,c[4]=0,c[8]=h,c[12]=0,c[1]=0,c[5]=d,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=g,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,i,s,a,r,o=hi,l=!1){const c=this.elements,u=2/(t-e),d=2/(i-s),h=-(t+e)/(t-e),f=-(i+s)/(i-s);let p,g;if(l)p=1/(r-a),g=r/(r-a);else if(o===hi)p=-2/(r-a),g=-(r+a)/(r-a);else if(o===So)p=-1/(r-a),g=-a/(r-a);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return c[0]=u,c[4]=0,c[8]=0,c[12]=h,c[1]=0,c[5]=d,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=p,c[14]=g,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const t=this.elements,i=e.elements;for(let s=0;s<16;s++)if(t[s]!==i[s])return!1;return!0}fromArray(e,t=0){for(let i=0;i<16;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],e}}const wr=new S,Li=new Me,YC=new S(0,0,0),jC=new S(1,1,1),Ws=new S,wc=new S,li=new S,_y=new Me,gy=new dt;class an{constructor(e=0,t=0,i=0,s=an.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=s}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,i,s=this._order){return this._x=e,this._y=t,this._z=i,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,i=!0){const s=e.elements,a=s[0],r=s[4],o=s[8],l=s[1],c=s[5],u=s[9],d=s[2],h=s[6],f=s[10];switch(t){case"XYZ":this._y=Math.asin(Ze(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,f),this._z=Math.atan2(-r,a)):(this._x=Math.atan2(h,c),this._z=0);break;case"YXZ":this._x=Math.asin(-Ze(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-d,a),this._z=0);break;case"ZXY":this._x=Math.asin(Ze(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-d,f),this._z=Math.atan2(-r,c)):(this._y=0,this._z=Math.atan2(l,a));break;case"ZYX":this._y=Math.asin(-Ze(d,-1,1)),Math.abs(d)<.9999999?(this._x=Math.atan2(h,f),this._z=Math.atan2(l,a)):(this._x=0,this._z=Math.atan2(-r,c));break;case"YZX":this._z=Math.asin(Ze(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-u,c),this._y=Math.atan2(-d,a)):(this._x=0,this._y=Math.atan2(o,f));break;case"XZY":this._z=Math.asin(-Ze(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(h,c),this._y=Math.atan2(o,a)):(this._x=Math.atan2(-u,f),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,i===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return _y.makeRotationFromQuaternion(e),this.setFromRotationMatrix(_y,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return gy.setFromEuler(this),this.setFromQuaternion(gy,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}an.DEFAULT_ORDER="XYZ";class Eh{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let i=0;i0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(s.matrixAutoUpdate=!1),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),s.instanceInfo=this._instanceInfo.map(o=>({...o})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(e),s.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(s.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(s.boundingBox=this.boundingBox.toJSON()));function a(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=a(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const l=o.shapes;if(Array.isArray(l))for(let c=0,u=l.length;c0){s.children=[];for(let o=0;o0){s.animations=[];for(let o=0;o0&&(i.geometries=o),l.length>0&&(i.materials=l),c.length>0&&(i.textures=c),u.length>0&&(i.images=u),d.length>0&&(i.shapes=d),h.length>0&&(i.skeletons=h),f.length>0&&(i.animations=f),p.length>0&&(i.nodes=p)}return i.object=s,i;function r(o){const l=[];for(const c in o){const u=o[c];delete u.metadata,l.push(u)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let i=0;i0?s.multiplyScalar(1/Math.sqrt(a)):s.set(0,0,0)}static getBarycoord(e,t,i,s,a){Di.subVectors(s,t),ws.subVectors(i,t),Tf.subVectors(e,t);const r=Di.dot(Di),o=Di.dot(ws),l=Di.dot(Tf),c=ws.dot(ws),u=ws.dot(Tf),d=r*c-o*o;if(d===0)return a.set(0,0,0),null;const h=1/d,f=(c*l-o*u)*h,p=(r*u-o*l)*h;return a.set(1-f-p,p,f)}static containsPoint(e,t,i,s){return this.getBarycoord(e,t,i,s,Ss)===null?!1:Ss.x>=0&&Ss.y>=0&&Ss.x+Ss.y<=1}static getInterpolation(e,t,i,s,a,r,o,l){return this.getBarycoord(e,t,i,s,Ss)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(a,Ss.x),l.addScaledVector(r,Ss.y),l.addScaledVector(o,Ss.z),l)}static getInterpolatedAttribute(e,t,i,s,a,r){return Af.setScalar(0),Rf.setScalar(0),Pf.setScalar(0),Af.fromBufferAttribute(e,t),Rf.fromBufferAttribute(e,i),Pf.fromBufferAttribute(e,s),r.setScalar(0),r.addScaledVector(Af,a.x),r.addScaledVector(Rf,a.y),r.addScaledVector(Pf,a.z),r}static isFrontFacing(e,t,i,s){return Di.subVectors(i,t),ws.subVectors(e,t),Di.cross(ws).dot(s)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,s){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[s]),this}setFromAttributeAndIndices(e,t,i,s){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,s),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Di.subVectors(this.c,this.b),ws.subVectors(this.a,this.b),Di.cross(ws).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Qn.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Qn.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,s,a){return Qn.getInterpolation(e,this.a,this.b,this.c,t,i,s,a)}containsPoint(e){return Qn.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Qn.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,s=this.b,a=this.c;let r,o;Mr.subVectors(s,i),Er.subVectors(a,i),Mf.subVectors(e,i);const l=Mr.dot(Mf),c=Er.dot(Mf);if(l<=0&&c<=0)return t.copy(i);Ef.subVectors(e,s);const u=Mr.dot(Ef),d=Er.dot(Ef);if(u>=0&&d<=u)return t.copy(s);const h=l*d-u*c;if(h<=0&&l>=0&&u<=0)return r=l/(l-u),t.copy(i).addScaledVector(Mr,r);Cf.subVectors(e,a);const f=Mr.dot(Cf),p=Er.dot(Cf);if(p>=0&&f<=p)return t.copy(a);const g=f*c-l*p;if(g<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(i).addScaledVector(Er,o);const _=u*p-f*d;if(_<=0&&d-u>=0&&f-p>=0)return Sy.subVectors(a,s),o=(d-u)/(d-u+(f-p)),t.copy(s).addScaledVector(Sy,o);const m=1/(_+g+h);return r=g*m,o=h*m,t.copy(i).addScaledVector(Mr,r).addScaledVector(Er,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const hS={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Xs={h:0,s:0,l:0},Tc={h:0,s:0,l:0};function If(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*6*(2/3-t):n}class ue{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){const s=e;s&&s.isColor?this.copy(s):typeof s=="number"?this.setHex(s):typeof s=="string"&&this.setStyle(s)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=gt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,at.colorSpaceToWorking(this,t),this}setRGB(e,t,i,s=at.workingColorSpace){return this.r=e,this.g=t,this.b=i,at.colorSpaceToWorking(this,s),this}setHSL(e,t,i,s=at.workingColorSpace){if(e=Z_(e,1),t=Ze(t,0,1),i=Ze(i,0,1),t===0)this.r=this.g=this.b=i;else{const a=i<=.5?i*(1+t):i+t-i*t,r=2*i-a;this.r=If(r,a,e+1/3),this.g=If(r,a,e),this.b=If(r,a,e-1/3)}return at.colorSpaceToWorking(this,s),this}setStyle(e,t=gt){function i(a){a!==void 0&&parseFloat(a)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(e)){let a;const r=s[1],o=s[2];switch(r){case"rgb":case"rgba":if(a=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setRGB(Math.min(255,parseInt(a[1],10))/255,Math.min(255,parseInt(a[2],10))/255,Math.min(255,parseInt(a[3],10))/255,t);if(a=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setRGB(Math.min(100,parseInt(a[1],10))/100,Math.min(100,parseInt(a[2],10))/100,Math.min(100,parseInt(a[3],10))/100,t);break;case"hsl":case"hsla":if(a=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setHSL(parseFloat(a[1])/360,parseFloat(a[2])/100,parseFloat(a[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(e)){const a=s[1],r=a.length;if(r===3)return this.setRGB(parseInt(a.charAt(0),16)/15,parseInt(a.charAt(1),16)/15,parseInt(a.charAt(2),16)/15,t);if(r===6)return this.setHex(parseInt(a,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=gt){const i=hS[e.toLowerCase()];return i!==void 0?this.setHex(i,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Fs(e.r),this.g=Fs(e.g),this.b=Fs(e.b),this}copyLinearToSRGB(e){return this.r=to(e.r),this.g=to(e.g),this.b=to(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=gt){return at.workingToColorSpace(En.copy(this),e),Math.round(Ze(En.r*255,0,255))*65536+Math.round(Ze(En.g*255,0,255))*256+Math.round(Ze(En.b*255,0,255))}getHexString(e=gt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=at.workingColorSpace){at.workingToColorSpace(En.copy(this),t);const i=En.r,s=En.g,a=En.b,r=Math.max(i,s,a),o=Math.min(i,s,a);let l,c;const u=(o+r)/2;if(o===r)l=0,c=0;else{const d=r-o;switch(c=u<=.5?d/(r+o):d/(2-r-o),r){case i:l=(s-a)/d+(s0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const i=e[t];if(i===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(i):s&&s.isVector3&&i&&i.isVector3?s.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==tr&&(i.blending=this.blending),this.side!==fs&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==Ol&&(i.blendSrc=this.blendSrc),this.blendDst!==Fl&&(i.blendDst=this.blendDst),this.blendEquation!==Is&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==sr&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==xm&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Ua&&(i.stencilFail=this.stencilFail),this.stencilZFail!==Ua&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==Ua&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function s(a){const r=[];for(const o in a){const l=a[o];delete l.metadata,r.push(l)}return r}if(t){const a=s(e.textures),r=s(e.images);a.length>0&&(i.textures=a),r.length>0&&(i.images=r)}return i}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let i=null;if(t!==null){const s=t.length;i=new Array(s);for(let a=0;a!==s;++a)i[a]=t[a].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class Ye extends Qt{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new ue(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new an,this.combine=nc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Ds=nA();function nA(){const n=new ArrayBuffer(4),e=new Float32Array(n),t=new Uint32Array(n),i=new Uint32Array(512),s=new Uint32Array(512);for(let l=0;l<256;++l){const c=l-127;c<-27?(i[l]=0,i[l|256]=32768,s[l]=24,s[l|256]=24):c<-14?(i[l]=1024>>-c-14,i[l|256]=1024>>-c-14|32768,s[l]=-c-1,s[l|256]=-c-1):c<=15?(i[l]=c+15<<10,i[l|256]=c+15<<10|32768,s[l]=13,s[l|256]=13):c<128?(i[l]=31744,i[l|256]=64512,s[l]=24,s[l|256]=24):(i[l]=31744,i[l|256]=64512,s[l]=13,s[l|256]=13)}const a=new Uint32Array(2048),r=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,u=0;for(;(c&8388608)===0;)c<<=1,u-=8388608;c&=-8388609,u+=947912704,a[l]=c|u}for(let l=1024;l<2048;++l)a[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)r[l]=l<<23;r[31]=1199570944,r[32]=2147483648;for(let l=33;l<63;++l)r[l]=2147483648+(l-32<<23);r[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:e,uint32View:t,baseTable:i,shiftTable:s,mantissaTable:a,exponentTable:r,offsetTable:o}}function Yn(n){Math.abs(n)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),n=Ze(n,-65504,65504),Ds.floatView[0]=n;const e=Ds.uint32View[0],t=e>>23&511;return Ds.baseTable[t]+((e&8388607)>>Ds.shiftTable[t])}function ul(n){const e=n>>10;return Ds.uint32View[0]=Ds.mantissaTable[Ds.offsetTable[e]+(n&1023)]+Ds.exponentTable[e],Ds.floatView[0]}class dl{static toHalfFloat(e){return Yn(e)}static fromHalfFloat(e){return ul(e)}}const nn=new S,Mc=new te;let iA=0;class rt{constructor(e,t,i=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:iA++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=zl,this.updateRanges=[],this.gpuType=Sn,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,i){e*=this.itemSize,i*=t.itemSize;for(let s=0,a=this.itemSize;st.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new vn);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new S(-1/0,-1/0,-1/0),new S(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,s=t.length;i0&&(e.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const l in i){const c=i[l];e.data.attributes[l]=c.toJSON(e.data)}const s={};let a=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],u=[];for(let d=0,h=c.length;d0&&(s[l]=u,a=!0)}a&&(e.data.morphAttributes=s,e.data.morphTargetsRelative=this.morphTargetsRelative);const r=this.groups;r.length>0&&(e.data.groups=JSON.parse(JSON.stringify(r)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const i=e.index;i!==null&&this.setIndex(i.clone());const s=e.attributes;for(const c in s){const u=s[c];this.setAttribute(c,u.clone(t))}const a=e.morphAttributes;for(const c in a){const u=[],d=a[c];for(let h=0,f=d.length;h0){const s=t[i[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,r=s.length;a(e.far-e.near)**2))&&(Ty.copy(a).invert(),va.copy(e.ray).applyMatrix4(Ty),!(i.boundingBox!==null&&va.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,va)))}_computeIntersections(e,t,i){let s;const a=this.geometry,r=this.material,o=a.index,l=a.attributes.position,c=a.attributes.uv,u=a.attributes.uv1,d=a.attributes.normal,h=a.groups,f=a.drawRange;if(o!==null)if(Array.isArray(r))for(let p=0,g=h.length;pt.far?null:{distance:c,point:Ic.clone(),object:n}}function Lc(n,e,t,i,s,a,r,o,l,c){n.getVertexPosition(o,Cc),n.getVertexPosition(l,Ac),n.getVertexPosition(c,Rc);const u=dA(n,e,t,i,Cc,Ac,Rc,Ey);if(u){const d=new S;Qn.getBarycoord(Ey,Cc,Ac,Rc,d),s&&(u.uv=Qn.getInterpolatedAttribute(s,o,l,c,d,new te)),a&&(u.uv1=Qn.getInterpolatedAttribute(a,o,l,c,d,new te)),r&&(u.normal=Qn.getInterpolatedAttribute(r,o,l,c,d,new S),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));const h={a:o,b:l,c,normal:new S,materialIndex:0};Qn.getNormal(Cc,Ac,Rc,h.normal),u.face=h,u.barycoord=d}return u}class Ei extends Ge{constructor(e=1,t=1,i=1,s=1,a=1,r=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:s,heightSegments:a,depthSegments:r};const o=this;s=Math.floor(s),a=Math.floor(a),r=Math.floor(r);const l=[],c=[],u=[],d=[];let h=0,f=0;p("z","y","x",-1,-1,i,t,e,r,a,0),p("z","y","x",1,-1,i,t,-e,r,a,1),p("x","z","y",1,1,e,i,t,s,r,2),p("x","z","y",1,-1,e,i,-t,s,r,3),p("x","y","z",1,-1,e,t,i,s,a,4),p("x","y","z",-1,-1,e,t,-i,s,a,5),this.setIndex(l),this.setAttribute("position",new Ee(c,3)),this.setAttribute("normal",new Ee(u,3)),this.setAttribute("uv",new Ee(d,2));function p(g,_,m,v,y,b,T,x,M,C,w){const E=b/M,R=T/C,D=b/2,O=T/2,k=x/2,U=M+1,F=C+1;let W=0,H=0;const ne=new S;for(let oe=0;oe0?1:-1,u.push(ne.x,ne.y,ne.z),d.push(Ie/M),d.push(1-oe/C),W+=1}}for(let oe=0;oee)i=s-1;else return s}return Math.max(0,t-1)}class Cw{_listeners=new Map;on(e,t){let i=this._listeners.get(e);return i||(i=new Set,this._listeners.set(e,i)),i.add(t),this}once(e,t){const i=(...s)=>{this.off(e,i),t(...s)};return this.on(e,i)}off(e,t){const i=this._listeners.get(e);return i?(t?i.delete(t):i.clear(),i.size===0&&this._listeners.delete(e),this):this}removeListener(e,t){return this.off(e,t)}removeAllListeners(e){return e?this._listeners.delete(e):this._listeners.clear(),this}emit(e,...t){const i=this._listeners.get(e);if(!i||i.size===0)return!1;for(const s of[...i])s(...t);return!0}}function vf(n){return n?{x:n.x,y:n.z,z:n.y}:null}function N1(n){return n?{x:n.x,y:n.z,z:n.y,w:-n.w}:null}function U1(n){return n*100/255}const py={Octane:{length:118.0074,width:84.19941,height:36.15907,offsetX:13.87566,offsetZ:20.75499},Dominus:{length:127.9268,width:83.27995,height:31.3,offsetX:9,offsetZ:15.75},Plank:{length:128.8198,width:84.67036,height:29.3944,offsetX:9.00857,offsetZ:12.0942},Breakout:{length:131.4924,width:80.521,height:30.3,offsetX:12.5,offsetZ:11.75},Hybrid:{length:127.0192,width:82.18787,height:34.15907,offsetX:13.87566,offsetZ:20.75499},Merc:{length:120.72,width:76.71,height:41.66,offsetX:11.37566,offsetZ:21.504988}},B1={21:{name:"Backfire",hitbox:"Octane"},22:{name:"Breakout",hitbox:"Breakout"},23:{name:"Octane",hitbox:"Octane"},24:{name:"Paladin",hitbox:"Plank"},25:{name:"Road Hog",hitbox:"Octane"},26:{name:"Gizmo",hitbox:"Octane"},28:{name:"X-Devil",hitbox:"Hybrid"},29:{name:"Hotshot",hitbox:"Dominus"},30:{name:"Merc",hitbox:"Merc"},31:{name:"Venom",hitbox:"Hybrid"},402:{name:"Takumi",hitbox:"Octane"},403:{name:"Dominus",hitbox:"Dominus"},404:{name:"Scarab",hitbox:"Octane"},523:{name:"Zippy",hitbox:"Octane"},597:{name:"DeLorean Time Machine",hitbox:"Dominus"},600:{name:"Ripper",hitbox:"Dominus"},607:{name:"Grog",hitbox:"Octane"},1018:{name:"Dominus GT",hitbox:"Dominus"},1159:{name:"X-Devil Mk2",hitbox:"Hybrid"},1171:{name:"Masamune",hitbox:"Dominus"},1172:{name:"Marauder",hitbox:"Octane"},1286:{name:"Aftershock",hitbox:"Dominus"},1295:{name:"Takumi RX-T",hitbox:"Octane"},1300:{name:"Road Hog XL",hitbox:"Octane"},1317:{name:"Esper",hitbox:"Hybrid"},1416:{name:"Breakout Type-S",hitbox:"Breakout"},1475:{name:"Proteus",hitbox:"Octane"},1478:{name:"Triton",hitbox:"Octane"},1533:{name:"Vulcan",hitbox:"Octane"},1568:{name:"Octane ZSR",hitbox:"Octane"},1603:{name:"Twin Mill III",hitbox:"Plank"},1623:{name:"Bone Shaker",hitbox:"Octane"},1624:{name:"Endo",hitbox:"Hybrid"},1675:{name:"Ice Charger",hitbox:"Dominus"},1689:{name:"Nemesis",hitbox:"Dominus"},1691:{name:"Mantis",hitbox:"Plank"},1856:{name:"Jager 619",hitbox:"Hybrid"},1883:{name:"Imperator DT5",hitbox:"Dominus"},1894:{name:"Samurai",hitbox:"Breakout"},1919:{name:"Centio",hitbox:"Plank"},1932:{name:"Animus GP",hitbox:"Breakout"},2070:{name:"Werewolf",hitbox:"Dominus"},2268:{name:"Fast & Furious Dodge Charger",hitbox:"Dominus"},2269:{name:"Fast & Furious Nissan Skyline",hitbox:"Hybrid"},2665:{name:"The Dark Knight's Tumbler",hitbox:"Octane"},2666:{name:"Batmobile (1989)",hitbox:"Dominus"},2853:{name:"Twinzer",hitbox:"Octane"},2919:{name:"Jurassic Jeep Wrangler",hitbox:"Octane"},2949:{name:"Fast 4WD",hitbox:"Octane"},2950:{name:"MR11",hitbox:"Dominus"},2951:{name:"Gazella GT",hitbox:"Dominus"},3031:{name:"Cyclone",hitbox:"Breakout"},3155:{name:"Maverick",hitbox:"Dominus"},3156:{name:"Maverick G1",hitbox:"Dominus"},3157:{name:"Maverick GXT",hitbox:"Dominus"},3265:{name:"McLaren 570S",hitbox:"Dominus"},3311:{name:"Komodo",hitbox:"Breakout"},3426:{name:"Diestro",hitbox:"Dominus"},3451:{name:"Nimbus",hitbox:"Hybrid"},3582:{name:"Insidio",hitbox:"Hybrid"},3594:{name:"Artemis G1",hitbox:"Plank"},3614:{name:"Artemis",hitbox:"Plank"},3622:{name:"Artemis GXT",hitbox:"Plank"},3702:{name:"Tygris",hitbox:"Hybrid"},3875:{name:"Guardian GXT",hitbox:"Dominus"},3879:{name:"Guardian",hitbox:"Dominus"},3880:{name:"Guardian G1",hitbox:"Dominus"},4014:{name:"K.I.T.T.",hitbox:"Dominus"},4155:{name:"Ecto-1",hitbox:"Dominus"},4268:{name:"Sentinel",hitbox:"Plank"},4284:{name:"Fennec",hitbox:"Octane"},4318:{name:"Mudcat",hitbox:"Octane"},4319:{name:"Mudcat G1",hitbox:"Octane"},4320:{name:"Mudcat GXT",hitbox:"Octane"},4367:{name:"Chikara GXT",hitbox:"Dominus"},4472:{name:"Chikara",hitbox:"Dominus"},4473:{name:"Chikara G1",hitbox:"Dominus"},4745:{name:"Ronin GXT",hitbox:"Dominus"},4770:{name:"Dominus",hitbox:"Dominus"},4780:{name:"Battle Bus",hitbox:"Merc"},4781:{name:"Peregrine TT",hitbox:"Dominus"},4782:{name:"Psyclops",hitbox:"Body_Tritip_Handling"},4861:{name:"Ronin",hitbox:"Dominus"},4864:{name:"Ronin G1",hitbox:"Dominus"},4906:{name:"Harbinger",hitbox:"Octane"},5020:{name:"Outlaw",hitbox:"Octane"},5039:{name:"Harbinger GXT",hitbox:"Octane"},5188:{name:"Scarab",hitbox:"Octane"},5265:{name:"Formula 1 2021",hitbox:"Plank"},5361:{name:"Dingo",hitbox:"Octane"},5470:{name:"R3MX",hitbox:"Hybrid"},5488:{name:"R3MX GXT",hitbox:"Hybrid"},5547:{name:"007's Aston Martin DB5",hitbox:"Octane"},5709:{name:"NASCAR Ford Mustang",hitbox:"Dominus"},5713:{name:"Ford F-150 RLE",hitbox:"Octane"},5773:{name:"NASCAR Toyota Camry",hitbox:"Dominus"},5823:{name:"NASCAR Chevrolet Camaro",hitbox:"Dominus"},5837:{name:"Outlaw GXT",hitbox:"Octane"},5858:{name:"Tyranno",hitbox:"Dominus"},5879:{name:"Fast & Furious Pontiac Fiero",hitbox:"Hybrid"},5951:{name:"Jackal",hitbox:"Octane"},5964:{name:"Lamborghini Huracan STO",hitbox:"Dominus"},5979:{name:"Tyranno GXT",hitbox:"Dominus"},6122:{name:"Masamune",hitbox:"Dominus"},6243:{name:"Nexus",hitbox:"Breakout"},6244:{name:"BMW M240i",hitbox:"Dominus"},6247:{name:"McLaren 765LT",hitbox:"Dominus"},6260:{name:"007's Aston Martin Valhalla",hitbox:"Dominus"},6489:{name:"Nexus SC",hitbox:"Breakout"},6836:{name:"Ford Mustang Shelby GT350R RLE",hitbox:"Dominus"},6939:{name:"Ford Mustang Mach-E RLE",hitbox:"Octane"},7012:{name:"Tesla Cybertruck",hitbox:"Hybrid"},7052:{name:"Formula 1 2022",hitbox:"Plank"},7211:{name:"Mamba",hitbox:"Dominus"},7336:{name:"Nomad",hitbox:"Merc"},7337:{name:"NASCAR Next Gen Chevrolet Camaro",hitbox:"Dominus"},7338:{name:"NASCAR Next Gen Ford Mustang",hitbox:"Dominus"},7341:{name:"NASCAR Next Gen Toyota Camry",hitbox:"Dominus"},7343:{name:"007's Aston Martin DBS",hitbox:"Dominus"},7415:{name:"Batmobile (2022)",hitbox:"Dominus"},7477:{name:"Nomad GXT",hitbox:"Merc"},7512:{name:"Lamborghini Countach LPI 800-4",hitbox:"Dominus"},7532:{name:"Maestro",hitbox:"Dominus"},7593:{name:"Nissan Z Performance",hitbox:"Dominus"},7651:{name:"Redline",hitbox:"Breakout"},7696:{name:"Whiplash",hitbox:"Breakout"},7772:{name:"Ferrari 296 GTB",hitbox:"Dominus"},7815:{name:"Ford Bronco Raptor RLE",hitbox:"Merc"},7890:{name:"Fuse",hitbox:"Breakout"},7901:{name:"Fast & Furious Mazda RX-7",hitbox:"Breakout"},7947:{name:"Honda Civic Type R",hitbox:"Octane"},7948:{name:"Honda Civic Type R-LE",hitbox:"Octane"},7979:{name:"Stampede",hitbox:"Merc"},8006:{name:"Mako",hitbox:"Breakout"},8360:{name:"Emperor",hitbox:"Breakout"},8361:{name:"Emperor II",hitbox:"Breakout"},8383:{name:"Xentari",hitbox:"Octane"},8454:{name:"Admiral",hitbox:"Dominus"},8524:{name:"Bugatti Centodieci",hitbox:"Plank"},8565:{name:"Emperor II: Frozen",hitbox:"Breakout"},8566:{name:"Emperor II: Scorched",hitbox:"Breakout"},8669:{name:"Ace",hitbox:"Breakout"},8806:{name:"Volkswagen Golf GTI",hitbox:"Octane"},8807:{name:"Volkswagen Golf GTI RLE",hitbox:"Octane"},9053:{name:"Fast & Furious Dodge Charger SRT Hellcat",hitbox:"Dominus"},9084:{name:"Nissan Silvia",hitbox:"Hybrid"},9085:{name:"Nissan Silvia RLE",hitbox:"Hybrid"},9088:{name:"Porsche 911 Turbo",hitbox:"Dominus"},9089:{name:"Porsche 911 Turbo RLE",hitbox:"Dominus"},9140:{name:"Bumblebee",hitbox:"Dominus"},9357:{name:"Diesel",hitbox:"Breakout"},9388:{name:"Lightning McQueen",hitbox:"Dominus"},9427:{name:"Primo",hitbox:"Hybrid"},9894:{name:"Scorpion",hitbox:"Dominus"},10044:{name:"Beskar",hitbox:"Hybrid"},10094:{name:"Ford Mustang GTD",hitbox:"Dominus"},10440:{name:"Nissan Fairlady Z",hitbox:"Dominus"},10441:{name:"Nissan Fairlady Z RLE",hitbox:"Dominus"},10689:{name:"Behemoth",hitbox:"Merc"},10694:{name:"Lockjaw",hitbox:"Dominus"},10697:{name:"The Incredibile",hitbox:"Breakout"},10698:{name:"1966 Cadillac DeVille",hitbox:"Breakout"},10805:{name:"Nissan Skyline GT-R (R32)",hitbox:"Hybrid"},10817:{name:"Quadra Turbo-R",hitbox:"Breakout"},10822:{name:"McLaren Senna",hitbox:"Breakout"},10896:{name:"BMW 1 Series",hitbox:"Octane"},10897:{name:"BMW 1 Series RLE",hitbox:"Octane"},10900:{name:"Shokunin",hitbox:"Octane"},10901:{name:"Shokunin GXT",hitbox:"Octane"},11016:{name:"Porsche 911 GT3 RS",hitbox:"Dominus"},11038:{name:"Revolver",hitbox:"Breakout"},11095:{name:"Dodge Charger Daytona Scat Pack",hitbox:"Dominus"},11098:{name:"Turtle Van",hitbox:"Merc"},11138:{name:"Void Burn",hitbox:"Hybrid"},11141:{name:"Lamborghini Urus SE",hitbox:"Hybrid"},11314:{name:"Jeep Wrangler Rubicon",hitbox:"Merc"},11315:{name:"Ford Mustang Shelby GT500",hitbox:"Dominus"},11336:{name:"Dominus: Neon",hitbox:"Dominus"},11379:{name:"Ram 1500 RHO",hitbox:"Hybrid"},11394:{name:"Azura",hitbox:"Breakout"},11505:{name:"Breakout X",hitbox:"Breakout"},11534:{name:"BMW M3 (E30)",hitbox:"Dominus"},11603:{name:"Fennec ZR-F",hitbox:"Octane"},11677:{name:"Chevrolet Corvette ZR1",hitbox:"Breakout"},11736:{name:"Recoil AV",hitbox:"Merc"},11800:{name:"Megastar",hitbox:"Breakout"},11905:{name:"The Mystery Machine",hitbox:"Merc"},11932:{name:"Hearse",hitbox:"Hybrid"},11933:{name:"Porsche 918 Spyder",hitbox:"Breakout"},11941:{name:"Mercedes-AMG GT 63 S",hitbox:"Dominus"},11949:{name:"Pontiac Firebird",hitbox:"Breakout"},11950:{name:"Chevrolet Astro",hitbox:"Merc"},12142:{name:"Homer's Car",hitbox:"Dominus"},12173:{name:"Ferrari F40",hitbox:"Breakout"}},z1=B1;function Aw(n){const e=z1[String(n)];return e?{name:e.name,hitboxType:e.hitbox}:null}function H1(n){if(!n)return null;const e={fov:n.fov,height:n.height,angle:n.angle,distance:n.distance,stiffness:n.stiffness,swivelSpeed:n.swivel_speed};return n.transition_speed!=null&&(e.transitionSpeed=n.transition_speed),e}const V1=2200,G1=!0,$1=!1,W1=.15,X1=10,K1=.1,q1=10,Y1=.1,j1=.15,Z1=10;function Ho(n,e){if(n.length===0)return null;let t=0,i=n.length-1;if(e<=n[0].time)return n[0];if(e>=n[i].time)return n[i];for(;t>1;n[s].time<=e?t=s:i=s-1}return n[t]}class J1{position={x:0,y:0,z:0};rotation={x:0,y:0,z:0,w:1};velocity={x:0,y:0,z:0};angularVelocity={x:0,y:0,z:0};sleeping=!1;visible=!0}class Q1{constructor(e,t,i){this.isBig=e,this.position=t,this.events=i}isAvailable=!0}class eC extends Cw{constructor(e,t,i,s,a,r=null){super(),this.id=e,this.name=t,this.team=i,this.carName=s,this.hitboxType=a,this.cameraSettings=r}position={x:0,y:0,z:0};rotation={x:0,y:0,z:0,w:1};velocity={x:0,y:0,z:0};angularVelocity={x:0,y:0,z:0};sleeping=!1;steer=0;boost=0;isBoosting=!1;isSupersonic=!1;isKickoffReset=!1;isVisible=!0;isBallCam=!0}class Rw extends Cw{constructor(e,t={}){super(),this.raw=e,this.options=t,this._compile()}duration=0;playerList=[];frameTimes=[];rawStartTime=0;ball=new J1;players=new Map;boostPads=new Map;_currentTime=0;_ballTimeline=[];_playerTimelines={};_ballFlags=[];_playerFlags={};_playerCameraEvents={};_teams={};_timelineCompaction=null;_compile(){const e=this.raw.frame_data,t=this.raw.meta,i=e.metadata_frames,s=i[0]?.time??0;this.rawStartTime=s;const a=l=>Math.max(0,l-s);this.duration=i.length?a(i[i.length-1].time):0,this.frameTimes=i.map(l=>a(l.time));const r=new Map;t.team_zero.forEach(l=>r.set(this._idKey(l.remote_id),{info:l,team:0})),t.team_one.forEach(l=>r.set(this._idKey(l.remote_id),{info:l,team:1})),e.ball_data.frames.forEach((l,c)=>{if(l==="Empty"||!("Data"in l))return;const u=this._rbToKeyframe(l.Data.rigid_body,a(i[c]?.time??s),c);u&&this._ballTimeline.push(u)}),e.players.forEach(([l,c])=>{const u=this._idKey(l),d=r.get(u);let h=d?.info.name??null,f=d?.team??0;if(!h){for(const T of c.frames)if(T!=="Empty"&&"Data"in T&&T.Data.player_name){h=T.Data.player_name,T.Data.is_team_0!=null&&(f=T.Data.is_team_0?0:1);break}}h||(h=`Player_${u}`);const p=d?.info,g=p?.car_body_id!=null?Aw(p.car_body_id):null,_=p?.car_body_name??g?.name??"Octane",m=p?.car_hitbox_family??g?.hitboxType??"Octane",v=[],y=[];c.frames.forEach((T,x)=>{const M=a(i[x]?.time??s);if(T==="Empty"||!("Data"in T))return;const C=this._rbToKeyframe(T.Data.rigid_body,M,x);C&&v.push(C);const w=T.Data.input?.steer;y.push({time:M,boost:U1(T.Data.boost_amount??0),isBoosting:!!T.Data.boost_active,present:!0,steer:w==null?0:Math.max(-1,Math.min(1,(w-128)/128))})});const b=H1(p?.camera_settings);this._playerTimelines[h]=v,this._playerFlags[h]=y,this._teams[h]=f,this.playerList.push({id:u,name:h,team:f,carName:_,hitboxType:m,cameraSettings:b}),this.players.set(h,new eC(u,h,f,_,m,b))});const o=new Map;this.playerList.forEach(l=>o.set(l.id,l.name));for(const[l,c]of this.raw.player_camera_events??[]){const u=o.get(this._idKey(l));u&&(this._playerCameraEvents[u]=c.map(d=>({time:a(i[d.frame]?.time??s),ballCam:d.ball_cam_active})))}this._preprocessMotionTimelines(),this._compileBoostPads(),this.seek(0)}_timelineProcessingOptions(){return{motionSmoothing:this.options.motionSmoothing??G1,smoothingBlendFactor:this.options.smoothingBlendFactor??W1,smoothingAnchorInterval:this.options.smoothingAnchorInterval??X1,timelineCompaction:this.options.timelineCompaction??$1,disableFrameFiltering:this.options.disableFrameFiltering??!1}}_preprocessMotionTimelines(){const e=this._timelineProcessingOptions();e.motionSmoothing&&this._applyVelocityBasedPositionCorrection(e),e.timelineCompaction&&this._applyTimelineCompaction(),e.disableFrameFiltering||this._filterInconsistentFrames()}_applyTimelineCompaction(){const e=this._buildTimelineCompaction();!e||e.gaps.length===0&&e.prematchEndTime===null||(this._timelineCompaction=e,this._ballTimeline=this._compactTimeline(this._ballTimeline,e),Object.entries(this._playerTimelines).forEach(([t,i])=>{this._playerTimelines[t]=this._compactTimeline(i,e)}),Object.entries(this._playerFlags).forEach(([t,i])=>{this._playerFlags[t]=this._compactTimeline(i,e)}),this.frameTimes=this.frameTimes.map(t=>this._compactTime(t,e)),this.duration=e.compactedDuration)}_buildTimelineCompaction(){if(this.frameTimes.length===0)return null;const e=this._detectPostGoalTimeGaps(),t=this._detectFirstKickoffGoTime(),i=t==null?null:Vo(t,e),a=e.reduce((r,o)=>r+o.duration,0)+(i??0);return a<=0?null:{gaps:e,prematchEndTime:i,removedDuration:a,compactedDuration:Math.max(0,this.duration-a)}}_detectPostGoalTimeGaps(){const e=[];for(const t of this.raw.goal_events??[]){const i=t.frame;if(!Number.isInteger(i)||i<0||i>=this.frameTimes.length)continue;const s=this.frameTimes[i];for(let a=i+1;a10)break;const l=o-r;if(l>.3){e.push({beforeFrame:a-1,afterFrame:a,beforeTime:r,afterTime:o,duration:l});break}}}return e}_detectFirstKickoffGoTime(){const e=this.raw.frame_data.metadata_frames;let t=!1;for(let s=0;s0&&(t=!0),t&&a===0)return this.frameTimes[s]??null}const i=e.findIndex(s=>s.replicated_game_state_name===54);return i===-1?null:this.frameTimes[i]??null}_compactTimeline(e,t){const i=this._remapReplayGaps(e,t.gaps);return t.prematchEndTime===null?i:this._remapPrematch(i,t.prematchEndTime)}_remapReplayGaps(e,t){if(t.length===0)return e;const i=[];t.forEach((a,r)=>{const o=e.find(l=>l.time>=a.afterTime);o&&i.push({...o,time:Vo(a.afterTime,t.slice(0,r+1))})});const s=e.filter(a=>!gy(a.time,t)).map(a=>({...a,time:Vo(a.time,t)}));for(const a of i){if(s.some(o=>Math.abs(o.time-a.time)<.001))continue;let r=s.findIndex(o=>o.time>a.time);r===-1&&(r=s.length),s.splice(r,0,a)}return s}_remapPrematch(e,t){let i=null;for(const a of e)if(a.timea.time>=t).map(a=>({...a,time:a.time-t}));return i&&(s.length===0||s[0].time>.001)&&s.unshift({...i,time:0}),s}_compactTime(e,t){const i=Vo(e,t.gaps);return t.prematchEndTime===null?i:Math.max(0,i-t.prematchEndTime)}_applyVelocityBasedPositionCorrection(e){const t=i=>{if(i.length<3)return;let s=0;for(;s=i.length-1)return;let a={...i[s].position};for(let r=s+1;rK1){a={...l.position};continue}if(_y(a,l.position)>q1){a={...l.position};continue}const u={x:(o.velocity.x+l.velocity.x)/2,y:(o.velocity.y+l.velocity.y)/2,z:(o.velocity.z+l.velocity.z)/2},d={x:a.x+u.x*c,y:a.y+u.y*c,z:a.z+u.z*c},h=(r-s)%e.smoothingAnchorInterval===0?.5:e.smoothingBlendFactor;a={x:d.x*(1-h)+l.position.x*h,y:d.y*(1-h)+l.position.y*h,z:d.z*(1-h)+l.position.z*h},l.position={...a}}};t(this._ballTimeline),Object.values(this._playerTimelines).forEach(t)}_filterInconsistentFrames(){this._ballTimeline=this._filterInconsistentTimeline(this._ballTimeline),Object.entries(this._playerTimelines).forEach(([e,t])=>{this._playerTimelines[e]=this._filterInconsistentTimeline(t)})}_filterInconsistentTimeline(e){if(e.length<2)return e;const t=[e[0]];let i=0;for(let s=1;s.001){const u=o*c,d=_y(r.position,a.position),h=Math.abs(d-u)/u;if(Number.isFinite(h)&&h>j1)continue}}t.push(a),i=s}return t}_compileBoostPads(){const e=new Map;(this.raw.boost_pad_events??[]).forEach(t=>{const i=t.kind==="Available"?!0:t.kind&&typeof t.kind=="object"&&"PickedUp"in t.kind?!1:null;if(i===null)return;const s=Math.max(0,t.time-this.rawStartTime);if(this._timelineCompaction&&this._isRemovedByTimelineCompaction(s))return;const a=this._timelineCompaction?this._compactTime(s,this._timelineCompaction):s,r=e.get(t.pad_id);r?r.push({time:a,available:i}):e.set(t.pad_id,[{time:a,available:i}])}),(this.raw.boost_pads??[]).forEach(t=>{const i=(t.pad_id?e.get(t.pad_id):void 0)??[];i.sort((s,a)=>s.time-a.time),this.boostPads.set(t.index,new Q1(t.size==="Big",t.position,i))})}_rbToKeyframe(e,t,i){const s=vf(e.location);return s?{time:t,frame:i,position:s,rotation:N1(e.rotation),velocity:vf(e.linear_velocity)??{x:0,y:0,z:0},angularVelocity:vf(e.angular_velocity),sleeping:!!e.sleeping}:null}_isRemovedByTimelineCompaction(e){const t=this._timelineCompaction;if(!t)return!1;if(gy(e,t.gaps))return!0;const i=Vo(e,t.gaps);return t.prematchEndTime!==null&&i=V1}const r=Ho(this._playerFlags[i]??[],e);r&&(s.boost=r.boost,s.isBoosting=r.isBoosting,s.steer=r.steer);const o=Ho(this._playerCameraEvents[i]??[],e);o&&o.ballCam!=null&&(s.isBallCam=o.ballCam);const l=this._playerTimelines[i]??[];s.isVisible=l.length>0&&e>=l[0].time-.001&&e<=l[l.length-1].time+1}for(const i of this.boostPads.values()){if(i.events.length===0)continue;const s=Ho(i.events,e);i.isAvailable=s&&s.time<=e?s.available:!0}}frameIndexAt(e){const t=this.frameTimes;if(t.length===0||e<=t[0])return 0;let i=0,s=t.length-1;if(e>=t[s])return s;for(;i>1;t[a]<=e?i=a:s=a-1}return i}getBall(){return this.ball}getPlayer(e){return this.players.get(e)}getPlayerById(e){for(const t of this.players.values())if(t.id===e)return t}getAllPlayers(){return Array.from(this.players.values())}getPlayerTeams(){return{...this._teams}}getGameTimeMap(){return[]}getCountdownEvents(){return[]}getPlayerStatsTimelines(){return{}}getGameEventTimeline(){return[]}getAdvancedStats(){return null}getEvents(){return[]}getEventsInRange(){return[]}getTextOverlaysAt(){return[]}getGamePhaseAt(){return null}}function my(n){return Math.sqrt(n.x*n.x+n.y*n.y+n.z*n.z)}function _y(n,e){const t=e.x-n.x,i=e.y-n.y,s=e.z-n.z;return Math.sqrt(t*t+i*i+s*s)}function Vo(n,e){let t=0;for(const i of e){if(n=i.afterTime){t+=i.duration;continue}return i.beforeTime-t}return n-t}function gy(n,e){return e.some(t=>n>t.beforeTime&&n>8&255]+Mn[n>>16&255]+Mn[n>>24&255]+"-"+Mn[e&255]+Mn[e>>8&255]+"-"+Mn[e>>16&15|64]+Mn[e>>24&255]+"-"+Mn[t&63|128]+Mn[t>>8&255]+"-"+Mn[t>>16&255]+Mn[t>>24&255]+Mn[i&255]+Mn[i>>8&255]+Mn[i>>16&255]+Mn[i>>24&255]).toLowerCase()}function Ze(n,e,t){return Math.max(e,Math.min(t,n))}function sg(n,e){return(n%e+e)%e}function FC(n,e,t,i,s){return i+(n-e)*(s-i)/(t-e)}function NC(n,e,t){return n!==e?(t-n)/(e-n):0}function Il(n,e,t){return(1-t)*n+t*e}function UC(n,e,t,i){return Il(n,e,1-Math.exp(-t*i))}function BC(n,e=1){return e-Math.abs(sg(n,e*2)-e)}function zC(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*(3-2*n))}function HC(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*n*(n*(n*6-15)+10))}function VC(n,e){return n+Math.floor(Math.random()*(e-n+1))}function GC(n,e){return n+Math.random()*(e-n)}function $C(n){return n*(.5-Math.random())}function WC(n){n!==void 0&&(yy=n);let e=yy+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function XC(n){return n*ir}function KC(n){return n*Co}function qC(n){return(n&n-1)===0&&n!==0}function YC(n){return Math.pow(2,Math.ceil(Math.log(n)/Math.LN2))}function jC(n){return Math.pow(2,Math.floor(Math.log(n)/Math.LN2))}function ZC(n,e,t,i,s){const a=Math.cos,r=Math.sin,o=a(t/2),l=r(t/2),c=a((e+i)/2),u=r((e+i)/2),d=a((e-i)/2),h=r((e-i)/2),f=a((i-e)/2),p=r((i-e)/2);switch(s){case"XYX":n.set(o*u,l*d,l*h,o*c);break;case"YZY":n.set(l*h,o*u,l*d,o*c);break;case"ZXZ":n.set(l*d,l*h,o*u,o*c);break;case"XZX":n.set(o*u,l*p,l*f,o*c);break;case"YXY":n.set(l*f,o*u,l*p,o*c);break;case"ZYZ":n.set(l*p,l*f,o*u,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+s)}}function zn(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return n/4294967295;case Uint16Array:return n/65535;case Uint8Array:return n/255;case Int32Array:return Math.max(n/2147483647,-1);case Int16Array:return Math.max(n/32767,-1);case Int8Array:return Math.max(n/127,-1);default:throw new Error("Invalid component type.")}}function ut(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return Math.round(n*4294967295);case Uint16Array:return Math.round(n*65535);case Uint8Array:return Math.round(n*255);case Int32Array:return Math.round(n*2147483647);case Int16Array:return Math.round(n*32767);case Int8Array:return Math.round(n*127);default:throw new Error("Invalid component type.")}}const vt={DEG2RAD:ir,RAD2DEG:Co,generateUUID:pi,clamp:Ze,euclideanModulo:sg,mapLinear:FC,inverseLerp:NC,lerp:Il,damp:UC,pingpong:BC,smoothstep:zC,smootherstep:HC,randInt:VC,randFloat:GC,randFloatSpread:$C,seededRandom:WC,degToRad:XC,radToDeg:KC,isPowerOfTwo:qC,ceilPowerOfTwo:YC,floorPowerOfTwo:jC,setQuaternionFromProperEuler:ZC,normalize:ut,denormalize:zn};class te{constructor(e=0,t=0){te.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,i=this.y,s=e.elements;return this.x=s[0]*t+s[3]*i+s[6],this.y=s[1]*t+s[4]*i+s[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Ze(this.x,e.x,t.x),this.y=Ze(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Ze(this.x,e,t),this.y=Ze(this.y,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Ze(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Ze(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),s=Math.sin(t),a=this.x-e.x,r=this.y-e.y;return this.x=a*i-r*s+e.x,this.y=a*s+r*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class dt{constructor(e=0,t=0,i=0,s=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=s}static slerpFlat(e,t,i,s,a,r,o){let l=i[s+0],c=i[s+1],u=i[s+2],d=i[s+3];const h=a[r+0],f=a[r+1],p=a[r+2],g=a[r+3];if(o===0){e[t+0]=l,e[t+1]=c,e[t+2]=u,e[t+3]=d;return}if(o===1){e[t+0]=h,e[t+1]=f,e[t+2]=p,e[t+3]=g;return}if(d!==g||l!==h||c!==f||u!==p){let _=1-o;const m=l*h+c*f+u*p+d*g,v=m>=0?1:-1,y=1-m*m;if(y>Number.EPSILON){const T=Math.sqrt(y),x=Math.atan2(T,m*v);_=Math.sin(_*x)/T,o=Math.sin(o*x)/T}const b=o*v;if(l=l*_+h*b,c=c*_+f*b,u=u*_+p*b,d=d*_+g*b,_===1-o){const T=1/Math.sqrt(l*l+c*c+u*u+d*d);l*=T,c*=T,u*=T,d*=T}}e[t]=l,e[t+1]=c,e[t+2]=u,e[t+3]=d}static multiplyQuaternionsFlat(e,t,i,s,a,r){const o=i[s],l=i[s+1],c=i[s+2],u=i[s+3],d=a[r],h=a[r+1],f=a[r+2],p=a[r+3];return e[t]=o*p+u*d+l*f-c*h,e[t+1]=l*p+u*h+c*d-o*f,e[t+2]=c*p+u*f+o*h-l*d,e[t+3]=u*p-o*d-l*h-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,i,s){return this._x=e,this._y=t,this._z=i,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const i=e._x,s=e._y,a=e._z,r=e._order,o=Math.cos,l=Math.sin,c=o(i/2),u=o(s/2),d=o(a/2),h=l(i/2),f=l(s/2),p=l(a/2);switch(r){case"XYZ":this._x=h*u*d+c*f*p,this._y=c*f*d-h*u*p,this._z=c*u*p+h*f*d,this._w=c*u*d-h*f*p;break;case"YXZ":this._x=h*u*d+c*f*p,this._y=c*f*d-h*u*p,this._z=c*u*p-h*f*d,this._w=c*u*d+h*f*p;break;case"ZXY":this._x=h*u*d-c*f*p,this._y=c*f*d+h*u*p,this._z=c*u*p+h*f*d,this._w=c*u*d-h*f*p;break;case"ZYX":this._x=h*u*d-c*f*p,this._y=c*f*d+h*u*p,this._z=c*u*p-h*f*d,this._w=c*u*d+h*f*p;break;case"YZX":this._x=h*u*d+c*f*p,this._y=c*f*d+h*u*p,this._z=c*u*p-h*f*d,this._w=c*u*d-h*f*p;break;case"XZY":this._x=h*u*d-c*f*p,this._y=c*f*d-h*u*p,this._z=c*u*p+h*f*d,this._w=c*u*d+h*f*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+r)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const i=t/2,s=Math.sin(i);return this._x=e.x*s,this._y=e.y*s,this._z=e.z*s,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],s=t[4],a=t[8],r=t[1],o=t[5],l=t[9],c=t[2],u=t[6],d=t[10],h=i+o+d;if(h>0){const f=.5/Math.sqrt(h+1);this._w=.25/f,this._x=(u-l)*f,this._y=(a-c)*f,this._z=(r-s)*f}else if(i>o&&i>d){const f=2*Math.sqrt(1+i-o-d);this._w=(u-l)/f,this._x=.25*f,this._y=(s+r)/f,this._z=(a+c)/f}else if(o>d){const f=2*Math.sqrt(1+o-i-d);this._w=(a-c)/f,this._x=(s+r)/f,this._y=.25*f,this._z=(l+u)/f}else{const f=2*Math.sqrt(1+d-i-o);this._w=(r-s)/f,this._x=(a+c)/f,this._y=(l+u)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<1e-8?(i=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Ze(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(i===0)return this;const s=Math.min(1,t/i);return this.slerp(e,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const i=e._x,s=e._y,a=e._z,r=e._w,o=t._x,l=t._y,c=t._z,u=t._w;return this._x=i*u+r*o+s*c-a*l,this._y=s*u+r*l+a*o-i*c,this._z=a*u+r*c+i*l-s*o,this._w=r*u-i*o-s*l-a*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const i=this._x,s=this._y,a=this._z,r=this._w;let o=r*e._w+i*e._x+s*e._y+a*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=r,this._x=i,this._y=s,this._z=a,this;const l=1-o*o;if(l<=Number.EPSILON){const f=1-t;return this._w=f*r+t*this._w,this._x=f*i+t*this._x,this._y=f*s+t*this._y,this._z=f*a+t*this._z,this.normalize(),this}const c=Math.sqrt(l),u=Math.atan2(c,o),d=Math.sin((1-t)*u)/c,h=Math.sin(t*u)/c;return this._w=r*d+this._w*h,this._x=i*d+this._x*h,this._y=s*d+this._y*h,this._z=a*d+this._z*h,this._onChangeCallback(),this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),s=Math.sqrt(1-i),a=Math.sqrt(i);return this.set(s*Math.sin(e),s*Math.cos(e),a*Math.sin(t),a*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class S{constructor(e=0,t=0,i=0){S.prototype.isVector3=!0,this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(vy.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(vy.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,s=this.z,a=e.elements;return this.x=a[0]*t+a[3]*i+a[6]*s,this.y=a[1]*t+a[4]*i+a[7]*s,this.z=a[2]*t+a[5]*i+a[8]*s,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,s=this.z,a=e.elements,r=1/(a[3]*t+a[7]*i+a[11]*s+a[15]);return this.x=(a[0]*t+a[4]*i+a[8]*s+a[12])*r,this.y=(a[1]*t+a[5]*i+a[9]*s+a[13])*r,this.z=(a[2]*t+a[6]*i+a[10]*s+a[14])*r,this}applyQuaternion(e){const t=this.x,i=this.y,s=this.z,a=e.x,r=e.y,o=e.z,l=e.w,c=2*(r*s-o*i),u=2*(o*t-a*s),d=2*(a*i-r*t);return this.x=t+l*c+r*d-o*u,this.y=i+l*u+o*c-a*d,this.z=s+l*d+a*u-r*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,i=this.y,s=this.z,a=e.elements;return this.x=a[0]*t+a[4]*i+a[8]*s,this.y=a[1]*t+a[5]*i+a[9]*s,this.z=a[2]*t+a[6]*i+a[10]*s,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Ze(this.x,e.x,t.x),this.y=Ze(this.y,e.y,t.y),this.z=Ze(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Ze(this.x,e,t),this.y=Ze(this.y,e,t),this.z=Ze(this.z,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Ze(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const i=e.x,s=e.y,a=e.z,r=t.x,o=t.y,l=t.z;return this.x=s*l-a*o,this.y=a*r-i*l,this.z=i*o-s*r,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return bf.copy(this).projectOnVector(e),this.sub(bf)}reflect(e){return this.sub(bf.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Ze(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,s=this.z-e.z;return t*t+i*i+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){const s=Math.sin(t)*e;return this.x=s*Math.sin(i),this.y=Math.cos(t)*e,this.z=s*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),s=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=s,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(e),this.y=t,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const bf=new S,vy=new dt;class at{constructor(e,t,i,s,a,r,o,l,c){at.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,s,a,r,o,l,c)}set(e,t,i,s,a,r,o,l,c){const u=this.elements;return u[0]=e,u[1]=s,u[2]=o,u[3]=t,u[4]=a,u[5]=l,u[6]=i,u[7]=r,u[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,s=t.elements,a=this.elements,r=i[0],o=i[3],l=i[6],c=i[1],u=i[4],d=i[7],h=i[2],f=i[5],p=i[8],g=s[0],_=s[3],m=s[6],v=s[1],y=s[4],b=s[7],T=s[2],x=s[5],M=s[8];return a[0]=r*g+o*v+l*T,a[3]=r*_+o*y+l*x,a[6]=r*m+o*b+l*M,a[1]=c*g+u*v+d*T,a[4]=c*_+u*y+d*x,a[7]=c*m+u*b+d*M,a[2]=h*g+f*v+p*T,a[5]=h*_+f*y+p*x,a[8]=h*m+f*b+p*M,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[1],s=e[2],a=e[3],r=e[4],o=e[5],l=e[6],c=e[7],u=e[8];return t*r*u-t*o*c-i*a*u+i*o*l+s*a*c-s*r*l}invert(){const e=this.elements,t=e[0],i=e[1],s=e[2],a=e[3],r=e[4],o=e[5],l=e[6],c=e[7],u=e[8],d=u*r-o*c,h=o*l-u*a,f=c*a-r*l,p=t*d+i*h+s*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);const g=1/p;return e[0]=d*g,e[1]=(s*c-u*i)*g,e[2]=(o*i-s*r)*g,e[3]=h*g,e[4]=(u*t-s*l)*g,e[5]=(s*a-o*t)*g,e[6]=f*g,e[7]=(i*l-c*t)*g,e[8]=(r*t-i*a)*g,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,s,a,r,o){const l=Math.cos(a),c=Math.sin(a);return this.set(i*l,i*c,-i*(l*r+c*o)+r+e,-s*c,s*l,-s*(-c*r+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(xf.makeScale(e,t)),this}rotate(e){return this.premultiply(xf.makeRotation(-e)),this}translate(e,t){return this.premultiply(xf.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,i=e.elements;for(let s=0;s<9;s++)if(t[s]!==i[s])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const xf=new at;function gS(n){for(let e=n.length-1;e>=0;--e)if(n[e]>=65535)return!0;return!1}const JC={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function Zr(n,e){return new JC[n](e)}function Wl(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}function yS(){const n=Wl("canvas");return n.style.display="block",n}const by={};function Xl(n){n in by||(by[n]=!0,console.warn(n))}function QC(n,e,t){return new Promise(function(i,s){function a(){switch(n.clientWaitSync(e,n.SYNC_FLUSH_COMMANDS_BIT,0)){case n.WAIT_FAILED:s();break;case n.TIMEOUT_EXPIRED:setTimeout(a,t);break;default:i()}}setTimeout(a,t)})}const xy=new at().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),wy=new at().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function eA(){const n={enabled:!0,workingColorSpace:xn,spaces:{},convert:function(s,a,r){return this.enabled===!1||a===r||!a||!r||(this.spaces[a].transfer===Pt&&(s.r=Fs(s.r),s.g=Fs(s.g),s.b=Fs(s.b)),this.spaces[a].primaries!==this.spaces[r].primaries&&(s.applyMatrix3(this.spaces[a].toXYZ),s.applyMatrix3(this.spaces[r].fromXYZ)),this.spaces[r].transfer===Pt&&(s.r=io(s.r),s.g=io(s.g),s.b=io(s.b))),s},workingToColorSpace:function(s,a){return this.convert(s,this.workingColorSpace,a)},colorSpaceToWorking:function(s,a){return this.convert(s,a,this.workingColorSpace)},getPrimaries:function(s){return this.spaces[s].primaries},getTransfer:function(s){return s===Ls?Gl:this.spaces[s].transfer},getToneMappingMode:function(s){return this.spaces[s].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(s,a=this.workingColorSpace){return s.fromArray(this.spaces[a].luminanceCoefficients)},define:function(s){Object.assign(this.spaces,s)},_getMatrix:function(s,a,r){return s.copy(this.spaces[a].toXYZ).multiply(this.spaces[r].fromXYZ)},_getDrawingBufferColorSpace:function(s){return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(s=this.workingColorSpace){return this.spaces[s].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(s,a){return Xl("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),n.workingToColorSpace(s,a)},toWorkingColorSpace:function(s,a){return Xl("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),n.colorSpaceToWorking(s,a)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],i=[.3127,.329];return n.define({[xn]:{primaries:e,whitePoint:i,transfer:Gl,toXYZ:xy,fromXYZ:wy,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:gt},outputColorSpaceConfig:{drawingBufferColorSpace:gt}},[gt]:{primaries:e,whitePoint:i,transfer:Pt,toXYZ:xy,fromXYZ:wy,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:gt}}}),n}const rt=eA();function Fs(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function io(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}let vr;class vS{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{vr===void 0&&(vr=Wl("canvas")),vr.width=e.width,vr.height=e.height;const s=vr.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),i=vr}return i.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=Wl("canvas");t.width=e.width,t.height=e.height;const i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const s=i.getImageData(0,0,e.width,e.height),a=s.data;for(let r=0;r1),this.pmremVersion=0}get width(){return this.source.getSize(Sf).x}get height(){return this.source.getSize(Sf).y}get depth(){return this.source.getSize(Sf).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const i=e[t];if(i===void 0){console.warn(`THREE.Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){console.warn(`THREE.Texture.setValues(): property '${t}' does not exist.`);continue}s&&i&&s.isVector2&&i.isVector2||s&&i&&s.isVector3&&i.isVector3||s&&i&&s.isMatrix3&&i.isMatrix3?s.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),t||(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==xh)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case ps:e.x=e.x-Math.floor(e.x);break;case Hn:e.x=e.x<0?0:1;break;case bo:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case ps:e.y=e.y-Math.floor(e.y);break;case Hn:e.y=e.y<0?0:1;break;case bo:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}Bt.DEFAULT_IMAGE=null;Bt.DEFAULT_MAPPING=xh;Bt.DEFAULT_ANISOTROPY=1;class qe{constructor(e=0,t=0,i=0,s=1){qe.prototype.isVector4=!0,this.x=e,this.y=t,this.z=i,this.w=s}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,s=this.z,a=this.w,r=e.elements;return this.x=r[0]*t+r[4]*i+r[8]*s+r[12]*a,this.y=r[1]*t+r[5]*i+r[9]*s+r[13]*a,this.z=r[2]*t+r[6]*i+r[10]*s+r[14]*a,this.w=r[3]*t+r[7]*i+r[11]*s+r[15]*a,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,i,s,a;const l=e.elements,c=l[0],u=l[4],d=l[8],h=l[1],f=l[5],p=l[9],g=l[2],_=l[6],m=l[10];if(Math.abs(u-h)<.01&&Math.abs(d-g)<.01&&Math.abs(p-_)<.01){if(Math.abs(u+h)<.1&&Math.abs(d+g)<.1&&Math.abs(p+_)<.1&&Math.abs(c+f+m-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const y=(c+1)/2,b=(f+1)/2,T=(m+1)/2,x=(u+h)/4,M=(d+g)/4,C=(p+_)/4;return y>b&&y>T?y<.01?(i=0,s=.707106781,a=.707106781):(i=Math.sqrt(y),s=x/i,a=M/i):b>T?b<.01?(i=.707106781,s=0,a=.707106781):(s=Math.sqrt(b),i=x/s,a=C/s):T<.01?(i=.707106781,s=.707106781,a=0):(a=Math.sqrt(T),i=M/a,s=C/a),this.set(i,s,a,t),this}let v=Math.sqrt((_-p)*(_-p)+(d-g)*(d-g)+(h-u)*(h-u));return Math.abs(v)<.001&&(v=1),this.x=(_-p)/v,this.y=(d-g)/v,this.z=(h-u)/v,this.w=Math.acos((c+f+m-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Ze(this.x,e.x,t.x),this.y=Ze(this.y,e.y,t.y),this.z=Ze(this.z,e.z,t.z),this.w=Ze(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Ze(this.x,e,t),this.y=Ze(this.y,e,t),this.z=Ze(this.z,e,t),this.w=Ze(this.w,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Ze(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class ag extends gs{constructor(e=1,t=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Vt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},i),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=i.depth,this.scissor=new qe(0,0,e,t),this.scissorTest=!1,this.viewport=new qe(0,0,e,t);const s={width:e,height:t,depth:i.depth},a=new Bt(s);this.textures=[];const r=i.count;for(let o=0;o1;this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,i=e.textures.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Li),Li.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Go),wc.subVectors(this.max,Go),br.subVectors(e.a,Go),xr.subVectors(e.b,Go),wr.subVectors(e.c,Go),Vs.subVectors(xr,br),Gs.subVectors(wr,xr),ya.subVectors(br,wr);let t=[0,-Vs.z,Vs.y,0,-Gs.z,Gs.y,0,-ya.z,ya.y,Vs.z,0,-Vs.x,Gs.z,0,-Gs.x,ya.z,0,-ya.x,-Vs.y,Vs.x,0,-Gs.y,Gs.x,0,-ya.y,ya.x,0];return!Tf(t,br,xr,wr,wc)||(t=[1,0,0,0,1,0,0,0,1],!Tf(t,br,xr,wr,wc))?!1:(Sc.crossVectors(Vs,Gs),t=[Sc.x,Sc.y,Sc.z],Tf(t,br,xr,wr,wc))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Li).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Li).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(vs[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),vs[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),vs[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),vs[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),vs[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),vs[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),vs[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),vs[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(vs),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const vs=[new S,new S,new S,new S,new S,new S,new S,new S],Li=new S,xc=new vn,br=new S,xr=new S,wr=new S,Vs=new S,Gs=new S,ya=new S,Go=new S,wc=new S,Sc=new S,va=new S;function Tf(n,e,t,i,s){for(let a=0,r=n.length-3;a<=r;a+=3){va.fromArray(n,a);const o=s.x*Math.abs(va.x)+s.y*Math.abs(va.y)+s.z*Math.abs(va.z),l=e.dot(va),c=t.dot(va),u=i.dot(va);if(Math.max(-Math.max(l,c,u),Math.min(l,c,u))>o)return!1}return!0}const aA=new vn,$o=new S,Mf=new S;class bn{constructor(e=new S,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const i=this.center;t!==void 0?i.copy(t):aA.setFromPoints(e).getCenter(i);let s=0;for(let a=0,r=e.length;athis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;$o.subVectors(e,this.center);const t=$o.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),s=(i-this.radius)*.5;this.center.addScaledVector($o,s/i),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(Mf.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint($o.copy(e.center).add(Mf)),this.expandByPoint($o.copy(e.center).sub(Mf))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}const bs=new S,Ef=new S,Tc=new S,$s=new S,Cf=new S,Mc=new S,Af=new S;class pr{constructor(e=new S,t=new S(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,bs)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=bs.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(bs.copy(this.origin).addScaledVector(this.direction,t),bs.distanceToSquared(e))}distanceSqToSegment(e,t,i,s){Ef.copy(e).add(t).multiplyScalar(.5),Tc.copy(t).sub(e).normalize(),$s.copy(this.origin).sub(Ef);const a=e.distanceTo(t)*.5,r=-this.direction.dot(Tc),o=$s.dot(this.direction),l=-$s.dot(Tc),c=$s.lengthSq(),u=Math.abs(1-r*r);let d,h,f,p;if(u>0)if(d=r*l-o,h=r*o-l,p=a*u,d>=0)if(h>=-p)if(h<=p){const g=1/u;d*=g,h*=g,f=d*(d+r*h+2*o)+h*(r*d+h+2*l)+c}else h=a,d=Math.max(0,-(r*h+o)),f=-d*d+h*(h+2*l)+c;else h=-a,d=Math.max(0,-(r*h+o)),f=-d*d+h*(h+2*l)+c;else h<=-p?(d=Math.max(0,-(-r*a+o)),h=d>0?-a:Math.min(Math.max(-a,-l),a),f=-d*d+h*(h+2*l)+c):h<=p?(d=0,h=Math.min(Math.max(-a,-l),a),f=h*(h+2*l)+c):(d=Math.max(0,-(r*a+o)),h=d>0?a:Math.min(Math.max(-a,-l),a),f=-d*d+h*(h+2*l)+c);else h=r>0?-a:a,d=Math.max(0,-(r*h+o)),f=-d*d+h*(h+2*l)+c;return i&&i.copy(this.origin).addScaledVector(this.direction,d),s&&s.copy(Ef).addScaledVector(Tc,h),f}intersectSphere(e,t){bs.subVectors(e.center,this.origin);const i=bs.dot(this.direction),s=bs.dot(bs)-i*i,a=e.radius*e.radius;if(s>a)return null;const r=Math.sqrt(a-s),o=i-r,l=i+r;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,s,a,r,o,l;const c=1/this.direction.x,u=1/this.direction.y,d=1/this.direction.z,h=this.origin;return c>=0?(i=(e.min.x-h.x)*c,s=(e.max.x-h.x)*c):(i=(e.max.x-h.x)*c,s=(e.min.x-h.x)*c),u>=0?(a=(e.min.y-h.y)*u,r=(e.max.y-h.y)*u):(a=(e.max.y-h.y)*u,r=(e.min.y-h.y)*u),i>r||a>s||((a>i||isNaN(i))&&(i=a),(r=0?(o=(e.min.z-h.z)*d,l=(e.max.z-h.z)*d):(o=(e.max.z-h.z)*d,l=(e.min.z-h.z)*d),i>l||o>s)||((o>i||i!==i)&&(i=o),(l=0?i:s,t)}intersectsBox(e){return this.intersectBox(e,bs)!==null}intersectTriangle(e,t,i,s,a){Cf.subVectors(t,e),Mc.subVectors(i,e),Af.crossVectors(Cf,Mc);let r=this.direction.dot(Af),o;if(r>0){if(s)return null;o=1}else if(r<0)o=-1,r=-r;else return null;$s.subVectors(this.origin,e);const l=o*this.direction.dot(Mc.crossVectors($s,Mc));if(l<0)return null;const c=o*this.direction.dot(Cf.cross($s));if(c<0||l+c>r)return null;const u=-o*$s.dot(Af);return u<0?null:this.at(u/r,a)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Me{constructor(e,t,i,s,a,r,o,l,c,u,d,h,f,p,g,_){Me.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,i,s,a,r,o,l,c,u,d,h,f,p,g,_)}set(e,t,i,s,a,r,o,l,c,u,d,h,f,p,g,_){const m=this.elements;return m[0]=e,m[4]=t,m[8]=i,m[12]=s,m[1]=a,m[5]=r,m[9]=o,m[13]=l,m[2]=c,m[6]=u,m[10]=d,m[14]=h,m[3]=f,m[7]=p,m[11]=g,m[15]=_,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Me().fromArray(this.elements)}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(e){const t=this.elements,i=e.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,i){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(e,t,i){return this.set(e.x,t.x,i.x,0,e.y,t.y,i.y,0,e.z,t.z,i.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,i=e.elements,s=1/Sr.setFromMatrixColumn(e,0).length(),a=1/Sr.setFromMatrixColumn(e,1).length(),r=1/Sr.setFromMatrixColumn(e,2).length();return t[0]=i[0]*s,t[1]=i[1]*s,t[2]=i[2]*s,t[3]=0,t[4]=i[4]*a,t[5]=i[5]*a,t[6]=i[6]*a,t[7]=0,t[8]=i[8]*r,t[9]=i[9]*r,t[10]=i[10]*r,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,i=e.x,s=e.y,a=e.z,r=Math.cos(i),o=Math.sin(i),l=Math.cos(s),c=Math.sin(s),u=Math.cos(a),d=Math.sin(a);if(e.order==="XYZ"){const h=r*u,f=r*d,p=o*u,g=o*d;t[0]=l*u,t[4]=-l*d,t[8]=c,t[1]=f+p*c,t[5]=h-g*c,t[9]=-o*l,t[2]=g-h*c,t[6]=p+f*c,t[10]=r*l}else if(e.order==="YXZ"){const h=l*u,f=l*d,p=c*u,g=c*d;t[0]=h+g*o,t[4]=p*o-f,t[8]=r*c,t[1]=r*d,t[5]=r*u,t[9]=-o,t[2]=f*o-p,t[6]=g+h*o,t[10]=r*l}else if(e.order==="ZXY"){const h=l*u,f=l*d,p=c*u,g=c*d;t[0]=h-g*o,t[4]=-r*d,t[8]=p+f*o,t[1]=f+p*o,t[5]=r*u,t[9]=g-h*o,t[2]=-r*c,t[6]=o,t[10]=r*l}else if(e.order==="ZYX"){const h=r*u,f=r*d,p=o*u,g=o*d;t[0]=l*u,t[4]=p*c-f,t[8]=h*c+g,t[1]=l*d,t[5]=g*c+h,t[9]=f*c-p,t[2]=-c,t[6]=o*l,t[10]=r*l}else if(e.order==="YZX"){const h=r*l,f=r*c,p=o*l,g=o*c;t[0]=l*u,t[4]=g-h*d,t[8]=p*d+f,t[1]=d,t[5]=r*u,t[9]=-o*u,t[2]=-c*u,t[6]=f*d+p,t[10]=h-g*d}else if(e.order==="XZY"){const h=r*l,f=r*c,p=o*l,g=o*c;t[0]=l*u,t[4]=-d,t[8]=c*u,t[1]=h*d+g,t[5]=r*u,t[9]=f*d-p,t[2]=p*d-f,t[6]=o*u,t[10]=g*d+h}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(rA,e,oA)}lookAt(e,t,i){const s=this.elements;return li.subVectors(e,t),li.lengthSq()===0&&(li.z=1),li.normalize(),Ws.crossVectors(i,li),Ws.lengthSq()===0&&(Math.abs(i.z)===1?li.x+=1e-4:li.z+=1e-4,li.normalize(),Ws.crossVectors(i,li)),Ws.normalize(),Ec.crossVectors(li,Ws),s[0]=Ws.x,s[4]=Ec.x,s[8]=li.x,s[1]=Ws.y,s[5]=Ec.y,s[9]=li.y,s[2]=Ws.z,s[6]=Ec.z,s[10]=li.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,s=t.elements,a=this.elements,r=i[0],o=i[4],l=i[8],c=i[12],u=i[1],d=i[5],h=i[9],f=i[13],p=i[2],g=i[6],_=i[10],m=i[14],v=i[3],y=i[7],b=i[11],T=i[15],x=s[0],M=s[4],C=s[8],w=s[12],E=s[1],R=s[5],k=s[9],O=s[13],D=s[2],U=s[6],F=s[10],W=s[14],H=s[3],ne=s[7],oe=s[11],pe=s[15];return a[0]=r*x+o*E+l*D+c*H,a[4]=r*M+o*R+l*U+c*ne,a[8]=r*C+o*k+l*F+c*oe,a[12]=r*w+o*O+l*W+c*pe,a[1]=u*x+d*E+h*D+f*H,a[5]=u*M+d*R+h*U+f*ne,a[9]=u*C+d*k+h*F+f*oe,a[13]=u*w+d*O+h*W+f*pe,a[2]=p*x+g*E+_*D+m*H,a[6]=p*M+g*R+_*U+m*ne,a[10]=p*C+g*k+_*F+m*oe,a[14]=p*w+g*O+_*W+m*pe,a[3]=v*x+y*E+b*D+T*H,a[7]=v*M+y*R+b*U+T*ne,a[11]=v*C+y*k+b*F+T*oe,a[15]=v*w+y*O+b*W+T*pe,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[4],s=e[8],a=e[12],r=e[1],o=e[5],l=e[9],c=e[13],u=e[2],d=e[6],h=e[10],f=e[14],p=e[3],g=e[7],_=e[11],m=e[15];return p*(+a*l*d-s*c*d-a*o*h+i*c*h+s*o*f-i*l*f)+g*(+t*l*f-t*c*h+a*r*h-s*r*f+s*c*u-a*l*u)+_*(+t*c*d-t*o*f-a*r*d+i*r*f+a*o*u-i*c*u)+m*(-s*o*u-t*l*d+t*o*h+s*r*d-i*r*h+i*l*u)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,i){const s=this.elements;return e.isVector3?(s[12]=e.x,s[13]=e.y,s[14]=e.z):(s[12]=e,s[13]=t,s[14]=i),this}invert(){const e=this.elements,t=e[0],i=e[1],s=e[2],a=e[3],r=e[4],o=e[5],l=e[6],c=e[7],u=e[8],d=e[9],h=e[10],f=e[11],p=e[12],g=e[13],_=e[14],m=e[15],v=d*_*c-g*h*c+g*l*f-o*_*f-d*l*m+o*h*m,y=p*h*c-u*_*c-p*l*f+r*_*f+u*l*m-r*h*m,b=u*g*c-p*d*c+p*o*f-r*g*f-u*o*m+r*d*m,T=p*d*l-u*g*l-p*o*h+r*g*h+u*o*_-r*d*_,x=t*v+i*y+s*b+a*T;if(x===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const M=1/x;return e[0]=v*M,e[1]=(g*h*a-d*_*a-g*s*f+i*_*f+d*s*m-i*h*m)*M,e[2]=(o*_*a-g*l*a+g*s*c-i*_*c-o*s*m+i*l*m)*M,e[3]=(d*l*a-o*h*a-d*s*c+i*h*c+o*s*f-i*l*f)*M,e[4]=y*M,e[5]=(u*_*a-p*h*a+p*s*f-t*_*f-u*s*m+t*h*m)*M,e[6]=(p*l*a-r*_*a-p*s*c+t*_*c+r*s*m-t*l*m)*M,e[7]=(r*h*a-u*l*a+u*s*c-t*h*c-r*s*f+t*l*f)*M,e[8]=b*M,e[9]=(p*d*a-u*g*a-p*i*f+t*g*f+u*i*m-t*d*m)*M,e[10]=(r*g*a-p*o*a+p*i*c-t*g*c-r*i*m+t*o*m)*M,e[11]=(u*o*a-r*d*a-u*i*c+t*d*c+r*i*f-t*o*f)*M,e[12]=T*M,e[13]=(u*g*s-p*d*s+p*i*h-t*g*h-u*i*_+t*d*_)*M,e[14]=(p*o*s-r*g*s-p*i*l+t*g*l+r*i*_-t*o*_)*M,e[15]=(r*d*s-u*o*s+u*i*l-t*d*l-r*i*h+t*o*h)*M,this}scale(e){const t=this.elements,i=e.x,s=e.y,a=e.z;return t[0]*=i,t[4]*=s,t[8]*=a,t[1]*=i,t[5]*=s,t[9]*=a,t[2]*=i,t[6]*=s,t[10]*=a,t[3]*=i,t[7]*=s,t[11]*=a,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],s=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,s))}makeTranslation(e,t,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const i=Math.cos(t),s=Math.sin(t),a=1-i,r=e.x,o=e.y,l=e.z,c=a*r,u=a*o;return this.set(c*r+i,c*o-s*l,c*l+s*o,0,c*o+s*l,u*o+i,u*l-s*r,0,c*l-s*o,u*l+s*r,a*l*l+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,s,a,r){return this.set(1,i,a,0,e,1,r,0,t,s,1,0,0,0,0,1),this}compose(e,t,i){const s=this.elements,a=t._x,r=t._y,o=t._z,l=t._w,c=a+a,u=r+r,d=o+o,h=a*c,f=a*u,p=a*d,g=r*u,_=r*d,m=o*d,v=l*c,y=l*u,b=l*d,T=i.x,x=i.y,M=i.z;return s[0]=(1-(g+m))*T,s[1]=(f+b)*T,s[2]=(p-y)*T,s[3]=0,s[4]=(f-b)*x,s[5]=(1-(h+m))*x,s[6]=(_+v)*x,s[7]=0,s[8]=(p+y)*M,s[9]=(_-v)*M,s[10]=(1-(h+g))*M,s[11]=0,s[12]=e.x,s[13]=e.y,s[14]=e.z,s[15]=1,this}decompose(e,t,i){const s=this.elements;let a=Sr.set(s[0],s[1],s[2]).length();const r=Sr.set(s[4],s[5],s[6]).length(),o=Sr.set(s[8],s[9],s[10]).length();this.determinant()<0&&(a=-a),e.x=s[12],e.y=s[13],e.z=s[14],ki.copy(this);const c=1/a,u=1/r,d=1/o;return ki.elements[0]*=c,ki.elements[1]*=c,ki.elements[2]*=c,ki.elements[4]*=u,ki.elements[5]*=u,ki.elements[6]*=u,ki.elements[8]*=d,ki.elements[9]*=d,ki.elements[10]*=d,t.setFromRotationMatrix(ki),i.x=a,i.y=r,i.z=o,this}makePerspective(e,t,i,s,a,r,o=hi,l=!1){const c=this.elements,u=2*a/(t-e),d=2*a/(i-s),h=(t+e)/(t-e),f=(i+s)/(i-s);let p,g;if(l)p=a/(r-a),g=r*a/(r-a);else if(o===hi)p=-(r+a)/(r-a),g=-2*r*a/(r-a);else if(o===Eo)p=-r/(r-a),g=-r*a/(r-a);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return c[0]=u,c[4]=0,c[8]=h,c[12]=0,c[1]=0,c[5]=d,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=g,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,i,s,a,r,o=hi,l=!1){const c=this.elements,u=2/(t-e),d=2/(i-s),h=-(t+e)/(t-e),f=-(i+s)/(i-s);let p,g;if(l)p=1/(r-a),g=r/(r-a);else if(o===hi)p=-2/(r-a),g=-(r+a)/(r-a);else if(o===Eo)p=-1/(r-a),g=-a/(r-a);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return c[0]=u,c[4]=0,c[8]=0,c[12]=h,c[1]=0,c[5]=d,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=p,c[14]=g,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const t=this.elements,i=e.elements;for(let s=0;s<16;s++)if(t[s]!==i[s])return!1;return!0}fromArray(e,t=0){for(let i=0;i<16;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],e}}const Sr=new S,ki=new Me,rA=new S(0,0,0),oA=new S(1,1,1),Ws=new S,Ec=new S,li=new S,Sy=new Me,Ty=new dt;class an{constructor(e=0,t=0,i=0,s=an.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=s}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,i,s=this._order){return this._x=e,this._y=t,this._z=i,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,i=!0){const s=e.elements,a=s[0],r=s[4],o=s[8],l=s[1],c=s[5],u=s[9],d=s[2],h=s[6],f=s[10];switch(t){case"XYZ":this._y=Math.asin(Ze(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,f),this._z=Math.atan2(-r,a)):(this._x=Math.atan2(h,c),this._z=0);break;case"YXZ":this._x=Math.asin(-Ze(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-d,a),this._z=0);break;case"ZXY":this._x=Math.asin(Ze(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-d,f),this._z=Math.atan2(-r,c)):(this._y=0,this._z=Math.atan2(l,a));break;case"ZYX":this._y=Math.asin(-Ze(d,-1,1)),Math.abs(d)<.9999999?(this._x=Math.atan2(h,f),this._z=Math.atan2(l,a)):(this._x=0,this._z=Math.atan2(-r,c));break;case"YZX":this._z=Math.asin(Ze(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-u,c),this._y=Math.atan2(-d,a)):(this._x=0,this._y=Math.atan2(o,f));break;case"XZY":this._z=Math.asin(-Ze(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(h,c),this._y=Math.atan2(o,a)):(this._x=Math.atan2(-u,f),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,i===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return Sy.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Sy,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Ty.setFromEuler(this),this.setFromQuaternion(Ty,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}an.DEFAULT_ORDER="XYZ";class Lh{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let i=0;i0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(s.matrixAutoUpdate=!1),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),s.instanceInfo=this._instanceInfo.map(o=>({...o})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(e),s.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(s.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(s.boundingBox=this.boundingBox.toJSON()));function a(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=a(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const l=o.shapes;if(Array.isArray(l))for(let c=0,u=l.length;c0){s.children=[];for(let o=0;o0){s.animations=[];for(let o=0;o0&&(i.geometries=o),l.length>0&&(i.materials=l),c.length>0&&(i.textures=c),u.length>0&&(i.images=u),d.length>0&&(i.shapes=d),h.length>0&&(i.skeletons=h),f.length>0&&(i.animations=f),p.length>0&&(i.nodes=p)}return i.object=s,i;function r(o){const l=[];for(const c in o){const u=o[c];delete u.metadata,l.push(u)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let i=0;i0?s.multiplyScalar(1/Math.sqrt(a)):s.set(0,0,0)}static getBarycoord(e,t,i,s,a){Di.subVectors(s,t),ws.subVectors(i,t),Pf.subVectors(e,t);const r=Di.dot(Di),o=Di.dot(ws),l=Di.dot(Pf),c=ws.dot(ws),u=ws.dot(Pf),d=r*c-o*o;if(d===0)return a.set(0,0,0),null;const h=1/d,f=(c*l-o*u)*h,p=(r*u-o*l)*h;return a.set(1-f-p,p,f)}static containsPoint(e,t,i,s){return this.getBarycoord(e,t,i,s,Ss)===null?!1:Ss.x>=0&&Ss.y>=0&&Ss.x+Ss.y<=1}static getInterpolation(e,t,i,s,a,r,o,l){return this.getBarycoord(e,t,i,s,Ss)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(a,Ss.x),l.addScaledVector(r,Ss.y),l.addScaledVector(o,Ss.z),l)}static getInterpolatedAttribute(e,t,i,s,a,r){return Df.setScalar(0),Of.setScalar(0),Ff.setScalar(0),Df.fromBufferAttribute(e,t),Of.fromBufferAttribute(e,i),Ff.fromBufferAttribute(e,s),r.setScalar(0),r.addScaledVector(Df,a.x),r.addScaledVector(Of,a.y),r.addScaledVector(Ff,a.z),r}static isFrontFacing(e,t,i,s){return Di.subVectors(i,t),ws.subVectors(e,t),Di.cross(ws).dot(s)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,s){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[s]),this}setFromAttributeAndIndices(e,t,i,s){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,s),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Di.subVectors(this.c,this.b),ws.subVectors(this.a,this.b),Di.cross(ws).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Qn.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Qn.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,s,a){return Qn.getInterpolation(e,this.a,this.b,this.c,t,i,s,a)}containsPoint(e){return Qn.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Qn.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,s=this.b,a=this.c;let r,o;Er.subVectors(s,i),Cr.subVectors(a,i),If.subVectors(e,i);const l=Er.dot(If),c=Cr.dot(If);if(l<=0&&c<=0)return t.copy(i);Lf.subVectors(e,s);const u=Er.dot(Lf),d=Cr.dot(Lf);if(u>=0&&d<=u)return t.copy(s);const h=l*d-u*c;if(h<=0&&l>=0&&u<=0)return r=l/(l-u),t.copy(i).addScaledVector(Er,r);kf.subVectors(e,a);const f=Er.dot(kf),p=Cr.dot(kf);if(p>=0&&f<=p)return t.copy(a);const g=f*c-l*p;if(g<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(i).addScaledVector(Cr,o);const _=u*p-f*d;if(_<=0&&d-u>=0&&f-p>=0)return Py.subVectors(a,s),o=(d-u)/(d-u+(f-p)),t.copy(s).addScaledVector(Py,o);const m=1/(_+g+h);return r=g*m,o=h*m,t.copy(i).addScaledVector(Er,r).addScaledVector(Cr,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const bS={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Xs={h:0,s:0,l:0},Ac={h:0,s:0,l:0};function Nf(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*6*(2/3-t):n}class ue{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){const s=e;s&&s.isColor?this.copy(s):typeof s=="number"?this.setHex(s):typeof s=="string"&&this.setStyle(s)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=gt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,rt.colorSpaceToWorking(this,t),this}setRGB(e,t,i,s=rt.workingColorSpace){return this.r=e,this.g=t,this.b=i,rt.colorSpaceToWorking(this,s),this}setHSL(e,t,i,s=rt.workingColorSpace){if(e=sg(e,1),t=Ze(t,0,1),i=Ze(i,0,1),t===0)this.r=this.g=this.b=i;else{const a=i<=.5?i*(1+t):i+t-i*t,r=2*i-a;this.r=Nf(r,a,e+1/3),this.g=Nf(r,a,e),this.b=Nf(r,a,e-1/3)}return rt.colorSpaceToWorking(this,s),this}setStyle(e,t=gt){function i(a){a!==void 0&&parseFloat(a)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(e)){let a;const r=s[1],o=s[2];switch(r){case"rgb":case"rgba":if(a=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setRGB(Math.min(255,parseInt(a[1],10))/255,Math.min(255,parseInt(a[2],10))/255,Math.min(255,parseInt(a[3],10))/255,t);if(a=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setRGB(Math.min(100,parseInt(a[1],10))/100,Math.min(100,parseInt(a[2],10))/100,Math.min(100,parseInt(a[3],10))/100,t);break;case"hsl":case"hsla":if(a=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setHSL(parseFloat(a[1])/360,parseFloat(a[2])/100,parseFloat(a[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(e)){const a=s[1],r=a.length;if(r===3)return this.setRGB(parseInt(a.charAt(0),16)/15,parseInt(a.charAt(1),16)/15,parseInt(a.charAt(2),16)/15,t);if(r===6)return this.setHex(parseInt(a,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=gt){const i=bS[e.toLowerCase()];return i!==void 0?this.setHex(i,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Fs(e.r),this.g=Fs(e.g),this.b=Fs(e.b),this}copyLinearToSRGB(e){return this.r=io(e.r),this.g=io(e.g),this.b=io(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=gt){return rt.workingToColorSpace(En.copy(this),e),Math.round(Ze(En.r*255,0,255))*65536+Math.round(Ze(En.g*255,0,255))*256+Math.round(Ze(En.b*255,0,255))}getHexString(e=gt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=rt.workingColorSpace){rt.workingToColorSpace(En.copy(this),t);const i=En.r,s=En.g,a=En.b,r=Math.max(i,s,a),o=Math.min(i,s,a);let l,c;const u=(o+r)/2;if(o===r)l=0,c=0;else{const d=r-o;switch(c=u<=.5?d/(r+o):d/(2-r-o),r){case i:l=(s-a)/d+(s0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const i=e[t];if(i===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(i):s&&s.isVector3&&i&&i.isVector3?s.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==nr&&(i.blending=this.blending),this.side!==fs&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==Bl&&(i.blendSrc=this.blendSrc),this.blendDst!==zl&&(i.blendDst=this.blendDst),this.blendEquation!==Is&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==ar&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==Am&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Ba&&(i.stencilFail=this.stencilFail),this.stencilZFail!==Ba&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==Ba&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function s(a){const r=[];for(const o in a){const l=a[o];delete l.metadata,r.push(l)}return r}if(t){const a=s(e.textures),r=s(e.images);a.length>0&&(i.textures=a),r.length>0&&(i.images=r)}return i}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let i=null;if(t!==null){const s=t.length;i=new Array(s);for(let a=0;a!==s;++a)i[a]=t[a].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class Ye extends Qt{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new ue(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new an,this.combine=rc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const ks=fA();function fA(){const n=new ArrayBuffer(4),e=new Float32Array(n),t=new Uint32Array(n),i=new Uint32Array(512),s=new Uint32Array(512);for(let l=0;l<256;++l){const c=l-127;c<-27?(i[l]=0,i[l|256]=32768,s[l]=24,s[l|256]=24):c<-14?(i[l]=1024>>-c-14,i[l|256]=1024>>-c-14|32768,s[l]=-c-1,s[l|256]=-c-1):c<=15?(i[l]=c+15<<10,i[l|256]=c+15<<10|32768,s[l]=13,s[l|256]=13):c<128?(i[l]=31744,i[l|256]=64512,s[l]=24,s[l|256]=24):(i[l]=31744,i[l|256]=64512,s[l]=13,s[l|256]=13)}const a=new Uint32Array(2048),r=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,u=0;for(;(c&8388608)===0;)c<<=1,u-=8388608;c&=-8388609,u+=947912704,a[l]=c|u}for(let l=1024;l<2048;++l)a[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)r[l]=l<<23;r[31]=1199570944,r[32]=2147483648;for(let l=33;l<63;++l)r[l]=2147483648+(l-32<<23);r[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:e,uint32View:t,baseTable:i,shiftTable:s,mantissaTable:a,exponentTable:r,offsetTable:o}}function Yn(n){Math.abs(n)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),n=Ze(n,-65504,65504),ks.floatView[0]=n;const e=ks.uint32View[0],t=e>>23&511;return ks.baseTable[t]+((e&8388607)>>ks.shiftTable[t])}function fl(n){const e=n>>10;return ks.uint32View[0]=ks.mantissaTable[ks.offsetTable[e]+(n&1023)]+ks.exponentTable[e],ks.floatView[0]}class pl{static toHalfFloat(e){return Yn(e)}static fromHalfFloat(e){return fl(e)}}const nn=new S,Rc=new te;let pA=0;class ot{constructor(e,t,i=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:pA++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=$l,this.updateRanges=[],this.gpuType=Sn,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,i){e*=this.itemSize,i*=t.itemSize;for(let s=0,a=this.itemSize;st.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new vn);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new S(-1/0,-1/0,-1/0),new S(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,s=t.length;i0&&(e.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const l in i){const c=i[l];e.data.attributes[l]=c.toJSON(e.data)}const s={};let a=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],u=[];for(let d=0,h=c.length;d0&&(s[l]=u,a=!0)}a&&(e.data.morphAttributes=s,e.data.morphTargetsRelative=this.morphTargetsRelative);const r=this.groups;r.length>0&&(e.data.groups=JSON.parse(JSON.stringify(r)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const i=e.index;i!==null&&this.setIndex(i.clone());const s=e.attributes;for(const c in s){const u=s[c];this.setAttribute(c,u.clone(t))}const a=e.morphAttributes;for(const c in a){const u=[],d=a[c];for(let h=0,f=d.length;h0){const s=t[i[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,r=s.length;a(e.far-e.near)**2))&&(Iy.copy(a).invert(),ba.copy(e.ray).applyMatrix4(Iy),!(i.boundingBox!==null&&ba.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,ba)))}_computeIntersections(e,t,i){let s;const a=this.geometry,r=this.material,o=a.index,l=a.attributes.position,c=a.attributes.uv,u=a.attributes.uv1,d=a.attributes.normal,h=a.groups,f=a.drawRange;if(o!==null)if(Array.isArray(r))for(let p=0,g=h.length;pt.far?null:{distance:c,point:Oc.clone(),object:n}}function Fc(n,e,t,i,s,a,r,o,l,c){n.getVertexPosition(o,Ic),n.getVertexPosition(l,Lc),n.getVertexPosition(c,kc);const u=wA(n,e,t,i,Ic,Lc,kc,ky);if(u){const d=new S;Qn.getBarycoord(ky,Ic,Lc,kc,d),s&&(u.uv=Qn.getInterpolatedAttribute(s,o,l,c,d,new te)),a&&(u.uv1=Qn.getInterpolatedAttribute(a,o,l,c,d,new te)),r&&(u.normal=Qn.getInterpolatedAttribute(r,o,l,c,d,new S),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));const h={a:o,b:l,c,normal:new S,materialIndex:0};Qn.getNormal(Ic,Lc,kc,h.normal),u.face=h,u.barycoord=d}return u}class Ci extends Ge{constructor(e=1,t=1,i=1,s=1,a=1,r=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:s,heightSegments:a,depthSegments:r};const o=this;s=Math.floor(s),a=Math.floor(a),r=Math.floor(r);const l=[],c=[],u=[],d=[];let h=0,f=0;p("z","y","x",-1,-1,i,t,e,r,a,0),p("z","y","x",1,-1,i,t,-e,r,a,1),p("x","z","y",1,1,e,i,t,s,r,2),p("x","z","y",1,-1,e,i,-t,s,r,3),p("x","y","z",1,-1,e,t,i,s,a,4),p("x","y","z",-1,-1,e,t,-i,s,a,5),this.setIndex(l),this.setAttribute("position",new Ee(c,3)),this.setAttribute("normal",new Ee(u,3)),this.setAttribute("uv",new Ee(d,2));function p(g,_,m,v,y,b,T,x,M,C,w){const E=b/M,R=T/C,k=b/2,O=T/2,D=x/2,U=M+1,F=C+1;let W=0,H=0;const ne=new S;for(let oe=0;oe0?1:-1,u.push(ne.x,ne.y,ne.z),d.push(Ie/M),d.push(1-oe/C),W+=1}}for(let oe=0;oe0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const i={};for(const s in this.extensions)this.extensions[s]===!0&&(i[s]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}}class Ah extends Qe{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Me,this.projectionMatrix=new Me,this.projectionMatrixInverse=new Me,this.coordinateSystem=hi,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const Ks=new S,Cy=new te,Ay=new te;class Jt extends Ah{constructor(e=50,t=1,i=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=i,this.far=s,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=To*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(nr*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return To*2*Math.atan(Math.tan(nr*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,i){Ks.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Ks.x,Ks.y).multiplyScalar(-e/Ks.z),Ks.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(Ks.x,Ks.y).multiplyScalar(-e/Ks.z)}getViewSize(e,t){return this.getViewBounds(e,Cy,Ay),t.subVectors(Ay,Cy)}setViewOffset(e,t,i,s,a,r){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=s,this.view.width=a,this.view.height=r,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(nr*.5*this.fov)/this.zoom,i=2*t,s=this.aspect*i,a=-.5*s;const r=this.view;if(this.view!==null&&this.view.enabled){const l=r.fullWidth,c=r.fullHeight;a+=r.offsetX*s/l,t-=r.offsetY*i/c,s*=r.width/l,i*=r.height/c}const o=this.filmOffset;o!==0&&(a+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(a,a+s,t,t-i,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const Ar=-90,Rr=1;class mS extends Qe{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new Jt(Ar,Rr,e,t);s.layers=this.layers,this.add(s);const a=new Jt(Ar,Rr,e,t);a.layers=this.layers,this.add(a);const r=new Jt(Ar,Rr,e,t);r.layers=this.layers,this.add(r);const o=new Jt(Ar,Rr,e,t);o.layers=this.layers,this.add(o);const l=new Jt(Ar,Rr,e,t);l.layers=this.layers,this.add(l);const c=new Jt(Ar,Rr,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[i,s,a,r,o,l]=t;for(const c of t)this.remove(c);if(e===hi)i.up.set(0,1,0),i.lookAt(1,0,0),s.up.set(0,1,0),s.lookAt(-1,0,0),a.up.set(0,0,-1),a.lookAt(0,1,0),r.up.set(0,0,1),r.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===So)i.up.set(0,-1,0),i.lookAt(-1,0,0),s.up.set(0,-1,0),s.lookAt(1,0,0),a.up.set(0,0,1),a.lookAt(0,1,0),r.up.set(0,0,-1),r.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:s}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[a,r,o,l,c,u]=this.children,d=e.getRenderTarget(),h=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const g=i.texture.generateMipmaps;i.texture.generateMipmaps=!1,e.setRenderTarget(i,0,s),e.render(t,a),e.setRenderTarget(i,1,s),e.render(t,r),e.setRenderTarget(i,2,s),e.render(t,o),e.setRenderTarget(i,3,s),e.render(t,l),e.setRenderTarget(i,4,s),e.render(t,c),i.texture.generateMipmaps=g,e.setRenderTarget(i,5,s),e.render(t,u),e.setRenderTarget(d,h,f),e.xr.enabled=p,i.texture.needsPMREMUpdate=!0}}class sc extends Bt{constructor(e=[],t=Bs,i,s,a,r,o,l,c,u){super(e,t,i,s,a,r,o,l,c,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class _S extends ms{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const i={width:e,height:e,depth:1},s=[i,i,i,i,i,i];this.texture=new sc(s),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const i={uniforms:{tEquirect:{value:null}},vertexShader:` +}`;class ti extends Qt{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=TA,this.fragmentShader=MA,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=Ao(e.uniforms),this.uniformsGroups=SA(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const s in this.uniforms){const r=this.uniforms[s].value;r&&r.isTexture?t.uniforms[s]={type:"t",value:r.toJSON(e).uuid}:r&&r.isColor?t.uniforms[s]={type:"c",value:r.getHex()}:r&&r.isVector2?t.uniforms[s]={type:"v2",value:r.toArray()}:r&&r.isVector3?t.uniforms[s]={type:"v3",value:r.toArray()}:r&&r.isVector4?t.uniforms[s]={type:"v4",value:r.toArray()}:r&&r.isMatrix3?t.uniforms[s]={type:"m3",value:r.toArray()}:r&&r.isMatrix4?t.uniforms[s]={type:"m4",value:r.toArray()}:t.uniforms[s]={value:r}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const i={};for(const s in this.extensions)this.extensions[s]===!0&&(i[s]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}}class Dh extends Qe{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Me,this.projectionMatrix=new Me,this.projectionMatrixInverse=new Me,this.coordinateSystem=hi,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const Ks=new S,Dy=new te,Oy=new te;class Jt extends Dh{constructor(e=50,t=1,i=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=i,this.far=s,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=Co*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(ir*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Co*2*Math.atan(Math.tan(ir*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,i){Ks.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Ks.x,Ks.y).multiplyScalar(-e/Ks.z),Ks.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(Ks.x,Ks.y).multiplyScalar(-e/Ks.z)}getViewSize(e,t){return this.getViewBounds(e,Dy,Oy),t.subVectors(Oy,Dy)}setViewOffset(e,t,i,s,a,r){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=s,this.view.width=a,this.view.height=r,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(ir*.5*this.fov)/this.zoom,i=2*t,s=this.aspect*i,a=-.5*s;const r=this.view;if(this.view!==null&&this.view.enabled){const l=r.fullWidth,c=r.fullHeight;a+=r.offsetX*s/l,t-=r.offsetY*i/c,s*=r.width/l,i*=r.height/c}const o=this.filmOffset;o!==0&&(a+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(a,a+s,t,t-i,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const Rr=-90,Pr=1;class SS extends Qe{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new Jt(Rr,Pr,e,t);s.layers=this.layers,this.add(s);const a=new Jt(Rr,Pr,e,t);a.layers=this.layers,this.add(a);const r=new Jt(Rr,Pr,e,t);r.layers=this.layers,this.add(r);const o=new Jt(Rr,Pr,e,t);o.layers=this.layers,this.add(o);const l=new Jt(Rr,Pr,e,t);l.layers=this.layers,this.add(l);const c=new Jt(Rr,Pr,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[i,s,a,r,o,l]=t;for(const c of t)this.remove(c);if(e===hi)i.up.set(0,1,0),i.lookAt(1,0,0),s.up.set(0,1,0),s.lookAt(-1,0,0),a.up.set(0,0,-1),a.lookAt(0,1,0),r.up.set(0,0,1),r.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===Eo)i.up.set(0,-1,0),i.lookAt(-1,0,0),s.up.set(0,-1,0),s.lookAt(1,0,0),a.up.set(0,0,1),a.lookAt(0,1,0),r.up.set(0,0,-1),r.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:s}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[a,r,o,l,c,u]=this.children,d=e.getRenderTarget(),h=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const g=i.texture.generateMipmaps;i.texture.generateMipmaps=!1,e.setRenderTarget(i,0,s),e.render(t,a),e.setRenderTarget(i,1,s),e.render(t,r),e.setRenderTarget(i,2,s),e.render(t,o),e.setRenderTarget(i,3,s),e.render(t,l),e.setRenderTarget(i,4,s),e.render(t,c),i.texture.generateMipmaps=g,e.setRenderTarget(i,5,s),e.render(t,u),e.setRenderTarget(d,h,f),e.xr.enabled=p,i.texture.needsPMREMUpdate=!0}}class lc extends Bt{constructor(e=[],t=Bs,i,s,a,r,o,l,c,u){super(e,t,i,s,a,r,o,l,c,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class TS extends ms{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const i={width:e,height:e,depth:1},s=[i,i,i,i,i,i];this.texture=new lc(s),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const i={uniforms:{tEquirect:{value:null}},vertexShader:` varying vec3 vWorldDirection; @@ -37,9 +37,9 @@ function fh(n,e){if(n.frames.length===0)return 0;let t=0,i=n.frames.length-1;for gl_FragColor = texture2D( tEquirect, sampleUV ); } - `},s=new Ei(5,5,5),a=new ti({name:"CubemapFromEquirect",uniforms:Mo(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:un,blending:ks});a.uniforms.tEquirect.value=t;const r=new we(s,a),o=t.minFilter;return t.minFilter===Ti&&(t.minFilter=Vt),new mS(1,10,this).update(e,r),t.minFilter=o,r.geometry.dispose(),r.material.dispose(),this}clear(e,t=!0,i=!0,s=!0){const a=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,i,s);e.setRenderTarget(a)}}class Mt extends Qe{constructor(){super(),this.isGroup=!0,this.type="Group"}}const mA={type:"move"};class Gu{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Mt,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Mt,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new S,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new S),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Mt,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new S,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new S),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const i of e.hand.values())this._getHandJoint(t,i)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,i){let s=null,a=null,r=null;const o=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){r=!0;for(const g of e.hand.values()){const _=t.getJointPose(g,i),m=this._getHandJoint(c,g);_!==null&&(m.matrix.fromArray(_.transform.matrix),m.matrix.decompose(m.position,m.rotation,m.scale),m.matrixWorldNeedsUpdate=!0,m.jointRadius=_.radius),m.visible=_!==null}const u=c.joints["index-finger-tip"],d=c.joints["thumb-tip"],h=u.position.distanceTo(d.position),f=.02,p=.005;c.inputState.pinching&&h>f+p?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&h<=f-p&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(a=t.getPose(e.gripSpace,i),a!==null&&(l.matrix.fromArray(a.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,a.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(a.linearVelocity)):l.hasLinearVelocity=!1,a.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(a.angularVelocity)):l.hasAngularVelocity=!1));o!==null&&(s=t.getPose(e.targetRaySpace,i),s===null&&a!==null&&(s=a),s!==null&&(o.matrix.fromArray(s.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,s.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(s.linearVelocity)):o.hasLinearVelocity=!1,s.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(s.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(mA)))}return o!==null&&(o.visible=s!==null),l!==null&&(l.visible=a!==null),c!==null&&(c.visible=r!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const i=new Mt;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}class Rh{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new ue(e),this.density=t}clone(){return new Rh(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class Ph{constructor(e,t=1,i=1e3){this.isFog=!0,this.name="",this.color=new ue(e),this.near=t,this.far=i}clone(){return new Ph(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class ac extends Qe{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new an,this.environmentIntensity=1,this.environmentRotation=new an,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class rc{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=zl,this.updateRanges=[],this.version=0,this.uuid=pi()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,i){e*=this.stride,i*=t.stride;for(let s=0,a=this.stride;se.far||t.push({distance:l,point:$o.clone(),uv:Qn.getInterpolation($o,Dc,Xo,kc,Ry,kf,Py,new te),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}}function Oc(n,e,t,i,s,a){Dr.subVectors(n,t).addScalar(.5).multiply(i),s!==void 0?(Wo.x=a*Dr.x-s*Dr.y,Wo.y=s*Dr.x+a*Dr.y):Wo.copy(Dr),n.copy(e),n.x+=Wo.x,n.y+=Wo.y,n.applyMatrix4(gS)}const Fc=new S,Iy=new S;class yS extends Qe{constructor(){super(),this.isLOD=!0,this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);const t=e.levels;for(let i=0,s=t.length;i0){let i,s;for(i=1,s=t.length;i0){Fc.setFromMatrixPosition(this.matrixWorld);const s=e.ray.origin.distanceTo(Fc);this.getObjectForDistance(s).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){Fc.setFromMatrixPosition(e.matrixWorld),Iy.setFromMatrixPosition(this.matrixWorld);const i=Fc.distanceTo(Iy)/e.zoom;t[0].object.visible=!0;let s,a;for(s=1,a=t.length;s=r)t[s-1].object.visible=!1,t[s].object.visible=!0;else break}for(this._currentLevel=s-1;s1?null:t.copy(e.start).addScaledVector(i,a)}intersectsLine(e){const t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const i=t||bA.getNormalMatrix(e),s=this.coplanarPoint(Nf).applyMatrix4(e),a=this.normal.applyMatrix3(i).normalize();return this.constant=-s.dot(a),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const ba=new bn,xA=new te(.5,.5),Bc=new S;class Po{constructor(e=new Ps,t=new Ps,i=new Ps,s=new Ps,a=new Ps,r=new Ps){this.planes=[e,t,i,s,a,r]}set(e,t,i,s,a,r){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(i),o[3].copy(s),o[4].copy(a),o[5].copy(r),this}copy(e){const t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=hi,i=!1){const s=this.planes,a=e.elements,r=a[0],o=a[1],l=a[2],c=a[3],u=a[4],d=a[5],h=a[6],f=a[7],p=a[8],g=a[9],_=a[10],m=a[11],v=a[12],y=a[13],b=a[14],T=a[15];if(s[0].setComponents(c-r,f-u,m-p,T-v).normalize(),s[1].setComponents(c+r,f+u,m+p,T+v).normalize(),s[2].setComponents(c+o,f+d,m+g,T+y).normalize(),s[3].setComponents(c-o,f-d,m-g,T-y).normalize(),i)s[4].setComponents(l,h,_,b).normalize(),s[5].setComponents(c-l,f-h,m-_,T-b).normalize();else if(s[4].setComponents(c-l,f-h,m-_,T-b).normalize(),t===hi)s[5].setComponents(c+l,f+h,m+_,T+b).normalize();else if(t===So)s[5].setComponents(l,h,_,b).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),ba.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),ba.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ba)}intersectsSprite(e){ba.center.set(0,0,0);const t=xA.distanceTo(e.center);return ba.radius=.7071067811865476+t,ba.applyMatrix4(e.matrixWorld),this.intersectsSphere(ba)}intersectsSphere(e){const t=this.planes,i=e.center,s=-e.radius;for(let a=0;a<6;a++)if(t[a].distanceToPoint(i)0?e.max.x:e.min.x,Bc.y=s.normal.y>0?e.max.y:e.min.y,Bc.z=s.normal.z>0?e.max.z:e.min.z,s.distanceToPoint(Bc)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}const Ji=new Me,Qi=new Po;class Oh{constructor(){this.coordinateSystem=hi}intersectsObject(e,t){if(!t.isArrayCamera||t.cameras.length===0)return!1;for(let i=0;i=a.length&&a.push({start:-1,count:-1,z:-1,index:-1});const o=a[this.index];r.push(o),this.index++,o.start=e,o.count=t,o.z=i,o.index=s}reset(){this.list.length=0,this.index=0}}const Wn=new Me,MA=new ue(1,1,1),zy=new Po,EA=new Oh,zc=new vn,xa=new bn,Yo=new S,Hy=new S,CA=new S,Bf=new TA,Cn=new we,Hc=[];function AA(n,e,t=0){const i=e.itemSize;if(n.isInterleavedBufferAttribute||n.array.constructor!==e.array.constructor){const s=n.count;for(let a=0;a65535?new Uint32Array(s):new Uint16Array(s);t.setIndex(new rt(a,1))}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;if(!!e.getIndex()!=!!t.getIndex())throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');for(const i in t.attributes){if(!e.hasAttribute(i))throw new Error(`THREE.BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`);const s=e.getAttribute(i),a=t.getAttribute(i);if(s.itemSize!==a.itemSize||s.normalized!==a.normalized)throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}validateInstanceId(e){const t=this._instanceInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid instanceId ${e}. Instance is either out of range or has been deleted.`)}validateGeometryId(e){const t=this._geometryInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`)}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new vn);const e=this.boundingBox,t=this._instanceInfo;e.makeEmpty();for(let i=0,s=t.length;i=this.maxInstanceCount&&this._availableInstanceIds.length===0)throw new Error("THREE.BatchedMesh: Maximum item count reached.");const i={visible:!0,active:!0,geometryIndex:e};let s=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(Uf),s=this._availableInstanceIds.shift(),this._instanceInfo[s]=i):(s=this._instanceInfo.length,this._instanceInfo.push(i));const a=this._matricesTexture;Wn.identity().toArray(a.image.data,s*16),a.needsUpdate=!0;const r=this._colorsTexture;return r&&(MA.toArray(r.image.data,s*4),r.needsUpdate=!0),this._visibilityChanged=!0,s}addGeometry(e,t=-1,i=-1){this._initializeGeometry(e),this._validateGeometry(e);const s={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},a=this._geometryInfo;s.vertexStart=this._nextVertexStart,s.reservedVertexCount=t===-1?e.getAttribute("position").count:t;const r=e.getIndex();if(r!==null&&(s.indexStart=this._nextIndexStart,s.reservedIndexCount=i===-1?r.count:i),s.indexStart!==-1&&s.indexStart+s.reservedIndexCount>this._maxIndexCount||s.vertexStart+s.reservedVertexCount>this._maxVertexCount)throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");let l;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(Uf),l=this._availableGeometryIds.shift(),a[l]=s):(l=this._geometryCount,this._geometryCount++,a.push(s)),this.setGeometryAt(l,e),this._nextIndexStart=s.indexStart+s.reservedIndexCount,this._nextVertexStart=s.vertexStart+s.reservedVertexCount,l}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,s=i.getIndex()!==null,a=i.getIndex(),r=t.getIndex(),o=this._geometryInfo[e];if(s&&r.count>o.reservedIndexCount||t.attributes.position.count>o.reservedVertexCount)throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");const l=o.vertexStart,c=o.reservedVertexCount;o.vertexCount=t.getAttribute("position").count;for(const u in i.attributes){const d=t.getAttribute(u),h=i.getAttribute(u);AA(d,h,l);const f=d.itemSize;for(let p=d.count,g=c;p=t.length||t[e].active===!1)return this;const i=this._instanceInfo;for(let s=0,a=i.length;so).sort((r,o)=>i[r].vertexStart-i[o].vertexStart),a=this.geometry;for(let r=0,o=i.length;r=this._geometryCount)return null;const i=this.geometry,s=this._geometryInfo[e];if(s.boundingBox===null){const a=new vn,r=i.index,o=i.attributes.position;for(let l=s.start,c=s.start+s.count;l=this._geometryCount)return null;const i=this.geometry,s=this._geometryInfo[e];if(s.boundingSphere===null){const a=new bn;this.getBoundingBoxAt(e,zc),zc.getCenter(a.center);const r=i.index,o=i.attributes.position;let l=0;for(let c=s.start,u=s.start+s.count;co.active);if(Math.max(...i.map(o=>o.vertexStart+o.reservedVertexCount))>e)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${t}. Cannot shrink further.`);if(this.geometry.index&&Math.max(...i.map(l=>l.indexStart+l.reservedIndexCount))>t)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${t}. Cannot shrink further.`);const a=this.geometry;a.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new Ge,this._initializeGeometry(a));const r=this.geometry;a.index&&wa(a.index.array,r.index.array);for(const o in a.attributes)wa(a.attributes[o].array,r.attributes[o].array)}raycast(e,t){const i=this._instanceInfo,s=this._geometryInfo,a=this.matrixWorld,r=this.geometry;Cn.material=this.material,Cn.geometry.index=r.index,Cn.geometry.attributes=r.attributes,Cn.geometry.boundingBox===null&&(Cn.geometry.boundingBox=new vn),Cn.geometry.boundingSphere===null&&(Cn.geometry.boundingSphere=new bn);for(let o=0,l=i.length;o({...t,boundingBox:t.boundingBox!==null?t.boundingBox.clone():null,boundingSphere:t.boundingSphere!==null?t.boundingSphere.clone():null})),this._instanceInfo=e._instanceInfo.map(t=>({...t})),this._availableInstanceIds=e._availableInstanceIds.slice(),this._availableGeometryIds=e._availableGeometryIds.slice(),this._nextIndexStart=e._nextIndexStart,this._nextVertexStart=e._nextVertexStart,this._geometryCount=e._geometryCount,this._maxInstanceCount=e._maxInstanceCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._indirectTexture=e._indirectTexture.clone(),this._indirectTexture.image.data=this._indirectTexture.image.data.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),this._colorsTexture!==null&&(this._colorsTexture=e._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,this._colorsTexture!==null&&(this._colorsTexture.dispose(),this._colorsTexture=null)}onBeforeRender(e,t,i,s,a){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const r=s.getIndex(),o=r===null?1:r.array.BYTES_PER_ELEMENT,l=this._instanceInfo,c=this._multiDrawStarts,u=this._multiDrawCounts,d=this._geometryInfo,h=this.perObjectFrustumCulled,f=this._indirectTexture,p=f.image.data,g=i.isArrayCamera?EA:zy;h&&!i.isArrayCamera&&(Wn.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse).multiply(this.matrixWorld),zy.setFromProjectionMatrix(Wn,i.coordinateSystem,i.reversedDepth));let _=0;if(this.sortObjects){Wn.copy(this.matrixWorld).invert(),Yo.setFromMatrixPosition(i.matrixWorld).applyMatrix4(Wn),Hy.set(0,0,-1).transformDirection(i.matrixWorld).transformDirection(Wn);for(let y=0,b=l.length;y0){const s=t[i[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,r=s.length;ai)return;zf.applyMatrix4(n.matrixWorld);const c=e.ray.origin.distanceTo(zf);if(!(ce.far))return{distance:c,point:Gy.clone().applyMatrix4(n.matrixWorld),index:r,face:null,faceIndex:null,barycoord:null,object:n}}const $y=new S,Wy=new S;class Ln extends In{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,i=[];for(let s=0,a=t.count;s0){const s=t[i[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,r=s.length;as.far)return;a.push({distance:c,distanceToRay:Math.sqrt(o),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:r})}}class bS extends Bt{constructor(e,t,i,s,a=Vt,r=Vt,o,l,c){super(e,t,i,s,a,r,o,l,c),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;const u=this;function d(){u.needsUpdate=!0,u._requestVideoFrameCallbackId=e.requestVideoFrameCallback(d)}"requestVideoFrameCallback"in e&&(this._requestVideoFrameCallbackId=e.requestVideoFrameCallback(d))}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;"requestVideoFrameCallback"in e===!1&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),super.dispose()}}class RA extends bS{constructor(e,t,i,s,a,r,o,l){super({},e,t,i,s,a,r,o,l),this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(e){this.image=e,this.needsUpdate=!0}}class PA extends Bt{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=dn,this.minFilter=dn,this.generateMipmaps=!1,this.needsUpdate=!0}}class Fh extends Bt{constructor(e,t,i,s,a,r,o,l,c,u,d,h){super(null,r,o,l,c,u,s,a,d,h),this.isCompressedTexture=!0,this.image={width:t,height:i},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class IA extends Fh{constructor(e,t,i,s,a,r){super(e,t,i,a,r),this.isCompressedArrayTexture=!0,this.image.depth=s,this.wrapR=Hn,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class LA extends Fh{constructor(e,t,i){super(void 0,e[0].width,e[0].height,t,i,Bs),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class oc extends Bt{constructor(e,t,i,s,a,r,o,l,c){super(e,t,i,s,a,r,o,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}}class tg extends Bt{constructor(e,t,i=zs,s,a,r,o=dn,l=dn,c,u=bo,d=1){if(u!==bo&&u!==xo)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const h={width:e,height:t,depth:d};super(h,s,a,r,o,l,u,i,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new ia(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class ng extends Bt{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class Nh extends Ge{constructor(e=1,t=1,i=4,s=8,a=1){super(),this.type="CapsuleGeometry",this.parameters={radius:e,height:t,capSegments:i,radialSegments:s,heightSegments:a},t=Math.max(0,t),i=Math.max(1,Math.floor(i)),s=Math.max(3,Math.floor(s)),a=Math.max(1,Math.floor(a));const r=[],o=[],l=[],c=[],u=t/2,d=Math.PI/2*e,h=t,f=2*d+h,p=i*2+a,g=s+1,_=new S,m=new S;for(let v=0;v<=p;v++){let y=0,b=0,T=0,x=0;if(v<=i){const w=v/i,E=w*Math.PI/2;b=-u-e*Math.cos(E),T=e*Math.sin(E),x=-e*Math.cos(E),y=w*d}else if(v<=i+a){const w=(v-i)/a;b=-u+w*t,T=e,x=0,y=d+w*h}else{const w=(v-i-a)/i,E=w*Math.PI/2;b=u+e*Math.sin(E),T=e*Math.cos(E),x=e*Math.sin(E),y=d+h+w*d}const M=Math.max(0,Math.min(1,y/f));let C=0;v===0?C=.5/s:v===p&&(C=-.5/s);for(let w=0;w<=s;w++){const E=w/s,R=E*Math.PI*2,D=Math.sin(R),O=Math.cos(R);m.x=-T*O,m.y=b,m.z=T*D,o.push(m.x,m.y,m.z),_.set(-T*O,x,T*D),_.normalize(),l.push(_.x,_.y,_.z),c.push(E+C,M)}if(v>0){const w=(v-1)*g;for(let E=0;E0&&y(!0),t>0&&y(!1)),this.setIndex(u),this.setAttribute("position",new Ee(d,3)),this.setAttribute("normal",new Ee(h,3)),this.setAttribute("uv",new Ee(f,2));function v(){const b=new S,T=new S;let x=0;const M=(t-e)/i;for(let C=0;C<=a;C++){const w=[],E=C/a,R=E*(t-e)+e;for(let D=0;D<=s;D++){const O=D/s,k=O*l+o,U=Math.sin(k),F=Math.cos(k);T.x=R*U,T.y=-E*i+_,T.z=R*F,d.push(T.x,T.y,T.z),b.set(U,M,F).normalize(),h.push(b.x,b.y,b.z),f.push(O,1-E),w.push(p++)}g.push(w)}for(let C=0;C0||w!==0)&&(u.push(E,R,O),x+=3),(t>0||w!==a-1)&&(u.push(R,D,O),x+=3)}c.addGroup(m,x,0),m+=x}function y(b){const T=p,x=new te,M=new S;let C=0;const w=b===!0?e:t,E=b===!0?1:-1;for(let D=1;D<=s;D++)d.push(0,_*E,0),h.push(0,E,0),f.push(.5,.5),p++;const R=p;for(let D=0;D<=s;D++){const k=D/s*l+o,U=Math.cos(k),F=Math.sin(k);M.x=w*F,M.y=_*E,M.z=w*U,d.push(M.x,M.y,M.z),h.push(0,E,0),x.x=U*.5+.5,x.y=F*.5*E+.5,f.push(x.x,x.y),p++}for(let D=0;D.9&&M<.1&&(y<.2&&(r[v+0]+=1),b<.2&&(r[v+2]+=1),T<.2&&(r[v+4]+=1))}}function h(v){a.push(v.x,v.y,v.z)}function f(v,y){const b=v*3;y.x=e[b+0],y.y=e[b+1],y.z=e[b+2]}function p(){const v=new S,y=new S,b=new S,T=new S,x=new te,M=new te,C=new te;for(let w=0,E=0;w0)l=s-1;else{l=s;break}if(s=l,i[s]===r)return s/(a-1);const u=i[s],h=i[s+1]-u,f=(r-u)/h;return(s+f)/(a-1)}getTangent(e,t){let s=e-1e-4,a=e+1e-4;s<0&&(s=0),a>1&&(a=1);const r=this.getPoint(s),o=this.getPoint(a),l=t||(r.isVector2?new te:new S);return l.copy(o).sub(r).normalize(),l}getTangentAt(e,t){const i=this.getUtoTmapping(e);return this.getTangent(i,t)}computeFrenetFrames(e,t=!1){const i=new S,s=[],a=[],r=[],o=new S,l=new Me;for(let f=0;f<=e;f++){const p=f/e;s[f]=this.getTangentAt(p,new S)}a[0]=new S,r[0]=new S;let c=Number.MAX_VALUE;const u=Math.abs(s[0].x),d=Math.abs(s[0].y),h=Math.abs(s[0].z);u<=c&&(c=u,i.set(1,0,0)),d<=c&&(c=d,i.set(0,1,0)),h<=c&&i.set(0,0,1),o.crossVectors(s[0],i).normalize(),a[0].crossVectors(s[0],o),r[0].crossVectors(s[0],a[0]);for(let f=1;f<=e;f++){if(a[f]=a[f-1].clone(),r[f]=r[f-1].clone(),o.crossVectors(s[f-1],s[f]),o.length()>Number.EPSILON){o.normalize();const p=Math.acos(Ze(s[f-1].dot(s[f]),-1,1));a[f].applyMatrix4(l.makeRotationAxis(o,p))}r[f].crossVectors(s[f],a[f])}if(t===!0){let f=Math.acos(Ze(a[0].dot(a[e]),-1,1));f/=e,s[0].dot(o.crossVectors(a[0],a[e]))>0&&(f=-f);for(let p=1;p<=e;p++)a[p].applyMatrix4(l.makeRotationAxis(s[p],f*p)),r[p].crossVectors(s[p],a[p])}return{tangents:s,normals:a,binormals:r}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class zh extends Ri{constructor(e=0,t=0,i=1,s=1,a=0,r=Math.PI*2,o=!1,l=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=i,this.yRadius=s,this.aStartAngle=a,this.aEndAngle=r,this.aClockwise=o,this.aRotation=l}getPoint(e,t=new te){const i=t,s=Math.PI*2;let a=this.aEndAngle-this.aStartAngle;const r=Math.abs(a)s;)a-=s;a0?0:(Math.floor(Math.abs(o)/a)+1)*a:l===0&&o===a-1&&(o=a-2,l=1);let c,u;this.closed||o>0?c=s[(o-1)%a]:(Yc.subVectors(s[0],s[1]).add(s[0]),c=Yc);const d=s[o%a],h=s[(o+1)%a];if(this.closed||o+2s.length-2?s.length-1:r+1],d=s[r>s.length-3?s.length-1:r+2];return i.set(qy(o,l.x,c.x,u.x,d.x),qy(o,l.y,c.y,u.y,d.y)),i}copy(e){super.copy(e),this.points=[];for(let t=0,i=e.points.length;t=i){const r=s[a]-i,o=this.curves[a],l=o.getLength(),c=l===0?0:1-r/l;return o.getPointAt(c,t)}a++}return null}getLength(){const e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const e=[];let t=0;for(let i=0,s=this.curves.length;i1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,i=e.curves.length;t0){const d=c.getPoint(0);d.equals(this.currentPoint)||this.lineTo(d.x,d.y)}this.curves.push(c);const u=c.getPoint(1);return this.currentPoint.copy(u),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class Ns extends Zd{constructor(e){super(e),this.uuid=pi(),this.type="Shape",this.holes=[]}getPointsHoles(e){const t=[];for(let i=0,s=this.holes.length;i80*t){o=1/0,l=1/0;let u=-1/0,d=-1/0;for(let h=t;hu&&(u=f),p>d&&(d=p)}c=Math.max(u-o,d-l),c=c!==0?32767/c:0}return Gl(a,r,t,o,l,c,0),r}function MS(n,e,t,i,s){let a;if(s===nR(n,e,t,i)>0)for(let r=e;r=e;r-=i)a=Yy(r/i|0,n[r],n[r+1],a);return a&&Co(a,a.next)&&(Wl(a),a=a.next),a}function cr(n,e){if(!n)return n;e||(e=n);let t=n,i;do if(i=!1,!t.steiner&&(Co(t,t.next)||Kt(t.prev,t,t.next)===0)){if(Wl(t),t=e=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==e);return e}function Gl(n,e,t,i,s,a,r){if(!n)return;!r&&a&&jA(n,i,s,a);let o=n;for(;n.prev!==n.next;){const l=n.prev,c=n.next;if(a?VA(n,i,s,a):HA(n)){e.push(l.i,n.i,c.i),Wl(n),n=c.next,o=c.next;continue}if(n=c,n===o){r?r===1?(n=GA(cr(n),e),Gl(n,e,t,i,s,a,2)):r===2&&$A(n,e,t,i,s,a):Gl(cr(n),e,t,i,s,a,1);break}}}function HA(n){const e=n.prev,t=n,i=n.next;if(Kt(e,t,i)>=0)return!1;const s=e.x,a=t.x,r=i.x,o=e.y,l=t.y,c=i.y,u=Math.min(s,a,r),d=Math.min(o,l,c),h=Math.max(s,a,r),f=Math.max(o,l,c);let p=i.next;for(;p!==e;){if(p.x>=u&&p.x<=h&&p.y>=d&&p.y<=f&&hl(s,o,a,l,r,c,p.x,p.y)&&Kt(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function VA(n,e,t,i){const s=n.prev,a=n,r=n.next;if(Kt(s,a,r)>=0)return!1;const o=s.x,l=a.x,c=r.x,u=s.y,d=a.y,h=r.y,f=Math.min(o,l,c),p=Math.min(u,d,h),g=Math.max(o,l,c),_=Math.max(u,d,h),m=Tm(f,p,e,t,i),v=Tm(g,_,e,t,i);let y=n.prevZ,b=n.nextZ;for(;y&&y.z>=m&&b&&b.z<=v;){if(y.x>=f&&y.x<=g&&y.y>=p&&y.y<=_&&y!==s&&y!==r&&hl(o,u,l,d,c,h,y.x,y.y)&&Kt(y.prev,y,y.next)>=0||(y=y.prevZ,b.x>=f&&b.x<=g&&b.y>=p&&b.y<=_&&b!==s&&b!==r&&hl(o,u,l,d,c,h,b.x,b.y)&&Kt(b.prev,b,b.next)>=0))return!1;b=b.nextZ}for(;y&&y.z>=m;){if(y.x>=f&&y.x<=g&&y.y>=p&&y.y<=_&&y!==s&&y!==r&&hl(o,u,l,d,c,h,y.x,y.y)&&Kt(y.prev,y,y.next)>=0)return!1;y=y.prevZ}for(;b&&b.z<=v;){if(b.x>=f&&b.x<=g&&b.y>=p&&b.y<=_&&b!==s&&b!==r&&hl(o,u,l,d,c,h,b.x,b.y)&&Kt(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function GA(n,e){let t=n;do{const i=t.prev,s=t.next.next;!Co(i,s)&&CS(i,t,t.next,s)&&$l(i,s)&&$l(s,i)&&(e.push(i.i,t.i,s.i),Wl(t),Wl(t.next),t=n=s),t=t.next}while(t!==n);return cr(t)}function $A(n,e,t,i,s,a){let r=n;do{let o=r.next.next;for(;o!==r.prev;){if(r.i!==o.i&&QA(r,o)){let l=AS(r,o);r=cr(r,r.next),l=cr(l,l.next),Gl(r,e,t,i,s,a,0),Gl(l,e,t,i,s,a,0);return}o=o.next}r=r.next}while(r!==n)}function WA(n,e,t,i){const s=[];for(let a=0,r=e.length;a=t.next.y&&t.next.y!==t.y){const d=t.x+(s-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(d<=i&&d>a&&(a=d,r=t.x=t.x&&t.x>=l&&i!==t.x&&ES(sr.x||t.x===r.x&&YA(r,t)))&&(r=t,u=d)}t=t.next}while(t!==o);return r}function YA(n,e){return Kt(n.prev,n,e.prev)<0&&Kt(e.next,n,n.next)<0}function jA(n,e,t,i){let s=n;do s.z===0&&(s.z=Tm(s.x,s.y,e,t,i)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next;while(s!==n);s.prevZ.nextZ=null,s.prevZ=null,ZA(s)}function ZA(n){let e,t=1;do{let i=n,s;n=null;let a=null;for(e=0;i;){e++;let r=i,o=0;for(let c=0;c0||l>0&&r;)o!==0&&(l===0||!r||i.z<=r.z)?(s=i,i=i.nextZ,o--):(s=r,r=r.nextZ,l--),a?a.nextZ=s:n=s,s.prevZ=a,a=s;i=r}a.nextZ=null,t*=2}while(e>1);return n}function Tm(n,e,t,i,s){return n=(n-t)*s|0,e=(e-i)*s|0,n=(n|n<<8)&16711935,n=(n|n<<4)&252645135,n=(n|n<<2)&858993459,n=(n|n<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,n|e<<1}function JA(n){let e=n,t=n;do(e.x=(n-r)*(a-o)&&(n-r)*(i-o)>=(t-r)*(e-o)&&(t-r)*(a-o)>=(s-r)*(i-o)}function hl(n,e,t,i,s,a,r,o){return!(n===r&&e===o)&&ES(n,e,t,i,s,a,r,o)}function QA(n,e){return n.next.i!==e.i&&n.prev.i!==e.i&&!eR(n,e)&&($l(n,e)&&$l(e,n)&&tR(n,e)&&(Kt(n.prev,n,e.prev)||Kt(n,e.prev,e))||Co(n,e)&&Kt(n.prev,n,n.next)>0&&Kt(e.prev,e,e.next)>0)}function Kt(n,e,t){return(e.y-n.y)*(t.x-e.x)-(e.x-n.x)*(t.y-e.y)}function Co(n,e){return n.x===e.x&&n.y===e.y}function CS(n,e,t,i){const s=Zc(Kt(n,e,t)),a=Zc(Kt(n,e,i)),r=Zc(Kt(t,i,n)),o=Zc(Kt(t,i,e));return!!(s!==a&&r!==o||s===0&&jc(n,t,e)||a===0&&jc(n,i,e)||r===0&&jc(t,n,i)||o===0&&jc(t,e,i))}function jc(n,e,t){return e.x<=Math.max(n.x,t.x)&&e.x>=Math.min(n.x,t.x)&&e.y<=Math.max(n.y,t.y)&&e.y>=Math.min(n.y,t.y)}function Zc(n){return n>0?1:n<0?-1:0}function eR(n,e){let t=n;do{if(t.i!==n.i&&t.next.i!==n.i&&t.i!==e.i&&t.next.i!==e.i&&CS(t,t.next,n,e))return!0;t=t.next}while(t!==n);return!1}function $l(n,e){return Kt(n.prev,n,n.next)<0?Kt(n,e,n.next)>=0&&Kt(n,n.prev,e)>=0:Kt(n,e,n.prev)<0||Kt(n,n.next,e)<0}function tR(n,e){let t=n,i=!1;const s=(n.x+e.x)/2,a=(n.y+e.y)/2;do t.y>a!=t.next.y>a&&t.next.y!==t.y&&s<(t.next.x-t.x)*(a-t.y)/(t.next.y-t.y)+t.x&&(i=!i),t=t.next;while(t!==n);return i}function AS(n,e){const t=Mm(n.i,n.x,n.y),i=Mm(e.i,e.x,e.y),s=n.next,a=e.prev;return n.next=e,e.prev=n,t.next=s,s.prev=t,i.next=t,t.prev=i,a.next=i,i.prev=a,i}function Yy(n,e,t,i){const s=Mm(n,e,t);return i?(s.next=i.next,s.prev=i,i.next.prev=s,i.next=s):(s.prev=s,s.next=s),s}function Wl(n){n.next.prev=n.prev,n.prev.next=n.next,n.prevZ&&(n.prevZ.nextZ=n.nextZ),n.nextZ&&(n.nextZ.prevZ=n.prevZ)}function Mm(n,e,t){return{i:n,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function nR(n,e,t,i){let s=0;for(let a=e,r=t-i;a2&&n[e-1].equals(n[0])&&n.pop()}function Zy(n,e){for(let t=0;tNumber.EPSILON){const J=Math.sqrt(A),le=Math.sqrt(it*it+I*I),ee=j.x-$e/J,He=j.y+ge/J,ye=Y.x-I/le,Ue=Y.y+it/le,Be=((ye-ee)*I-(Ue-He)*it)/(ge*I-$e*it);Q=ee+ge*Be-G.x,_e=He+$e*Be-G.y;const de=Q*Q+_e*_e;if(de<=2)return new te(Q,_e);ce=Math.sqrt(de/2)}else{let J=!1;ge>Number.EPSILON?it>Number.EPSILON&&(J=!0):ge<-Number.EPSILON?it<-Number.EPSILON&&(J=!0):Math.sign($e)===Math.sign(I)&&(J=!0),J?(Q=-$e,_e=ge,ce=Math.sqrt(A)):(Q=ge,_e=$e,ce=Math.sqrt(A/2))}return new te(Q/ce,_e/ce)}const ne=[];for(let G=0,j=U.length,Y=j-1,Q=G+1;G=0;G--){const j=G/_,Y=f*Math.cos(j*Math.PI/2),Q=p*Math.sin(j*Math.PI/2)+g;for(let _e=0,ce=U.length;_e=0;){const Q=Y;let _e=Y-1;_e<0&&(_e=G.length-1);for(let ce=0,ge=u+_*2;ce0)&&f.push(y,b,x),(m!==i-1||l0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class Ya extends Qt{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new ue(16777215),this.specular=new ue(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ue(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ha,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new an,this.combine=nc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class IS extends Qt{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new ue(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ue(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ha,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class LS extends Qt{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ha,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class qh extends Qt{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new ue(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ue(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ha,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new an,this.combine=nc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class dg extends Qt{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=Qw,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class hg extends Qt{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class DS extends Qt{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new ue(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ha,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}class kS extends Rt{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}function ja(n,e){return!n||n.constructor===e?n:typeof e.BYTES_PER_ELEMENT=="number"?new e(n):Array.prototype.slice.call(n)}function OS(n){return ArrayBuffer.isView(n)&&!(n instanceof DataView)}function FS(n){function e(s,a){return n[s]-n[a]}const t=n.length,i=new Array(t);for(let s=0;s!==t;++s)i[s]=s;return i.sort(e),i}function Em(n,e,t){const i=n.length,s=new n.constructor(i);for(let a=0,r=0;r!==i;++a){const o=t[a]*e;for(let l=0;l!==e;++l)s[r++]=n[o+l]}return s}function fg(n,e,t,i){let s=1,a=n[0];for(;a!==void 0&&a[i]===void 0;)a=n[s++];if(a===void 0)return;let r=a[i];if(r!==void 0)if(Array.isArray(r))do r=a[i],r!==void 0&&(e.push(a.time),t.push(...r)),a=n[s++];while(a!==void 0);else if(r.toArray!==void 0)do r=a[i],r!==void 0&&(e.push(a.time),r.toArray(t,t.length)),a=n[s++];while(a!==void 0);else do r=a[i],r!==void 0&&(e.push(a.time),t.push(r)),a=n[s++];while(a!==void 0)}function oR(n,e,t,i,s=30){const a=n.clone();a.name=e;const r=[];for(let l=0;l=i)){d.push(c.times[f]);for(let g=0;ga.tracks[l].times[0]&&(o=a.tracks[l].times[0]);for(let l=0;l=o.times[p]){const m=p*d+u,v=m+d-u;g=o.values.slice(m,v)}else{const m=o.createInterpolant(),v=u,y=d-u;m.evaluate(a),g=m.resultBuffer.slice(v,y)}l==="quaternion"&&new dt().fromArray(g).normalize().conjugate().toArray(g);const _=c.times.length;for(let m=0;m<_;++m){const v=m*f+h;if(l==="quaternion")dt.multiplyQuaternionsFlat(c.values,v,g,0,c.values,v);else{const y=f-h*2;for(let b=0;b=a)){const o=t[1];e=a)break t}r=i,i=0;break n}break e}for(;i>>1;et;)--r;if(++r,a!==0||r!==s){a>=r&&(r=Math.max(r,1),a=r-1);const o=this.getValueSize();this.times=i.slice(a,r),this.values=this.values.slice(a*o,r*o)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const i=this.times,s=this.values,a=i.length;a===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let r=null;for(let o=0;o!==a;o++){const l=i[o];if(typeof l=="number"&&isNaN(l)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,o,l),e=!1;break}if(r!==null&&r>l){console.error("THREE.KeyframeTrack: Out of order keys.",this,o,l,r),e=!1;break}r=l}if(s!==void 0&&OS(s))for(let o=0,l=s.length;o!==l;++o){const c=s[o];if(isNaN(c)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,o,c),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),i=this.getValueSize(),s=this.getInterpolation()===Vu,a=e.length-1;let r=1;for(let o=1;o0){e[r]=e[a];for(let o=a*i,l=r*i,c=0;c!==i;++c)t[l+c]=t[o+c];++r}return r!==e.length?(this.times=e.slice(0,r),this.values=t.slice(0,r*i)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),i=this.constructor,s=new i(this.name,e,t);return s.createInterpolant=this.createInterpolant,s}}Pi.prototype.ValueTypeName="";Pi.prototype.TimeBufferType=Float32Array;Pi.prototype.ValueBufferType=Float32Array;Pi.prototype.DefaultInterpolation=rr;class pr extends Pi{constructor(e,t,i){super(e,t,i)}}pr.prototype.ValueTypeName="bool";pr.prototype.ValueBufferType=Array;pr.prototype.DefaultInterpolation=wo;pr.prototype.InterpolantFactoryMethodLinear=void 0;pr.prototype.InterpolantFactoryMethodSmooth=void 0;class mg extends Pi{constructor(e,t,i,s){super(e,t,i,s)}}mg.prototype.ValueTypeName="color";class ca extends Pi{constructor(e,t,i,s){super(e,t,i,s)}}ca.prototype.ValueTypeName="number";class BS extends Lo{constructor(e,t,i,s){super(e,t,i,s)}interpolate_(e,t,i,s){const a=this.resultBuffer,r=this.sampleValues,o=this.valueSize,l=(i-t)/(s-t);let c=e*o;for(let u=c+o;c!==u;c+=4)dt.slerpFlat(a,0,r,c-o,r,c,l);return a}}class _s extends Pi{constructor(e,t,i,s){super(e,t,i,s)}InterpolantFactoryMethodLinear(e){return new BS(this.times,this.values,this.getValueSize(),e)}}_s.prototype.ValueTypeName="quaternion";_s.prototype.InterpolantFactoryMethodSmooth=void 0;class mr extends Pi{constructor(e,t,i){super(e,t,i)}}mr.prototype.ValueTypeName="string";mr.prototype.ValueBufferType=Array;mr.prototype.DefaultInterpolation=wo;mr.prototype.InterpolantFactoryMethodLinear=void 0;mr.prototype.InterpolantFactoryMethodSmooth=void 0;class Hs extends Pi{constructor(e,t,i,s){super(e,t,i,s)}}Hs.prototype.ValueTypeName="vector";class ua{constructor(e="",t=-1,i=[],s=Sh){this.name=e,this.tracks=i,this.duration=t,this.blendMode=s,this.uuid=pi(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){const t=[],i=e.tracks,s=1/(e.fps||1);for(let r=0,o=i.length;r!==o;++r)t.push(dR(i[r]).scale(s));const a=new this(e.name,e.duration,t,e.blendMode);return a.uuid=e.uuid,a.userData=JSON.parse(e.userData||"{}"),a}static toJSON(e){const t=[],i=e.tracks,s={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let a=0,r=i.length;a!==r;++a)t.push(Pi.toJSON(i[a]));return s}static CreateFromMorphTargetSequence(e,t,i,s){const a=t.length,r=[];for(let o=0;o1){const d=u[1];let h=s[d];h||(s[d]=h=[]),h.push(c)}}const r=[];for(const o in s)r.push(this.CreateFromMorphTargetSequence(o,s[o],t,i));return r}static parseAnimation(e,t){if(console.warn("THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const i=function(d,h,f,p,g){if(f.length!==0){const _=[],m=[];fg(f,_,m,p),_.length!==0&&g.push(new d(h,_,m))}},s=[],a=e.name||"default",r=e.fps||30,o=e.blendMode;let l=e.length||-1;const c=e.hierarchy||[];for(let d=0;d{t&&t(a),this.manager.itemEnd(e)},0),a;if(Ts[e]!==void 0){Ts[e].push({onLoad:t,onProgress:i,onError:s});return}Ts[e]=[],Ts[e].push({onLoad:t,onProgress:i,onError:s});const r=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,l=this.responseType;fetch(r).then(c=>{if(c.status===200||c.status===0){if(c.status===0&&console.warn("THREE.FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||c.body===void 0||c.body.getReader===void 0)return c;const u=Ts[e],d=c.body.getReader(),h=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),f=h?parseInt(h):0,p=f!==0;let g=0;const _=new ReadableStream({start(m){v();function v(){d.read().then(({done:y,value:b})=>{if(y)m.close();else{g+=b.byteLength;const T=new ProgressEvent("progress",{lengthComputable:p,loaded:g,total:f});for(let x=0,M=u.length;x{m.error(y)})}}});return new Response(_)}else throw new hR(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`,c)}).then(c=>{switch(l){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then(u=>new DOMParser().parseFromString(u,o));case"json":return c.json();default:if(o==="")return c.text();{const d=/charset="?([^;"\s]*)"?/i.exec(o),h=d&&d[1]?d[1].toLowerCase():void 0,f=new TextDecoder(h);return c.arrayBuffer().then(p=>f.decode(p))}}}).then(c=>{cs.add(`file:${e}`,c);const u=Ts[e];delete Ts[e];for(let d=0,h=u.length;d{const u=Ts[e];if(u===void 0)throw this.manager.itemError(e),c;delete Ts[e];for(let d=0,h=u.length;d{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}class fR extends on{constructor(e){super(e)}load(e,t,i,s){const a=this,r=new Gn(this.manager);r.setPath(this.path),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,function(o){try{t(a.parse(JSON.parse(o)))}catch(l){s?s(l):console.error(l),a.manager.itemError(e)}},i,s)}parse(e){const t=[];for(let i=0;i0:s.vertexColors=e.vertexColors),e.uniforms!==void 0)for(const a in e.uniforms){const r=e.uniforms[a];switch(s.uniforms[a]={},r.type){case"t":s.uniforms[a].value=i(r.value);break;case"c":s.uniforms[a].value=new ue().setHex(r.value);break;case"v2":s.uniforms[a].value=new te().fromArray(r.value);break;case"v3":s.uniforms[a].value=new S().fromArray(r.value);break;case"v4":s.uniforms[a].value=new qe().fromArray(r.value);break;case"m3":s.uniforms[a].value=new st().fromArray(r.value);break;case"m4":s.uniforms[a].value=new Me().fromArray(r.value);break;default:s.uniforms[a].value=r.value}}if(e.defines!==void 0&&(s.defines=e.defines),e.vertexShader!==void 0&&(s.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(s.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(s.glslVersion=e.glslVersion),e.extensions!==void 0)for(const a in e.extensions)s.extensions[a]=e.extensions[a];if(e.lights!==void 0&&(s.lights=e.lights),e.clipping!==void 0&&(s.clipping=e.clipping),e.size!==void 0&&(s.size=e.size),e.sizeAttenuation!==void 0&&(s.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(s.map=i(e.map)),e.matcap!==void 0&&(s.matcap=i(e.matcap)),e.alphaMap!==void 0&&(s.alphaMap=i(e.alphaMap)),e.bumpMap!==void 0&&(s.bumpMap=i(e.bumpMap)),e.bumpScale!==void 0&&(s.bumpScale=e.bumpScale),e.normalMap!==void 0&&(s.normalMap=i(e.normalMap)),e.normalMapType!==void 0&&(s.normalMapType=e.normalMapType),e.normalScale!==void 0){let a=e.normalScale;Array.isArray(a)===!1&&(a=[a,a]),s.normalScale=new te().fromArray(a)}return e.displacementMap!==void 0&&(s.displacementMap=i(e.displacementMap)),e.displacementScale!==void 0&&(s.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(s.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(s.roughnessMap=i(e.roughnessMap)),e.metalnessMap!==void 0&&(s.metalnessMap=i(e.metalnessMap)),e.emissiveMap!==void 0&&(s.emissiveMap=i(e.emissiveMap)),e.emissiveIntensity!==void 0&&(s.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(s.specularMap=i(e.specularMap)),e.specularIntensityMap!==void 0&&(s.specularIntensityMap=i(e.specularIntensityMap)),e.specularColorMap!==void 0&&(s.specularColorMap=i(e.specularColorMap)),e.envMap!==void 0&&(s.envMap=i(e.envMap)),e.envMapRotation!==void 0&&s.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(s.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(s.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(s.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(s.lightMap=i(e.lightMap)),e.lightMapIntensity!==void 0&&(s.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(s.aoMap=i(e.aoMap)),e.aoMapIntensity!==void 0&&(s.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(s.gradientMap=i(e.gradientMap)),e.clearcoatMap!==void 0&&(s.clearcoatMap=i(e.clearcoatMap)),e.clearcoatRoughnessMap!==void 0&&(s.clearcoatRoughnessMap=i(e.clearcoatRoughnessMap)),e.clearcoatNormalMap!==void 0&&(s.clearcoatNormalMap=i(e.clearcoatNormalMap)),e.clearcoatNormalScale!==void 0&&(s.clearcoatNormalScale=new te().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(s.iridescenceMap=i(e.iridescenceMap)),e.iridescenceThicknessMap!==void 0&&(s.iridescenceThicknessMap=i(e.iridescenceThicknessMap)),e.transmissionMap!==void 0&&(s.transmissionMap=i(e.transmissionMap)),e.thicknessMap!==void 0&&(s.thicknessMap=i(e.thicknessMap)),e.anisotropyMap!==void 0&&(s.anisotropyMap=i(e.anisotropyMap)),e.sheenColorMap!==void 0&&(s.sheenColorMap=i(e.sheenColorMap)),e.sheenRoughnessMap!==void 0&&(s.sheenRoughnessMap=i(e.sheenRoughnessMap)),s}setTextures(e){return this.textures=e,this}createMaterialFromType(e){return Zh.createMaterialFromType(e)}static createMaterialFromType(e){const t={ShadowMaterial:RS,SpriteMaterial:Ih,RawShaderMaterial:PS,ShaderMaterial:ti,PointsMaterial:sa,MeshPhysicalMaterial:ii,MeshStandardMaterial:Pn,MeshPhongMaterial:Ya,MeshToonMaterial:IS,MeshNormalMaterial:LS,MeshLambertMaterial:qh,MeshDepthMaterial:dg,MeshDistanceMaterial:hg,MeshBasicMaterial:Ye,MeshMatcapMaterial:DS,LineDashedMaterial:kS,LineBasicMaterial:Rt,Material:Qt};return new t[e]}}class Us{static extractUrlBase(e){const t=e.lastIndexOf("/");return t===-1?"./":e.slice(0,t+1)}static resolveURL(e,t){return typeof e!="string"||e===""?"":(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}}class XS extends Ge{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){const e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}}class KS extends on{constructor(e){super(e)}load(e,t,i,s){const a=this,r=new Gn(a.manager);r.setPath(a.path),r.setRequestHeader(a.requestHeader),r.setWithCredentials(a.withCredentials),r.load(e,function(o){try{t(a.parse(JSON.parse(o)))}catch(l){s?s(l):console.error(l),a.manager.itemError(e)}},i,s)}parse(e){const t={},i={};function s(f,p){if(t[p]!==void 0)return t[p];const _=f.interleavedBuffers[p],m=a(f,_.buffer),v=Yr(_.type,m),y=new rc(v,_.stride);return y.uuid=_.uuid,t[p]=y,y}function a(f,p){if(i[p]!==void 0)return i[p];const _=f.arrayBuffers[p],m=new Uint32Array(_).buffer;return i[p]=m,m}const r=e.isInstancedBufferGeometry?new XS:new Ge,o=e.data.index;if(o!==void 0){const f=Yr(o.type,o.array);r.setIndex(new rt(f,1))}const l=e.data.attributes;for(const f in l){const p=l[f];let g;if(p.isInterleavedBufferAttribute){const _=s(e.data,p.data);g=new la(_,p.itemSize,p.offset,p.normalized)}else{const _=Yr(p.type,p.array),m=p.isInstancedBufferAttribute?or:rt;g=new m(_,p.itemSize,p.normalized)}p.name!==void 0&&(g.name=p.name),p.usage!==void 0&&g.setUsage(p.usage),r.setAttribute(f,g)}const c=e.data.morphAttributes;if(c)for(const f in c){const p=c[f],g=[];for(let _=0,m=p.length;_0){const l=new _g(t);a=new Xl(l),a.setCrossOrigin(this.crossOrigin);for(let c=0,u=e.length;c0){s=new Xl(this.manager),s.setCrossOrigin(this.crossOrigin);for(let r=0,o=e.length;r{let _=null,m=null;return g.boundingBox!==void 0&&(_=new vn().fromJSON(g.boundingBox)),g.boundingSphere!==void 0&&(m=new bn().fromJSON(g.boundingSphere)),{...g,boundingBox:_,boundingSphere:m}}),r._instanceInfo=e.instanceInfo,r._availableInstanceIds=e._availableInstanceIds,r._availableGeometryIds=e._availableGeometryIds,r._nextIndexStart=e.nextIndexStart,r._nextVertexStart=e.nextVertexStart,r._geometryCount=e.geometryCount,r._maxInstanceCount=e.maxInstanceCount,r._maxVertexCount=e.maxVertexCount,r._maxIndexCount=e.maxIndexCount,r._geometryInitialized=e.geometryInitialized,r._matricesTexture=c(e.matricesTexture.uuid),r._indirectTexture=c(e.indirectTexture.uuid),e.colorsTexture!==void 0&&(r._colorsTexture=c(e.colorsTexture.uuid)),e.boundingSphere!==void 0&&(r.boundingSphere=new bn().fromJSON(e.boundingSphere)),e.boundingBox!==void 0&&(r.boundingBox=new vn().fromJSON(e.boundingBox));break;case"LOD":r=new yS;break;case"Line":r=new In(o(e.geometry),l(e.material));break;case"LineLoop":r=new eg(o(e.geometry),l(e.material));break;case"LineSegments":r=new Ln(o(e.geometry),l(e.material));break;case"PointCloud":case"Points":r=new ir(o(e.geometry),l(e.material));break;case"Sprite":r=new Lh(l(e.material));break;case"Group":r=new Mt;break;case"Bone":r=new Eo;break;default:r=new Qe}if(r.uuid=e.uuid,e.name!==void 0&&(r.name=e.name),e.matrix!==void 0?(r.matrix.fromArray(e.matrix),e.matrixAutoUpdate!==void 0&&(r.matrixAutoUpdate=e.matrixAutoUpdate),r.matrixAutoUpdate&&r.matrix.decompose(r.position,r.quaternion,r.scale)):(e.position!==void 0&&r.position.fromArray(e.position),e.rotation!==void 0&&r.rotation.fromArray(e.rotation),e.quaternion!==void 0&&r.quaternion.fromArray(e.quaternion),e.scale!==void 0&&r.scale.fromArray(e.scale)),e.up!==void 0&&r.up.fromArray(e.up),e.castShadow!==void 0&&(r.castShadow=e.castShadow),e.receiveShadow!==void 0&&(r.receiveShadow=e.receiveShadow),e.shadow&&(e.shadow.intensity!==void 0&&(r.shadow.intensity=e.shadow.intensity),e.shadow.bias!==void 0&&(r.shadow.bias=e.shadow.bias),e.shadow.normalBias!==void 0&&(r.shadow.normalBias=e.shadow.normalBias),e.shadow.radius!==void 0&&(r.shadow.radius=e.shadow.radius),e.shadow.mapSize!==void 0&&r.shadow.mapSize.fromArray(e.shadow.mapSize),e.shadow.camera!==void 0&&(r.shadow.camera=this.parseObject(e.shadow.camera))),e.visible!==void 0&&(r.visible=e.visible),e.frustumCulled!==void 0&&(r.frustumCulled=e.frustumCulled),e.renderOrder!==void 0&&(r.renderOrder=e.renderOrder),e.userData!==void 0&&(r.userData=e.userData),e.layers!==void 0&&(r.layers.mask=e.layers),e.children!==void 0){const h=e.children;for(let f=0;f"u"&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,i,s){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const a=this,r=cs.get(`image-bitmap:${e}`);if(r!==void 0){if(a.manager.itemStart(e),r.then){r.then(c=>{if(Kf.has(r)===!0)s&&s(Kf.get(r)),a.manager.itemError(e),a.manager.itemEnd(e);else return t&&t(c),a.manager.itemEnd(e),c});return}return setTimeout(function(){t&&t(r),a.manager.itemEnd(e)},0),r}const o={};o.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",o.headers=this.requestHeader,o.signal=typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;const l=fetch(e,o).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign(a.options,{colorSpaceConversion:"none"}))}).then(function(c){return cs.add(`image-bitmap:${e}`,c),t&&t(c),a.manager.itemEnd(e),c}).catch(function(c){s&&s(c),Kf.set(l,c),cs.remove(`image-bitmap:${e}`),a.manager.itemError(e),a.manager.itemEnd(e)});cs.add(`image-bitmap:${e}`,l),a.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}let Jc;class yg{static getContext(){return Jc===void 0&&(Jc=new(window.AudioContext||window.webkitAudioContext)),Jc}static setContext(e){Jc=e}}class xR extends on{constructor(e){super(e)}load(e,t,i,s){const a=this,r=new Gn(this.manager);r.setResponseType("arraybuffer"),r.setPath(this.path),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,function(l){try{const c=l.slice(0);yg.getContext().decodeAudioData(c,function(d){t(d)}).catch(o)}catch(c){o(c)}},i,s);function o(l){s?s(l):console.error(l),a.manager.itemError(e)}}}const a0=new Me,r0=new Me,Sa=new Me;class wR{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new Jt,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Jt,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){const t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,Sa.copy(e.projectionMatrix);const s=t.eyeSep/2,a=s*t.near/t.focus,r=t.near*Math.tan(nr*t.fov*.5)/t.zoom;let o,l;r0.elements[12]=-s,a0.elements[12]=s,o=-r*t.aspect+a,l=r*t.aspect+a,Sa.elements[0]=2*t.near/(l-o),Sa.elements[8]=(l+o)/(l-o),this.cameraL.projectionMatrix.copy(Sa),o=-r*t.aspect-a,l=r*t.aspect-a,Sa.elements[0]=2*t.near/(l-o),Sa.elements[8]=(l+o)/(l-o),this.cameraR.projectionMatrix.copy(Sa)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(r0),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(a0)}}class YS extends Jt{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class vg{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}const Ta=new S,qf=new dt,SR=new S,Ma=new S,Ea=new S;class TR extends Qe{constructor(){super(),this.type="AudioListener",this.context=yg.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new vg}getInput(){return this.gain}removeFilter(){return this.filter!==null&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return this.filter!==null?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e);const t=this.context.listener;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(Ta,qf,SR),Ma.set(0,0,-1).applyQuaternion(qf),Ea.set(0,1,0).applyQuaternion(qf),t.positionX){const i=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(Ta.x,i),t.positionY.linearRampToValueAtTime(Ta.y,i),t.positionZ.linearRampToValueAtTime(Ta.z,i),t.forwardX.linearRampToValueAtTime(Ma.x,i),t.forwardY.linearRampToValueAtTime(Ma.y,i),t.forwardZ.linearRampToValueAtTime(Ma.z,i),t.upX.linearRampToValueAtTime(Ea.x,i),t.upY.linearRampToValueAtTime(Ea.y,i),t.upZ.linearRampToValueAtTime(Ea.z,i)}else t.setPosition(Ta.x,Ta.y,Ta.z),t.setOrientation(Ma.x,Ma.y,Ma.z,Ea.x,Ea.y,Ea.z)}}class jS extends Qe{constructor(e){super(),this.type="Audio",this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType="buffer",this.autoplay&&this.play(),this}play(e=0){if(this.isPlaying===!0){console.warn("THREE.Audio: Audio is already playing.");return}if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}this._startedAt=this.context.currentTime+e;const t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.isPlaying===!0&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this}stop(e=0){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this._progress=0,this.source!==null&&(this.source.stop(this.context.currentTime+e),this.source.onended=null),this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(i,s,this._addIndex*t,1,t);for(let l=t,c=t+t;l!==c;++l)if(i[l]!==i[l+t]){o.setValue(i,s);break}}saveOriginalState(){const e=this.binding,t=this.buffer,i=this.valueSize,s=i*this._origIndex;e.getValue(t,s);for(let a=i,r=s;a!==r;++a)t[a]=t[s+a%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let i=e;i=.5)for(let r=0;r!==a;++r)e[t+r]=e[i+r]}_slerp(e,t,i,s){dt.slerpFlat(e,t,e,t,e,i,s)}_slerpAdditive(e,t,i,s,a){const r=this._workIndex*a;dt.multiplyQuaternionsFlat(e,r,e,t,e,i),dt.slerpFlat(e,t,e,t,e,r,s)}_lerp(e,t,i,s,a){const r=1-s;for(let o=0;o!==a;++o){const l=t+o;e[l]=e[l]*r+e[i+o]*s}}_lerpAdditive(e,t,i,s,a){for(let r=0;r!==a;++r){const o=t+r;e[o]=e[o]+e[i+r]*s}}}const bg="\\[\\]\\.:\\/",AR=new RegExp("["+bg+"]","g"),xg="[^"+bg+"]",RR="[^"+bg.replace("\\.","")+"]",PR=/((?:WC+[\/:])*)/.source.replace("WC",xg),IR=/(WCOD+)?/.source.replace("WCOD",RR),LR=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",xg),DR=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",xg),kR=new RegExp("^"+PR+IR+LR+DR+"$"),OR=["material","materials","bones","map"];class FR{constructor(e,t,i){const s=i||yt.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,s)}getValue(e,t){this.bind();const i=this._targetGroup.nCachedObjects_,s=this._bindings[i];s!==void 0&&s.getValue(e,t)}setValue(e,t){const i=this._bindings;for(let s=this._targetGroup.nCachedObjects_,a=i.length;s!==a;++s)i[s].setValue(e,t)}bind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].bind()}unbind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].unbind()}}class yt{constructor(e,t,i){this.path=t,this.parsedPath=i||yt.parseTrackName(t),this.node=yt.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,i){return e&&e.isAnimationObjectGroup?new yt.Composite(e,t,i):new yt(e,t,i)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(AR,"")}static parseTrackName(e){const t=kR.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const i={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},s=i.nodeName&&i.nodeName.lastIndexOf(".");if(s!==void 0&&s!==-1){const a=i.nodeName.substring(s+1);OR.indexOf(a)!==-1&&(i.nodeName=i.nodeName.substring(0,s),i.objectName=a)}if(i.propertyName===null||i.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return i}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){const i=e.skeleton.getBoneByName(t);if(i!==void 0)return i}if(e.children){const i=function(a){for(let r=0;r=a){const d=a++,h=e[d];t[h.uuid]=u,e[u]=h,t[c]=d,e[d]=l;for(let f=0,p=s;f!==p;++f){const g=i[f],_=g[d],m=g[u];g[u]=_,g[d]=m}}}this.nCachedObjects_=a}uncache(){const e=this._objects,t=this._indicesByUUID,i=this._bindings,s=i.length;let a=this.nCachedObjects_,r=e.length;for(let o=0,l=arguments.length;o!==l;++o){const c=arguments[o],u=c.uuid,d=t[u];if(d!==void 0)if(delete t[u],d0&&(t[f.uuid]=d),e[d]=f,e.pop();for(let p=0,g=s;p!==g;++p){const _=i[p];_[d]=_[h],_.pop()}}}this.nCachedObjects_=a}subscribe_(e,t){const i=this._bindingsIndicesByPath;let s=i[e];const a=this._bindings;if(s!==void 0)return a[s];const r=this._paths,o=this._parsedPaths,l=this._objects,c=l.length,u=this.nCachedObjects_,d=new Array(c);s=a.length,i[e]=s,r.push(e),o.push(t),a.push(d);for(let h=u,f=l.length;h!==f;++h){const p=l[h];d[h]=new yt(p,e,t)}return d}unsubscribe_(e){const t=this._bindingsIndicesByPath,i=t[e];if(i!==void 0){const s=this._paths,a=this._parsedPaths,r=this._bindings,o=r.length-1,l=r[o],c=e[o];t[c]=i,r[i]=l,r.pop(),a[i]=a[o],a.pop(),s[i]=s[o],s.pop()}}}class JS{constructor(e,t,i=null,s=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=i,this.blendMode=s;const a=t.tracks,r=a.length,o=new Array(r),l={endingStart:Ka,endingEnd:Ka};for(let c=0;c!==r;++c){const u=a[c].createInterpolant(null);o[c]=u,u.settings=l}this._interpolantSettings=l,this._interpolants=o,this._propertyBindings=new Array(r),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=jw,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,i=!1){if(e.fadeOut(t),this.fadeIn(t),i===!0){const s=this._clip.duration,a=e._clip.duration,r=a/s,o=s/a;e.warp(1,r,t),this.warp(o,1,t)}return this}crossFadeTo(e,t,i=!1){return e.crossFadeFrom(this,t,i)}stopFading(){const e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,i){const s=this._mixer,a=s.time,r=this.timeScale;let o=this._timeScaleInterpolant;o===null&&(o=s._lendControlInterpolant(),this._timeScaleInterpolant=o);const l=o.parameterPositions,c=o.sampleValues;return l[0]=a,l[1]=a+i,c[0]=e/r,c[1]=t/r,this}stopWarping(){const e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,i,s){if(!this.enabled){this._updateWeight(e);return}const a=this._startTime;if(a!==null){const l=(e-a)*i;l<0||i===0?t=0:(this._startTime=null,t=i*l)}t*=this._updateTimeScale(e);const r=this._updateTime(t),o=this._updateWeight(e);if(o>0){const l=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case q_:for(let u=0,d=l.length;u!==d;++u)l[u].evaluate(r),c[u].accumulateAdditive(o);break;case Sh:default:for(let u=0,d=l.length;u!==d;++u)l[u].evaluate(r),c[u].accumulate(s,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const i=this._weightInterpolant;if(i!==null){const s=i.evaluate(e)[0];t*=s,e>i.parameterPositions[1]&&(this.stopFading(),s===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const i=this._timeScaleInterpolant;if(i!==null){const s=i.evaluate(e)[0];t*=s,e>i.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,i=this.loop;let s=this.time+e,a=this._loopCount;const r=i===Zw;if(e===0)return a===-1?s:r&&(a&1)===1?t-s:s;if(i===Xd){a===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(s>=t)s=t;else if(s<0)s=0;else{this.time=s;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(a===-1&&(e>=0?(a=0,this._setEndings(!0,this.repetitions===0,r)):this._setEndings(this.repetitions===0,!0,r)),s>=t||s<0){const o=Math.floor(s/t);s-=t*o,a+=Math.abs(o);const l=this.repetitions-a;if(l<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,s=e>0?t:0,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(l===1){const c=e<0;this._setEndings(c,!c,r)}else this._setEndings(!1,!1,r);this._loopCount=a,this.time=s,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this.time=s;if(r&&(a&1)===1)return t-s}return s}_setEndings(e,t,i){const s=this._interpolantSettings;i?(s.endingStart=qa,s.endingEnd=qa):(e?s.endingStart=this.zeroSlopeAtStart?qa:Ka:s.endingStart=Ul,t?s.endingEnd=this.zeroSlopeAtEnd?qa:Ka:s.endingEnd=Ul)}_scheduleFading(e,t,i){const s=this._mixer,a=s.time;let r=this._weightInterpolant;r===null&&(r=s._lendControlInterpolant(),this._weightInterpolant=r);const o=r.parameterPositions,l=r.sampleValues;return o[0]=a,l[0]=t,o[1]=a+e,l[1]=i,this}}const UR=new Float32Array(1);class QS extends gs{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const i=e._localRoot||this._root,s=e._clip.tracks,a=s.length,r=e._propertyBindings,o=e._interpolants,l=i.uuid,c=this._bindingsByRootAndName;let u=c[l];u===void 0&&(u={},c[l]=u);for(let d=0;d!==a;++d){const h=s[d],f=h.name;let p=u[f];if(p!==void 0)++p.referenceCount,r[d]=p;else{if(p=r[d],p!==void 0){p._cacheIndex===null&&(++p.referenceCount,this._addInactiveBinding(p,l,f));continue}const g=t&&t._propertyBindings[d].binding.parsedPath;p=new ZS(yt.create(i,f,g),h.ValueTypeName,h.getValueSize()),++p.referenceCount,this._addInactiveBinding(p,l,f),r[d]=p}o[d].resultBuffer=p.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){const i=(e._localRoot||this._root).uuid,s=e._clip.uuid,a=this._actionsByClip[s];this._bindAction(e,a&&a.knownActions[0]),this._addInactiveAction(e,s,i)}const t=e._propertyBindings;for(let i=0,s=t.length;i!==s;++i){const a=t[i];a.useCount++===0&&(this._lendBinding(a),a.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let i=0,s=t.length;i!==s;++i){const a=t[i];--a.useCount===0&&(a.restoreOriginalState(),this._takeBackBinding(a))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return t!==null&&t=0;--i)e[i].stop();return this}update(e){e*=this.timeScale;const t=this._actions,i=this._nActiveActions,s=this.time+=e,a=Math.sign(e),r=this._accuIndex^=1;for(let c=0;c!==i;++c)t[c]._update(s,e,a,r);const o=this._bindings,l=this._nActiveBindings;for(let c=0;c!==l;++c)o[c].apply(r);return this}setTime(e){this.time=0;for(let t=0;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,u0).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const d0=new S,Qc=new S,Fr=new S,Nr=new S,Yf=new S,YR=new S,jR=new S;class ZR{constructor(e=new S,t=new S){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){d0.subVectors(e,this.start),Qc.subVectors(this.end,this.start);const i=Qc.dot(Qc);let a=Qc.dot(d0)/i;return t&&(a=Ze(a,0,1)),a}closestPointToPoint(e,t,i){const s=this.closestPointToPointParameter(e,t);return this.delta(i).multiplyScalar(s).add(this.start)}distanceSqToLine3(e,t=YR,i=jR){const s=10000000000000001e-32;let a,r;const o=this.start,l=e.start,c=this.end,u=e.end;Fr.subVectors(c,o),Nr.subVectors(u,l),Yf.subVectors(o,l);const d=Fr.dot(Fr),h=Nr.dot(Nr),f=Nr.dot(Yf);if(d<=s&&h<=s)return t.copy(o),i.copy(l),t.sub(i),t.dot(t);if(d<=s)a=0,r=f/h,r=Ze(r,0,1);else{const p=Fr.dot(Yf);if(h<=s)r=0,a=Ze(-p/d,0,1);else{const g=Fr.dot(Nr),_=d*h-g*g;_!==0?a=Ze((g*f-p*h)/_,0,1):a=0,r=(g*a+f)/h,r<0?(r=0,a=Ze(-p/d,0,1)):r>1&&(r=1,a=Ze((g-p)/d,0,1))}}return t.copy(o).add(Fr.multiplyScalar(a)),i.copy(l).add(Nr.multiplyScalar(r)),t.sub(i),t.dot(t)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}const h0=new S;class JR extends Qe{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const i=new Ge,s=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let r=0,o=1,l=32;r1)for(let d=0;d.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{g0.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(g0,t)}}setLength(e,t=e*.2,i=t*.2){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(i,t,i),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class uP extends Ln{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],i=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],s=new Ge;s.setAttribute("position",new Ee(t,3)),s.setAttribute("color",new Ee(i,3));const a=new Rt({vertexColors:!0,toneMapped:!1});super(s,a),this.type="AxesHelper"}setColors(e,t,i){const s=new ue,a=this.geometry.attributes.color.array;return s.set(e),s.toArray(a,0),s.toArray(a,3),s.set(t),s.toArray(a,6),s.toArray(a,9),s.set(i),s.toArray(a,12),s.toArray(a,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class dP{constructor(){this.type="ShapePath",this.color=new ue,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new Zd,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,i,s){return this.currentPath.quadraticCurveTo(e,t,i,s),this}bezierCurveTo(e,t,i,s,a,r){return this.currentPath.bezierCurveTo(e,t,i,s,a,r),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(m){const v=[];for(let y=0,b=m.length;yNumber.EPSILON){if(E<0&&(M=v[x],w=-w,C=v[T],E=-E),m.yC.y)continue;if(m.y===M.y){if(m.x===M.x)return!0}else{const R=E*(m.x-M.x)-w*(m.y-M.y);if(R===0)return!0;if(R<0)continue;b=!b}}else{if(m.y!==M.y)continue;if(C.x<=m.x&&m.x<=M.x||M.x<=m.x&&m.x<=C.x)return!0}}return b}const s=Mi.isClockWise,a=this.subPaths;if(a.length===0)return[];let r,o,l;const c=[];if(a.length===1)return o=a[0],l=new Ns,l.curves=o.curves,c.push(l),c;let u=!s(a[0].getPoints());u=e?!u:u;const d=[],h=[];let f=[],p=0,g;h[p]=void 0,f[p]=[];for(let m=0,v=a.length;m1){let m=!1,v=0;for(let y=0,b=h.length;y0&&m===!1&&(f=d)}let _;for(let m=0,v=h.length;me?(n.repeat.x=1,n.repeat.y=t/e,n.offset.x=0,n.offset.y=(1-n.repeat.y)/2):(n.repeat.x=e/t,n.repeat.y=1,n.offset.x=(1-n.repeat.x)/2,n.offset.y=0),n}function fP(n,e){const t=n.image&&n.image.width?n.image.width/n.image.height:1;return t>e?(n.repeat.x=e/t,n.repeat.y=1,n.offset.x=(1-n.repeat.x)/2,n.offset.y=0):(n.repeat.x=1,n.repeat.y=t/e,n.offset.x=0,n.offset.y=(1-n.repeat.y)/2),n}function pP(n){return n.repeat.x=1,n.repeat.y=1,n.offset.x=0,n.offset.y=0,n}function Rm(n,e,t,i){const s=mP(i);switch(t){case W_:return n*e;case bh:return n*e/s.components*s.byteLength;case ic:return n*e/s.components*s.byteLength;case K_:return n*e*2/s.components*s.byteLength;case xh:return n*e*2/s.components*s.byteLength;case X_:return n*e*3/s.components*s.byteLength;case Vn:return n*e*4/s.components*s.byteLength;case wh:return n*e*4/s.components*s.byteLength;case Tl:case Ml:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case El:case Cl:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case vd:case xd:return Math.max(n,16)*Math.max(e,8)/4;case yd:case bd:return Math.max(n,8)*Math.max(e,8)/2;case wd:case Sd:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case Td:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case Md:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case Ed:return Math.floor((n+4)/5)*Math.floor((e+3)/4)*16;case Cd:return Math.floor((n+4)/5)*Math.floor((e+4)/5)*16;case Ad:return Math.floor((n+5)/6)*Math.floor((e+4)/5)*16;case Rd:return Math.floor((n+5)/6)*Math.floor((e+5)/6)*16;case Pd:return Math.floor((n+7)/8)*Math.floor((e+4)/5)*16;case Id:return Math.floor((n+7)/8)*Math.floor((e+5)/6)*16;case Ld:return Math.floor((n+7)/8)*Math.floor((e+7)/8)*16;case Dd:return Math.floor((n+9)/10)*Math.floor((e+4)/5)*16;case kd:return Math.floor((n+9)/10)*Math.floor((e+5)/6)*16;case Od:return Math.floor((n+9)/10)*Math.floor((e+7)/8)*16;case Fd:return Math.floor((n+9)/10)*Math.floor((e+9)/10)*16;case Nd:return Math.floor((n+11)/12)*Math.floor((e+9)/10)*16;case Ud:return Math.floor((n+11)/12)*Math.floor((e+11)/12)*16;case Bd:case zd:case Hd:return Math.ceil(n/4)*Math.ceil(e/4)*16;case Vd:case Gd:return Math.ceil(n/4)*Math.ceil(e/4)*8;case $d:case Wd:return Math.ceil(n/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function mP(n){switch(n){case Yi:case H_:return{byteLength:1,components:1};case yo:case V_:case ls:return{byteLength:2,components:1};case yh:case vh:return{byteLength:2,components:4};case zs:case gh:case Sn:return{byteLength:4,components:1};case G_:case $_:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${n}.`)}class _P{static contain(e,t){return hP(e,t)}static cover(e,t){return fP(e,t)}static fill(e){return pP(e)}static getByteLength(e,t,i,s){return Rm(e,t,i,s)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:ph}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=ph);function nT(){let n=null,e=!1,t=null,i=null;function s(a,r){t(a,r),i=n.requestAnimationFrame(s)}return{start:function(){e!==!0&&t!==null&&(i=n.requestAnimationFrame(s),e=!0)},stop:function(){n.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(a){t=a},setContext:function(a){n=a}}}function gP(n){const e=new WeakMap;function t(o,l){const c=o.array,u=o.usage,d=c.byteLength,h=n.createBuffer();n.bindBuffer(l,h),n.bufferData(l,c,u),o.onUploadCallback();let f;if(c instanceof Float32Array)f=n.FLOAT;else if(typeof Float16Array<"u"&&c instanceof Float16Array)f=n.HALF_FLOAT;else if(c instanceof Uint16Array)o.isFloat16BufferAttribute?f=n.HALF_FLOAT:f=n.UNSIGNED_SHORT;else if(c instanceof Int16Array)f=n.SHORT;else if(c instanceof Uint32Array)f=n.UNSIGNED_INT;else if(c instanceof Int32Array)f=n.INT;else if(c instanceof Int8Array)f=n.BYTE;else if(c instanceof Uint8Array)f=n.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)f=n.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:h,type:f,bytesPerElement:c.BYTES_PER_ELEMENT,version:o.version,size:d}}function i(o,l,c){const u=l.array,d=l.updateRanges;if(n.bindBuffer(c,o),d.length===0)n.bufferSubData(c,0,u);else{d.sort((f,p)=>f.start-p.start);let h=0;for(let f=1;ff+p?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&h<=f-p&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(a=t.getPose(e.gripSpace,i),a!==null&&(l.matrix.fromArray(a.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,a.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(a.linearVelocity)):l.hasLinearVelocity=!1,a.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(a.angularVelocity)):l.hasAngularVelocity=!1));o!==null&&(s=t.getPose(e.targetRaySpace,i),s===null&&a!==null&&(s=a),s!==null&&(o.matrix.fromArray(s.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,s.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(s.linearVelocity)):o.hasLinearVelocity=!1,s.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(s.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(EA)))}return o!==null&&(o.visible=s!==null),l!==null&&(l.visible=a!==null),c!==null&&(c.visible=r!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const i=new Mt;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}class Oh{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new ue(e),this.density=t}clone(){return new Oh(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class Fh{constructor(e,t=1,i=1e3){this.isFog=!0,this.name="",this.color=new ue(e),this.near=t,this.far=i}clone(){return new Fh(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class cc extends Qe{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new an,this.environmentIntensity=1,this.environmentRotation=new an,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class uc{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=$l,this.updateRanges=[],this.version=0,this.uuid=pi()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,i){e*=this.stride,i*=t.stride;for(let s=0,a=this.stride;se.far||t.push({distance:l,point:Ko.clone(),uv:Qn.getInterpolation(Ko,Nc,Yo,Uc,Fy,zf,Ny,new te),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}}function Bc(n,e,t,i,s,a){Dr.subVectors(n,t).addScalar(.5).multiply(i),s!==void 0?(qo.x=a*Dr.x-s*Dr.y,qo.y=s*Dr.x+a*Dr.y):qo.copy(Dr),n.copy(e),n.x+=qo.x,n.y+=qo.y,n.applyMatrix4(MS)}const zc=new S,Uy=new S;class ES extends Qe{constructor(){super(),this.isLOD=!0,this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);const t=e.levels;for(let i=0,s=t.length;i0){let i,s;for(i=1,s=t.length;i0){zc.setFromMatrixPosition(this.matrixWorld);const s=e.ray.origin.distanceTo(zc);this.getObjectForDistance(s).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){zc.setFromMatrixPosition(e.matrixWorld),Uy.setFromMatrixPosition(this.matrixWorld);const i=zc.distanceTo(Uy)/e.zoom;t[0].object.visible=!0;let s,a;for(s=1,a=t.length;s=r)t[s-1].object.visible=!1,t[s].object.visible=!0;else break}for(this._currentLevel=s-1;s1?null:t.copy(e.start).addScaledVector(i,a)}intersectsLine(e){const t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const i=t||IA.getNormalMatrix(e),s=this.coplanarPoint(Gf).applyMatrix4(e),a=this.normal.applyMatrix3(i).normalize();return this.constant=-s.dot(a),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const xa=new bn,LA=new te(.5,.5),Gc=new S;class ko{constructor(e=new Ps,t=new Ps,i=new Ps,s=new Ps,a=new Ps,r=new Ps){this.planes=[e,t,i,s,a,r]}set(e,t,i,s,a,r){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(i),o[3].copy(s),o[4].copy(a),o[5].copy(r),this}copy(e){const t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=hi,i=!1){const s=this.planes,a=e.elements,r=a[0],o=a[1],l=a[2],c=a[3],u=a[4],d=a[5],h=a[6],f=a[7],p=a[8],g=a[9],_=a[10],m=a[11],v=a[12],y=a[13],b=a[14],T=a[15];if(s[0].setComponents(c-r,f-u,m-p,T-v).normalize(),s[1].setComponents(c+r,f+u,m+p,T+v).normalize(),s[2].setComponents(c+o,f+d,m+g,T+y).normalize(),s[3].setComponents(c-o,f-d,m-g,T-y).normalize(),i)s[4].setComponents(l,h,_,b).normalize(),s[5].setComponents(c-l,f-h,m-_,T-b).normalize();else if(s[4].setComponents(c-l,f-h,m-_,T-b).normalize(),t===hi)s[5].setComponents(c+l,f+h,m+_,T+b).normalize();else if(t===Eo)s[5].setComponents(l,h,_,b).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),xa.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),xa.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(xa)}intersectsSprite(e){xa.center.set(0,0,0);const t=LA.distanceTo(e.center);return xa.radius=.7071067811865476+t,xa.applyMatrix4(e.matrixWorld),this.intersectsSphere(xa)}intersectsSphere(e){const t=this.planes,i=e.center,s=-e.radius;for(let a=0;a<6;a++)if(t[a].distanceToPoint(i)0?e.max.x:e.min.x,Gc.y=s.normal.y>0?e.max.y:e.min.y,Gc.z=s.normal.z>0?e.max.z:e.min.z,s.distanceToPoint(Gc)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}const Qi=new Me,es=new ko;class Hh{constructor(){this.coordinateSystem=hi}intersectsObject(e,t){if(!t.isArrayCamera||t.cameras.length===0)return!1;for(let i=0;i=a.length&&a.push({start:-1,count:-1,z:-1,index:-1});const o=a[this.index];r.push(o),this.index++,o.start=e,o.count=t,o.z=i,o.index=s}reset(){this.list.length=0,this.index=0}}const Wn=new Me,FA=new ue(1,1,1),Ky=new ko,NA=new Hh,$c=new vn,wa=new bn,Jo=new S,qy=new S,UA=new S,Wf=new OA,Cn=new we,Wc=[];function BA(n,e,t=0){const i=e.itemSize;if(n.isInterleavedBufferAttribute||n.array.constructor!==e.array.constructor){const s=n.count;for(let a=0;a65535?new Uint32Array(s):new Uint16Array(s);t.setIndex(new ot(a,1))}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;if(!!e.getIndex()!=!!t.getIndex())throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');for(const i in t.attributes){if(!e.hasAttribute(i))throw new Error(`THREE.BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`);const s=e.getAttribute(i),a=t.getAttribute(i);if(s.itemSize!==a.itemSize||s.normalized!==a.normalized)throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}validateInstanceId(e){const t=this._instanceInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid instanceId ${e}. Instance is either out of range or has been deleted.`)}validateGeometryId(e){const t=this._geometryInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`)}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new vn);const e=this.boundingBox,t=this._instanceInfo;e.makeEmpty();for(let i=0,s=t.length;i=this.maxInstanceCount&&this._availableInstanceIds.length===0)throw new Error("THREE.BatchedMesh: Maximum item count reached.");const i={visible:!0,active:!0,geometryIndex:e};let s=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort($f),s=this._availableInstanceIds.shift(),this._instanceInfo[s]=i):(s=this._instanceInfo.length,this._instanceInfo.push(i));const a=this._matricesTexture;Wn.identity().toArray(a.image.data,s*16),a.needsUpdate=!0;const r=this._colorsTexture;return r&&(FA.toArray(r.image.data,s*4),r.needsUpdate=!0),this._visibilityChanged=!0,s}addGeometry(e,t=-1,i=-1){this._initializeGeometry(e),this._validateGeometry(e);const s={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},a=this._geometryInfo;s.vertexStart=this._nextVertexStart,s.reservedVertexCount=t===-1?e.getAttribute("position").count:t;const r=e.getIndex();if(r!==null&&(s.indexStart=this._nextIndexStart,s.reservedIndexCount=i===-1?r.count:i),s.indexStart!==-1&&s.indexStart+s.reservedIndexCount>this._maxIndexCount||s.vertexStart+s.reservedVertexCount>this._maxVertexCount)throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");let l;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort($f),l=this._availableGeometryIds.shift(),a[l]=s):(l=this._geometryCount,this._geometryCount++,a.push(s)),this.setGeometryAt(l,e),this._nextIndexStart=s.indexStart+s.reservedIndexCount,this._nextVertexStart=s.vertexStart+s.reservedVertexCount,l}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,s=i.getIndex()!==null,a=i.getIndex(),r=t.getIndex(),o=this._geometryInfo[e];if(s&&r.count>o.reservedIndexCount||t.attributes.position.count>o.reservedVertexCount)throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");const l=o.vertexStart,c=o.reservedVertexCount;o.vertexCount=t.getAttribute("position").count;for(const u in i.attributes){const d=t.getAttribute(u),h=i.getAttribute(u);BA(d,h,l);const f=d.itemSize;for(let p=d.count,g=c;p=t.length||t[e].active===!1)return this;const i=this._instanceInfo;for(let s=0,a=i.length;so).sort((r,o)=>i[r].vertexStart-i[o].vertexStart),a=this.geometry;for(let r=0,o=i.length;r=this._geometryCount)return null;const i=this.geometry,s=this._geometryInfo[e];if(s.boundingBox===null){const a=new vn,r=i.index,o=i.attributes.position;for(let l=s.start,c=s.start+s.count;l=this._geometryCount)return null;const i=this.geometry,s=this._geometryInfo[e];if(s.boundingSphere===null){const a=new bn;this.getBoundingBoxAt(e,$c),$c.getCenter(a.center);const r=i.index,o=i.attributes.position;let l=0;for(let c=s.start,u=s.start+s.count;co.active);if(Math.max(...i.map(o=>o.vertexStart+o.reservedVertexCount))>e)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${t}. Cannot shrink further.`);if(this.geometry.index&&Math.max(...i.map(l=>l.indexStart+l.reservedIndexCount))>t)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${t}. Cannot shrink further.`);const a=this.geometry;a.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new Ge,this._initializeGeometry(a));const r=this.geometry;a.index&&Sa(a.index.array,r.index.array);for(const o in a.attributes)Sa(a.attributes[o].array,r.attributes[o].array)}raycast(e,t){const i=this._instanceInfo,s=this._geometryInfo,a=this.matrixWorld,r=this.geometry;Cn.material=this.material,Cn.geometry.index=r.index,Cn.geometry.attributes=r.attributes,Cn.geometry.boundingBox===null&&(Cn.geometry.boundingBox=new vn),Cn.geometry.boundingSphere===null&&(Cn.geometry.boundingSphere=new bn);for(let o=0,l=i.length;o({...t,boundingBox:t.boundingBox!==null?t.boundingBox.clone():null,boundingSphere:t.boundingSphere!==null?t.boundingSphere.clone():null})),this._instanceInfo=e._instanceInfo.map(t=>({...t})),this._availableInstanceIds=e._availableInstanceIds.slice(),this._availableGeometryIds=e._availableGeometryIds.slice(),this._nextIndexStart=e._nextIndexStart,this._nextVertexStart=e._nextVertexStart,this._geometryCount=e._geometryCount,this._maxInstanceCount=e._maxInstanceCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._indirectTexture=e._indirectTexture.clone(),this._indirectTexture.image.data=this._indirectTexture.image.data.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),this._colorsTexture!==null&&(this._colorsTexture=e._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,this._colorsTexture!==null&&(this._colorsTexture.dispose(),this._colorsTexture=null)}onBeforeRender(e,t,i,s,a){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const r=s.getIndex(),o=r===null?1:r.array.BYTES_PER_ELEMENT,l=this._instanceInfo,c=this._multiDrawStarts,u=this._multiDrawCounts,d=this._geometryInfo,h=this.perObjectFrustumCulled,f=this._indirectTexture,p=f.image.data,g=i.isArrayCamera?NA:Ky;h&&!i.isArrayCamera&&(Wn.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse).multiply(this.matrixWorld),Ky.setFromProjectionMatrix(Wn,i.coordinateSystem,i.reversedDepth));let _=0;if(this.sortObjects){Wn.copy(this.matrixWorld).invert(),Jo.setFromMatrixPosition(i.matrixWorld).applyMatrix4(Wn),qy.set(0,0,-1).transformDirection(i.matrixWorld).transformDirection(Wn);for(let y=0,b=l.length;y0){const s=t[i[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,r=s.length;ai)return;Xf.applyMatrix4(n.matrixWorld);const c=e.ray.origin.distanceTo(Xf);if(!(ce.far))return{distance:c,point:jy.clone().applyMatrix4(n.matrixWorld),index:r,face:null,faceIndex:null,barycoord:null,object:n}}const Zy=new S,Jy=new S;class Ln extends In{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,i=[];for(let s=0,a=t.count;s0){const s=t[i[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,r=s.length;as.far)return;a.push({distance:c,distanceToRay:Math.sqrt(o),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:r})}}class AS extends Bt{constructor(e,t,i,s,a=Vt,r=Vt,o,l,c){super(e,t,i,s,a,r,o,l,c),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;const u=this;function d(){u.needsUpdate=!0,u._requestVideoFrameCallbackId=e.requestVideoFrameCallback(d)}"requestVideoFrameCallback"in e&&(this._requestVideoFrameCallbackId=e.requestVideoFrameCallback(d))}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;"requestVideoFrameCallback"in e===!1&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),super.dispose()}}class zA extends AS{constructor(e,t,i,s,a,r,o,l){super({},e,t,i,s,a,r,o,l),this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(e){this.image=e,this.needsUpdate=!0}}class HA extends Bt{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=dn,this.minFilter=dn,this.generateMipmaps=!1,this.needsUpdate=!0}}class Vh extends Bt{constructor(e,t,i,s,a,r,o,l,c,u,d,h){super(null,r,o,l,c,u,s,a,d,h),this.isCompressedTexture=!0,this.image={width:t,height:i},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class VA extends Vh{constructor(e,t,i,s,a,r){super(e,t,i,a,r),this.isCompressedArrayTexture=!0,this.image.depth=s,this.wrapR=Hn,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class GA extends Vh{constructor(e,t,i){super(void 0,e[0].width,e[0].height,t,i,Bs),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class dc extends Bt{constructor(e,t,i,s,a,r,o,l,c){super(e,t,i,s,a,r,o,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}}class lg extends Bt{constructor(e,t,i=zs,s,a,r,o=dn,l=dn,c,u=So,d=1){if(u!==So&&u!==To)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const h={width:e,height:t,depth:d};super(h,s,a,r,o,l,u,i,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new sa(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class cg extends Bt{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class Gh extends Ge{constructor(e=1,t=1,i=4,s=8,a=1){super(),this.type="CapsuleGeometry",this.parameters={radius:e,height:t,capSegments:i,radialSegments:s,heightSegments:a},t=Math.max(0,t),i=Math.max(1,Math.floor(i)),s=Math.max(3,Math.floor(s)),a=Math.max(1,Math.floor(a));const r=[],o=[],l=[],c=[],u=t/2,d=Math.PI/2*e,h=t,f=2*d+h,p=i*2+a,g=s+1,_=new S,m=new S;for(let v=0;v<=p;v++){let y=0,b=0,T=0,x=0;if(v<=i){const w=v/i,E=w*Math.PI/2;b=-u-e*Math.cos(E),T=e*Math.sin(E),x=-e*Math.cos(E),y=w*d}else if(v<=i+a){const w=(v-i)/a;b=-u+w*t,T=e,x=0,y=d+w*h}else{const w=(v-i-a)/i,E=w*Math.PI/2;b=u+e*Math.sin(E),T=e*Math.cos(E),x=e*Math.sin(E),y=d+h+w*d}const M=Math.max(0,Math.min(1,y/f));let C=0;v===0?C=.5/s:v===p&&(C=-.5/s);for(let w=0;w<=s;w++){const E=w/s,R=E*Math.PI*2,k=Math.sin(R),O=Math.cos(R);m.x=-T*O,m.y=b,m.z=T*k,o.push(m.x,m.y,m.z),_.set(-T*O,x,T*k),_.normalize(),l.push(_.x,_.y,_.z),c.push(E+C,M)}if(v>0){const w=(v-1)*g;for(let E=0;E0&&y(!0),t>0&&y(!1)),this.setIndex(u),this.setAttribute("position",new Ee(d,3)),this.setAttribute("normal",new Ee(h,3)),this.setAttribute("uv",new Ee(f,2));function v(){const b=new S,T=new S;let x=0;const M=(t-e)/i;for(let C=0;C<=a;C++){const w=[],E=C/a,R=E*(t-e)+e;for(let k=0;k<=s;k++){const O=k/s,D=O*l+o,U=Math.sin(D),F=Math.cos(D);T.x=R*U,T.y=-E*i+_,T.z=R*F,d.push(T.x,T.y,T.z),b.set(U,M,F).normalize(),h.push(b.x,b.y,b.z),f.push(O,1-E),w.push(p++)}g.push(w)}for(let C=0;C0||w!==0)&&(u.push(E,R,O),x+=3),(t>0||w!==a-1)&&(u.push(R,k,O),x+=3)}c.addGroup(m,x,0),m+=x}function y(b){const T=p,x=new te,M=new S;let C=0;const w=b===!0?e:t,E=b===!0?1:-1;for(let k=1;k<=s;k++)d.push(0,_*E,0),h.push(0,E,0),f.push(.5,.5),p++;const R=p;for(let k=0;k<=s;k++){const D=k/s*l+o,U=Math.cos(D),F=Math.sin(D);M.x=w*F,M.y=_*E,M.z=w*U,d.push(M.x,M.y,M.z),h.push(0,E,0),x.x=U*.5+.5,x.y=F*.5*E+.5,f.push(x.x,x.y),p++}for(let k=0;k.9&&M<.1&&(y<.2&&(r[v+0]+=1),b<.2&&(r[v+2]+=1),T<.2&&(r[v+4]+=1))}}function h(v){a.push(v.x,v.y,v.z)}function f(v,y){const b=v*3;y.x=e[b+0],y.y=e[b+1],y.z=e[b+2]}function p(){const v=new S,y=new S,b=new S,T=new S,x=new te,M=new te,C=new te;for(let w=0,E=0;w0)l=s-1;else{l=s;break}if(s=l,i[s]===r)return s/(a-1);const u=i[s],h=i[s+1]-u,f=(r-u)/h;return(s+f)/(a-1)}getTangent(e,t){let s=e-1e-4,a=e+1e-4;s<0&&(s=0),a>1&&(a=1);const r=this.getPoint(s),o=this.getPoint(a),l=t||(r.isVector2?new te:new S);return l.copy(o).sub(r).normalize(),l}getTangentAt(e,t){const i=this.getUtoTmapping(e);return this.getTangent(i,t)}computeFrenetFrames(e,t=!1){const i=new S,s=[],a=[],r=[],o=new S,l=new Me;for(let f=0;f<=e;f++){const p=f/e;s[f]=this.getTangentAt(p,new S)}a[0]=new S,r[0]=new S;let c=Number.MAX_VALUE;const u=Math.abs(s[0].x),d=Math.abs(s[0].y),h=Math.abs(s[0].z);u<=c&&(c=u,i.set(1,0,0)),d<=c&&(c=d,i.set(0,1,0)),h<=c&&i.set(0,0,1),o.crossVectors(s[0],i).normalize(),a[0].crossVectors(s[0],o),r[0].crossVectors(s[0],a[0]);for(let f=1;f<=e;f++){if(a[f]=a[f-1].clone(),r[f]=r[f-1].clone(),o.crossVectors(s[f-1],s[f]),o.length()>Number.EPSILON){o.normalize();const p=Math.acos(Ze(s[f-1].dot(s[f]),-1,1));a[f].applyMatrix4(l.makeRotationAxis(o,p))}r[f].crossVectors(s[f],a[f])}if(t===!0){let f=Math.acos(Ze(a[0].dot(a[e]),-1,1));f/=e,s[0].dot(o.crossVectors(a[0],a[e]))>0&&(f=-f);for(let p=1;p<=e;p++)a[p].applyMatrix4(l.makeRotationAxis(s[p],f*p)),r[p].crossVectors(s[p],a[p])}return{tangents:s,normals:a,binormals:r}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class Xh extends Pi{constructor(e=0,t=0,i=1,s=1,a=0,r=Math.PI*2,o=!1,l=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=i,this.yRadius=s,this.aStartAngle=a,this.aEndAngle=r,this.aClockwise=o,this.aRotation=l}getPoint(e,t=new te){const i=t,s=Math.PI*2;let a=this.aEndAngle-this.aStartAngle;const r=Math.abs(a)s;)a-=s;a0?0:(Math.floor(Math.abs(o)/a)+1)*a:l===0&&o===a-1&&(o=a-2,l=1);let c,u;this.closed||o>0?c=s[(o-1)%a]:(Qc.subVectors(s[0],s[1]).add(s[0]),c=Qc);const d=s[o%a],h=s[(o+1)%a];if(this.closed||o+2s.length-2?s.length-1:r+1],d=s[r>s.length-3?s.length-1:r+2];return i.set(t0(o,l.x,c.x,u.x,d.x),t0(o,l.y,c.y,u.y,d.y)),i}copy(e){super.copy(e),this.points=[];for(let t=0,i=e.points.length;t=i){const r=s[a]-i,o=this.curves[a],l=o.getLength(),c=l===0?0:1-r/l;return o.getPointAt(c,t)}a++}return null}getLength(){const e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const e=[];let t=0;for(let i=0,s=this.curves.length;i1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,i=e.curves.length;t0){const d=c.getPoint(0);d.equals(this.currentPoint)||this.lineTo(d.x,d.y)}this.curves.push(c);const u=c.getPoint(1);return this.currentPoint.copy(u),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class Ns extends ih{constructor(e){super(e),this.uuid=pi(),this.type="Shape",this.holes=[]}getPointsHoles(e){const t=[];for(let i=0,s=this.holes.length;i80*t){o=1/0,l=1/0;let u=-1/0,d=-1/0;for(let h=t;hu&&(u=f),p>d&&(d=p)}c=Math.max(u-o,d-l),c=c!==0?32767/c:0}return Kl(a,r,t,o,l,c,0),r}function kS(n,e,t,i,s){let a;if(s===fR(n,e,t,i)>0)for(let r=e;r=e;r-=i)a=n0(r/i|0,n[r],n[r+1],a);return a&&Po(a,a.next)&&(Yl(a),a=a.next),a}function ur(n,e){if(!n)return n;e||(e=n);let t=n,i;do if(i=!1,!t.steiner&&(Po(t,t.next)||Kt(t.prev,t,t.next)===0)){if(Yl(t),t=e=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==e);return e}function Kl(n,e,t,i,s,a,r){if(!n)return;!r&&a&&oR(n,i,s,a);let o=n;for(;n.prev!==n.next;){const l=n.prev,c=n.next;if(a?QA(n,i,s,a):JA(n)){e.push(l.i,n.i,c.i),Yl(n),n=c.next,o=c.next;continue}if(n=c,n===o){r?r===1?(n=eR(ur(n),e),Kl(n,e,t,i,s,a,2)):r===2&&tR(n,e,t,i,s,a):Kl(ur(n),e,t,i,s,a,1);break}}}function JA(n){const e=n.prev,t=n,i=n.next;if(Kt(e,t,i)>=0)return!1;const s=e.x,a=t.x,r=i.x,o=e.y,l=t.y,c=i.y,u=Math.min(s,a,r),d=Math.min(o,l,c),h=Math.max(s,a,r),f=Math.max(o,l,c);let p=i.next;for(;p!==e;){if(p.x>=u&&p.x<=h&&p.y>=d&&p.y<=f&&ml(s,o,a,l,r,c,p.x,p.y)&&Kt(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function QA(n,e,t,i){const s=n.prev,a=n,r=n.next;if(Kt(s,a,r)>=0)return!1;const o=s.x,l=a.x,c=r.x,u=s.y,d=a.y,h=r.y,f=Math.min(o,l,c),p=Math.min(u,d,h),g=Math.max(o,l,c),_=Math.max(u,d,h),m=Im(f,p,e,t,i),v=Im(g,_,e,t,i);let y=n.prevZ,b=n.nextZ;for(;y&&y.z>=m&&b&&b.z<=v;){if(y.x>=f&&y.x<=g&&y.y>=p&&y.y<=_&&y!==s&&y!==r&&ml(o,u,l,d,c,h,y.x,y.y)&&Kt(y.prev,y,y.next)>=0||(y=y.prevZ,b.x>=f&&b.x<=g&&b.y>=p&&b.y<=_&&b!==s&&b!==r&&ml(o,u,l,d,c,h,b.x,b.y)&&Kt(b.prev,b,b.next)>=0))return!1;b=b.nextZ}for(;y&&y.z>=m;){if(y.x>=f&&y.x<=g&&y.y>=p&&y.y<=_&&y!==s&&y!==r&&ml(o,u,l,d,c,h,y.x,y.y)&&Kt(y.prev,y,y.next)>=0)return!1;y=y.prevZ}for(;b&&b.z<=v;){if(b.x>=f&&b.x<=g&&b.y>=p&&b.y<=_&&b!==s&&b!==r&&ml(o,u,l,d,c,h,b.x,b.y)&&Kt(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function eR(n,e){let t=n;do{const i=t.prev,s=t.next.next;!Po(i,s)&&OS(i,t,t.next,s)&&ql(i,s)&&ql(s,i)&&(e.push(i.i,t.i,s.i),Yl(t),Yl(t.next),t=n=s),t=t.next}while(t!==n);return ur(t)}function tR(n,e,t,i,s,a){let r=n;do{let o=r.next.next;for(;o!==r.prev;){if(r.i!==o.i&&uR(r,o)){let l=FS(r,o);r=ur(r,r.next),l=ur(l,l.next),Kl(r,e,t,i,s,a,0),Kl(l,e,t,i,s,a,0);return}o=o.next}r=r.next}while(r!==n)}function nR(n,e,t,i){const s=[];for(let a=0,r=e.length;a=t.next.y&&t.next.y!==t.y){const d=t.x+(s-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(d<=i&&d>a&&(a=d,r=t.x=t.x&&t.x>=l&&i!==t.x&&DS(sr.x||t.x===r.x&&rR(r,t)))&&(r=t,u=d)}t=t.next}while(t!==o);return r}function rR(n,e){return Kt(n.prev,n,e.prev)<0&&Kt(e.next,n,n.next)<0}function oR(n,e,t,i){let s=n;do s.z===0&&(s.z=Im(s.x,s.y,e,t,i)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next;while(s!==n);s.prevZ.nextZ=null,s.prevZ=null,lR(s)}function lR(n){let e,t=1;do{let i=n,s;n=null;let a=null;for(e=0;i;){e++;let r=i,o=0;for(let c=0;c0||l>0&&r;)o!==0&&(l===0||!r||i.z<=r.z)?(s=i,i=i.nextZ,o--):(s=r,r=r.nextZ,l--),a?a.nextZ=s:n=s,s.prevZ=a,a=s;i=r}a.nextZ=null,t*=2}while(e>1);return n}function Im(n,e,t,i,s){return n=(n-t)*s|0,e=(e-i)*s|0,n=(n|n<<8)&16711935,n=(n|n<<4)&252645135,n=(n|n<<2)&858993459,n=(n|n<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,n|e<<1}function cR(n){let e=n,t=n;do(e.x=(n-r)*(a-o)&&(n-r)*(i-o)>=(t-r)*(e-o)&&(t-r)*(a-o)>=(s-r)*(i-o)}function ml(n,e,t,i,s,a,r,o){return!(n===r&&e===o)&&DS(n,e,t,i,s,a,r,o)}function uR(n,e){return n.next.i!==e.i&&n.prev.i!==e.i&&!dR(n,e)&&(ql(n,e)&&ql(e,n)&&hR(n,e)&&(Kt(n.prev,n,e.prev)||Kt(n,e.prev,e))||Po(n,e)&&Kt(n.prev,n,n.next)>0&&Kt(e.prev,e,e.next)>0)}function Kt(n,e,t){return(e.y-n.y)*(t.x-e.x)-(e.x-n.x)*(t.y-e.y)}function Po(n,e){return n.x===e.x&&n.y===e.y}function OS(n,e,t,i){const s=tu(Kt(n,e,t)),a=tu(Kt(n,e,i)),r=tu(Kt(t,i,n)),o=tu(Kt(t,i,e));return!!(s!==a&&r!==o||s===0&&eu(n,t,e)||a===0&&eu(n,i,e)||r===0&&eu(t,n,i)||o===0&&eu(t,e,i))}function eu(n,e,t){return e.x<=Math.max(n.x,t.x)&&e.x>=Math.min(n.x,t.x)&&e.y<=Math.max(n.y,t.y)&&e.y>=Math.min(n.y,t.y)}function tu(n){return n>0?1:n<0?-1:0}function dR(n,e){let t=n;do{if(t.i!==n.i&&t.next.i!==n.i&&t.i!==e.i&&t.next.i!==e.i&&OS(t,t.next,n,e))return!0;t=t.next}while(t!==n);return!1}function ql(n,e){return Kt(n.prev,n,n.next)<0?Kt(n,e,n.next)>=0&&Kt(n,n.prev,e)>=0:Kt(n,e,n.prev)<0||Kt(n,n.next,e)<0}function hR(n,e){let t=n,i=!1;const s=(n.x+e.x)/2,a=(n.y+e.y)/2;do t.y>a!=t.next.y>a&&t.next.y!==t.y&&s<(t.next.x-t.x)*(a-t.y)/(t.next.y-t.y)+t.x&&(i=!i),t=t.next;while(t!==n);return i}function FS(n,e){const t=Lm(n.i,n.x,n.y),i=Lm(e.i,e.x,e.y),s=n.next,a=e.prev;return n.next=e,e.prev=n,t.next=s,s.prev=t,i.next=t,t.prev=i,a.next=i,i.prev=a,i}function n0(n,e,t,i){const s=Lm(n,e,t);return i?(s.next=i.next,s.prev=i,i.next.prev=s,i.next=s):(s.prev=s,s.next=s),s}function Yl(n){n.next.prev=n.prev,n.prev.next=n.next,n.prevZ&&(n.prevZ.nextZ=n.nextZ),n.nextZ&&(n.nextZ.prevZ=n.prevZ)}function Lm(n,e,t){return{i:n,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function fR(n,e,t,i){let s=0;for(let a=e,r=t-i;a2&&n[e-1].equals(n[0])&&n.pop()}function s0(n,e){for(let t=0;tNumber.EPSILON){const J=Math.sqrt(A),le=Math.sqrt(it*it+I*I),ee=j.x-$e/J,He=j.y+ge/J,ye=Y.x-I/le,Ue=Y.y+it/le,Be=((ye-ee)*I-(Ue-He)*it)/(ge*I-$e*it);Q=ee+ge*Be-G.x,_e=He+$e*Be-G.y;const de=Q*Q+_e*_e;if(de<=2)return new te(Q,_e);ce=Math.sqrt(de/2)}else{let J=!1;ge>Number.EPSILON?it>Number.EPSILON&&(J=!0):ge<-Number.EPSILON?it<-Number.EPSILON&&(J=!0):Math.sign($e)===Math.sign(I)&&(J=!0),J?(Q=-$e,_e=ge,ce=Math.sqrt(A)):(Q=ge,_e=$e,ce=Math.sqrt(A/2))}return new te(Q/ce,_e/ce)}const ne=[];for(let G=0,j=U.length,Y=j-1,Q=G+1;G=0;G--){const j=G/_,Y=f*Math.cos(j*Math.PI/2),Q=p*Math.sin(j*Math.PI/2)+g;for(let _e=0,ce=U.length;_e=0;){const Q=Y;let _e=Y-1;_e<0&&(_e=G.length-1);for(let ce=0,ge=u+_*2;ce0)&&f.push(y,b,x),(m!==i-1||l0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class ja extends Qt{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new ue(16777215),this.specular=new ue(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ue(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=fa,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new an,this.combine=rc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class BS extends Qt{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new ue(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ue(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=fa,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class zS extends Qt{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=fa,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class ef extends Qt{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new ue(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ue(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=fa,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new an,this.combine=rc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class yg extends Qt{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=oS,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class vg extends Qt{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class HS extends Qt{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new ue(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=fa,this.normalScale=new te(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}class VS extends Rt{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}function Za(n,e){return!n||n.constructor===e?n:typeof e.BYTES_PER_ELEMENT=="number"?new e(n):Array.prototype.slice.call(n)}function GS(n){return ArrayBuffer.isView(n)&&!(n instanceof DataView)}function $S(n){function e(s,a){return n[s]-n[a]}const t=n.length,i=new Array(t);for(let s=0;s!==t;++s)i[s]=s;return i.sort(e),i}function km(n,e,t){const i=n.length,s=new n.constructor(i);for(let a=0,r=0;r!==i;++a){const o=t[a]*e;for(let l=0;l!==e;++l)s[r++]=n[o+l]}return s}function bg(n,e,t,i){let s=1,a=n[0];for(;a!==void 0&&a[i]===void 0;)a=n[s++];if(a===void 0)return;let r=a[i];if(r!==void 0)if(Array.isArray(r))do r=a[i],r!==void 0&&(e.push(a.time),t.push(...r)),a=n[s++];while(a!==void 0);else if(r.toArray!==void 0)do r=a[i],r!==void 0&&(e.push(a.time),r.toArray(t,t.length)),a=n[s++];while(a!==void 0);else do r=a[i],r!==void 0&&(e.push(a.time),t.push(r)),a=n[s++];while(a!==void 0)}function yR(n,e,t,i,s=30){const a=n.clone();a.name=e;const r=[];for(let l=0;l=i)){d.push(c.times[f]);for(let g=0;ga.tracks[l].times[0]&&(o=a.tracks[l].times[0]);for(let l=0;l=o.times[p]){const m=p*d+u,v=m+d-u;g=o.values.slice(m,v)}else{const m=o.createInterpolant(),v=u,y=d-u;m.evaluate(a),g=m.resultBuffer.slice(v,y)}l==="quaternion"&&new dt().fromArray(g).normalize().conjugate().toArray(g);const _=c.times.length;for(let m=0;m<_;++m){const v=m*f+h;if(l==="quaternion")dt.multiplyQuaternionsFlat(c.values,v,g,0,c.values,v);else{const y=f-h*2;for(let b=0;b=a)){const o=t[1];e=a)break t}r=i,i=0;break n}break e}for(;i>>1;et;)--r;if(++r,a!==0||r!==s){a>=r&&(r=Math.max(r,1),a=r-1);const o=this.getValueSize();this.times=i.slice(a,r),this.values=this.values.slice(a*o,r*o)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const i=this.times,s=this.values,a=i.length;a===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let r=null;for(let o=0;o!==a;o++){const l=i[o];if(typeof l=="number"&&isNaN(l)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,o,l),e=!1;break}if(r!==null&&r>l){console.error("THREE.KeyframeTrack: Out of order keys.",this,o,l,r),e=!1;break}r=l}if(s!==void 0&&GS(s))for(let o=0,l=s.length;o!==l;++o){const c=s[o];if(isNaN(c)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,o,c),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),i=this.getValueSize(),s=this.getInterpolation()===Xu,a=e.length-1;let r=1;for(let o=1;o0){e[r]=e[a];for(let o=a*i,l=r*i,c=0;c!==i;++c)t[l+c]=t[o+c];++r}return r!==e.length?(this.times=e.slice(0,r),this.values=t.slice(0,r*i)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),i=this.constructor,s=new i(this.name,e,t);return s.createInterpolant=this.createInterpolant,s}}Ii.prototype.ValueTypeName="";Ii.prototype.TimeBufferType=Float32Array;Ii.prototype.ValueBufferType=Float32Array;Ii.prototype.DefaultInterpolation=or;class mr extends Ii{constructor(e,t,i){super(e,t,i)}}mr.prototype.ValueTypeName="bool";mr.prototype.ValueBufferType=Array;mr.prototype.DefaultInterpolation=Mo;mr.prototype.InterpolantFactoryMethodLinear=void 0;mr.prototype.InterpolantFactoryMethodSmooth=void 0;class wg extends Ii{constructor(e,t,i,s){super(e,t,i,s)}}wg.prototype.ValueTypeName="color";class ua extends Ii{constructor(e,t,i,s){super(e,t,i,s)}}ua.prototype.ValueTypeName="number";class KS extends Oo{constructor(e,t,i,s){super(e,t,i,s)}interpolate_(e,t,i,s){const a=this.resultBuffer,r=this.sampleValues,o=this.valueSize,l=(i-t)/(s-t);let c=e*o;for(let u=c+o;c!==u;c+=4)dt.slerpFlat(a,0,r,c-o,r,c,l);return a}}class _s extends Ii{constructor(e,t,i,s){super(e,t,i,s)}InterpolantFactoryMethodLinear(e){return new KS(this.times,this.values,this.getValueSize(),e)}}_s.prototype.ValueTypeName="quaternion";_s.prototype.InterpolantFactoryMethodSmooth=void 0;class _r extends Ii{constructor(e,t,i){super(e,t,i)}}_r.prototype.ValueTypeName="string";_r.prototype.ValueBufferType=Array;_r.prototype.DefaultInterpolation=Mo;_r.prototype.InterpolantFactoryMethodLinear=void 0;_r.prototype.InterpolantFactoryMethodSmooth=void 0;class Hs extends Ii{constructor(e,t,i,s){super(e,t,i,s)}}Hs.prototype.ValueTypeName="vector";class da{constructor(e="",t=-1,i=[],s=Rh){this.name=e,this.tracks=i,this.duration=t,this.blendMode=s,this.uuid=pi(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){const t=[],i=e.tracks,s=1/(e.fps||1);for(let r=0,o=i.length;r!==o;++r)t.push(wR(i[r]).scale(s));const a=new this(e.name,e.duration,t,e.blendMode);return a.uuid=e.uuid,a.userData=JSON.parse(e.userData||"{}"),a}static toJSON(e){const t=[],i=e.tracks,s={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let a=0,r=i.length;a!==r;++a)t.push(Ii.toJSON(i[a]));return s}static CreateFromMorphTargetSequence(e,t,i,s){const a=t.length,r=[];for(let o=0;o1){const d=u[1];let h=s[d];h||(s[d]=h=[]),h.push(c)}}const r=[];for(const o in s)r.push(this.CreateFromMorphTargetSequence(o,s[o],t,i));return r}static parseAnimation(e,t){if(console.warn("THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const i=function(d,h,f,p,g){if(f.length!==0){const _=[],m=[];bg(f,_,m,p),_.length!==0&&g.push(new d(h,_,m))}},s=[],a=e.name||"default",r=e.fps||30,o=e.blendMode;let l=e.length||-1;const c=e.hierarchy||[];for(let d=0;d{t&&t(a),this.manager.itemEnd(e)},0),a;if(Ts[e]!==void 0){Ts[e].push({onLoad:t,onProgress:i,onError:s});return}Ts[e]=[],Ts[e].push({onLoad:t,onProgress:i,onError:s});const r=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,l=this.responseType;fetch(r).then(c=>{if(c.status===200||c.status===0){if(c.status===0&&console.warn("THREE.FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||c.body===void 0||c.body.getReader===void 0)return c;const u=Ts[e],d=c.body.getReader(),h=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),f=h?parseInt(h):0,p=f!==0;let g=0;const _=new ReadableStream({start(m){v();function v(){d.read().then(({done:y,value:b})=>{if(y)m.close();else{g+=b.byteLength;const T=new ProgressEvent("progress",{lengthComputable:p,loaded:g,total:f});for(let x=0,M=u.length;x{m.error(y)})}}});return new Response(_)}else throw new SR(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`,c)}).then(c=>{switch(l){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then(u=>new DOMParser().parseFromString(u,o));case"json":return c.json();default:if(o==="")return c.text();{const d=/charset="?([^;"\s]*)"?/i.exec(o),h=d&&d[1]?d[1].toLowerCase():void 0,f=new TextDecoder(h);return c.arrayBuffer().then(p=>f.decode(p))}}}).then(c=>{cs.add(`file:${e}`,c);const u=Ts[e];delete Ts[e];for(let d=0,h=u.length;d{const u=Ts[e];if(u===void 0)throw this.manager.itemError(e),c;delete Ts[e];for(let d=0,h=u.length;d{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}class TR extends on{constructor(e){super(e)}load(e,t,i,s){const a=this,r=new Gn(this.manager);r.setPath(this.path),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,function(o){try{t(a.parse(JSON.parse(o)))}catch(l){s?s(l):console.error(l),a.manager.itemError(e)}},i,s)}parse(e){const t=[];for(let i=0;i0:s.vertexColors=e.vertexColors),e.uniforms!==void 0)for(const a in e.uniforms){const r=e.uniforms[a];switch(s.uniforms[a]={},r.type){case"t":s.uniforms[a].value=i(r.value);break;case"c":s.uniforms[a].value=new ue().setHex(r.value);break;case"v2":s.uniforms[a].value=new te().fromArray(r.value);break;case"v3":s.uniforms[a].value=new S().fromArray(r.value);break;case"v4":s.uniforms[a].value=new qe().fromArray(r.value);break;case"m3":s.uniforms[a].value=new at().fromArray(r.value);break;case"m4":s.uniforms[a].value=new Me().fromArray(r.value);break;default:s.uniforms[a].value=r.value}}if(e.defines!==void 0&&(s.defines=e.defines),e.vertexShader!==void 0&&(s.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(s.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(s.glslVersion=e.glslVersion),e.extensions!==void 0)for(const a in e.extensions)s.extensions[a]=e.extensions[a];if(e.lights!==void 0&&(s.lights=e.lights),e.clipping!==void 0&&(s.clipping=e.clipping),e.size!==void 0&&(s.size=e.size),e.sizeAttenuation!==void 0&&(s.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(s.map=i(e.map)),e.matcap!==void 0&&(s.matcap=i(e.matcap)),e.alphaMap!==void 0&&(s.alphaMap=i(e.alphaMap)),e.bumpMap!==void 0&&(s.bumpMap=i(e.bumpMap)),e.bumpScale!==void 0&&(s.bumpScale=e.bumpScale),e.normalMap!==void 0&&(s.normalMap=i(e.normalMap)),e.normalMapType!==void 0&&(s.normalMapType=e.normalMapType),e.normalScale!==void 0){let a=e.normalScale;Array.isArray(a)===!1&&(a=[a,a]),s.normalScale=new te().fromArray(a)}return e.displacementMap!==void 0&&(s.displacementMap=i(e.displacementMap)),e.displacementScale!==void 0&&(s.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(s.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(s.roughnessMap=i(e.roughnessMap)),e.metalnessMap!==void 0&&(s.metalnessMap=i(e.metalnessMap)),e.emissiveMap!==void 0&&(s.emissiveMap=i(e.emissiveMap)),e.emissiveIntensity!==void 0&&(s.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(s.specularMap=i(e.specularMap)),e.specularIntensityMap!==void 0&&(s.specularIntensityMap=i(e.specularIntensityMap)),e.specularColorMap!==void 0&&(s.specularColorMap=i(e.specularColorMap)),e.envMap!==void 0&&(s.envMap=i(e.envMap)),e.envMapRotation!==void 0&&s.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(s.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(s.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(s.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(s.lightMap=i(e.lightMap)),e.lightMapIntensity!==void 0&&(s.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(s.aoMap=i(e.aoMap)),e.aoMapIntensity!==void 0&&(s.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(s.gradientMap=i(e.gradientMap)),e.clearcoatMap!==void 0&&(s.clearcoatMap=i(e.clearcoatMap)),e.clearcoatRoughnessMap!==void 0&&(s.clearcoatRoughnessMap=i(e.clearcoatRoughnessMap)),e.clearcoatNormalMap!==void 0&&(s.clearcoatNormalMap=i(e.clearcoatNormalMap)),e.clearcoatNormalScale!==void 0&&(s.clearcoatNormalScale=new te().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(s.iridescenceMap=i(e.iridescenceMap)),e.iridescenceThicknessMap!==void 0&&(s.iridescenceThicknessMap=i(e.iridescenceThicknessMap)),e.transmissionMap!==void 0&&(s.transmissionMap=i(e.transmissionMap)),e.thicknessMap!==void 0&&(s.thicknessMap=i(e.thicknessMap)),e.anisotropyMap!==void 0&&(s.anisotropyMap=i(e.anisotropyMap)),e.sheenColorMap!==void 0&&(s.sheenColorMap=i(e.sheenColorMap)),e.sheenRoughnessMap!==void 0&&(s.sheenRoughnessMap=i(e.sheenRoughnessMap)),s}setTextures(e){return this.textures=e,this}createMaterialFromType(e){return sf.createMaterialFromType(e)}static createMaterialFromType(e){const t={ShadowMaterial:NS,SpriteMaterial:Nh,RawShaderMaterial:US,ShaderMaterial:ti,PointsMaterial:aa,MeshPhysicalMaterial:ii,MeshStandardMaterial:Pn,MeshPhongMaterial:ja,MeshToonMaterial:BS,MeshNormalMaterial:zS,MeshLambertMaterial:ef,MeshDepthMaterial:yg,MeshDistanceMaterial:vg,MeshBasicMaterial:Ye,MeshMatcapMaterial:HS,LineDashedMaterial:VS,LineBasicMaterial:Rt,Material:Qt};return new t[e]}}class Us{static extractUrlBase(e){const t=e.lastIndexOf("/");return t===-1?"./":e.slice(0,t+1)}static resolveURL(e,t){return typeof e!="string"||e===""?"":(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}}class eT extends Ge{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){const e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}}class tT extends on{constructor(e){super(e)}load(e,t,i,s){const a=this,r=new Gn(a.manager);r.setPath(a.path),r.setRequestHeader(a.requestHeader),r.setWithCredentials(a.withCredentials),r.load(e,function(o){try{t(a.parse(JSON.parse(o)))}catch(l){s?s(l):console.error(l),a.manager.itemError(e)}},i,s)}parse(e){const t={},i={};function s(f,p){if(t[p]!==void 0)return t[p];const _=f.interleavedBuffers[p],m=a(f,_.buffer),v=Zr(_.type,m),y=new uc(v,_.stride);return y.uuid=_.uuid,t[p]=y,y}function a(f,p){if(i[p]!==void 0)return i[p];const _=f.arrayBuffers[p],m=new Uint32Array(_).buffer;return i[p]=m,m}const r=e.isInstancedBufferGeometry?new eT:new Ge,o=e.data.index;if(o!==void 0){const f=Zr(o.type,o.array);r.setIndex(new ot(f,1))}const l=e.data.attributes;for(const f in l){const p=l[f];let g;if(p.isInterleavedBufferAttribute){const _=s(e.data,p.data);g=new ca(_,p.itemSize,p.offset,p.normalized)}else{const _=Zr(p.type,p.array),m=p.isInstancedBufferAttribute?lr:ot;g=new m(_,p.itemSize,p.normalized)}p.name!==void 0&&(g.name=p.name),p.usage!==void 0&&g.setUsage(p.usage),r.setAttribute(f,g)}const c=e.data.morphAttributes;if(c)for(const f in c){const p=c[f],g=[];for(let _=0,m=p.length;_0){const l=new Sg(t);a=new jl(l),a.setCrossOrigin(this.crossOrigin);for(let c=0,u=e.length;c0){s=new jl(this.manager),s.setCrossOrigin(this.crossOrigin);for(let r=0,o=e.length;r{let _=null,m=null;return g.boundingBox!==void 0&&(_=new vn().fromJSON(g.boundingBox)),g.boundingSphere!==void 0&&(m=new bn().fromJSON(g.boundingSphere)),{...g,boundingBox:_,boundingSphere:m}}),r._instanceInfo=e.instanceInfo,r._availableInstanceIds=e._availableInstanceIds,r._availableGeometryIds=e._availableGeometryIds,r._nextIndexStart=e.nextIndexStart,r._nextVertexStart=e.nextVertexStart,r._geometryCount=e.geometryCount,r._maxInstanceCount=e.maxInstanceCount,r._maxVertexCount=e.maxVertexCount,r._maxIndexCount=e.maxIndexCount,r._geometryInitialized=e.geometryInitialized,r._matricesTexture=c(e.matricesTexture.uuid),r._indirectTexture=c(e.indirectTexture.uuid),e.colorsTexture!==void 0&&(r._colorsTexture=c(e.colorsTexture.uuid)),e.boundingSphere!==void 0&&(r.boundingSphere=new bn().fromJSON(e.boundingSphere)),e.boundingBox!==void 0&&(r.boundingBox=new vn().fromJSON(e.boundingBox));break;case"LOD":r=new ES;break;case"Line":r=new In(o(e.geometry),l(e.material));break;case"LineLoop":r=new og(o(e.geometry),l(e.material));break;case"LineSegments":r=new Ln(o(e.geometry),l(e.material));break;case"PointCloud":case"Points":r=new sr(o(e.geometry),l(e.material));break;case"Sprite":r=new Uh(l(e.material));break;case"Group":r=new Mt;break;case"Bone":r=new Ro;break;default:r=new Qe}if(r.uuid=e.uuid,e.name!==void 0&&(r.name=e.name),e.matrix!==void 0?(r.matrix.fromArray(e.matrix),e.matrixAutoUpdate!==void 0&&(r.matrixAutoUpdate=e.matrixAutoUpdate),r.matrixAutoUpdate&&r.matrix.decompose(r.position,r.quaternion,r.scale)):(e.position!==void 0&&r.position.fromArray(e.position),e.rotation!==void 0&&r.rotation.fromArray(e.rotation),e.quaternion!==void 0&&r.quaternion.fromArray(e.quaternion),e.scale!==void 0&&r.scale.fromArray(e.scale)),e.up!==void 0&&r.up.fromArray(e.up),e.castShadow!==void 0&&(r.castShadow=e.castShadow),e.receiveShadow!==void 0&&(r.receiveShadow=e.receiveShadow),e.shadow&&(e.shadow.intensity!==void 0&&(r.shadow.intensity=e.shadow.intensity),e.shadow.bias!==void 0&&(r.shadow.bias=e.shadow.bias),e.shadow.normalBias!==void 0&&(r.shadow.normalBias=e.shadow.normalBias),e.shadow.radius!==void 0&&(r.shadow.radius=e.shadow.radius),e.shadow.mapSize!==void 0&&r.shadow.mapSize.fromArray(e.shadow.mapSize),e.shadow.camera!==void 0&&(r.shadow.camera=this.parseObject(e.shadow.camera))),e.visible!==void 0&&(r.visible=e.visible),e.frustumCulled!==void 0&&(r.frustumCulled=e.frustumCulled),e.renderOrder!==void 0&&(r.renderOrder=e.renderOrder),e.userData!==void 0&&(r.userData=e.userData),e.layers!==void 0&&(r.layers.mask=e.layers),e.children!==void 0){const h=e.children;for(let f=0;f"u"&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,i,s){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const a=this,r=cs.get(`image-bitmap:${e}`);if(r!==void 0){if(a.manager.itemStart(e),r.then){r.then(c=>{if(Qf.has(r)===!0)s&&s(Qf.get(r)),a.manager.itemError(e),a.manager.itemEnd(e);else return t&&t(c),a.manager.itemEnd(e),c});return}return setTimeout(function(){t&&t(r),a.manager.itemEnd(e)},0),r}const o={};o.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",o.headers=this.requestHeader,o.signal=typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;const l=fetch(e,o).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign(a.options,{colorSpaceConversion:"none"}))}).then(function(c){return cs.add(`image-bitmap:${e}`,c),t&&t(c),a.manager.itemEnd(e),c}).catch(function(c){s&&s(c),Qf.set(l,c),cs.remove(`image-bitmap:${e}`),a.manager.itemError(e),a.manager.itemEnd(e)});cs.add(`image-bitmap:${e}`,l),a.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}let nu;class Mg{static getContext(){return nu===void 0&&(nu=new(window.AudioContext||window.webkitAudioContext)),nu}static setContext(e){nu=e}}class LR extends on{constructor(e){super(e)}load(e,t,i,s){const a=this,r=new Gn(this.manager);r.setResponseType("arraybuffer"),r.setPath(this.path),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,function(l){try{const c=l.slice(0);Mg.getContext().decodeAudioData(c,function(d){t(d)}).catch(o)}catch(c){o(c)}},i,s);function o(l){s?s(l):console.error(l),a.manager.itemError(e)}}}const h0=new Me,f0=new Me,Ta=new Me;class kR{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new Jt,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Jt,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){const t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,Ta.copy(e.projectionMatrix);const s=t.eyeSep/2,a=s*t.near/t.focus,r=t.near*Math.tan(ir*t.fov*.5)/t.zoom;let o,l;f0.elements[12]=-s,h0.elements[12]=s,o=-r*t.aspect+a,l=r*t.aspect+a,Ta.elements[0]=2*t.near/(l-o),Ta.elements[8]=(l+o)/(l-o),this.cameraL.projectionMatrix.copy(Ta),o=-r*t.aspect-a,l=r*t.aspect-a,Ta.elements[0]=2*t.near/(l-o),Ta.elements[8]=(l+o)/(l-o),this.cameraR.projectionMatrix.copy(Ta)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(f0),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(h0)}}class iT extends Jt{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class Eg{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}const Ma=new S,ep=new dt,DR=new S,Ea=new S,Ca=new S;class OR extends Qe{constructor(){super(),this.type="AudioListener",this.context=Mg.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new Eg}getInput(){return this.gain}removeFilter(){return this.filter!==null&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return this.filter!==null?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e);const t=this.context.listener;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(Ma,ep,DR),Ea.set(0,0,-1).applyQuaternion(ep),Ca.set(0,1,0).applyQuaternion(ep),t.positionX){const i=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(Ma.x,i),t.positionY.linearRampToValueAtTime(Ma.y,i),t.positionZ.linearRampToValueAtTime(Ma.z,i),t.forwardX.linearRampToValueAtTime(Ea.x,i),t.forwardY.linearRampToValueAtTime(Ea.y,i),t.forwardZ.linearRampToValueAtTime(Ea.z,i),t.upX.linearRampToValueAtTime(Ca.x,i),t.upY.linearRampToValueAtTime(Ca.y,i),t.upZ.linearRampToValueAtTime(Ca.z,i)}else t.setPosition(Ma.x,Ma.y,Ma.z),t.setOrientation(Ea.x,Ea.y,Ea.z,Ca.x,Ca.y,Ca.z)}}class sT extends Qe{constructor(e){super(),this.type="Audio",this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType="buffer",this.autoplay&&this.play(),this}play(e=0){if(this.isPlaying===!0){console.warn("THREE.Audio: Audio is already playing.");return}if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}this._startedAt=this.context.currentTime+e;const t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.isPlaying===!0&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this}stop(e=0){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this._progress=0,this.source!==null&&(this.source.stop(this.context.currentTime+e),this.source.onended=null),this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(i,s,this._addIndex*t,1,t);for(let l=t,c=t+t;l!==c;++l)if(i[l]!==i[l+t]){o.setValue(i,s);break}}saveOriginalState(){const e=this.binding,t=this.buffer,i=this.valueSize,s=i*this._origIndex;e.getValue(t,s);for(let a=i,r=s;a!==r;++a)t[a]=t[s+a%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let i=e;i=.5)for(let r=0;r!==a;++r)e[t+r]=e[i+r]}_slerp(e,t,i,s){dt.slerpFlat(e,t,e,t,e,i,s)}_slerpAdditive(e,t,i,s,a){const r=this._workIndex*a;dt.multiplyQuaternionsFlat(e,r,e,t,e,i),dt.slerpFlat(e,t,e,t,e,r,s)}_lerp(e,t,i,s,a){const r=1-s;for(let o=0;o!==a;++o){const l=t+o;e[l]=e[l]*r+e[i+o]*s}}_lerpAdditive(e,t,i,s,a){for(let r=0;r!==a;++r){const o=t+r;e[o]=e[o]+e[i+r]*s}}}const Cg="\\[\\]\\.:\\/",BR=new RegExp("["+Cg+"]","g"),Ag="[^"+Cg+"]",zR="[^"+Cg.replace("\\.","")+"]",HR=/((?:WC+[\/:])*)/.source.replace("WC",Ag),VR=/(WCOD+)?/.source.replace("WCOD",zR),GR=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Ag),$R=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Ag),WR=new RegExp("^"+HR+VR+GR+$R+"$"),XR=["material","materials","bones","map"];class KR{constructor(e,t,i){const s=i||yt.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,s)}getValue(e,t){this.bind();const i=this._targetGroup.nCachedObjects_,s=this._bindings[i];s!==void 0&&s.getValue(e,t)}setValue(e,t){const i=this._bindings;for(let s=this._targetGroup.nCachedObjects_,a=i.length;s!==a;++s)i[s].setValue(e,t)}bind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].bind()}unbind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].unbind()}}class yt{constructor(e,t,i){this.path=t,this.parsedPath=i||yt.parseTrackName(t),this.node=yt.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,i){return e&&e.isAnimationObjectGroup?new yt.Composite(e,t,i):new yt(e,t,i)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(BR,"")}static parseTrackName(e){const t=WR.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const i={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},s=i.nodeName&&i.nodeName.lastIndexOf(".");if(s!==void 0&&s!==-1){const a=i.nodeName.substring(s+1);XR.indexOf(a)!==-1&&(i.nodeName=i.nodeName.substring(0,s),i.objectName=a)}if(i.propertyName===null||i.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return i}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){const i=e.skeleton.getBoneByName(t);if(i!==void 0)return i}if(e.children){const i=function(a){for(let r=0;r=a){const d=a++,h=e[d];t[h.uuid]=u,e[u]=h,t[c]=d,e[d]=l;for(let f=0,p=s;f!==p;++f){const g=i[f],_=g[d],m=g[u];g[u]=_,g[d]=m}}}this.nCachedObjects_=a}uncache(){const e=this._objects,t=this._indicesByUUID,i=this._bindings,s=i.length;let a=this.nCachedObjects_,r=e.length;for(let o=0,l=arguments.length;o!==l;++o){const c=arguments[o],u=c.uuid,d=t[u];if(d!==void 0)if(delete t[u],d0&&(t[f.uuid]=d),e[d]=f,e.pop();for(let p=0,g=s;p!==g;++p){const _=i[p];_[d]=_[h],_.pop()}}}this.nCachedObjects_=a}subscribe_(e,t){const i=this._bindingsIndicesByPath;let s=i[e];const a=this._bindings;if(s!==void 0)return a[s];const r=this._paths,o=this._parsedPaths,l=this._objects,c=l.length,u=this.nCachedObjects_,d=new Array(c);s=a.length,i[e]=s,r.push(e),o.push(t),a.push(d);for(let h=u,f=l.length;h!==f;++h){const p=l[h];d[h]=new yt(p,e,t)}return d}unsubscribe_(e){const t=this._bindingsIndicesByPath,i=t[e];if(i!==void 0){const s=this._paths,a=this._parsedPaths,r=this._bindings,o=r.length-1,l=r[o],c=e[o];t[c]=i,r[i]=l,r.pop(),a[i]=a[o],a.pop(),s[i]=s[o],s.pop()}}}class rT{constructor(e,t,i=null,s=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=i,this.blendMode=s;const a=t.tracks,r=a.length,o=new Array(r),l={endingStart:qa,endingEnd:qa};for(let c=0;c!==r;++c){const u=a[c].createInterpolant(null);o[c]=u,u.settings=l}this._interpolantSettings=l,this._interpolants=o,this._propertyBindings=new Array(r),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=sS,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,i=!1){if(e.fadeOut(t),this.fadeIn(t),i===!0){const s=this._clip.duration,a=e._clip.duration,r=a/s,o=s/a;e.warp(1,r,t),this.warp(o,1,t)}return this}crossFadeTo(e,t,i=!1){return e.crossFadeFrom(this,t,i)}stopFading(){const e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,i){const s=this._mixer,a=s.time,r=this.timeScale;let o=this._timeScaleInterpolant;o===null&&(o=s._lendControlInterpolant(),this._timeScaleInterpolant=o);const l=o.parameterPositions,c=o.sampleValues;return l[0]=a,l[1]=a+i,c[0]=e/r,c[1]=t/r,this}stopWarping(){const e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,i,s){if(!this.enabled){this._updateWeight(e);return}const a=this._startTime;if(a!==null){const l=(e-a)*i;l<0||i===0?t=0:(this._startTime=null,t=i*l)}t*=this._updateTimeScale(e);const r=this._updateTime(t),o=this._updateWeight(e);if(o>0){const l=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case tg:for(let u=0,d=l.length;u!==d;++u)l[u].evaluate(r),c[u].accumulateAdditive(o);break;case Rh:default:for(let u=0,d=l.length;u!==d;++u)l[u].evaluate(r),c[u].accumulate(s,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const i=this._weightInterpolant;if(i!==null){const s=i.evaluate(e)[0];t*=s,e>i.parameterPositions[1]&&(this.stopFading(),s===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const i=this._timeScaleInterpolant;if(i!==null){const s=i.evaluate(e)[0];t*=s,e>i.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,i=this.loop;let s=this.time+e,a=this._loopCount;const r=i===aS;if(e===0)return a===-1?s:r&&(a&1)===1?t-s:s;if(i===Jd){a===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(s>=t)s=t;else if(s<0)s=0;else{this.time=s;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(a===-1&&(e>=0?(a=0,this._setEndings(!0,this.repetitions===0,r)):this._setEndings(this.repetitions===0,!0,r)),s>=t||s<0){const o=Math.floor(s/t);s-=t*o,a+=Math.abs(o);const l=this.repetitions-a;if(l<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,s=e>0?t:0,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(l===1){const c=e<0;this._setEndings(c,!c,r)}else this._setEndings(!1,!1,r);this._loopCount=a,this.time=s,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this.time=s;if(r&&(a&1)===1)return t-s}return s}_setEndings(e,t,i){const s=this._interpolantSettings;i?(s.endingStart=Ya,s.endingEnd=Ya):(e?s.endingStart=this.zeroSlopeAtStart?Ya:qa:s.endingStart=Vl,t?s.endingEnd=this.zeroSlopeAtEnd?Ya:qa:s.endingEnd=Vl)}_scheduleFading(e,t,i){const s=this._mixer,a=s.time;let r=this._weightInterpolant;r===null&&(r=s._lendControlInterpolant(),this._weightInterpolant=r);const o=r.parameterPositions,l=r.sampleValues;return o[0]=a,l[0]=t,o[1]=a+e,l[1]=i,this}}const YR=new Float32Array(1);class oT extends gs{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const i=e._localRoot||this._root,s=e._clip.tracks,a=s.length,r=e._propertyBindings,o=e._interpolants,l=i.uuid,c=this._bindingsByRootAndName;let u=c[l];u===void 0&&(u={},c[l]=u);for(let d=0;d!==a;++d){const h=s[d],f=h.name;let p=u[f];if(p!==void 0)++p.referenceCount,r[d]=p;else{if(p=r[d],p!==void 0){p._cacheIndex===null&&(++p.referenceCount,this._addInactiveBinding(p,l,f));continue}const g=t&&t._propertyBindings[d].binding.parsedPath;p=new aT(yt.create(i,f,g),h.ValueTypeName,h.getValueSize()),++p.referenceCount,this._addInactiveBinding(p,l,f),r[d]=p}o[d].resultBuffer=p.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){const i=(e._localRoot||this._root).uuid,s=e._clip.uuid,a=this._actionsByClip[s];this._bindAction(e,a&&a.knownActions[0]),this._addInactiveAction(e,s,i)}const t=e._propertyBindings;for(let i=0,s=t.length;i!==s;++i){const a=t[i];a.useCount++===0&&(this._lendBinding(a),a.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let i=0,s=t.length;i!==s;++i){const a=t[i];--a.useCount===0&&(a.restoreOriginalState(),this._takeBackBinding(a))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return t!==null&&t=0;--i)e[i].stop();return this}update(e){e*=this.timeScale;const t=this._actions,i=this._nActiveActions,s=this.time+=e,a=Math.sign(e),r=this._accuIndex^=1;for(let c=0;c!==i;++c)t[c]._update(s,e,a,r);const o=this._bindings,l=this._nActiveBindings;for(let c=0;c!==l;++c)o[c].apply(r);return this}setTime(e){this.time=0;for(let t=0;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,g0).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const y0=new S,iu=new S,Nr=new S,Ur=new S,tp=new S,rP=new S,oP=new S;class lP{constructor(e=new S,t=new S){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){y0.subVectors(e,this.start),iu.subVectors(this.end,this.start);const i=iu.dot(iu);let a=iu.dot(y0)/i;return t&&(a=Ze(a,0,1)),a}closestPointToPoint(e,t,i){const s=this.closestPointToPointParameter(e,t);return this.delta(i).multiplyScalar(s).add(this.start)}distanceSqToLine3(e,t=rP,i=oP){const s=10000000000000001e-32;let a,r;const o=this.start,l=e.start,c=this.end,u=e.end;Nr.subVectors(c,o),Ur.subVectors(u,l),tp.subVectors(o,l);const d=Nr.dot(Nr),h=Ur.dot(Ur),f=Ur.dot(tp);if(d<=s&&h<=s)return t.copy(o),i.copy(l),t.sub(i),t.dot(t);if(d<=s)a=0,r=f/h,r=Ze(r,0,1);else{const p=Nr.dot(tp);if(h<=s)r=0,a=Ze(-p/d,0,1);else{const g=Nr.dot(Ur),_=d*h-g*g;_!==0?a=Ze((g*f-p*h)/_,0,1):a=0,r=(g*a+f)/h,r<0?(r=0,a=Ze(-p/d,0,1)):r>1&&(r=1,a=Ze((g-p)/d,0,1))}}return t.copy(o).add(Nr.multiplyScalar(a)),i.copy(l).add(Ur.multiplyScalar(r)),t.sub(i),t.dot(t)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}const v0=new S;class cP extends Qe{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const i=new Ge,s=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let r=0,o=1,l=32;r1)for(let d=0;d.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{T0.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(T0,t)}}setLength(e,t=e*.2,i=t*.2){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(i,t,i),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class xP extends Ln{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],i=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],s=new Ge;s.setAttribute("position",new Ee(t,3)),s.setAttribute("color",new Ee(i,3));const a=new Rt({vertexColors:!0,toneMapped:!1});super(s,a),this.type="AxesHelper"}setColors(e,t,i){const s=new ue,a=this.geometry.attributes.color.array;return s.set(e),s.toArray(a,0),s.toArray(a,3),s.set(t),s.toArray(a,6),s.toArray(a,9),s.set(i),s.toArray(a,12),s.toArray(a,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class wP{constructor(){this.type="ShapePath",this.color=new ue,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new ih,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,i,s){return this.currentPath.quadraticCurveTo(e,t,i,s),this}bezierCurveTo(e,t,i,s,a,r){return this.currentPath.bezierCurveTo(e,t,i,s,a,r),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(m){const v=[];for(let y=0,b=m.length;yNumber.EPSILON){if(E<0&&(M=v[x],w=-w,C=v[T],E=-E),m.yC.y)continue;if(m.y===M.y){if(m.x===M.x)return!0}else{const R=E*(m.x-M.x)-w*(m.y-M.y);if(R===0)return!0;if(R<0)continue;b=!b}}else{if(m.y!==M.y)continue;if(C.x<=m.x&&m.x<=M.x||M.x<=m.x&&m.x<=C.x)return!0}}return b}const s=Ei.isClockWise,a=this.subPaths;if(a.length===0)return[];let r,o,l;const c=[];if(a.length===1)return o=a[0],l=new Ns,l.curves=o.curves,c.push(l),c;let u=!s(a[0].getPoints());u=e?!u:u;const d=[],h=[];let f=[],p=0,g;h[p]=void 0,f[p]=[];for(let m=0,v=a.length;m1){let m=!1,v=0;for(let y=0,b=h.length;y0&&m===!1&&(f=d)}let _;for(let m=0,v=h.length;me?(n.repeat.x=1,n.repeat.y=t/e,n.offset.x=0,n.offset.y=(1-n.repeat.y)/2):(n.repeat.x=e/t,n.repeat.y=1,n.offset.x=(1-n.repeat.x)/2,n.offset.y=0),n}function TP(n,e){const t=n.image&&n.image.width?n.image.width/n.image.height:1;return t>e?(n.repeat.x=e/t,n.repeat.y=1,n.offset.x=(1-n.repeat.x)/2,n.offset.y=0):(n.repeat.x=1,n.repeat.y=t/e,n.offset.x=0,n.offset.y=(1-n.repeat.y)/2),n}function MP(n){return n.repeat.x=1,n.repeat.y=1,n.offset.x=0,n.offset.y=0,n}function Fm(n,e,t,i){const s=EP(i);switch(t){case J_:return n*e;case Eh:return n*e/s.components*s.byteLength;case oc:return n*e/s.components*s.byteLength;case eg:return n*e*2/s.components*s.byteLength;case Ch:return n*e*2/s.components*s.byteLength;case Q_:return n*e*3/s.components*s.byteLength;case Vn:return n*e*4/s.components*s.byteLength;case Ah:return n*e*4/s.components*s.byteLength;case Cl:case Al:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case Rl:case Pl:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case Md:case Cd:return Math.max(n,16)*Math.max(e,8)/4;case Td:case Ed:return Math.max(n,8)*Math.max(e,8)/2;case Ad:case Rd:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case Pd:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case Id:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case Ld:return Math.floor((n+4)/5)*Math.floor((e+3)/4)*16;case kd:return Math.floor((n+4)/5)*Math.floor((e+4)/5)*16;case Dd:return Math.floor((n+5)/6)*Math.floor((e+4)/5)*16;case Od:return Math.floor((n+5)/6)*Math.floor((e+5)/6)*16;case Fd:return Math.floor((n+7)/8)*Math.floor((e+4)/5)*16;case Nd:return Math.floor((n+7)/8)*Math.floor((e+5)/6)*16;case Ud:return Math.floor((n+7)/8)*Math.floor((e+7)/8)*16;case Bd:return Math.floor((n+9)/10)*Math.floor((e+4)/5)*16;case zd:return Math.floor((n+9)/10)*Math.floor((e+5)/6)*16;case Hd:return Math.floor((n+9)/10)*Math.floor((e+7)/8)*16;case Vd:return Math.floor((n+9)/10)*Math.floor((e+9)/10)*16;case Gd:return Math.floor((n+11)/12)*Math.floor((e+9)/10)*16;case $d:return Math.floor((n+11)/12)*Math.floor((e+11)/12)*16;case Wd:case Xd:case Kd:return Math.ceil(n/4)*Math.ceil(e/4)*16;case qd:case Yd:return Math.ceil(n/4)*Math.ceil(e/4)*8;case jd:case Zd:return Math.ceil(n/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function EP(n){switch(n){case ji:case q_:return{byteLength:1,components:1};case xo:case Y_:case ls:return{byteLength:2,components:1};case Th:case Mh:return{byteLength:2,components:4};case zs:case Sh:case Sn:return{byteLength:4,components:1};case j_:case Z_:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${n}.`)}class CP{static contain(e,t){return SP(e,t)}static cover(e,t){return TP(e,t)}static fill(e){return MP(e)}static getByteLength(e,t,i,s){return Fm(e,t,i,s)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:bh}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=bh);function uT(){let n=null,e=!1,t=null,i=null;function s(a,r){t(a,r),i=n.requestAnimationFrame(s)}return{start:function(){e!==!0&&t!==null&&(i=n.requestAnimationFrame(s),e=!0)},stop:function(){n.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(a){t=a},setContext:function(a){n=a}}}function AP(n){const e=new WeakMap;function t(o,l){const c=o.array,u=o.usage,d=c.byteLength,h=n.createBuffer();n.bindBuffer(l,h),n.bufferData(l,c,u),o.onUploadCallback();let f;if(c instanceof Float32Array)f=n.FLOAT;else if(typeof Float16Array<"u"&&c instanceof Float16Array)f=n.HALF_FLOAT;else if(c instanceof Uint16Array)o.isFloat16BufferAttribute?f=n.HALF_FLOAT:f=n.UNSIGNED_SHORT;else if(c instanceof Int16Array)f=n.SHORT;else if(c instanceof Uint32Array)f=n.UNSIGNED_INT;else if(c instanceof Int32Array)f=n.INT;else if(c instanceof Int8Array)f=n.BYTE;else if(c instanceof Uint8Array)f=n.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)f=n.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:h,type:f,bytesPerElement:c.BYTES_PER_ELEMENT,version:o.version,size:d}}function i(o,l,c){const u=l.array,d=l.updateRanges;if(n.bindBuffer(c,o),d.length===0)n.bufferSubData(c,0,u);else{d.sort((f,p)=>f.start-p.start);let h=0;for(let f=1;f 0 +#endif`,$P=`#if NUM_CLIPPING_PLANES > 0 vec4 plane; #ifdef ALPHA_TO_COVERAGE float distanceToPlane, distanceGradient; @@ -289,26 +289,26 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve if ( clipped ) discard; #endif #endif -#endif`,kP=`#if NUM_CLIPPING_PLANES > 0 +#endif`,WP=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; -#endif`,OP=`#if NUM_CLIPPING_PLANES > 0 +#endif`,XP=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; -#endif`,FP=`#if NUM_CLIPPING_PLANES > 0 +#endif`,KP=`#if NUM_CLIPPING_PLANES > 0 vClipPosition = - mvPosition.xyz; -#endif`,NP=`#if defined( USE_COLOR_ALPHA ) +#endif`,qP=`#if defined( USE_COLOR_ALPHA ) diffuseColor *= vColor; #elif defined( USE_COLOR ) diffuseColor.rgb *= vColor; -#endif`,UP=`#if defined( USE_COLOR_ALPHA ) +#endif`,YP=`#if defined( USE_COLOR_ALPHA ) varying vec4 vColor; #elif defined( USE_COLOR ) varying vec3 vColor; -#endif`,BP=`#if defined( USE_COLOR_ALPHA ) +#endif`,jP=`#if defined( USE_COLOR_ALPHA ) varying vec4 vColor; #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) varying vec3 vColor; -#endif`,zP=`#if defined( USE_COLOR_ALPHA ) +#endif`,ZP=`#if defined( USE_COLOR_ALPHA ) vColor = vec4( 1.0 ); #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) vColor = vec3( 1.0 ); @@ -322,7 +322,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve #ifdef USE_BATCHING_COLOR vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); vColor.xyz *= batchingColor.xyz; -#endif`,HP=`#define PI 3.141592653589793 +#endif`,JP=`#define PI 3.141592653589793 #define PI2 6.283185307179586 #define PI_HALF 1.5707963267948966 #define RECIPROCAL_PI 0.3183098861837907 @@ -396,7 +396,7 @@ vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); -} // validated`,VP=`#ifdef ENVMAP_TYPE_CUBE_UV +} // validated`,QP=`#ifdef ENVMAP_TYPE_CUBE_UV #define cubeUV_minMipLevel 4.0 #define cubeUV_minTileSize 16.0 float getFace( vec3 direction ) { @@ -489,7 +489,7 @@ float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { return vec4( mix( color0, color1, mipF ), 1.0 ); } } -#endif`,GP=`vec3 transformedNormal = objectNormal; +#endif`,eI=`vec3 transformedNormal = objectNormal; #ifdef USE_TANGENT vec3 transformedTangent = objectTangent; #endif @@ -518,21 +518,21 @@ transformedNormal = normalMatrix * transformedNormal; #ifdef FLIP_SIDED transformedTangent = - transformedTangent; #endif -#endif`,$P=`#ifdef USE_DISPLACEMENTMAP +#endif`,tI=`#ifdef USE_DISPLACEMENTMAP uniform sampler2D displacementMap; uniform float displacementScale; uniform float displacementBias; -#endif`,WP=`#ifdef USE_DISPLACEMENTMAP +#endif`,nI=`#ifdef USE_DISPLACEMENTMAP transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); -#endif`,XP=`#ifdef USE_EMISSIVEMAP +#endif`,iI=`#ifdef USE_EMISSIVEMAP vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE emissiveColor = sRGBTransferEOTF( emissiveColor ); #endif totalEmissiveRadiance *= emissiveColor.rgb; -#endif`,KP=`#ifdef USE_EMISSIVEMAP +#endif`,sI=`#ifdef USE_EMISSIVEMAP uniform sampler2D emissiveMap; -#endif`,qP="gl_FragColor = linearToOutputTexel( gl_FragColor );",YP=`vec4 LinearTransferOETF( in vec4 value ) { +#endif`,aI="gl_FragColor = linearToOutputTexel( gl_FragColor );",rI=`vec4 LinearTransferOETF( in vec4 value ) { return value; } vec4 sRGBTransferEOTF( in vec4 value ) { @@ -540,7 +540,7 @@ vec4 sRGBTransferEOTF( in vec4 value ) { } vec4 sRGBTransferOETF( in vec4 value ) { return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); -}`,jP=`#ifdef USE_ENVMAP +}`,oI=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vec3 cameraToFrag; if ( isOrthographic ) { @@ -569,7 +569,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { #elif defined( ENVMAP_BLENDING_ADD ) outgoingLight += envColor.xyz * specularStrength * reflectivity; #endif -#endif`,ZP=`#ifdef USE_ENVMAP +#endif`,lI=`#ifdef USE_ENVMAP uniform float envMapIntensity; uniform float flipEnvMap; uniform mat3 envMapRotation; @@ -579,7 +579,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { uniform sampler2D envMap; #endif -#endif`,JP=`#ifdef USE_ENVMAP +#endif`,cI=`#ifdef USE_ENVMAP uniform float reflectivity; #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS @@ -590,7 +590,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { #else varying vec3 vReflect; #endif -#endif`,QP=`#ifdef USE_ENVMAP +#endif`,uI=`#ifdef USE_ENVMAP #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif @@ -601,7 +601,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { varying vec3 vReflect; uniform float refractionRatio; #endif -#endif`,eI=`#ifdef USE_ENVMAP +#endif`,dI=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vWorldPosition = worldPosition.xyz; #else @@ -618,18 +618,18 @@ vec4 sRGBTransferOETF( in vec4 value ) { vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); #endif #endif -#endif`,tI=`#ifdef USE_FOG +#endif`,hI=`#ifdef USE_FOG vFogDepth = - mvPosition.z; -#endif`,nI=`#ifdef USE_FOG +#endif`,fI=`#ifdef USE_FOG varying float vFogDepth; -#endif`,iI=`#ifdef USE_FOG +#endif`,pI=`#ifdef USE_FOG #ifdef FOG_EXP2 float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); #else float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); #endif gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); -#endif`,sI=`#ifdef USE_FOG +#endif`,mI=`#ifdef USE_FOG uniform vec3 fogColor; varying float vFogDepth; #ifdef FOG_EXP2 @@ -638,7 +638,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { uniform float fogNear; uniform float fogFar; #endif -#endif`,aI=`#ifdef USE_GRADIENTMAP +#endif`,_I=`#ifdef USE_GRADIENTMAP uniform sampler2D gradientMap; #endif vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { @@ -650,12 +650,12 @@ vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { vec2 fw = fwidth( coord ) * 0.5; return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); #endif -}`,rI=`#ifdef USE_LIGHTMAP +}`,gI=`#ifdef USE_LIGHTMAP uniform sampler2D lightMap; uniform float lightMapIntensity; -#endif`,oI=`LambertMaterial material; +#endif`,yI=`LambertMaterial material; material.diffuseColor = diffuseColor.rgb; -material.specularStrength = specularStrength;`,lI=`varying vec3 vViewPosition; +material.specularStrength = specularStrength;`,vI=`varying vec3 vViewPosition; struct LambertMaterial { vec3 diffuseColor; float specularStrength; @@ -669,7 +669,7 @@ void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometr reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Lambert -#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,cI=`uniform bool receiveShadow; +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,bI=`uniform bool receiveShadow; uniform vec3 ambientLightColor; #if defined( USE_LIGHT_PROBES ) uniform vec3 lightProbe[ 9 ]; @@ -785,7 +785,7 @@ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosi vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); return irradiance; } -#endif`,uI=`#ifdef USE_ENVMAP +#endif`,xI=`#ifdef USE_ENVMAP vec3 getIBLIrradiance( const in vec3 normal ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); @@ -818,8 +818,8 @@ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosi #endif } #endif -#endif`,dI=`ToonMaterial material; -material.diffuseColor = diffuseColor.rgb;`,hI=`varying vec3 vViewPosition; +#endif`,wI=`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,SI=`varying vec3 vViewPosition; struct ToonMaterial { vec3 diffuseColor; }; @@ -831,11 +831,11 @@ void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPo reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Toon -#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,fI=`BlinnPhongMaterial material; +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,TI=`BlinnPhongMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularColor = specular; material.specularShininess = shininess; -material.specularStrength = specularStrength;`,pI=`varying vec3 vViewPosition; +material.specularStrength = specularStrength;`,MI=`varying vec3 vViewPosition; struct BlinnPhongMaterial { vec3 diffuseColor; vec3 specularColor; @@ -852,7 +852,7 @@ void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geom reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_BlinnPhong -#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,mI=`PhysicalMaterial material; +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,EI=`PhysicalMaterial material; material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); @@ -938,7 +938,7 @@ material.roughness = min( material.roughness, 1.0 ); material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; -#endif`,_I=`struct PhysicalMaterial { +#endif`,CI=`struct PhysicalMaterial { vec3 diffuseColor; float roughness; vec3 specularColor; @@ -1239,7 +1239,7 @@ void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradia #define RE_IndirectSpecular RE_IndirectSpecular_Physical float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); -}`,gI=` +}`,AI=` vec3 geometryPosition = - vViewPosition; vec3 geometryNormal = normal; vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); @@ -1354,7 +1354,7 @@ IncidentLight directLight; #if defined( RE_IndirectSpecular ) vec3 radiance = vec3( 0.0 ); vec3 clearcoatRadiance = vec3( 0.0 ); -#endif`,yI=`#if defined( RE_IndirectDiffuse ) +#endif`,RI=`#if defined( RE_IndirectDiffuse ) #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; @@ -1373,32 +1373,32 @@ IncidentLight directLight; #ifdef USE_CLEARCOAT clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); #endif -#endif`,vI=`#if defined( RE_IndirectDiffuse ) +#endif`,PI=`#if defined( RE_IndirectDiffuse ) RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); #endif #if defined( RE_IndirectSpecular ) RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); -#endif`,bI=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) +#endif`,II=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; -#endif`,xI=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) +#endif`,LI=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) uniform float logDepthBufFC; varying float vFragDepth; varying float vIsPerspective; -#endif`,wI=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER +#endif`,kI=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER varying float vFragDepth; varying float vIsPerspective; -#endif`,SI=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER +#endif`,DI=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER vFragDepth = 1.0 + gl_Position.w; vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); -#endif`,TI=`#ifdef USE_MAP +#endif`,OI=`#ifdef USE_MAP vec4 sampledDiffuseColor = texture2D( map, vMapUv ); #ifdef DECODE_VIDEO_TEXTURE sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); #endif diffuseColor *= sampledDiffuseColor; -#endif`,MI=`#ifdef USE_MAP +#endif`,FI=`#ifdef USE_MAP uniform sampler2D map; -#endif`,EI=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) +#endif`,NI=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) #if defined( USE_POINTS_UV ) vec2 uv = vUv; #else @@ -1410,7 +1410,7 @@ IncidentLight directLight; #endif #ifdef USE_ALPHAMAP diffuseColor.a *= texture2D( alphaMap, uv ).g; -#endif`,CI=`#if defined( USE_POINTS_UV ) +#endif`,UI=`#if defined( USE_POINTS_UV ) varying vec2 vUv; #else #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) @@ -1422,19 +1422,19 @@ IncidentLight directLight; #endif #ifdef USE_ALPHAMAP uniform sampler2D alphaMap; -#endif`,AI=`float metalnessFactor = metalness; +#endif`,BI=`float metalnessFactor = metalness; #ifdef USE_METALNESSMAP vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); metalnessFactor *= texelMetalness.b; -#endif`,RI=`#ifdef USE_METALNESSMAP +#endif`,zI=`#ifdef USE_METALNESSMAP uniform sampler2D metalnessMap; -#endif`,PI=`#ifdef USE_INSTANCING_MORPH +#endif`,HI=`#ifdef USE_INSTANCING_MORPH float morphTargetInfluences[ MORPHTARGETS_COUNT ]; float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; } -#endif`,II=`#if defined( USE_MORPHCOLORS ) +#endif`,VI=`#if defined( USE_MORPHCOLORS ) vColor *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { #if defined( USE_COLOR_ALPHA ) @@ -1443,12 +1443,12 @@ IncidentLight directLight; if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; #endif } -#endif`,LI=`#ifdef USE_MORPHNORMALS +#endif`,GI=`#ifdef USE_MORPHNORMALS objectNormal *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; } -#endif`,DI=`#ifdef USE_MORPHTARGETS +#endif`,$I=`#ifdef USE_MORPHTARGETS #ifndef USE_INSTANCING_MORPH uniform float morphTargetBaseInfluence; uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; @@ -1462,12 +1462,12 @@ IncidentLight directLight; ivec3 morphUV = ivec3( x, y, morphTargetIndex ); return texelFetch( morphTargetsTexture, morphUV, 0 ); } -#endif`,kI=`#ifdef USE_MORPHTARGETS +#endif`,WI=`#ifdef USE_MORPHTARGETS transformed *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; } -#endif`,OI=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#endif`,XI=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; #ifdef FLAT_SHADED vec3 fdx = dFdx( vViewPosition ); vec3 fdy = dFdy( vViewPosition ); @@ -1508,7 +1508,7 @@ IncidentLight directLight; tbn2[1] *= faceDirection; #endif #endif -vec3 nonPerturbedNormal = normal;`,FI=`#ifdef USE_NORMALMAP_OBJECTSPACE +vec3 nonPerturbedNormal = normal;`,KI=`#ifdef USE_NORMALMAP_OBJECTSPACE normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; #ifdef FLIP_SIDED normal = - normal; @@ -1523,25 +1523,25 @@ vec3 nonPerturbedNormal = normal;`,FI=`#ifdef USE_NORMALMAP_OBJECTSPACE normal = normalize( tbn * mapN ); #elif defined( USE_BUMPMAP ) normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); -#endif`,NI=`#ifndef FLAT_SHADED +#endif`,qI=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif -#endif`,UI=`#ifndef FLAT_SHADED +#endif`,YI=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif -#endif`,BI=`#ifndef FLAT_SHADED +#endif`,jI=`#ifndef FLAT_SHADED vNormal = normalize( transformedNormal ); #ifdef USE_TANGENT vTangent = normalize( transformedTangent ); vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); #endif -#endif`,zI=`#ifdef USE_NORMALMAP +#endif`,ZI=`#ifdef USE_NORMALMAP uniform sampler2D normalMap; uniform vec2 normalScale; #endif @@ -1563,13 +1563,13 @@ vec3 nonPerturbedNormal = normal;`,FI=`#ifdef USE_NORMALMAP_OBJECTSPACE float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); return mat3( T * scale, B * scale, N ); } -#endif`,HI=`#ifdef USE_CLEARCOAT +#endif`,JI=`#ifdef USE_CLEARCOAT vec3 clearcoatNormal = nonPerturbedNormal; -#endif`,VI=`#ifdef USE_CLEARCOAT_NORMALMAP +#endif`,QI=`#ifdef USE_CLEARCOAT_NORMALMAP vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; clearcoatMapN.xy *= clearcoatNormalScale; clearcoatNormal = normalize( tbn2 * clearcoatMapN ); -#endif`,GI=`#ifdef USE_CLEARCOATMAP +#endif`,eL=`#ifdef USE_CLEARCOATMAP uniform sampler2D clearcoatMap; #endif #ifdef USE_CLEARCOAT_NORMALMAP @@ -1578,18 +1578,18 @@ vec3 nonPerturbedNormal = normal;`,FI=`#ifdef USE_NORMALMAP_OBJECTSPACE #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform sampler2D clearcoatRoughnessMap; -#endif`,$I=`#ifdef USE_IRIDESCENCEMAP +#endif`,tL=`#ifdef USE_IRIDESCENCEMAP uniform sampler2D iridescenceMap; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform sampler2D iridescenceThicknessMap; -#endif`,WI=`#ifdef OPAQUE +#endif`,nL=`#ifdef OPAQUE diffuseColor.a = 1.0; #endif #ifdef USE_TRANSMISSION diffuseColor.a *= material.transmissionAlpha; #endif -gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,XI=`vec3 packNormalToRGB( const in vec3 normal ) { +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,iL=`vec3 packNormalToRGB( const in vec3 normal ) { return normalize( normal ) * 0.5 + 0.5; } vec3 unpackRGBToNormal( const in vec3 rgb ) { @@ -1658,9 +1658,9 @@ float viewZToPerspectiveDepth( const in float viewZ, const in float near, const } float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { return ( near * far ) / ( ( far - near ) * depth - far ); -}`,KI=`#ifdef PREMULTIPLIED_ALPHA +}`,sL=`#ifdef PREMULTIPLIED_ALPHA gl_FragColor.rgb *= gl_FragColor.a; -#endif`,qI=`vec4 mvPosition = vec4( transformed, 1.0 ); +#endif`,aL=`vec4 mvPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING mvPosition = batchingMatrix * mvPosition; #endif @@ -1668,22 +1668,22 @@ float perspectiveDepthToViewZ( const in float depth, const in float near, const mvPosition = instanceMatrix * mvPosition; #endif mvPosition = modelViewMatrix * mvPosition; -gl_Position = projectionMatrix * mvPosition;`,YI=`#ifdef DITHERING +gl_Position = projectionMatrix * mvPosition;`,rL=`#ifdef DITHERING gl_FragColor.rgb = dithering( gl_FragColor.rgb ); -#endif`,jI=`#ifdef DITHERING +#endif`,oL=`#ifdef DITHERING vec3 dithering( vec3 color ) { float grid_position = rand( gl_FragCoord.xy ); vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); return color + dither_shift_RGB; } -#endif`,ZI=`float roughnessFactor = roughness; +#endif`,lL=`float roughnessFactor = roughness; #ifdef USE_ROUGHNESSMAP vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); roughnessFactor *= texelRoughness.g; -#endif`,JI=`#ifdef USE_ROUGHNESSMAP +#endif`,cL=`#ifdef USE_ROUGHNESSMAP uniform sampler2D roughnessMap; -#endif`,QI=`#if NUM_SPOT_LIGHT_COORDS > 0 +#endif`,uL=`#if NUM_SPOT_LIGHT_COORDS > 0 varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #if NUM_SPOT_LIGHT_MAPS > 0 @@ -1878,7 +1878,7 @@ gl_Position = projectionMatrix * mvPosition;`,YI=`#ifdef DITHERING } return mix( 1.0, shadow, shadowIntensity ); } -#endif`,eL=`#if NUM_SPOT_LIGHT_COORDS > 0 +#endif`,dL=`#if NUM_SPOT_LIGHT_COORDS > 0 uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif @@ -1919,7 +1919,7 @@ gl_Position = projectionMatrix * mvPosition;`,YI=`#ifdef DITHERING }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif -#endif`,tL=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) +#endif`,hL=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); vec4 shadowWorldPosition; #endif @@ -1951,7 +1951,7 @@ gl_Position = projectionMatrix * mvPosition;`,YI=`#ifdef DITHERING vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end -#endif`,nL=`float getShadowMask() { +#endif`,fL=`float getShadowMask() { float shadow = 1.0; #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 @@ -1983,12 +1983,12 @@ gl_Position = projectionMatrix * mvPosition;`,YI=`#ifdef DITHERING #endif #endif return shadow; -}`,iL=`#ifdef USE_SKINNING +}`,pL=`#ifdef USE_SKINNING mat4 boneMatX = getBoneMatrix( skinIndex.x ); mat4 boneMatY = getBoneMatrix( skinIndex.y ); mat4 boneMatZ = getBoneMatrix( skinIndex.z ); mat4 boneMatW = getBoneMatrix( skinIndex.w ); -#endif`,sL=`#ifdef USE_SKINNING +#endif`,mL=`#ifdef USE_SKINNING uniform mat4 bindMatrix; uniform mat4 bindMatrixInverse; uniform highp sampler2D boneTexture; @@ -2003,7 +2003,7 @@ gl_Position = projectionMatrix * mvPosition;`,YI=`#ifdef DITHERING vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); return mat4( v1, v2, v3, v4 ); } -#endif`,aL=`#ifdef USE_SKINNING +#endif`,_L=`#ifdef USE_SKINNING vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); vec4 skinned = vec4( 0.0 ); skinned += boneMatX * skinVertex * skinWeight.x; @@ -2011,7 +2011,7 @@ gl_Position = projectionMatrix * mvPosition;`,YI=`#ifdef DITHERING skinned += boneMatZ * skinVertex * skinWeight.z; skinned += boneMatW * skinVertex * skinWeight.w; transformed = ( bindMatrixInverse * skinned ).xyz; -#endif`,rL=`#ifdef USE_SKINNING +#endif`,gL=`#ifdef USE_SKINNING mat4 skinMatrix = mat4( 0.0 ); skinMatrix += skinWeight.x * boneMatX; skinMatrix += skinWeight.y * boneMatY; @@ -2022,17 +2022,17 @@ gl_Position = projectionMatrix * mvPosition;`,YI=`#ifdef DITHERING #ifdef USE_TANGENT objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; #endif -#endif`,oL=`float specularStrength; +#endif`,yL=`float specularStrength; #ifdef USE_SPECULARMAP vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); specularStrength = texelSpecular.r; #else specularStrength = 1.0; -#endif`,lL=`#ifdef USE_SPECULARMAP +#endif`,vL=`#ifdef USE_SPECULARMAP uniform sampler2D specularMap; -#endif`,cL=`#if defined( TONE_MAPPING ) +#endif`,bL=`#if defined( TONE_MAPPING ) gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); -#endif`,uL=`#ifndef saturate +#endif`,xL=`#ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif uniform float toneMappingExposure; @@ -2129,7 +2129,7 @@ vec3 NeutralToneMapping( vec3 color ) { float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); return mix( color, vec3( newPeak ), g ); } -vec3 CustomToneMapping( vec3 color ) { return color; }`,dL=`#ifdef USE_TRANSMISSION +vec3 CustomToneMapping( vec3 color ) { return color; }`,wL=`#ifdef USE_TRANSMISSION material.transmission = transmission; material.transmissionAlpha = 1.0; material.thickness = thickness; @@ -2150,7 +2150,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,dL=`#ifdef USE_TRANSMISS material.attenuationColor, material.attenuationDistance ); material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); -#endif`,hL=`#ifdef USE_TRANSMISSION +#endif`,SL=`#ifdef USE_TRANSMISSION uniform float transmission; uniform float thickness; uniform float attenuationDistance; @@ -2276,7 +2276,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,dL=`#ifdef USE_TRANSMISS float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); } -#endif`,fL=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) +#endif`,TL=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP @@ -2346,7 +2346,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,dL=`#ifdef USE_TRANSMISS #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; -#endif`,pL=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) +#endif`,ML=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP @@ -2440,7 +2440,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,dL=`#ifdef USE_TRANSMISS #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; -#endif`,mL=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) +#endif`,EL=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) vUv = vec3( uv, 1 ).xy; #endif #ifdef USE_MAP @@ -2511,7 +2511,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,dL=`#ifdef USE_TRANSMISS #endif #ifdef USE_THICKNESSMAP vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; -#endif`,_L=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 +#endif`,CL=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 vec4 worldPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING worldPosition = batchingMatrix * worldPosition; @@ -2520,12 +2520,12 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,dL=`#ifdef USE_TRANSMISS worldPosition = instanceMatrix * worldPosition; #endif worldPosition = modelMatrix * worldPosition; -#endif`;const gL=`varying vec2 vUv; +#endif`;const AL=`varying vec2 vUv; uniform mat3 uvTransform; void main() { vUv = ( uvTransform * vec3( uv, 1 ) ).xy; gl_Position = vec4( position.xy, 1.0, 1.0 ); -}`,yL=`uniform sampler2D t2D; +}`,RL=`uniform sampler2D t2D; uniform float backgroundIntensity; varying vec2 vUv; void main() { @@ -2537,14 +2537,14 @@ void main() { gl_FragColor = texColor; #include #include -}`,vL=`varying vec3 vWorldDirection; +}`,PL=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; -}`,bL=`#ifdef ENVMAP_TYPE_CUBE +}`,IL=`#ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #elif defined( ENVMAP_TYPE_CUBE_UV ) uniform sampler2D envMap; @@ -2567,14 +2567,14 @@ void main() { gl_FragColor = texColor; #include #include -}`,xL=`varying vec3 vWorldDirection; +}`,LL=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; -}`,wL=`uniform samplerCube tCube; +}`,kL=`uniform samplerCube tCube; uniform float tFlip; uniform float opacity; varying vec3 vWorldDirection; @@ -2584,7 +2584,7 @@ void main() { gl_FragColor.a *= opacity; #include #include -}`,SL=`#include +}`,DL=`#include #include #include #include @@ -2611,7 +2611,7 @@ void main() { #include #include vHighPrecisionZW = gl_Position.zw; -}`,TL=`#if DEPTH_PACKING == 3200 +}`,OL=`#if DEPTH_PACKING == 3200 uniform float opacity; #endif #include @@ -2649,7 +2649,7 @@ void main() { #elif DEPTH_PACKING == 3203 gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); #endif -}`,ML=`#define DISTANCE +}`,FL=`#define DISTANCE varying vec3 vWorldPosition; #include #include @@ -2676,7 +2676,7 @@ void main() { #include #include vWorldPosition = worldPosition.xyz; -}`,EL=`#define DISTANCE +}`,NL=`#define DISTANCE uniform vec3 referencePosition; uniform float nearDistance; uniform float farDistance; @@ -2700,13 +2700,13 @@ void main () { dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); dist = saturate( dist ); gl_FragColor = packDepthToRGBA( dist ); -}`,CL=`varying vec3 vWorldDirection; +}`,UL=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include -}`,AL=`uniform sampler2D tEquirect; +}`,BL=`uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { @@ -2715,7 +2715,7 @@ void main() { gl_FragColor = texture2D( tEquirect, sampleUV ); #include #include -}`,RL=`uniform float scale; +}`,zL=`uniform float scale; attribute float lineDistance; varying float vLineDistance; #include @@ -2737,7 +2737,7 @@ void main() { #include #include #include -}`,PL=`uniform vec3 diffuse; +}`,HL=`uniform vec3 diffuse; uniform float opacity; uniform float dashSize; uniform float totalSize; @@ -2765,7 +2765,7 @@ void main() { #include #include #include -}`,IL=`#include +}`,VL=`#include #include #include #include @@ -2797,7 +2797,7 @@ void main() { #include #include #include -}`,LL=`uniform vec3 diffuse; +}`,GL=`uniform vec3 diffuse; uniform float opacity; #ifndef FLAT_SHADED varying vec3 vNormal; @@ -2845,7 +2845,7 @@ void main() { #include #include #include -}`,DL=`#define LAMBERT +}`,$L=`#define LAMBERT varying vec3 vViewPosition; #include #include @@ -2884,7 +2884,7 @@ void main() { #include #include #include -}`,kL=`#define LAMBERT +}`,WL=`#define LAMBERT uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; @@ -2941,7 +2941,7 @@ void main() { #include #include #include -}`,OL=`#define MATCAP +}`,XL=`#define MATCAP varying vec3 vViewPosition; #include #include @@ -2975,7 +2975,7 @@ void main() { #include #include vViewPosition = - mvPosition.xyz; -}`,FL=`#define MATCAP +}`,KL=`#define MATCAP uniform vec3 diffuse; uniform float opacity; uniform sampler2D matcap; @@ -3021,7 +3021,7 @@ void main() { #include #include #include -}`,NL=`#define NORMAL +}`,qL=`#define NORMAL #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif @@ -3054,7 +3054,7 @@ void main() { #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) vViewPosition = - mvPosition.xyz; #endif -}`,UL=`#define NORMAL +}`,YL=`#define NORMAL uniform float opacity; #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; @@ -3076,7 +3076,7 @@ void main() { #ifdef OPAQUE gl_FragColor.a = 1.0; #endif -}`,BL=`#define PHONG +}`,jL=`#define PHONG varying vec3 vViewPosition; #include #include @@ -3115,7 +3115,7 @@ void main() { #include #include #include -}`,zL=`#define PHONG +}`,ZL=`#define PHONG uniform vec3 diffuse; uniform vec3 emissive; uniform vec3 specular; @@ -3174,7 +3174,7 @@ void main() { #include #include #include -}`,HL=`#define STANDARD +}`,JL=`#define STANDARD varying vec3 vViewPosition; #ifdef USE_TRANSMISSION varying vec3 vWorldPosition; @@ -3217,7 +3217,7 @@ void main() { #ifdef USE_TRANSMISSION vWorldPosition = worldPosition.xyz; #endif -}`,VL=`#define STANDARD +}`,QL=`#define STANDARD #ifdef PHYSICAL #define IOR #define USE_SPECULAR @@ -3342,7 +3342,7 @@ void main() { #include #include #include -}`,GL=`#define TOON +}`,e2=`#define TOON varying vec3 vViewPosition; #include #include @@ -3379,7 +3379,7 @@ void main() { #include #include #include -}`,$L=`#define TOON +}`,t2=`#define TOON uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; @@ -3432,7 +3432,7 @@ void main() { #include #include #include -}`,WL=`uniform float size; +}`,n2=`uniform float size; uniform float scale; #include #include @@ -3463,7 +3463,7 @@ void main() { #include #include #include -}`,XL=`uniform vec3 diffuse; +}`,i2=`uniform vec3 diffuse; uniform float opacity; #include #include @@ -3488,7 +3488,7 @@ void main() { #include #include #include -}`,KL=`#include +}`,s2=`#include #include #include #include @@ -3511,7 +3511,7 @@ void main() { #include #include #include -}`,qL=`uniform vec3 color; +}`,a2=`uniform vec3 color; uniform float opacity; #include #include @@ -3527,7 +3527,7 @@ void main() { #include #include #include -}`,YL=`uniform float rotation; +}`,r2=`uniform float rotation; uniform vec2 center; #include #include @@ -3551,7 +3551,7 @@ void main() { #include #include #include -}`,jL=`uniform vec3 diffuse; +}`,o2=`uniform vec3 diffuse; uniform float opacity; #include #include @@ -3576,7 +3576,7 @@ void main() { #include #include #include -}`,mt={alphahash_fragment:yP,alphahash_pars_fragment:vP,alphamap_fragment:bP,alphamap_pars_fragment:xP,alphatest_fragment:wP,alphatest_pars_fragment:SP,aomap_fragment:TP,aomap_pars_fragment:MP,batching_pars_vertex:EP,batching_vertex:CP,begin_vertex:AP,beginnormal_vertex:RP,bsdfs:PP,iridescence_fragment:IP,bumpmap_pars_fragment:LP,clipping_planes_fragment:DP,clipping_planes_pars_fragment:kP,clipping_planes_pars_vertex:OP,clipping_planes_vertex:FP,color_fragment:NP,color_pars_fragment:UP,color_pars_vertex:BP,color_vertex:zP,common:HP,cube_uv_reflection_fragment:VP,defaultnormal_vertex:GP,displacementmap_pars_vertex:$P,displacementmap_vertex:WP,emissivemap_fragment:XP,emissivemap_pars_fragment:KP,colorspace_fragment:qP,colorspace_pars_fragment:YP,envmap_fragment:jP,envmap_common_pars_fragment:ZP,envmap_pars_fragment:JP,envmap_pars_vertex:QP,envmap_physical_pars_fragment:uI,envmap_vertex:eI,fog_vertex:tI,fog_pars_vertex:nI,fog_fragment:iI,fog_pars_fragment:sI,gradientmap_pars_fragment:aI,lightmap_pars_fragment:rI,lights_lambert_fragment:oI,lights_lambert_pars_fragment:lI,lights_pars_begin:cI,lights_toon_fragment:dI,lights_toon_pars_fragment:hI,lights_phong_fragment:fI,lights_phong_pars_fragment:pI,lights_physical_fragment:mI,lights_physical_pars_fragment:_I,lights_fragment_begin:gI,lights_fragment_maps:yI,lights_fragment_end:vI,logdepthbuf_fragment:bI,logdepthbuf_pars_fragment:xI,logdepthbuf_pars_vertex:wI,logdepthbuf_vertex:SI,map_fragment:TI,map_pars_fragment:MI,map_particle_fragment:EI,map_particle_pars_fragment:CI,metalnessmap_fragment:AI,metalnessmap_pars_fragment:RI,morphinstance_vertex:PI,morphcolor_vertex:II,morphnormal_vertex:LI,morphtarget_pars_vertex:DI,morphtarget_vertex:kI,normal_fragment_begin:OI,normal_fragment_maps:FI,normal_pars_fragment:NI,normal_pars_vertex:UI,normal_vertex:BI,normalmap_pars_fragment:zI,clearcoat_normal_fragment_begin:HI,clearcoat_normal_fragment_maps:VI,clearcoat_pars_fragment:GI,iridescence_pars_fragment:$I,opaque_fragment:WI,packing:XI,premultiplied_alpha_fragment:KI,project_vertex:qI,dithering_fragment:YI,dithering_pars_fragment:jI,roughnessmap_fragment:ZI,roughnessmap_pars_fragment:JI,shadowmap_pars_fragment:QI,shadowmap_pars_vertex:eL,shadowmap_vertex:tL,shadowmask_pars_fragment:nL,skinbase_vertex:iL,skinning_pars_vertex:sL,skinning_vertex:aL,skinnormal_vertex:rL,specularmap_fragment:oL,specularmap_pars_fragment:lL,tonemapping_fragment:cL,tonemapping_pars_fragment:uL,transmission_fragment:dL,transmission_pars_fragment:hL,uv_pars_fragment:fL,uv_pars_vertex:pL,uv_vertex:mL,worldpos_vertex:_L,background_vert:gL,background_frag:yL,backgroundCube_vert:vL,backgroundCube_frag:bL,cube_vert:xL,cube_frag:wL,depth_vert:SL,depth_frag:TL,distanceRGBA_vert:ML,distanceRGBA_frag:EL,equirect_vert:CL,equirect_frag:AL,linedashed_vert:RL,linedashed_frag:PL,meshbasic_vert:IL,meshbasic_frag:LL,meshlambert_vert:DL,meshlambert_frag:kL,meshmatcap_vert:OL,meshmatcap_frag:FL,meshnormal_vert:NL,meshnormal_frag:UL,meshphong_vert:BL,meshphong_frag:zL,meshphysical_vert:HL,meshphysical_frag:VL,meshtoon_vert:GL,meshtoon_frag:$L,points_vert:WL,points_frag:XL,shadow_vert:KL,shadow_frag:qL,sprite_vert:YL,sprite_frag:jL},Te={common:{diffuse:{value:new ue(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new st},alphaMap:{value:null},alphaMapTransform:{value:new st},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new st}},envmap:{envMap:{value:null},envMapRotation:{value:new st},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new st}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new st}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new st},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new st},normalScale:{value:new te(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new st},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new st}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new st}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new st}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new ue(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new ue(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new st},alphaTest:{value:0},uvTransform:{value:new st}},sprite:{diffuse:{value:new ue(16777215)},opacity:{value:1},center:{value:new te(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new st},alphaMap:{value:null},alphaMapTransform:{value:new st},alphaTest:{value:0}}},Wi={basic:{uniforms:Nn([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.fog]),vertexShader:mt.meshbasic_vert,fragmentShader:mt.meshbasic_frag},lambert:{uniforms:Nn([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,Te.lights,{emissive:{value:new ue(0)}}]),vertexShader:mt.meshlambert_vert,fragmentShader:mt.meshlambert_frag},phong:{uniforms:Nn([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,Te.lights,{emissive:{value:new ue(0)},specular:{value:new ue(1118481)},shininess:{value:30}}]),vertexShader:mt.meshphong_vert,fragmentShader:mt.meshphong_frag},standard:{uniforms:Nn([Te.common,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.roughnessmap,Te.metalnessmap,Te.fog,Te.lights,{emissive:{value:new ue(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:mt.meshphysical_vert,fragmentShader:mt.meshphysical_frag},toon:{uniforms:Nn([Te.common,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.gradientmap,Te.fog,Te.lights,{emissive:{value:new ue(0)}}]),vertexShader:mt.meshtoon_vert,fragmentShader:mt.meshtoon_frag},matcap:{uniforms:Nn([Te.common,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,{matcap:{value:null}}]),vertexShader:mt.meshmatcap_vert,fragmentShader:mt.meshmatcap_frag},points:{uniforms:Nn([Te.points,Te.fog]),vertexShader:mt.points_vert,fragmentShader:mt.points_frag},dashed:{uniforms:Nn([Te.common,Te.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:mt.linedashed_vert,fragmentShader:mt.linedashed_frag},depth:{uniforms:Nn([Te.common,Te.displacementmap]),vertexShader:mt.depth_vert,fragmentShader:mt.depth_frag},normal:{uniforms:Nn([Te.common,Te.bumpmap,Te.normalmap,Te.displacementmap,{opacity:{value:1}}]),vertexShader:mt.meshnormal_vert,fragmentShader:mt.meshnormal_frag},sprite:{uniforms:Nn([Te.sprite,Te.fog]),vertexShader:mt.sprite_vert,fragmentShader:mt.sprite_frag},background:{uniforms:{uvTransform:{value:new st},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:mt.background_vert,fragmentShader:mt.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new st}},vertexShader:mt.backgroundCube_vert,fragmentShader:mt.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:mt.cube_vert,fragmentShader:mt.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:mt.equirect_vert,fragmentShader:mt.equirect_frag},distanceRGBA:{uniforms:Nn([Te.common,Te.displacementmap,{referencePosition:{value:new S},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:mt.distanceRGBA_vert,fragmentShader:mt.distanceRGBA_frag},shadow:{uniforms:Nn([Te.lights,Te.fog,{color:{value:new ue(0)},opacity:{value:1}}]),vertexShader:mt.shadow_vert,fragmentShader:mt.shadow_frag}};Wi.physical={uniforms:Nn([Wi.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new st},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new st},clearcoatNormalScale:{value:new te(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new st},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new st},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new st},sheen:{value:0},sheenColor:{value:new ue(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new st},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new st},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new st},transmissionSamplerSize:{value:new te},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new st},attenuationDistance:{value:0},attenuationColor:{value:new ue(0)},specularColor:{value:new ue(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new st},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new st},anisotropyVector:{value:new te},anisotropyMap:{value:null},anisotropyMapTransform:{value:new st}}]),vertexShader:mt.meshphysical_vert,fragmentShader:mt.meshphysical_frag};const au={r:0,b:0,g:0},Ra=new an,ZL=new Me;function JL(n,e,t,i,s,a,r){const o=new ue(0);let l=a===!0?0:1,c,u,d=null,h=0,f=null;function p(y){let b=y.isScene===!0?y.background:null;return b&&b.isTexture&&(b=(y.backgroundBlurriness>0?t:e).get(b)),b}function g(y){let b=!1;const T=p(y);T===null?m(o,l):T&&T.isColor&&(m(T,1),b=!0);const x=n.xr.getEnvironmentBlendMode();x==="additive"?i.buffers.color.setClear(0,0,0,1,r):x==="alpha-blend"&&i.buffers.color.setClear(0,0,0,0,r),(n.autoClear||b)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),n.clear(n.autoClearColor,n.autoClearDepth,n.autoClearStencil))}function _(y,b){const T=p(b);T&&(T.isCubeTexture||T.mapping===Ao)?(u===void 0&&(u=new we(new Ei(1,1,1),new ti({name:"BackgroundCubeMaterial",uniforms:Mo(Wi.backgroundCube.uniforms),vertexShader:Wi.backgroundCube.vertexShader,fragmentShader:Wi.backgroundCube.fragmentShader,side:un,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(x,M,C){this.matrixWorld.copyPosition(C.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),s.update(u)),Ra.copy(b.backgroundRotation),Ra.x*=-1,Ra.y*=-1,Ra.z*=-1,T.isCubeTexture&&T.isRenderTargetTexture===!1&&(Ra.y*=-1,Ra.z*=-1),u.material.uniforms.envMap.value=T,u.material.uniforms.flipEnvMap.value=T.isCubeTexture&&T.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=b.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(ZL.makeRotationFromEuler(Ra)),u.material.toneMapped=at.getTransfer(T.colorSpace)!==Pt,(d!==T||h!==T.version||f!==n.toneMapping)&&(u.material.needsUpdate=!0,d=T,h=T.version,f=n.toneMapping),u.layers.enableAll(),y.unshift(u,u.geometry,u.material,0,0,null)):T&&T.isTexture&&(c===void 0&&(c=new we(new Dn(2,2),new ti({name:"BackgroundMaterial",uniforms:Mo(Wi.background.uniforms),vertexShader:Wi.background.vertexShader,fragmentShader:Wi.background.fragmentShader,side:fs,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),s.update(c)),c.material.uniforms.t2D.value=T,c.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,c.material.toneMapped=at.getTransfer(T.colorSpace)!==Pt,T.matrixAutoUpdate===!0&&T.updateMatrix(),c.material.uniforms.uvTransform.value.copy(T.matrix),(d!==T||h!==T.version||f!==n.toneMapping)&&(c.material.needsUpdate=!0,d=T,h=T.version,f=n.toneMapping),c.layers.enableAll(),y.unshift(c,c.geometry,c.material,0,0,null))}function m(y,b){y.getRGB(au,fS(n)),i.buffers.color.setClear(au.r,au.g,au.b,b,r)}function v(){u!==void 0&&(u.geometry.dispose(),u.material.dispose(),u=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return o},setClearColor:function(y,b=1){o.set(y),l=b,m(o,l)},getClearAlpha:function(){return l},setClearAlpha:function(y){l=y,m(o,l)},render:g,addToRenderList:_,dispose:v}}function QL(n,e){const t=n.getParameter(n.MAX_VERTEX_ATTRIBS),i={},s=h(null);let a=s,r=!1;function o(E,R,D,O,k){let U=!1;const F=d(O,D,R);a!==F&&(a=F,c(a.object)),U=f(E,O,D,k),U&&p(E,O,D,k),k!==null&&e.update(k,n.ELEMENT_ARRAY_BUFFER),(U||r)&&(r=!1,b(E,R,D,O),k!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e.get(k).buffer))}function l(){return n.createVertexArray()}function c(E){return n.bindVertexArray(E)}function u(E){return n.deleteVertexArray(E)}function d(E,R,D){const O=D.wireframe===!0;let k=i[E.id];k===void 0&&(k={},i[E.id]=k);let U=k[R.id];U===void 0&&(U={},k[R.id]=U);let F=U[O];return F===void 0&&(F=h(l()),U[O]=F),F}function h(E){const R=[],D=[],O=[];for(let k=0;k=0){const oe=k[H];let pe=U[H];if(pe===void 0&&(H==="instanceMatrix"&&E.instanceMatrix&&(pe=E.instanceMatrix),H==="instanceColor"&&E.instanceColor&&(pe=E.instanceColor)),oe===void 0||oe.attribute!==pe||pe&&oe.data!==pe.data)return!0;F++}return a.attributesNum!==F||a.index!==O}function p(E,R,D,O){const k={},U=R.attributes;let F=0;const W=D.getAttributes();for(const H in W)if(W[H].location>=0){let oe=U[H];oe===void 0&&(H==="instanceMatrix"&&E.instanceMatrix&&(oe=E.instanceMatrix),H==="instanceColor"&&E.instanceColor&&(oe=E.instanceColor));const pe={};pe.attribute=oe,oe&&oe.data&&(pe.data=oe.data),k[H]=pe,F++}a.attributes=k,a.attributesNum=F,a.index=O}function g(){const E=a.newAttributes;for(let R=0,D=E.length;R=0){let ne=k[W];if(ne===void 0&&(W==="instanceMatrix"&&E.instanceMatrix&&(ne=E.instanceMatrix),W==="instanceColor"&&E.instanceColor&&(ne=E.instanceColor)),ne!==void 0){const oe=ne.normalized,pe=ne.itemSize,Ie=e.get(ne);if(Ie===void 0)continue;const De=Ie.buffer,Xe=Ie.type,ke=Ie.bytesPerElement,Z=Xe===n.INT||Xe===n.UNSIGNED_INT||ne.gpuType===gh;if(ne.isInterleavedBufferAttribute){const se=ne.data,Se=se.stride,X=ne.offset;if(se.isInstancedInterleavedBuffer){for(let ie=0;ie0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision>0)return"highp";M="mediump"}return M==="mediump"&&n.getShaderPrecisionFormat(n.VERTEX_SHADER,n.MEDIUM_FLOAT).precision>0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=t.precision!==void 0?t.precision:"highp";const u=l(c);u!==c&&(console.warn("THREE.WebGLRenderer:",c,"not supported, using",u,"instead."),c=u);const d=t.logarithmicDepthBuffer===!0,h=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),f=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),p=n.getParameter(n.MAX_VERTEX_TEXTURE_IMAGE_UNITS),g=n.getParameter(n.MAX_TEXTURE_SIZE),_=n.getParameter(n.MAX_CUBE_MAP_TEXTURE_SIZE),m=n.getParameter(n.MAX_VERTEX_ATTRIBS),v=n.getParameter(n.MAX_VERTEX_UNIFORM_VECTORS),y=n.getParameter(n.MAX_VARYING_VECTORS),b=n.getParameter(n.MAX_FRAGMENT_UNIFORM_VECTORS),T=p>0,x=n.getParameter(n.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:l,textureFormatReadable:r,textureTypeReadable:o,precision:c,logarithmicDepthBuffer:d,reversedDepthBuffer:h,maxTextures:f,maxVertexTextures:p,maxTextureSize:g,maxCubemapSize:_,maxAttributes:m,maxVertexUniforms:v,maxVaryings:y,maxFragmentUniforms:b,vertexTextures:T,maxSamples:x}}function n2(n){const e=this;let t=null,i=0,s=!1,a=!1;const r=new Ps,o=new st,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(d,h){const f=d.length!==0||h||i!==0||s;return s=h,i=d.length,f},this.beginShadows=function(){a=!0,u(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(d,h){t=u(d,h,0)},this.setState=function(d,h,f){const p=d.clippingPlanes,g=d.clipIntersection,_=d.clipShadows,m=n.get(d);if(!s||p===null||p.length===0||a&&!_)a?u(null):c();else{const v=a?0:i,y=v*4;let b=m.clippingState||null;l.value=b,b=u(p,h,y,f);for(let T=0;T!==y;++T)b[T]=t[T];m.clippingState=b,this.numIntersection=g?this.numPlanes:0,this.numPlanes+=v}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function u(d,h,f,p){const g=d!==null?d.length:0;let _=null;if(g!==0){if(_=l.value,p!==!0||_===null){const m=f+g*4,v=h.matrixWorldInverse;o.getNormalMatrix(v),(_===null||_.length0){const c=new _S(l.height);return c.fromEquirectangularTexture(n,r),e.set(r,c),r.addEventListener("dispose",s),t(c.texture,r.mapping)}else return null}}return r}function s(r){const o=r.target;o.removeEventListener("dispose",s);const l=e.get(o);l!==void 0&&(e.delete(o),l.dispose())}function a(){e=new WeakMap}return{get:i,dispose:a}}const jr=4,y0=[.125,.215,.35,.446,.526,.582],Ha=20,Jf=new uc,v0=new ue;let Qf=null,ep=0,tp=0,np=!1;const Ba=(1+Math.sqrt(5))/2,Ur=1/Ba,b0=[new S(-Ba,Ur,0),new S(Ba,Ur,0),new S(-Ur,0,Ba),new S(Ur,0,Ba),new S(0,Ba,-Ur),new S(0,Ba,Ur),new S(-1,1,-1),new S(1,1,-1),new S(-1,1,1),new S(1,1,1)],s2=new S;class Jd{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,i=.1,s=100,a={}){const{size:r=256,position:o=s2}=a;Qf=this._renderer.getRenderTarget(),ep=this._renderer.getActiveCubeFace(),tp=this._renderer.getActiveMipmapLevel(),np=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(r);const l=this._allocateTargets();return l.depthBuffer=!0,this._sceneToCubeUV(e,i,s,l,o),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=S0(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=w0(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?T:0,T,T),d.setRenderTarget(s),m&&d.render(_,l),d.render(e,l)}_.geometry.dispose(),_.material.dispose(),d.toneMapping=f,d.autoClear=h,e.background=v}_textureToCubeUV(e,t){const i=this._renderer,s=e.mapping===Bs||e.mapping===oa;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=S0()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=w0());const a=s?this._cubemapMaterial:this._equirectMaterial,r=new we(this._lodPlanes[0],a),o=a.uniforms;o.envMap.value=e;const l=this._cubeSize;ru(t,0,0,3*l,2*l),i.setRenderTarget(t),i.render(r,Jf)}_applyPMREM(e){const t=this._renderer,i=t.autoClear;t.autoClear=!1;const s=this._lodPlanes.length;for(let a=1;aHa&&console.warn(`sigmaRadians, ${a}, is too large and will clip, as it requested ${_} samples when the maximum is set to ${Ha}`);const m=[];let v=0;for(let M=0;My-jr?s-y+jr:0),x=4*(this._cubeSize-b);ru(t,T,x,3*b,2*b),l.setRenderTarget(t),l.render(d,Jf)}}function a2(n){const e=[],t=[],i=[];let s=n;const a=n-jr+1+y0.length;for(let r=0;rn-jr?l=y0[r-n+jr-1]:r===0&&(l=0),i.push(l);const c=1/(o-2),u=-c,d=1+c,h=[u,u,d,u,d,d,u,u,d,d,u,d],f=6,p=6,g=3,_=2,m=1,v=new Float32Array(g*p*f),y=new Float32Array(_*p*f),b=new Float32Array(m*p*f);for(let x=0;x2?0:-1,w=[M,C,0,M+2/3,C,0,M+2/3,C+1,0,M,C,0,M+2/3,C+1,0,M,C+1,0];v.set(w,g*p*x),y.set(h,_*p*x);const E=[x,x,x,x,x,x];b.set(E,m*p*x)}const T=new Ge;T.setAttribute("position",new rt(v,g)),T.setAttribute("uv",new rt(y,_)),T.setAttribute("faceIndex",new rt(b,m)),e.push(T),s>jr&&s--}return{lodPlanes:e,sizeLods:t,sigmas:i}}function x0(n,e,t){const i=new ms(n,e,t);return i.texture.mapping=Ao,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function ru(n,e,t,i,s){n.viewport.set(e,t,i,s),n.scissor.set(e,t,i,s)}function r2(n,e,t){const i=new Float32Array(Ha),s=new S(0,1,0);return new ti({name:"SphericalGaussianBlur",defines:{n:Ha,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:s}},vertexShader:Mg(),fragmentShader:` +}`,mt={alphahash_fragment:RP,alphahash_pars_fragment:PP,alphamap_fragment:IP,alphamap_pars_fragment:LP,alphatest_fragment:kP,alphatest_pars_fragment:DP,aomap_fragment:OP,aomap_pars_fragment:FP,batching_pars_vertex:NP,batching_vertex:UP,begin_vertex:BP,beginnormal_vertex:zP,bsdfs:HP,iridescence_fragment:VP,bumpmap_pars_fragment:GP,clipping_planes_fragment:$P,clipping_planes_pars_fragment:WP,clipping_planes_pars_vertex:XP,clipping_planes_vertex:KP,color_fragment:qP,color_pars_fragment:YP,color_pars_vertex:jP,color_vertex:ZP,common:JP,cube_uv_reflection_fragment:QP,defaultnormal_vertex:eI,displacementmap_pars_vertex:tI,displacementmap_vertex:nI,emissivemap_fragment:iI,emissivemap_pars_fragment:sI,colorspace_fragment:aI,colorspace_pars_fragment:rI,envmap_fragment:oI,envmap_common_pars_fragment:lI,envmap_pars_fragment:cI,envmap_pars_vertex:uI,envmap_physical_pars_fragment:xI,envmap_vertex:dI,fog_vertex:hI,fog_pars_vertex:fI,fog_fragment:pI,fog_pars_fragment:mI,gradientmap_pars_fragment:_I,lightmap_pars_fragment:gI,lights_lambert_fragment:yI,lights_lambert_pars_fragment:vI,lights_pars_begin:bI,lights_toon_fragment:wI,lights_toon_pars_fragment:SI,lights_phong_fragment:TI,lights_phong_pars_fragment:MI,lights_physical_fragment:EI,lights_physical_pars_fragment:CI,lights_fragment_begin:AI,lights_fragment_maps:RI,lights_fragment_end:PI,logdepthbuf_fragment:II,logdepthbuf_pars_fragment:LI,logdepthbuf_pars_vertex:kI,logdepthbuf_vertex:DI,map_fragment:OI,map_pars_fragment:FI,map_particle_fragment:NI,map_particle_pars_fragment:UI,metalnessmap_fragment:BI,metalnessmap_pars_fragment:zI,morphinstance_vertex:HI,morphcolor_vertex:VI,morphnormal_vertex:GI,morphtarget_pars_vertex:$I,morphtarget_vertex:WI,normal_fragment_begin:XI,normal_fragment_maps:KI,normal_pars_fragment:qI,normal_pars_vertex:YI,normal_vertex:jI,normalmap_pars_fragment:ZI,clearcoat_normal_fragment_begin:JI,clearcoat_normal_fragment_maps:QI,clearcoat_pars_fragment:eL,iridescence_pars_fragment:tL,opaque_fragment:nL,packing:iL,premultiplied_alpha_fragment:sL,project_vertex:aL,dithering_fragment:rL,dithering_pars_fragment:oL,roughnessmap_fragment:lL,roughnessmap_pars_fragment:cL,shadowmap_pars_fragment:uL,shadowmap_pars_vertex:dL,shadowmap_vertex:hL,shadowmask_pars_fragment:fL,skinbase_vertex:pL,skinning_pars_vertex:mL,skinning_vertex:_L,skinnormal_vertex:gL,specularmap_fragment:yL,specularmap_pars_fragment:vL,tonemapping_fragment:bL,tonemapping_pars_fragment:xL,transmission_fragment:wL,transmission_pars_fragment:SL,uv_pars_fragment:TL,uv_pars_vertex:ML,uv_vertex:EL,worldpos_vertex:CL,background_vert:AL,background_frag:RL,backgroundCube_vert:PL,backgroundCube_frag:IL,cube_vert:LL,cube_frag:kL,depth_vert:DL,depth_frag:OL,distanceRGBA_vert:FL,distanceRGBA_frag:NL,equirect_vert:UL,equirect_frag:BL,linedashed_vert:zL,linedashed_frag:HL,meshbasic_vert:VL,meshbasic_frag:GL,meshlambert_vert:$L,meshlambert_frag:WL,meshmatcap_vert:XL,meshmatcap_frag:KL,meshnormal_vert:qL,meshnormal_frag:YL,meshphong_vert:jL,meshphong_frag:ZL,meshphysical_vert:JL,meshphysical_frag:QL,meshtoon_vert:e2,meshtoon_frag:t2,points_vert:n2,points_frag:i2,shadow_vert:s2,shadow_frag:a2,sprite_vert:r2,sprite_frag:o2},Te={common:{diffuse:{value:new ue(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new at},alphaMap:{value:null},alphaMapTransform:{value:new at},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new at}},envmap:{envMap:{value:null},envMapRotation:{value:new at},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new at}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new at}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new at},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new at},normalScale:{value:new te(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new at},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new at}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new at}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new at}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new ue(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new ue(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new at},alphaTest:{value:0},uvTransform:{value:new at}},sprite:{diffuse:{value:new ue(16777215)},opacity:{value:1},center:{value:new te(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new at},alphaMap:{value:null},alphaMapTransform:{value:new at},alphaTest:{value:0}}},Xi={basic:{uniforms:Nn([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.fog]),vertexShader:mt.meshbasic_vert,fragmentShader:mt.meshbasic_frag},lambert:{uniforms:Nn([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,Te.lights,{emissive:{value:new ue(0)}}]),vertexShader:mt.meshlambert_vert,fragmentShader:mt.meshlambert_frag},phong:{uniforms:Nn([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,Te.lights,{emissive:{value:new ue(0)},specular:{value:new ue(1118481)},shininess:{value:30}}]),vertexShader:mt.meshphong_vert,fragmentShader:mt.meshphong_frag},standard:{uniforms:Nn([Te.common,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.roughnessmap,Te.metalnessmap,Te.fog,Te.lights,{emissive:{value:new ue(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:mt.meshphysical_vert,fragmentShader:mt.meshphysical_frag},toon:{uniforms:Nn([Te.common,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.gradientmap,Te.fog,Te.lights,{emissive:{value:new ue(0)}}]),vertexShader:mt.meshtoon_vert,fragmentShader:mt.meshtoon_frag},matcap:{uniforms:Nn([Te.common,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,{matcap:{value:null}}]),vertexShader:mt.meshmatcap_vert,fragmentShader:mt.meshmatcap_frag},points:{uniforms:Nn([Te.points,Te.fog]),vertexShader:mt.points_vert,fragmentShader:mt.points_frag},dashed:{uniforms:Nn([Te.common,Te.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:mt.linedashed_vert,fragmentShader:mt.linedashed_frag},depth:{uniforms:Nn([Te.common,Te.displacementmap]),vertexShader:mt.depth_vert,fragmentShader:mt.depth_frag},normal:{uniforms:Nn([Te.common,Te.bumpmap,Te.normalmap,Te.displacementmap,{opacity:{value:1}}]),vertexShader:mt.meshnormal_vert,fragmentShader:mt.meshnormal_frag},sprite:{uniforms:Nn([Te.sprite,Te.fog]),vertexShader:mt.sprite_vert,fragmentShader:mt.sprite_frag},background:{uniforms:{uvTransform:{value:new at},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:mt.background_vert,fragmentShader:mt.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new at}},vertexShader:mt.backgroundCube_vert,fragmentShader:mt.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:mt.cube_vert,fragmentShader:mt.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:mt.equirect_vert,fragmentShader:mt.equirect_frag},distanceRGBA:{uniforms:Nn([Te.common,Te.displacementmap,{referencePosition:{value:new S},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:mt.distanceRGBA_vert,fragmentShader:mt.distanceRGBA_frag},shadow:{uniforms:Nn([Te.lights,Te.fog,{color:{value:new ue(0)},opacity:{value:1}}]),vertexShader:mt.shadow_vert,fragmentShader:mt.shadow_frag}};Xi.physical={uniforms:Nn([Xi.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new at},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new at},clearcoatNormalScale:{value:new te(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new at},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new at},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new at},sheen:{value:0},sheenColor:{value:new ue(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new at},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new at},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new at},transmissionSamplerSize:{value:new te},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new at},attenuationDistance:{value:0},attenuationColor:{value:new ue(0)},specularColor:{value:new ue(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new at},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new at},anisotropyVector:{value:new te},anisotropyMap:{value:null},anisotropyMapTransform:{value:new at}}]),vertexShader:mt.meshphysical_vert,fragmentShader:mt.meshphysical_frag};const cu={r:0,b:0,g:0},Pa=new an,l2=new Me;function c2(n,e,t,i,s,a,r){const o=new ue(0);let l=a===!0?0:1,c,u,d=null,h=0,f=null;function p(y){let b=y.isScene===!0?y.background:null;return b&&b.isTexture&&(b=(y.backgroundBlurriness>0?t:e).get(b)),b}function g(y){let b=!1;const T=p(y);T===null?m(o,l):T&&T.isColor&&(m(T,1),b=!0);const x=n.xr.getEnvironmentBlendMode();x==="additive"?i.buffers.color.setClear(0,0,0,1,r):x==="alpha-blend"&&i.buffers.color.setClear(0,0,0,0,r),(n.autoClear||b)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),n.clear(n.autoClearColor,n.autoClearDepth,n.autoClearStencil))}function _(y,b){const T=p(b);T&&(T.isCubeTexture||T.mapping===Io)?(u===void 0&&(u=new we(new Ci(1,1,1),new ti({name:"BackgroundCubeMaterial",uniforms:Ao(Xi.backgroundCube.uniforms),vertexShader:Xi.backgroundCube.vertexShader,fragmentShader:Xi.backgroundCube.fragmentShader,side:un,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(x,M,C){this.matrixWorld.copyPosition(C.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),s.update(u)),Pa.copy(b.backgroundRotation),Pa.x*=-1,Pa.y*=-1,Pa.z*=-1,T.isCubeTexture&&T.isRenderTargetTexture===!1&&(Pa.y*=-1,Pa.z*=-1),u.material.uniforms.envMap.value=T,u.material.uniforms.flipEnvMap.value=T.isCubeTexture&&T.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=b.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(l2.makeRotationFromEuler(Pa)),u.material.toneMapped=rt.getTransfer(T.colorSpace)!==Pt,(d!==T||h!==T.version||f!==n.toneMapping)&&(u.material.needsUpdate=!0,d=T,h=T.version,f=n.toneMapping),u.layers.enableAll(),y.unshift(u,u.geometry,u.material,0,0,null)):T&&T.isTexture&&(c===void 0&&(c=new we(new kn(2,2),new ti({name:"BackgroundMaterial",uniforms:Ao(Xi.background.uniforms),vertexShader:Xi.background.vertexShader,fragmentShader:Xi.background.fragmentShader,side:fs,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),s.update(c)),c.material.uniforms.t2D.value=T,c.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,c.material.toneMapped=rt.getTransfer(T.colorSpace)!==Pt,T.matrixAutoUpdate===!0&&T.updateMatrix(),c.material.uniforms.uvTransform.value.copy(T.matrix),(d!==T||h!==T.version||f!==n.toneMapping)&&(c.material.needsUpdate=!0,d=T,h=T.version,f=n.toneMapping),c.layers.enableAll(),y.unshift(c,c.geometry,c.material,0,0,null))}function m(y,b){y.getRGB(cu,xS(n)),i.buffers.color.setClear(cu.r,cu.g,cu.b,b,r)}function v(){u!==void 0&&(u.geometry.dispose(),u.material.dispose(),u=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return o},setClearColor:function(y,b=1){o.set(y),l=b,m(o,l)},getClearAlpha:function(){return l},setClearAlpha:function(y){l=y,m(o,l)},render:g,addToRenderList:_,dispose:v}}function u2(n,e){const t=n.getParameter(n.MAX_VERTEX_ATTRIBS),i={},s=h(null);let a=s,r=!1;function o(E,R,k,O,D){let U=!1;const F=d(O,k,R);a!==F&&(a=F,c(a.object)),U=f(E,O,k,D),U&&p(E,O,k,D),D!==null&&e.update(D,n.ELEMENT_ARRAY_BUFFER),(U||r)&&(r=!1,b(E,R,k,O),D!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e.get(D).buffer))}function l(){return n.createVertexArray()}function c(E){return n.bindVertexArray(E)}function u(E){return n.deleteVertexArray(E)}function d(E,R,k){const O=k.wireframe===!0;let D=i[E.id];D===void 0&&(D={},i[E.id]=D);let U=D[R.id];U===void 0&&(U={},D[R.id]=U);let F=U[O];return F===void 0&&(F=h(l()),U[O]=F),F}function h(E){const R=[],k=[],O=[];for(let D=0;D=0){const oe=D[H];let pe=U[H];if(pe===void 0&&(H==="instanceMatrix"&&E.instanceMatrix&&(pe=E.instanceMatrix),H==="instanceColor"&&E.instanceColor&&(pe=E.instanceColor)),oe===void 0||oe.attribute!==pe||pe&&oe.data!==pe.data)return!0;F++}return a.attributesNum!==F||a.index!==O}function p(E,R,k,O){const D={},U=R.attributes;let F=0;const W=k.getAttributes();for(const H in W)if(W[H].location>=0){let oe=U[H];oe===void 0&&(H==="instanceMatrix"&&E.instanceMatrix&&(oe=E.instanceMatrix),H==="instanceColor"&&E.instanceColor&&(oe=E.instanceColor));const pe={};pe.attribute=oe,oe&&oe.data&&(pe.data=oe.data),D[H]=pe,F++}a.attributes=D,a.attributesNum=F,a.index=O}function g(){const E=a.newAttributes;for(let R=0,k=E.length;R=0){let ne=D[W];if(ne===void 0&&(W==="instanceMatrix"&&E.instanceMatrix&&(ne=E.instanceMatrix),W==="instanceColor"&&E.instanceColor&&(ne=E.instanceColor)),ne!==void 0){const oe=ne.normalized,pe=ne.itemSize,Ie=e.get(ne);if(Ie===void 0)continue;const ke=Ie.buffer,Xe=Ie.type,De=Ie.bytesPerElement,Z=Xe===n.INT||Xe===n.UNSIGNED_INT||ne.gpuType===Sh;if(ne.isInterleavedBufferAttribute){const ae=ne.data,Se=ae.stride,X=ne.offset;if(ae.isInstancedInterleavedBuffer){for(let ie=0;ie0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision>0)return"highp";M="mediump"}return M==="mediump"&&n.getShaderPrecisionFormat(n.VERTEX_SHADER,n.MEDIUM_FLOAT).precision>0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=t.precision!==void 0?t.precision:"highp";const u=l(c);u!==c&&(console.warn("THREE.WebGLRenderer:",c,"not supported, using",u,"instead."),c=u);const d=t.logarithmicDepthBuffer===!0,h=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),f=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),p=n.getParameter(n.MAX_VERTEX_TEXTURE_IMAGE_UNITS),g=n.getParameter(n.MAX_TEXTURE_SIZE),_=n.getParameter(n.MAX_CUBE_MAP_TEXTURE_SIZE),m=n.getParameter(n.MAX_VERTEX_ATTRIBS),v=n.getParameter(n.MAX_VERTEX_UNIFORM_VECTORS),y=n.getParameter(n.MAX_VARYING_VECTORS),b=n.getParameter(n.MAX_FRAGMENT_UNIFORM_VECTORS),T=p>0,x=n.getParameter(n.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:l,textureFormatReadable:r,textureTypeReadable:o,precision:c,logarithmicDepthBuffer:d,reversedDepthBuffer:h,maxTextures:f,maxVertexTextures:p,maxTextureSize:g,maxCubemapSize:_,maxAttributes:m,maxVertexUniforms:v,maxVaryings:y,maxFragmentUniforms:b,vertexTextures:T,maxSamples:x}}function f2(n){const e=this;let t=null,i=0,s=!1,a=!1;const r=new Ps,o=new at,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(d,h){const f=d.length!==0||h||i!==0||s;return s=h,i=d.length,f},this.beginShadows=function(){a=!0,u(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(d,h){t=u(d,h,0)},this.setState=function(d,h,f){const p=d.clippingPlanes,g=d.clipIntersection,_=d.clipShadows,m=n.get(d);if(!s||p===null||p.length===0||a&&!_)a?u(null):c();else{const v=a?0:i,y=v*4;let b=m.clippingState||null;l.value=b,b=u(p,h,y,f);for(let T=0;T!==y;++T)b[T]=t[T];m.clippingState=b,this.numIntersection=g?this.numPlanes:0,this.numPlanes+=v}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function u(d,h,f,p){const g=d!==null?d.length:0;let _=null;if(g!==0){if(_=l.value,p!==!0||_===null){const m=f+g*4,v=h.matrixWorldInverse;o.getNormalMatrix(v),(_===null||_.length0){const c=new TS(l.height);return c.fromEquirectangularTexture(n,r),e.set(r,c),r.addEventListener("dispose",s),t(c.texture,r.mapping)}else return null}}return r}function s(r){const o=r.target;o.removeEventListener("dispose",s);const l=e.get(o);l!==void 0&&(e.delete(o),l.dispose())}function a(){e=new WeakMap}return{get:i,dispose:a}}const Jr=4,M0=[.125,.215,.35,.446,.526,.582],Va=20,sp=new pc,E0=new ue;let ap=null,rp=0,op=0,lp=!1;const za=(1+Math.sqrt(5))/2,Br=1/za,C0=[new S(-za,Br,0),new S(za,Br,0),new S(-Br,0,za),new S(Br,0,za),new S(0,za,-Br),new S(0,za,Br),new S(-1,1,-1),new S(1,1,-1),new S(-1,1,1),new S(1,1,1)],m2=new S;class sh{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,i=.1,s=100,a={}){const{size:r=256,position:o=m2}=a;ap=this._renderer.getRenderTarget(),rp=this._renderer.getActiveCubeFace(),op=this._renderer.getActiveMipmapLevel(),lp=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(r);const l=this._allocateTargets();return l.depthBuffer=!0,this._sceneToCubeUV(e,i,s,l,o),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=P0(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=R0(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?T:0,T,T),d.setRenderTarget(s),m&&d.render(_,l),d.render(e,l)}_.geometry.dispose(),_.material.dispose(),d.toneMapping=f,d.autoClear=h,e.background=v}_textureToCubeUV(e,t){const i=this._renderer,s=e.mapping===Bs||e.mapping===la;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=P0()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=R0());const a=s?this._cubemapMaterial:this._equirectMaterial,r=new we(this._lodPlanes[0],a),o=a.uniforms;o.envMap.value=e;const l=this._cubeSize;uu(t,0,0,3*l,2*l),i.setRenderTarget(t),i.render(r,sp)}_applyPMREM(e){const t=this._renderer,i=t.autoClear;t.autoClear=!1;const s=this._lodPlanes.length;for(let a=1;aVa&&console.warn(`sigmaRadians, ${a}, is too large and will clip, as it requested ${_} samples when the maximum is set to ${Va}`);const m=[];let v=0;for(let M=0;My-Jr?s-y+Jr:0),x=4*(this._cubeSize-b);uu(t,T,x,3*b,2*b),l.setRenderTarget(t),l.render(d,sp)}}function _2(n){const e=[],t=[],i=[];let s=n;const a=n-Jr+1+M0.length;for(let r=0;rn-Jr?l=M0[r-n+Jr-1]:r===0&&(l=0),i.push(l);const c=1/(o-2),u=-c,d=1+c,h=[u,u,d,u,d,d,u,u,d,d,u,d],f=6,p=6,g=3,_=2,m=1,v=new Float32Array(g*p*f),y=new Float32Array(_*p*f),b=new Float32Array(m*p*f);for(let x=0;x2?0:-1,w=[M,C,0,M+2/3,C,0,M+2/3,C+1,0,M,C,0,M+2/3,C+1,0,M,C+1,0];v.set(w,g*p*x),y.set(h,_*p*x);const E=[x,x,x,x,x,x];b.set(E,m*p*x)}const T=new Ge;T.setAttribute("position",new ot(v,g)),T.setAttribute("uv",new ot(y,_)),T.setAttribute("faceIndex",new ot(b,m)),e.push(T),s>Jr&&s--}return{lodPlanes:e,sizeLods:t,sigmas:i}}function A0(n,e,t){const i=new ms(n,e,t);return i.texture.mapping=Io,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function uu(n,e,t,i,s){n.viewport.set(e,t,i,s),n.scissor.set(e,t,i,s)}function g2(n,e,t){const i=new Float32Array(Va),s=new S(0,1,0);return new ti({name:"SphericalGaussianBlur",defines:{n:Va,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:s}},vertexShader:Lg(),fragmentShader:` precision mediump float; precision mediump int; @@ -3636,7 +3636,7 @@ void main() { } } - `,blending:ks,depthTest:!1,depthWrite:!1})}function w0(){return new ti({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Mg(),fragmentShader:` + `,blending:Ds,depthTest:!1,depthWrite:!1})}function R0(){return new ti({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Lg(),fragmentShader:` precision mediump float; precision mediump int; @@ -3655,7 +3655,7 @@ void main() { gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); } - `,blending:ks,depthTest:!1,depthWrite:!1})}function S0(){return new ti({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Mg(),fragmentShader:` + `,blending:Ds,depthTest:!1,depthWrite:!1})}function P0(){return new ti({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Lg(),fragmentShader:` precision mediump float; precision mediump int; @@ -3671,7 +3671,7 @@ void main() { gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); } - `,blending:ks,depthTest:!1,depthWrite:!1})}function Mg(){return` + `,blending:Ds,depthTest:!1,depthWrite:!1})}function Lg(){return` precision mediump float; precision mediump int; @@ -3726,17 +3726,17 @@ void main() { gl_Position = vec4( position, 1.0 ); } - `}function o2(n){let e=new WeakMap,t=null;function i(o){if(o&&o.isTexture){const l=o.mapping,c=l===ar||l===Nl,u=l===Bs||l===oa;if(c||u){let d=e.get(o);const h=d!==void 0?d.texture.pmremVersion:0;if(o.isRenderTargetTexture&&o.pmremVersion!==h)return t===null&&(t=new Jd(n)),d=c?t.fromEquirectangular(o,d):t.fromCubemap(o,d),d.texture.pmremVersion=o.pmremVersion,e.set(o,d),d.texture;if(d!==void 0)return d.texture;{const f=o.image;return c&&f&&f.height>0||u&&f&&s(f)?(t===null&&(t=new Jd(n)),d=c?t.fromEquirectangular(o):t.fromCubemap(o),d.texture.pmremVersion=o.pmremVersion,e.set(o,d),o.addEventListener("dispose",a),d.texture):null}}}return o}function s(o){let l=0;const c=6;for(let u=0;ue.maxTextureSize&&(T=Math.ceil(b/e.maxTextureSize),b=e.maxTextureSize);const x=new Float32Array(b*T*4*d),M=new Th(x,b,T,d);M.type=Sn,M.needsUpdate=!0;const C=y*4;for(let E=0;E0)return n;const s=e*t;let a=M0[s];if(a===void 0&&(a=new Float32Array(s),M0[s]=a),e!==0){i.toArray(a,0);for(let r=1,o=0;r!==e;++r)o+=t,n[r].toArray(a,o)}return a}function hn(n,e){if(n.length!==e.length)return!1;for(let t=0,i=n.length;t0||u&&f&&s(f)?(t===null&&(t=new sh(n)),d=c?t.fromEquirectangular(o):t.fromCubemap(o),d.texture.pmremVersion=o.pmremVersion,e.set(o,d),o.addEventListener("dispose",a),d.texture):null}}}return o}function s(o){let l=0;const c=6;for(let u=0;ue.maxTextureSize&&(T=Math.ceil(b/e.maxTextureSize),b=e.maxTextureSize);const x=new Float32Array(b*T*4*d),M=new Ph(x,b,T,d);M.type=Sn,M.needsUpdate=!0;const C=y*4;for(let E=0;E0)return n;const s=e*t;let a=L0[s];if(a===void 0&&(a=new Float32Array(s),L0[s]=a),e!==0){i.toArray(a,0);for(let r=1,o=0;r!==e;++r)o+=t,n[r].toArray(a,o)}return a}function hn(n,e){if(n.length!==e.length)return!1;for(let t=0,i=n.length;t":" "} ${o}: ${t[r]}`)}return i.join(` -`)}const L0=new st;function oD(n){at._getMatrix(L0,at.workingColorSpace,n);const e=`mat3( ${L0.elements.map(t=>t.toFixed(4))} )`;switch(at.getTransfer(n)){case Bl:return[e,"LinearTransferOETF"];case Pt:return[e,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",n),[e,"LinearTransferOETF"]}}function D0(n,e,t){const i=n.getShaderParameter(e,n.COMPILE_STATUS),a=(n.getShaderInfoLog(e)||"").trim();if(i&&a==="")return"";const r=/ERROR: 0:(\d+)/.exec(a);if(r){const o=parseInt(r[1]);return t.toUpperCase()+` +`)}const B0=new at;function yk(n){rt._getMatrix(B0,rt.workingColorSpace,n);const e=`mat3( ${B0.elements.map(t=>t.toFixed(4))} )`;switch(rt.getTransfer(n)){case Gl:return[e,"LinearTransferOETF"];case Pt:return[e,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",n),[e,"LinearTransferOETF"]}}function z0(n,e,t){const i=n.getShaderParameter(e,n.COMPILE_STATUS),a=(n.getShaderInfoLog(e)||"").trim();if(i&&a==="")return"";const r=/ERROR: 0:(\d+)/.exec(a);if(r){const o=parseInt(r[1]);return t.toUpperCase()+` `+a+` -`+rD(n.getShaderSource(e),o)}else return a}function lD(n,e){const t=oD(e);return[`vec4 ${n}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(` -`)}function cD(n,e){let t;switch(e){case Gw:t="Linear";break;case $w:t="Reinhard";break;case Ww:t="Cineon";break;case z_:t="ACESFilmic";break;case Kw:t="AgX";break;case qw:t="Neutral";break;case Xw:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+n+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const ou=new S;function uD(){at.getLuminanceCoefficients(ou);const n=ou.x.toFixed(4),e=ou.y.toFixed(4),t=ou.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${n}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(` -`)}function dD(n){return[n.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",n.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(fl).join(` -`)}function hD(n){const e=[];for(const t in n){const i=n[t];i!==!1&&e.push("#define "+t+" "+i)}return e.join(` -`)}function fD(n,e){const t={},i=n.getProgramParameter(e,n.ACTIVE_ATTRIBUTES);for(let s=0;s/gm;function Pm(n){return n.replace(pD,_D)}const mD=new Map;function _D(n,e){let t=mt[e];if(t===void 0){const i=mD.get(e);if(i!==void 0)t=mt[i],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,i);else throw new Error("Can not resolve #include <"+e+">")}return Pm(t)}const gD=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function F0(n){return n.replace(gD,yD)}function yD(n,e,t,i){let s="";for(let a=parseInt(e);a/gm;function Nm(n){return n.replace(Mk,Ck)}const Ek=new Map;function Ck(n,e){let t=mt[e];if(t===void 0){const i=Ek.get(e);if(i!==void 0)t=mt[i],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,i);else throw new Error("Can not resolve #include <"+e+">")}return Nm(t)}const Ak=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function G0(n){return n.replace(Ak,Rk)}function Rk(n,e,t,i){let s="";for(let a=parseInt(e);a0&&(_+=` -`),m=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p].filter(fl).join(` +`),m=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p].filter(_l).join(` `),m.length>0&&(m+=` -`)):(_=[N0(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+u:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` -`].filter(fl).join(` -`),m=[N0(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+u:"",t.envMap?"#define "+d:"",h?"#define CUBEUV_TEXEL_WIDTH "+h.texelWidth:"",h?"#define CUBEUV_TEXEL_HEIGHT "+h.texelHeight:"",h?"#define CUBEUV_MAX_MIP "+h.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==Os?"#define TONE_MAPPING":"",t.toneMapping!==Os?mt.tonemapping_pars_fragment:"",t.toneMapping!==Os?cD("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",mt.colorspace_pars_fragment,lD("linearToOutputTexel",t.outputColorSpace),uD(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` -`].filter(fl).join(` -`)),r=Pm(r),r=k0(r,t),r=O0(r,t),o=Pm(o),o=k0(o,t),o=O0(o,t),r=F0(r),o=F0(o),t.isRawShaderMaterial!==!0&&(v=`#version 300 es +`)):(_=[$0(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+u:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` +`].filter(_l).join(` +`),m=[$0(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+u:"",t.envMap?"#define "+d:"",h?"#define CUBEUV_TEXEL_WIDTH "+h.texelWidth:"",h?"#define CUBEUV_TEXEL_HEIGHT "+h.texelHeight:"",h?"#define CUBEUV_MAX_MIP "+h.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==Os?"#define TONE_MAPPING":"",t.toneMapping!==Os?mt.tonemapping_pars_fragment:"",t.toneMapping!==Os?bk("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",mt.colorspace_pars_fragment,vk("linearToOutputTexel",t.outputColorSpace),xk(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` +`].filter(_l).join(` +`)),r=Nm(r),r=H0(r,t),r=V0(r,t),o=Nm(o),o=H0(o,t),o=V0(o,t),r=G0(r),o=G0(o),t.isRawShaderMaterial!==!0&&(v=`#version 300 es `,_=[f,"#define attribute in","#define varying out","#define texture2D texture"].join(` `)+` -`+_,m=["#define varying in",t.glslVersion===wm?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===wm?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` +`+_,m=["#define varying in",t.glslVersion===Rm?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===Rm?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` `)+` -`+m);const y=v+_+r,b=v+m+o,T=I0(s,s.VERTEX_SHADER,y),x=I0(s,s.FRAGMENT_SHADER,b);s.attachShader(g,T),s.attachShader(g,x),t.index0AttributeName!==void 0?s.bindAttribLocation(g,0,t.index0AttributeName):t.morphTargets===!0&&s.bindAttribLocation(g,0,"position"),s.linkProgram(g);function M(R){if(n.debug.checkShaderErrors){const D=s.getProgramInfoLog(g)||"",O=s.getShaderInfoLog(T)||"",k=s.getShaderInfoLog(x)||"",U=D.trim(),F=O.trim(),W=k.trim();let H=!0,ne=!0;if(s.getProgramParameter(g,s.LINK_STATUS)===!1)if(H=!1,typeof n.debug.onShaderError=="function")n.debug.onShaderError(s,g,T,x);else{const oe=D0(s,T,"vertex"),pe=D0(s,x,"fragment");console.error("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(g,s.VALIDATE_STATUS)+` +`+m);const y=v+_+r,b=v+m+o,T=U0(s,s.VERTEX_SHADER,y),x=U0(s,s.FRAGMENT_SHADER,b);s.attachShader(g,T),s.attachShader(g,x),t.index0AttributeName!==void 0?s.bindAttribLocation(g,0,t.index0AttributeName):t.morphTargets===!0&&s.bindAttribLocation(g,0,"position"),s.linkProgram(g);function M(R){if(n.debug.checkShaderErrors){const k=s.getProgramInfoLog(g)||"",O=s.getShaderInfoLog(T)||"",D=s.getShaderInfoLog(x)||"",U=k.trim(),F=O.trim(),W=D.trim();let H=!0,ne=!0;if(s.getProgramParameter(g,s.LINK_STATUS)===!1)if(H=!1,typeof n.debug.onShaderError=="function")n.debug.onShaderError(s,g,T,x);else{const oe=z0(s,T,"vertex"),pe=z0(s,x,"fragment");console.error("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(g,s.VALIDATE_STATUS)+` Material Name: `+R.name+` Material Type: `+R.type+` Program Info Log: `+U+` `+oe+` -`+pe)}else U!==""?console.warn("THREE.WebGLProgram: Program Info Log:",U):(F===""||W==="")&&(ne=!1);ne&&(R.diagnostics={runnable:H,programLog:U,vertexShader:{log:F,prefix:_},fragmentShader:{log:W,prefix:m}})}s.deleteShader(T),s.deleteShader(x),C=new $u(s,g),w=fD(s,g)}let C;this.getUniforms=function(){return C===void 0&&M(this),C};let w;this.getAttributes=function(){return w===void 0&&M(this),w};let E=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=s.getProgramParameter(g,sD)),E},this.destroy=function(){i.releaseStatesOfProgram(this),s.deleteProgram(g),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=aD++,this.cacheKey=e,this.usedTimes=1,this.program=g,this.vertexShader=T,this.fragmentShader=x,this}let MD=0;class ED{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,i=e.fragmentShader,s=this._getShaderStage(t),a=this._getShaderStage(i),r=this._getShaderCacheForMaterial(e);return r.has(s)===!1&&(r.add(s),s.usedTimes++),r.has(a)===!1&&(r.add(a),a.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return i===void 0&&(i=new CD(e),t.set(e,i)),i}}class CD{constructor(e){this.id=MD++,this.code=e,this.usedTimes=0}}function AD(n,e,t,i,s,a,r){const o=new Eh,l=new ED,c=new Set,u=[],d=s.logarithmicDepthBuffer,h=s.vertexTextures;let f=s.precision;const p={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function g(w){return c.add(w),w===0?"uv":`uv${w}`}function _(w,E,R,D,O){const k=D.fog,U=O.geometry,F=w.isMeshStandardMaterial?D.environment:null,W=(w.isMeshStandardMaterial?t:e).get(w.envMap||F),H=W&&W.mapping===Ao?W.image.height:null,ne=p[w.type];w.precision!==null&&(f=s.getMaxPrecision(w.precision),f!==w.precision&&console.warn("THREE.WebGLProgram.getParameters:",w.precision,"not supported, using",f,"instead."));const oe=U.morphAttributes.position||U.morphAttributes.normal||U.morphAttributes.color,pe=oe!==void 0?oe.length:0;let Ie=0;U.morphAttributes.position!==void 0&&(Ie=1),U.morphAttributes.normal!==void 0&&(Ie=2),U.morphAttributes.color!==void 0&&(Ie=3);let De,Xe,ke,Z;if(ne){const Et=Wi[ne];De=Et.vertexShader,Xe=Et.fragmentShader}else De=w.vertexShader,Xe=w.fragmentShader,l.update(w),ke=l.getVertexShaderID(w),Z=l.getFragmentShaderID(w);const se=n.getRenderTarget(),Se=n.state.buffers.depth.getReversed(),X=O.isInstancedMesh===!0,ie=O.isBatchedMesh===!0,xe=!!w.map,Ae=!!w.matcap,L=!!W,G=!!w.aoMap,j=!!w.lightMap,Y=!!w.bumpMap,Q=!!w.normalMap,_e=!!w.displacementMap,ce=!!w.emissiveMap,ge=!!w.metalnessMap,$e=!!w.roughnessMap,it=w.anisotropy>0,I=w.clearcoat>0,A=w.dispersion>0,V=w.iridescence>0,J=w.sheen>0,le=w.transmission>0,ee=it&&!!w.anisotropyMap,He=I&&!!w.clearcoatMap,ye=I&&!!w.clearcoatNormalMap,Ue=I&&!!w.clearcoatRoughnessMap,Be=V&&!!w.iridescenceMap,de=V&&!!w.iridescenceThicknessMap,Pe=J&&!!w.sheenColorMap,Je=J&&!!w.sheenRoughnessMap,Ve=!!w.specularMap,Ce=!!w.specularColorMap,ht=!!w.specularIntensityMap,N=le&&!!w.transmissionMap,me=le&&!!w.thicknessMap,be=!!w.gradientMap,Fe=!!w.alphaMap,he=w.alphaTest>0,re=!!w.alphaHash,ze=!!w.extensions;let lt=Os;w.toneMapped&&(se===null||se.isXRRenderTarget===!0)&&(lt=n.toneMapping);const kt={shaderID:ne,shaderType:w.type,shaderName:w.name,vertexShader:De,fragmentShader:Xe,defines:w.defines,customVertexShaderID:ke,customFragmentShaderID:Z,isRawShaderMaterial:w.isRawShaderMaterial===!0,glslVersion:w.glslVersion,precision:f,batching:ie,batchingColor:ie&&O._colorsTexture!==null,instancing:X,instancingColor:X&&O.instanceColor!==null,instancingMorph:X&&O.morphTexture!==null,supportsVertexTextures:h,outputColorSpace:se===null?n.outputColorSpace:se.isXRRenderTarget===!0?se.texture.colorSpace:xn,alphaToCoverage:!!w.alphaToCoverage,map:xe,matcap:Ae,envMap:L,envMapMode:L&&W.mapping,envMapCubeUVHeight:H,aoMap:G,lightMap:j,bumpMap:Y,normalMap:Q,displacementMap:h&&_e,emissiveMap:ce,normalMapObjectSpace:Q&&w.normalMapType===tS,normalMapTangentSpace:Q&&w.normalMapType===ha,metalnessMap:ge,roughnessMap:$e,anisotropy:it,anisotropyMap:ee,clearcoat:I,clearcoatMap:He,clearcoatNormalMap:ye,clearcoatRoughnessMap:Ue,dispersion:A,iridescence:V,iridescenceMap:Be,iridescenceThicknessMap:de,sheen:J,sheenColorMap:Pe,sheenRoughnessMap:Je,specularMap:Ve,specularColorMap:Ce,specularIntensityMap:ht,transmission:le,transmissionMap:N,thicknessMap:me,gradientMap:be,opaque:w.transparent===!1&&w.blending===tr&&w.alphaToCoverage===!1,alphaMap:Fe,alphaTest:he,alphaHash:re,combine:w.combine,mapUv:xe&&g(w.map.channel),aoMapUv:G&&g(w.aoMap.channel),lightMapUv:j&&g(w.lightMap.channel),bumpMapUv:Y&&g(w.bumpMap.channel),normalMapUv:Q&&g(w.normalMap.channel),displacementMapUv:_e&&g(w.displacementMap.channel),emissiveMapUv:ce&&g(w.emissiveMap.channel),metalnessMapUv:ge&&g(w.metalnessMap.channel),roughnessMapUv:$e&&g(w.roughnessMap.channel),anisotropyMapUv:ee&&g(w.anisotropyMap.channel),clearcoatMapUv:He&&g(w.clearcoatMap.channel),clearcoatNormalMapUv:ye&&g(w.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ue&&g(w.clearcoatRoughnessMap.channel),iridescenceMapUv:Be&&g(w.iridescenceMap.channel),iridescenceThicknessMapUv:de&&g(w.iridescenceThicknessMap.channel),sheenColorMapUv:Pe&&g(w.sheenColorMap.channel),sheenRoughnessMapUv:Je&&g(w.sheenRoughnessMap.channel),specularMapUv:Ve&&g(w.specularMap.channel),specularColorMapUv:Ce&&g(w.specularColorMap.channel),specularIntensityMapUv:ht&&g(w.specularIntensityMap.channel),transmissionMapUv:N&&g(w.transmissionMap.channel),thicknessMapUv:me&&g(w.thicknessMap.channel),alphaMapUv:Fe&&g(w.alphaMap.channel),vertexTangents:!!U.attributes.tangent&&(Q||it),vertexColors:w.vertexColors,vertexAlphas:w.vertexColors===!0&&!!U.attributes.color&&U.attributes.color.itemSize===4,pointsUvs:O.isPoints===!0&&!!U.attributes.uv&&(xe||Fe),fog:!!k,useFog:w.fog===!0,fogExp2:!!k&&k.isFogExp2,flatShading:w.flatShading===!0&&w.wireframe===!1,sizeAttenuation:w.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:Se,skinning:O.isSkinnedMesh===!0,morphTargets:U.morphAttributes.position!==void 0,morphNormals:U.morphAttributes.normal!==void 0,morphColors:U.morphAttributes.color!==void 0,morphTargetsCount:pe,morphTextureStride:Ie,numDirLights:E.directional.length,numPointLights:E.point.length,numSpotLights:E.spot.length,numSpotLightMaps:E.spotLightMap.length,numRectAreaLights:E.rectArea.length,numHemiLights:E.hemi.length,numDirLightShadows:E.directionalShadowMap.length,numPointLightShadows:E.pointShadowMap.length,numSpotLightShadows:E.spotShadowMap.length,numSpotLightShadowsWithMaps:E.numSpotLightShadowsWithMaps,numLightProbes:E.numLightProbes,numClippingPlanes:r.numPlanes,numClipIntersection:r.numIntersection,dithering:w.dithering,shadowMapEnabled:n.shadowMap.enabled&&R.length>0,shadowMapType:n.shadowMap.type,toneMapping:lt,decodeVideoTexture:xe&&w.map.isVideoTexture===!0&&at.getTransfer(w.map.colorSpace)===Pt,decodeVideoTextureEmissive:ce&&w.emissiveMap.isVideoTexture===!0&&at.getTransfer(w.emissiveMap.colorSpace)===Pt,premultipliedAlpha:w.premultipliedAlpha,doubleSided:w.side===ct,flipSided:w.side===un,useDepthPacking:w.depthPacking>=0,depthPacking:w.depthPacking||0,index0AttributeName:w.index0AttributeName,extensionClipCullDistance:ze&&w.extensions.clipCullDistance===!0&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ze&&w.extensions.multiDraw===!0||ie)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:w.customProgramCacheKey()};return kt.vertexUv1s=c.has(1),kt.vertexUv2s=c.has(2),kt.vertexUv3s=c.has(3),c.clear(),kt}function m(w){const E=[];if(w.shaderID?E.push(w.shaderID):(E.push(w.customVertexShaderID),E.push(w.customFragmentShaderID)),w.defines!==void 0)for(const R in w.defines)E.push(R),E.push(w.defines[R]);return w.isRawShaderMaterial===!1&&(v(E,w),y(E,w),E.push(n.outputColorSpace)),E.push(w.customProgramCacheKey),E.join()}function v(w,E){w.push(E.precision),w.push(E.outputColorSpace),w.push(E.envMapMode),w.push(E.envMapCubeUVHeight),w.push(E.mapUv),w.push(E.alphaMapUv),w.push(E.lightMapUv),w.push(E.aoMapUv),w.push(E.bumpMapUv),w.push(E.normalMapUv),w.push(E.displacementMapUv),w.push(E.emissiveMapUv),w.push(E.metalnessMapUv),w.push(E.roughnessMapUv),w.push(E.anisotropyMapUv),w.push(E.clearcoatMapUv),w.push(E.clearcoatNormalMapUv),w.push(E.clearcoatRoughnessMapUv),w.push(E.iridescenceMapUv),w.push(E.iridescenceThicknessMapUv),w.push(E.sheenColorMapUv),w.push(E.sheenRoughnessMapUv),w.push(E.specularMapUv),w.push(E.specularColorMapUv),w.push(E.specularIntensityMapUv),w.push(E.transmissionMapUv),w.push(E.thicknessMapUv),w.push(E.combine),w.push(E.fogExp2),w.push(E.sizeAttenuation),w.push(E.morphTargetsCount),w.push(E.morphAttributeCount),w.push(E.numDirLights),w.push(E.numPointLights),w.push(E.numSpotLights),w.push(E.numSpotLightMaps),w.push(E.numHemiLights),w.push(E.numRectAreaLights),w.push(E.numDirLightShadows),w.push(E.numPointLightShadows),w.push(E.numSpotLightShadows),w.push(E.numSpotLightShadowsWithMaps),w.push(E.numLightProbes),w.push(E.shadowMapType),w.push(E.toneMapping),w.push(E.numClippingPlanes),w.push(E.numClipIntersection),w.push(E.depthPacking)}function y(w,E){o.disableAll(),E.supportsVertexTextures&&o.enable(0),E.instancing&&o.enable(1),E.instancingColor&&o.enable(2),E.instancingMorph&&o.enable(3),E.matcap&&o.enable(4),E.envMap&&o.enable(5),E.normalMapObjectSpace&&o.enable(6),E.normalMapTangentSpace&&o.enable(7),E.clearcoat&&o.enable(8),E.iridescence&&o.enable(9),E.alphaTest&&o.enable(10),E.vertexColors&&o.enable(11),E.vertexAlphas&&o.enable(12),E.vertexUv1s&&o.enable(13),E.vertexUv2s&&o.enable(14),E.vertexUv3s&&o.enable(15),E.vertexTangents&&o.enable(16),E.anisotropy&&o.enable(17),E.alphaHash&&o.enable(18),E.batching&&o.enable(19),E.dispersion&&o.enable(20),E.batchingColor&&o.enable(21),E.gradientMap&&o.enable(22),w.push(o.mask),o.disableAll(),E.fog&&o.enable(0),E.useFog&&o.enable(1),E.flatShading&&o.enable(2),E.logarithmicDepthBuffer&&o.enable(3),E.reversedDepthBuffer&&o.enable(4),E.skinning&&o.enable(5),E.morphTargets&&o.enable(6),E.morphNormals&&o.enable(7),E.morphColors&&o.enable(8),E.premultipliedAlpha&&o.enable(9),E.shadowMapEnabled&&o.enable(10),E.doubleSided&&o.enable(11),E.flipSided&&o.enable(12),E.useDepthPacking&&o.enable(13),E.dithering&&o.enable(14),E.transmission&&o.enable(15),E.sheen&&o.enable(16),E.opaque&&o.enable(17),E.pointsUvs&&o.enable(18),E.decodeVideoTexture&&o.enable(19),E.decodeVideoTextureEmissive&&o.enable(20),E.alphaToCoverage&&o.enable(21),w.push(o.mask)}function b(w){const E=p[w.type];let R;if(E){const D=Wi[E];R=pS.clone(D.uniforms)}else R=w.uniforms;return R}function T(w,E){let R;for(let D=0,O=u.length;D0?i.push(m):f.transparent===!0?s.push(m):t.push(m)}function l(d,h,f,p,g,_){const m=r(d,h,f,p,g,_);f.transmission>0?i.unshift(m):f.transparent===!0?s.unshift(m):t.unshift(m)}function c(d,h){t.length>1&&t.sort(d||PD),i.length>1&&i.sort(h||U0),s.length>1&&s.sort(h||U0)}function u(){for(let d=e,h=n.length;d=a.length?(r=new B0,a.push(r)):r=a[s],r}function t(){n=new WeakMap}return{get:e,dispose:t}}function LD(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new S,color:new ue};break;case"SpotLight":t={position:new S,direction:new S,color:new ue,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new S,color:new ue,distance:0,decay:0};break;case"HemisphereLight":t={direction:new S,skyColor:new ue,groundColor:new ue};break;case"RectAreaLight":t={color:new ue,position:new S,halfWidth:new S,halfHeight:new S};break}return n[e.id]=t,t}}}function DD(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new te};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new te};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new te,shadowCameraNear:1,shadowCameraFar:1e3};break}return n[e.id]=t,t}}}let kD=0;function OD(n,e){return(e.castShadow?2:0)-(n.castShadow?2:0)+(e.map?1:0)-(n.map?1:0)}function FD(n){const e=new LD,t=DD(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)i.probe.push(new S);const s=new S,a=new Me,r=new Me;function o(c){let u=0,d=0,h=0;for(let w=0;w<9;w++)i.probe[w].set(0,0,0);let f=0,p=0,g=0,_=0,m=0,v=0,y=0,b=0,T=0,x=0,M=0;c.sort(OD);for(let w=0,E=c.length;w0&&(n.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Te.LTC_FLOAT_1,i.rectAreaLTC2=Te.LTC_FLOAT_2):(i.rectAreaLTC1=Te.LTC_HALF_1,i.rectAreaLTC2=Te.LTC_HALF_2)),i.ambient[0]=u,i.ambient[1]=d,i.ambient[2]=h;const C=i.hash;(C.directionalLength!==f||C.pointLength!==p||C.spotLength!==g||C.rectAreaLength!==_||C.hemiLength!==m||C.numDirectionalShadows!==v||C.numPointShadows!==y||C.numSpotShadows!==b||C.numSpotMaps!==T||C.numLightProbes!==M)&&(i.directional.length=f,i.spot.length=g,i.rectArea.length=_,i.point.length=p,i.hemi.length=m,i.directionalShadow.length=v,i.directionalShadowMap.length=v,i.pointShadow.length=y,i.pointShadowMap.length=y,i.spotShadow.length=b,i.spotShadowMap.length=b,i.directionalShadowMatrix.length=v,i.pointShadowMatrix.length=y,i.spotLightMatrix.length=b+T-x,i.spotLightMap.length=T,i.numSpotLightShadowsWithMaps=x,i.numLightProbes=M,C.directionalLength=f,C.pointLength=p,C.spotLength=g,C.rectAreaLength=_,C.hemiLength=m,C.numDirectionalShadows=v,C.numPointShadows=y,C.numSpotShadows=b,C.numSpotMaps=T,C.numLightProbes=M,i.version=kD++)}function l(c,u){let d=0,h=0,f=0,p=0,g=0;const _=u.matrixWorldInverse;for(let m=0,v=c.length;m=r.length?(o=new z0(n),r.push(o)):o=r[a],o}function i(){e=new WeakMap}return{get:t,dispose:i}}const UD=`void main() { +`+pe)}else U!==""?console.warn("THREE.WebGLProgram: Program Info Log:",U):(F===""||W==="")&&(ne=!1);ne&&(R.diagnostics={runnable:H,programLog:U,vertexShader:{log:F,prefix:_},fragmentShader:{log:W,prefix:m}})}s.deleteShader(T),s.deleteShader(x),C=new qu(s,g),w=Tk(s,g)}let C;this.getUniforms=function(){return C===void 0&&M(this),C};let w;this.getAttributes=function(){return w===void 0&&M(this),w};let E=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=s.getProgramParameter(g,mk)),E},this.destroy=function(){i.releaseStatesOfProgram(this),s.deleteProgram(g),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=_k++,this.cacheKey=e,this.usedTimes=1,this.program=g,this.vertexShader=T,this.fragmentShader=x,this}let Fk=0;class Nk{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,i=e.fragmentShader,s=this._getShaderStage(t),a=this._getShaderStage(i),r=this._getShaderCacheForMaterial(e);return r.has(s)===!1&&(r.add(s),s.usedTimes++),r.has(a)===!1&&(r.add(a),a.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return i===void 0&&(i=new Uk(e),t.set(e,i)),i}}class Uk{constructor(e){this.id=Fk++,this.code=e,this.usedTimes=0}}function Bk(n,e,t,i,s,a,r){const o=new Lh,l=new Nk,c=new Set,u=[],d=s.logarithmicDepthBuffer,h=s.vertexTextures;let f=s.precision;const p={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function g(w){return c.add(w),w===0?"uv":`uv${w}`}function _(w,E,R,k,O){const D=k.fog,U=O.geometry,F=w.isMeshStandardMaterial?k.environment:null,W=(w.isMeshStandardMaterial?t:e).get(w.envMap||F),H=W&&W.mapping===Io?W.image.height:null,ne=p[w.type];w.precision!==null&&(f=s.getMaxPrecision(w.precision),f!==w.precision&&console.warn("THREE.WebGLProgram.getParameters:",w.precision,"not supported, using",f,"instead."));const oe=U.morphAttributes.position||U.morphAttributes.normal||U.morphAttributes.color,pe=oe!==void 0?oe.length:0;let Ie=0;U.morphAttributes.position!==void 0&&(Ie=1),U.morphAttributes.normal!==void 0&&(Ie=2),U.morphAttributes.color!==void 0&&(Ie=3);let ke,Xe,De,Z;if(ne){const Et=Xi[ne];ke=Et.vertexShader,Xe=Et.fragmentShader}else ke=w.vertexShader,Xe=w.fragmentShader,l.update(w),De=l.getVertexShaderID(w),Z=l.getFragmentShaderID(w);const ae=n.getRenderTarget(),Se=n.state.buffers.depth.getReversed(),X=O.isInstancedMesh===!0,ie=O.isBatchedMesh===!0,xe=!!w.map,Ae=!!w.matcap,L=!!W,G=!!w.aoMap,j=!!w.lightMap,Y=!!w.bumpMap,Q=!!w.normalMap,_e=!!w.displacementMap,ce=!!w.emissiveMap,ge=!!w.metalnessMap,$e=!!w.roughnessMap,it=w.anisotropy>0,I=w.clearcoat>0,A=w.dispersion>0,V=w.iridescence>0,J=w.sheen>0,le=w.transmission>0,ee=it&&!!w.anisotropyMap,He=I&&!!w.clearcoatMap,ye=I&&!!w.clearcoatNormalMap,Ue=I&&!!w.clearcoatRoughnessMap,Be=V&&!!w.iridescenceMap,de=V&&!!w.iridescenceThicknessMap,Pe=J&&!!w.sheenColorMap,Je=J&&!!w.sheenRoughnessMap,Ve=!!w.specularMap,Ce=!!w.specularColorMap,ht=!!w.specularIntensityMap,N=le&&!!w.transmissionMap,me=le&&!!w.thicknessMap,be=!!w.gradientMap,Fe=!!w.alphaMap,he=w.alphaTest>0,re=!!w.alphaHash,ze=!!w.extensions;let lt=Os;w.toneMapped&&(ae===null||ae.isXRRenderTarget===!0)&&(lt=n.toneMapping);const Dt={shaderID:ne,shaderType:w.type,shaderName:w.name,vertexShader:ke,fragmentShader:Xe,defines:w.defines,customVertexShaderID:De,customFragmentShaderID:Z,isRawShaderMaterial:w.isRawShaderMaterial===!0,glslVersion:w.glslVersion,precision:f,batching:ie,batchingColor:ie&&O._colorsTexture!==null,instancing:X,instancingColor:X&&O.instanceColor!==null,instancingMorph:X&&O.morphTexture!==null,supportsVertexTextures:h,outputColorSpace:ae===null?n.outputColorSpace:ae.isXRRenderTarget===!0?ae.texture.colorSpace:xn,alphaToCoverage:!!w.alphaToCoverage,map:xe,matcap:Ae,envMap:L,envMapMode:L&&W.mapping,envMapCubeUVHeight:H,aoMap:G,lightMap:j,bumpMap:Y,normalMap:Q,displacementMap:h&&_e,emissiveMap:ce,normalMapObjectSpace:Q&&w.normalMapType===cS,normalMapTangentSpace:Q&&w.normalMapType===fa,metalnessMap:ge,roughnessMap:$e,anisotropy:it,anisotropyMap:ee,clearcoat:I,clearcoatMap:He,clearcoatNormalMap:ye,clearcoatRoughnessMap:Ue,dispersion:A,iridescence:V,iridescenceMap:Be,iridescenceThicknessMap:de,sheen:J,sheenColorMap:Pe,sheenRoughnessMap:Je,specularMap:Ve,specularColorMap:Ce,specularIntensityMap:ht,transmission:le,transmissionMap:N,thicknessMap:me,gradientMap:be,opaque:w.transparent===!1&&w.blending===nr&&w.alphaToCoverage===!1,alphaMap:Fe,alphaTest:he,alphaHash:re,combine:w.combine,mapUv:xe&&g(w.map.channel),aoMapUv:G&&g(w.aoMap.channel),lightMapUv:j&&g(w.lightMap.channel),bumpMapUv:Y&&g(w.bumpMap.channel),normalMapUv:Q&&g(w.normalMap.channel),displacementMapUv:_e&&g(w.displacementMap.channel),emissiveMapUv:ce&&g(w.emissiveMap.channel),metalnessMapUv:ge&&g(w.metalnessMap.channel),roughnessMapUv:$e&&g(w.roughnessMap.channel),anisotropyMapUv:ee&&g(w.anisotropyMap.channel),clearcoatMapUv:He&&g(w.clearcoatMap.channel),clearcoatNormalMapUv:ye&&g(w.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ue&&g(w.clearcoatRoughnessMap.channel),iridescenceMapUv:Be&&g(w.iridescenceMap.channel),iridescenceThicknessMapUv:de&&g(w.iridescenceThicknessMap.channel),sheenColorMapUv:Pe&&g(w.sheenColorMap.channel),sheenRoughnessMapUv:Je&&g(w.sheenRoughnessMap.channel),specularMapUv:Ve&&g(w.specularMap.channel),specularColorMapUv:Ce&&g(w.specularColorMap.channel),specularIntensityMapUv:ht&&g(w.specularIntensityMap.channel),transmissionMapUv:N&&g(w.transmissionMap.channel),thicknessMapUv:me&&g(w.thicknessMap.channel),alphaMapUv:Fe&&g(w.alphaMap.channel),vertexTangents:!!U.attributes.tangent&&(Q||it),vertexColors:w.vertexColors,vertexAlphas:w.vertexColors===!0&&!!U.attributes.color&&U.attributes.color.itemSize===4,pointsUvs:O.isPoints===!0&&!!U.attributes.uv&&(xe||Fe),fog:!!D,useFog:w.fog===!0,fogExp2:!!D&&D.isFogExp2,flatShading:w.flatShading===!0&&w.wireframe===!1,sizeAttenuation:w.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:Se,skinning:O.isSkinnedMesh===!0,morphTargets:U.morphAttributes.position!==void 0,morphNormals:U.morphAttributes.normal!==void 0,morphColors:U.morphAttributes.color!==void 0,morphTargetsCount:pe,morphTextureStride:Ie,numDirLights:E.directional.length,numPointLights:E.point.length,numSpotLights:E.spot.length,numSpotLightMaps:E.spotLightMap.length,numRectAreaLights:E.rectArea.length,numHemiLights:E.hemi.length,numDirLightShadows:E.directionalShadowMap.length,numPointLightShadows:E.pointShadowMap.length,numSpotLightShadows:E.spotShadowMap.length,numSpotLightShadowsWithMaps:E.numSpotLightShadowsWithMaps,numLightProbes:E.numLightProbes,numClippingPlanes:r.numPlanes,numClipIntersection:r.numIntersection,dithering:w.dithering,shadowMapEnabled:n.shadowMap.enabled&&R.length>0,shadowMapType:n.shadowMap.type,toneMapping:lt,decodeVideoTexture:xe&&w.map.isVideoTexture===!0&&rt.getTransfer(w.map.colorSpace)===Pt,decodeVideoTextureEmissive:ce&&w.emissiveMap.isVideoTexture===!0&&rt.getTransfer(w.emissiveMap.colorSpace)===Pt,premultipliedAlpha:w.premultipliedAlpha,doubleSided:w.side===ct,flipSided:w.side===un,useDepthPacking:w.depthPacking>=0,depthPacking:w.depthPacking||0,index0AttributeName:w.index0AttributeName,extensionClipCullDistance:ze&&w.extensions.clipCullDistance===!0&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ze&&w.extensions.multiDraw===!0||ie)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:w.customProgramCacheKey()};return Dt.vertexUv1s=c.has(1),Dt.vertexUv2s=c.has(2),Dt.vertexUv3s=c.has(3),c.clear(),Dt}function m(w){const E=[];if(w.shaderID?E.push(w.shaderID):(E.push(w.customVertexShaderID),E.push(w.customFragmentShaderID)),w.defines!==void 0)for(const R in w.defines)E.push(R),E.push(w.defines[R]);return w.isRawShaderMaterial===!1&&(v(E,w),y(E,w),E.push(n.outputColorSpace)),E.push(w.customProgramCacheKey),E.join()}function v(w,E){w.push(E.precision),w.push(E.outputColorSpace),w.push(E.envMapMode),w.push(E.envMapCubeUVHeight),w.push(E.mapUv),w.push(E.alphaMapUv),w.push(E.lightMapUv),w.push(E.aoMapUv),w.push(E.bumpMapUv),w.push(E.normalMapUv),w.push(E.displacementMapUv),w.push(E.emissiveMapUv),w.push(E.metalnessMapUv),w.push(E.roughnessMapUv),w.push(E.anisotropyMapUv),w.push(E.clearcoatMapUv),w.push(E.clearcoatNormalMapUv),w.push(E.clearcoatRoughnessMapUv),w.push(E.iridescenceMapUv),w.push(E.iridescenceThicknessMapUv),w.push(E.sheenColorMapUv),w.push(E.sheenRoughnessMapUv),w.push(E.specularMapUv),w.push(E.specularColorMapUv),w.push(E.specularIntensityMapUv),w.push(E.transmissionMapUv),w.push(E.thicknessMapUv),w.push(E.combine),w.push(E.fogExp2),w.push(E.sizeAttenuation),w.push(E.morphTargetsCount),w.push(E.morphAttributeCount),w.push(E.numDirLights),w.push(E.numPointLights),w.push(E.numSpotLights),w.push(E.numSpotLightMaps),w.push(E.numHemiLights),w.push(E.numRectAreaLights),w.push(E.numDirLightShadows),w.push(E.numPointLightShadows),w.push(E.numSpotLightShadows),w.push(E.numSpotLightShadowsWithMaps),w.push(E.numLightProbes),w.push(E.shadowMapType),w.push(E.toneMapping),w.push(E.numClippingPlanes),w.push(E.numClipIntersection),w.push(E.depthPacking)}function y(w,E){o.disableAll(),E.supportsVertexTextures&&o.enable(0),E.instancing&&o.enable(1),E.instancingColor&&o.enable(2),E.instancingMorph&&o.enable(3),E.matcap&&o.enable(4),E.envMap&&o.enable(5),E.normalMapObjectSpace&&o.enable(6),E.normalMapTangentSpace&&o.enable(7),E.clearcoat&&o.enable(8),E.iridescence&&o.enable(9),E.alphaTest&&o.enable(10),E.vertexColors&&o.enable(11),E.vertexAlphas&&o.enable(12),E.vertexUv1s&&o.enable(13),E.vertexUv2s&&o.enable(14),E.vertexUv3s&&o.enable(15),E.vertexTangents&&o.enable(16),E.anisotropy&&o.enable(17),E.alphaHash&&o.enable(18),E.batching&&o.enable(19),E.dispersion&&o.enable(20),E.batchingColor&&o.enable(21),E.gradientMap&&o.enable(22),w.push(o.mask),o.disableAll(),E.fog&&o.enable(0),E.useFog&&o.enable(1),E.flatShading&&o.enable(2),E.logarithmicDepthBuffer&&o.enable(3),E.reversedDepthBuffer&&o.enable(4),E.skinning&&o.enable(5),E.morphTargets&&o.enable(6),E.morphNormals&&o.enable(7),E.morphColors&&o.enable(8),E.premultipliedAlpha&&o.enable(9),E.shadowMapEnabled&&o.enable(10),E.doubleSided&&o.enable(11),E.flipSided&&o.enable(12),E.useDepthPacking&&o.enable(13),E.dithering&&o.enable(14),E.transmission&&o.enable(15),E.sheen&&o.enable(16),E.opaque&&o.enable(17),E.pointsUvs&&o.enable(18),E.decodeVideoTexture&&o.enable(19),E.decodeVideoTextureEmissive&&o.enable(20),E.alphaToCoverage&&o.enable(21),w.push(o.mask)}function b(w){const E=p[w.type];let R;if(E){const k=Xi[E];R=wS.clone(k.uniforms)}else R=w.uniforms;return R}function T(w,E){let R;for(let k=0,O=u.length;k0?i.push(m):f.transparent===!0?s.push(m):t.push(m)}function l(d,h,f,p,g,_){const m=r(d,h,f,p,g,_);f.transmission>0?i.unshift(m):f.transparent===!0?s.unshift(m):t.unshift(m)}function c(d,h){t.length>1&&t.sort(d||Hk),i.length>1&&i.sort(h||W0),s.length>1&&s.sort(h||W0)}function u(){for(let d=e,h=n.length;d=a.length?(r=new X0,a.push(r)):r=a[s],r}function t(){n=new WeakMap}return{get:e,dispose:t}}function Gk(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new S,color:new ue};break;case"SpotLight":t={position:new S,direction:new S,color:new ue,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new S,color:new ue,distance:0,decay:0};break;case"HemisphereLight":t={direction:new S,skyColor:new ue,groundColor:new ue};break;case"RectAreaLight":t={color:new ue,position:new S,halfWidth:new S,halfHeight:new S};break}return n[e.id]=t,t}}}function $k(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new te};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new te};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new te,shadowCameraNear:1,shadowCameraFar:1e3};break}return n[e.id]=t,t}}}let Wk=0;function Xk(n,e){return(e.castShadow?2:0)-(n.castShadow?2:0)+(e.map?1:0)-(n.map?1:0)}function Kk(n){const e=new Gk,t=$k(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)i.probe.push(new S);const s=new S,a=new Me,r=new Me;function o(c){let u=0,d=0,h=0;for(let w=0;w<9;w++)i.probe[w].set(0,0,0);let f=0,p=0,g=0,_=0,m=0,v=0,y=0,b=0,T=0,x=0,M=0;c.sort(Xk);for(let w=0,E=c.length;w0&&(n.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Te.LTC_FLOAT_1,i.rectAreaLTC2=Te.LTC_FLOAT_2):(i.rectAreaLTC1=Te.LTC_HALF_1,i.rectAreaLTC2=Te.LTC_HALF_2)),i.ambient[0]=u,i.ambient[1]=d,i.ambient[2]=h;const C=i.hash;(C.directionalLength!==f||C.pointLength!==p||C.spotLength!==g||C.rectAreaLength!==_||C.hemiLength!==m||C.numDirectionalShadows!==v||C.numPointShadows!==y||C.numSpotShadows!==b||C.numSpotMaps!==T||C.numLightProbes!==M)&&(i.directional.length=f,i.spot.length=g,i.rectArea.length=_,i.point.length=p,i.hemi.length=m,i.directionalShadow.length=v,i.directionalShadowMap.length=v,i.pointShadow.length=y,i.pointShadowMap.length=y,i.spotShadow.length=b,i.spotShadowMap.length=b,i.directionalShadowMatrix.length=v,i.pointShadowMatrix.length=y,i.spotLightMatrix.length=b+T-x,i.spotLightMap.length=T,i.numSpotLightShadowsWithMaps=x,i.numLightProbes=M,C.directionalLength=f,C.pointLength=p,C.spotLength=g,C.rectAreaLength=_,C.hemiLength=m,C.numDirectionalShadows=v,C.numPointShadows=y,C.numSpotShadows=b,C.numSpotMaps=T,C.numLightProbes=M,i.version=Wk++)}function l(c,u){let d=0,h=0,f=0,p=0,g=0;const _=u.matrixWorldInverse;for(let m=0,v=c.length;m=r.length?(o=new K0(n),r.push(o)):o=r[a],o}function i(){e=new WeakMap}return{get:t,dispose:i}}const Yk=`void main() { gl_Position = vec4( position, 1.0 ); -}`,BD=`uniform sampler2D shadow_pass; +}`,jk=`uniform sampler2D shadow_pass; uniform vec2 resolution; uniform float radius; #include @@ -3805,12 +3805,12 @@ void main() { squared_mean = squared_mean / samples; float std_dev = sqrt( squared_mean - mean * mean ); gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); -}`;function zD(n,e,t){let i=new Po;const s=new te,a=new te,r=new qe,o=new dg({depthPacking:eS}),l=new hg,c={},u=t.maxTextureSize,d={[fs]:un,[un]:fs,[ct]:ct},h=new ti({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new te},radius:{value:4}},vertexShader:UD,fragmentShader:BD}),f=h.clone();f.defines.HORIZONTAL_PASS=1;const p=new Ge;p.setAttribute("position",new rt(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const g=new we(p,h),_=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=N_;let m=this.type;this.render=function(x,M,C){if(_.enabled===!1||_.autoUpdate===!1&&_.needsUpdate===!1||x.length===0)return;const w=n.getRenderTarget(),E=n.getActiveCubeFace(),R=n.getActiveMipmapLevel(),D=n.state;D.setBlending(ks),D.buffers.depth.getReversed()===!0?D.buffers.color.setClear(0,0,0,0):D.buffers.color.setClear(1,1,1,1),D.buffers.depth.setTest(!0),D.setScissorTest(!1);const O=m!==as&&this.type===as,k=m===as&&this.type!==as;for(let U=0,F=x.length;Uu||s.y>u)&&(s.x>u&&(a.x=Math.floor(u/ne.x),s.x=a.x*ne.x,H.mapSize.x=a.x),s.y>u&&(a.y=Math.floor(u/ne.y),s.y=a.y*ne.y,H.mapSize.y=a.y)),H.map===null||O===!0||k===!0){const pe=this.type!==as?{minFilter:dn,magFilter:dn}:{};H.map!==null&&H.map.dispose(),H.map=new ms(s.x,s.y,pe),H.map.texture.name=W.name+".shadowMap",H.camera.updateProjectionMatrix()}n.setRenderTarget(H.map),n.clear();const oe=H.getViewportCount();for(let pe=0;pe0||M.map&&M.alphaTest>0||M.alphaToCoverage===!0){const D=E.uuid,O=M.uuid;let k=c[D];k===void 0&&(k={},c[D]=k);let U=k[O];U===void 0&&(U=E.clone(),k[O]=U,M.addEventListener("dispose",T)),E=U}if(E.visible=M.visible,E.wireframe=M.wireframe,w===as?E.side=M.shadowSide!==null?M.shadowSide:M.side:E.side=M.shadowSide!==null?M.shadowSide:d[M.side],E.alphaMap=M.alphaMap,E.alphaTest=M.alphaToCoverage===!0?.5:M.alphaTest,E.map=M.map,E.clipShadows=M.clipShadows,E.clippingPlanes=M.clippingPlanes,E.clipIntersection=M.clipIntersection,E.displacementMap=M.displacementMap,E.displacementScale=M.displacementScale,E.displacementBias=M.displacementBias,E.wireframeLinewidth=M.wireframeLinewidth,E.linewidth=M.linewidth,C.isPointLight===!0&&E.isMeshDistanceMaterial===!0){const D=n.properties.get(E);D.light=C}return E}function b(x,M,C,w,E){if(x.visible===!1)return;if(x.layers.test(M.layers)&&(x.isMesh||x.isLine||x.isPoints)&&(x.castShadow||x.receiveShadow&&E===as)&&(!x.frustumCulled||i.intersectsObject(x))){x.modelViewMatrix.multiplyMatrices(C.matrixWorldInverse,x.matrixWorld);const O=e.update(x),k=x.material;if(Array.isArray(k)){const U=O.groups;for(let F=0,W=U.length;F=1):H.indexOf("OpenGL ES")!==-1&&(W=parseFloat(/^OpenGL ES (\d)/.exec(H)[1]),F=W>=2);let ne=null,oe={};const pe=n.getParameter(n.SCISSOR_BOX),Ie=n.getParameter(n.VIEWPORT),De=new qe().fromArray(pe),Xe=new qe().fromArray(Ie);function ke(N,me,be,Fe){const he=new Uint8Array(4),re=n.createTexture();n.bindTexture(N,re),n.texParameteri(N,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(N,n.TEXTURE_MAG_FILTER,n.NEAREST);for(let ze=0;ze"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new te,u=new WeakMap;let d;const h=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function p(I,A){return f?new OffscreenCanvas(I,A):Hl("canvas")}function g(I,A,V){let J=1;const le=it(I);if((le.width>V||le.height>V)&&(J=V/Math.max(le.width,le.height)),J<1)if(typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&I instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&I instanceof ImageBitmap||typeof VideoFrame<"u"&&I instanceof VideoFrame){const ee=Math.floor(J*le.width),He=Math.floor(J*le.height);d===void 0&&(d=p(ee,He));const ye=A?p(ee,He):d;return ye.width=ee,ye.height=He,ye.getContext("2d").drawImage(I,0,0,ee,He),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+le.width+"x"+le.height+") to ("+ee+"x"+He+")."),ye}else return"data"in I&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+le.width+"x"+le.height+")."),I;return I}function _(I){return I.generateMipmaps}function m(I){n.generateMipmap(I)}function v(I){return I.isWebGLCubeRenderTarget?n.TEXTURE_CUBE_MAP:I.isWebGL3DRenderTarget?n.TEXTURE_3D:I.isWebGLArrayRenderTarget||I.isCompressedArrayTexture?n.TEXTURE_2D_ARRAY:n.TEXTURE_2D}function y(I,A,V,J,le=!1){if(I!==null){if(n[I]!==void 0)return n[I];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+I+"'")}let ee=A;if(A===n.RED&&(V===n.FLOAT&&(ee=n.R32F),V===n.HALF_FLOAT&&(ee=n.R16F),V===n.UNSIGNED_BYTE&&(ee=n.R8)),A===n.RED_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.R8UI),V===n.UNSIGNED_SHORT&&(ee=n.R16UI),V===n.UNSIGNED_INT&&(ee=n.R32UI),V===n.BYTE&&(ee=n.R8I),V===n.SHORT&&(ee=n.R16I),V===n.INT&&(ee=n.R32I)),A===n.RG&&(V===n.FLOAT&&(ee=n.RG32F),V===n.HALF_FLOAT&&(ee=n.RG16F),V===n.UNSIGNED_BYTE&&(ee=n.RG8)),A===n.RG_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.RG8UI),V===n.UNSIGNED_SHORT&&(ee=n.RG16UI),V===n.UNSIGNED_INT&&(ee=n.RG32UI),V===n.BYTE&&(ee=n.RG8I),V===n.SHORT&&(ee=n.RG16I),V===n.INT&&(ee=n.RG32I)),A===n.RGB_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.RGB8UI),V===n.UNSIGNED_SHORT&&(ee=n.RGB16UI),V===n.UNSIGNED_INT&&(ee=n.RGB32UI),V===n.BYTE&&(ee=n.RGB8I),V===n.SHORT&&(ee=n.RGB16I),V===n.INT&&(ee=n.RGB32I)),A===n.RGBA_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.RGBA8UI),V===n.UNSIGNED_SHORT&&(ee=n.RGBA16UI),V===n.UNSIGNED_INT&&(ee=n.RGBA32UI),V===n.BYTE&&(ee=n.RGBA8I),V===n.SHORT&&(ee=n.RGBA16I),V===n.INT&&(ee=n.RGBA32I)),A===n.RGB&&(V===n.UNSIGNED_INT_5_9_9_9_REV&&(ee=n.RGB9_E5),V===n.UNSIGNED_INT_10F_11F_11F_REV&&(ee=n.R11F_G11F_B10F)),A===n.RGBA){const He=le?Bl:at.getTransfer(J);V===n.FLOAT&&(ee=n.RGBA32F),V===n.HALF_FLOAT&&(ee=n.RGBA16F),V===n.UNSIGNED_BYTE&&(ee=He===Pt?n.SRGB8_ALPHA8:n.RGBA8),V===n.UNSIGNED_SHORT_4_4_4_4&&(ee=n.RGBA4),V===n.UNSIGNED_SHORT_5_5_5_1&&(ee=n.RGB5_A1)}return(ee===n.R16F||ee===n.R32F||ee===n.RG16F||ee===n.RG32F||ee===n.RGBA16F||ee===n.RGBA32F)&&e.get("EXT_color_buffer_float"),ee}function b(I,A){let V;return I?A===null||A===zs||A===vo?V=n.DEPTH24_STENCIL8:A===Sn?V=n.DEPTH32F_STENCIL8:A===yo&&(V=n.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):A===null||A===zs||A===vo?V=n.DEPTH_COMPONENT24:A===Sn?V=n.DEPTH_COMPONENT32F:A===yo&&(V=n.DEPTH_COMPONENT16),V}function T(I,A){return _(I)===!0||I.isFramebufferTexture&&I.minFilter!==dn&&I.minFilter!==Vt?Math.log2(Math.max(A.width,A.height))+1:I.mipmaps!==void 0&&I.mipmaps.length>0?I.mipmaps.length:I.isCompressedTexture&&Array.isArray(I.image)?A.mipmaps.length:1}function x(I){const A=I.target;A.removeEventListener("dispose",x),C(A),A.isVideoTexture&&u.delete(A)}function M(I){const A=I.target;A.removeEventListener("dispose",M),E(A)}function C(I){const A=i.get(I);if(A.__webglInit===void 0)return;const V=I.source,J=h.get(V);if(J){const le=J[A.__cacheKey];le.usedTimes--,le.usedTimes===0&&w(I),Object.keys(J).length===0&&h.delete(V)}i.remove(I)}function w(I){const A=i.get(I);n.deleteTexture(A.__webglTexture);const V=I.source,J=h.get(V);delete J[A.__cacheKey],r.memory.textures--}function E(I){const A=i.get(I);if(I.depthTexture&&(I.depthTexture.dispose(),i.remove(I.depthTexture)),I.isWebGLCubeRenderTarget)for(let J=0;J<6;J++){if(Array.isArray(A.__webglFramebuffer[J]))for(let le=0;le=s.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+I+" texture units while this GPU supports only "+s.maxTextures),R+=1,I}function k(I){const A=[];return A.push(I.wrapS),A.push(I.wrapT),A.push(I.wrapR||0),A.push(I.magFilter),A.push(I.minFilter),A.push(I.anisotropy),A.push(I.internalFormat),A.push(I.format),A.push(I.type),A.push(I.generateMipmaps),A.push(I.premultiplyAlpha),A.push(I.flipY),A.push(I.unpackAlignment),A.push(I.colorSpace),A.join()}function U(I,A){const V=i.get(I);if(I.isVideoTexture&&ge(I),I.isRenderTargetTexture===!1&&I.isExternalTexture!==!0&&I.version>0&&V.__version!==I.version){const J=I.image;if(J===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(J.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{Z(V,I,A);return}}else I.isExternalTexture&&(V.__webglTexture=I.sourceTexture?I.sourceTexture:null);t.bindTexture(n.TEXTURE_2D,V.__webglTexture,n.TEXTURE0+A)}function F(I,A){const V=i.get(I);if(I.isRenderTargetTexture===!1&&I.version>0&&V.__version!==I.version){Z(V,I,A);return}t.bindTexture(n.TEXTURE_2D_ARRAY,V.__webglTexture,n.TEXTURE0+A)}function W(I,A){const V=i.get(I);if(I.isRenderTargetTexture===!1&&I.version>0&&V.__version!==I.version){Z(V,I,A);return}t.bindTexture(n.TEXTURE_3D,V.__webglTexture,n.TEXTURE0+A)}function H(I,A){const V=i.get(I);if(I.version>0&&V.__version!==I.version){se(V,I,A);return}t.bindTexture(n.TEXTURE_CUBE_MAP,V.__webglTexture,n.TEXTURE0+A)}const ne={[ps]:n.REPEAT,[Hn]:n.CLAMP_TO_EDGE,[go]:n.MIRRORED_REPEAT},oe={[dn]:n.NEAREST,[_h]:n.NEAREST_MIPMAP_NEAREST,[Xa]:n.NEAREST_MIPMAP_LINEAR,[Vt]:n.LINEAR,[eo]:n.LINEAR_MIPMAP_NEAREST,[Ti]:n.LINEAR_MIPMAP_LINEAR},pe={[nS]:n.NEVER,[lS]:n.ALWAYS,[iS]:n.LESS,[j_]:n.LEQUAL,[sS]:n.EQUAL,[oS]:n.GEQUAL,[aS]:n.GREATER,[rS]:n.NOTEQUAL};function Ie(I,A){if(A.type===Sn&&e.has("OES_texture_float_linear")===!1&&(A.magFilter===Vt||A.magFilter===eo||A.magFilter===Xa||A.magFilter===Ti||A.minFilter===Vt||A.minFilter===eo||A.minFilter===Xa||A.minFilter===Ti)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),n.texParameteri(I,n.TEXTURE_WRAP_S,ne[A.wrapS]),n.texParameteri(I,n.TEXTURE_WRAP_T,ne[A.wrapT]),(I===n.TEXTURE_3D||I===n.TEXTURE_2D_ARRAY)&&n.texParameteri(I,n.TEXTURE_WRAP_R,ne[A.wrapR]),n.texParameteri(I,n.TEXTURE_MAG_FILTER,oe[A.magFilter]),n.texParameteri(I,n.TEXTURE_MIN_FILTER,oe[A.minFilter]),A.compareFunction&&(n.texParameteri(I,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(I,n.TEXTURE_COMPARE_FUNC,pe[A.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(A.magFilter===dn||A.minFilter!==Xa&&A.minFilter!==Ti||A.type===Sn&&e.has("OES_texture_float_linear")===!1)return;if(A.anisotropy>1||i.get(A).__currentAnisotropy){const V=e.get("EXT_texture_filter_anisotropic");n.texParameterf(I,V.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(A.anisotropy,s.getMaxAnisotropy())),i.get(A).__currentAnisotropy=A.anisotropy}}}function De(I,A){let V=!1;I.__webglInit===void 0&&(I.__webglInit=!0,A.addEventListener("dispose",x));const J=A.source;let le=h.get(J);le===void 0&&(le={},h.set(J,le));const ee=k(A);if(ee!==I.__cacheKey){le[ee]===void 0&&(le[ee]={texture:n.createTexture(),usedTimes:0},r.memory.textures++,V=!0),le[ee].usedTimes++;const He=le[I.__cacheKey];He!==void 0&&(le[I.__cacheKey].usedTimes--,He.usedTimes===0&&w(A)),I.__cacheKey=ee,I.__webglTexture=le[ee].texture}return V}function Xe(I,A,V){return Math.floor(Math.floor(I/V)/A)}function ke(I,A,V,J){const ee=I.updateRanges;if(ee.length===0)t.texSubImage2D(n.TEXTURE_2D,0,0,0,A.width,A.height,V,J,A.data);else{ee.sort((de,Pe)=>de.start-Pe.start);let He=0;for(let de=1;de0){N&&me&&t.texStorage2D(n.TEXTURE_2D,Fe,Ve,ht[0].width,ht[0].height);for(let he=0,re=ht.length;he0){const ze=Rm(Ce.width,Ce.height,A.format,A.type);for(const lt of A.layerUpdates){const kt=Ce.data.subarray(lt*ze/Ce.data.BYTES_PER_ELEMENT,(lt+1)*ze/Ce.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,he,0,0,lt,Ce.width,Ce.height,1,Pe,kt)}A.clearLayerUpdates()}else t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,he,0,0,0,Ce.width,Ce.height,de.depth,Pe,Ce.data)}else t.compressedTexImage3D(n.TEXTURE_2D_ARRAY,he,Ve,Ce.width,Ce.height,de.depth,0,Ce.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else N?be&&t.texSubImage3D(n.TEXTURE_2D_ARRAY,he,0,0,0,Ce.width,Ce.height,de.depth,Pe,Je,Ce.data):t.texImage3D(n.TEXTURE_2D_ARRAY,he,Ve,Ce.width,Ce.height,de.depth,0,Pe,Je,Ce.data)}else{N&&me&&t.texStorage2D(n.TEXTURE_2D,Fe,Ve,ht[0].width,ht[0].height);for(let he=0,re=ht.length;he0){const he=Rm(de.width,de.height,A.format,A.type);for(const re of A.layerUpdates){const ze=de.data.subarray(re*he/de.data.BYTES_PER_ELEMENT,(re+1)*he/de.data.BYTES_PER_ELEMENT);t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,re,de.width,de.height,1,Pe,Je,ze)}A.clearLayerUpdates()}else t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,de.width,de.height,de.depth,Pe,Je,de.data)}else t.texImage3D(n.TEXTURE_2D_ARRAY,0,Ve,de.width,de.height,de.depth,0,Pe,Je,de.data);else if(A.isData3DTexture)N?(me&&t.texStorage3D(n.TEXTURE_3D,Fe,Ve,de.width,de.height,de.depth),be&&t.texSubImage3D(n.TEXTURE_3D,0,0,0,0,de.width,de.height,de.depth,Pe,Je,de.data)):t.texImage3D(n.TEXTURE_3D,0,Ve,de.width,de.height,de.depth,0,Pe,Je,de.data);else if(A.isFramebufferTexture){if(me)if(N)t.texStorage2D(n.TEXTURE_2D,Fe,Ve,de.width,de.height);else{let he=de.width,re=de.height;for(let ze=0;ze>=1,re>>=1}}else if(ht.length>0){if(N&&me){const he=it(ht[0]);t.texStorage2D(n.TEXTURE_2D,Fe,Ve,he.width,he.height)}for(let he=0,re=ht.length;he0&&Fe++;const re=it(Pe[0]);t.texStorage2D(n.TEXTURE_CUBE_MAP,Fe,ht,re.width,re.height)}for(let re=0;re<6;re++)if(de){N?be&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+re,0,0,0,Pe[re].width,Pe[re].height,Ve,Ce,Pe[re].data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+re,0,ht,Pe[re].width,Pe[re].height,0,Ve,Ce,Pe[re].data);for(let ze=0;ze>ee),Je=Math.max(1,A.height>>ee);le===n.TEXTURE_3D||le===n.TEXTURE_2D_ARRAY?t.texImage3D(le,ee,Ue,Pe,Je,A.depth,0,He,ye,null):t.texImage2D(le,ee,Ue,Pe,Je,0,He,ye,null)}t.bindFramebuffer(n.FRAMEBUFFER,I),ce(A)?o.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,J,le,de.__webglTexture,0,_e(A)):(le===n.TEXTURE_2D||le>=n.TEXTURE_CUBE_MAP_POSITIVE_X&&le<=n.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&n.framebufferTexture2D(n.FRAMEBUFFER,J,le,de.__webglTexture,ee),t.bindFramebuffer(n.FRAMEBUFFER,null)}function X(I,A,V){if(n.bindRenderbuffer(n.RENDERBUFFER,I),A.depthBuffer){const J=A.depthTexture,le=J&&J.isDepthTexture?J.type:null,ee=b(A.stencilBuffer,le),He=A.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ye=_e(A);ce(A)?o.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,ye,ee,A.width,A.height):V?n.renderbufferStorageMultisample(n.RENDERBUFFER,ye,ee,A.width,A.height):n.renderbufferStorage(n.RENDERBUFFER,ee,A.width,A.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,He,n.RENDERBUFFER,I)}else{const J=A.textures;for(let le=0;le{delete A.__boundDepthTexture,delete A.__depthDisposeCallback,J.removeEventListener("dispose",le)};J.addEventListener("dispose",le),A.__depthDisposeCallback=le}A.__boundDepthTexture=J}if(I.depthTexture&&!A.__autoAllocateDepthBuffer){if(V)throw new Error("target.depthTexture not supported in Cube render targets");const J=I.texture.mipmaps;J&&J.length>0?ie(A.__webglFramebuffer[0],I):ie(A.__webglFramebuffer,I)}else if(V){A.__webglDepthbuffer=[];for(let J=0;J<6;J++)if(t.bindFramebuffer(n.FRAMEBUFFER,A.__webglFramebuffer[J]),A.__webglDepthbuffer[J]===void 0)A.__webglDepthbuffer[J]=n.createRenderbuffer(),X(A.__webglDepthbuffer[J],I,!1);else{const le=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ee=A.__webglDepthbuffer[J];n.bindRenderbuffer(n.RENDERBUFFER,ee),n.framebufferRenderbuffer(n.FRAMEBUFFER,le,n.RENDERBUFFER,ee)}}else{const J=I.texture.mipmaps;if(J&&J.length>0?t.bindFramebuffer(n.FRAMEBUFFER,A.__webglFramebuffer[0]):t.bindFramebuffer(n.FRAMEBUFFER,A.__webglFramebuffer),A.__webglDepthbuffer===void 0)A.__webglDepthbuffer=n.createRenderbuffer(),X(A.__webglDepthbuffer,I,!1);else{const le=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ee=A.__webglDepthbuffer;n.bindRenderbuffer(n.RENDERBUFFER,ee),n.framebufferRenderbuffer(n.FRAMEBUFFER,le,n.RENDERBUFFER,ee)}}t.bindFramebuffer(n.FRAMEBUFFER,null)}function Ae(I,A,V){const J=i.get(I);A!==void 0&&Se(J.__webglFramebuffer,I,I.texture,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,0),V!==void 0&&xe(I)}function L(I){const A=I.texture,V=i.get(I),J=i.get(A);I.addEventListener("dispose",M);const le=I.textures,ee=I.isWebGLCubeRenderTarget===!0,He=le.length>1;if(He||(J.__webglTexture===void 0&&(J.__webglTexture=n.createTexture()),J.__version=A.version,r.memory.textures++),ee){V.__webglFramebuffer=[];for(let ye=0;ye<6;ye++)if(A.mipmaps&&A.mipmaps.length>0){V.__webglFramebuffer[ye]=[];for(let Ue=0;Ue0){V.__webglFramebuffer=[];for(let ye=0;ye0&&ce(I)===!1){V.__webglMultisampledFramebuffer=n.createFramebuffer(),V.__webglColorRenderbuffer=[],t.bindFramebuffer(n.FRAMEBUFFER,V.__webglMultisampledFramebuffer);for(let ye=0;ye0)for(let Ue=0;Ue0)for(let Ue=0;Ue0){if(ce(I)===!1){const A=I.textures,V=I.width,J=I.height;let le=n.COLOR_BUFFER_BIT;const ee=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,He=i.get(I),ye=A.length>1;if(ye)for(let Be=0;Be0?t.bindFramebuffer(n.DRAW_FRAMEBUFFER,He.__webglFramebuffer[0]):t.bindFramebuffer(n.DRAW_FRAMEBUFFER,He.__webglFramebuffer);for(let Be=0;Be0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&A.__useRenderToTexture!==!1}function ge(I){const A=r.render.frame;u.get(I)!==A&&(u.set(I,A),I.update())}function $e(I,A){const V=I.colorSpace,J=I.format,le=I.type;return I.isCompressedTexture===!0||I.isVideoTexture===!0||V!==xn&&V!==Ls&&(at.getTransfer(V)===Pt?(J!==Vn||le!==Yi)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",V)),A}function it(I){return typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement?(c.width=I.naturalWidth||I.width,c.height=I.naturalHeight||I.height):typeof VideoFrame<"u"&&I instanceof VideoFrame?(c.width=I.displayWidth,c.height=I.displayHeight):(c.width=I.width,c.height=I.height),c}this.allocateTextureUnit=O,this.resetTextureUnits=D,this.setTexture2D=U,this.setTexture2DArray=F,this.setTexture3D=W,this.setTextureCube=H,this.rebindTextures=Ae,this.setupRenderTarget=L,this.updateRenderTargetMipmap=G,this.updateMultisampleRenderTarget=Q,this.setupDepthRenderbuffer=xe,this.setupFrameBufferTexture=Se,this.useMultisampledRTT=ce}function oT(n,e){function t(i,s=Ls){let a;const r=at.getTransfer(s);if(i===Yi)return n.UNSIGNED_BYTE;if(i===yh)return n.UNSIGNED_SHORT_4_4_4_4;if(i===vh)return n.UNSIGNED_SHORT_5_5_5_1;if(i===G_)return n.UNSIGNED_INT_5_9_9_9_REV;if(i===$_)return n.UNSIGNED_INT_10F_11F_11F_REV;if(i===H_)return n.BYTE;if(i===V_)return n.SHORT;if(i===yo)return n.UNSIGNED_SHORT;if(i===gh)return n.INT;if(i===zs)return n.UNSIGNED_INT;if(i===Sn)return n.FLOAT;if(i===ls)return n.HALF_FLOAT;if(i===W_)return n.ALPHA;if(i===X_)return n.RGB;if(i===Vn)return n.RGBA;if(i===bo)return n.DEPTH_COMPONENT;if(i===xo)return n.DEPTH_STENCIL;if(i===bh)return n.RED;if(i===ic)return n.RED_INTEGER;if(i===K_)return n.RG;if(i===xh)return n.RG_INTEGER;if(i===wh)return n.RGBA_INTEGER;if(i===Tl||i===Ml||i===El||i===Cl)if(r===Pt)if(a=e.get("WEBGL_compressed_texture_s3tc_srgb"),a!==null){if(i===Tl)return a.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===Ml)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===El)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===Cl)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(a=e.get("WEBGL_compressed_texture_s3tc"),a!==null){if(i===Tl)return a.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===Ml)return a.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===El)return a.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===Cl)return a.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===yd||i===vd||i===bd||i===xd)if(a=e.get("WEBGL_compressed_texture_pvrtc"),a!==null){if(i===yd)return a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===vd)return a.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===bd)return a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===xd)return a.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===wd||i===Sd||i===Td)if(a=e.get("WEBGL_compressed_texture_etc"),a!==null){if(i===wd||i===Sd)return r===Pt?a.COMPRESSED_SRGB8_ETC2:a.COMPRESSED_RGB8_ETC2;if(i===Td)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:a.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(i===Md||i===Ed||i===Cd||i===Ad||i===Rd||i===Pd||i===Id||i===Ld||i===Dd||i===kd||i===Od||i===Fd||i===Nd||i===Ud)if(a=e.get("WEBGL_compressed_texture_astc"),a!==null){if(i===Md)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:a.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===Ed)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:a.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===Cd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:a.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===Ad)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:a.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===Rd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:a.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===Pd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:a.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===Id)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:a.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===Ld)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:a.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===Dd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:a.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===kd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:a.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===Od)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:a.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===Fd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:a.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===Nd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:a.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===Ud)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:a.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===Bd||i===zd||i===Hd)if(a=e.get("EXT_texture_compression_bptc"),a!==null){if(i===Bd)return r===Pt?a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:a.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===zd)return a.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===Hd)return a.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===Vd||i===Gd||i===$d||i===Wd)if(a=e.get("EXT_texture_compression_rgtc"),a!==null){if(i===Vd)return a.COMPRESSED_RED_RGTC1_EXT;if(i===Gd)return a.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===$d)return a.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===Wd)return a.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===vo?n.UNSIGNED_INT_24_8:n[i]!==void 0?n[i]:null}return{convert:t}}const $D=` +}`;function Zk(n,e,t){let i=new ko;const s=new te,a=new te,r=new qe,o=new yg({depthPacking:lS}),l=new vg,c={},u=t.maxTextureSize,d={[fs]:un,[un]:fs,[ct]:ct},h=new ti({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new te},radius:{value:4}},vertexShader:Yk,fragmentShader:jk}),f=h.clone();f.defines.HORIZONTAL_PASS=1;const p=new Ge;p.setAttribute("position",new ot(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const g=new we(p,h),_=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=$_;let m=this.type;this.render=function(x,M,C){if(_.enabled===!1||_.autoUpdate===!1&&_.needsUpdate===!1||x.length===0)return;const w=n.getRenderTarget(),E=n.getActiveCubeFace(),R=n.getActiveMipmapLevel(),k=n.state;k.setBlending(Ds),k.buffers.depth.getReversed()===!0?k.buffers.color.setClear(0,0,0,0):k.buffers.color.setClear(1,1,1,1),k.buffers.depth.setTest(!0),k.setScissorTest(!1);const O=m!==as&&this.type===as,D=m===as&&this.type!==as;for(let U=0,F=x.length;Uu||s.y>u)&&(s.x>u&&(a.x=Math.floor(u/ne.x),s.x=a.x*ne.x,H.mapSize.x=a.x),s.y>u&&(a.y=Math.floor(u/ne.y),s.y=a.y*ne.y,H.mapSize.y=a.y)),H.map===null||O===!0||D===!0){const pe=this.type!==as?{minFilter:dn,magFilter:dn}:{};H.map!==null&&H.map.dispose(),H.map=new ms(s.x,s.y,pe),H.map.texture.name=W.name+".shadowMap",H.camera.updateProjectionMatrix()}n.setRenderTarget(H.map),n.clear();const oe=H.getViewportCount();for(let pe=0;pe0||M.map&&M.alphaTest>0||M.alphaToCoverage===!0){const k=E.uuid,O=M.uuid;let D=c[k];D===void 0&&(D={},c[k]=D);let U=D[O];U===void 0&&(U=E.clone(),D[O]=U,M.addEventListener("dispose",T)),E=U}if(E.visible=M.visible,E.wireframe=M.wireframe,w===as?E.side=M.shadowSide!==null?M.shadowSide:M.side:E.side=M.shadowSide!==null?M.shadowSide:d[M.side],E.alphaMap=M.alphaMap,E.alphaTest=M.alphaToCoverage===!0?.5:M.alphaTest,E.map=M.map,E.clipShadows=M.clipShadows,E.clippingPlanes=M.clippingPlanes,E.clipIntersection=M.clipIntersection,E.displacementMap=M.displacementMap,E.displacementScale=M.displacementScale,E.displacementBias=M.displacementBias,E.wireframeLinewidth=M.wireframeLinewidth,E.linewidth=M.linewidth,C.isPointLight===!0&&E.isMeshDistanceMaterial===!0){const k=n.properties.get(E);k.light=C}return E}function b(x,M,C,w,E){if(x.visible===!1)return;if(x.layers.test(M.layers)&&(x.isMesh||x.isLine||x.isPoints)&&(x.castShadow||x.receiveShadow&&E===as)&&(!x.frustumCulled||i.intersectsObject(x))){x.modelViewMatrix.multiplyMatrices(C.matrixWorldInverse,x.matrixWorld);const O=e.update(x),D=x.material;if(Array.isArray(D)){const U=O.groups;for(let F=0,W=U.length;F=1):H.indexOf("OpenGL ES")!==-1&&(W=parseFloat(/^OpenGL ES (\d)/.exec(H)[1]),F=W>=2);let ne=null,oe={};const pe=n.getParameter(n.SCISSOR_BOX),Ie=n.getParameter(n.VIEWPORT),ke=new qe().fromArray(pe),Xe=new qe().fromArray(Ie);function De(N,me,be,Fe){const he=new Uint8Array(4),re=n.createTexture();n.bindTexture(N,re),n.texParameteri(N,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(N,n.TEXTURE_MAG_FILTER,n.NEAREST);for(let ze=0;ze"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new te,u=new WeakMap;let d;const h=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function p(I,A){return f?new OffscreenCanvas(I,A):Wl("canvas")}function g(I,A,V){let J=1;const le=it(I);if((le.width>V||le.height>V)&&(J=V/Math.max(le.width,le.height)),J<1)if(typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&I instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&I instanceof ImageBitmap||typeof VideoFrame<"u"&&I instanceof VideoFrame){const ee=Math.floor(J*le.width),He=Math.floor(J*le.height);d===void 0&&(d=p(ee,He));const ye=A?p(ee,He):d;return ye.width=ee,ye.height=He,ye.getContext("2d").drawImage(I,0,0,ee,He),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+le.width+"x"+le.height+") to ("+ee+"x"+He+")."),ye}else return"data"in I&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+le.width+"x"+le.height+")."),I;return I}function _(I){return I.generateMipmaps}function m(I){n.generateMipmap(I)}function v(I){return I.isWebGLCubeRenderTarget?n.TEXTURE_CUBE_MAP:I.isWebGL3DRenderTarget?n.TEXTURE_3D:I.isWebGLArrayRenderTarget||I.isCompressedArrayTexture?n.TEXTURE_2D_ARRAY:n.TEXTURE_2D}function y(I,A,V,J,le=!1){if(I!==null){if(n[I]!==void 0)return n[I];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+I+"'")}let ee=A;if(A===n.RED&&(V===n.FLOAT&&(ee=n.R32F),V===n.HALF_FLOAT&&(ee=n.R16F),V===n.UNSIGNED_BYTE&&(ee=n.R8)),A===n.RED_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.R8UI),V===n.UNSIGNED_SHORT&&(ee=n.R16UI),V===n.UNSIGNED_INT&&(ee=n.R32UI),V===n.BYTE&&(ee=n.R8I),V===n.SHORT&&(ee=n.R16I),V===n.INT&&(ee=n.R32I)),A===n.RG&&(V===n.FLOAT&&(ee=n.RG32F),V===n.HALF_FLOAT&&(ee=n.RG16F),V===n.UNSIGNED_BYTE&&(ee=n.RG8)),A===n.RG_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.RG8UI),V===n.UNSIGNED_SHORT&&(ee=n.RG16UI),V===n.UNSIGNED_INT&&(ee=n.RG32UI),V===n.BYTE&&(ee=n.RG8I),V===n.SHORT&&(ee=n.RG16I),V===n.INT&&(ee=n.RG32I)),A===n.RGB_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.RGB8UI),V===n.UNSIGNED_SHORT&&(ee=n.RGB16UI),V===n.UNSIGNED_INT&&(ee=n.RGB32UI),V===n.BYTE&&(ee=n.RGB8I),V===n.SHORT&&(ee=n.RGB16I),V===n.INT&&(ee=n.RGB32I)),A===n.RGBA_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.RGBA8UI),V===n.UNSIGNED_SHORT&&(ee=n.RGBA16UI),V===n.UNSIGNED_INT&&(ee=n.RGBA32UI),V===n.BYTE&&(ee=n.RGBA8I),V===n.SHORT&&(ee=n.RGBA16I),V===n.INT&&(ee=n.RGBA32I)),A===n.RGB&&(V===n.UNSIGNED_INT_5_9_9_9_REV&&(ee=n.RGB9_E5),V===n.UNSIGNED_INT_10F_11F_11F_REV&&(ee=n.R11F_G11F_B10F)),A===n.RGBA){const He=le?Gl:rt.getTransfer(J);V===n.FLOAT&&(ee=n.RGBA32F),V===n.HALF_FLOAT&&(ee=n.RGBA16F),V===n.UNSIGNED_BYTE&&(ee=He===Pt?n.SRGB8_ALPHA8:n.RGBA8),V===n.UNSIGNED_SHORT_4_4_4_4&&(ee=n.RGBA4),V===n.UNSIGNED_SHORT_5_5_5_1&&(ee=n.RGB5_A1)}return(ee===n.R16F||ee===n.R32F||ee===n.RG16F||ee===n.RG32F||ee===n.RGBA16F||ee===n.RGBA32F)&&e.get("EXT_color_buffer_float"),ee}function b(I,A){let V;return I?A===null||A===zs||A===wo?V=n.DEPTH24_STENCIL8:A===Sn?V=n.DEPTH32F_STENCIL8:A===xo&&(V=n.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):A===null||A===zs||A===wo?V=n.DEPTH_COMPONENT24:A===Sn?V=n.DEPTH_COMPONENT32F:A===xo&&(V=n.DEPTH_COMPONENT16),V}function T(I,A){return _(I)===!0||I.isFramebufferTexture&&I.minFilter!==dn&&I.minFilter!==Vt?Math.log2(Math.max(A.width,A.height))+1:I.mipmaps!==void 0&&I.mipmaps.length>0?I.mipmaps.length:I.isCompressedTexture&&Array.isArray(I.image)?A.mipmaps.length:1}function x(I){const A=I.target;A.removeEventListener("dispose",x),C(A),A.isVideoTexture&&u.delete(A)}function M(I){const A=I.target;A.removeEventListener("dispose",M),E(A)}function C(I){const A=i.get(I);if(A.__webglInit===void 0)return;const V=I.source,J=h.get(V);if(J){const le=J[A.__cacheKey];le.usedTimes--,le.usedTimes===0&&w(I),Object.keys(J).length===0&&h.delete(V)}i.remove(I)}function w(I){const A=i.get(I);n.deleteTexture(A.__webglTexture);const V=I.source,J=h.get(V);delete J[A.__cacheKey],r.memory.textures--}function E(I){const A=i.get(I);if(I.depthTexture&&(I.depthTexture.dispose(),i.remove(I.depthTexture)),I.isWebGLCubeRenderTarget)for(let J=0;J<6;J++){if(Array.isArray(A.__webglFramebuffer[J]))for(let le=0;le=s.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+I+" texture units while this GPU supports only "+s.maxTextures),R+=1,I}function D(I){const A=[];return A.push(I.wrapS),A.push(I.wrapT),A.push(I.wrapR||0),A.push(I.magFilter),A.push(I.minFilter),A.push(I.anisotropy),A.push(I.internalFormat),A.push(I.format),A.push(I.type),A.push(I.generateMipmaps),A.push(I.premultiplyAlpha),A.push(I.flipY),A.push(I.unpackAlignment),A.push(I.colorSpace),A.join()}function U(I,A){const V=i.get(I);if(I.isVideoTexture&&ge(I),I.isRenderTargetTexture===!1&&I.isExternalTexture!==!0&&I.version>0&&V.__version!==I.version){const J=I.image;if(J===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(J.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{Z(V,I,A);return}}else I.isExternalTexture&&(V.__webglTexture=I.sourceTexture?I.sourceTexture:null);t.bindTexture(n.TEXTURE_2D,V.__webglTexture,n.TEXTURE0+A)}function F(I,A){const V=i.get(I);if(I.isRenderTargetTexture===!1&&I.version>0&&V.__version!==I.version){Z(V,I,A);return}t.bindTexture(n.TEXTURE_2D_ARRAY,V.__webglTexture,n.TEXTURE0+A)}function W(I,A){const V=i.get(I);if(I.isRenderTargetTexture===!1&&I.version>0&&V.__version!==I.version){Z(V,I,A);return}t.bindTexture(n.TEXTURE_3D,V.__webglTexture,n.TEXTURE0+A)}function H(I,A){const V=i.get(I);if(I.version>0&&V.__version!==I.version){ae(V,I,A);return}t.bindTexture(n.TEXTURE_CUBE_MAP,V.__webglTexture,n.TEXTURE0+A)}const ne={[ps]:n.REPEAT,[Hn]:n.CLAMP_TO_EDGE,[bo]:n.MIRRORED_REPEAT},oe={[dn]:n.NEAREST,[wh]:n.NEAREST_MIPMAP_NEAREST,[Ka]:n.NEAREST_MIPMAP_LINEAR,[Vt]:n.LINEAR,[no]:n.LINEAR_MIPMAP_NEAREST,[Mi]:n.LINEAR_MIPMAP_LINEAR},pe={[uS]:n.NEVER,[_S]:n.ALWAYS,[dS]:n.LESS,[ig]:n.LEQUAL,[hS]:n.EQUAL,[mS]:n.GEQUAL,[fS]:n.GREATER,[pS]:n.NOTEQUAL};function Ie(I,A){if(A.type===Sn&&e.has("OES_texture_float_linear")===!1&&(A.magFilter===Vt||A.magFilter===no||A.magFilter===Ka||A.magFilter===Mi||A.minFilter===Vt||A.minFilter===no||A.minFilter===Ka||A.minFilter===Mi)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),n.texParameteri(I,n.TEXTURE_WRAP_S,ne[A.wrapS]),n.texParameteri(I,n.TEXTURE_WRAP_T,ne[A.wrapT]),(I===n.TEXTURE_3D||I===n.TEXTURE_2D_ARRAY)&&n.texParameteri(I,n.TEXTURE_WRAP_R,ne[A.wrapR]),n.texParameteri(I,n.TEXTURE_MAG_FILTER,oe[A.magFilter]),n.texParameteri(I,n.TEXTURE_MIN_FILTER,oe[A.minFilter]),A.compareFunction&&(n.texParameteri(I,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(I,n.TEXTURE_COMPARE_FUNC,pe[A.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(A.magFilter===dn||A.minFilter!==Ka&&A.minFilter!==Mi||A.type===Sn&&e.has("OES_texture_float_linear")===!1)return;if(A.anisotropy>1||i.get(A).__currentAnisotropy){const V=e.get("EXT_texture_filter_anisotropic");n.texParameterf(I,V.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(A.anisotropy,s.getMaxAnisotropy())),i.get(A).__currentAnisotropy=A.anisotropy}}}function ke(I,A){let V=!1;I.__webglInit===void 0&&(I.__webglInit=!0,A.addEventListener("dispose",x));const J=A.source;let le=h.get(J);le===void 0&&(le={},h.set(J,le));const ee=D(A);if(ee!==I.__cacheKey){le[ee]===void 0&&(le[ee]={texture:n.createTexture(),usedTimes:0},r.memory.textures++,V=!0),le[ee].usedTimes++;const He=le[I.__cacheKey];He!==void 0&&(le[I.__cacheKey].usedTimes--,He.usedTimes===0&&w(A)),I.__cacheKey=ee,I.__webglTexture=le[ee].texture}return V}function Xe(I,A,V){return Math.floor(Math.floor(I/V)/A)}function De(I,A,V,J){const ee=I.updateRanges;if(ee.length===0)t.texSubImage2D(n.TEXTURE_2D,0,0,0,A.width,A.height,V,J,A.data);else{ee.sort((de,Pe)=>de.start-Pe.start);let He=0;for(let de=1;de0){N&&me&&t.texStorage2D(n.TEXTURE_2D,Fe,Ve,ht[0].width,ht[0].height);for(let he=0,re=ht.length;he0){const ze=Fm(Ce.width,Ce.height,A.format,A.type);for(const lt of A.layerUpdates){const Dt=Ce.data.subarray(lt*ze/Ce.data.BYTES_PER_ELEMENT,(lt+1)*ze/Ce.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,he,0,0,lt,Ce.width,Ce.height,1,Pe,Dt)}A.clearLayerUpdates()}else t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,he,0,0,0,Ce.width,Ce.height,de.depth,Pe,Ce.data)}else t.compressedTexImage3D(n.TEXTURE_2D_ARRAY,he,Ve,Ce.width,Ce.height,de.depth,0,Ce.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else N?be&&t.texSubImage3D(n.TEXTURE_2D_ARRAY,he,0,0,0,Ce.width,Ce.height,de.depth,Pe,Je,Ce.data):t.texImage3D(n.TEXTURE_2D_ARRAY,he,Ve,Ce.width,Ce.height,de.depth,0,Pe,Je,Ce.data)}else{N&&me&&t.texStorage2D(n.TEXTURE_2D,Fe,Ve,ht[0].width,ht[0].height);for(let he=0,re=ht.length;he0){const he=Fm(de.width,de.height,A.format,A.type);for(const re of A.layerUpdates){const ze=de.data.subarray(re*he/de.data.BYTES_PER_ELEMENT,(re+1)*he/de.data.BYTES_PER_ELEMENT);t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,re,de.width,de.height,1,Pe,Je,ze)}A.clearLayerUpdates()}else t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,de.width,de.height,de.depth,Pe,Je,de.data)}else t.texImage3D(n.TEXTURE_2D_ARRAY,0,Ve,de.width,de.height,de.depth,0,Pe,Je,de.data);else if(A.isData3DTexture)N?(me&&t.texStorage3D(n.TEXTURE_3D,Fe,Ve,de.width,de.height,de.depth),be&&t.texSubImage3D(n.TEXTURE_3D,0,0,0,0,de.width,de.height,de.depth,Pe,Je,de.data)):t.texImage3D(n.TEXTURE_3D,0,Ve,de.width,de.height,de.depth,0,Pe,Je,de.data);else if(A.isFramebufferTexture){if(me)if(N)t.texStorage2D(n.TEXTURE_2D,Fe,Ve,de.width,de.height);else{let he=de.width,re=de.height;for(let ze=0;ze>=1,re>>=1}}else if(ht.length>0){if(N&&me){const he=it(ht[0]);t.texStorage2D(n.TEXTURE_2D,Fe,Ve,he.width,he.height)}for(let he=0,re=ht.length;he0&&Fe++;const re=it(Pe[0]);t.texStorage2D(n.TEXTURE_CUBE_MAP,Fe,ht,re.width,re.height)}for(let re=0;re<6;re++)if(de){N?be&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+re,0,0,0,Pe[re].width,Pe[re].height,Ve,Ce,Pe[re].data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+re,0,ht,Pe[re].width,Pe[re].height,0,Ve,Ce,Pe[re].data);for(let ze=0;ze>ee),Je=Math.max(1,A.height>>ee);le===n.TEXTURE_3D||le===n.TEXTURE_2D_ARRAY?t.texImage3D(le,ee,Ue,Pe,Je,A.depth,0,He,ye,null):t.texImage2D(le,ee,Ue,Pe,Je,0,He,ye,null)}t.bindFramebuffer(n.FRAMEBUFFER,I),ce(A)?o.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,J,le,de.__webglTexture,0,_e(A)):(le===n.TEXTURE_2D||le>=n.TEXTURE_CUBE_MAP_POSITIVE_X&&le<=n.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&n.framebufferTexture2D(n.FRAMEBUFFER,J,le,de.__webglTexture,ee),t.bindFramebuffer(n.FRAMEBUFFER,null)}function X(I,A,V){if(n.bindRenderbuffer(n.RENDERBUFFER,I),A.depthBuffer){const J=A.depthTexture,le=J&&J.isDepthTexture?J.type:null,ee=b(A.stencilBuffer,le),He=A.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ye=_e(A);ce(A)?o.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,ye,ee,A.width,A.height):V?n.renderbufferStorageMultisample(n.RENDERBUFFER,ye,ee,A.width,A.height):n.renderbufferStorage(n.RENDERBUFFER,ee,A.width,A.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,He,n.RENDERBUFFER,I)}else{const J=A.textures;for(let le=0;le{delete A.__boundDepthTexture,delete A.__depthDisposeCallback,J.removeEventListener("dispose",le)};J.addEventListener("dispose",le),A.__depthDisposeCallback=le}A.__boundDepthTexture=J}if(I.depthTexture&&!A.__autoAllocateDepthBuffer){if(V)throw new Error("target.depthTexture not supported in Cube render targets");const J=I.texture.mipmaps;J&&J.length>0?ie(A.__webglFramebuffer[0],I):ie(A.__webglFramebuffer,I)}else if(V){A.__webglDepthbuffer=[];for(let J=0;J<6;J++)if(t.bindFramebuffer(n.FRAMEBUFFER,A.__webglFramebuffer[J]),A.__webglDepthbuffer[J]===void 0)A.__webglDepthbuffer[J]=n.createRenderbuffer(),X(A.__webglDepthbuffer[J],I,!1);else{const le=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ee=A.__webglDepthbuffer[J];n.bindRenderbuffer(n.RENDERBUFFER,ee),n.framebufferRenderbuffer(n.FRAMEBUFFER,le,n.RENDERBUFFER,ee)}}else{const J=I.texture.mipmaps;if(J&&J.length>0?t.bindFramebuffer(n.FRAMEBUFFER,A.__webglFramebuffer[0]):t.bindFramebuffer(n.FRAMEBUFFER,A.__webglFramebuffer),A.__webglDepthbuffer===void 0)A.__webglDepthbuffer=n.createRenderbuffer(),X(A.__webglDepthbuffer,I,!1);else{const le=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ee=A.__webglDepthbuffer;n.bindRenderbuffer(n.RENDERBUFFER,ee),n.framebufferRenderbuffer(n.FRAMEBUFFER,le,n.RENDERBUFFER,ee)}}t.bindFramebuffer(n.FRAMEBUFFER,null)}function Ae(I,A,V){const J=i.get(I);A!==void 0&&Se(J.__webglFramebuffer,I,I.texture,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,0),V!==void 0&&xe(I)}function L(I){const A=I.texture,V=i.get(I),J=i.get(A);I.addEventListener("dispose",M);const le=I.textures,ee=I.isWebGLCubeRenderTarget===!0,He=le.length>1;if(He||(J.__webglTexture===void 0&&(J.__webglTexture=n.createTexture()),J.__version=A.version,r.memory.textures++),ee){V.__webglFramebuffer=[];for(let ye=0;ye<6;ye++)if(A.mipmaps&&A.mipmaps.length>0){V.__webglFramebuffer[ye]=[];for(let Ue=0;Ue0){V.__webglFramebuffer=[];for(let ye=0;ye0&&ce(I)===!1){V.__webglMultisampledFramebuffer=n.createFramebuffer(),V.__webglColorRenderbuffer=[],t.bindFramebuffer(n.FRAMEBUFFER,V.__webglMultisampledFramebuffer);for(let ye=0;ye0)for(let Ue=0;Ue0)for(let Ue=0;Ue0){if(ce(I)===!1){const A=I.textures,V=I.width,J=I.height;let le=n.COLOR_BUFFER_BIT;const ee=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,He=i.get(I),ye=A.length>1;if(ye)for(let Be=0;Be0?t.bindFramebuffer(n.DRAW_FRAMEBUFFER,He.__webglFramebuffer[0]):t.bindFramebuffer(n.DRAW_FRAMEBUFFER,He.__webglFramebuffer);for(let Be=0;Be0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&A.__useRenderToTexture!==!1}function ge(I){const A=r.render.frame;u.get(I)!==A&&(u.set(I,A),I.update())}function $e(I,A){const V=I.colorSpace,J=I.format,le=I.type;return I.isCompressedTexture===!0||I.isVideoTexture===!0||V!==xn&&V!==Ls&&(rt.getTransfer(V)===Pt?(J!==Vn||le!==ji)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",V)),A}function it(I){return typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement?(c.width=I.naturalWidth||I.width,c.height=I.naturalHeight||I.height):typeof VideoFrame<"u"&&I instanceof VideoFrame?(c.width=I.displayWidth,c.height=I.displayHeight):(c.width=I.width,c.height=I.height),c}this.allocateTextureUnit=O,this.resetTextureUnits=k,this.setTexture2D=U,this.setTexture2DArray=F,this.setTexture3D=W,this.setTextureCube=H,this.rebindTextures=Ae,this.setupRenderTarget=L,this.updateRenderTargetMipmap=G,this.updateMultisampleRenderTarget=Q,this.setupDepthRenderbuffer=xe,this.setupFrameBufferTexture=Se,this.useMultisampledRTT=ce}function mT(n,e){function t(i,s=Ls){let a;const r=rt.getTransfer(s);if(i===ji)return n.UNSIGNED_BYTE;if(i===Th)return n.UNSIGNED_SHORT_4_4_4_4;if(i===Mh)return n.UNSIGNED_SHORT_5_5_5_1;if(i===j_)return n.UNSIGNED_INT_5_9_9_9_REV;if(i===Z_)return n.UNSIGNED_INT_10F_11F_11F_REV;if(i===q_)return n.BYTE;if(i===Y_)return n.SHORT;if(i===xo)return n.UNSIGNED_SHORT;if(i===Sh)return n.INT;if(i===zs)return n.UNSIGNED_INT;if(i===Sn)return n.FLOAT;if(i===ls)return n.HALF_FLOAT;if(i===J_)return n.ALPHA;if(i===Q_)return n.RGB;if(i===Vn)return n.RGBA;if(i===So)return n.DEPTH_COMPONENT;if(i===To)return n.DEPTH_STENCIL;if(i===Eh)return n.RED;if(i===oc)return n.RED_INTEGER;if(i===eg)return n.RG;if(i===Ch)return n.RG_INTEGER;if(i===Ah)return n.RGBA_INTEGER;if(i===Cl||i===Al||i===Rl||i===Pl)if(r===Pt)if(a=e.get("WEBGL_compressed_texture_s3tc_srgb"),a!==null){if(i===Cl)return a.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===Al)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===Rl)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===Pl)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(a=e.get("WEBGL_compressed_texture_s3tc"),a!==null){if(i===Cl)return a.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===Al)return a.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===Rl)return a.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===Pl)return a.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===Td||i===Md||i===Ed||i===Cd)if(a=e.get("WEBGL_compressed_texture_pvrtc"),a!==null){if(i===Td)return a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===Md)return a.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===Ed)return a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===Cd)return a.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===Ad||i===Rd||i===Pd)if(a=e.get("WEBGL_compressed_texture_etc"),a!==null){if(i===Ad||i===Rd)return r===Pt?a.COMPRESSED_SRGB8_ETC2:a.COMPRESSED_RGB8_ETC2;if(i===Pd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:a.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(i===Id||i===Ld||i===kd||i===Dd||i===Od||i===Fd||i===Nd||i===Ud||i===Bd||i===zd||i===Hd||i===Vd||i===Gd||i===$d)if(a=e.get("WEBGL_compressed_texture_astc"),a!==null){if(i===Id)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:a.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===Ld)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:a.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===kd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:a.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===Dd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:a.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===Od)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:a.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===Fd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:a.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===Nd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:a.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===Ud)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:a.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===Bd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:a.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===zd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:a.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===Hd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:a.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===Vd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:a.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===Gd)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:a.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===$d)return r===Pt?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:a.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===Wd||i===Xd||i===Kd)if(a=e.get("EXT_texture_compression_bptc"),a!==null){if(i===Wd)return r===Pt?a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:a.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===Xd)return a.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===Kd)return a.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===qd||i===Yd||i===jd||i===Zd)if(a=e.get("EXT_texture_compression_rgtc"),a!==null){if(i===qd)return a.COMPRESSED_RED_RGTC1_EXT;if(i===Yd)return a.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===jd)return a.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===Zd)return a.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===wo?n.UNSIGNED_INT_24_8:n[i]!==void 0?n[i]:null}return{convert:t}}const tD=` void main() { gl_Position = vec4( position, 1.0 ); -}`,WD=` +}`,nD=` uniform sampler2DArray depthColor; uniform float depthWidth; uniform float depthHeight; @@ -3829,16 +3829,16 @@ void main() { } -}`;class XD{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const i=new ng(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,i=new ti({vertexShader:$D,fragmentShader:WD,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new we(new Dn(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class KD extends gs{constructor(e,t){super();const i=this;let s=null,a=1,r=null,o="local-floor",l=1,c=null,u=null,d=null,h=null,f=null,p=null;const g=typeof XRWebGLBinding<"u",_=new XD,m={},v=t.getContextAttributes();let y=null,b=null;const T=[],x=[],M=new te;let C=null;const w=new Jt;w.viewport=new qe;const E=new Jt;E.viewport=new qe;const R=[w,E],D=new YS;let O=null,k=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Z){let se=T[Z];return se===void 0&&(se=new Gu,T[Z]=se),se.getTargetRaySpace()},this.getControllerGrip=function(Z){let se=T[Z];return se===void 0&&(se=new Gu,T[Z]=se),se.getGripSpace()},this.getHand=function(Z){let se=T[Z];return se===void 0&&(se=new Gu,T[Z]=se),se.getHandSpace()};function U(Z){const se=x.indexOf(Z.inputSource);if(se===-1)return;const Se=T[se];Se!==void 0&&(Se.update(Z.inputSource,Z.frame,c||r),Se.dispatchEvent({type:Z.type,data:Z.inputSource}))}function F(){s.removeEventListener("select",U),s.removeEventListener("selectstart",U),s.removeEventListener("selectend",U),s.removeEventListener("squeeze",U),s.removeEventListener("squeezestart",U),s.removeEventListener("squeezeend",U),s.removeEventListener("end",F),s.removeEventListener("inputsourceschange",W);for(let Z=0;Z=0&&(x[X]=null,T[X].disconnect(Se))}for(let se=0;se=x.length){x.push(Se),X=xe;break}else if(x[xe]===null){x[xe]=Se,X=xe;break}if(X===-1)break}const ie=T[X];ie&&ie.connect(Se)}}const H=new S,ne=new S;function oe(Z,se,Se){H.setFromMatrixPosition(se.matrixWorld),ne.setFromMatrixPosition(Se.matrixWorld);const X=H.distanceTo(ne),ie=se.projectionMatrix.elements,xe=Se.projectionMatrix.elements,Ae=ie[14]/(ie[10]-1),L=ie[14]/(ie[10]+1),G=(ie[9]+1)/ie[5],j=(ie[9]-1)/ie[5],Y=(ie[8]-1)/ie[0],Q=(xe[8]+1)/xe[0],_e=Ae*Y,ce=Ae*Q,ge=X/(-Y+Q),$e=ge*-Y;if(se.matrixWorld.decompose(Z.position,Z.quaternion,Z.scale),Z.translateX($e),Z.translateZ(ge),Z.matrixWorld.compose(Z.position,Z.quaternion,Z.scale),Z.matrixWorldInverse.copy(Z.matrixWorld).invert(),ie[10]===-1)Z.projectionMatrix.copy(se.projectionMatrix),Z.projectionMatrixInverse.copy(se.projectionMatrixInverse);else{const it=Ae+ge,I=L+ge,A=_e-$e,V=ce+(X-$e),J=G*L/I*it,le=j*L/I*it;Z.projectionMatrix.makePerspective(A,V,J,le,it,I),Z.projectionMatrixInverse.copy(Z.projectionMatrix).invert()}}function pe(Z,se){se===null?Z.matrixWorld.copy(Z.matrix):Z.matrixWorld.multiplyMatrices(se.matrixWorld,Z.matrix),Z.matrixWorldInverse.copy(Z.matrixWorld).invert()}this.updateCamera=function(Z){if(s===null)return;let se=Z.near,Se=Z.far;_.texture!==null&&(_.depthNear>0&&(se=_.depthNear),_.depthFar>0&&(Se=_.depthFar)),D.near=E.near=w.near=se,D.far=E.far=w.far=Se,(O!==D.near||k!==D.far)&&(s.updateRenderState({depthNear:D.near,depthFar:D.far}),O=D.near,k=D.far),D.layers.mask=Z.layers.mask|6,w.layers.mask=D.layers.mask&3,E.layers.mask=D.layers.mask&5;const X=Z.parent,ie=D.cameras;pe(D,X);for(let xe=0;xe0&&(_.alphaTest.value=m.alphaTest);const v=e.get(m),y=v.envMap,b=v.envMapRotation;y&&(_.envMap.value=y,Pa.copy(b),Pa.x*=-1,Pa.y*=-1,Pa.z*=-1,y.isCubeTexture&&y.isRenderTargetTexture===!1&&(Pa.y*=-1,Pa.z*=-1),_.envMapRotation.value.setFromMatrix4(qD.makeRotationFromEuler(Pa)),_.flipEnvMap.value=y.isCubeTexture&&y.isRenderTargetTexture===!1?-1:1,_.reflectivity.value=m.reflectivity,_.ior.value=m.ior,_.refractionRatio.value=m.refractionRatio),m.lightMap&&(_.lightMap.value=m.lightMap,_.lightMapIntensity.value=m.lightMapIntensity,t(m.lightMap,_.lightMapTransform)),m.aoMap&&(_.aoMap.value=m.aoMap,_.aoMapIntensity.value=m.aoMapIntensity,t(m.aoMap,_.aoMapTransform))}function r(_,m){_.diffuse.value.copy(m.color),_.opacity.value=m.opacity,m.map&&(_.map.value=m.map,t(m.map,_.mapTransform))}function o(_,m){_.dashSize.value=m.dashSize,_.totalSize.value=m.dashSize+m.gapSize,_.scale.value=m.scale}function l(_,m,v,y){_.diffuse.value.copy(m.color),_.opacity.value=m.opacity,_.size.value=m.size*v,_.scale.value=y*.5,m.map&&(_.map.value=m.map,t(m.map,_.uvTransform)),m.alphaMap&&(_.alphaMap.value=m.alphaMap,t(m.alphaMap,_.alphaMapTransform)),m.alphaTest>0&&(_.alphaTest.value=m.alphaTest)}function c(_,m){_.diffuse.value.copy(m.color),_.opacity.value=m.opacity,_.rotation.value=m.rotation,m.map&&(_.map.value=m.map,t(m.map,_.mapTransform)),m.alphaMap&&(_.alphaMap.value=m.alphaMap,t(m.alphaMap,_.alphaMapTransform)),m.alphaTest>0&&(_.alphaTest.value=m.alphaTest)}function u(_,m){_.specular.value.copy(m.specular),_.shininess.value=Math.max(m.shininess,1e-4)}function d(_,m){m.gradientMap&&(_.gradientMap.value=m.gradientMap)}function h(_,m){_.metalness.value=m.metalness,m.metalnessMap&&(_.metalnessMap.value=m.metalnessMap,t(m.metalnessMap,_.metalnessMapTransform)),_.roughness.value=m.roughness,m.roughnessMap&&(_.roughnessMap.value=m.roughnessMap,t(m.roughnessMap,_.roughnessMapTransform)),m.envMap&&(_.envMapIntensity.value=m.envMapIntensity)}function f(_,m,v){_.ior.value=m.ior,m.sheen>0&&(_.sheenColor.value.copy(m.sheenColor).multiplyScalar(m.sheen),_.sheenRoughness.value=m.sheenRoughness,m.sheenColorMap&&(_.sheenColorMap.value=m.sheenColorMap,t(m.sheenColorMap,_.sheenColorMapTransform)),m.sheenRoughnessMap&&(_.sheenRoughnessMap.value=m.sheenRoughnessMap,t(m.sheenRoughnessMap,_.sheenRoughnessMapTransform))),m.clearcoat>0&&(_.clearcoat.value=m.clearcoat,_.clearcoatRoughness.value=m.clearcoatRoughness,m.clearcoatMap&&(_.clearcoatMap.value=m.clearcoatMap,t(m.clearcoatMap,_.clearcoatMapTransform)),m.clearcoatRoughnessMap&&(_.clearcoatRoughnessMap.value=m.clearcoatRoughnessMap,t(m.clearcoatRoughnessMap,_.clearcoatRoughnessMapTransform)),m.clearcoatNormalMap&&(_.clearcoatNormalMap.value=m.clearcoatNormalMap,t(m.clearcoatNormalMap,_.clearcoatNormalMapTransform),_.clearcoatNormalScale.value.copy(m.clearcoatNormalScale),m.side===un&&_.clearcoatNormalScale.value.negate())),m.dispersion>0&&(_.dispersion.value=m.dispersion),m.iridescence>0&&(_.iridescence.value=m.iridescence,_.iridescenceIOR.value=m.iridescenceIOR,_.iridescenceThicknessMinimum.value=m.iridescenceThicknessRange[0],_.iridescenceThicknessMaximum.value=m.iridescenceThicknessRange[1],m.iridescenceMap&&(_.iridescenceMap.value=m.iridescenceMap,t(m.iridescenceMap,_.iridescenceMapTransform)),m.iridescenceThicknessMap&&(_.iridescenceThicknessMap.value=m.iridescenceThicknessMap,t(m.iridescenceThicknessMap,_.iridescenceThicknessMapTransform))),m.transmission>0&&(_.transmission.value=m.transmission,_.transmissionSamplerMap.value=v.texture,_.transmissionSamplerSize.value.set(v.width,v.height),m.transmissionMap&&(_.transmissionMap.value=m.transmissionMap,t(m.transmissionMap,_.transmissionMapTransform)),_.thickness.value=m.thickness,m.thicknessMap&&(_.thicknessMap.value=m.thicknessMap,t(m.thicknessMap,_.thicknessMapTransform)),_.attenuationDistance.value=m.attenuationDistance,_.attenuationColor.value.copy(m.attenuationColor)),m.anisotropy>0&&(_.anisotropyVector.value.set(m.anisotropy*Math.cos(m.anisotropyRotation),m.anisotropy*Math.sin(m.anisotropyRotation)),m.anisotropyMap&&(_.anisotropyMap.value=m.anisotropyMap,t(m.anisotropyMap,_.anisotropyMapTransform))),_.specularIntensity.value=m.specularIntensity,_.specularColor.value.copy(m.specularColor),m.specularColorMap&&(_.specularColorMap.value=m.specularColorMap,t(m.specularColorMap,_.specularColorMapTransform)),m.specularIntensityMap&&(_.specularIntensityMap.value=m.specularIntensityMap,t(m.specularIntensityMap,_.specularIntensityMapTransform))}function p(_,m){m.matcap&&(_.matcap.value=m.matcap)}function g(_,m){const v=e.get(m).light;_.referencePosition.value.setFromMatrixPosition(v.matrixWorld),_.nearDistance.value=v.shadow.camera.near,_.farDistance.value=v.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:s}}function jD(n,e,t,i){let s={},a={},r=[];const o=n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS);function l(v,y){const b=y.program;i.uniformBlockBinding(v,b)}function c(v,y){let b=s[v.id];b===void 0&&(p(v),b=u(v),s[v.id]=b,v.addEventListener("dispose",_));const T=y.program;i.updateUBOMapping(v,T);const x=e.render.frame;a[v.id]!==x&&(h(v),a[v.id]=x)}function u(v){const y=d();v.__bindingPointIndex=y;const b=n.createBuffer(),T=v.__size,x=v.usage;return n.bindBuffer(n.UNIFORM_BUFFER,b),n.bufferData(n.UNIFORM_BUFFER,T,x),n.bindBuffer(n.UNIFORM_BUFFER,null),n.bindBufferBase(n.UNIFORM_BUFFER,y,b),b}function d(){for(let v=0;v0&&(b+=T-x),v.__size=b,v.__cache={},this}function g(v){const y={boundary:0,storage:0};return typeof v=="number"||typeof v=="boolean"?(y.boundary=4,y.storage=4):v.isVector2?(y.boundary=8,y.storage=8):v.isVector3||v.isColor?(y.boundary=16,y.storage=12):v.isVector4?(y.boundary=16,y.storage=16):v.isMatrix3?(y.boundary=48,y.storage=48):v.isMatrix4?(y.boundary=64,y.storage=64):v.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",v),y}function _(v){const y=v.target;y.removeEventListener("dispose",_);const b=r.indexOf(y.__bindingPointIndex);r.splice(b,1),n.deleteBuffer(s[y.id]),delete s[y.id],delete a[y.id]}function m(){for(const v in s)n.deleteBuffer(s[v]);r=[],s={},a={}}return{bind:l,update:c,dispose:m}}class Eg{constructor(e={}){const{canvas:t=uS(),context:i=null,depth:s=!0,stencil:a=!1,alpha:r=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:d=!1,reversedDepthBuffer:h=!1}=e;this.isWebGLRenderer=!0;let f;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=i.getContextAttributes().alpha}else f=r;const p=new Uint32Array(4),g=new Int32Array(4);let _=null,m=null;const v=[],y=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Os,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const b=this;let T=!1;this._outputColorSpace=gt;let x=0,M=0,C=null,w=-1,E=null;const R=new qe,D=new qe;let O=null;const k=new ue(0);let U=0,F=t.width,W=t.height,H=1,ne=null,oe=null;const pe=new qe(0,0,F,W),Ie=new qe(0,0,F,W);let De=!1;const Xe=new Po;let ke=!1,Z=!1;const se=new Me,Se=new S,X=new qe,ie={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let xe=!1;function Ae(){return C===null?H:1}let L=i;function G(P,B){return t.getContext(P,B)}try{const P={alpha:!0,depth:s,stencil:a,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:u,failIfMajorPerformanceCaveat:d};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${ph}`),t.addEventListener("webglcontextlost",be,!1),t.addEventListener("webglcontextrestored",Fe,!1),t.addEventListener("webglcontextcreationerror",he,!1),L===null){const B="webgl2";if(L=G(B,P),L===null)throw G(B)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(P){throw console.error("THREE.WebGLRenderer: "+P.message),P}let j,Y,Q,_e,ce,ge,$e,it,I,A,V,J,le,ee,He,ye,Ue,Be,de,Pe,Je,Ve,Ce,ht;function N(){j=new l2(L),j.init(),Ve=new oT(L,j),Y=new t2(L,j,e,Ve),Q=new VD(L,j),Y.reversedDepthBuffer&&h&&Q.buffers.depth.setReversed(!0),_e=new d2(L),ce=new RD,ge=new GD(L,j,Q,ce,Y,Ve,_e),$e=new i2(b),it=new o2(b),I=new gP(L),Ce=new QL(L,I),A=new c2(L,I,_e,Ce),V=new f2(L,A,I,_e),de=new h2(L,Y,ge),ye=new n2(ce),J=new AD(b,$e,it,j,Y,Ce,ye),le=new YD(b,ce),ee=new ID,He=new ND(j),Be=new JL(b,$e,it,Q,V,f,l),Ue=new zD(b,V,Y),ht=new jD(L,_e,Y,Q),Pe=new e2(L,j,_e),Je=new u2(L,j,_e),_e.programs=J.programs,b.capabilities=Y,b.extensions=j,b.properties=ce,b.renderLists=ee,b.shadowMap=Ue,b.state=Q,b.info=_e}N();const me=new KD(b,L);this.xr=me,this.getContext=function(){return L},this.getContextAttributes=function(){return L.getContextAttributes()},this.forceContextLoss=function(){const P=j.get("WEBGL_lose_context");P&&P.loseContext()},this.forceContextRestore=function(){const P=j.get("WEBGL_lose_context");P&&P.restoreContext()},this.getPixelRatio=function(){return H},this.setPixelRatio=function(P){P!==void 0&&(H=P,this.setSize(F,W,!1))},this.getSize=function(P){return P.set(F,W)},this.setSize=function(P,B,K=!0){if(me.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}F=P,W=B,t.width=Math.floor(P*H),t.height=Math.floor(B*H),K===!0&&(t.style.width=P+"px",t.style.height=B+"px"),this.setViewport(0,0,P,B)},this.getDrawingBufferSize=function(P){return P.set(F*H,W*H).floor()},this.setDrawingBufferSize=function(P,B,K){F=P,W=B,H=K,t.width=Math.floor(P*K),t.height=Math.floor(B*K),this.setViewport(0,0,P,B)},this.getCurrentViewport=function(P){return P.copy(R)},this.getViewport=function(P){return P.copy(pe)},this.setViewport=function(P,B,K,q){P.isVector4?pe.set(P.x,P.y,P.z,P.w):pe.set(P,B,K,q),Q.viewport(R.copy(pe).multiplyScalar(H).round())},this.getScissor=function(P){return P.copy(Ie)},this.setScissor=function(P,B,K,q){P.isVector4?Ie.set(P.x,P.y,P.z,P.w):Ie.set(P,B,K,q),Q.scissor(D.copy(Ie).multiplyScalar(H).round())},this.getScissorTest=function(){return De},this.setScissorTest=function(P){Q.setScissorTest(De=P)},this.setOpaqueSort=function(P){ne=P},this.setTransparentSort=function(P){oe=P},this.getClearColor=function(P){return P.copy(Be.getClearColor())},this.setClearColor=function(){Be.setClearColor(...arguments)},this.getClearAlpha=function(){return Be.getClearAlpha()},this.setClearAlpha=function(){Be.setClearAlpha(...arguments)},this.clear=function(P=!0,B=!0,K=!0){let q=0;if(P){let z=!1;if(C!==null){const fe=C.texture.format;z=fe===wh||fe===xh||fe===ic}if(z){const fe=C.texture.type,Re=fe===Yi||fe===zs||fe===yo||fe===vo||fe===yh||fe===vh,Ne=Be.getClearColor(),Oe=Be.getClearAlpha(),je=Ne.r,et=Ne.g,We=Ne.b;Re?(p[0]=je,p[1]=et,p[2]=We,p[3]=Oe,L.clearBufferuiv(L.COLOR,0,p)):(g[0]=je,g[1]=et,g[2]=We,g[3]=Oe,L.clearBufferiv(L.COLOR,0,g))}else q|=L.COLOR_BUFFER_BIT}B&&(q|=L.DEPTH_BUFFER_BIT),K&&(q|=L.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),L.clear(q)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",be,!1),t.removeEventListener("webglcontextrestored",Fe,!1),t.removeEventListener("webglcontextcreationerror",he,!1),Be.dispose(),ee.dispose(),He.dispose(),ce.dispose(),$e.dispose(),it.dispose(),V.dispose(),Ce.dispose(),ht.dispose(),J.dispose(),me.dispose(),me.removeEventListener("sessionstart",Zi),me.removeEventListener("sessionend",ty),ma.stop()};function be(P){P.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),T=!0}function Fe(){console.log("THREE.WebGLRenderer: Context Restored."),T=!1;const P=_e.autoReset,B=Ue.enabled,K=Ue.autoUpdate,q=Ue.needsUpdate,z=Ue.type;N(),_e.autoReset=P,Ue.enabled=B,Ue.autoUpdate=K,Ue.needsUpdate=q,Ue.type=z}function he(P){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",P.statusMessage)}function re(P){const B=P.target;B.removeEventListener("dispose",re),ze(B)}function ze(P){lt(P),ce.remove(P)}function lt(P){const B=ce.get(P).programs;B!==void 0&&(B.forEach(function(K){J.releaseProgram(K)}),P.isShaderMaterial&&J.releaseShaderCache(P))}this.renderBufferDirect=function(P,B,K,q,z,fe){B===null&&(B=ie);const Re=z.isMesh&&z.matrixWorld.determinant()<0,Ne=b1(P,B,K,q,z);Q.setMaterial(q,Re);let Oe=K.index,je=1;if(q.wireframe===!0){if(Oe=A.getWireframeAttribute(K),Oe===void 0)return;je=2}const et=K.drawRange,We=K.attributes.position;let wt=et.start*je,It=(et.start+et.count)*je;fe!==null&&(wt=Math.max(wt,fe.start*je),It=Math.min(It,(fe.start+fe.count)*je)),Oe!==null?(wt=Math.max(wt,0),It=Math.min(It,Oe.count)):We!=null&&(wt=Math.max(wt,0),It=Math.min(It,We.count));const qt=It-wt;if(qt<0||qt===1/0)return;Ce.setup(z,q,Ne,K,Oe);let Ft,Dt=Pe;if(Oe!==null&&(Ft=I.get(Oe),Dt=Je,Dt.setIndex(Ft)),z.isMesh)q.wireframe===!0?(Q.setLineWidth(q.wireframeLinewidth*Ae()),Dt.setMode(L.LINES)):Dt.setMode(L.TRIANGLES);else if(z.isLine){let Ke=q.linewidth;Ke===void 0&&(Ke=1),Q.setLineWidth(Ke*Ae()),z.isLineSegments?Dt.setMode(L.LINES):z.isLineLoop?Dt.setMode(L.LINE_LOOP):Dt.setMode(L.LINE_STRIP)}else z.isPoints?Dt.setMode(L.POINTS):z.isSprite&&Dt.setMode(L.TRIANGLES);if(z.isBatchedMesh)if(z._multiDrawInstances!==null)Vl("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),Dt.renderMultiDrawInstances(z._multiDrawStarts,z._multiDrawCounts,z._multiDrawCount,z._multiDrawInstances);else if(j.get("WEBGL_multi_draw"))Dt.renderMultiDraw(z._multiDrawStarts,z._multiDrawCounts,z._multiDrawCount);else{const Ke=z._multiDrawStarts,Gt=z._multiDrawCounts,St=z._multiDrawCount,ri=Oe?I.get(Oe).bytesPerElement:1,gr=ce.get(q).currentProgram.getUniforms();for(let oi=0;oi{function fe(){if(q.forEach(function(Re){ce.get(Re).currentProgram.isReady()&&q.delete(Re)}),q.size===0){z(P);return}setTimeout(fe,10)}j.get("KHR_parallel_shader_compile")!==null?fe():setTimeout(fe,10)})};let Et=null;function ys(P){Et&&Et(P)}function Zi(){ma.stop()}function ty(){ma.start()}const ma=new nT;ma.setAnimationLoop(ys),typeof self<"u"&&ma.setContext(self),this.setAnimationLoop=function(P){Et=P,me.setAnimationLoop(P),P===null?ma.stop():ma.start()},me.addEventListener("sessionstart",Zi),me.addEventListener("sessionend",ty),this.render=function(P,B){if(B!==void 0&&B.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(T===!0)return;if(P.matrixWorldAutoUpdate===!0&&P.updateMatrixWorld(),B.parent===null&&B.matrixWorldAutoUpdate===!0&&B.updateMatrixWorld(),me.enabled===!0&&me.isPresenting===!0&&(me.cameraAutoUpdate===!0&&me.updateCamera(B),B=me.getCamera()),P.isScene===!0&&P.onBeforeRender(b,P,B,C),m=He.get(P,y.length),m.init(B),y.push(m),se.multiplyMatrices(B.projectionMatrix,B.matrixWorldInverse),Xe.setFromProjectionMatrix(se,hi,B.reversedDepth),Z=this.localClippingEnabled,ke=ye.init(this.clippingPlanes,Z),_=ee.get(P,v.length),_.init(),v.push(_),me.enabled===!0&&me.isPresenting===!0){const fe=b.xr.getDepthSensingMesh();fe!==null&&df(fe,B,-1/0,b.sortObjects)}df(P,B,0,b.sortObjects),_.finish(),b.sortObjects===!0&&_.sort(ne,oe),xe=me.enabled===!1||me.isPresenting===!1||me.hasDepthSensing()===!1,xe&&Be.addToRenderList(_,P),this.info.render.frame++,ke===!0&&ye.beginShadows();const K=m.state.shadowsArray;Ue.render(K,P,B),ke===!0&&ye.endShadows(),this.info.autoReset===!0&&this.info.reset();const q=_.opaque,z=_.transmissive;if(m.setupLights(),B.isArrayCamera){const fe=B.cameras;if(z.length>0)for(let Re=0,Ne=fe.length;Re0&&iy(q,z,P,B),xe&&Be.render(P),ny(_,P,B);C!==null&&M===0&&(ge.updateMultisampleRenderTarget(C),ge.updateRenderTargetMipmap(C)),P.isScene===!0&&P.onAfterRender(b,P,B),Ce.resetDefaultState(),w=-1,E=null,y.pop(),y.length>0?(m=y[y.length-1],ke===!0&&ye.setGlobalState(b.clippingPlanes,m.state.camera)):m=null,v.pop(),v.length>0?_=v[v.length-1]:_=null};function df(P,B,K,q){if(P.visible===!1)return;if(P.layers.test(B.layers)){if(P.isGroup)K=P.renderOrder;else if(P.isLOD)P.autoUpdate===!0&&P.update(B);else if(P.isLight)m.pushLight(P),P.castShadow&&m.pushShadow(P);else if(P.isSprite){if(!P.frustumCulled||Xe.intersectsSprite(P)){q&&X.setFromMatrixPosition(P.matrixWorld).applyMatrix4(se);const Re=V.update(P),Ne=P.material;Ne.visible&&_.push(P,Re,Ne,K,X.z,null)}}else if((P.isMesh||P.isLine||P.isPoints)&&(!P.frustumCulled||Xe.intersectsObject(P))){const Re=V.update(P),Ne=P.material;if(q&&(P.boundingSphere!==void 0?(P.boundingSphere===null&&P.computeBoundingSphere(),X.copy(P.boundingSphere.center)):(Re.boundingSphere===null&&Re.computeBoundingSphere(),X.copy(Re.boundingSphere.center)),X.applyMatrix4(P.matrixWorld).applyMatrix4(se)),Array.isArray(Ne)){const Oe=Re.groups;for(let je=0,et=Oe.length;je0&&mc(z,B,K),fe.length>0&&mc(fe,B,K),Re.length>0&&mc(Re,B,K),Q.buffers.depth.setTest(!0),Q.buffers.depth.setMask(!0),Q.buffers.color.setMask(!0),Q.setPolygonOffset(!1)}function iy(P,B,K,q){if((K.isScene===!0?K.overrideMaterial:null)!==null)return;m.state.transmissionRenderTarget[q.id]===void 0&&(m.state.transmissionRenderTarget[q.id]=new ms(1,1,{generateMipmaps:!0,type:j.has("EXT_color_buffer_half_float")||j.has("EXT_color_buffer_float")?ls:Yi,minFilter:Ti,samples:4,stencilBuffer:a,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:at.workingColorSpace}));const fe=m.state.transmissionRenderTarget[q.id],Re=q.viewport||R;fe.setSize(Re.z*b.transmissionResolutionScale,Re.w*b.transmissionResolutionScale);const Ne=b.getRenderTarget(),Oe=b.getActiveCubeFace(),je=b.getActiveMipmapLevel();b.setRenderTarget(fe),b.getClearColor(k),U=b.getClearAlpha(),U<1&&b.setClearColor(16777215,.5),b.clear(),xe&&Be.render(K);const et=b.toneMapping;b.toneMapping=Os;const We=q.viewport;if(q.viewport!==void 0&&(q.viewport=void 0),m.setupLightsView(q),ke===!0&&ye.setGlobalState(b.clippingPlanes,q),mc(P,K,q),ge.updateMultisampleRenderTarget(fe),ge.updateRenderTargetMipmap(fe),j.has("WEBGL_multisampled_render_to_texture")===!1){let wt=!1;for(let It=0,qt=B.length;It0),We=!!K.morphAttributes.position,wt=!!K.morphAttributes.normal,It=!!K.morphAttributes.color;let qt=Os;q.toneMapped&&(C===null||C.isXRRenderTarget===!0)&&(qt=b.toneMapping);const Ft=K.morphAttributes.position||K.morphAttributes.normal||K.morphAttributes.color,Dt=Ft!==void 0?Ft.length:0,Ke=ce.get(q),Gt=m.state.lights;if(ke===!0&&(Z===!0||P!==E)){const On=P===E&&q.id===w;ye.setState(q,P,On)}let St=!1;q.version===Ke.__version?(Ke.needsLights&&Ke.lightsStateVersion!==Gt.state.version||Ke.outputColorSpace!==Ne||z.isBatchedMesh&&Ke.batching===!1||!z.isBatchedMesh&&Ke.batching===!0||z.isBatchedMesh&&Ke.batchingColor===!0&&z.colorTexture===null||z.isBatchedMesh&&Ke.batchingColor===!1&&z.colorTexture!==null||z.isInstancedMesh&&Ke.instancing===!1||!z.isInstancedMesh&&Ke.instancing===!0||z.isSkinnedMesh&&Ke.skinning===!1||!z.isSkinnedMesh&&Ke.skinning===!0||z.isInstancedMesh&&Ke.instancingColor===!0&&z.instanceColor===null||z.isInstancedMesh&&Ke.instancingColor===!1&&z.instanceColor!==null||z.isInstancedMesh&&Ke.instancingMorph===!0&&z.morphTexture===null||z.isInstancedMesh&&Ke.instancingMorph===!1&&z.morphTexture!==null||Ke.envMap!==Oe||q.fog===!0&&Ke.fog!==fe||Ke.numClippingPlanes!==void 0&&(Ke.numClippingPlanes!==ye.numPlanes||Ke.numIntersection!==ye.numIntersection)||Ke.vertexAlphas!==je||Ke.vertexTangents!==et||Ke.morphTargets!==We||Ke.morphNormals!==wt||Ke.morphColors!==It||Ke.toneMapping!==qt||Ke.morphTargetsCount!==Dt)&&(St=!0):(St=!0,Ke.__version=q.version);let ri=Ke.currentProgram;St===!0&&(ri=_c(q,B,z));let gr=!1,oi=!1,No=!1;const $t=ri.getUniforms(),mi=Ke.uniforms;if(Q.useProgram(ri.program)&&(gr=!0,oi=!0,No=!0),q.id!==w&&(w=q.id,oi=!0),gr||E!==P){Q.buffers.depth.getReversed()&&P.reversedDepth!==!0&&(P._reversedDepth=!0,P.updateProjectionMatrix()),$t.setValue(L,"projectionMatrix",P.projectionMatrix),$t.setValue(L,"viewMatrix",P.matrixWorldInverse);const $n=$t.map.cameraPosition;$n!==void 0&&$n.setValue(L,Se.setFromMatrixPosition(P.matrixWorld)),Y.logarithmicDepthBuffer&&$t.setValue(L,"logDepthBufFC",2/(Math.log(P.far+1)/Math.LN2)),(q.isMeshPhongMaterial||q.isMeshToonMaterial||q.isMeshLambertMaterial||q.isMeshBasicMaterial||q.isMeshStandardMaterial||q.isShaderMaterial)&&$t.setValue(L,"isOrthographic",P.isOrthographicCamera===!0),E!==P&&(E=P,oi=!0,No=!0)}if(z.isSkinnedMesh){$t.setOptional(L,z,"bindMatrix"),$t.setOptional(L,z,"bindMatrixInverse");const On=z.skeleton;On&&(On.boneTexture===null&&On.computeBoneTexture(),$t.setValue(L,"boneTexture",On.boneTexture,ge))}z.isBatchedMesh&&($t.setOptional(L,z,"batchingTexture"),$t.setValue(L,"batchingTexture",z._matricesTexture,ge),$t.setOptional(L,z,"batchingIdTexture"),$t.setValue(L,"batchingIdTexture",z._indirectTexture,ge),$t.setOptional(L,z,"batchingColorTexture"),z._colorsTexture!==null&&$t.setValue(L,"batchingColorTexture",z._colorsTexture,ge));const _i=K.morphAttributes;if((_i.position!==void 0||_i.normal!==void 0||_i.color!==void 0)&&de.update(z,K,ri),(oi||Ke.receiveShadow!==z.receiveShadow)&&(Ke.receiveShadow=z.receiveShadow,$t.setValue(L,"receiveShadow",z.receiveShadow)),q.isMeshGouraudMaterial&&q.envMap!==null&&(mi.envMap.value=Oe,mi.flipEnvMap.value=Oe.isCubeTexture&&Oe.isRenderTargetTexture===!1?-1:1),q.isMeshStandardMaterial&&q.envMap===null&&B.environment!==null&&(mi.envMapIntensity.value=B.environmentIntensity),oi&&($t.setValue(L,"toneMappingExposure",b.toneMappingExposure),Ke.needsLights&&x1(mi,No),fe&&q.fog===!0&&le.refreshFogUniforms(mi,fe),le.refreshMaterialUniforms(mi,q,H,W,m.state.transmissionRenderTarget[P.id]),$u.upload(L,ay(Ke),mi,ge)),q.isShaderMaterial&&q.uniformsNeedUpdate===!0&&($u.upload(L,ay(Ke),mi,ge),q.uniformsNeedUpdate=!1),q.isSpriteMaterial&&$t.setValue(L,"center",z.center),$t.setValue(L,"modelViewMatrix",z.modelViewMatrix),$t.setValue(L,"normalMatrix",z.normalMatrix),$t.setValue(L,"modelMatrix",z.matrixWorld),q.isShaderMaterial||q.isRawShaderMaterial){const On=q.uniformsGroups;for(let $n=0,hf=On.length;$n0&&ge.useMultisampledRTT(P)===!1?z=ce.get(P).__webglMultisampledFramebuffer:Array.isArray(et)?z=et[K]:z=et,R.copy(P.viewport),D.copy(P.scissor),O=P.scissorTest}else R.copy(pe).multiplyScalar(H).floor(),D.copy(Ie).multiplyScalar(H).floor(),O=De;if(K!==0&&(z=S1),Q.bindFramebuffer(L.FRAMEBUFFER,z)&&q&&Q.drawBuffers(P,z),Q.viewport(R),Q.scissor(D),Q.setScissorTest(O),fe){const Oe=ce.get(P.texture);L.framebufferTexture2D(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_CUBE_MAP_POSITIVE_X+B,Oe.__webglTexture,K)}else if(Re){const Oe=B;for(let je=0;je=0&&B<=P.width-q&&K>=0&&K<=P.height-z&&(P.textures.length>1&&L.readBuffer(L.COLOR_ATTACHMENT0+Ne),L.readPixels(B,K,q,z,Ve.convert(et),Ve.convert(We),fe))}finally{const je=C!==null?ce.get(C).__webglFramebuffer:null;Q.bindFramebuffer(L.FRAMEBUFFER,je)}}},this.readRenderTargetPixelsAsync=async function(P,B,K,q,z,fe,Re,Ne=0){if(!(P&&P.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Oe=ce.get(P).__webglFramebuffer;if(P.isWebGLCubeRenderTarget&&Re!==void 0&&(Oe=Oe[Re]),Oe)if(B>=0&&B<=P.width-q&&K>=0&&K<=P.height-z){Q.bindFramebuffer(L.FRAMEBUFFER,Oe);const je=P.textures[Ne],et=je.format,We=je.type;if(!Y.textureFormatReadable(et))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Y.textureTypeReadable(We))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const wt=L.createBuffer();L.bindBuffer(L.PIXEL_PACK_BUFFER,wt),L.bufferData(L.PIXEL_PACK_BUFFER,fe.byteLength,L.STREAM_READ),P.textures.length>1&&L.readBuffer(L.COLOR_ATTACHMENT0+Ne),L.readPixels(B,K,q,z,Ve.convert(et),Ve.convert(We),0);const It=C!==null?ce.get(C).__webglFramebuffer:null;Q.bindFramebuffer(L.FRAMEBUFFER,It);const qt=L.fenceSync(L.SYNC_GPU_COMMANDS_COMPLETE,0);return L.flush(),await VC(L,qt,4),L.bindBuffer(L.PIXEL_PACK_BUFFER,wt),L.getBufferSubData(L.PIXEL_PACK_BUFFER,0,fe),L.deleteBuffer(wt),L.deleteSync(qt),fe}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(P,B=null,K=0){const q=Math.pow(2,-K),z=Math.floor(P.image.width*q),fe=Math.floor(P.image.height*q),Re=B!==null?B.x:0,Ne=B!==null?B.y:0;ge.setTexture2D(P,0),L.copyTexSubImage2D(L.TEXTURE_2D,K,0,0,Re,Ne,z,fe),Q.unbindTexture()};const T1=L.createFramebuffer(),M1=L.createFramebuffer();this.copyTextureToTexture=function(P,B,K=null,q=null,z=0,fe=null){fe===null&&(z!==0?(Vl("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),fe=z,z=0):fe=0);let Re,Ne,Oe,je,et,We,wt,It,qt;const Ft=P.isCompressedTexture?P.mipmaps[fe]:P.image;if(K!==null)Re=K.max.x-K.min.x,Ne=K.max.y-K.min.y,Oe=K.isBox3?K.max.z-K.min.z:1,je=K.min.x,et=K.min.y,We=K.isBox3?K.min.z:0;else{const _i=Math.pow(2,-z);Re=Math.floor(Ft.width*_i),Ne=Math.floor(Ft.height*_i),P.isDataArrayTexture?Oe=Ft.depth:P.isData3DTexture?Oe=Math.floor(Ft.depth*_i):Oe=1,je=0,et=0,We=0}q!==null?(wt=q.x,It=q.y,qt=q.z):(wt=0,It=0,qt=0);const Dt=Ve.convert(B.format),Ke=Ve.convert(B.type);let Gt;B.isData3DTexture?(ge.setTexture3D(B,0),Gt=L.TEXTURE_3D):B.isDataArrayTexture||B.isCompressedArrayTexture?(ge.setTexture2DArray(B,0),Gt=L.TEXTURE_2D_ARRAY):(ge.setTexture2D(B,0),Gt=L.TEXTURE_2D),L.pixelStorei(L.UNPACK_FLIP_Y_WEBGL,B.flipY),L.pixelStorei(L.UNPACK_PREMULTIPLY_ALPHA_WEBGL,B.premultiplyAlpha),L.pixelStorei(L.UNPACK_ALIGNMENT,B.unpackAlignment);const St=L.getParameter(L.UNPACK_ROW_LENGTH),ri=L.getParameter(L.UNPACK_IMAGE_HEIGHT),gr=L.getParameter(L.UNPACK_SKIP_PIXELS),oi=L.getParameter(L.UNPACK_SKIP_ROWS),No=L.getParameter(L.UNPACK_SKIP_IMAGES);L.pixelStorei(L.UNPACK_ROW_LENGTH,Ft.width),L.pixelStorei(L.UNPACK_IMAGE_HEIGHT,Ft.height),L.pixelStorei(L.UNPACK_SKIP_PIXELS,je),L.pixelStorei(L.UNPACK_SKIP_ROWS,et),L.pixelStorei(L.UNPACK_SKIP_IMAGES,We);const $t=P.isDataArrayTexture||P.isData3DTexture,mi=B.isDataArrayTexture||B.isData3DTexture;if(P.isDepthTexture){const _i=ce.get(P),On=ce.get(B),$n=ce.get(_i.__renderTarget),hf=ce.get(On.__renderTarget);Q.bindFramebuffer(L.READ_FRAMEBUFFER,$n.__webglFramebuffer),Q.bindFramebuffer(L.DRAW_FRAMEBUFFER,hf.__webglFramebuffer);for(let _a=0;_aMath.PI&&(i-=Xn),s<-Math.PI?s+=Xn:s>Math.PI&&(s-=Xn),i<=s?this._spherical.theta=Math.max(i,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(i+s)/2?Math.max(i,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let a=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const r=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),a=r!=this._spherical.radius}if(ln.setFromSpherical(this._spherical),ln.applyQuaternion(this._quatInverse),t.copy(this.target).add(ln),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let r=null;if(this.object.isPerspectiveCamera){const o=ln.length();r=this._clampDistance(o*this._scale);const l=o-r;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),a=!!l}else if(this.object.isOrthographicCamera){const o=new S(this._mouse.x,this._mouse.y,0);o.unproject(this.object);const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),a=l!==this.object.zoom;const c=new S(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(o),this.object.updateMatrixWorld(),r=ln.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;r!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(r).add(this.object.position):(lu.origin.copy(this.object.position),lu.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(lu.direction))sp||8*(1-this._lastQuaternion.dot(this.object.quaternion))>sp||this._lastTargetPosition.distanceToSquared(this.target)>sp?(this.dispatchEvent(H0),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Xn/60*this.autoRotateSpeed*e:Xn/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){ln.setFromMatrixColumn(t,0),ln.multiplyScalar(-e),this._panOffset.add(ln)}_panUp(e,t){this.screenSpacePanning===!0?ln.setFromMatrixColumn(t,1):(ln.setFromMatrixColumn(t,0),ln.crossVectors(this.object.up,ln)),ln.multiplyScalar(e),this._panOffset.add(ln)}_pan(e,t){const i=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;ln.copy(s).sub(this.target);let a=ln.length();a*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*a/i.clientHeight,this.object.matrix),this._panUp(2*t*a/i.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/i.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/i.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const i=this.domElement.getBoundingClientRect(),s=e-i.left,a=t-i.top,r=i.width,o=i.height;this._mouse.x=s/r*2-1,this._mouse.y=-(a/o)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Xn*this._rotateDelta.x/t.clientHeight),this._rotateUp(Xn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(Xn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-Xn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(Xn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-Xn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(i,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(i,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,s=e.pageY-t.y,a=Math.sqrt(i*i+s*s);this._dollyStart.set(0,a)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const i=this._getSecondPointerPosition(e),s=.5*(e.pageX+i.x),a=.5*(e.pageY+i.y);this._rotateEnd.set(s,a)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Xn*this._rotateDelta.x/t.clientHeight),this._rotateUp(Xn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(i,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,s=e.pageY-t.y,a=Math.sqrt(i*i+s*s);this._dollyEnd.set(0,a),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const r=(e.pageX+t.x)*.5,o=(e.pageY+t.y)*.5;this._updateZoomParameters(r,o)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t(O=F.indexOf(` -`))&&k=C.byteLength||!(U=d(C)))&&r(1,"no header found"),(F=U.match(w))||r(3,"bad initial token"),k.valid|=1,k.programtype=F[1],k.string+=U+` -`;U=d(C),U!==!1;){if(k.string+=U+` -`,U.charAt(0)==="#"){k.comments+=U+` -`;continue}if((F=U.match(E))&&(k.gamma=parseFloat(F[1])),(F=U.match(R))&&(k.exposure=parseFloat(F[1])),(F=U.match(D))&&(k.valid|=2,k.format=F[1]),(F=U.match(O))&&(k.valid|=4,k.height=parseInt(F[1],10),k.width=parseInt(F[2],10)),k.valid&2&&k.valid&4)break}return k.valid&2||r(3,"missing format specifier"),k.valid&4||r(3,"missing image size specifier"),k},f=function(C,w,E){const R=w;if(R<8||R>32767||C[0]!==2||C[1]!==2||C[2]&128)return new Uint8Array(C);R!==(C[2]<<8|C[3])&&r(3,"wrong scanline width");const D=new Uint8Array(4*w*E);D.length||r(4,"unable to allocate buffer space");let O=0,k=0;const U=4*R,F=new Uint8Array(4),W=new Uint8Array(U);let H=E;for(;H>0&&kC.byteLength&&r(1),F[0]=C[k++],F[1]=C[k++],F[2]=C[k++],F[3]=C[k++],(F[0]!=2||F[1]!=2||(F[2]<<8|F[3])!=R)&&r(3,"bad rgbe scanline format");let ne=0,oe;for(;ne128;if(Ie&&(oe-=128),(oe===0||ne+oe>U)&&r(3,"bad scanline data"),Ie){const De=C[k++];for(let Xe=0;Xe{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(const t of e)t.dispose()}}function Br(n){return new qh({color:0,emissive:16777215,emissiveIntensity:n})}let cT=null;function pk(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof window<"u"&&window.location?.href?window.location.href:import.meta.url}function mk(){return"./"}function _k(n){return/^[a-z][a-z\d+\-.]*:/i.test(n)||n.startsWith("//")}function gk(n=cT){const e=n==null||n===""?mk():String(n);return new URL(e,pk()).href}function wi(n,e=cT){const t=String(n);return _k(t)?t:new URL(t.replace(/^\/+/,""),gk(e)).href}class yk{constructor(e,t={}){if(this.container=typeof e=="string"?document.getElementById(e):e,this.assetBase=t.assetBase,!this.container){console.error("Invalid container passed to SceneManager");return}this.scene=new ac,this.scene.background=new ue(8900331);const i=this.container.clientWidth,s=this.container.clientHeight;this.camera=new Jt(75,i/s,10,5e4),this.camera.position.set(0,2e3,5e3),this.renderer=new Eg({antialias:!0,preserveDrawingBuffer:t.preserveDrawingBuffer===!0}),this.renderer.setSize(i,s),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=U_,this.renderer.toneMapping=z_,this.renderer.toneMappingExposure=1,this.renderer.outputColorSpace=gt,this.container.appendChild(this.renderer.domElement),window.addEventListener("resize",()=>this.onWindowResize())}initDefaultEnvironment(){if(!this._neutralEnvTexture){const e=new Jd(this.renderer);this._neutralEnvTexture=e.fromScene(new fk,.04).texture,e.dispose()}if(this.scene.environment=this._neutralEnvTexture,!this._defaultLightsAdded){const e=new Do(16777215,1.5);e.position.set(3e3,8e3,4e3),this.scene.add(e);const t=new dc(16777215,.4);this.scene.add(t),this._defaultLightsAdded=!0}}applyEnvironment(e){return new Promise(t=>{const i=new hk,s=wi(e.skyboxUrl,this.assetBase);i.load(s,a=>{this.scene.background&&this.scene.background.dispose&&this.scene.background.dispose(),a.mapping=ar,this.scene.background=a,this.scene.environment=a,this.currentEnvironmentId=e.id;const r=e.rotation??{};this._skyboxBaseRotation={x:vt.degToRad(r.x??0),y:vt.degToRad(r.y??0),z:vt.degToRad(r.z??0)},this._skyboxAnimatedY=0,this._skyboxAnimation=e.animation??null,this._applySkyboxRotation(),typeof e.exposure=="number"&&(this.renderer.toneMappingExposure=e.exposure),console.log(`[SceneManager] environment applied: ${e.id}`),t(!0)},void 0,a=>{console.error(`[SceneManager] Failed to load environment "${e.id}":`,a),t(!1)})})}_applySkyboxRotation(){const e=this._skyboxBaseRotation;if(!e)return;const t=e.y+(this._skyboxAnimatedY??0);this.scene.backgroundRotation&&this.scene.backgroundRotation.set(e.x,t,e.z),this.scene.environmentRotation&&this.scene.environmentRotation.set(e.x,t,e.z)}updateSkyboxAnimation(e){const t=this._skyboxAnimation;!t||!t.enabled||!e||(this._skyboxAnimatedY=(this._skyboxAnimatedY??0)+vt.degToRad(t.speed*e),this._applySkyboxRotation())}setDefaultBackground(){this.scene.background&&this.scene.background.dispose&&this.scene.background.dispose(),this.scene.background=new ue(1710638),this.initDefaultEnvironment(),this.renderer.toneMappingExposure=1,this._skyboxAnimation=null,this._skyboxBaseRotation=null,this.currentEnvironmentId=null,console.log("[SceneManager] Using neutral default environment (no skybox)")}setExposure(e){this.renderer&&(this.renderer.toneMappingExposure=e)}onWindowResize(){if(!this.container||!this.renderer)return;const e=this.container.clientWidth,t=this.container.clientHeight;this.camera.aspect=e/t,this.camera.updateProjectionMatrix(),this.renderer.setSize(e,t)}render(){this.renderer&&this.renderer.render(this.scene,this.camera)}dispose(){this.renderer&&(this.renderer.dispose(),this.renderer.domElement&&this.renderer.domElement.parentNode&&this.renderer.domElement.parentNode.removeChild(this.renderer.domElement),this.renderer=null)}}function G0(n,e){if(e===Jw)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),n;if(e===Kd||e===Y_){let t=n.getIndex();if(t===null){const r=[],o=n.getAttribute("position");if(o!==void 0){for(let l=0;l=2.0 are supported."));return}const c=new Zk(a,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let u=0;u=0&&o[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}c.setExtensions(r),c.setPlugins(o),c.parse(i,s)}parseAsync(e,t){const i=this;return new Promise(function(s,a){i.parse(e,t,s,a)})}}function vk(){let n={};return{get:function(e){return n[e]},add:function(e,t){n[e]=t},remove:function(e){delete n[e]},removeAll:function(){n={}}}}const xt={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class bk{constructor(e){this.parser=e,this.name=xt.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let i=0,s=t.length;i=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,a.source,r)}}class kk{constructor(e){this.parser=e,this.name=xt.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,i=this.parser,s=i.json,a=s.textures[e];if(!a.extensions||!a.extensions[t])return null;const r=a.extensions[t],o=s.images[r.source];let l=i.textureLoader;if(o.uri){const c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,r.source,l)}}class Ok{constructor(e){this.parser=e,this.name=xt.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,i=this.parser,s=i.json,a=s.textures[e];if(!a.extensions||!a.extensions[t])return null;const r=a.extensions[t],o=s.images[r.source];let l=i.textureLoader;if(o.uri){const c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,r.source,l)}}class Fk{constructor(e){this.name=xt.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,i=t.bufferViews[e];if(i.extensions&&i.extensions[this.name]){const s=i.extensions[this.name],a=this.parser.getDependency("buffer",s.buffer),r=this.parser.options.meshoptDecoder;if(!r||!r.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return a.then(function(o){const l=s.byteOffset||0,c=s.byteLength||0,u=s.count,d=s.byteStride,h=new Uint8Array(o,l,c);return r.decodeGltfBufferAsync?r.decodeGltfBufferAsync(u,d,h,s.mode,s.filter).then(function(f){return f.buffer}):r.ready.then(function(){const f=new ArrayBuffer(u*d);return r.decodeGltfBuffer(new Uint8Array(f),u,d,h,s.mode,s.filter),f})})}else return null}}class Nk{constructor(e){this.name=xt.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,i=t.nodes[e];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;const s=t.meshes[i.mesh];for(const c of s.primitives)if(c.mode!==xi.TRIANGLES&&c.mode!==xi.TRIANGLE_STRIP&&c.mode!==xi.TRIANGLE_FAN&&c.mode!==void 0)return null;const r=i.extensions[this.name].attributes,o=[],l={};for(const c in r)o.push(this.parser.getDependency("accessor",r[c]).then(u=>(l[c]=u,l[c])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(c=>{const u=c.pop(),d=u.isGroup?u.children:[u],h=c[0].count,f=[];for(const p of d){const g=new Me,_=new S,m=new dt,v=new S(1,1,1),y=new kh(p.geometry,p.material,h);for(let b=0;b0||n.search(/^data\:image\/jpeg/)===0?"image/jpeg":n.search(/\.webp($|\?)/i)>0||n.search(/^data\:image\/webp/)===0?"image/webp":n.search(/\.ktx2($|\?)/i)>0||n.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const jk=new Me;class Zk{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new vk,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let i=!1,s=-1,a=!1,r=-1;if(typeof navigator<"u"){const o=navigator.userAgent;i=/^((?!chrome|android).)*safari/i.test(o)===!0;const l=o.match(/Version\/(\d+)/);s=i&&l?parseInt(l[1],10):-1,a=o.indexOf("Firefox")>-1,r=a?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||i&&s<17||a&&r<98?this.textureLoader=new Yh(this.options.manager):this.textureLoader=new qS(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Gn(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const i=this,s=this.json,a=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(r){return r._markDefs&&r._markDefs()}),Promise.all(this._invokeAll(function(r){return r.beforeRoot&&r.beforeRoot()})).then(function(){return Promise.all([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])}).then(function(r){const o={scene:r[0][s.scene||0],scenes:r[0],animations:r[1],cameras:r[2],asset:s.asset,parser:i,userData:{}};return Ia(a,o,s),rs(o,s),Promise.all(i._invokeAll(function(l){return l.afterRoot&&l.afterRoot(o)})).then(function(){for(const l of o.scenes)l.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let s=0,a=t.length;s{const l=this.associations.get(r);l!=null&&this.associations.set(o,l);for(const[c,u]of r.children.entries())a(u,o.children[c])};return a(i,s),s.name+="_instance_"+e.uses[t]++,s}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let i=0;i=2&&_.setY(w,x[M*l+1]),l>=3&&_.setZ(w,x[M*l+2]),l>=4&&_.setW(w,x[M*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}_.normalized=p}return _})}loadTexture(e){const t=this.json,i=this.options,a=t.textures[e].source,r=t.images[a];let o=this.textureLoader;if(r.uri){const l=i.manager.getHandler(r.uri);l!==null&&(o=l)}return this.loadTextureImage(e,a,o)}loadTextureImage(e,t,i){const s=this,a=this.json,r=a.textures[e],o=a.images[t],l=(o.uri||o.bufferView)+":"+r.sampler;if(this.textureCache[l])return this.textureCache[l];const c=this.loadImageSource(t,i).then(function(u){u.flipY=!1,u.name=r.name||o.name||"",u.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(u.name=o.uri);const h=(a.samplers||{})[r.sampler]||{};return u.magFilter=W0[h.magFilter]||Vt,u.minFilter=W0[h.minFilter]||Ti,u.wrapS=X0[h.wrapS]||ps,u.wrapT=X0[h.wrapT]||ps,u.generateMipmaps=!u.isCompressedTexture&&u.minFilter!==dn&&u.minFilter!==Vt,s.associations.set(u,{textures:e}),u}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){const i=this,s=this.json,a=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(d=>d.clone());const r=s.images[e],o=self.URL||self.webkitURL;let l=r.uri||"",c=!1;if(r.bufferView!==void 0)l=i.getDependency("bufferView",r.bufferView).then(function(d){c=!0;const h=new Blob([d],{type:r.mimeType});return l=o.createObjectURL(h),l});else if(r.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const u=Promise.resolve(l).then(function(d){return new Promise(function(h,f){let p=h;t.isImageBitmapLoader===!0&&(p=function(g){const _=new Bt(g);_.needsUpdate=!0,h(_)}),t.load(Us.resolveURL(d,a.path),p,void 0,f)})}).then(function(d){return c===!0&&o.revokeObjectURL(l),rs(d,r),d.userData.mimeType=r.mimeType||Yk(r.uri),d}).catch(function(d){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),d});return this.sourceCache[e]=u,u}assignTexture(e,t,i,s){const a=this;return this.getDependency("texture",i.index).then(function(r){if(!r)return null;if(i.texCoord!==void 0&&i.texCoord>0&&(r=r.clone(),r.channel=i.texCoord),a.extensions[xt.KHR_TEXTURE_TRANSFORM]){const o=i.extensions!==void 0?i.extensions[xt.KHR_TEXTURE_TRANSFORM]:void 0;if(o){const l=a.associations.get(r);r=a.extensions[xt.KHR_TEXTURE_TRANSFORM].extendTexture(r,o),a.associations.set(r,l)}}return s!==void 0&&(r.colorSpace=s),e[t]=r,r})}assignFinalMaterial(e){const t=e.geometry;let i=e.material;const s=t.attributes.tangent===void 0,a=t.attributes.color!==void 0,r=t.attributes.normal===void 0;if(e.isPoints){const o="PointsMaterial:"+i.uuid;let l=this.cache.get(o);l||(l=new sa,Qt.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,l.sizeAttenuation=!1,this.cache.add(o,l)),i=l}else if(e.isLine){const o="LineBasicMaterial:"+i.uuid;let l=this.cache.get(o);l||(l=new Rt,Qt.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,this.cache.add(o,l)),i=l}if(s||a||r){let o="ClonedMaterial:"+i.uuid+":";s&&(o+="derivative-tangents:"),a&&(o+="vertex-colors:"),r&&(o+="flat-shading:");let l=this.cache.get(o);l||(l=i.clone(),a&&(l.vertexColors=!0),r&&(l.flatShading=!0),s&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(o,l),this.associations.set(l,this.associations.get(i))),i=l}e.material=i}getMaterialType(){return Pn}loadMaterial(e){const t=this,i=this.json,s=this.extensions,a=i.materials[e];let r;const o={},l=a.extensions||{},c=[];if(l[xt.KHR_MATERIALS_UNLIT]){const d=s[xt.KHR_MATERIALS_UNLIT];r=d.getMaterialType(),c.push(d.extendParams(o,a,t))}else{const d=a.pbrMetallicRoughness||{};if(o.color=new ue(1,1,1),o.opacity=1,Array.isArray(d.baseColorFactor)){const h=d.baseColorFactor;o.color.setRGB(h[0],h[1],h[2],xn),o.opacity=h[3]}d.baseColorTexture!==void 0&&c.push(t.assignTexture(o,"map",d.baseColorTexture,gt)),o.metalness=d.metallicFactor!==void 0?d.metallicFactor:1,o.roughness=d.roughnessFactor!==void 0?d.roughnessFactor:1,d.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,"metalnessMap",d.metallicRoughnessTexture)),c.push(t.assignTexture(o,"roughnessMap",d.metallicRoughnessTexture))),r=this._invokeOne(function(h){return h.getMaterialType&&h.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(h){return h.extendMaterialParams&&h.extendMaterialParams(e,o)})))}a.doubleSided===!0&&(o.side=ct);const u=a.alphaMode||rp.OPAQUE;if(u===rp.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,u===rp.MASK&&(o.alphaTest=a.alphaCutoff!==void 0?a.alphaCutoff:.5)),a.normalTexture!==void 0&&r!==Ye&&(c.push(t.assignTexture(o,"normalMap",a.normalTexture)),o.normalScale=new te(1,1),a.normalTexture.scale!==void 0)){const d=a.normalTexture.scale;o.normalScale.set(d,d)}if(a.occlusionTexture!==void 0&&r!==Ye&&(c.push(t.assignTexture(o,"aoMap",a.occlusionTexture)),a.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=a.occlusionTexture.strength)),a.emissiveFactor!==void 0&&r!==Ye){const d=a.emissiveFactor;o.emissive=new ue().setRGB(d[0],d[1],d[2],xn)}return a.emissiveTexture!==void 0&&r!==Ye&&c.push(t.assignTexture(o,"emissiveMap",a.emissiveTexture,gt)),Promise.all(c).then(function(){const d=new r(o);return a.name&&(d.name=a.name),rs(d,a),t.associations.set(d,{materials:e}),a.extensions&&Ia(s,d,a),d})}createUniqueName(e){const t=yt.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,i=this.extensions,s=this.primitiveCache;function a(o){return i[xt.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(l){return K0(l,o,t)})}const r=[];for(let o=0,l=e.length;o0&&Kk(m,a),m.name=t.createUniqueName(a.name||"mesh_"+e),rs(m,a),_.extensions&&Ia(s,m,_),t.assignFinalMaterial(m),d.push(m)}for(let f=0,p=d.length;f1?u=new Mt:c.length===1?u=c[0]:u=new Qe,u!==c[0])for(let d=0,h=c.length;d1){const d=s.associations.get(u);s.associations.set(u,{...d})}return s.associations.get(u).nodes=e,u}),this.nodeCache[e]}loadScene(e){const t=this.extensions,i=this.json.scenes[e],s=this,a=new Mt;i.name&&(a.name=s.createUniqueName(i.name)),rs(a,i),i.extensions&&Ia(t,a,i);const r=i.nodes||[],o=[];for(let l=0,c=r.length;l{const d=new Map;for(const[h,f]of s.associations)(h instanceof Qt||h instanceof Bt)&&d.set(h,f);return u.traverse(h=>{const f=s.associations.get(h);f!=null&&d.set(h,f)}),d};return s.associations=c(a),a})}_createAnimationTracks(e,t,i,s,a){const r=[],o=e.name?e.name:e.uuid,l=[];Ys[a.path]===Ys.weights?e.traverse(function(h){h.morphTargetInfluences&&l.push(h.name?h.name:h.uuid)}):l.push(o);let c;switch(Ys[a.path]){case Ys.weights:c=ca;break;case Ys.rotation:c=_s;break;case Ys.translation:case Ys.scale:c=Hs;break;default:i.itemSize===1?c=ca:c=Hs;break}const u=s.interpolation!==void 0?$k[s.interpolation]:rr,d=this._getArrayFromAccessor(i);for(let h=0,f=l.length;h{this.parse(r,t,s)},i,s)}parse(e,t,i=()=>{}){this.decodeDracoFile(e,t,null,null,gt,i).catch(i)}decodeDracoFile(e,t,i,s,a=xn,r=()=>{}){const o={attributeIDs:i||this.defaultAttributeIDs,attributeTypes:s||this.defaultAttributeTypes,useUniqueIDs:!!i,vertexColorSpace:a};return this.decodeGeometry(e,o).then(t).catch(r)}decodeGeometry(e,t){const i=JSON.stringify(t);if(lp.has(e)){const l=lp.get(e);if(l.key===i)return l.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let s;const a=this.workerNextTaskID++,r=e.byteLength,o=this._getWorker(a,r).then(l=>(s=l,new Promise((c,u)=>{s._callbacks[a]={resolve:c,reject:u},s.postMessage({type:"decode",id:a,taskConfig:t,buffer:e},[e])}))).then(l=>this._createGeometry(l.geometry));return o.catch(()=>!0).then(()=>{s&&a&&this._releaseTask(s,a)}),lp.set(e,{key:i,promise:o}),o}_createGeometry(e){const t=new Ge;e.index&&t.setIndex(new rt(e.index.array,1));for(let i=0;i{i.load(e,s,void 0,a)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(i=>{const s=i[0];e||(this.decoderConfig.wasmBinary=i[1]);const a=Qk.toString(),r=["/* draco decoder */",s,"","/* worker */",a.substring(a.indexOf("{")+1,a.lastIndexOf("}"))].join(` -`);this.workerSourceURL=URL.createObjectURL(new Blob([r]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.lengtha._taskLoad?-1:1});const i=this.workerPool[this.workerPool.length-1];return i._taskCosts[e]=t,i._taskLoad+=t,i})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e{const d=u.draco,h=new d.Decoder;try{const f=t(d,h,new Int8Array(l),c),p=f.attributes.map(g=>g.array.buffer);f.index&&p.push(f.index.array.buffer),self.postMessage({type:"decode",id:o.id,geometry:f},p)}catch(f){console.error(f),self.postMessage({type:"error",id:o.id,error:f.message})}finally{d.destroy(h)}});break}};function t(r,o,l,c){const u=c.attributeIDs,d=c.attributeTypes;let h,f;const p=o.GetEncodedGeometryType(l);if(p===r.TRIANGULAR_MESH)h=new r.Mesh,f=o.DecodeArrayToMesh(l,l.byteLength,h);else if(p===r.POINT_CLOUD)h=new r.PointCloud,f=o.DecodeArrayToPointCloud(l,l.byteLength,h);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!f.ok()||h.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+f.error_msg());const g={index:null,attributes:[]};for(const _ in u){const m=self[d[_]];let v,y;if(c.useUniqueIDs)y=u[_],v=o.GetAttributeByUniqueId(h,y);else{if(y=o.GetAttributeId(h,r[u[_]]),y===-1)continue;v=o.GetAttribute(h,y)}const b=s(r,o,h,_,m,v);_==="color"&&(b.vertexColorSpace=c.vertexColorSpace),g.attributes.push(b)}return p===r.TRIANGULAR_MESH&&(g.index=i(r,o,h)),r.destroy(h),g}function i(r,o,l){const u=l.num_faces()*3,d=u*4,h=r._malloc(d);o.GetTrianglesUInt32Array(l,d,h);const f=new Uint32Array(r.HEAPF32.buffer,h,u).slice();return r._free(h),{array:f,itemSize:1}}function s(r,o,l,c,u,d){const h=d.num_components(),p=l.num_points()*h,g=p*u.BYTES_PER_ELEMENT,_=a(r,u),m=r._malloc(g);o.GetAttributeDataArrayForAllPoints(l,d,_,g,m);const v=new u(r.HEAPF32.buffer,m,p).slice();return r._free(m),{name:c,array:v,itemSize:h}}function a(r,o){switch(o){case Float32Array:return r.DT_FLOAT32;case Int8Array:return r.DT_INT8;case Int16Array:return r.DT_INT16;case Int32Array:return r.DT_INT32;case Uint8Array:return r.DT_UINT8;case Uint16Array:return r.DT_UINT16;case Uint32Array:return r.DT_UINT32}}}const eO=/^[og]\s*(.+)?/,tO=/^mtllib /,nO=/^usemtl /,iO=/^usemap /,q0=/\s+/,Y0=new S,cp=new S,j0=new S,Z0=new S,yi=new S,cu=new ue;function sO(){const n={objects:[],object:{},vertices:[],normals:[],colors:[],uvs:[],materials:{},materialLibraries:[],startObject:function(e,t){if(this.object&&this.object.fromDeclaration===!1){this.object.name=e,this.object.fromDeclaration=t!==!1;return}const i=this.object&&typeof this.object.currentMaterial=="function"?this.object.currentMaterial():void 0;if(this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0),this.object={name:e||"",fromDeclaration:t!==!1,geometry:{vertices:[],normals:[],colors:[],uvs:[],hasUVIndices:!1},materials:[],smooth:!0,startMaterial:function(s,a){const r=this._finalize(!1);r&&(r.inherited||r.groupCount<=0)&&this.materials.splice(r.index,1);const o={index:this.materials.length,name:s||"",mtllib:Array.isArray(a)&&a.length>0?a[a.length-1]:"",smooth:r!==void 0?r.smooth:this.smooth,groupStart:r!==void 0?r.groupEnd:0,groupEnd:-1,groupCount:-1,inherited:!1,clone:function(l){const c={index:typeof l=="number"?l:this.index,name:this.name,mtllib:this.mtllib,smooth:this.smooth,groupStart:0,groupEnd:-1,groupCount:-1,inherited:!1};return c.clone=this.clone.bind(c),c}};return this.materials.push(o),o},currentMaterial:function(){if(this.materials.length>0)return this.materials[this.materials.length-1]},_finalize:function(s){const a=this.currentMaterial();if(a&&a.groupEnd===-1&&(a.groupEnd=this.geometry.vertices.length/3,a.groupCount=a.groupEnd-a.groupStart,a.inherited=!1),s&&this.materials.length>1)for(let r=this.materials.length-1;r>=0;r--)this.materials[r].groupCount<=0&&this.materials.splice(r,1);return s&&this.materials.length===0&&this.materials.push({name:"",smooth:this.smooth}),a}},i&&i.name&&typeof i.clone=="function"){const s=i.clone(0);s.inherited=!0,this.object.materials.push(s)}this.objects.push(this.object)},finalize:function(){this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0)},parseVertexIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseNormalIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseUVIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/2)*2},addVertex:function(e,t,i){const s=this.vertices,a=this.object.geometry.vertices;a.push(s[e+0],s[e+1],s[e+2]),a.push(s[t+0],s[t+1],s[t+2]),a.push(s[i+0],s[i+1],s[i+2])},addVertexPoint:function(e){const t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addVertexLine:function(e){const t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addNormal:function(e,t,i){const s=this.normals,a=this.object.geometry.normals;a.push(s[e+0],s[e+1],s[e+2]),a.push(s[t+0],s[t+1],s[t+2]),a.push(s[i+0],s[i+1],s[i+2])},addFaceNormal:function(e,t,i){const s=this.vertices,a=this.object.geometry.normals;Y0.fromArray(s,e),cp.fromArray(s,t),j0.fromArray(s,i),yi.subVectors(j0,cp),Z0.subVectors(Y0,cp),yi.cross(Z0),yi.normalize(),a.push(yi.x,yi.y,yi.z),a.push(yi.x,yi.y,yi.z),a.push(yi.x,yi.y,yi.z)},addColor:function(e,t,i){const s=this.colors,a=this.object.geometry.colors;s[e]!==void 0&&a.push(s[e+0],s[e+1],s[e+2]),s[t]!==void 0&&a.push(s[t+0],s[t+1],s[t+2]),s[i]!==void 0&&a.push(s[i+0],s[i+1],s[i+2])},addUV:function(e,t,i){const s=this.uvs,a=this.object.geometry.uvs;a.push(s[e+0],s[e+1]),a.push(s[t+0],s[t+1]),a.push(s[i+0],s[i+1])},addDefaultUV:function(){const e=this.object.geometry.uvs;e.push(0,0),e.push(0,0),e.push(0,0)},addUVLine:function(e){const t=this.uvs;this.object.geometry.uvs.push(t[e+0],t[e+1])},addFace:function(e,t,i,s,a,r,o,l,c){const u=this.vertices.length;let d=this.parseVertexIndex(e,u),h=this.parseVertexIndex(t,u),f=this.parseVertexIndex(i,u);if(this.addVertex(d,h,f),this.addColor(d,h,f),o!==void 0&&o!==""){const p=this.normals.length;d=this.parseNormalIndex(o,p),h=this.parseNormalIndex(l,p),f=this.parseNormalIndex(c,p),this.addNormal(d,h,f)}else this.addFaceNormal(d,h,f);if(s!==void 0&&s!==""){const p=this.uvs.length;d=this.parseUVIndex(s,p),h=this.parseUVIndex(a,p),f=this.parseUVIndex(r,p),this.addUV(d,h,f),this.object.geometry.hasUVIndices=!0}else this.addDefaultUV()},addPointGeometry:function(e){this.object.geometry.type="Points";const t=this.vertices.length;for(let i=0,s=e.length;i=0&&(x[X]=null,T[X].disconnect(Se))}for(let ae=0;ae=x.length){x.push(Se),X=xe;break}else if(x[xe]===null){x[xe]=Se,X=xe;break}if(X===-1)break}const ie=T[X];ie&&ie.connect(Se)}}const H=new S,ne=new S;function oe(Z,ae,Se){H.setFromMatrixPosition(ae.matrixWorld),ne.setFromMatrixPosition(Se.matrixWorld);const X=H.distanceTo(ne),ie=ae.projectionMatrix.elements,xe=Se.projectionMatrix.elements,Ae=ie[14]/(ie[10]-1),L=ie[14]/(ie[10]+1),G=(ie[9]+1)/ie[5],j=(ie[9]-1)/ie[5],Y=(ie[8]-1)/ie[0],Q=(xe[8]+1)/xe[0],_e=Ae*Y,ce=Ae*Q,ge=X/(-Y+Q),$e=ge*-Y;if(ae.matrixWorld.decompose(Z.position,Z.quaternion,Z.scale),Z.translateX($e),Z.translateZ(ge),Z.matrixWorld.compose(Z.position,Z.quaternion,Z.scale),Z.matrixWorldInverse.copy(Z.matrixWorld).invert(),ie[10]===-1)Z.projectionMatrix.copy(ae.projectionMatrix),Z.projectionMatrixInverse.copy(ae.projectionMatrixInverse);else{const it=Ae+ge,I=L+ge,A=_e-$e,V=ce+(X-$e),J=G*L/I*it,le=j*L/I*it;Z.projectionMatrix.makePerspective(A,V,J,le,it,I),Z.projectionMatrixInverse.copy(Z.projectionMatrix).invert()}}function pe(Z,ae){ae===null?Z.matrixWorld.copy(Z.matrix):Z.matrixWorld.multiplyMatrices(ae.matrixWorld,Z.matrix),Z.matrixWorldInverse.copy(Z.matrixWorld).invert()}this.updateCamera=function(Z){if(s===null)return;let ae=Z.near,Se=Z.far;_.texture!==null&&(_.depthNear>0&&(ae=_.depthNear),_.depthFar>0&&(Se=_.depthFar)),k.near=E.near=w.near=ae,k.far=E.far=w.far=Se,(O!==k.near||D!==k.far)&&(s.updateRenderState({depthNear:k.near,depthFar:k.far}),O=k.near,D=k.far),k.layers.mask=Z.layers.mask|6,w.layers.mask=k.layers.mask&3,E.layers.mask=k.layers.mask&5;const X=Z.parent,ie=k.cameras;pe(k,X);for(let xe=0;xe0&&(_.alphaTest.value=m.alphaTest);const v=e.get(m),y=v.envMap,b=v.envMapRotation;y&&(_.envMap.value=y,Ia.copy(b),Ia.x*=-1,Ia.y*=-1,Ia.z*=-1,y.isCubeTexture&&y.isRenderTargetTexture===!1&&(Ia.y*=-1,Ia.z*=-1),_.envMapRotation.value.setFromMatrix4(aD.makeRotationFromEuler(Ia)),_.flipEnvMap.value=y.isCubeTexture&&y.isRenderTargetTexture===!1?-1:1,_.reflectivity.value=m.reflectivity,_.ior.value=m.ior,_.refractionRatio.value=m.refractionRatio),m.lightMap&&(_.lightMap.value=m.lightMap,_.lightMapIntensity.value=m.lightMapIntensity,t(m.lightMap,_.lightMapTransform)),m.aoMap&&(_.aoMap.value=m.aoMap,_.aoMapIntensity.value=m.aoMapIntensity,t(m.aoMap,_.aoMapTransform))}function r(_,m){_.diffuse.value.copy(m.color),_.opacity.value=m.opacity,m.map&&(_.map.value=m.map,t(m.map,_.mapTransform))}function o(_,m){_.dashSize.value=m.dashSize,_.totalSize.value=m.dashSize+m.gapSize,_.scale.value=m.scale}function l(_,m,v,y){_.diffuse.value.copy(m.color),_.opacity.value=m.opacity,_.size.value=m.size*v,_.scale.value=y*.5,m.map&&(_.map.value=m.map,t(m.map,_.uvTransform)),m.alphaMap&&(_.alphaMap.value=m.alphaMap,t(m.alphaMap,_.alphaMapTransform)),m.alphaTest>0&&(_.alphaTest.value=m.alphaTest)}function c(_,m){_.diffuse.value.copy(m.color),_.opacity.value=m.opacity,_.rotation.value=m.rotation,m.map&&(_.map.value=m.map,t(m.map,_.mapTransform)),m.alphaMap&&(_.alphaMap.value=m.alphaMap,t(m.alphaMap,_.alphaMapTransform)),m.alphaTest>0&&(_.alphaTest.value=m.alphaTest)}function u(_,m){_.specular.value.copy(m.specular),_.shininess.value=Math.max(m.shininess,1e-4)}function d(_,m){m.gradientMap&&(_.gradientMap.value=m.gradientMap)}function h(_,m){_.metalness.value=m.metalness,m.metalnessMap&&(_.metalnessMap.value=m.metalnessMap,t(m.metalnessMap,_.metalnessMapTransform)),_.roughness.value=m.roughness,m.roughnessMap&&(_.roughnessMap.value=m.roughnessMap,t(m.roughnessMap,_.roughnessMapTransform)),m.envMap&&(_.envMapIntensity.value=m.envMapIntensity)}function f(_,m,v){_.ior.value=m.ior,m.sheen>0&&(_.sheenColor.value.copy(m.sheenColor).multiplyScalar(m.sheen),_.sheenRoughness.value=m.sheenRoughness,m.sheenColorMap&&(_.sheenColorMap.value=m.sheenColorMap,t(m.sheenColorMap,_.sheenColorMapTransform)),m.sheenRoughnessMap&&(_.sheenRoughnessMap.value=m.sheenRoughnessMap,t(m.sheenRoughnessMap,_.sheenRoughnessMapTransform))),m.clearcoat>0&&(_.clearcoat.value=m.clearcoat,_.clearcoatRoughness.value=m.clearcoatRoughness,m.clearcoatMap&&(_.clearcoatMap.value=m.clearcoatMap,t(m.clearcoatMap,_.clearcoatMapTransform)),m.clearcoatRoughnessMap&&(_.clearcoatRoughnessMap.value=m.clearcoatRoughnessMap,t(m.clearcoatRoughnessMap,_.clearcoatRoughnessMapTransform)),m.clearcoatNormalMap&&(_.clearcoatNormalMap.value=m.clearcoatNormalMap,t(m.clearcoatNormalMap,_.clearcoatNormalMapTransform),_.clearcoatNormalScale.value.copy(m.clearcoatNormalScale),m.side===un&&_.clearcoatNormalScale.value.negate())),m.dispersion>0&&(_.dispersion.value=m.dispersion),m.iridescence>0&&(_.iridescence.value=m.iridescence,_.iridescenceIOR.value=m.iridescenceIOR,_.iridescenceThicknessMinimum.value=m.iridescenceThicknessRange[0],_.iridescenceThicknessMaximum.value=m.iridescenceThicknessRange[1],m.iridescenceMap&&(_.iridescenceMap.value=m.iridescenceMap,t(m.iridescenceMap,_.iridescenceMapTransform)),m.iridescenceThicknessMap&&(_.iridescenceThicknessMap.value=m.iridescenceThicknessMap,t(m.iridescenceThicknessMap,_.iridescenceThicknessMapTransform))),m.transmission>0&&(_.transmission.value=m.transmission,_.transmissionSamplerMap.value=v.texture,_.transmissionSamplerSize.value.set(v.width,v.height),m.transmissionMap&&(_.transmissionMap.value=m.transmissionMap,t(m.transmissionMap,_.transmissionMapTransform)),_.thickness.value=m.thickness,m.thicknessMap&&(_.thicknessMap.value=m.thicknessMap,t(m.thicknessMap,_.thicknessMapTransform)),_.attenuationDistance.value=m.attenuationDistance,_.attenuationColor.value.copy(m.attenuationColor)),m.anisotropy>0&&(_.anisotropyVector.value.set(m.anisotropy*Math.cos(m.anisotropyRotation),m.anisotropy*Math.sin(m.anisotropyRotation)),m.anisotropyMap&&(_.anisotropyMap.value=m.anisotropyMap,t(m.anisotropyMap,_.anisotropyMapTransform))),_.specularIntensity.value=m.specularIntensity,_.specularColor.value.copy(m.specularColor),m.specularColorMap&&(_.specularColorMap.value=m.specularColorMap,t(m.specularColorMap,_.specularColorMapTransform)),m.specularIntensityMap&&(_.specularIntensityMap.value=m.specularIntensityMap,t(m.specularIntensityMap,_.specularIntensityMapTransform))}function p(_,m){m.matcap&&(_.matcap.value=m.matcap)}function g(_,m){const v=e.get(m).light;_.referencePosition.value.setFromMatrixPosition(v.matrixWorld),_.nearDistance.value=v.shadow.camera.near,_.farDistance.value=v.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:s}}function oD(n,e,t,i){let s={},a={},r=[];const o=n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS);function l(v,y){const b=y.program;i.uniformBlockBinding(v,b)}function c(v,y){let b=s[v.id];b===void 0&&(p(v),b=u(v),s[v.id]=b,v.addEventListener("dispose",_));const T=y.program;i.updateUBOMapping(v,T);const x=e.render.frame;a[v.id]!==x&&(h(v),a[v.id]=x)}function u(v){const y=d();v.__bindingPointIndex=y;const b=n.createBuffer(),T=v.__size,x=v.usage;return n.bindBuffer(n.UNIFORM_BUFFER,b),n.bufferData(n.UNIFORM_BUFFER,T,x),n.bindBuffer(n.UNIFORM_BUFFER,null),n.bindBufferBase(n.UNIFORM_BUFFER,y,b),b}function d(){for(let v=0;v0&&(b+=T-x),v.__size=b,v.__cache={},this}function g(v){const y={boundary:0,storage:0};return typeof v=="number"||typeof v=="boolean"?(y.boundary=4,y.storage=4):v.isVector2?(y.boundary=8,y.storage=8):v.isVector3||v.isColor?(y.boundary=16,y.storage=12):v.isVector4?(y.boundary=16,y.storage=16):v.isMatrix3?(y.boundary=48,y.storage=48):v.isMatrix4?(y.boundary=64,y.storage=64):v.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",v),y}function _(v){const y=v.target;y.removeEventListener("dispose",_);const b=r.indexOf(y.__bindingPointIndex);r.splice(b,1),n.deleteBuffer(s[y.id]),delete s[y.id],delete a[y.id]}function m(){for(const v in s)n.deleteBuffer(s[v]);r=[],s={},a={}}return{bind:l,update:c,dispose:m}}class kg{constructor(e={}){const{canvas:t=yS(),context:i=null,depth:s=!0,stencil:a=!1,alpha:r=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:d=!1,reversedDepthBuffer:h=!1}=e;this.isWebGLRenderer=!0;let f;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=i.getContextAttributes().alpha}else f=r;const p=new Uint32Array(4),g=new Int32Array(4);let _=null,m=null;const v=[],y=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Os,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const b=this;let T=!1;this._outputColorSpace=gt;let x=0,M=0,C=null,w=-1,E=null;const R=new qe,k=new qe;let O=null;const D=new ue(0);let U=0,F=t.width,W=t.height,H=1,ne=null,oe=null;const pe=new qe(0,0,F,W),Ie=new qe(0,0,F,W);let ke=!1;const Xe=new ko;let De=!1,Z=!1;const ae=new Me,Se=new S,X=new qe,ie={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let xe=!1;function Ae(){return C===null?H:1}let L=i;function G(P,B){return t.getContext(P,B)}try{const P={alpha:!0,depth:s,stencil:a,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:u,failIfMajorPerformanceCaveat:d};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${bh}`),t.addEventListener("webglcontextlost",be,!1),t.addEventListener("webglcontextrestored",Fe,!1),t.addEventListener("webglcontextcreationerror",he,!1),L===null){const B="webgl2";if(L=G(B,P),L===null)throw G(B)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(P){throw console.error("THREE.WebGLRenderer: "+P.message),P}let j,Y,Q,_e,ce,ge,$e,it,I,A,V,J,le,ee,He,ye,Ue,Be,de,Pe,Je,Ve,Ce,ht;function N(){j=new v2(L),j.init(),Ve=new mT(L,j),Y=new h2(L,j,e,Ve),Q=new Qk(L,j),Y.reversedDepthBuffer&&h&&Q.buffers.depth.setReversed(!0),_e=new w2(L),ce=new zk,ge=new eD(L,j,Q,ce,Y,Ve,_e),$e=new p2(b),it=new y2(b),I=new AP(L),Ce=new u2(L,I),A=new b2(L,I,_e,Ce),V=new T2(L,A,I,_e),de=new S2(L,Y,ge),ye=new f2(ce),J=new Bk(b,$e,it,j,Y,Ce,ye),le=new rD(b,ce),ee=new Vk,He=new qk(j),Be=new c2(b,$e,it,Q,V,f,l),Ue=new Zk(b,V,Y),ht=new oD(L,_e,Y,Q),Pe=new d2(L,j,_e),Je=new x2(L,j,_e),_e.programs=J.programs,b.capabilities=Y,b.extensions=j,b.properties=ce,b.renderLists=ee,b.shadowMap=Ue,b.state=Q,b.info=_e}N();const me=new sD(b,L);this.xr=me,this.getContext=function(){return L},this.getContextAttributes=function(){return L.getContextAttributes()},this.forceContextLoss=function(){const P=j.get("WEBGL_lose_context");P&&P.loseContext()},this.forceContextRestore=function(){const P=j.get("WEBGL_lose_context");P&&P.restoreContext()},this.getPixelRatio=function(){return H},this.setPixelRatio=function(P){P!==void 0&&(H=P,this.setSize(F,W,!1))},this.getSize=function(P){return P.set(F,W)},this.setSize=function(P,B,K=!0){if(me.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}F=P,W=B,t.width=Math.floor(P*H),t.height=Math.floor(B*H),K===!0&&(t.style.width=P+"px",t.style.height=B+"px"),this.setViewport(0,0,P,B)},this.getDrawingBufferSize=function(P){return P.set(F*H,W*H).floor()},this.setDrawingBufferSize=function(P,B,K){F=P,W=B,H=K,t.width=Math.floor(P*K),t.height=Math.floor(B*K),this.setViewport(0,0,P,B)},this.getCurrentViewport=function(P){return P.copy(R)},this.getViewport=function(P){return P.copy(pe)},this.setViewport=function(P,B,K,q){P.isVector4?pe.set(P.x,P.y,P.z,P.w):pe.set(P,B,K,q),Q.viewport(R.copy(pe).multiplyScalar(H).round())},this.getScissor=function(P){return P.copy(Ie)},this.setScissor=function(P,B,K,q){P.isVector4?Ie.set(P.x,P.y,P.z,P.w):Ie.set(P,B,K,q),Q.scissor(k.copy(Ie).multiplyScalar(H).round())},this.getScissorTest=function(){return ke},this.setScissorTest=function(P){Q.setScissorTest(ke=P)},this.setOpaqueSort=function(P){ne=P},this.setTransparentSort=function(P){oe=P},this.getClearColor=function(P){return P.copy(Be.getClearColor())},this.setClearColor=function(){Be.setClearColor(...arguments)},this.getClearAlpha=function(){return Be.getClearAlpha()},this.setClearAlpha=function(){Be.setClearAlpha(...arguments)},this.clear=function(P=!0,B=!0,K=!0){let q=0;if(P){let z=!1;if(C!==null){const fe=C.texture.format;z=fe===Ah||fe===Ch||fe===oc}if(z){const fe=C.texture.type,Re=fe===ji||fe===zs||fe===xo||fe===wo||fe===Th||fe===Mh,Ne=Be.getClearColor(),Oe=Be.getClearAlpha(),je=Ne.r,et=Ne.g,We=Ne.b;Re?(p[0]=je,p[1]=et,p[2]=We,p[3]=Oe,L.clearBufferuiv(L.COLOR,0,p)):(g[0]=je,g[1]=et,g[2]=We,g[3]=Oe,L.clearBufferiv(L.COLOR,0,g))}else q|=L.COLOR_BUFFER_BIT}B&&(q|=L.DEPTH_BUFFER_BIT),K&&(q|=L.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),L.clear(q)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",be,!1),t.removeEventListener("webglcontextrestored",Fe,!1),t.removeEventListener("webglcontextcreationerror",he,!1),Be.dispose(),ee.dispose(),He.dispose(),ce.dispose(),$e.dispose(),it.dispose(),V.dispose(),Ce.dispose(),ht.dispose(),J.dispose(),me.dispose(),me.removeEventListener("sessionstart",Ji),me.removeEventListener("sessionend",ly),_a.stop()};function be(P){P.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),T=!0}function Fe(){console.log("THREE.WebGLRenderer: Context Restored."),T=!1;const P=_e.autoReset,B=Ue.enabled,K=Ue.autoUpdate,q=Ue.needsUpdate,z=Ue.type;N(),_e.autoReset=P,Ue.enabled=B,Ue.autoUpdate=K,Ue.needsUpdate=q,Ue.type=z}function he(P){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",P.statusMessage)}function re(P){const B=P.target;B.removeEventListener("dispose",re),ze(B)}function ze(P){lt(P),ce.remove(P)}function lt(P){const B=ce.get(P).programs;B!==void 0&&(B.forEach(function(K){J.releaseProgram(K)}),P.isShaderMaterial&&J.releaseShaderCache(P))}this.renderBufferDirect=function(P,B,K,q,z,fe){B===null&&(B=ie);const Re=z.isMesh&&z.matrixWorld.determinant()<0,Ne=P1(P,B,K,q,z);Q.setMaterial(q,Re);let Oe=K.index,je=1;if(q.wireframe===!0){if(Oe=A.getWireframeAttribute(K),Oe===void 0)return;je=2}const et=K.drawRange,We=K.attributes.position;let wt=et.start*je,It=(et.start+et.count)*je;fe!==null&&(wt=Math.max(wt,fe.start*je),It=Math.min(It,(fe.start+fe.count)*je)),Oe!==null?(wt=Math.max(wt,0),It=Math.min(It,Oe.count)):We!=null&&(wt=Math.max(wt,0),It=Math.min(It,We.count));const qt=It-wt;if(qt<0||qt===1/0)return;Ce.setup(z,q,Ne,K,Oe);let Ft,kt=Pe;if(Oe!==null&&(Ft=I.get(Oe),kt=Je,kt.setIndex(Ft)),z.isMesh)q.wireframe===!0?(Q.setLineWidth(q.wireframeLinewidth*Ae()),kt.setMode(L.LINES)):kt.setMode(L.TRIANGLES);else if(z.isLine){let Ke=q.linewidth;Ke===void 0&&(Ke=1),Q.setLineWidth(Ke*Ae()),z.isLineSegments?kt.setMode(L.LINES):z.isLineLoop?kt.setMode(L.LINE_LOOP):kt.setMode(L.LINE_STRIP)}else z.isPoints?kt.setMode(L.POINTS):z.isSprite&&kt.setMode(L.TRIANGLES);if(z.isBatchedMesh)if(z._multiDrawInstances!==null)Xl("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),kt.renderMultiDrawInstances(z._multiDrawStarts,z._multiDrawCounts,z._multiDrawCount,z._multiDrawInstances);else if(j.get("WEBGL_multi_draw"))kt.renderMultiDraw(z._multiDrawStarts,z._multiDrawCounts,z._multiDrawCount);else{const Ke=z._multiDrawStarts,Gt=z._multiDrawCounts,St=z._multiDrawCount,ri=Oe?I.get(Oe).bytesPerElement:1,yr=ce.get(q).currentProgram.getUniforms();for(let oi=0;oi{function fe(){if(q.forEach(function(Re){ce.get(Re).currentProgram.isReady()&&q.delete(Re)}),q.size===0){z(P);return}setTimeout(fe,10)}j.get("KHR_parallel_shader_compile")!==null?fe():setTimeout(fe,10)})};let Et=null;function ys(P){Et&&Et(P)}function Ji(){_a.stop()}function ly(){_a.start()}const _a=new uT;_a.setAnimationLoop(ys),typeof self<"u"&&_a.setContext(self),this.setAnimationLoop=function(P){Et=P,me.setAnimationLoop(P),P===null?_a.stop():_a.start()},me.addEventListener("sessionstart",Ji),me.addEventListener("sessionend",ly),this.render=function(P,B){if(B!==void 0&&B.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(T===!0)return;if(P.matrixWorldAutoUpdate===!0&&P.updateMatrixWorld(),B.parent===null&&B.matrixWorldAutoUpdate===!0&&B.updateMatrixWorld(),me.enabled===!0&&me.isPresenting===!0&&(me.cameraAutoUpdate===!0&&me.updateCamera(B),B=me.getCamera()),P.isScene===!0&&P.onBeforeRender(b,P,B,C),m=He.get(P,y.length),m.init(B),y.push(m),ae.multiplyMatrices(B.projectionMatrix,B.matrixWorldInverse),Xe.setFromProjectionMatrix(ae,hi,B.reversedDepth),Z=this.localClippingEnabled,De=ye.init(this.clippingPlanes,Z),_=ee.get(P,v.length),_.init(),v.push(_),me.enabled===!0&&me.isPresenting===!0){const fe=b.xr.getDepthSensingMesh();fe!==null&&gf(fe,B,-1/0,b.sortObjects)}gf(P,B,0,b.sortObjects),_.finish(),b.sortObjects===!0&&_.sort(ne,oe),xe=me.enabled===!1||me.isPresenting===!1||me.hasDepthSensing()===!1,xe&&Be.addToRenderList(_,P),this.info.render.frame++,De===!0&&ye.beginShadows();const K=m.state.shadowsArray;Ue.render(K,P,B),De===!0&&ye.endShadows(),this.info.autoReset===!0&&this.info.reset();const q=_.opaque,z=_.transmissive;if(m.setupLights(),B.isArrayCamera){const fe=B.cameras;if(z.length>0)for(let Re=0,Ne=fe.length;Re0&&uy(q,z,P,B),xe&&Be.render(P),cy(_,P,B);C!==null&&M===0&&(ge.updateMultisampleRenderTarget(C),ge.updateRenderTargetMipmap(C)),P.isScene===!0&&P.onAfterRender(b,P,B),Ce.resetDefaultState(),w=-1,E=null,y.pop(),y.length>0?(m=y[y.length-1],De===!0&&ye.setGlobalState(b.clippingPlanes,m.state.camera)):m=null,v.pop(),v.length>0?_=v[v.length-1]:_=null};function gf(P,B,K,q){if(P.visible===!1)return;if(P.layers.test(B.layers)){if(P.isGroup)K=P.renderOrder;else if(P.isLOD)P.autoUpdate===!0&&P.update(B);else if(P.isLight)m.pushLight(P),P.castShadow&&m.pushShadow(P);else if(P.isSprite){if(!P.frustumCulled||Xe.intersectsSprite(P)){q&&X.setFromMatrixPosition(P.matrixWorld).applyMatrix4(ae);const Re=V.update(P),Ne=P.material;Ne.visible&&_.push(P,Re,Ne,K,X.z,null)}}else if((P.isMesh||P.isLine||P.isPoints)&&(!P.frustumCulled||Xe.intersectsObject(P))){const Re=V.update(P),Ne=P.material;if(q&&(P.boundingSphere!==void 0?(P.boundingSphere===null&&P.computeBoundingSphere(),X.copy(P.boundingSphere.center)):(Re.boundingSphere===null&&Re.computeBoundingSphere(),X.copy(Re.boundingSphere.center)),X.applyMatrix4(P.matrixWorld).applyMatrix4(ae)),Array.isArray(Ne)){const Oe=Re.groups;for(let je=0,et=Oe.length;je0&&vc(z,B,K),fe.length>0&&vc(fe,B,K),Re.length>0&&vc(Re,B,K),Q.buffers.depth.setTest(!0),Q.buffers.depth.setMask(!0),Q.buffers.color.setMask(!0),Q.setPolygonOffset(!1)}function uy(P,B,K,q){if((K.isScene===!0?K.overrideMaterial:null)!==null)return;m.state.transmissionRenderTarget[q.id]===void 0&&(m.state.transmissionRenderTarget[q.id]=new ms(1,1,{generateMipmaps:!0,type:j.has("EXT_color_buffer_half_float")||j.has("EXT_color_buffer_float")?ls:ji,minFilter:Mi,samples:4,stencilBuffer:a,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:rt.workingColorSpace}));const fe=m.state.transmissionRenderTarget[q.id],Re=q.viewport||R;fe.setSize(Re.z*b.transmissionResolutionScale,Re.w*b.transmissionResolutionScale);const Ne=b.getRenderTarget(),Oe=b.getActiveCubeFace(),je=b.getActiveMipmapLevel();b.setRenderTarget(fe),b.getClearColor(D),U=b.getClearAlpha(),U<1&&b.setClearColor(16777215,.5),b.clear(),xe&&Be.render(K);const et=b.toneMapping;b.toneMapping=Os;const We=q.viewport;if(q.viewport!==void 0&&(q.viewport=void 0),m.setupLightsView(q),De===!0&&ye.setGlobalState(b.clippingPlanes,q),vc(P,K,q),ge.updateMultisampleRenderTarget(fe),ge.updateRenderTargetMipmap(fe),j.has("WEBGL_multisampled_render_to_texture")===!1){let wt=!1;for(let It=0,qt=B.length;It0),We=!!K.morphAttributes.position,wt=!!K.morphAttributes.normal,It=!!K.morphAttributes.color;let qt=Os;q.toneMapped&&(C===null||C.isXRRenderTarget===!0)&&(qt=b.toneMapping);const Ft=K.morphAttributes.position||K.morphAttributes.normal||K.morphAttributes.color,kt=Ft!==void 0?Ft.length:0,Ke=ce.get(q),Gt=m.state.lights;if(De===!0&&(Z===!0||P!==E)){const On=P===E&&q.id===w;ye.setState(q,P,On)}let St=!1;q.version===Ke.__version?(Ke.needsLights&&Ke.lightsStateVersion!==Gt.state.version||Ke.outputColorSpace!==Ne||z.isBatchedMesh&&Ke.batching===!1||!z.isBatchedMesh&&Ke.batching===!0||z.isBatchedMesh&&Ke.batchingColor===!0&&z.colorTexture===null||z.isBatchedMesh&&Ke.batchingColor===!1&&z.colorTexture!==null||z.isInstancedMesh&&Ke.instancing===!1||!z.isInstancedMesh&&Ke.instancing===!0||z.isSkinnedMesh&&Ke.skinning===!1||!z.isSkinnedMesh&&Ke.skinning===!0||z.isInstancedMesh&&Ke.instancingColor===!0&&z.instanceColor===null||z.isInstancedMesh&&Ke.instancingColor===!1&&z.instanceColor!==null||z.isInstancedMesh&&Ke.instancingMorph===!0&&z.morphTexture===null||z.isInstancedMesh&&Ke.instancingMorph===!1&&z.morphTexture!==null||Ke.envMap!==Oe||q.fog===!0&&Ke.fog!==fe||Ke.numClippingPlanes!==void 0&&(Ke.numClippingPlanes!==ye.numPlanes||Ke.numIntersection!==ye.numIntersection)||Ke.vertexAlphas!==je||Ke.vertexTangents!==et||Ke.morphTargets!==We||Ke.morphNormals!==wt||Ke.morphColors!==It||Ke.toneMapping!==qt||Ke.morphTargetsCount!==kt)&&(St=!0):(St=!0,Ke.__version=q.version);let ri=Ke.currentProgram;St===!0&&(ri=bc(q,B,z));let yr=!1,oi=!1,zo=!1;const $t=ri.getUniforms(),mi=Ke.uniforms;if(Q.useProgram(ri.program)&&(yr=!0,oi=!0,zo=!0),q.id!==w&&(w=q.id,oi=!0),yr||E!==P){Q.buffers.depth.getReversed()&&P.reversedDepth!==!0&&(P._reversedDepth=!0,P.updateProjectionMatrix()),$t.setValue(L,"projectionMatrix",P.projectionMatrix),$t.setValue(L,"viewMatrix",P.matrixWorldInverse);const $n=$t.map.cameraPosition;$n!==void 0&&$n.setValue(L,Se.setFromMatrixPosition(P.matrixWorld)),Y.logarithmicDepthBuffer&&$t.setValue(L,"logDepthBufFC",2/(Math.log(P.far+1)/Math.LN2)),(q.isMeshPhongMaterial||q.isMeshToonMaterial||q.isMeshLambertMaterial||q.isMeshBasicMaterial||q.isMeshStandardMaterial||q.isShaderMaterial)&&$t.setValue(L,"isOrthographic",P.isOrthographicCamera===!0),E!==P&&(E=P,oi=!0,zo=!0)}if(z.isSkinnedMesh){$t.setOptional(L,z,"bindMatrix"),$t.setOptional(L,z,"bindMatrixInverse");const On=z.skeleton;On&&(On.boneTexture===null&&On.computeBoneTexture(),$t.setValue(L,"boneTexture",On.boneTexture,ge))}z.isBatchedMesh&&($t.setOptional(L,z,"batchingTexture"),$t.setValue(L,"batchingTexture",z._matricesTexture,ge),$t.setOptional(L,z,"batchingIdTexture"),$t.setValue(L,"batchingIdTexture",z._indirectTexture,ge),$t.setOptional(L,z,"batchingColorTexture"),z._colorsTexture!==null&&$t.setValue(L,"batchingColorTexture",z._colorsTexture,ge));const _i=K.morphAttributes;if((_i.position!==void 0||_i.normal!==void 0||_i.color!==void 0)&&de.update(z,K,ri),(oi||Ke.receiveShadow!==z.receiveShadow)&&(Ke.receiveShadow=z.receiveShadow,$t.setValue(L,"receiveShadow",z.receiveShadow)),q.isMeshGouraudMaterial&&q.envMap!==null&&(mi.envMap.value=Oe,mi.flipEnvMap.value=Oe.isCubeTexture&&Oe.isRenderTargetTexture===!1?-1:1),q.isMeshStandardMaterial&&q.envMap===null&&B.environment!==null&&(mi.envMapIntensity.value=B.environmentIntensity),oi&&($t.setValue(L,"toneMappingExposure",b.toneMappingExposure),Ke.needsLights&&I1(mi,zo),fe&&q.fog===!0&&le.refreshFogUniforms(mi,fe),le.refreshMaterialUniforms(mi,q,H,W,m.state.transmissionRenderTarget[P.id]),qu.upload(L,hy(Ke),mi,ge)),q.isShaderMaterial&&q.uniformsNeedUpdate===!0&&(qu.upload(L,hy(Ke),mi,ge),q.uniformsNeedUpdate=!1),q.isSpriteMaterial&&$t.setValue(L,"center",z.center),$t.setValue(L,"modelViewMatrix",z.modelViewMatrix),$t.setValue(L,"normalMatrix",z.normalMatrix),$t.setValue(L,"modelMatrix",z.matrixWorld),q.isShaderMaterial||q.isRawShaderMaterial){const On=q.uniformsGroups;for(let $n=0,yf=On.length;$n0&&ge.useMultisampledRTT(P)===!1?z=ce.get(P).__webglMultisampledFramebuffer:Array.isArray(et)?z=et[K]:z=et,R.copy(P.viewport),k.copy(P.scissor),O=P.scissorTest}else R.copy(pe).multiplyScalar(H).floor(),k.copy(Ie).multiplyScalar(H).floor(),O=ke;if(K!==0&&(z=k1),Q.bindFramebuffer(L.FRAMEBUFFER,z)&&q&&Q.drawBuffers(P,z),Q.viewport(R),Q.scissor(k),Q.setScissorTest(O),fe){const Oe=ce.get(P.texture);L.framebufferTexture2D(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_CUBE_MAP_POSITIVE_X+B,Oe.__webglTexture,K)}else if(Re){const Oe=B;for(let je=0;je=0&&B<=P.width-q&&K>=0&&K<=P.height-z&&(P.textures.length>1&&L.readBuffer(L.COLOR_ATTACHMENT0+Ne),L.readPixels(B,K,q,z,Ve.convert(et),Ve.convert(We),fe))}finally{const je=C!==null?ce.get(C).__webglFramebuffer:null;Q.bindFramebuffer(L.FRAMEBUFFER,je)}}},this.readRenderTargetPixelsAsync=async function(P,B,K,q,z,fe,Re,Ne=0){if(!(P&&P.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Oe=ce.get(P).__webglFramebuffer;if(P.isWebGLCubeRenderTarget&&Re!==void 0&&(Oe=Oe[Re]),Oe)if(B>=0&&B<=P.width-q&&K>=0&&K<=P.height-z){Q.bindFramebuffer(L.FRAMEBUFFER,Oe);const je=P.textures[Ne],et=je.format,We=je.type;if(!Y.textureFormatReadable(et))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Y.textureTypeReadable(We))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const wt=L.createBuffer();L.bindBuffer(L.PIXEL_PACK_BUFFER,wt),L.bufferData(L.PIXEL_PACK_BUFFER,fe.byteLength,L.STREAM_READ),P.textures.length>1&&L.readBuffer(L.COLOR_ATTACHMENT0+Ne),L.readPixels(B,K,q,z,Ve.convert(et),Ve.convert(We),0);const It=C!==null?ce.get(C).__webglFramebuffer:null;Q.bindFramebuffer(L.FRAMEBUFFER,It);const qt=L.fenceSync(L.SYNC_GPU_COMMANDS_COMPLETE,0);return L.flush(),await QC(L,qt,4),L.bindBuffer(L.PIXEL_PACK_BUFFER,wt),L.getBufferSubData(L.PIXEL_PACK_BUFFER,0,fe),L.deleteBuffer(wt),L.deleteSync(qt),fe}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(P,B=null,K=0){const q=Math.pow(2,-K),z=Math.floor(P.image.width*q),fe=Math.floor(P.image.height*q),Re=B!==null?B.x:0,Ne=B!==null?B.y:0;ge.setTexture2D(P,0),L.copyTexSubImage2D(L.TEXTURE_2D,K,0,0,Re,Ne,z,fe),Q.unbindTexture()};const D1=L.createFramebuffer(),O1=L.createFramebuffer();this.copyTextureToTexture=function(P,B,K=null,q=null,z=0,fe=null){fe===null&&(z!==0?(Xl("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),fe=z,z=0):fe=0);let Re,Ne,Oe,je,et,We,wt,It,qt;const Ft=P.isCompressedTexture?P.mipmaps[fe]:P.image;if(K!==null)Re=K.max.x-K.min.x,Ne=K.max.y-K.min.y,Oe=K.isBox3?K.max.z-K.min.z:1,je=K.min.x,et=K.min.y,We=K.isBox3?K.min.z:0;else{const _i=Math.pow(2,-z);Re=Math.floor(Ft.width*_i),Ne=Math.floor(Ft.height*_i),P.isDataArrayTexture?Oe=Ft.depth:P.isData3DTexture?Oe=Math.floor(Ft.depth*_i):Oe=1,je=0,et=0,We=0}q!==null?(wt=q.x,It=q.y,qt=q.z):(wt=0,It=0,qt=0);const kt=Ve.convert(B.format),Ke=Ve.convert(B.type);let Gt;B.isData3DTexture?(ge.setTexture3D(B,0),Gt=L.TEXTURE_3D):B.isDataArrayTexture||B.isCompressedArrayTexture?(ge.setTexture2DArray(B,0),Gt=L.TEXTURE_2D_ARRAY):(ge.setTexture2D(B,0),Gt=L.TEXTURE_2D),L.pixelStorei(L.UNPACK_FLIP_Y_WEBGL,B.flipY),L.pixelStorei(L.UNPACK_PREMULTIPLY_ALPHA_WEBGL,B.premultiplyAlpha),L.pixelStorei(L.UNPACK_ALIGNMENT,B.unpackAlignment);const St=L.getParameter(L.UNPACK_ROW_LENGTH),ri=L.getParameter(L.UNPACK_IMAGE_HEIGHT),yr=L.getParameter(L.UNPACK_SKIP_PIXELS),oi=L.getParameter(L.UNPACK_SKIP_ROWS),zo=L.getParameter(L.UNPACK_SKIP_IMAGES);L.pixelStorei(L.UNPACK_ROW_LENGTH,Ft.width),L.pixelStorei(L.UNPACK_IMAGE_HEIGHT,Ft.height),L.pixelStorei(L.UNPACK_SKIP_PIXELS,je),L.pixelStorei(L.UNPACK_SKIP_ROWS,et),L.pixelStorei(L.UNPACK_SKIP_IMAGES,We);const $t=P.isDataArrayTexture||P.isData3DTexture,mi=B.isDataArrayTexture||B.isData3DTexture;if(P.isDepthTexture){const _i=ce.get(P),On=ce.get(B),$n=ce.get(_i.__renderTarget),yf=ce.get(On.__renderTarget);Q.bindFramebuffer(L.READ_FRAMEBUFFER,$n.__webglFramebuffer),Q.bindFramebuffer(L.DRAW_FRAMEBUFFER,yf.__webglFramebuffer);for(let ga=0;gaMath.PI&&(i-=Xn),s<-Math.PI?s+=Xn:s>Math.PI&&(s-=Xn),i<=s?this._spherical.theta=Math.max(i,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(i+s)/2?Math.max(i,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let a=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const r=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),a=r!=this._spherical.radius}if(ln.setFromSpherical(this._spherical),ln.applyQuaternion(this._quatInverse),t.copy(this.target).add(ln),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let r=null;if(this.object.isPerspectiveCamera){const o=ln.length();r=this._clampDistance(o*this._scale);const l=o-r;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),a=!!l}else if(this.object.isOrthographicCamera){const o=new S(this._mouse.x,this._mouse.y,0);o.unproject(this.object);const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),a=l!==this.object.zoom;const c=new S(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(o),this.object.updateMatrixWorld(),r=ln.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;r!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(r).add(this.object.position):(hu.origin.copy(this.object.position),hu.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(hu.direction))up||8*(1-this._lastQuaternion.dot(this.object.quaternion))>up||this._lastTargetPosition.distanceToSquared(this.target)>up?(this.dispatchEvent(q0),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Xn/60*this.autoRotateSpeed*e:Xn/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){ln.setFromMatrixColumn(t,0),ln.multiplyScalar(-e),this._panOffset.add(ln)}_panUp(e,t){this.screenSpacePanning===!0?ln.setFromMatrixColumn(t,1):(ln.setFromMatrixColumn(t,0),ln.crossVectors(this.object.up,ln)),ln.multiplyScalar(e),this._panOffset.add(ln)}_pan(e,t){const i=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;ln.copy(s).sub(this.target);let a=ln.length();a*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*a/i.clientHeight,this.object.matrix),this._panUp(2*t*a/i.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/i.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/i.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const i=this.domElement.getBoundingClientRect(),s=e-i.left,a=t-i.top,r=i.width,o=i.height;this._mouse.x=s/r*2-1,this._mouse.y=-(a/o)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Xn*this._rotateDelta.x/t.clientHeight),this._rotateUp(Xn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(Xn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-Xn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(Xn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-Xn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(i,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(i,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,s=e.pageY-t.y,a=Math.sqrt(i*i+s*s);this._dollyStart.set(0,a)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const i=this._getSecondPointerPosition(e),s=.5*(e.pageX+i.x),a=.5*(e.pageY+i.y);this._rotateEnd.set(s,a)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Xn*this._rotateDelta.x/t.clientHeight),this._rotateUp(Xn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(i,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,s=e.pageY-t.y,a=Math.sqrt(i*i+s*s);this._dollyEnd.set(0,a),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const r=(e.pageX+t.x)*.5,o=(e.pageY+t.y)*.5;this._updateZoomParameters(r,o)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t(O=F.indexOf(` +`))&&D=C.byteLength||!(U=d(C)))&&r(1,"no header found"),(F=U.match(w))||r(3,"bad initial token"),D.valid|=1,D.programtype=F[1],D.string+=U+` +`;U=d(C),U!==!1;){if(D.string+=U+` +`,U.charAt(0)==="#"){D.comments+=U+` +`;continue}if((F=U.match(E))&&(D.gamma=parseFloat(F[1])),(F=U.match(R))&&(D.exposure=parseFloat(F[1])),(F=U.match(k))&&(D.valid|=2,D.format=F[1]),(F=U.match(O))&&(D.valid|=4,D.height=parseInt(F[1],10),D.width=parseInt(F[2],10)),D.valid&2&&D.valid&4)break}return D.valid&2||r(3,"missing format specifier"),D.valid&4||r(3,"missing image size specifier"),D},f=function(C,w,E){const R=w;if(R<8||R>32767||C[0]!==2||C[1]!==2||C[2]&128)return new Uint8Array(C);R!==(C[2]<<8|C[3])&&r(3,"wrong scanline width");const k=new Uint8Array(4*w*E);k.length||r(4,"unable to allocate buffer space");let O=0,D=0;const U=4*R,F=new Uint8Array(4),W=new Uint8Array(U);let H=E;for(;H>0&&DC.byteLength&&r(1),F[0]=C[D++],F[1]=C[D++],F[2]=C[D++],F[3]=C[D++],(F[0]!=2||F[1]!=2||(F[2]<<8|F[3])!=R)&&r(3,"bad rgbe scanline format");let ne=0,oe;for(;ne128;if(Ie&&(oe-=128),(oe===0||ne+oe>U)&&r(3,"bad scanline data"),Ie){const ke=C[D++];for(let Xe=0;Xe{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(const t of e)t.dispose()}}function zr(n){return new ef({color:0,emissive:16777215,emissiveIntensity:n})}let gT=null;function MD(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof window<"u"&&window.location?.href?window.location.href:import.meta.url}function ED(){return"./"}function CD(n){return/^[a-z][a-z\d+\-.]*:/i.test(n)||n.startsWith("//")}function AD(n=gT){const e=n==null||n===""?ED():String(n);return new URL(e,MD()).href}function Si(n,e=gT){const t=String(n);return CD(t)?t:new URL(t.replace(/^\/+/,""),AD(e)).href}class RD{constructor(e,t={}){if(this.container=typeof e=="string"?document.getElementById(e):e,this.assetBase=t.assetBase,!this.container){console.error("Invalid container passed to SceneManager");return}this.scene=new cc,this.scene.background=new ue(8900331);const i=this.container.clientWidth,s=this.container.clientHeight;this.camera=new Jt(75,i/s,10,5e4),this.camera.position.set(0,2e3,5e3),this.renderer=new kg({antialias:!0,preserveDrawingBuffer:t.preserveDrawingBuffer===!0}),this.renderer.setSize(i,s),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=W_,this.renderer.toneMapping=K_,this.renderer.toneMappingExposure=1,this.renderer.outputColorSpace=gt,this.container.appendChild(this.renderer.domElement),window.addEventListener("resize",()=>this.onWindowResize())}initDefaultEnvironment(){if(!this._neutralEnvTexture){const e=new sh(this.renderer);this._neutralEnvTexture=e.fromScene(new TD,.04).texture,e.dispose()}if(this.scene.environment=this._neutralEnvTexture,!this._defaultLightsAdded){const e=new Fo(16777215,1.5);e.position.set(3e3,8e3,4e3),this.scene.add(e);const t=new mc(16777215,.4);this.scene.add(t),this._defaultLightsAdded=!0}}applyEnvironment(e){return new Promise(t=>{const i=new SD,s=Si(e.skyboxUrl,this.assetBase);i.load(s,a=>{this.scene.background&&this.scene.background.dispose&&this.scene.background.dispose(),a.mapping=rr,this.scene.background=a,this.scene.environment=a,this.currentEnvironmentId=e.id;const r=e.rotation??{};this._skyboxBaseRotation={x:vt.degToRad(r.x??0),y:vt.degToRad(r.y??0),z:vt.degToRad(r.z??0)},this._skyboxAnimatedY=0,this._skyboxAnimation=e.animation??null,this._applySkyboxRotation(),typeof e.exposure=="number"&&(this.renderer.toneMappingExposure=e.exposure),console.log(`[SceneManager] environment applied: ${e.id}`),t(!0)},void 0,a=>{console.error(`[SceneManager] Failed to load environment "${e.id}":`,a),t(!1)})})}_applySkyboxRotation(){const e=this._skyboxBaseRotation;if(!e)return;const t=e.y+(this._skyboxAnimatedY??0);this.scene.backgroundRotation&&this.scene.backgroundRotation.set(e.x,t,e.z),this.scene.environmentRotation&&this.scene.environmentRotation.set(e.x,t,e.z)}updateSkyboxAnimation(e){const t=this._skyboxAnimation;!t||!t.enabled||!e||(this._skyboxAnimatedY=(this._skyboxAnimatedY??0)+vt.degToRad(t.speed*e),this._applySkyboxRotation())}setDefaultBackground(){this.scene.background&&this.scene.background.dispose&&this.scene.background.dispose(),this.scene.background=new ue(1710638),this.initDefaultEnvironment(),this.renderer.toneMappingExposure=1,this._skyboxAnimation=null,this._skyboxBaseRotation=null,this.currentEnvironmentId=null,console.log("[SceneManager] Using neutral default environment (no skybox)")}setExposure(e){this.renderer&&(this.renderer.toneMappingExposure=e)}onWindowResize(){if(!this.container||!this.renderer)return;const e=this.container.clientWidth,t=this.container.clientHeight;this.camera.aspect=e/t,this.camera.updateProjectionMatrix(),this.renderer.setSize(e,t)}render(){this.renderer&&this.renderer.render(this.scene,this.camera)}dispose(){this.renderer&&(this.renderer.dispose(),this.renderer.domElement&&this.renderer.domElement.parentNode&&this.renderer.domElement.parentNode.removeChild(this.renderer.domElement),this.renderer=null)}}function j0(n,e){if(e===rS)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),n;if(e===Qd||e===ng){let t=n.getIndex();if(t===null){const r=[],o=n.getAttribute("position");if(o!==void 0){for(let l=0;l=2.0 are supported."));return}const c=new lO(a,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let u=0;u=0&&o[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}c.setExtensions(r),c.setPlugins(o),c.parse(i,s)}parseAsync(e,t){const i=this;return new Promise(function(s,a){i.parse(e,t,s,a)})}}function PD(){let n={};return{get:function(e){return n[e]},add:function(e,t){n[e]=t},remove:function(e){delete n[e]},removeAll:function(){n={}}}}const xt={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class ID{constructor(e){this.parser=e,this.name=xt.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let i=0,s=t.length;i=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,a.source,r)}}class WD{constructor(e){this.parser=e,this.name=xt.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,i=this.parser,s=i.json,a=s.textures[e];if(!a.extensions||!a.extensions[t])return null;const r=a.extensions[t],o=s.images[r.source];let l=i.textureLoader;if(o.uri){const c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,r.source,l)}}class XD{constructor(e){this.parser=e,this.name=xt.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,i=this.parser,s=i.json,a=s.textures[e];if(!a.extensions||!a.extensions[t])return null;const r=a.extensions[t],o=s.images[r.source];let l=i.textureLoader;if(o.uri){const c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,r.source,l)}}class KD{constructor(e){this.name=xt.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,i=t.bufferViews[e];if(i.extensions&&i.extensions[this.name]){const s=i.extensions[this.name],a=this.parser.getDependency("buffer",s.buffer),r=this.parser.options.meshoptDecoder;if(!r||!r.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return a.then(function(o){const l=s.byteOffset||0,c=s.byteLength||0,u=s.count,d=s.byteStride,h=new Uint8Array(o,l,c);return r.decodeGltfBufferAsync?r.decodeGltfBufferAsync(u,d,h,s.mode,s.filter).then(function(f){return f.buffer}):r.ready.then(function(){const f=new ArrayBuffer(u*d);return r.decodeGltfBuffer(new Uint8Array(f),u,d,h,s.mode,s.filter),f})})}else return null}}class qD{constructor(e){this.name=xt.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,i=t.nodes[e];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;const s=t.meshes[i.mesh];for(const c of s.primitives)if(c.mode!==xi.TRIANGLES&&c.mode!==xi.TRIANGLE_STRIP&&c.mode!==xi.TRIANGLE_FAN&&c.mode!==void 0)return null;const r=i.extensions[this.name].attributes,o=[],l={};for(const c in r)o.push(this.parser.getDependency("accessor",r[c]).then(u=>(l[c]=u,l[c])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(c=>{const u=c.pop(),d=u.isGroup?u.children:[u],h=c[0].count,f=[];for(const p of d){const g=new Me,_=new S,m=new dt,v=new S(1,1,1),y=new zh(p.geometry,p.material,h);for(let b=0;b0||n.search(/^data\:image\/jpeg/)===0?"image/jpeg":n.search(/\.webp($|\?)/i)>0||n.search(/^data\:image\/webp/)===0?"image/webp":n.search(/\.ktx2($|\?)/i)>0||n.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const oO=new Me;class lO{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new PD,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let i=!1,s=-1,a=!1,r=-1;if(typeof navigator<"u"){const o=navigator.userAgent;i=/^((?!chrome|android).)*safari/i.test(o)===!0;const l=o.match(/Version\/(\d+)/);s=i&&l?parseInt(l[1],10):-1,a=o.indexOf("Firefox")>-1,r=a?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||i&&s<17||a&&r<98?this.textureLoader=new tf(this.options.manager):this.textureLoader=new nT(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Gn(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const i=this,s=this.json,a=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(r){return r._markDefs&&r._markDefs()}),Promise.all(this._invokeAll(function(r){return r.beforeRoot&&r.beforeRoot()})).then(function(){return Promise.all([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])}).then(function(r){const o={scene:r[0][s.scene||0],scenes:r[0],animations:r[1],cameras:r[2],asset:s.asset,parser:i,userData:{}};return La(a,o,s),rs(o,s),Promise.all(i._invokeAll(function(l){return l.afterRoot&&l.afterRoot(o)})).then(function(){for(const l of o.scenes)l.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let s=0,a=t.length;s{const l=this.associations.get(r);l!=null&&this.associations.set(o,l);for(const[c,u]of r.children.entries())a(u,o.children[c])};return a(i,s),s.name+="_instance_"+e.uses[t]++,s}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let i=0;i=2&&_.setY(w,x[M*l+1]),l>=3&&_.setZ(w,x[M*l+2]),l>=4&&_.setW(w,x[M*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}_.normalized=p}return _})}loadTexture(e){const t=this.json,i=this.options,a=t.textures[e].source,r=t.images[a];let o=this.textureLoader;if(r.uri){const l=i.manager.getHandler(r.uri);l!==null&&(o=l)}return this.loadTextureImage(e,a,o)}loadTextureImage(e,t,i){const s=this,a=this.json,r=a.textures[e],o=a.images[t],l=(o.uri||o.bufferView)+":"+r.sampler;if(this.textureCache[l])return this.textureCache[l];const c=this.loadImageSource(t,i).then(function(u){u.flipY=!1,u.name=r.name||o.name||"",u.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(u.name=o.uri);const h=(a.samplers||{})[r.sampler]||{};return u.magFilter=J0[h.magFilter]||Vt,u.minFilter=J0[h.minFilter]||Mi,u.wrapS=Q0[h.wrapS]||ps,u.wrapT=Q0[h.wrapT]||ps,u.generateMipmaps=!u.isCompressedTexture&&u.minFilter!==dn&&u.minFilter!==Vt,s.associations.set(u,{textures:e}),u}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){const i=this,s=this.json,a=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(d=>d.clone());const r=s.images[e],o=self.URL||self.webkitURL;let l=r.uri||"",c=!1;if(r.bufferView!==void 0)l=i.getDependency("bufferView",r.bufferView).then(function(d){c=!0;const h=new Blob([d],{type:r.mimeType});return l=o.createObjectURL(h),l});else if(r.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const u=Promise.resolve(l).then(function(d){return new Promise(function(h,f){let p=h;t.isImageBitmapLoader===!0&&(p=function(g){const _=new Bt(g);_.needsUpdate=!0,h(_)}),t.load(Us.resolveURL(d,a.path),p,void 0,f)})}).then(function(d){return c===!0&&o.revokeObjectURL(l),rs(d,r),d.userData.mimeType=r.mimeType||rO(r.uri),d}).catch(function(d){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),d});return this.sourceCache[e]=u,u}assignTexture(e,t,i,s){const a=this;return this.getDependency("texture",i.index).then(function(r){if(!r)return null;if(i.texCoord!==void 0&&i.texCoord>0&&(r=r.clone(),r.channel=i.texCoord),a.extensions[xt.KHR_TEXTURE_TRANSFORM]){const o=i.extensions!==void 0?i.extensions[xt.KHR_TEXTURE_TRANSFORM]:void 0;if(o){const l=a.associations.get(r);r=a.extensions[xt.KHR_TEXTURE_TRANSFORM].extendTexture(r,o),a.associations.set(r,l)}}return s!==void 0&&(r.colorSpace=s),e[t]=r,r})}assignFinalMaterial(e){const t=e.geometry;let i=e.material;const s=t.attributes.tangent===void 0,a=t.attributes.color!==void 0,r=t.attributes.normal===void 0;if(e.isPoints){const o="PointsMaterial:"+i.uuid;let l=this.cache.get(o);l||(l=new aa,Qt.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,l.sizeAttenuation=!1,this.cache.add(o,l)),i=l}else if(e.isLine){const o="LineBasicMaterial:"+i.uuid;let l=this.cache.get(o);l||(l=new Rt,Qt.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,this.cache.add(o,l)),i=l}if(s||a||r){let o="ClonedMaterial:"+i.uuid+":";s&&(o+="derivative-tangents:"),a&&(o+="vertex-colors:"),r&&(o+="flat-shading:");let l=this.cache.get(o);l||(l=i.clone(),a&&(l.vertexColors=!0),r&&(l.flatShading=!0),s&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(o,l),this.associations.set(l,this.associations.get(i))),i=l}e.material=i}getMaterialType(){return Pn}loadMaterial(e){const t=this,i=this.json,s=this.extensions,a=i.materials[e];let r;const o={},l=a.extensions||{},c=[];if(l[xt.KHR_MATERIALS_UNLIT]){const d=s[xt.KHR_MATERIALS_UNLIT];r=d.getMaterialType(),c.push(d.extendParams(o,a,t))}else{const d=a.pbrMetallicRoughness||{};if(o.color=new ue(1,1,1),o.opacity=1,Array.isArray(d.baseColorFactor)){const h=d.baseColorFactor;o.color.setRGB(h[0],h[1],h[2],xn),o.opacity=h[3]}d.baseColorTexture!==void 0&&c.push(t.assignTexture(o,"map",d.baseColorTexture,gt)),o.metalness=d.metallicFactor!==void 0?d.metallicFactor:1,o.roughness=d.roughnessFactor!==void 0?d.roughnessFactor:1,d.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,"metalnessMap",d.metallicRoughnessTexture)),c.push(t.assignTexture(o,"roughnessMap",d.metallicRoughnessTexture))),r=this._invokeOne(function(h){return h.getMaterialType&&h.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(h){return h.extendMaterialParams&&h.extendMaterialParams(e,o)})))}a.doubleSided===!0&&(o.side=ct);const u=a.alphaMode||hp.OPAQUE;if(u===hp.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,u===hp.MASK&&(o.alphaTest=a.alphaCutoff!==void 0?a.alphaCutoff:.5)),a.normalTexture!==void 0&&r!==Ye&&(c.push(t.assignTexture(o,"normalMap",a.normalTexture)),o.normalScale=new te(1,1),a.normalTexture.scale!==void 0)){const d=a.normalTexture.scale;o.normalScale.set(d,d)}if(a.occlusionTexture!==void 0&&r!==Ye&&(c.push(t.assignTexture(o,"aoMap",a.occlusionTexture)),a.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=a.occlusionTexture.strength)),a.emissiveFactor!==void 0&&r!==Ye){const d=a.emissiveFactor;o.emissive=new ue().setRGB(d[0],d[1],d[2],xn)}return a.emissiveTexture!==void 0&&r!==Ye&&c.push(t.assignTexture(o,"emissiveMap",a.emissiveTexture,gt)),Promise.all(c).then(function(){const d=new r(o);return a.name&&(d.name=a.name),rs(d,a),t.associations.set(d,{materials:e}),a.extensions&&La(s,d,a),d})}createUniqueName(e){const t=yt.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,i=this.extensions,s=this.primitiveCache;function a(o){return i[xt.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(l){return ev(l,o,t)})}const r=[];for(let o=0,l=e.length;o0&&sO(m,a),m.name=t.createUniqueName(a.name||"mesh_"+e),rs(m,a),_.extensions&&La(s,m,_),t.assignFinalMaterial(m),d.push(m)}for(let f=0,p=d.length;f1?u=new Mt:c.length===1?u=c[0]:u=new Qe,u!==c[0])for(let d=0,h=c.length;d1){const d=s.associations.get(u);s.associations.set(u,{...d})}return s.associations.get(u).nodes=e,u}),this.nodeCache[e]}loadScene(e){const t=this.extensions,i=this.json.scenes[e],s=this,a=new Mt;i.name&&(a.name=s.createUniqueName(i.name)),rs(a,i),i.extensions&&La(t,a,i);const r=i.nodes||[],o=[];for(let l=0,c=r.length;l{const d=new Map;for(const[h,f]of s.associations)(h instanceof Qt||h instanceof Bt)&&d.set(h,f);return u.traverse(h=>{const f=s.associations.get(h);f!=null&&d.set(h,f)}),d};return s.associations=c(a),a})}_createAnimationTracks(e,t,i,s,a){const r=[],o=e.name?e.name:e.uuid,l=[];Ys[a.path]===Ys.weights?e.traverse(function(h){h.morphTargetInfluences&&l.push(h.name?h.name:h.uuid)}):l.push(o);let c;switch(Ys[a.path]){case Ys.weights:c=ua;break;case Ys.rotation:c=_s;break;case Ys.translation:case Ys.scale:c=Hs;break;default:i.itemSize===1?c=ua:c=Hs;break}const u=s.interpolation!==void 0?tO[s.interpolation]:or,d=this._getArrayFromAccessor(i);for(let h=0,f=l.length;h{this.parse(r,t,s)},i,s)}parse(e,t,i=()=>{}){this.decodeDracoFile(e,t,null,null,gt,i).catch(i)}decodeDracoFile(e,t,i,s,a=xn,r=()=>{}){const o={attributeIDs:i||this.defaultAttributeIDs,attributeTypes:s||this.defaultAttributeTypes,useUniqueIDs:!!i,vertexColorSpace:a};return this.decodeGeometry(e,o).then(t).catch(r)}decodeGeometry(e,t){const i=JSON.stringify(t);if(pp.has(e)){const l=pp.get(e);if(l.key===i)return l.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let s;const a=this.workerNextTaskID++,r=e.byteLength,o=this._getWorker(a,r).then(l=>(s=l,new Promise((c,u)=>{s._callbacks[a]={resolve:c,reject:u},s.postMessage({type:"decode",id:a,taskConfig:t,buffer:e},[e])}))).then(l=>this._createGeometry(l.geometry));return o.catch(()=>!0).then(()=>{s&&a&&this._releaseTask(s,a)}),pp.set(e,{key:i,promise:o}),o}_createGeometry(e){const t=new Ge;e.index&&t.setIndex(new ot(e.index.array,1));for(let i=0;i{i.load(e,s,void 0,a)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(i=>{const s=i[0];e||(this.decoderConfig.wasmBinary=i[1]);const a=uO.toString(),r=["/* draco decoder */",s,"","/* worker */",a.substring(a.indexOf("{")+1,a.lastIndexOf("}"))].join(` +`);this.workerSourceURL=URL.createObjectURL(new Blob([r]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.lengtha._taskLoad?-1:1});const i=this.workerPool[this.workerPool.length-1];return i._taskCosts[e]=t,i._taskLoad+=t,i})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e{const d=u.draco,h=new d.Decoder;try{const f=t(d,h,new Int8Array(l),c),p=f.attributes.map(g=>g.array.buffer);f.index&&p.push(f.index.array.buffer),self.postMessage({type:"decode",id:o.id,geometry:f},p)}catch(f){console.error(f),self.postMessage({type:"error",id:o.id,error:f.message})}finally{d.destroy(h)}});break}};function t(r,o,l,c){const u=c.attributeIDs,d=c.attributeTypes;let h,f;const p=o.GetEncodedGeometryType(l);if(p===r.TRIANGULAR_MESH)h=new r.Mesh,f=o.DecodeArrayToMesh(l,l.byteLength,h);else if(p===r.POINT_CLOUD)h=new r.PointCloud,f=o.DecodeArrayToPointCloud(l,l.byteLength,h);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!f.ok()||h.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+f.error_msg());const g={index:null,attributes:[]};for(const _ in u){const m=self[d[_]];let v,y;if(c.useUniqueIDs)y=u[_],v=o.GetAttributeByUniqueId(h,y);else{if(y=o.GetAttributeId(h,r[u[_]]),y===-1)continue;v=o.GetAttribute(h,y)}const b=s(r,o,h,_,m,v);_==="color"&&(b.vertexColorSpace=c.vertexColorSpace),g.attributes.push(b)}return p===r.TRIANGULAR_MESH&&(g.index=i(r,o,h)),r.destroy(h),g}function i(r,o,l){const u=l.num_faces()*3,d=u*4,h=r._malloc(d);o.GetTrianglesUInt32Array(l,d,h);const f=new Uint32Array(r.HEAPF32.buffer,h,u).slice();return r._free(h),{array:f,itemSize:1}}function s(r,o,l,c,u,d){const h=d.num_components(),p=l.num_points()*h,g=p*u.BYTES_PER_ELEMENT,_=a(r,u),m=r._malloc(g);o.GetAttributeDataArrayForAllPoints(l,d,_,g,m);const v=new u(r.HEAPF32.buffer,m,p).slice();return r._free(m),{name:c,array:v,itemSize:h}}function a(r,o){switch(o){case Float32Array:return r.DT_FLOAT32;case Int8Array:return r.DT_INT8;case Int16Array:return r.DT_INT16;case Int32Array:return r.DT_INT32;case Uint8Array:return r.DT_UINT8;case Uint16Array:return r.DT_UINT16;case Uint32Array:return r.DT_UINT32}}}const dO=/^[og]\s*(.+)?/,hO=/^mtllib /,fO=/^usemtl /,pO=/^usemap /,tv=/\s+/,nv=new S,mp=new S,iv=new S,sv=new S,yi=new S,fu=new ue;function mO(){const n={objects:[],object:{},vertices:[],normals:[],colors:[],uvs:[],materials:{},materialLibraries:[],startObject:function(e,t){if(this.object&&this.object.fromDeclaration===!1){this.object.name=e,this.object.fromDeclaration=t!==!1;return}const i=this.object&&typeof this.object.currentMaterial=="function"?this.object.currentMaterial():void 0;if(this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0),this.object={name:e||"",fromDeclaration:t!==!1,geometry:{vertices:[],normals:[],colors:[],uvs:[],hasUVIndices:!1},materials:[],smooth:!0,startMaterial:function(s,a){const r=this._finalize(!1);r&&(r.inherited||r.groupCount<=0)&&this.materials.splice(r.index,1);const o={index:this.materials.length,name:s||"",mtllib:Array.isArray(a)&&a.length>0?a[a.length-1]:"",smooth:r!==void 0?r.smooth:this.smooth,groupStart:r!==void 0?r.groupEnd:0,groupEnd:-1,groupCount:-1,inherited:!1,clone:function(l){const c={index:typeof l=="number"?l:this.index,name:this.name,mtllib:this.mtllib,smooth:this.smooth,groupStart:0,groupEnd:-1,groupCount:-1,inherited:!1};return c.clone=this.clone.bind(c),c}};return this.materials.push(o),o},currentMaterial:function(){if(this.materials.length>0)return this.materials[this.materials.length-1]},_finalize:function(s){const a=this.currentMaterial();if(a&&a.groupEnd===-1&&(a.groupEnd=this.geometry.vertices.length/3,a.groupCount=a.groupEnd-a.groupStart,a.inherited=!1),s&&this.materials.length>1)for(let r=this.materials.length-1;r>=0;r--)this.materials[r].groupCount<=0&&this.materials.splice(r,1);return s&&this.materials.length===0&&this.materials.push({name:"",smooth:this.smooth}),a}},i&&i.name&&typeof i.clone=="function"){const s=i.clone(0);s.inherited=!0,this.object.materials.push(s)}this.objects.push(this.object)},finalize:function(){this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0)},parseVertexIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseNormalIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseUVIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/2)*2},addVertex:function(e,t,i){const s=this.vertices,a=this.object.geometry.vertices;a.push(s[e+0],s[e+1],s[e+2]),a.push(s[t+0],s[t+1],s[t+2]),a.push(s[i+0],s[i+1],s[i+2])},addVertexPoint:function(e){const t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addVertexLine:function(e){const t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addNormal:function(e,t,i){const s=this.normals,a=this.object.geometry.normals;a.push(s[e+0],s[e+1],s[e+2]),a.push(s[t+0],s[t+1],s[t+2]),a.push(s[i+0],s[i+1],s[i+2])},addFaceNormal:function(e,t,i){const s=this.vertices,a=this.object.geometry.normals;nv.fromArray(s,e),mp.fromArray(s,t),iv.fromArray(s,i),yi.subVectors(iv,mp),sv.subVectors(nv,mp),yi.cross(sv),yi.normalize(),a.push(yi.x,yi.y,yi.z),a.push(yi.x,yi.y,yi.z),a.push(yi.x,yi.y,yi.z)},addColor:function(e,t,i){const s=this.colors,a=this.object.geometry.colors;s[e]!==void 0&&a.push(s[e+0],s[e+1],s[e+2]),s[t]!==void 0&&a.push(s[t+0],s[t+1],s[t+2]),s[i]!==void 0&&a.push(s[i+0],s[i+1],s[i+2])},addUV:function(e,t,i){const s=this.uvs,a=this.object.geometry.uvs;a.push(s[e+0],s[e+1]),a.push(s[t+0],s[t+1]),a.push(s[i+0],s[i+1])},addDefaultUV:function(){const e=this.object.geometry.uvs;e.push(0,0),e.push(0,0),e.push(0,0)},addUVLine:function(e){const t=this.uvs;this.object.geometry.uvs.push(t[e+0],t[e+1])},addFace:function(e,t,i,s,a,r,o,l,c){const u=this.vertices.length;let d=this.parseVertexIndex(e,u),h=this.parseVertexIndex(t,u),f=this.parseVertexIndex(i,u);if(this.addVertex(d,h,f),this.addColor(d,h,f),o!==void 0&&o!==""){const p=this.normals.length;d=this.parseNormalIndex(o,p),h=this.parseNormalIndex(l,p),f=this.parseNormalIndex(c,p),this.addNormal(d,h,f)}else this.addFaceNormal(d,h,f);if(s!==void 0&&s!==""){const p=this.uvs.length;d=this.parseUVIndex(s,p),h=this.parseUVIndex(a,p),f=this.parseUVIndex(r,p),this.addUV(d,h,f),this.object.geometry.hasUVIndices=!0}else this.addDefaultUV()},addPointGeometry:function(e){this.object.geometry.type="Points";const t=this.vertices.length;for(let i=0,s=e.length;i=7?(cu.setRGB(parseFloat(d[4]),parseFloat(d[5]),parseFloat(d[6]),gt),t.colors.push(cu.r,cu.g,cu.b)):t.colors.push(void 0,void 0,void 0);break;case"vn":t.normals.push(parseFloat(d[1]),parseFloat(d[2]),parseFloat(d[3]));break;case"vt":t.uvs.push(parseFloat(d[1]),parseFloat(d[2]));break}}else if(u==="f"){const h=c.slice(1).trim().split(q0),f=[];for(let g=0,_=h.length;g<_;g++){const m=h[g];if(m.length>0){const v=m.split("/");f.push(v)}}const p=f[0];for(let g=1,_=f.length-1;g<_;g++){const m=f[g],v=f[g+1];t.addFace(p[0],m[0],v[0],p[1],m[1],v[1],p[2],m[2],v[2])}}else if(u==="l"){const d=c.substring(1).trim().split(" ");let h=[];const f=[];if(c.indexOf("/")===-1)h=d;else for(let p=0,g=d.length;p1){const h=s[1].trim().toLowerCase();t.object.smooth=h!=="0"&&h!=="off"}else t.object.smooth=!0;const d=t.object.currentMaterial();d&&(d.smooth=t.object.smooth)}else{if(c==="\0")continue;console.warn('THREE.OBJLoader: Unexpected line: "'+c+'"')}}t.finalize();const a=new Mt;if(a.materialLibraries=[].concat(t.materialLibraries),!(t.objects.length===1&&t.objects[0].geometry.vertices.length===0)===!0)for(let o=0,l=t.objects.length;o0&&g.setAttribute("normal",new Ee(u.normals,3)),u.colors.length>0&&(p=!0,g.setAttribute("color",new Ee(u.colors,3))),u.hasUVIndices===!0&&g.setAttribute("uv",new Ee(u.uvs,2));const _=[];for(let v=0,y=d.length;v1){for(let v=0,y=d.length;v0){const o=new sa({size:1,sizeAttenuation:!1}),l=new Ge;l.setAttribute("position",new Ee(t.vertices,3)),t.colors.length>0&&t.colors[0]!==void 0&&(l.setAttribute("color",new Ee(t.colors,3)),o.vertexColors=!0);const c=new ir(l,o);a.add(c)}return a}}const up=new Map;async function rO(n,e){const t=wi("models/stadium/stadium.glb",e);let i=up.get(t);return i||(i=n.loadAsync(t).then(s=>{const a=s.scene;return oO(a),a}).catch(s=>{throw up.delete(t),s}),up.set(t,i)),i}function oO(n){const e=["Sol_Trait_T0","Sol_Trait_T1","Milieu_Forme","Milieu_Forme.001","cage_T0","cage_T1","Couleur_Hexagone_T0","Couleur_Hexagone_T1","wall_gradient_color_2","wall_gradient_color_2.001","Fond_BackBoard_Transparent","dégradé_transparent_T0","dégradé_transparent_T1","grid_transperant","Detail_Milieu","Detail_Milieu.001"],t=["Glow","Glass"],i=["Plafond_Hexagone_T0","Plafond_Hexagone_T1","Plafond_Transparent"];n.traverse(s=>{if(!s.isMesh)return;s.receiveShadow=!0,s.castShadow=!i.includes(s.name),t.some(r=>s.name.includes(r))&&(console.log(`[ArenaManager] Disabling frustum culling for: ${s.name}`),s.frustumCulled=!1),s.material&&/^Hexagone_T[01]$/.test(s.material.name??"")&&(s.material=s.material.clone(),s.material.transparent=!0,s.material.opacity=.18,s.material.depthWrite=!1,s.renderOrder=1),s.material&&s.material.name==="bannière_pub"&&(s.visible=!1),s.material&&s.material.name==="Sol_Hexagone"&&(s.material=s.material.clone(),s.material.color.setScalar(.35),s.material.metalness=0,s.material.roughness=1),s.material&&s.material.name&&e.includes(s.material.name)&&(console.log(`[ArenaManager] Fixing visibility for: ${s.name} (material: ${s.material.name})`),s.material=s.material.clone(),s.material.side=ct,s.material.depthWrite=!1,s.renderOrder=1,s.frustumCulled=!1)})}class lO{constructor(e,t={}){this.scene=e,this.assetBase=t.assetBase,this.arenaMeshes=[],this.drawingCollider=null,this.drawingColliderMeshes=[],this.arenaDecorMesh=null,this.showArenaDecor=!0,this.dracoLoader=new hT,this.dracoLoader.setDecoderPath(wi("draco/",this.assetBase)),this.gltfLoader=new Ag,this.gltfLoader.setDRACOLoader(this.dracoLoader)}async loadArenaMeshes(){try{console.log("Loading arena mesh...");const t=(await rO(this.gltfLoader,this.assetBase)).clone(!0);t.traverse(i=>{i.isMesh&&this.arenaMeshes.push(i)}),console.log(`[ArenaManager] Collected ${this.arenaMeshes.length} meshes for raycasting`),this.scene.add(t),console.log("Arena mesh loaded successfully with correct orientation")}catch(e){console.error("Error loading arena mesh:",e);const t=new Dn(10240,8192),i=new Pn({color:3355443,side:ct}),s=new we(t,i);s.rotation.x=-Math.PI/2,s.receiveShadow=!0,this.scene.add(s),this.arenaMeshes.push(s)}}getArenaMeshes(){return this.arenaMeshes}getDrawingColliderMeshes(){return this.drawingColliderMeshes}async loadDrawingCollider(e=!1){try{console.log("[ArenaManager] Loading drawing collider...");const i=await new aO().loadAsync(wi("models/stadium/DrawingArena.obj",this.assetBase));i.rotation.x=Math.PI/2,i.rotation.y=Math.PI,i.scale.setScalar(.99),i.position.y=20,i.traverse(s=>{s.isMesh&&(this.drawingColliderMeshes.push(s),s.castShadow=!1,s.receiveShadow=!1,e?s.material=new Ye({color:65280,transparent:!0,opacity:.7,side:ct}):s.material=new Ye({visible:!1}))}),this.drawingCollider=i,this.scene.add(i),console.log(`[ArenaManager] Drawing collider loaded with ${this.drawingColliderMeshes.length} meshes`)}catch(t){console.error("[ArenaManager] Failed to load drawing collider:",t)}}setDrawingColliderVisible(e){for(const t of this.drawingColliderMeshes)e?t.material=new Ye({color:65280,wireframe:!0,transparent:!0,opacity:.5}):t.material=new Ye({visible:!1})}async loadArenaDecor(e=!0){try{console.log("[ArenaManager] Loading arena decoration mesh...");const t=await this.gltfLoader.loadAsync(wi("models/stadium/arene.glb",this.assetBase));this.arenaDecorMesh=t.scene,this.showArenaDecor=e,this.arenaDecorMesh.traverse(i=>{i.isMesh&&(i.receiveShadow=!0,i.castShadow=!0)}),this.arenaDecorMesh.visible=e,this.scene.add(this.arenaDecorMesh),console.log(`[ArenaManager] Arena decoration loaded, visible: ${e}`)}catch(t){console.error("[ArenaManager] Failed to load arena decoration:",t)}}setArenaDecorVisible(e){this.showArenaDecor=e,this.arenaDecorMesh&&(this.arenaDecorMesh.visible=e,console.log(`[ArenaManager] Arena decoration visibility set to: ${e}`))}isArenaDecorVisible(){return this.showArenaDecor}}var Si=Uint8Array,Zr=Uint16Array,cO=Int32Array,fT=new Si([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),pT=new Si([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),uO=new Si([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),mT=function(n,e){for(var t=new Zr(31),i=0;i<31;++i)t[i]=e+=1<>1|(Nt&21845)<<1;js=(js&52428)>>2|(js&13107)<<2,js=(js&61680)>>4|(js&3855)<<4,Dm[Nt]=((js&65280)>>8|(js&255)<<8)>>1}var Il=(function(n,e,t){for(var i=n.length,s=0,a=new Zr(e);s>l]=c}else for(o=new Zr(i),s=0;s>15-n[s]);return o}),hc=new Si(288);for(var Nt=0;Nt<144;++Nt)hc[Nt]=8;for(var Nt=144;Nt<256;++Nt)hc[Nt]=9;for(var Nt=256;Nt<280;++Nt)hc[Nt]=7;for(var Nt=280;Nt<288;++Nt)hc[Nt]=8;var yT=new Si(32);for(var Nt=0;Nt<32;++Nt)yT[Nt]=5;var pO=Il(hc,9,1),mO=Il(yT,5,1),dp=function(n){for(var e=n[0],t=1;te&&(e=n[t]);return e},ki=function(n,e,t){var i=e/8|0;return(n[i]|n[i+1]<<8)>>(e&7)&t},hp=function(n,e){var t=e/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},_O=function(n){return(n+7)/8|0},gO=function(n,e,t){return(t==null||t>n.length)&&(t=n.length),new Si(n.subarray(e,t))},yO=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Hi=function(n,e,t){var i=new Error(e||yO[n]);if(i.code=n,Error.captureStackTrace&&Error.captureStackTrace(i,Hi),!t)throw i;return i},vO=function(n,e,t,i){var s=n.length,a=0;if(!s||e.f&&!e.l)return t||new Si(0);var r=!t,o=r||e.i!=2,l=e.i;r&&(t=new Si(s*3));var c=function(xe){var Ae=t.length;if(xe>Ae){var L=new Si(Math.max(Ae*2,xe));L.set(t),t=L}},u=e.f||0,d=e.p||0,h=e.b||0,f=e.l,p=e.d,g=e.m,_=e.n,m=s*8;do{if(!f){u=ki(n,d,1);var v=ki(n,d+1,3);if(d+=3,v)if(v==1)f=pO,p=mO,g=9,_=5;else if(v==2){var x=ki(n,d,31)+257,M=ki(n,d+10,15)+4,C=x+ki(n,d+5,31)+1;d+=14;for(var w=new Si(C),E=new Si(19),R=0;R>4;if(y<16)w[R++]=y;else{var F=0,W=0;for(y==16?(W=3+ki(n,d,3),d+=2,F=w[R-1]):y==17?(W=3+ki(n,d,7),d+=3):y==18&&(W=11+ki(n,d,127),d+=7);W--;)w[R++]=F}}var H=w.subarray(0,x),ne=w.subarray(x);g=dp(H),_=dp(ne),f=Il(H,g,1),p=Il(ne,_,1)}else Hi(1);else{var y=_O(d)+4,b=n[y-4]|n[y-3]<<8,T=y+b;if(T>s){l&&Hi(0);break}o&&c(h+b),t.set(n.subarray(y,T),h),e.b=h+=b,e.p=d=T*8,e.f=u;continue}if(d>m){l&&Hi(0);break}}o&&c(h+131072);for(var oe=(1<>4;if(d+=F&15,d>m){l&&Hi(0);break}if(F||Hi(2),De<256)t[h++]=De;else if(De==256){Ie=d,f=null;break}else{var Xe=De-254;if(De>264){var R=De-257,ke=fT[R];Xe=ki(n,d,(1<>4;Z||Hi(3),d+=Z&15;var ne=fO[se];if(se>3){var ke=pT[se];ne+=hp(n,d)&(1<m){l&&Hi(0);break}o&&c(h+131072);var Se=h+Xe;if(h>4>7||(n[0]<<8|n[1])%31)&&Hi(6,"invalid zlib data"),(n[1]>>5&1)==1&&Hi(6,"invalid zlib data: "+(n[1]&32?"need":"unexpected")+" dictionary"),(n[1]>>3&4)+2};function wO(n,e){return vO(n.subarray(xO(n),-4),{i:2},e,e)}var SO=typeof TextDecoder<"u"&&new TextDecoder,TO=0;try{SO.decode(bO,{stream:!0}),TO=1}catch{}function vT(n,e,t){const i=t.length-n-1;if(e>=t[i])return i-1;if(e<=t[n])return n;let s=n,a=i,r=Math.floor((s+a)/2);for(;e=t[r+1];)e=g&&(p[f][0]=p[h][0]/o[v+1][m],_=p[f][0]*o[m][v]);const y=m>=-1?1:-m,b=d-1<=v?g-1:t-d;for(let x=y;x<=b;++x)p[f][x]=(p[h][x]-p[h][x-1])/o[v+1][m+x],_+=p[f][x]*o[m+x][v];d<=v&&(p[f][g]=-p[h][g-1]/o[v+1][d],_+=p[f][g]*o[d][v]),r[g][d]=_;const T=h;h=f,f=T}}let u=t;for(let d=1;d<=i;++d){for(let h=0;h<=t;++h)r[d][h]*=u;u*=t-d}return r}function AO(n,e,t,i,s){const a=st.toArray()),e.startKnot=this.startKnot,e.endKnot=this.endKnot,e}fromJSON(e){return super.fromJSON(e),this.degree=e.degree,this.knots=[...e.knots],this.controlPoints=e.controlPoints.map(t=>new qe(t[0],t[1],t[2],t[3])),this.startKnot=e.startKnot,this.endKnot=e.endKnot,this}}let _t,Zt,Un;class DO extends on{constructor(e){super(e)}load(e,t,i,s){const a=this,r=a.path===""?Us.extractUrlBase(e):a.path,o=new Gn(this.manager);o.setPath(a.path),o.setResponseType("arraybuffer"),o.setRequestHeader(a.requestHeader),o.setWithCredentials(a.withCredentials),o.load(e,function(l){try{t(a.parse(l,r))}catch(c){s?s(c):console.error(c),a.manager.itemError(e)}},i,s)}parse(e,t){if(BO(e))_t=new UO().parse(e);else{const s=wT(e);if(!zO(s))throw new Error("THREE.FBXLoader: Unknown format.");if(Q0(s)<7e3)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+Q0(s));_t=new NO().parse(s)}const i=new Yh(this.manager).setPath(this.resourcePath||t).setCrossOrigin(this.crossOrigin);return new kO(i,this.manager).parse(_t)}}class kO{constructor(e,t){this.textureLoader=e,this.manager=t}parse(){Zt=this.parseConnections();const e=this.parseImages(),t=this.parseTextures(e),i=this.parseMaterials(t),s=this.parseDeformers(),a=new OO().parse(s);return this.parseScene(s,a,i),Un}parseConnections(){const e=new Map;return"Connections"in _t&&_t.Connections.connections.forEach(function(i){const s=i[0],a=i[1],r=i[2];e.has(s)||e.set(s,{parents:[],children:[]});const o={ID:a,relationship:r};e.get(s).parents.push(o),e.has(a)||e.set(a,{parents:[],children:[]});const l={ID:s,relationship:r};e.get(a).children.push(l)}),e}parseImages(){const e={},t={};if("Video"in _t.Objects){const i=_t.Objects.Video;for(const s in i){const a=i[s],r=parseInt(s);if(e[r]=a.RelativeFilename||a.Filename,"Content"in a){const o=a.Content instanceof ArrayBuffer&&a.Content.byteLength>0,l=typeof a.Content=="string"&&a.Content!=="";if(o||l){const c=this.parseImage(i[s]);t[a.RelativeFilename||a.Filename]=c}}}}for(const i in e){const s=e[i];t[s]!==void 0?e[i]=t[s]:e[i]=e[i].split("\\").pop()}return e}parseImage(e){const t=e.Content,i=e.RelativeFilename||e.Filename,s=i.slice(i.lastIndexOf(".")+1).toLowerCase();let a;switch(s){case"bmp":a="image/bmp";break;case"jpg":case"jpeg":a="image/jpeg";break;case"png":a="image/png";break;case"tif":a="image/tiff";break;case"tga":this.manager.getHandler(".tga")===null&&console.warn("FBXLoader: TGA loader not found, skipping ",i),a="image/tga";break;case"webp":a="image/webp";break;default:console.warn('FBXLoader: Image type "'+s+'" is not supported.');return}if(typeof t=="string")return"data:"+a+";base64,"+t;{const r=new Uint8Array(t);return window.URL.createObjectURL(new Blob([r],{type:a}))}}parseTextures(e){const t=new Map;if("Texture"in _t.Objects){const i=_t.Objects.Texture;for(const s in i){const a=this.parseTexture(i[s],e);t.set(parseInt(s),a)}}return t}parseTexture(e,t){const i=this.loadTexture(e,t);i.ID=e.id,i.name=e.attrName;const s=e.WrapModeU,a=e.WrapModeV,r=s!==void 0?s.value:0,o=a!==void 0?a.value:0;if(i.wrapS=r===0?ps:Hn,i.wrapT=o===0?ps:Hn,"Scaling"in e){const l=e.Scaling.value;i.repeat.x=l[0],i.repeat.y=l[1]}if("Translation"in e){const l=e.Translation.value;i.offset.x=l[0],i.offset.y=l[1]}return i}loadTexture(e,t){const i=e.FileName.split(".").pop().toLowerCase();let s=this.manager.getHandler(`.${i}`);s===null&&(s=this.textureLoader);const a=s.path;a||s.setPath(this.textureLoader.path);const r=Zt.get(e.id).children;let o;if(r!==void 0&&r.length>0&&t[r[0].ID]!==void 0&&(o=t[r[0].ID],(o.indexOf("blob:")===0||o.indexOf("data:")===0)&&s.setPath(void 0)),o===void 0)return console.warn("FBXLoader: Undefined filename, creating placeholder texture."),new Bt;const l=s.load(o);return s.setPath(a),l}parseMaterials(e){const t=new Map;if("Material"in _t.Objects){const i=_t.Objects.Material;for(const s in i){const a=this.parseMaterial(i[s],e);a!==null&&t.set(parseInt(s),a)}}return t}parseMaterial(e,t){const i=e.id,s=e.attrName;let a=e.ShadingModel;if(typeof a=="object"&&(a=a.value),!Zt.has(i))return null;const r=this.parseParameters(e,t,i);let o;switch(a.toLowerCase()){case"phong":o=new Ya;break;case"lambert":o=new qh;break;default:console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.',a),o=new Ya;break}return o.setValues(r),o.name=s,o}parseParameters(e,t,i){const s={};e.BumpFactor&&(s.bumpScale=e.BumpFactor.value),e.Diffuse?s.color=at.colorSpaceToWorking(new ue().fromArray(e.Diffuse.value),gt):e.DiffuseColor&&(e.DiffuseColor.type==="Color"||e.DiffuseColor.type==="ColorRGB")&&(s.color=at.colorSpaceToWorking(new ue().fromArray(e.DiffuseColor.value),gt)),e.DisplacementFactor&&(s.displacementScale=e.DisplacementFactor.value),e.Emissive?s.emissive=at.colorSpaceToWorking(new ue().fromArray(e.Emissive.value),gt):e.EmissiveColor&&(e.EmissiveColor.type==="Color"||e.EmissiveColor.type==="ColorRGB")&&(s.emissive=at.colorSpaceToWorking(new ue().fromArray(e.EmissiveColor.value),gt)),e.EmissiveFactor&&(s.emissiveIntensity=parseFloat(e.EmissiveFactor.value)),s.opacity=1-(e.TransparencyFactor?parseFloat(e.TransparencyFactor.value):0),(s.opacity===1||s.opacity===0)&&(s.opacity=e.Opacity?parseFloat(e.Opacity.value):null,s.opacity===null&&(s.opacity=1-(e.TransparentColor?parseFloat(e.TransparentColor.value[0]):0))),s.opacity<1&&(s.transparent=!0),e.ReflectionFactor&&(s.reflectivity=e.ReflectionFactor.value),e.Shininess&&(s.shininess=e.Shininess.value),e.Specular?s.specular=at.colorSpaceToWorking(new ue().fromArray(e.Specular.value),gt):e.SpecularColor&&e.SpecularColor.type==="Color"&&(s.specular=at.colorSpaceToWorking(new ue().fromArray(e.SpecularColor.value),gt));const a=this;return Zt.get(i).children.forEach(function(r){const o=r.relationship;switch(o){case"Bump":s.bumpMap=a.getTexture(t,r.ID);break;case"Maya|TEX_ao_map":s.aoMap=a.getTexture(t,r.ID);break;case"DiffuseColor":case"Maya|TEX_color_map":s.map=a.getTexture(t,r.ID),s.map!==void 0&&(s.map.colorSpace=gt);break;case"DisplacementColor":s.displacementMap=a.getTexture(t,r.ID);break;case"EmissiveColor":s.emissiveMap=a.getTexture(t,r.ID),s.emissiveMap!==void 0&&(s.emissiveMap.colorSpace=gt);break;case"NormalMap":case"Maya|TEX_normal_map":s.normalMap=a.getTexture(t,r.ID);break;case"ReflectionColor":s.envMap=a.getTexture(t,r.ID),s.envMap!==void 0&&(s.envMap.mapping=ar,s.envMap.colorSpace=gt);break;case"SpecularColor":s.specularMap=a.getTexture(t,r.ID),s.specularMap!==void 0&&(s.specularMap.colorSpace=gt);break;case"TransparentColor":case"TransparencyFactor":s.alphaMap=a.getTexture(t,r.ID),s.transparent=!0;break;default:console.warn("THREE.FBXLoader: %s map is not supported in three.js, skipping texture.",o);break}}),s}getTexture(e,t){return"LayeredTexture"in _t.Objects&&t in _t.Objects.LayeredTexture&&(console.warn("THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer."),t=Zt.get(t).children[0].ID),e.get(t)}parseDeformers(){const e={},t={};if("Deformer"in _t.Objects){const i=_t.Objects.Deformer;for(const s in i){const a=i[s],r=Zt.get(parseInt(s));if(a.attrType==="Skin"){const o=this.parseSkeleton(r,i);o.ID=s,r.parents.length>1&&console.warn("THREE.FBXLoader: skeleton attached to more than one geometry is not supported."),o.geometryID=r.parents[0].ID,e[s]=o}else if(a.attrType==="BlendShape"){const o={id:s};o.rawTargets=this.parseMorphTargets(r,i),o.id=s,r.parents.length>1&&console.warn("THREE.FBXLoader: morph target attached to more than one geometry is not supported."),t[s]=o}}}return{skeletons:e,morphTargets:t}}parseSkeleton(e,t){const i=[];return e.children.forEach(function(s){const a=t[s.ID];if(a.attrType!=="Cluster")return;const r={ID:s.ID,indices:[],weights:[],transformLink:new Me().fromArray(a.TransformLink.a)};"Indexes"in a&&(r.indices=a.Indexes.a,r.weights=a.Weights.a),i.push(r)}),{rawBones:i,bones:[]}}parseMorphTargets(e,t){const i=[];for(let s=0;s1?r=o:o.length>0?r=o[0]:(r=new Ya({name:on.DEFAULT_MATERIAL_NAME,color:13421772}),o.push(r)),"color"in a.attributes&&o.forEach(function(l){l.vertexColors=!0}),a.groups.length>0){let l=!1;for(let c=0,u=a.groups.length;c=o.length)&&(d.materialIndex=o.length,l=!0)}if(l){const c=new Ya;o.push(c)}}return a.FBX_Deformer?(s=new Dh(a,r),s.normalizeSkinWeights()):s=new we(a,r),s}createCurve(e,t){const i=e.children.reduce(function(a,r){return t.has(r.ID)&&(a=t.get(r.ID)),a},null),s=new Rt({name:on.DEFAULT_MATERIAL_NAME,color:3342591,linewidth:1});return new In(i,s)}getTransformData(e,t){const i={};"InheritType"in t&&(i.inheritType=parseInt(t.InheritType.value)),"RotationOrder"in t?i.eulerOrder=Kl(t.RotationOrder.value):i.eulerOrder=Kl(0),"Lcl_Translation"in t&&(i.translation=t.Lcl_Translation.value),"PreRotation"in t&&(i.preRotation=t.PreRotation.value),"Lcl_Rotation"in t&&(i.rotation=t.Lcl_Rotation.value),"PostRotation"in t&&(i.postRotation=t.PostRotation.value),"Lcl_Scaling"in t&&(i.scale=t.Lcl_Scaling.value),"ScalingOffset"in t&&(i.scalingOffset=t.ScalingOffset.value),"ScalingPivot"in t&&(i.scalingPivot=t.ScalingPivot.value),"RotationOffset"in t&&(i.rotationOffset=t.RotationOffset.value),"RotationPivot"in t&&(i.rotationPivot=t.RotationPivot.value),e.userData.transformData=i}setLookAtProperties(e,t){"LookAtProperty"in t&&Zt.get(e.ID).children.forEach(function(s){if(s.relationship==="LookAtProperty"){const a=_t.Objects.Model[s.ID];if("Lcl_Translation"in a){const r=a.Lcl_Translation.value;e.target!==void 0?(e.target.position.fromArray(r),Un.add(e.target)):e.lookAt(new S().fromArray(r))}}})}bindSkeleton(e,t,i){const s=this.parsePoseNodes();for(const a in e){const r=e[a];Zt.get(parseInt(r.ID)).parents.forEach(function(l){if(t.has(l.ID)){const c=l.ID;Zt.get(c).parents.forEach(function(d){i.has(d.ID)&&i.get(d.ID).bind(new Ro(r.bones),s[d.ID])})}})}}parsePoseNodes(){const e={};if("Pose"in _t.Objects){const t=_t.Objects.Pose;for(const i in t)if(t[i].attrType==="BindPose"&&t[i].NbPoseNodes>0){const s=t[i].PoseNode;Array.isArray(s)?s.forEach(function(a){e[a.Node]=new Me().fromArray(a.Matrix.a)}):e[s.Node]=new Me().fromArray(s.Matrix.a)}}return e}addGlobalSceneSettings(){if("GlobalSettings"in _t){if("AmbientColor"in _t.GlobalSettings){const e=_t.GlobalSettings.AmbientColor.value,t=e[0],i=e[1],s=e[2];if(t!==0||i!==0||s!==0){const a=new ue().setRGB(t,i,s,gt);Un.add(new dc(a,1))}}"UnitScaleFactor"in _t.GlobalSettings&&(Un.userData.unitScaleFactor=_t.GlobalSettings.UnitScaleFactor.value)}}}class OO{constructor(){this.negativeMaterialIndices=!1}parse(e){const t=new Map;if("Geometry"in _t.Objects){const i=_t.Objects.Geometry;for(const s in i){const a=Zt.get(parseInt(s)),r=this.parseGeometry(a,i[s],e);t.set(parseInt(s),r)}}return this.negativeMaterialIndices===!0&&console.warn("THREE.FBXLoader: The FBX file contains invalid (negative) material indices. The asset might not render as expected."),t}parseGeometry(e,t,i){switch(t.attrType){case"Mesh":return this.parseMeshGeometry(e,t,i);case"NurbsCurve":return this.parseNurbsGeometry(t)}}parseMeshGeometry(e,t,i){const s=i.skeletons,a=[],r=e.parents.map(function(d){return _t.Objects.Model[d.ID]});if(r.length===0)return;const o=e.children.reduce(function(d,h){return s[h.ID]!==void 0&&(d=s[h.ID]),d},null);e.children.forEach(function(d){i.morphTargets[d.ID]!==void 0&&a.push(i.morphTargets[d.ID])});const l=r[0],c={};"RotationOrder"in l&&(c.eulerOrder=Kl(l.RotationOrder.value)),"InheritType"in l&&(c.inheritType=parseInt(l.InheritType.value)),"GeometricTranslation"in l&&(c.translation=l.GeometricTranslation.value),"GeometricRotation"in l&&(c.rotation=l.GeometricRotation.value),"GeometricScaling"in l&&(c.scale=l.GeometricScaling.value);const u=xT(c);return this.genGeometry(t,o,a,u)}genGeometry(e,t,i,s){const a=new Ge;e.attrName&&(a.name=e.attrName);const r=this.parseGeoNode(e,t),o=this.genBuffers(r),l=new Ee(o.vertex,3);if(l.applyMatrix4(s),a.setAttribute("position",l),o.colors.length>0&&a.setAttribute("color",new Ee(o.colors,3)),t&&(a.setAttribute("skinIndex",new Ch(o.weightsIndices,4)),a.setAttribute("skinWeight",new Ee(o.vertexWeights,4)),a.FBX_Deformer=t),o.normal.length>0){const c=new st().getNormalMatrix(s),u=new Ee(o.normal,3);u.applyNormalMatrix(c),a.setAttribute("normal",u)}if(o.uvs.forEach(function(c,u){const d=u===0?"uv":`uv${u}`;a.setAttribute(d,new Ee(o.uvs[u],2))}),r.material&&r.material.mappingType!=="AllSame"){let c=o.materialIndex[0],u=0;if(o.materialIndex.forEach(function(d,h){d!==c&&(a.addGroup(u,h-u,c),c=d,u=h)}),a.groups.length>0){const d=a.groups[a.groups.length-1],h=d.start+d.count;h!==o.materialIndex.length&&a.addGroup(h,o.materialIndex.length-h,c)}a.groups.length===0&&a.addGroup(0,o.materialIndex.length,o.materialIndex[0])}return this.addMorphTargets(a,e,i,s),a}parseGeoNode(e,t){const i={};if(i.vertexPositions=e.Vertices!==void 0?e.Vertices.a:[],i.vertexIndices=e.PolygonVertexIndex!==void 0?e.PolygonVertexIndex.a:[],e.LayerElementColor&&e.LayerElementColor[0].Colors&&(i.color=this.parseVertexColors(e.LayerElementColor[0])),e.LayerElementMaterial&&(i.material=this.parseMaterialIndices(e.LayerElementMaterial[0])),e.LayerElementNormal&&(i.normal=this.parseNormals(e.LayerElementNormal[0])),e.LayerElementUV){i.uv=[];let s=0;for(;e.LayerElementUV[s];)e.LayerElementUV[s].UV&&i.uv.push(this.parseUVs(e.LayerElementUV[s])),s++}return i.weightTable={},t!==null&&(i.skeleton=t,t.rawBones.forEach(function(s,a){s.indices.forEach(function(r,o){i.weightTable[r]===void 0&&(i.weightTable[r]=[]),i.weightTable[r].push({id:a,weight:s.weights[o]})})})),i}genBuffers(e){const t={vertex:[],normal:[],colors:[],uvs:[],materialIndex:[],vertexWeights:[],weightsIndices:[]};let i=0,s=0,a=!1,r=[],o=[],l=[],c=[],u=[],d=[];const h=this;return e.vertexIndices.forEach(function(f,p){let g,_=!1;f<0&&(f=f^-1,_=!0);let m=[],v=[];if(r.push(f*3,f*3+1,f*3+2),e.color){const y=uu(p,i,f,e.color);l.push(y[0],y[1],y[2])}if(e.skeleton){if(e.weightTable[f]!==void 0&&e.weightTable[f].forEach(function(y){v.push(y.weight),m.push(y.id)}),v.length>4){a||(console.warn("THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights."),a=!0);const y=[0,0,0,0],b=[0,0,0,0];v.forEach(function(T,x){let M=T,C=m[x];b.forEach(function(w,E,R){if(M>w){R[E]=M,M=w;const D=y[E];y[E]=C,C=D}})}),m=y,v=b}for(;v.length<4;)v.push(0),m.push(0);for(let y=0;y<4;++y)u.push(v[y]),d.push(m[y])}if(e.normal){const y=uu(p,i,f,e.normal);o.push(y[0],y[1],y[2])}e.material&&e.material.mappingType!=="AllSame"&&(g=uu(p,i,f,e.material)[0],g<0&&(h.negativeMaterialIndices=!0,g=0)),e.uv&&e.uv.forEach(function(y,b){const T=uu(p,i,f,y);c[b]===void 0&&(c[b]=[]),c[b].push(T[0]),c[b].push(T[1])}),s++,_&&(h.genFace(t,e,r,g,o,l,c,u,d,s),i++,s=0,r=[],o=[],l=[],c=[],u=[],d=[])}),t}getNormalNewell(e){const t=new S(0,0,0);for(let i=0;i.5?new S(0,1,0):new S(0,0,1)).cross(t).normalize(),a=t.clone().cross(s).normalize();return{normal:t,tangent:s,bitangent:a}}flattenVertex(e,t,i){return new te(e.dot(t),e.dot(i))}genFace(e,t,i,s,a,r,o,l,c,u){let d;if(u>3){const h=[],f=t.baseVertexPositions||t.vertexPositions;for(let m=0;m1&&console.warn("THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.");const r=e.get(a[0].ID);i[s]={name:t[s].attrName,layer:r}}return i}addClip(e){let t=[];const i=this;return e.layer.forEach(function(s){t=t.concat(i.generateTracks(s))}),new ua(e.name,-1,t)}generateTracks(e){const t=[];let i=new S,s=new S;if(e.transform&&e.transform.decompose(i,new dt,s),i=i.toArray(),s=s.toArray(),e.T!==void 0&&Object.keys(e.T.curves).length>0){const a=this.generateVectorTrack(e.modelName,e.T.curves,i,"position");a!==void 0&&t.push(a)}if(e.R!==void 0&&Object.keys(e.R.curves).length>0){const a=this.generateRotationTrack(e.modelName,e.R.curves,e.preRotation,e.postRotation,e.eulerOrder);a!==void 0&&t.push(a)}if(e.S!==void 0&&Object.keys(e.S.curves).length>0){const a=this.generateVectorTrack(e.modelName,e.S.curves,s,"scale");a!==void 0&&t.push(a)}if(e.DeformPercent!==void 0){const a=this.generateMorphTrack(e);a!==void 0&&t.push(a)}return t}generateVectorTrack(e,t,i,s){const a=this.getTimesForAllAxes(t),r=this.getKeyframeTrackValues(a,t,i);return new Hs(e+"."+s,a,r)}generateRotationTrack(e,t,i,s,a){let r,o;if(t.x!==void 0&&t.y!==void 0&&t.z!==void 0){const h=this.interpolateRotations(t.x,t.y,t.z,a);r=h[0],o=h[1]}const l=Kl(0);i!==void 0&&(i=i.map(vt.degToRad),i.push(l),i=new an().fromArray(i),i=new dt().setFromEuler(i)),s!==void 0&&(s=s.map(vt.degToRad),s.push(l),s=new an().fromArray(s),s=new dt().setFromEuler(s).invert());const c=new dt,u=new an,d=[];if(!o||!r)return new _s(e+".quaternion",[0],[0]);for(let h=0;h2&&new dt().fromArray(d,(h-3)/3*4).dot(c)<0&&c.set(-c.x,-c.y,-c.z,-c.w),c.toArray(d,h/3*4);return new _s(e+".quaternion",r,d)}generateMorphTrack(e){const t=e.DeformPercent.curves.morph,i=t.values.map(function(a){return a/100}),s=Un.getObjectByName(e.modelName).morphTargetDictionary[e.morphName];return new ca(e.modelName+".morphTargetInfluences["+s+"]",t.times,i)}getTimesForAllAxes(e){let t=[];if(e.x!==void 0&&(t=t.concat(e.x.times)),e.y!==void 0&&(t=t.concat(e.y.times)),e.z!==void 0&&(t=t.concat(e.z.times)),t=t.sort(function(i,s){return i-s}),t.length>1){let i=1,s=t[0];for(let a=1;a=180||f[1]>=180||f[2]>=180){const g=Math.max(...f)/180,_=new an(...c,s),m=new an(...d,s),v=new dt().setFromEuler(_),y=new dt().setFromEuler(m);v.dot(y)&&y.set(-y.x,-y.y,-y.z,-y.w);const b=e.times[o-1],T=e.times[o]-b,x=new dt,M=new an;for(let C=0;C<1;C+=1/g)x.copy(v.clone().slerp(y.clone(),C)),a.push(b+C*T),M.setFromQuaternion(x,s),r.push(M.x),r.push(M.y),r.push(M.z)}else a.push(e.times[o]),r.push(vt.degToRad(e.values[o])),r.push(vt.degToRad(t.values[o])),r.push(vt.degToRad(i.values[o]))}return[a,r]}}class NO{getPrevNode(){return this.nodeStack[this.currentIndent-2]}getCurrentNode(){return this.nodeStack[this.currentIndent-1]}getCurrentProp(){return this.currentProp}pushStack(e){this.nodeStack.push(e),this.currentIndent+=1}popStack(){this.nodeStack.pop(),this.currentIndent-=1}setCurrentProp(e,t){this.currentProp=e,this.currentPropName=t}parse(e){this.currentIndent=0,this.allNodes=new bT,this.nodeStack=[],this.currentProp=[],this.currentPropName="";const t=this,i=e.split(/[\r\n]+/);return i.forEach(function(s,a){const r=s.match(/^[\s\t]*;/),o=s.match(/^[\s\t]*$/);if(r||o)return;const l=s.match("^\\t{"+t.currentIndent+"}(\\w+):(.*){",""),c=s.match("^\\t{"+t.currentIndent+"}(\\w+):[\\s\\t\\r\\n](.*)"),u=s.match("^\\t{"+(t.currentIndent-1)+"}}");l?t.parseNodeBegin(s,l):c?t.parseNodeProperty(s,c,i[++a]):u?t.popStack():s.match(/^[^\s\t}]/)&&t.parseNodePropertyContinued(s)}),this.allNodes}parseNodeBegin(e,t){const i=t[1].trim().replace(/^"/,"").replace(/"$/,""),s=t[2].split(",").map(function(l){return l.trim().replace(/^"/,"").replace(/"$/,"")}),a={name:i},r=this.parseNodeAttr(s),o=this.getCurrentNode();this.currentIndent===0?this.allNodes.add(i,a):i in o?(i==="PoseNode"?o.PoseNode.push(a):o[i].id!==void 0&&(o[i]={},o[i][o[i].id]=o[i]),r.id!==""&&(o[i][r.id]=a)):typeof r.id=="number"?(o[i]={},o[i][r.id]=a):i!=="Properties70"&&(i==="PoseNode"?o[i]=[a]:o[i]=a),typeof r.id=="number"&&(a.id=r.id),r.name!==""&&(a.attrName=r.name),r.type!==""&&(a.attrType=r.type),this.pushStack(a)}parseNodeAttr(e){let t=e[0];e[0]!==""&&(t=parseInt(e[0]),isNaN(t)&&(t=e[0]));let i="",s="";return e.length>1&&(i=e[1].replace(/^(\w+)::/,""),s=e[2]),{id:t,name:i,type:s}}parseNodeProperty(e,t,i){let s=t[1].replace(/^"/,"").replace(/"$/,"").trim(),a=t[2].replace(/^"/,"").replace(/"$/,"").trim();s==="Content"&&a===","&&(a=i.replace(/"/g,"").replace(/,$/,"").trim());const r=this.getCurrentNode();if(r.name==="Properties70"){this.parseNodeSpecialProperty(e,s,a);return}if(s==="C"){const l=a.split(",").slice(1),c=parseInt(l[0]),u=parseInt(l[1]);let d=a.split(",").slice(3);d=d.map(function(h){return h.trim().replace(/^"/,"")}),s="connections",a=[c,u],GO(a,d),r[s]===void 0&&(r[s]=[])}s==="Node"&&(r.id=a),s in r&&Array.isArray(r[s])?r[s].push(a):s!=="a"?r[s]=a:r.a=a,this.setCurrentProp(r,s),s==="a"&&a.slice(-1)!==","&&(r.a=pp(a))}parseNodePropertyContinued(e){const t=this.getCurrentNode();t.a+=e,e.slice(-1)!==","&&(t.a=pp(t.a))}parseNodeSpecialProperty(e,t,i){const s=i.split('",').map(function(u){return u.trim().replace(/^\"/,"").replace(/\s/,"_")}),a=s[0],r=s[1],o=s[2],l=s[3];let c=s[4];switch(r){case"int":case"enum":case"bool":case"ULongLong":case"double":case"Number":case"FieldOfView":c=parseFloat(c);break;case"Color":case"ColorRGB":case"Vector3D":case"Lcl_Translation":case"Lcl_Rotation":case"Lcl_Scaling":c=pp(c);break}this.getPrevNode()[a]={type:r,type2:o,flag:l,value:c},this.setCurrentProp(this.getPrevNode(),a)}}class UO{parse(e){const t=new J0(e);t.skip(23);const i=t.getUint32();if(i<6400)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+i);const s=new bT;for(;!this.endOfContent(t);){const a=this.parseNode(t,i);a!==null&&s.add(a.name,a)}return s}endOfContent(e){return e.size()%16===0?(e.getOffset()+160+16&-16)>=e.size():e.getOffset()+160+16>=e.size()}parseNode(e,t){const i={},s=t>=7500?e.getUint64():e.getUint32(),a=t>=7500?e.getUint64():e.getUint32();t>=7500?e.getUint64():e.getUint32();const r=e.getUint8(),o=e.getString(r);if(s===0)return null;const l=[];for(let h=0;h0?l[0]:"",u=l.length>1?l[1]:"",d=l.length>2?l[2]:"";for(i.singleProperty=a===1&&e.getOffset()===s;s>e.getOffset();){const h=this.parseNode(e,t);h!==null&&this.parseSubNode(o,i,h)}return i.propertyList=l,typeof c=="number"&&(i.id=c),u!==""&&(i.attrName=u),d!==""&&(i.attrType=d),o!==""&&(i.name=o),i}parseSubNode(e,t,i){if(i.singleProperty===!0){const s=i.propertyList[0];Array.isArray(s)?(t[i.name]=i,i.a=s):t[i.name]=s}else if(e==="Connections"&&i.name==="C"){const s=[];i.propertyList.forEach(function(a,r){r!==0&&s.push(a)}),t.connections===void 0&&(t.connections=[]),t.connections.push(s)}else if(i.name==="Properties70")Object.keys(i).forEach(function(a){t[a]=i[a]});else if(e==="Properties70"&&i.name==="P"){let s=i.propertyList[0],a=i.propertyList[1];const r=i.propertyList[2],o=i.propertyList[3];let l;s.indexOf("Lcl ")===0&&(s=s.replace("Lcl ","Lcl_")),a.indexOf("Lcl ")===0&&(a=a.replace("Lcl ","Lcl_")),a==="Color"||a==="ColorRGB"||a==="Vector"||a==="Vector3D"||a.indexOf("Lcl_")===0?l=[i.propertyList[4],i.propertyList[5],i.propertyList[6]]:l=i.propertyList[4],t[s]={type:a,type2:r,flag:o,value:l}}else t[i.name]===void 0?typeof i.id=="number"?(t[i.name]={},t[i.name][i.id]=i):t[i.name]=i:i.name==="PoseNode"?(Array.isArray(t[i.name])||(t[i.name]=[t[i.name]]),t[i.name].push(i)):t[i.name][i.id]===void 0&&(t[i.name][i.id]=i)}parseProperty(e){const t=e.getString(1);let i;switch(t){case"C":return e.getBoolean();case"D":return e.getFloat64();case"F":return e.getFloat32();case"I":return e.getInt32();case"L":return e.getInt64();case"R":return i=e.getUint32(),e.getArrayBuffer(i);case"S":return i=e.getUint32(),e.getString(i);case"Y":return e.getInt16();case"b":case"c":case"d":case"f":case"i":case"l":const s=e.getUint32(),a=e.getUint32(),r=e.getUint32();if(a===0)switch(t){case"b":case"c":return e.getBooleanArray(s);case"d":return e.getFloat64Array(s);case"f":return e.getFloat32Array(s);case"i":return e.getInt32Array(s);case"l":return e.getInt64Array(s)}const o=wO(new Uint8Array(e.getArrayBuffer(r))),l=new J0(o.buffer);switch(t){case"b":case"c":return l.getBooleanArray(s);case"d":return l.getFloat64Array(s);case"f":return l.getFloat32Array(s);case"i":return l.getInt32Array(s);case"l":return l.getInt64Array(s)}break;default:throw new Error("THREE.FBXLoader: Unknown property type "+t)}}}class J0{constructor(e,t){this.dv=new DataView(e),this.offset=0,this.littleEndian=t!==void 0?t:!0,this._textDecoder=new TextDecoder}getOffset(){return this.offset}size(){return this.dv.buffer.byteLength}skip(e){this.offset+=e}getBoolean(){return(this.getUint8()&1)===1}getBooleanArray(e){const t=[];for(let i=0;i=0&&(i=new Uint8Array(this.dv.buffer,t,s)),this._textDecoder.decode(i)}}class bT{add(e,t){this[e]=t}}function BO(n){const e="Kaydara FBX Binary \0";return n.byteLength>=e.length&&e===wT(n,0,e.length)}function zO(n){const e=["K","a","y","d","a","r","a","\\","F","B","X","\\","B","i","n","a","r","y","\\","\\"];let t=0;function i(s){const a=n[s-1];return n=n.slice(t+s),t++,a}for(let s=0;s(console.warn(`⚠️ Could not load texture ${u}:`,d.message),null))])}this._processModelMaterials(s,a,e,i.format);const o=this._calculateModelScale(s,e,i.scale);if(s.userData.scaleInfo=o,s.userData.format=i.format,i.wheelSockets){s.userData.wheelSockets=!0,s.userData.wheelModelName=i.wheelModel;const l=this._findWheelSockets(s);s.userData.wheelSocketObjects=l,console.log(`🔌 Found ${Object.keys(l).length} wheel sockets`)}return{model:s,chassisTexture:a,wheelModel:r}}_findWheelSockets(e){const t={},i=["Wheel_BL","Wheel_BR","Wheel_FL","Wheel_FR"];console.log("🔍 Searching for wheel sockets..."),e.traverse(s=>{const a=s.name,r=a.toLowerCase();for(const o of i)(a===o||r===o.toLowerCase())&&(t[o]=s,console.log(` Found socket: "${a}" at position (${s.position.x.toFixed(2)}, ${s.position.y.toFixed(2)}, ${s.position.z.toFixed(2)})`))});for(const s of i)t[s]||console.warn(` ⚠️ Missing wheel socket: ${s}`);return Object.keys(t).length===0&&(console.warn("⚠️ No wheel sockets found! Listing all objects:"),e.traverse(s=>{console.log(` - "${s.name}" (${s.type})`)})),t}_calculateModelScale(e,t,i=null){const s=new vn().setFromObject(e),a=new S;s.getSize(a),console.log(`📐 ${t.toUpperCase()} model dimensions (raw):`),console.log(` Size: X=${a.x.toFixed(2)}, Y=${a.y.toFixed(2)}, Z=${a.z.toFixed(2)}`),console.log(` Min Y: ${s.min.y.toFixed(2)}, Max Y: ${s.max.y.toFixed(2)}`);const r=this.HITBOX_DIMENSIONS[t]||this.HITBOX_DIMENSIONS.octane;let o;if(i!==null)o=i,console.log(` Using override scale: ${o}`);else{const l=a.z,u=r.length*1/l;o=u*.55,console.log(` Target RL: ${r.length} x ${r.width} x ${r.height} uu`),console.log(` Scale to RL: ${u.toFixed(4)}, Final scale: ${o.toFixed(6)}`)}return{scale:o}}_loadFBX(e){return new Promise((t,i)=>{this.fbxLoader.load(e,s=>t(s),void 0,s=>i(new Error(`Failed to load FBX: ${e} - ${s.message}`)))})}_loadGLB(e){return new Promise((t,i)=>{this.gltfLoader.load(e,s=>{t(s.scene)},void 0,s=>i(new Error(`Failed to load GLB: ${e} - ${s.message}`)))})}async loadWheelModel(e){const t=wi(`models/wheels/${e}`,this.assetBase);if(this.wheelModelCache.has(t))return this.wheelModelCache.get(t);if(this.wheelLoadingPromises.has(t))return this.wheelLoadingPromises.get(t);const i=this._loadGLB(t);this.wheelLoadingPromises.set(t,i);try{const s=await i;return console.log(`✓ Loaded wheel model: ${e}`),s.traverse(a=>{a.isMesh&&(a.castShadow=!0,a.receiveShadow=!0)}),this.wheelModelCache.set(t,s),s}catch(s){throw console.error(`Failed to load wheel model ${e}:`,s),s}finally{this.wheelLoadingPromises.delete(t)}}_loadTexture(e){return new Promise((t,i)=>{this.textureLoader.load(e,s=>{s.flipY=!1,s.colorSpace=gt,t(s)},void 0,s=>i(new Error(`Failed to load texture: ${e}`)))})}_processModelMaterials(e,t,i,s="fbx"){console.log(`📦 Processing materials for ${i} (${s}):`);const a=["body","paint"],r=[];e.traverse(o=>{o.isLight&&(r.push(o),console.log(` 🔦 Removing imported light: "${o.name||o.type}"`))}),r.forEach(o=>{o.parent&&o.parent.remove(o)}),e.traverse(o=>{o.isMesh&&(console.log(` Mesh: "${o.name}"`),(Array.isArray(o.material)?o.material:[o.material]).forEach((c,u)=>{console.log(` [${u}] Material: "${c.name}" - Color: #${c.color?.getHexString()||"none"}`);const d=(c.name||"").toLowerCase(),h=(o.name||"").toLowerCase(),f=a.some(p=>d.includes(p)||h.includes(p));if(s==="glb")(c.isMeshStandardMaterial||c.isMeshPhysicalMaterial)&&(console.log(` → GLB material (keeping as-is): metalness=${c.metalness?.toFixed(2)}, roughness=${c.roughness?.toFixed(2)}`),c.userData.originalColor=c.color?.clone(),c.userData.isBodyMaterial=f);else if(c.isMeshPhongMaterial||c.isMeshLambertMaterial||c.isMeshBasicMaterial){let p;f?(p=new Pn({color:c.color,map:c.map,metalness:.8,roughness:.15}),console.log(" → Body material: shiny metallic")):(p=new Pn({color:c.color,map:c.map,metalness:.1,roughness:.6}),console.log(" → Non-body material: matte")),p.name=c.name,Array.isArray(o.material)?o.material[u]=p:o.material=p}}))}),t?console.log(` ✓ Chassis texture loaded for ${i}`):s==="fbx"&&console.log(` ⚠️ No chassis texture for ${i}`)}getModelTypeForCar(e,t){return e&&this.carNameToModel[e]?this.carNameToModel[e]:this.hitboxToModel[t]||"octane"}getModelTypeForHitbox(e){return this.hitboxToModel[e]||"octane"}async createCarMesh(e,t=0){const i=this.getModelTypeForHitbox(e);try{const s=await this.loadModel(i);if(!s||!s.model)return console.warn(`No cached model for ${i}`),null;const a=s.model.userData.format||"fbx";let r;a==="glb"?(r=mp(s.model),r.traverse(c=>{c.isMesh&&(Array.isArray(c.material)?c.material=c.material.map(u=>u.clone()):c.material&&(c.material=c.material.clone()))})):r=s.model.clone(),this.applyTeamColor(r,t);const o=new Mt,l=s.model.userData.scaleInfo;return l&&r.scale.setScalar(l.scale),o.add(r),r.traverse(c=>{c.isMesh&&(c.castShadow=!0)}),o.userData.modelType=i,o.userData.hitboxType=e,o.userData.team=t,o.userData.isFBXModel=a==="fbx",o.userData.isGLBModel=a==="glb",o}catch(s){return console.error(`Failed to create car mesh for ${e}:`,s),null}}applyTeamColor(e,t){const i=t===0?this.TEAM_COLORS.blue:this.TEAM_COLORS.orange,s=["body","paint"];let a=!1;console.log("🔍 Analyzing car meshes for team coloring:"),e.traverse(r=>{if(r.isMesh){const o=Array.isArray(r.material)?r.material:[r.material];console.log(` Mesh: "${r.name}" with ${o.length} material(s)`),o.forEach((l,c)=>{console.log(` [${c}] Material: "${l.name}", isBodyMaterial: ${l.userData?.isBodyMaterial}`)})}}),e.traverse(r=>{r.isMesh&&(Array.isArray(r.material)?r.material:[r.material]).forEach((l,c)=>{const u=(l.name||"").toLowerCase(),d=(r.name||"").toLowerCase(),h=l.userData?.isBodyMaterial||s.some(f=>u.includes(f)||d.includes(f));if(console.log(` Checking "${l.name}" on "${r.name}": isBody=${h}`),h){a=!0;const f=l.clone();f.color=i.clone(),f.metalness=.39,f.roughness=.47,f.userData={...l.userData},Array.isArray(r.material)?r.material[c]=f:r.material=f,console.log(`🎨 Applied team color to: "${l.name}" on mesh "${r.name}" (index ${c})`)}})}),a||console.warn("⚠️ No body material found for team coloring! Check material names.")}updateTeamColor(e,t){this.applyTeamColor(e,t)}isModelReady(e,t){const i=this.getModelTypeForCar(e,t);return this.modelCache.has(this.modelCacheKey(i))}getCarMeshSync(e,t,i=0){const s=this.getModelTypeForCar(e,t),a=this.modelCache.get(this.modelCacheKey(s));if(!a||!a.model)return null;const r=a.model.userData.format||"fbx",o=a.model.userData.wheelSockets;let l;r==="glb"?(l=mp(a.model),l.traverse(d=>{d.isMesh&&(Array.isArray(d.material)?d.material=d.material.map(h=>h.clone()):d.material&&(d.material=d.material.clone()))})):l=a.model.clone(),this.applyTeamColor(l,i);const c=new Mt,u=a.model.userData.scaleInfo;return u&&l.scale.setScalar(u.scale),c.add(l),l.traverse(d=>{d.isMesh&&(d.castShadow=!0)}),c.userData.modelType=s,c.userData.carName=e,c.userData.hitboxType=t,c.userData.team=i,c.userData.isFBXModel=r==="fbx",c.userData.isGLBModel=r==="glb",c.userData.hasWheelSockets=o,o?c.userData.wheels=this._attachWheelsToSockets(l,a.wheelModel):c.userData.wheels=this._findWheelMeshes(l),c}_attachWheelsToSockets(e,t){const i=[],s={Wheel_FL:{side:"left",position:"front"},Wheel_FR:{side:"right",position:"front"},Wheel_BL:{side:"left",position:"rear"},Wheel_BR:{side:"right",position:"rear"}};if(!t)return console.warn("⚠️ No wheel model template available for socket attachment"),i;console.log("🔧 Attaching wheels to sockets...");const a={};e.traverse(r=>{const o=r.name;s[o]&&(a[o]=r)});for(const[r,o]of Object.entries(s)){const l=a[r];if(!l){console.warn(` ⚠️ Socket not found: ${r}`);continue}const c=mp(t);c.traverse(u=>{u.isMesh&&(Array.isArray(u.material)?u.material=u.material.map(d=>d.clone()):u.material&&(u.material=u.material.clone()),u.castShadow=!0)}),c.position.set(0,0,0),c.rotation.set(0,0,0),l.add(c),console.log(` ✓ Attached wheel to ${r} (${o.position} ${o.side})`),i.push({mesh:c,steeringPivot:o.position==="front"?l:null,side:o.side,position:o.position,socket:l})}return console.log(`✓ Attached ${i.length} wheels to sockets`),i}_findWheelMeshes(e){const t=[],i={fl:{side:"left",position:"front"},fr:{side:"right",position:"front"},rl:{side:"left",position:"rear"},rr:{side:"right",position:"rear"}};console.log("🔍 Searching for wheels in model...");const s={};e.traverse(a=>{const o=a.name.toLowerCase().match(/^wheel_(fl|fr|rl|rr)_(y|z)$/);if(o){const l=o[1],c=o[2];s[l]||(s[l]={}),s[l][c]=a,console.log(` Found: "${a.name}" (${c==="y"?"wheel mesh":"steering pivot"})`)}});for(const[a,r]of Object.entries(s)){const o=i[a];if(!o)continue;const l=r.y,c=r.z;l&&(a==="fr"&&(l.rotation.z+=Math.PI,console.log(" Fixed FR wheel orientation (rotation.z += PI)")),t.push({mesh:l,steeringPivot:o.position==="front"?c:null,side:o.side,position:o.position}),console.log(`🛞 Wheel ${a.toUpperCase()}: mesh="${l.name}"${c&&o.position==="front"?`, steering="${c.name}"`:""}`))}return t.length===0?(console.warn("⚠️ No wheel meshes found. Expected: Wheel_FL_Y, Wheel_FR_Y, etc."),console.warn(" Listing all objects in model:"),e.traverse(a=>{console.log(` - "${a.name}" (${a.type})`)})):console.log(`✓ Found ${t.length} wheels`),t}dispose(){}}const jO=2,_p=new Map;function ZO(n){const e=wi("models/ball/scene.gltf",n);let t=_p.get(e);if(!t){const i=new Ag;t=new Promise(s=>{i.load(e,a=>{console.log("✓ Ball model loaded"),s(a.scene)},void 0,a=>{console.error("Failed to load ball model:",a),_p.delete(e),s(null)})}),_p.set(e,t)}return t}class JO{constructor(e,t,i={}){this.scene=e,this.effectsManager=t,this.assetBase=i.assetBase,this.actors={},this.ballActorId=null,this.ballIndicator=null,this.ballVerticalLine=null,this.playerNames=new Set,this.actorToPlayer={},this.actorLinks={},this.playerNameToCarActorId={},this.playerNameToPriActorId={},this.playerTeams={},this.actorLoadouts={},this.carBodyIds={},this.carModelLoader=new YO({assetBase:this.assetBase}),this.pendingCarReplacements=new Map,this._lastGoalScanTime=null,this._firedGoalTimes=new Set,this._p0=new S,this._p1=new S,this._v0=new S,this._v1=new S,this._nextRot=new dt,this._q0=new dt,this._q1=new dt,this._qResult=new dt,this.onPlayerFound=null,this.lastBallTouchTeam=0,this.BALL_TOUCH_DISTANCE=200,this.ballTimeline=[],this.playerTimelineMap={},this.timelineIndices={ball:0,players:{}},this.interpolantsInitialized=!1,this.animationMixer=null,this.animationActions={},this.animationClock=new vg(!1),this.replayDuration=0,this.useAnimationSystem=!1,this.SMOOTHING_WINDOW=5,this.positionBuffers={},this.rotationBuffers={},this.interpolationEnabled=!0,this.interpolationMethod="lerp",this.smoothingWindowSize=12,this.lastFrameInfo=null,this._lowPassState=new Map,this._lowPassAlpha=.3,this._predictState=new Map,this._predictCorrectionTime=.1,this._smoothingBuffers=new Map,this._adaptiveState=new Map,this.ballModel=null,this._ballModelReplaced=!1,this.ballModelReady=ZO(this.assetBase).then(s=>(this.ballModel=s,s!==null))}async waitForBallModel(){const e=await this.ballModelReady;return e&&!this._ballModelReplaced&&this.ballActorId&&this.actors[this.ballActorId]&&(this.replaceBallWithModel(this.ballActorId),this._ballModelReplaced=!0),e}replaceBallWithModel(e){const t=this.actors[e];if(!t||!this.ballModel)return;const i=this.ballModel.clone();i.userData=t.userData,i.position.copy(t.position),i.quaternion.copy(t.quaternion),i.scale.copy(t.scale);const s=92.75;i.scale.set(s,s,s),i.traverse(a=>{a.isMesh&&(a.castShadow=!0,a.receiveShadow=!0)}),this.scene.remove(t),this.scene.add(i),t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose(),this.actors[e]=i,console.log("✓ Ball replaced with GLTF model")}reset(){Object.values(this.actors).forEach(e=>{this.scene.remove(e),e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()}),this.actors={},this.ballActorId=null,this.ballIndicator&&(this.scene.remove(this.ballIndicator),this.ballIndicator.geometry&&this.ballIndicator.geometry.dispose(),this.ballIndicator.material&&this.ballIndicator.material.dispose(),this.ballIndicator=null),this.ballVerticalLine&&(this.scene.remove(this.ballVerticalLine),this.ballVerticalLine.geometry&&this.ballVerticalLine.geometry.dispose(),this.ballVerticalLine.material&&this.ballVerticalLine.material.dispose(),this.ballVerticalLine=null),this.actorToPlayer={},this.actorLinks={},this.playerNames.clear(),this.playerNameToCarActorId={},this.playerNameToPriActorId={},this.playerTeams={},this.actorLoadouts={},this.carBodyIds={},this.pendingCarReplacements.clear(),this._lastGoalScanTime=null,this._firedGoalTimes.clear(),this.ballTimeline=[],this.playerTimelineMap={},this.ballTimelineCorrected=[],this.playerTimelineMapCorrected={},this.ballTimelineFiltered=[],this.playerTimelineMapFiltered={},this.timelineIndices={ball:0,players:{}},this.timelineIndicesFiltered={ball:0,players:{}},this.timelineIndicesCorrected={ball:0,players:{}},this.interpolantsInitialized=!1,this.animationMixer?.stopAllAction?.(),this.animationMixer=null,this.animationActions={},this.replayDuration=0,this.positionBuffers={},this.rotationBuffers={},this._lowPassState.clear(),this._predictState.clear(),this._smoothingBuffers.clear(),this._adaptiveState.clear(),this._ballModelReplaced=!1}resetGoalExplosionPlaybackState(){this._lastGoalScanTime=null,this._firedGoalTimes.clear()}setPlayerTeams(e){this.playerTeams=e}initFromFramework(e){console.log("[ActorManager] Initializing actors from framework..."),this._createBallMesh();const t=e.playerList;t.forEach((i,s)=>{this._createCarMesh(i.name,i.team,s,i.carName,i.hitboxType);const a=this.playerNameToCarActorId[i.name];this.actors[a]}),console.log(`[ActorManager] Created ${t.length} car meshes + 1 ball`)}initInterpolants(e){console.log("[ActorManager] Initializing interpolation system..."),this.ballTimeline=e.ballTimeline||[],this.playerTimelineMap=e.playerTimelines||{},this.ballTimelineCorrected=this._correctTimeShiftedPositions(this.ballTimeline),this.playerTimelineMapCorrected={},Object.entries(this.playerTimelineMap).forEach(([s,a])=>{this.playerTimelineMapCorrected[s]=this._correctTimeShiftedPositions(a)}),this.ballTimelineFiltered=this._filterBadFrames(this.ballTimeline),this.playerTimelineMapFiltered={},Object.entries(this.playerTimelineMap).forEach(([s,a])=>{this.playerTimelineMapFiltered[s]=this._filterBadFrames(a)}),this.timelineIndices={ball:0,players:{}},this.timelineIndicesFiltered={ball:0,players:{}},this.timelineIndicesCorrected={ball:0,players:{}},Object.keys(this.playerTimelineMap).forEach(s=>{this.timelineIndices.players[s]=0,this.timelineIndicesFiltered.players[s]=0,this.timelineIndicesCorrected.players[s]=0}),this.ballTimeline.length>0&&(this.replayDuration=this.ballTimeline[this.ballTimeline.length-1].time),this.useAnimationSystem&&this._initAnimationSystem(),this.interpolantsInitialized=!0;const t=this.ballTimeline.length-this.ballTimelineFiltered.length,i=this.ballTimelineCorrected._correctedCount||0;console.log(` Ball: ${this.ballTimeline.length} keyframes (${i} corrected, ${t} filtered)`),Object.entries(this.playerTimelineMap).forEach(([s,a])=>{const r=this.playerTimelineMapCorrected[s]?._correctedCount||0;console.log(` ${s}: ${a.length} keyframes (${r} corrected)`)}),console.log(` Replay duration: ${this.replayDuration.toFixed(2)}s`),console.log("[ActorManager] Animation system ready")}_initAnimationSystem(){console.log("[ActorManager] Building Three.js animation clips..."),this.animationMixer=new QS(this.scene);const e=this.actors[this.ballActorId];if(e&&this.ballTimeline.length>0){const t=this._createAnimationClip("ball",this.ballTimeline,e);if(t){const i=this.animationMixer.clipAction(t,e);i.setLoop(Xd),i.clampWhenFinished=!0,this.animationActions.ball=i,console.log(` ✓ Ball animation: ${t.duration.toFixed(2)}s`)}}Object.entries(this.playerTimelineMap).forEach(([t,i])=>{const s=this.playerNameToCarActorId[t],a=this.actors[s];if(a&&i.length>0){const r=this._createAnimationClip(t,i,a);if(r){const o=this.animationMixer.clipAction(r,a);o.setLoop(Xd),o.clampWhenFinished=!0,this.animationActions[t]=o,console.log(` ✓ ${t} animation: ${r.duration.toFixed(2)}s`)}}}),console.log("[ActorManager] Animation clips ready")}_createAnimationClip(e,t,i){if(!t||t.length<2)return null;const s=[],a=[],r=[],o=t[0];o.time>0&&(s.push(0),o.position?a.push(o.position.x,o.position.y,o.position.z):a.push(0,0,0),o.rotation?r.push(o.rotation.x,o.rotation.y,o.rotation.z,o.rotation.w):r.push(0,0,0,1));for(const h of t){if(s.push(h.time),h.position)a.push(h.position.x,h.position.y,h.position.z);else{const f=a.length-3;f>=0?a.push(a[f],a[f+1],a[f+2]):a.push(0,0,0)}if(h.rotation)r.push(h.rotation.x,h.rotation.y,h.rotation.z,h.rotation.w);else{const f=r.length-4;f>=0?r.push(r[f],r[f+1],r[f+2],r[f+3]):r.push(0,0,0,1)}}const l=new Hs(".position",s,a,rr),c=new _s(".quaternion",s,r),u=s[s.length-1]-s[0];return new ua(e,u,[l,c])}startAnimations(){this.animationMixer&&(Object.values(this.animationActions).forEach(e=>{e.reset(),e.play()}),this.animationClock.start(),console.log("[ActorManager] Animations started"))}pauseAnimations(){this.animationMixer&&Object.values(this.animationActions).forEach(e=>{e.paused=!0})}resumeAnimations(){this.animationMixer&&Object.values(this.animationActions).forEach(e=>{e.paused=!1})}seekAnimations(e){this.animationMixer&&(Object.values(this.animationActions).forEach(t=>{t.time=e}),this.animationMixer.setTime(e))}updateAnimations(e){!this.animationMixer||!this.useAnimationSystem||this.animationMixer.update(e)}_subsampleTimeline(e){return!e||e.length<4?e:e.filter((t,i)=>i%2===0)}_getOrCreateSmoothingBuffer(e){return this.positionBuffers[e]||(this.positionBuffers[e]=[],this.rotationBuffers[e]=[]),{positions:this.positionBuffers[e],rotations:this.rotationBuffers[e]}}_smoothPosition(e,t){const i=this._getOrCreateSmoothingBuffer(e).positions;for(i.push({x:t.x,y:t.y,z:t.z});i.length>this.SMOOTHING_WINDOW;)i.shift();if(i.length===1)return t;let s=0,a=0,r=0;for(const o of i)s+=o.x,a+=o.y,r+=o.z;return{x:s/i.length,y:a/i.length,z:r/i.length}}_smoothRotation(e,t){const i=this._getOrCreateSmoothingBuffer(e).rotations;for(i.push({x:t.x,y:t.y,z:t.z,w:t.w});i.length>this.SMOOTHING_WINDOW;)i.shift();if(i.length<3)return t;const s=Math.floor(i.length/2);return i[s]}resetSmoothingBuffers(){this.positionBuffers={},this.rotationBuffers={},this._lowPassState.clear()}_findKeyframeIndex(e,t,i=0){if(!e||e.length===0)return-1;if(t<=e[0].time)return 0;if(t>=e[e.length-1].time)return e.length-2;let s=Math.max(0,Math.min(i,e.length-2));if(e[s].time<=t&&e[s+1].time>t)return s;if(s+2t)return s+1;let a=0,r=e.length-2;for(;a<=r;){const o=Math.floor((a+r)/2);if(e[o].time<=t&&e[o+1].time>t)return o;e[o].time>t?r=o-1:a=o+1}return Math.max(0,Math.min(a,e.length-2))}_applySmoothing(e,t){this._smoothingBuffers.has(e)||this._smoothingBuffers.set(e,[]);const i=this._smoothingBuffers.get(e);for(i.push({x:t.x,y:t.y,z:t.z});i.length>this.smoothingWindowSize;)i.shift();if(i.length===1)return t;let s=0,a=0,r=0;for(const o of i)s+=o.x,a+=o.y,r+=o.z;return{x:s/i.length,y:a/i.length,z:r/i.length}}_applyEmaSmoothing(e,t){const i=`ema-${e}`;if(!this._smoothingBuffers.has(i))return this._smoothingBuffers.set(i,{x:t.x,y:t.y,z:t.z}),t;const s=this._smoothingBuffers.get(i),a=Math.max(.05,Math.min(.5,1/this.smoothingWindowSize)),r={x:a*t.x+(1-a)*s.x,y:a*t.y+(1-a)*s.y,z:a*t.z+(1-a)*s.z};return this._smoothingBuffers.set(i,r),r}_applyDoubleEmaSmoothing(e,t){const i=`dema-${e}`;if(!this._smoothingBuffers.has(i))return this._smoothingBuffers.set(i,{level:{x:t.x,y:t.y,z:t.z},trend:{x:0,y:0,z:0}}),t;const s=this._smoothingBuffers.get(i),a=Math.max(.1,Math.min(.6,2/this.smoothingWindowSize)),r=a*.5,o={x:a*t.x+(1-a)*(s.level.x+s.trend.x),y:a*t.y+(1-a)*(s.level.y+s.trend.y),z:a*t.z+(1-a)*(s.level.z+s.trend.z)},l={x:r*(o.x-s.level.x)+(1-r)*s.trend.x,y:r*(o.y-s.level.y)+(1-r)*s.trend.y,z:r*(o.z-s.level.z)+(1-r)*s.trend.z};return s.level=o,s.trend=l,{x:o.x+l.x,y:o.y+l.y,z:o.z+l.z}}_applyWeightedSmoothing(e,t){const i=`wma-${e}`;this._smoothingBuffers.has(i)||this._smoothingBuffers.set(i,[]);const s=this._smoothingBuffers.get(i);for(s.push({x:t.x,y:t.y,z:t.z});s.length>this.smoothingWindowSize;)s.shift();if(s.length===1)return t;let a=0,r=0,o=0,l=0;for(let c=0;cthis.smoothingWindowSize;)s.shift();if(s.length===1)return t;const a=s.length/3;let r=0,o=0,l=0,c=0;for(let u=0;u.001&&(s.derivedVel={x:(t.x-s.lastPos.x)/a,y:(t.y-s.lastPos.y)/a,z:(t.z-s.lastPos.z)/a});const r=Math.sqrt(s.derivedVel.x**2+s.derivedVel.y**2+s.derivedVel.z**2),o=2,l=this.smoothingWindowSize,c=300,u=1500;let d;if(ru)d=o;else{const _=(r-c)/(u-c);d=Math.round(l-_*(l-o))}if(s.buffer.length>=2){const _=s.buffer[s.buffer.length-1],m=s.buffer[s.buffer.length-2],v={x:_.x-m.x,y:_.y-m.y,z:_.z-m.z},y={x:t.x-_.x,y:t.y-_.y,z:t.z-_.z},b=Math.sqrt(v.x**2+v.y**2+v.z**2),T=Math.sqrt(y.x**2+y.y**2+y.z**2);if(b>.1&&T>.1&&(v.x*y.x+v.y*y.y+v.z*y.z)/(b*T)<.5)for(;s.buffer.length>Math.max(2,d/2);)s.buffer.shift()}for(s.buffer.push({x:t.x,y:t.y,z:t.z});s.buffer.length>d;)s.buffer.shift();if(s.lastPos={x:t.x,y:t.y,z:t.z},s.lastTime=i,s.buffer.length===1)return t;let h=0,f=0,p=0,g=0;for(let _=0;_u+10&&(h.z=t.position.z+t.velocity.z*r-.5*c*r*r,h.zu+10&&(p.z=t.position.z+t.velocity.z*o-.5*c*o*o,p.z0&&o>0){const b=d*o;m>b*2&&(v=b*2/m)}const y=_*v+(1-v)*l;return{x:h.x+g.x*y,y:h.y+g.y*y,z:h.z+g.z*y}}_physicsTickInterpolate(e,t,i){const s=t.time-e.time,a=i-e.time,r=a/s;if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};const o=(e.velocity.x+t.velocity.x)/2,l=(e.velocity.y+t.velocity.y)/2,c=(e.velocity.z+t.velocity.z)/2,u=e.position.x+o*a,d=e.position.y+l*a,h=e.position.z+c*a,f=e.position.x+o*s,p=e.position.y+l*s,g=e.position.z+c*s,_=t.position.x-f,m=t.position.y-p,v=t.position.z-g;return{x:u+_*r,y:d+m*r,z:h+v*r}}_velocityOnlyInterpolate(e,t,i){const s=i-e.time,a=t.time-e.time,r=s/a;if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};const o=e.velocity.x+(t.velocity.x-e.velocity.x)*r/2,l=e.velocity.y+(t.velocity.y-e.velocity.y)*r/2,c=e.velocity.z+(t.velocity.z-e.velocity.z)*r/2;return{x:e.position.x+o*s,y:e.position.y+l*s,z:e.position.z+c*s}}_smartHybridInterpolate(e,t,i){const s=i-e.time,a=t.time-e.time,r=Math.max(0,Math.min(1,s/a));if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};const o=Math.sqrt(e.velocity.x**2+e.velocity.y**2+e.velocity.z**2),l=Math.sqrt(t.velocity.x**2+t.velocity.y**2+t.velocity.z**2);let c=1;o>10&&l>10&&(c=(e.velocity.x*t.velocity.x+e.velocity.y*t.velocity.y+e.velocity.z*t.velocity.z)/(o*l));const u=o>10?Math.abs(l-o)/o:0;if(c<.95||u>.1){const h=r*r*(3-2*r);return{x:e.position.x+(t.position.x-e.position.x)*h,y:e.position.y+(t.position.y-e.position.y)*h,z:e.position.z+(t.position.z-e.position.z)*h}}else{const h=(e.velocity.x+t.velocity.x)/2,f=(e.velocity.y+t.velocity.y)/2,p=(e.velocity.z+t.velocity.z)/2,g=e.position.x+h*s,_=e.position.y+f*s,m=e.position.z+p*s,v=e.position.x+h*a,y=e.position.y+f*a,b=e.position.z+p*a,T=t.position.x-v,x=t.position.y-y,M=t.position.z-b;return{x:g+T*r,y:_+x*r,z:m+M*r}}}_isBadFrame(e,t){if(!e.velocity||!t.velocity||!e.position||!t.position)return!1;const i=t.time-e.time;if(i<.001)return!1;const s=(e.velocity.x+t.velocity.x)/2,a=(e.velocity.y+t.velocity.y)/2,r=(e.velocity.z+t.velocity.z)/2,o=Math.sqrt(s**2+a**2+r**2);if(o<200)return!1;const l=t.position.x-e.position.x,c=t.position.y-e.position.y,u=t.position.z-e.position.z,d=Math.sqrt(l*l+c*c+u*u),h=o*i,f=d/h;return f<.6||f>1.4}_filterBadFrames(e){if(!e||e.length<2)return e;const t=[e[0]];for(let i=1;i0&&a.position&&a.velocity){const o=e[s-1];if(o.position&&o.velocity){const l=a.time-o.time;if(l>.001){const c=(o.velocity.x+a.velocity.x)/2,u=(o.velocity.y+a.velocity.y)/2,d=(o.velocity.z+a.velocity.z)/2,h=Math.sqrt(c**2+u**2+d**2);if(h>100){const f=a.position.x-o.position.x,p=a.position.y-o.position.y,g=a.position.z-o.position.z,_=Math.sqrt(f*f+p*p+g*g),m=h*l,v=_/m;let y=0;v>.15&&v<.35?y=l*.75:v>.4&&v<.6?y=l*.5:v>.65&&v<.85&&(y=l*.25),y>0&&(r.position.x+=a.velocity.x*y,r.position.y+=a.velocity.y*y,r.position.z+=a.velocity.z*y,i++)}}}}t.push(r)}return t._correctedCount=i,t}_timeShiftedInterpolate(e,t,i){const s=i-e.time,a=t.time-e.time,r=Math.max(0,Math.min(1,s/a));return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r}}_velocityAnchoredInterpolate(e,t,i,s,a,r){if(!t.velocity||!i.velocity){const m=(s-t.time)/(i.time-t.time);return{x:t.position.x+(i.position.x-t.position.x)*m,y:t.position.y+(i.position.y-t.position.y)*m,z:t.position.z+(i.position.z-t.position.z)*m}}this._velocityAnchorState||(this._velocityAnchorState=new Map);let o=this._velocityAnchorState.get(e);(!o||Math.abs(s-o.lastTime)>.5||r%10===0)&&(o={anchorPos:{...t.position},anchorTime:t.time,anchorIdx:r,lastTime:s},this._velocityAnchorState.set(e,o)),s-o.anchorTime;let u=o.anchorPos.x,d=o.anchorPos.y,h=o.anchorPos.z;const f=(t.velocity.x+i.velocity.x)/2,p=(t.velocity.y+i.velocity.y)/2,g=(t.velocity.z+i.velocity.z)/2,_=s-t.time;return o.anchorIdx===r?(u=o.anchorPos.x+f*_,d=o.anchorPos.y+p*_,h=o.anchorPos.z+g*_):(u=t.position.x+f*_,d=t.position.y+p*_,h=t.position.z+g*_),o.lastTime=s,{x:u,y:d,z:h}}_hermiteInterpolate(e,t,i){const s=t.time-e.time,a=i-e.time,r=Math.max(0,Math.min(1,a/s)),o={x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};if(!e.velocity||!t.velocity)return o;const l=r*r,c=l*r,u=2*c-3*l+1,d=c-2*l+r,h=-2*c+3*l,f=c-l,p={x:e.velocity.x*s,y:e.velocity.y*s,z:e.velocity.z*s},g={x:t.velocity.x*s,y:t.velocity.y*s,z:t.velocity.z*s},_={x:u*e.position.x+d*p.x+h*t.position.x+f*g.x,y:u*e.position.y+d*p.y+h*t.position.y+f*g.y,z:u*e.position.z+d*p.z+h*t.position.z+f*g.z},m=_.x-o.x,v=_.y-o.y,y=_.z-o.z,b=t.position.x-e.position.x,T=t.position.y-e.position.y,x=t.position.z-e.position.z;return m*m+v*v+y*y>b*b+T*T+x*x?o:_}_physicsSimInterpolate(e,t,i,s=!1){const a=t.time-e.time,r=i-e.time,o=Math.max(0,Math.min(1,r/a));if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*o,y:e.position.y+(t.position.y-e.position.y)*o,z:e.position.z+(t.position.z-e.position.z)*o};const l=-650,c=o*o,u=c*o,d=2*u-3*c+1,h=u-2*c+o,f=-2*u+3*c,p=u-c;let g=e.velocity.y*a,_=t.velocity.y*a;if(s){const m=.5*l*a*a;g+=m*.5,_+=m*.5}return{x:d*e.position.x+h*(e.velocity.x*a)+f*t.position.x+p*(t.velocity.x*a),y:d*e.position.y+h*g+f*t.position.y+p*_,z:d*e.position.z+h*(e.velocity.z*a)+f*t.position.z+p*(t.velocity.z*a)}}getBallPositionAt(e){if(!this.ballTimeline||this.ballTimeline.length<2)return null;const t=this.ballTimeline[0];if(e2e3)return s.sleeping?null:{...s.position};if(s.sleeping)return{...s.position};const d=(e-s.time)/r;let h;switch(this.interpolationMethod){case"catmull-rom":{const f=this.ballTimeline[Math.max(0,i-1)],p=this.ballTimeline[Math.min(this.ballTimeline.length-1,i+2)];f?.position&&p?.position?h=this._catmullRomInterpolate(f.position,s.position,a.position,p.position,d):h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}case"lerp-smooth":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applySmoothing("ball",h);break}case"lerp-ema":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyEmaSmoothing("ball",h);break}case"lerp-dema":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyDoubleEmaSmoothing("ball",h);break}case"lerp-wma":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyWeightedSmoothing("ball",h);break}case"lerp-gauss":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyGaussianSmoothing("ball",h);break}case"one-euro":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyOneEuroFilter("ball",h);break}case"predict-correct":{h=this._predictCorrectInterpolate("ball",s,a,e);break}case"velocity-smooth":{h=this._velocitySmoothInterpolate("ball",s,a,e,!0);break}case"physics-tick":{h=this._physicsTickInterpolate(s,a,e);break}case"hermite":{h=this._hermiteInterpolate(s,a,e);break}case"physics-sim":{const f=this.ballTimelineCorrected;if(f&&f.length>=2){const p=this._findKeyframeIndex(f,e,this.timelineIndicesCorrected.ball);this.timelineIndicesCorrected.ball=p;const g=f[p],_=f[p+1];if(g?.position&&_?.position){h=this._physicsSimInterpolate(g,_,e,!0);break}}h=this._physicsSimInterpolate(s,a,e,!0);break}case"velocity-only":{h=this._velocityOnlyInterpolate(s,a,e);break}case"smart-hybrid":{h=this._smartHybridInterpolate(s,a,e);break}case"time-shifted":{const f=this.ballTimelineFiltered;if(!f||f.length<2){h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}const p=this._findKeyframeIndex(f,e,this.timelineIndicesFiltered.ball);this.timelineIndicesFiltered.ball=p;const g=f[p],_=f[p+1];if(!g?.position||!_?.position){h=g?.position?{...g.position}:{...s.position};break}const m=_.time-g.time,v=m>0?Math.max(0,Math.min(1,(e-g.time)/m)):0;h={x:g.position.x+(_.position.x-g.position.x)*v,y:g.position.y+(_.position.y-g.position.y)*v,z:g.position.z+(_.position.z-g.position.z)*v};break}case"position-lerp":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}case"position-catmull":{const f=this.ballTimeline[Math.max(0,i-1)],p=this.ballTimeline[Math.min(this.ballTimeline.length-1,i+2)];f?.position&&p?.position?h=this._catmullRomInterpolate(f.position,s.position,a.position,p.position,d):h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}case"position-smooth":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyLowPassFilter("ball",h);break}case"adaptive-smooth":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyAdaptiveSmoothing("ball",h,e);break}default:{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}}return h}getBallRotationAt(e){if(!this.ballTimeline||this.ballTimeline.length<2)return null;const t=this.ballTimeline[0];if(e2e3)return{...s.rotation}}if(s.sleeping)return{...s.rotation};const o=(e-s.time)/r;return this._q0.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w),this._q1.set(a.rotation.x,a.rotation.y,a.rotation.z,a.rotation.w),this._qResult.slerpQuaternions(this._q0,this._q1,o),{x:this._qResult.x,y:this._qResult.y,z:this._qResult.z,w:this._qResult.w}}getPlayerPositionAt(e,t){const i=this.playerTimelineMap[e];if(!i||i.length<2)return null;const s=i[0];if(t=2){const h=this._findKeyframeIndex(d,t,this.timelineIndicesCorrected.players[e]||0);this.timelineIndicesCorrected.players[e]=h;const f=d[h],p=d[h+1];if(f?.position&&p?.position){u=this._physicsSimInterpolate(f,p,t,!1);break}}u=this._physicsSimInterpolate(r,o,t,!1);break}case"velocity-only":{u=this._velocityOnlyInterpolate(r,o,t);break}case"smart-hybrid":{u=this._smartHybridInterpolate(r,o,t);break}case"time-shifted":{const d=this.playerTimelineMapFiltered[e];if(!d||d.length<2){u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}const h=this._findKeyframeIndex(d,t,this.timelineIndicesFiltered.players[e]||0);this.timelineIndicesFiltered.players[e]=h;const f=d[h],p=d[h+1];if(!f?.position||!p?.position){u=f?.position?{...f.position}:{...r.position};break}const g=p.time-f.time,_=g>0?Math.max(0,Math.min(1,(t-f.time)/g)):0;u={x:f.position.x+(p.position.x-f.position.x)*_,y:f.position.y+(p.position.y-f.position.y)*_,z:f.position.z+(p.position.z-f.position.z)*_};break}case"position-lerp":{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}case"position-catmull":{const d=i[Math.max(0,a-1)],h=i[Math.min(i.length-1,a+2)];d?.position&&h?.position?u=this._catmullRomInterpolate(d.position,r.position,o.position,h.position,c):u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}case"position-smooth":{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c},u=this._applyLowPassFilter(`player-${e}`,u);break}case"adaptive-smooth":{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c},u=this._applyAdaptiveSmoothing(`player-${e}`,u,t);break}default:{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}}return u}getPlayerRotationAt(e,t){const i=this.playerTimelineMap[e];if(!i||i.length<2)return null;const s=i[0];if(t=2){const r=this.getBallPositionAt(t),o=this.getBallRotationAt(t);r?i.position.set(r.x,r.y,r.z):a=!1,o&&i.quaternion.set(o.x,o.y,o.z,o.w)}else i.position.set(s.position.x,s.position.y,s.position.z),i.quaternion.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w);if(i.userData.location.copy(i.position),i.userData.rotation.copy(i.quaternion),i.userData.velocity.set(s.velocity.x,s.velocity.y,s.velocity.z),s.angularVelocity&&i.userData.angularVelocity.set(s.angularVelocity.x,s.angularVelocity.y,s.angularVelocity.z),i.userData.sleeping=s.sleeping,i.visible=a&&s.visible!==!1&&!i.userData.isHiddenByGoal,this.ballIndicator&&(this.ballIndicator.position.set(i.position.x,2,i.position.z),this.ballIndicator.visible=i.visible),this.ballVerticalLine){const o=new Float32Array([i.position.x,2,i.position.z,i.position.x,i.position.y,i.position.z]);this.ballVerticalLine.geometry.setAttribute("position",new rt(o,3)),this.ballVerticalLine.geometry.attributes.position.needsUpdate=!0,this.ballVerticalLine.visible=i.visible}if(i.userData.velocity&&i.visible){let r=this.lastBallTouchTeam,o=this.BALL_TOUCH_DISTANCE;Object.keys(this.actors).forEach(l=>{const c=this.actors[l];if(c&&c.userData.isCar&&c.userData.playerId){const u=i.position.distanceTo(c.position);u{const a=this.playerNameToCarActorId[s.name];if(!a)return;const r=this.actors[a];if(!r)return;const o=s.name;if(!this.useAnimationSystem||!this.animationMixer)if(this.interpolantsInitialized&&this.playerTimelineMap[o]){const c=this.getPlayerPositionAt(o,t),u=this.getPlayerRotationAt(o,t);c&&r.position.set(c.x,c.y,c.z),u&&r.quaternion.set(u.x,u.y,u.z,u.w)}else r.position.set(s.position.x,s.position.y,s.position.z),r.quaternion.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w);r.userData.location.copy(r.position),r.userData.rotation.copy(r.quaternion),r.userData.velocity.set(s.velocity.x,s.velocity.y,s.velocity.z),r.userData.sleeping=s.sleeping,r.userData.steer=s.steer||0;const l=r.position.length()>.1;r.visible=s.isVisible&&l&&!r.userData.sleeping}),this._updateGoalExplosions(t)}_updateGoalExplosions(e){const t=this.effectsManager,i=t&&t.explosions?t.explosions.goalEvents:null;if(!(i instanceof Map)||i.size===0)return;const s=this._lastGoalScanTime;s!==null&&e=c&&e<=c+jO&&(r=!0,o=!0),s!==null&&s=c&&!this._firedGoalTimes.has(c)){this._firedGoalTimes.add(c);const d=this.getBallPositionAt(c)||a&&a.position||null;d&&this.effectsManager.triggerGoalExplosion(d,l.team)}}a&&(a.userData.isHiddenByGoal=r,r&&(a.visible=!1)),o||this.effectsManager.clearGoalExplosions?.(),this._lastGoalScanTime=e}processFrame(e,t,i,s){if(e){if(e.new_actors&&e.new_actors.forEach(a=>{if(!this.actors[a.actor_id]){const r=t(a.object_id),o=r&&r.includes("Ball"),l=r&&r.includes("Car");if(o||l){let c;o?c=new yn(92.75,16,16):c=new Ei(118,36,84);const u=new Pn({color:o?16777215:Math.random()*16777215}),d=new we(c,u);if(d.userData={location:new S,rotation:new dt,isCar:l,isBall:o,playerId:null,lastUpdateTime:e.time,bodyId:null,hasReceivedUpdate:!1},this.scene.add(d),this.actors[a.actor_id]=d,o){this.ballActorId=a.actor_id,this.ballModel&&this.replaceBallWithModel(a.actor_id);const h=92.75,f=new ni(h*.95,h,32),p=new Ye({color:16777215,side:ct});this.ballIndicator=new we(f,p),this.ballIndicator.rotation.x=-Math.PI/2,this.ballIndicator.visible=!1,this.scene.add(this.ballIndicator);const g=new Ge().setFromPoints([new S(0,0,0),new S(0,1,0)]),_=new Rt({color:16777215,opacity:.5,transparent:!0});this.ballVerticalLine=new In(g,_),this.ballVerticalLine.frustumCulled=!1,this.ballVerticalLine.visible=!1,this.scene.add(this.ballVerticalLine)}else l&&this.effectsManager.createBoostTrail(d,a.actor_id)}}}),e.deleted_actors&&e.deleted_actors.forEach(a=>{if(this.actors[a]){const r=this.actors[a];r.userData.isCar&&this.effectsManager.removeBoostTrail(a),this.scene.remove(r),r.geometry&&r.geometry.dispose(),r.material&&r.material.dispose(),delete this.actors[a],this.ballActorId===a&&(this.ballActorId=null,this.ballIndicator&&(this.scene.remove(this.ballIndicator),this.ballIndicator.geometry&&this.ballIndicator.geometry.dispose(),this.ballIndicator.material&&this.ballIndicator.material.dispose(),this.ballIndicator=null),this.ballVerticalLine&&(this.scene.remove(this.ballVerticalLine),this.ballVerticalLine.geometry&&this.ballVerticalLine.geometry.dispose(),this.ballVerticalLine.material&&this.ballVerticalLine.material.dispose(),this.ballVerticalLine=null))}}),e.updated_actors&&e.updated_actors.forEach(a=>{const r=this.actors[a.actor_id];a.attribute.TeamLoadout&&(this.actorLoadouts[a.actor_id]=a.attribute.TeamLoadout,r&&r.userData.isCar&&(r.userData.teamLoadout=a.attribute.TeamLoadout,this.resolveBodyId(r,a.actor_id)));const o=t(a.object_id),l=o&&(o.includes("PRI_TA")||o.includes("PlayerReplicationInfo"));if(a.attribute.String&&this.playerNames.has(a.attribute.String)){const c=a.attribute.String;this.actorToPlayer[a.actor_id]=c,l&&!this.playerNameToPriActorId[c]&&(this.playerNameToPriActorId[c]=a.actor_id,console.log(`[ActorManager] Mapped ${c} -> PRI Actor ${a.actor_id} (object: ${o})`)),this.checkCarPlayerLink(a.actor_id)}if(a.attribute.Reservation&&this.playerNames.has(a.attribute.Reservation.name)){const c=a.attribute.Reservation.name;this.actorToPlayer[a.actor_id]=c,l&&!this.playerNameToPriActorId[c]&&(this.playerNameToPriActorId[c]=a.actor_id,console.log(`[ActorManager] Mapped ${c} -> PRI Actor ${a.actor_id} (object: ${o})`)),this.checkCarPlayerLink(a.actor_id)}if(a.attribute.ActiveActor){const c=a.attribute.ActiveActor.actor;this.actorLinks[a.actor_id]||(this.actorLinks[a.actor_id]=new Set),this.actorLinks[a.actor_id].add(c),r&&r.userData.isCar&&this.checkCarPlayerLink(c,a.actor_id)}if(r&&a.attribute&&a.attribute.RigidBody){const c=a.attribute.RigidBody;if(c.location&&(r.userData.location.set(c.location.x,c.location.z,c.location.y),r.userData.lastUpdateTime=e.time,r.userData.hasReceivedUpdate=!0),c.linear_velocity&&(r.userData.velocity||(r.userData.velocity=new S),r.userData.velocity.set(c.linear_velocity.x,c.linear_velocity.z,c.linear_velocity.y)),c.rotation&&r.userData.rotation.set(c.rotation.x,c.rotation.z,c.rotation.y,-c.rotation.w),c.angular_velocity&&(r.userData.angularVelocity||(r.userData.angularVelocity=new S),r.userData.angularVelocity.set(c.angular_velocity.x,c.angular_velocity.z,c.angular_velocity.y)),c.sleeping!==void 0&&(r.userData.sleeping=c.sleeping,c.sleeping&&(r.userData.velocity&&r.userData.velocity.set(0,0,0),r.userData.angularVelocity&&r.userData.angularVelocity.set(0,0,0))),r.userData.isBall&&r.userData.isHiddenByGoal&&c.location){const u=c.location.x,d=c.location.y,h=c.location.z;Math.sqrt(u*u+d*d+h*h)<500&&(r.userData.isHiddenByGoal=!1)}}}),this.effectsManager.explosions.goalEvents.has(i)){const a=this.effectsManager.explosions.goalEvents.get(i),r=this.actors[this.ballActorId];r&&(s||(this.effectsManager.triggerGoalExplosion(r.position,a.team),console.log(`🎯 GOAL! Explosion at frame ${i} for team ${a.team} by ${a.playerName}`)),r.userData.isHiddenByGoal=!0)}if(this.effectsManager.explosions.demoEvents.has(i)){const a=this.effectsManager.explosions.demoEvents.get(i),r=this.actors[a.victimActorId];if(r){if(!s){const o=r.userData.playerId,l=o&&this.playerTeams&&this.playerTeams[o]||0;this.effectsManager.triggerDemoExplosion(r.position,l),console.log(`💥 DEMO! Explosion at frame ${i} for actor ${a.victimActorId}`)}r.userData.sleeping=!0}}}}resolveBodyId(e,t){if(!e||!e.userData.isCar||!e.userData.teamLoadout)return;let i=0;e.userData.playerId&&Object.prototype.hasOwnProperty.call(this.playerTeams,e.userData.playerId)&&(i=this.playerTeams[e.userData.playerId]);const s=e.userData.teamLoadout,a=i===1?s.orange?.body:s.blue?.body;a&&e.userData.bodyId!==a&&(e.userData.bodyId=a,this.updateCarHitbox(e,a,t))}updateCarHitbox(e,t,i){const s=bw(t),a=s?.name||"Octane",r=s?.hitboxType||"Octane";this.replaceCarWithModel(i,e,a,r)}async replaceCarWithModel(e,t,i,s){if(this.carModelLoader.isModelReady(i,s))this._doCarReplacement(e,t,i,s);else{this.pendingCarReplacements.set(e,{oldMesh:t,carName:i,hitboxType:s});try{const a=this.carModelLoader.getModelTypeForCar(i,s);await this.carModelLoader.loadModel(a);const r=this.pendingCarReplacements.get(e);r&&this.actors[e]===r.oldMesh&&this._doCarReplacement(e,r.oldMesh,r.carName,r.hitboxType),this.pendingCarReplacements.delete(e)}catch(a){console.warn(`Failed to load model for ${i} (${s}):`,a),this.pendingCarReplacements.delete(e),t&&(t.visible=!0)}}}_doCarReplacement(e,t,i,s){let a=0;t.userData.playerId&&Object.prototype.hasOwnProperty.call(this.playerTeams,t.userData.playerId)?a=this.playerTeams[t.userData.playerId]:t.userData.team!==void 0&&(a=t.userData.team);const r=this.carModelLoader.getCarMeshSync(i,s,a);if(!r){console.warn(`Could not get car mesh for ${i} (${s})`);return}const o=r.userData.wheels;r.userData={...t.userData},r.userData.isFBXModel=!0,r.userData.carName=i,r.userData.hitboxType=s,r.userData.wheels=o,r.position.copy(t.position),r.quaternion.copy(t.quaternion),this.scene.remove(t),t.geometry&&t.geometry.dispose(),t.material&&(Array.isArray(t.material)?t.material.forEach(c=>c.dispose()):t.material.dispose()),this.scene.add(r),this.actors[e]=r,this.effectsManager.removeBoostTrail(e),this.effectsManager.createBoostTrail(r,e);const l=this.carModelLoader.getModelTypeForCar(i,s);console.log(`🚗 Replaced car ${e} with ${l.toUpperCase()} model (${i}, ${s} hitbox, team ${a===0?"blue":"orange"})`)}checkCarPlayerLink(e,t){const i=this.actorToPlayer[e],s=this.actorLoadouts[e];if(!(!i&&!s))if(t){const a=this.actors[t];a&&a.userData.isCar&&(this.onPlayerFound&&this.onPlayerFound(i),a.userData.playerId=i,this.playerNameToCarActorId[i]=t,s&&(a.userData.teamLoadout=s),this.resolveBodyId(a,t))}else this.actorLinks[e]&&this.actorLinks[e].forEach(a=>{this.checkCarPlayerLink(e,a)})}updateInterpolation(e,t,i){const s=t[i];if(s&&Object.keys(this.actors).forEach(a=>{const r=this.actors[a],o=r.userData.location,l=r.userData.rotation;if(!o||!l||!r.userData.hasReceivedUpdate)return;let c=null,u=0;for(let d=i+1;dp.actor_id==a&&p.attribute&&p.attribute.RigidBody);if(f){c=f,u=h.time;break}}}if(c){const d=r.userData.lastUpdateTime||s.time,h=u;if(h>d){const f=(e-d)/(h-d),p=Math.max(0,Math.min(1,f)),g=h-d||.033,_=c.attribute.RigidBody;if(_.location)if(this._p0.copy(o),this._p1.set(_.location.x,_.location.z,_.location.y),r.userData.sleeping)r.position.copy(o);else{const m=c.attribute.RigidBody;if(r.userData.velocity&&m.linear_velocity){const v=p,y=v*v,b=y*v;if(g>.5)r.position.lerpVectors(o,this._p1,p);else{this._v0.copy(r.userData.velocity).multiplyScalar(g),this._v1.set(m.linear_velocity.x,m.linear_velocity.z,m.linear_velocity.y).multiplyScalar(g);const T=2*b-3*y+1,x=b-2*y+v,M=-2*b+3*y,C=b-y;r.position.set(T*this._p0.x+x*this._v0.x+M*this._p1.x+C*this._v1.x,T*this._p0.y+x*this._v0.y+M*this._p1.y+C*this._v1.y,T*this._p0.z+x*this._v0.z+M*this._p1.z+C*this._v1.z)}}else r.position.lerpVectors(o,this._p1,p)}else r.position.copy(o);_.rotation?(this._nextRot.set(_.rotation.x,_.rotation.z,_.rotation.y,-_.rotation.w),r.quaternion.slerpQuaternions(l,this._nextRot,p)):r.quaternion.copy(l);return}}r.position.copy(o),r.quaternion.copy(l)}),Object.keys(this.actors).forEach(a=>{const r=this.actors[a];if(r&&r.userData.isCar){const l=r.position.length()>.1,c=r.userData.sleeping===!0;r.visible=l&&!c}}),this.ballActorId&&this.actors[this.ballActorId]){const a=this.actors[this.ballActorId];if(a.visible=!a.userData.isHiddenByGoal,this.ballIndicator&&(this.ballIndicator.position.set(a.position.x,2,a.position.z),this.ballIndicator.visible=a.visible),this.ballVerticalLine){const o=new Float32Array([a.position.x,2,a.position.z,a.position.x,a.position.y,a.position.z]);this.ballVerticalLine.geometry.setAttribute("position",new rt(o,3)),this.ballVerticalLine.geometry.attributes.position.needsUpdate=!0,this.ballVerticalLine.visible=a.visible}if(a.userData.velocity&&a.visible){let r=this.lastBallTouchTeam,o=this.BALL_TOUCH_DISTANCE;Object.keys(this.actors).forEach(l=>{const c=this.actors[l];if(c&&c.userData.isCar&&c.userData.playerId){const u=a.position.distanceTo(c.position);if(u{const s=this.actors[i];if(!s||!s.userData.isCar||!s.userData.isFBXModel&&!s.userData.hasWheelSockets||!s.userData.wheels||s.userData.wheels.length===0)return;const a=s.position;let r=this._previousCarPositions.get(i);r||(r=a.clone(),this._previousCarPositions.set(i,r));const l=new S().subVectors(a,r).length();if(this._previousCarPositions.set(i,a.clone()),l<.01)return;const d=Math.min(l/e,.5)*1;let h=0;s.userData.steer!==void 0&&(h=-s.userData.steer*t),s.userData.wheels.forEach(f=>{if(f.socket){const p=f.side==="left"?1:-1;if(f.mesh.rotateZ(p*d),f.position==="front"&&f.steeringPivot){const g=f.side==="left"?-1:1;f.steeringPivot.rotation.y=g*h}}else{const p=f.side==="left"?-1:1;f.mesh.rotateY(p*d),f.position==="front"&&f.steeringPivot&&(f.steeringPivot.rotation.z=h)}})})}resetWheelTracking(){this._previousCarPositions&&this._previousCarPositions.clear()}updateSupersonicState(e,t,i){const s=this.playerNameToCarActorId[e];if(!s)return;const a=this.actors[s];if(!a||!a.userData.isCar)return;const r=a.userData.velocity||new S(0,0,0);this.effectsManager.updateSupersonicTrail(s,t,a.position,a.quaternion,r,i)}setInterpolationEnabled(e){this.interpolationEnabled=e,console.log(`[ActorManager] Interpolation ${e?"enabled":"disabled"}`)}setInterpolationMethod(e){if(!["lerp","hermite","catmull-rom","predict-correct","velocity-smooth","physics-tick","velocity-only","smart-hybrid","time-shifted","lerp-smooth","lerp-ema","lerp-dema","lerp-wma","lerp-gauss","one-euro","position-lerp","position-catmull","position-smooth","adaptive-smooth"].includes(e)){console.warn(`[ActorManager] Invalid interpolation method: ${e}`);return}this.interpolationMethod=e,this._smoothingBuffers.clear(),this._lowPassState.clear(),this._adaptiveState.clear(),this.resetSmoothingBuffers(),console.log(`[ActorManager] Interpolation method set to: ${e}`)}setSmoothingWindowSize(e){this.smoothingWindowSize=Math.max(1,Math.min(20,e)),this._smoothingBuffers.clear(),console.log(`[ActorManager] Smoothing window size set to: ${this.smoothingWindowSize}`)}getInterpolationSettings(){return{enabled:this.interpolationEnabled,method:this.interpolationMethod,smoothingWindowSize:this.smoothingWindowSize}}clearSmoothingBuffers(){this._smoothingBuffers.clear()}getFrameInfo(){return this.lastFrameInfo}createBallMeshForLive(){const e=new yn(92.75,16,16),t=new Pn({color:16777215}),i=new we(e,t);if(i.castShadow=!0,i.receiveShadow=!0,i.userData={location:new S,rotation:new dt,velocity:new S,angularVelocity:new S,isCar:!1,isBall:!0,playerId:null,sleeping:!1,isHiddenByGoal:!1},this.scene.add(i),this.ballModel){const s=this.ballModel.clone();s.position.copy(i.position),s.quaternion.copy(i.quaternion),s.userData={...i.userData};const a=92.75;return s.scale.set(a,a,a),s.traverse(r=>{r.isMesh&&(r.castShadow=!0,r.receiveShadow=!0)}),this.scene.remove(i),this.scene.add(s),i.geometry&&i.geometry.dispose(),i.material&&i.material.dispose(),console.log("✓ Live ball created with GLTF model"),s}return i}createCarMeshForLive(e,t,i,s=null){const a=`live_car_${t}`,r=new Ei(118,36,84),o=e===0?3381759:16737792,l=new Pn({color:o}),c=new we(r,l);return c.castShadow=!0,c.receiveShadow=!0,c.visible=!1,c.userData={location:new S,rotation:new dt,velocity:new S,angularVelocity:new S,isCar:!0,isBall:!1,playerId:i,team:e,sleeping:!1,steer:0,bodyId:s,liveActorId:a},this.scene.add(c),this.actors[a]=c,this.playerNameToCarActorId[i]=a,this.effectsManager.createBoostTrail(c,a),s&&s>0?this.updateCarHitbox(c,s,a):this.replaceCarWithModel(a,c,"Octane","Octane"),console.log(`[ActorManager] Created live car for ${i} (team ${e===0?"blue":"orange"}, bodyId: ${s})`),c}updateBoostParticlesLive(e,t,i,s){const a=t&&i>0,r=s.userData.velocity||new S(0,0,0);this.effectsManager.updateBoostTrail(e,a,s.position,s.quaternion,r)}updateSupersonicTrailLive(e,t,i,s){const a=s.userData.velocity||new S(0,0,0);this.effectsManager.updateSupersonicTrail(e,t,s.position,s.quaternion,a,i)}removeLiveCar(e){const t=this.actors[e];t&&(this.scene.remove(t),t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose(),delete this.actors[e],this.effectsManager.removeBoostTrail(e))}removeLiveBall(e){e&&(this.scene.remove(e),e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose())}}function Ms(n,e,t){t===-1?(n.clearUpdateRanges?.(),n.addUpdateRange?.(0,n.count*n.itemSize)):n.addUpdateRange?(n.clearUpdateRanges(),n.addUpdateRange(e,t)):(n.updateRange.offset=e,n.updateRange.count=t)}class pt extends Qe{constructor(e,t){super(),this.active=!1,this.orientToMovement=!1,t&&(this.orientToMovement=!0),this.scene=e,this.geometry=null,this.mesh=null,this.nodeCenters=null,this.lastNodeCenter=null,this.currentNodeCenter=null,this.lastOrientationDir=null,this.nodeIDs=null,this.currentLength=0,this.currentEnd=0,this.currentNodeID=0,this.advanceFrequency=60,this.advancePeriod=1/this.advanceFrequency,this.lastAdvanceTime=0,this.paused=!1,this.pauseAdvanceUpdateTimeDiff=0,this._internalTime=0,this._useInternalTime=!1}setAdvanceFrequency(e){this.advanceFrequency=e,this.advancePeriod=1/this.advanceFrequency}initialize(e,t,i,s,a,r){this.deactivate(),this.destroyMesh(),this.length=t>0?t+1:0,this.dragTexture=i?1:0,this.targetObject=r,this.initializeLocalHeadGeometry(s,a),this.nodeIDs=[],this.nodeCenters=[];for(let o=0;o=this.length?0:this.currentEnd+1;if(i?this.updateNodePositionsFromTransformMatrix(s,i):this.updateNodePositionsFromOrientationTangent(s,t.position,t.tangent),this.currentLength>=1&&(this.connectNodes(this.currentEnd,s),this.currentLength>=this.length)){const a=this.currentEnd+1>=this.length?0:this.currentEnd+1;this.disconnectNodes(a)}this.currentLength=this.length&&(this.currentEnd=0),this.currentLength>=1&&(this.currentLengththis.advancePeriod?(this.advance(),this.lastAdvanceTime=t):this.updateHead()}}updateHead=(function(){const e=new Me;return function(){this.currentEnd<0||(this.targetObject.updateMatrixWorld(),e.copy(this.targetObject.matrixWorld),this.updateNodePositionsFromTransformMatrix(this.currentEnd,e))}})();updateNodeID(e,t){this.nodeIDs[e]=t;const i=this.geometry.getAttribute("nodeID"),s=this.geometry.getAttribute("nodeVertexID");for(let a=0;a1e-4)){this.lastOrientationDir||(this.lastOrientationDir=new S),t.setFromUnitVectors(a,r),s.copy(this.currentNodeCenter);for(let f=0;f=7?(fu.setRGB(parseFloat(d[4]),parseFloat(d[5]),parseFloat(d[6]),gt),t.colors.push(fu.r,fu.g,fu.b)):t.colors.push(void 0,void 0,void 0);break;case"vn":t.normals.push(parseFloat(d[1]),parseFloat(d[2]),parseFloat(d[3]));break;case"vt":t.uvs.push(parseFloat(d[1]),parseFloat(d[2]));break}}else if(u==="f"){const h=c.slice(1).trim().split(tv),f=[];for(let g=0,_=h.length;g<_;g++){const m=h[g];if(m.length>0){const v=m.split("/");f.push(v)}}const p=f[0];for(let g=1,_=f.length-1;g<_;g++){const m=f[g],v=f[g+1];t.addFace(p[0],m[0],v[0],p[1],m[1],v[1],p[2],m[2],v[2])}}else if(u==="l"){const d=c.substring(1).trim().split(" ");let h=[];const f=[];if(c.indexOf("/")===-1)h=d;else for(let p=0,g=d.length;p1){const h=s[1].trim().toLowerCase();t.object.smooth=h!=="0"&&h!=="off"}else t.object.smooth=!0;const d=t.object.currentMaterial();d&&(d.smooth=t.object.smooth)}else{if(c==="\0")continue;console.warn('THREE.OBJLoader: Unexpected line: "'+c+'"')}}t.finalize();const a=new Mt;if(a.materialLibraries=[].concat(t.materialLibraries),!(t.objects.length===1&&t.objects[0].geometry.vertices.length===0)===!0)for(let o=0,l=t.objects.length;o0&&g.setAttribute("normal",new Ee(u.normals,3)),u.colors.length>0&&(p=!0,g.setAttribute("color",new Ee(u.colors,3))),u.hasUVIndices===!0&&g.setAttribute("uv",new Ee(u.uvs,2));const _=[];for(let v=0,y=d.length;v1){for(let v=0,y=d.length;v0){const o=new aa({size:1,sizeAttenuation:!1}),l=new Ge;l.setAttribute("position",new Ee(t.vertices,3)),t.colors.length>0&&t.colors[0]!==void 0&&(l.setAttribute("color",new Ee(t.colors,3)),o.vertexColors=!0);const c=new sr(l,o);a.add(c)}return a}}const _p=new Map;async function gO(n,e){const t=Si("models/stadium/stadium.glb",e);let i=_p.get(t);return i||(i=n.loadAsync(t).then(s=>{const a=s.scene;return yO(a),a}).catch(s=>{throw _p.delete(t),s}),_p.set(t,i)),i}function yO(n){const e=["Sol_Trait_T0","Sol_Trait_T1","Milieu_Forme","Milieu_Forme.001","cage_T0","cage_T1","Couleur_Hexagone_T0","Couleur_Hexagone_T1","wall_gradient_color_2","wall_gradient_color_2.001","Fond_BackBoard_Transparent","dégradé_transparent_T0","dégradé_transparent_T1","grid_transperant","Detail_Milieu","Detail_Milieu.001"],t=["Glow","Glass"],i=["Plafond_Hexagone_T0","Plafond_Hexagone_T1","Plafond_Transparent"];n.traverse(s=>{if(!s.isMesh)return;s.receiveShadow=!0,s.castShadow=!i.includes(s.name),t.some(r=>s.name.includes(r))&&(console.log(`[ArenaManager] Disabling frustum culling for: ${s.name}`),s.frustumCulled=!1),s.material&&/^Hexagone_T[01]$/.test(s.material.name??"")&&(s.material=s.material.clone(),s.material.transparent=!0,s.material.opacity=.18,s.material.depthWrite=!1,s.renderOrder=1),s.material&&s.material.name==="bannière_pub"&&(s.visible=!1),s.material&&s.material.name==="Sol_Hexagone"&&(s.material=s.material.clone(),s.material.color.setScalar(.35),s.material.metalness=0,s.material.roughness=1),s.material&&s.material.name&&e.includes(s.material.name)&&(console.log(`[ArenaManager] Fixing visibility for: ${s.name} (material: ${s.material.name})`),s.material=s.material.clone(),s.material.side=ct,s.material.depthWrite=!1,s.renderOrder=1,s.frustumCulled=!1)})}class vO{constructor(e,t={}){this.scene=e,this.assetBase=t.assetBase,this.arenaMeshes=[],this.drawingCollider=null,this.drawingColliderMeshes=[],this.arenaDecorMesh=null,this.showArenaDecor=!0,this.dracoLoader=new bT,this.dracoLoader.setDecoderPath(Si("draco/",this.assetBase)),this.gltfLoader=new Og,this.gltfLoader.setDRACOLoader(this.dracoLoader)}async loadArenaMeshes(){try{console.log("Loading arena mesh...");const t=(await gO(this.gltfLoader,this.assetBase)).clone(!0);t.traverse(i=>{i.isMesh&&this.arenaMeshes.push(i)}),console.log(`[ArenaManager] Collected ${this.arenaMeshes.length} meshes for raycasting`),this.scene.add(t),console.log("Arena mesh loaded successfully with correct orientation")}catch(e){console.error("Error loading arena mesh:",e);const t=new kn(10240,8192),i=new Pn({color:3355443,side:ct}),s=new we(t,i);s.rotation.x=-Math.PI/2,s.receiveShadow=!0,this.scene.add(s),this.arenaMeshes.push(s)}}getArenaMeshes(){return this.arenaMeshes}getDrawingColliderMeshes(){return this.drawingColliderMeshes}async loadDrawingCollider(e=!1){try{console.log("[ArenaManager] Loading drawing collider...");const i=await new _O().loadAsync(Si("models/stadium/DrawingArena.obj",this.assetBase));i.rotation.x=Math.PI/2,i.rotation.y=Math.PI,i.scale.setScalar(.99),i.position.y=20,i.traverse(s=>{s.isMesh&&(this.drawingColliderMeshes.push(s),s.castShadow=!1,s.receiveShadow=!1,e?s.material=new Ye({color:65280,transparent:!0,opacity:.7,side:ct}):s.material=new Ye({visible:!1}))}),this.drawingCollider=i,this.scene.add(i),console.log(`[ArenaManager] Drawing collider loaded with ${this.drawingColliderMeshes.length} meshes`)}catch(t){console.error("[ArenaManager] Failed to load drawing collider:",t)}}setDrawingColliderVisible(e){for(const t of this.drawingColliderMeshes)e?t.material=new Ye({color:65280,wireframe:!0,transparent:!0,opacity:.5}):t.material=new Ye({visible:!1})}async loadArenaDecor(e=!0){try{console.log("[ArenaManager] Loading arena decoration mesh...");const t=await this.gltfLoader.loadAsync(Si("models/stadium/arene.glb",this.assetBase));this.arenaDecorMesh=t.scene,this.showArenaDecor=e,this.arenaDecorMesh.traverse(i=>{i.isMesh&&(i.receiveShadow=!0,i.castShadow=!0)}),this.arenaDecorMesh.visible=e,this.scene.add(this.arenaDecorMesh),console.log(`[ArenaManager] Arena decoration loaded, visible: ${e}`)}catch(t){console.error("[ArenaManager] Failed to load arena decoration:",t)}}setArenaDecorVisible(e){this.showArenaDecor=e,this.arenaDecorMesh&&(this.arenaDecorMesh.visible=e,console.log(`[ArenaManager] Arena decoration visibility set to: ${e}`))}isArenaDecorVisible(){return this.showArenaDecor}}var Ti=Uint8Array,Qr=Uint16Array,bO=Int32Array,xT=new Ti([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),wT=new Ti([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),xO=new Ti([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ST=function(n,e){for(var t=new Qr(31),i=0;i<31;++i)t[i]=e+=1<>1|(Nt&21845)<<1;js=(js&52428)>>2|(js&13107)<<2,js=(js&61680)>>4|(js&3855)<<4,zm[Nt]=((js&65280)>>8|(js&255)<<8)>>1}var Dl=(function(n,e,t){for(var i=n.length,s=0,a=new Qr(e);s>l]=c}else for(o=new Qr(i),s=0;s>15-n[s]);return o}),_c=new Ti(288);for(var Nt=0;Nt<144;++Nt)_c[Nt]=8;for(var Nt=144;Nt<256;++Nt)_c[Nt]=9;for(var Nt=256;Nt<280;++Nt)_c[Nt]=7;for(var Nt=280;Nt<288;++Nt)_c[Nt]=8;var ET=new Ti(32);for(var Nt=0;Nt<32;++Nt)ET[Nt]=5;var MO=Dl(_c,9,1),EO=Dl(ET,5,1),gp=function(n){for(var e=n[0],t=1;te&&(e=n[t]);return e},Oi=function(n,e,t){var i=e/8|0;return(n[i]|n[i+1]<<8)>>(e&7)&t},yp=function(n,e){var t=e/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},CO=function(n){return(n+7)/8|0},AO=function(n,e,t){return(t==null||t>n.length)&&(t=n.length),new Ti(n.subarray(e,t))},RO=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Vi=function(n,e,t){var i=new Error(e||RO[n]);if(i.code=n,Error.captureStackTrace&&Error.captureStackTrace(i,Vi),!t)throw i;return i},PO=function(n,e,t,i){var s=n.length,a=0;if(!s||e.f&&!e.l)return t||new Ti(0);var r=!t,o=r||e.i!=2,l=e.i;r&&(t=new Ti(s*3));var c=function(xe){var Ae=t.length;if(xe>Ae){var L=new Ti(Math.max(Ae*2,xe));L.set(t),t=L}},u=e.f||0,d=e.p||0,h=e.b||0,f=e.l,p=e.d,g=e.m,_=e.n,m=s*8;do{if(!f){u=Oi(n,d,1);var v=Oi(n,d+1,3);if(d+=3,v)if(v==1)f=MO,p=EO,g=9,_=5;else if(v==2){var x=Oi(n,d,31)+257,M=Oi(n,d+10,15)+4,C=x+Oi(n,d+5,31)+1;d+=14;for(var w=new Ti(C),E=new Ti(19),R=0;R>4;if(y<16)w[R++]=y;else{var F=0,W=0;for(y==16?(W=3+Oi(n,d,3),d+=2,F=w[R-1]):y==17?(W=3+Oi(n,d,7),d+=3):y==18&&(W=11+Oi(n,d,127),d+=7);W--;)w[R++]=F}}var H=w.subarray(0,x),ne=w.subarray(x);g=gp(H),_=gp(ne),f=Dl(H,g,1),p=Dl(ne,_,1)}else Vi(1);else{var y=CO(d)+4,b=n[y-4]|n[y-3]<<8,T=y+b;if(T>s){l&&Vi(0);break}o&&c(h+b),t.set(n.subarray(y,T),h),e.b=h+=b,e.p=d=T*8,e.f=u;continue}if(d>m){l&&Vi(0);break}}o&&c(h+131072);for(var oe=(1<>4;if(d+=F&15,d>m){l&&Vi(0);break}if(F||Vi(2),ke<256)t[h++]=ke;else if(ke==256){Ie=d,f=null;break}else{var Xe=ke-254;if(ke>264){var R=ke-257,De=xT[R];Xe=Oi(n,d,(1<>4;Z||Vi(3),d+=Z&15;var ne=TO[ae];if(ae>3){var De=wT[ae];ne+=yp(n,d)&(1<m){l&&Vi(0);break}o&&c(h+131072);var Se=h+Xe;if(h>4>7||(n[0]<<8|n[1])%31)&&Vi(6,"invalid zlib data"),(n[1]>>5&1)==1&&Vi(6,"invalid zlib data: "+(n[1]&32?"need":"unexpected")+" dictionary"),(n[1]>>3&4)+2};function kO(n,e){return PO(n.subarray(LO(n),-4),{i:2},e,e)}var DO=typeof TextDecoder<"u"&&new TextDecoder,OO=0;try{DO.decode(IO,{stream:!0}),OO=1}catch{}function CT(n,e,t){const i=t.length-n-1;if(e>=t[i])return i-1;if(e<=t[n])return n;let s=n,a=i,r=Math.floor((s+a)/2);for(;e=t[r+1];)e=g&&(p[f][0]=p[h][0]/o[v+1][m],_=p[f][0]*o[m][v]);const y=m>=-1?1:-m,b=d-1<=v?g-1:t-d;for(let x=y;x<=b;++x)p[f][x]=(p[h][x]-p[h][x-1])/o[v+1][m+x],_+=p[f][x]*o[m+x][v];d<=v&&(p[f][g]=-p[h][g-1]/o[v+1][d],_+=p[f][g]*o[d][v]),r[g][d]=_;const T=h;h=f,f=T}}let u=t;for(let d=1;d<=i;++d){for(let h=0;h<=t;++h)r[d][h]*=u;u*=t-d}return r}function BO(n,e,t,i,s){const a=st.toArray()),e.startKnot=this.startKnot,e.endKnot=this.endKnot,e}fromJSON(e){return super.fromJSON(e),this.degree=e.degree,this.knots=[...e.knots],this.controlPoints=e.controlPoints.map(t=>new qe(t[0],t[1],t[2],t[3])),this.startKnot=e.startKnot,this.endKnot=e.endKnot,this}}let _t,Zt,Un;class $O extends on{constructor(e){super(e)}load(e,t,i,s){const a=this,r=a.path===""?Us.extractUrlBase(e):a.path,o=new Gn(this.manager);o.setPath(a.path),o.setResponseType("arraybuffer"),o.setRequestHeader(a.requestHeader),o.setWithCredentials(a.withCredentials),o.load(e,function(l){try{t(a.parse(l,r))}catch(c){s?s(c):console.error(c),a.manager.itemError(e)}},i,s)}parse(e,t){if(jO(e))_t=new YO().parse(e);else{const s=PT(e);if(!ZO(s))throw new Error("THREE.FBXLoader: Unknown format.");if(rv(s)<7e3)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+rv(s));_t=new qO().parse(s)}const i=new tf(this.manager).setPath(this.resourcePath||t).setCrossOrigin(this.crossOrigin);return new WO(i,this.manager).parse(_t)}}class WO{constructor(e,t){this.textureLoader=e,this.manager=t}parse(){Zt=this.parseConnections();const e=this.parseImages(),t=this.parseTextures(e),i=this.parseMaterials(t),s=this.parseDeformers(),a=new XO().parse(s);return this.parseScene(s,a,i),Un}parseConnections(){const e=new Map;return"Connections"in _t&&_t.Connections.connections.forEach(function(i){const s=i[0],a=i[1],r=i[2];e.has(s)||e.set(s,{parents:[],children:[]});const o={ID:a,relationship:r};e.get(s).parents.push(o),e.has(a)||e.set(a,{parents:[],children:[]});const l={ID:s,relationship:r};e.get(a).children.push(l)}),e}parseImages(){const e={},t={};if("Video"in _t.Objects){const i=_t.Objects.Video;for(const s in i){const a=i[s],r=parseInt(s);if(e[r]=a.RelativeFilename||a.Filename,"Content"in a){const o=a.Content instanceof ArrayBuffer&&a.Content.byteLength>0,l=typeof a.Content=="string"&&a.Content!=="";if(o||l){const c=this.parseImage(i[s]);t[a.RelativeFilename||a.Filename]=c}}}}for(const i in e){const s=e[i];t[s]!==void 0?e[i]=t[s]:e[i]=e[i].split("\\").pop()}return e}parseImage(e){const t=e.Content,i=e.RelativeFilename||e.Filename,s=i.slice(i.lastIndexOf(".")+1).toLowerCase();let a;switch(s){case"bmp":a="image/bmp";break;case"jpg":case"jpeg":a="image/jpeg";break;case"png":a="image/png";break;case"tif":a="image/tiff";break;case"tga":this.manager.getHandler(".tga")===null&&console.warn("FBXLoader: TGA loader not found, skipping ",i),a="image/tga";break;case"webp":a="image/webp";break;default:console.warn('FBXLoader: Image type "'+s+'" is not supported.');return}if(typeof t=="string")return"data:"+a+";base64,"+t;{const r=new Uint8Array(t);return window.URL.createObjectURL(new Blob([r],{type:a}))}}parseTextures(e){const t=new Map;if("Texture"in _t.Objects){const i=_t.Objects.Texture;for(const s in i){const a=this.parseTexture(i[s],e);t.set(parseInt(s),a)}}return t}parseTexture(e,t){const i=this.loadTexture(e,t);i.ID=e.id,i.name=e.attrName;const s=e.WrapModeU,a=e.WrapModeV,r=s!==void 0?s.value:0,o=a!==void 0?a.value:0;if(i.wrapS=r===0?ps:Hn,i.wrapT=o===0?ps:Hn,"Scaling"in e){const l=e.Scaling.value;i.repeat.x=l[0],i.repeat.y=l[1]}if("Translation"in e){const l=e.Translation.value;i.offset.x=l[0],i.offset.y=l[1]}return i}loadTexture(e,t){const i=e.FileName.split(".").pop().toLowerCase();let s=this.manager.getHandler(`.${i}`);s===null&&(s=this.textureLoader);const a=s.path;a||s.setPath(this.textureLoader.path);const r=Zt.get(e.id).children;let o;if(r!==void 0&&r.length>0&&t[r[0].ID]!==void 0&&(o=t[r[0].ID],(o.indexOf("blob:")===0||o.indexOf("data:")===0)&&s.setPath(void 0)),o===void 0)return console.warn("FBXLoader: Undefined filename, creating placeholder texture."),new Bt;const l=s.load(o);return s.setPath(a),l}parseMaterials(e){const t=new Map;if("Material"in _t.Objects){const i=_t.Objects.Material;for(const s in i){const a=this.parseMaterial(i[s],e);a!==null&&t.set(parseInt(s),a)}}return t}parseMaterial(e,t){const i=e.id,s=e.attrName;let a=e.ShadingModel;if(typeof a=="object"&&(a=a.value),!Zt.has(i))return null;const r=this.parseParameters(e,t,i);let o;switch(a.toLowerCase()){case"phong":o=new ja;break;case"lambert":o=new ef;break;default:console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.',a),o=new ja;break}return o.setValues(r),o.name=s,o}parseParameters(e,t,i){const s={};e.BumpFactor&&(s.bumpScale=e.BumpFactor.value),e.Diffuse?s.color=rt.colorSpaceToWorking(new ue().fromArray(e.Diffuse.value),gt):e.DiffuseColor&&(e.DiffuseColor.type==="Color"||e.DiffuseColor.type==="ColorRGB")&&(s.color=rt.colorSpaceToWorking(new ue().fromArray(e.DiffuseColor.value),gt)),e.DisplacementFactor&&(s.displacementScale=e.DisplacementFactor.value),e.Emissive?s.emissive=rt.colorSpaceToWorking(new ue().fromArray(e.Emissive.value),gt):e.EmissiveColor&&(e.EmissiveColor.type==="Color"||e.EmissiveColor.type==="ColorRGB")&&(s.emissive=rt.colorSpaceToWorking(new ue().fromArray(e.EmissiveColor.value),gt)),e.EmissiveFactor&&(s.emissiveIntensity=parseFloat(e.EmissiveFactor.value)),s.opacity=1-(e.TransparencyFactor?parseFloat(e.TransparencyFactor.value):0),(s.opacity===1||s.opacity===0)&&(s.opacity=e.Opacity?parseFloat(e.Opacity.value):null,s.opacity===null&&(s.opacity=1-(e.TransparentColor?parseFloat(e.TransparentColor.value[0]):0))),s.opacity<1&&(s.transparent=!0),e.ReflectionFactor&&(s.reflectivity=e.ReflectionFactor.value),e.Shininess&&(s.shininess=e.Shininess.value),e.Specular?s.specular=rt.colorSpaceToWorking(new ue().fromArray(e.Specular.value),gt):e.SpecularColor&&e.SpecularColor.type==="Color"&&(s.specular=rt.colorSpaceToWorking(new ue().fromArray(e.SpecularColor.value),gt));const a=this;return Zt.get(i).children.forEach(function(r){const o=r.relationship;switch(o){case"Bump":s.bumpMap=a.getTexture(t,r.ID);break;case"Maya|TEX_ao_map":s.aoMap=a.getTexture(t,r.ID);break;case"DiffuseColor":case"Maya|TEX_color_map":s.map=a.getTexture(t,r.ID),s.map!==void 0&&(s.map.colorSpace=gt);break;case"DisplacementColor":s.displacementMap=a.getTexture(t,r.ID);break;case"EmissiveColor":s.emissiveMap=a.getTexture(t,r.ID),s.emissiveMap!==void 0&&(s.emissiveMap.colorSpace=gt);break;case"NormalMap":case"Maya|TEX_normal_map":s.normalMap=a.getTexture(t,r.ID);break;case"ReflectionColor":s.envMap=a.getTexture(t,r.ID),s.envMap!==void 0&&(s.envMap.mapping=rr,s.envMap.colorSpace=gt);break;case"SpecularColor":s.specularMap=a.getTexture(t,r.ID),s.specularMap!==void 0&&(s.specularMap.colorSpace=gt);break;case"TransparentColor":case"TransparencyFactor":s.alphaMap=a.getTexture(t,r.ID),s.transparent=!0;break;default:console.warn("THREE.FBXLoader: %s map is not supported in three.js, skipping texture.",o);break}}),s}getTexture(e,t){return"LayeredTexture"in _t.Objects&&t in _t.Objects.LayeredTexture&&(console.warn("THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer."),t=Zt.get(t).children[0].ID),e.get(t)}parseDeformers(){const e={},t={};if("Deformer"in _t.Objects){const i=_t.Objects.Deformer;for(const s in i){const a=i[s],r=Zt.get(parseInt(s));if(a.attrType==="Skin"){const o=this.parseSkeleton(r,i);o.ID=s,r.parents.length>1&&console.warn("THREE.FBXLoader: skeleton attached to more than one geometry is not supported."),o.geometryID=r.parents[0].ID,e[s]=o}else if(a.attrType==="BlendShape"){const o={id:s};o.rawTargets=this.parseMorphTargets(r,i),o.id=s,r.parents.length>1&&console.warn("THREE.FBXLoader: morph target attached to more than one geometry is not supported."),t[s]=o}}}return{skeletons:e,morphTargets:t}}parseSkeleton(e,t){const i=[];return e.children.forEach(function(s){const a=t[s.ID];if(a.attrType!=="Cluster")return;const r={ID:s.ID,indices:[],weights:[],transformLink:new Me().fromArray(a.TransformLink.a)};"Indexes"in a&&(r.indices=a.Indexes.a,r.weights=a.Weights.a),i.push(r)}),{rawBones:i,bones:[]}}parseMorphTargets(e,t){const i=[];for(let s=0;s1?r=o:o.length>0?r=o[0]:(r=new ja({name:on.DEFAULT_MATERIAL_NAME,color:13421772}),o.push(r)),"color"in a.attributes&&o.forEach(function(l){l.vertexColors=!0}),a.groups.length>0){let l=!1;for(let c=0,u=a.groups.length;c=o.length)&&(d.materialIndex=o.length,l=!0)}if(l){const c=new ja;o.push(c)}}return a.FBX_Deformer?(s=new Bh(a,r),s.normalizeSkinWeights()):s=new we(a,r),s}createCurve(e,t){const i=e.children.reduce(function(a,r){return t.has(r.ID)&&(a=t.get(r.ID)),a},null),s=new Rt({name:on.DEFAULT_MATERIAL_NAME,color:3342591,linewidth:1});return new In(i,s)}getTransformData(e,t){const i={};"InheritType"in t&&(i.inheritType=parseInt(t.InheritType.value)),"RotationOrder"in t?i.eulerOrder=Zl(t.RotationOrder.value):i.eulerOrder=Zl(0),"Lcl_Translation"in t&&(i.translation=t.Lcl_Translation.value),"PreRotation"in t&&(i.preRotation=t.PreRotation.value),"Lcl_Rotation"in t&&(i.rotation=t.Lcl_Rotation.value),"PostRotation"in t&&(i.postRotation=t.PostRotation.value),"Lcl_Scaling"in t&&(i.scale=t.Lcl_Scaling.value),"ScalingOffset"in t&&(i.scalingOffset=t.ScalingOffset.value),"ScalingPivot"in t&&(i.scalingPivot=t.ScalingPivot.value),"RotationOffset"in t&&(i.rotationOffset=t.RotationOffset.value),"RotationPivot"in t&&(i.rotationPivot=t.RotationPivot.value),e.userData.transformData=i}setLookAtProperties(e,t){"LookAtProperty"in t&&Zt.get(e.ID).children.forEach(function(s){if(s.relationship==="LookAtProperty"){const a=_t.Objects.Model[s.ID];if("Lcl_Translation"in a){const r=a.Lcl_Translation.value;e.target!==void 0?(e.target.position.fromArray(r),Un.add(e.target)):e.lookAt(new S().fromArray(r))}}})}bindSkeleton(e,t,i){const s=this.parsePoseNodes();for(const a in e){const r=e[a];Zt.get(parseInt(r.ID)).parents.forEach(function(l){if(t.has(l.ID)){const c=l.ID;Zt.get(c).parents.forEach(function(d){i.has(d.ID)&&i.get(d.ID).bind(new Lo(r.bones),s[d.ID])})}})}}parsePoseNodes(){const e={};if("Pose"in _t.Objects){const t=_t.Objects.Pose;for(const i in t)if(t[i].attrType==="BindPose"&&t[i].NbPoseNodes>0){const s=t[i].PoseNode;Array.isArray(s)?s.forEach(function(a){e[a.Node]=new Me().fromArray(a.Matrix.a)}):e[s.Node]=new Me().fromArray(s.Matrix.a)}}return e}addGlobalSceneSettings(){if("GlobalSettings"in _t){if("AmbientColor"in _t.GlobalSettings){const e=_t.GlobalSettings.AmbientColor.value,t=e[0],i=e[1],s=e[2];if(t!==0||i!==0||s!==0){const a=new ue().setRGB(t,i,s,gt);Un.add(new mc(a,1))}}"UnitScaleFactor"in _t.GlobalSettings&&(Un.userData.unitScaleFactor=_t.GlobalSettings.UnitScaleFactor.value)}}}class XO{constructor(){this.negativeMaterialIndices=!1}parse(e){const t=new Map;if("Geometry"in _t.Objects){const i=_t.Objects.Geometry;for(const s in i){const a=Zt.get(parseInt(s)),r=this.parseGeometry(a,i[s],e);t.set(parseInt(s),r)}}return this.negativeMaterialIndices===!0&&console.warn("THREE.FBXLoader: The FBX file contains invalid (negative) material indices. The asset might not render as expected."),t}parseGeometry(e,t,i){switch(t.attrType){case"Mesh":return this.parseMeshGeometry(e,t,i);case"NurbsCurve":return this.parseNurbsGeometry(t)}}parseMeshGeometry(e,t,i){const s=i.skeletons,a=[],r=e.parents.map(function(d){return _t.Objects.Model[d.ID]});if(r.length===0)return;const o=e.children.reduce(function(d,h){return s[h.ID]!==void 0&&(d=s[h.ID]),d},null);e.children.forEach(function(d){i.morphTargets[d.ID]!==void 0&&a.push(i.morphTargets[d.ID])});const l=r[0],c={};"RotationOrder"in l&&(c.eulerOrder=Zl(l.RotationOrder.value)),"InheritType"in l&&(c.inheritType=parseInt(l.InheritType.value)),"GeometricTranslation"in l&&(c.translation=l.GeometricTranslation.value),"GeometricRotation"in l&&(c.rotation=l.GeometricRotation.value),"GeometricScaling"in l&&(c.scale=l.GeometricScaling.value);const u=RT(c);return this.genGeometry(t,o,a,u)}genGeometry(e,t,i,s){const a=new Ge;e.attrName&&(a.name=e.attrName);const r=this.parseGeoNode(e,t),o=this.genBuffers(r),l=new Ee(o.vertex,3);if(l.applyMatrix4(s),a.setAttribute("position",l),o.colors.length>0&&a.setAttribute("color",new Ee(o.colors,3)),t&&(a.setAttribute("skinIndex",new kh(o.weightsIndices,4)),a.setAttribute("skinWeight",new Ee(o.vertexWeights,4)),a.FBX_Deformer=t),o.normal.length>0){const c=new at().getNormalMatrix(s),u=new Ee(o.normal,3);u.applyNormalMatrix(c),a.setAttribute("normal",u)}if(o.uvs.forEach(function(c,u){const d=u===0?"uv":`uv${u}`;a.setAttribute(d,new Ee(o.uvs[u],2))}),r.material&&r.material.mappingType!=="AllSame"){let c=o.materialIndex[0],u=0;if(o.materialIndex.forEach(function(d,h){d!==c&&(a.addGroup(u,h-u,c),c=d,u=h)}),a.groups.length>0){const d=a.groups[a.groups.length-1],h=d.start+d.count;h!==o.materialIndex.length&&a.addGroup(h,o.materialIndex.length-h,c)}a.groups.length===0&&a.addGroup(0,o.materialIndex.length,o.materialIndex[0])}return this.addMorphTargets(a,e,i,s),a}parseGeoNode(e,t){const i={};if(i.vertexPositions=e.Vertices!==void 0?e.Vertices.a:[],i.vertexIndices=e.PolygonVertexIndex!==void 0?e.PolygonVertexIndex.a:[],e.LayerElementColor&&e.LayerElementColor[0].Colors&&(i.color=this.parseVertexColors(e.LayerElementColor[0])),e.LayerElementMaterial&&(i.material=this.parseMaterialIndices(e.LayerElementMaterial[0])),e.LayerElementNormal&&(i.normal=this.parseNormals(e.LayerElementNormal[0])),e.LayerElementUV){i.uv=[];let s=0;for(;e.LayerElementUV[s];)e.LayerElementUV[s].UV&&i.uv.push(this.parseUVs(e.LayerElementUV[s])),s++}return i.weightTable={},t!==null&&(i.skeleton=t,t.rawBones.forEach(function(s,a){s.indices.forEach(function(r,o){i.weightTable[r]===void 0&&(i.weightTable[r]=[]),i.weightTable[r].push({id:a,weight:s.weights[o]})})})),i}genBuffers(e){const t={vertex:[],normal:[],colors:[],uvs:[],materialIndex:[],vertexWeights:[],weightsIndices:[]};let i=0,s=0,a=!1,r=[],o=[],l=[],c=[],u=[],d=[];const h=this;return e.vertexIndices.forEach(function(f,p){let g,_=!1;f<0&&(f=f^-1,_=!0);let m=[],v=[];if(r.push(f*3,f*3+1,f*3+2),e.color){const y=pu(p,i,f,e.color);l.push(y[0],y[1],y[2])}if(e.skeleton){if(e.weightTable[f]!==void 0&&e.weightTable[f].forEach(function(y){v.push(y.weight),m.push(y.id)}),v.length>4){a||(console.warn("THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights."),a=!0);const y=[0,0,0,0],b=[0,0,0,0];v.forEach(function(T,x){let M=T,C=m[x];b.forEach(function(w,E,R){if(M>w){R[E]=M,M=w;const k=y[E];y[E]=C,C=k}})}),m=y,v=b}for(;v.length<4;)v.push(0),m.push(0);for(let y=0;y<4;++y)u.push(v[y]),d.push(m[y])}if(e.normal){const y=pu(p,i,f,e.normal);o.push(y[0],y[1],y[2])}e.material&&e.material.mappingType!=="AllSame"&&(g=pu(p,i,f,e.material)[0],g<0&&(h.negativeMaterialIndices=!0,g=0)),e.uv&&e.uv.forEach(function(y,b){const T=pu(p,i,f,y);c[b]===void 0&&(c[b]=[]),c[b].push(T[0]),c[b].push(T[1])}),s++,_&&(h.genFace(t,e,r,g,o,l,c,u,d,s),i++,s=0,r=[],o=[],l=[],c=[],u=[],d=[])}),t}getNormalNewell(e){const t=new S(0,0,0);for(let i=0;i.5?new S(0,1,0):new S(0,0,1)).cross(t).normalize(),a=t.clone().cross(s).normalize();return{normal:t,tangent:s,bitangent:a}}flattenVertex(e,t,i){return new te(e.dot(t),e.dot(i))}genFace(e,t,i,s,a,r,o,l,c,u){let d;if(u>3){const h=[],f=t.baseVertexPositions||t.vertexPositions;for(let m=0;m1&&console.warn("THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.");const r=e.get(a[0].ID);i[s]={name:t[s].attrName,layer:r}}return i}addClip(e){let t=[];const i=this;return e.layer.forEach(function(s){t=t.concat(i.generateTracks(s))}),new da(e.name,-1,t)}generateTracks(e){const t=[];let i=new S,s=new S;if(e.transform&&e.transform.decompose(i,new dt,s),i=i.toArray(),s=s.toArray(),e.T!==void 0&&Object.keys(e.T.curves).length>0){const a=this.generateVectorTrack(e.modelName,e.T.curves,i,"position");a!==void 0&&t.push(a)}if(e.R!==void 0&&Object.keys(e.R.curves).length>0){const a=this.generateRotationTrack(e.modelName,e.R.curves,e.preRotation,e.postRotation,e.eulerOrder);a!==void 0&&t.push(a)}if(e.S!==void 0&&Object.keys(e.S.curves).length>0){const a=this.generateVectorTrack(e.modelName,e.S.curves,s,"scale");a!==void 0&&t.push(a)}if(e.DeformPercent!==void 0){const a=this.generateMorphTrack(e);a!==void 0&&t.push(a)}return t}generateVectorTrack(e,t,i,s){const a=this.getTimesForAllAxes(t),r=this.getKeyframeTrackValues(a,t,i);return new Hs(e+"."+s,a,r)}generateRotationTrack(e,t,i,s,a){let r,o;if(t.x!==void 0&&t.y!==void 0&&t.z!==void 0){const h=this.interpolateRotations(t.x,t.y,t.z,a);r=h[0],o=h[1]}const l=Zl(0);i!==void 0&&(i=i.map(vt.degToRad),i.push(l),i=new an().fromArray(i),i=new dt().setFromEuler(i)),s!==void 0&&(s=s.map(vt.degToRad),s.push(l),s=new an().fromArray(s),s=new dt().setFromEuler(s).invert());const c=new dt,u=new an,d=[];if(!o||!r)return new _s(e+".quaternion",[0],[0]);for(let h=0;h2&&new dt().fromArray(d,(h-3)/3*4).dot(c)<0&&c.set(-c.x,-c.y,-c.z,-c.w),c.toArray(d,h/3*4);return new _s(e+".quaternion",r,d)}generateMorphTrack(e){const t=e.DeformPercent.curves.morph,i=t.values.map(function(a){return a/100}),s=Un.getObjectByName(e.modelName).morphTargetDictionary[e.morphName];return new ua(e.modelName+".morphTargetInfluences["+s+"]",t.times,i)}getTimesForAllAxes(e){let t=[];if(e.x!==void 0&&(t=t.concat(e.x.times)),e.y!==void 0&&(t=t.concat(e.y.times)),e.z!==void 0&&(t=t.concat(e.z.times)),t=t.sort(function(i,s){return i-s}),t.length>1){let i=1,s=t[0];for(let a=1;a=180||f[1]>=180||f[2]>=180){const g=Math.max(...f)/180,_=new an(...c,s),m=new an(...d,s),v=new dt().setFromEuler(_),y=new dt().setFromEuler(m);v.dot(y)&&y.set(-y.x,-y.y,-y.z,-y.w);const b=e.times[o-1],T=e.times[o]-b,x=new dt,M=new an;for(let C=0;C<1;C+=1/g)x.copy(v.clone().slerp(y.clone(),C)),a.push(b+C*T),M.setFromQuaternion(x,s),r.push(M.x),r.push(M.y),r.push(M.z)}else a.push(e.times[o]),r.push(vt.degToRad(e.values[o])),r.push(vt.degToRad(t.values[o])),r.push(vt.degToRad(i.values[o]))}return[a,r]}}class qO{getPrevNode(){return this.nodeStack[this.currentIndent-2]}getCurrentNode(){return this.nodeStack[this.currentIndent-1]}getCurrentProp(){return this.currentProp}pushStack(e){this.nodeStack.push(e),this.currentIndent+=1}popStack(){this.nodeStack.pop(),this.currentIndent-=1}setCurrentProp(e,t){this.currentProp=e,this.currentPropName=t}parse(e){this.currentIndent=0,this.allNodes=new AT,this.nodeStack=[],this.currentProp=[],this.currentPropName="";const t=this,i=e.split(/[\r\n]+/);return i.forEach(function(s,a){const r=s.match(/^[\s\t]*;/),o=s.match(/^[\s\t]*$/);if(r||o)return;const l=s.match("^\\t{"+t.currentIndent+"}(\\w+):(.*){",""),c=s.match("^\\t{"+t.currentIndent+"}(\\w+):[\\s\\t\\r\\n](.*)"),u=s.match("^\\t{"+(t.currentIndent-1)+"}}");l?t.parseNodeBegin(s,l):c?t.parseNodeProperty(s,c,i[++a]):u?t.popStack():s.match(/^[^\s\t}]/)&&t.parseNodePropertyContinued(s)}),this.allNodes}parseNodeBegin(e,t){const i=t[1].trim().replace(/^"/,"").replace(/"$/,""),s=t[2].split(",").map(function(l){return l.trim().replace(/^"/,"").replace(/"$/,"")}),a={name:i},r=this.parseNodeAttr(s),o=this.getCurrentNode();this.currentIndent===0?this.allNodes.add(i,a):i in o?(i==="PoseNode"?o.PoseNode.push(a):o[i].id!==void 0&&(o[i]={},o[i][o[i].id]=o[i]),r.id!==""&&(o[i][r.id]=a)):typeof r.id=="number"?(o[i]={},o[i][r.id]=a):i!=="Properties70"&&(i==="PoseNode"?o[i]=[a]:o[i]=a),typeof r.id=="number"&&(a.id=r.id),r.name!==""&&(a.attrName=r.name),r.type!==""&&(a.attrType=r.type),this.pushStack(a)}parseNodeAttr(e){let t=e[0];e[0]!==""&&(t=parseInt(e[0]),isNaN(t)&&(t=e[0]));let i="",s="";return e.length>1&&(i=e[1].replace(/^(\w+)::/,""),s=e[2]),{id:t,name:i,type:s}}parseNodeProperty(e,t,i){let s=t[1].replace(/^"/,"").replace(/"$/,"").trim(),a=t[2].replace(/^"/,"").replace(/"$/,"").trim();s==="Content"&&a===","&&(a=i.replace(/"/g,"").replace(/,$/,"").trim());const r=this.getCurrentNode();if(r.name==="Properties70"){this.parseNodeSpecialProperty(e,s,a);return}if(s==="C"){const l=a.split(",").slice(1),c=parseInt(l[0]),u=parseInt(l[1]);let d=a.split(",").slice(3);d=d.map(function(h){return h.trim().replace(/^"/,"")}),s="connections",a=[c,u],eF(a,d),r[s]===void 0&&(r[s]=[])}s==="Node"&&(r.id=a),s in r&&Array.isArray(r[s])?r[s].push(a):s!=="a"?r[s]=a:r.a=a,this.setCurrentProp(r,s),s==="a"&&a.slice(-1)!==","&&(r.a=bp(a))}parseNodePropertyContinued(e){const t=this.getCurrentNode();t.a+=e,e.slice(-1)!==","&&(t.a=bp(t.a))}parseNodeSpecialProperty(e,t,i){const s=i.split('",').map(function(u){return u.trim().replace(/^\"/,"").replace(/\s/,"_")}),a=s[0],r=s[1],o=s[2],l=s[3];let c=s[4];switch(r){case"int":case"enum":case"bool":case"ULongLong":case"double":case"Number":case"FieldOfView":c=parseFloat(c);break;case"Color":case"ColorRGB":case"Vector3D":case"Lcl_Translation":case"Lcl_Rotation":case"Lcl_Scaling":c=bp(c);break}this.getPrevNode()[a]={type:r,type2:o,flag:l,value:c},this.setCurrentProp(this.getPrevNode(),a)}}class YO{parse(e){const t=new av(e);t.skip(23);const i=t.getUint32();if(i<6400)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+i);const s=new AT;for(;!this.endOfContent(t);){const a=this.parseNode(t,i);a!==null&&s.add(a.name,a)}return s}endOfContent(e){return e.size()%16===0?(e.getOffset()+160+16&-16)>=e.size():e.getOffset()+160+16>=e.size()}parseNode(e,t){const i={},s=t>=7500?e.getUint64():e.getUint32(),a=t>=7500?e.getUint64():e.getUint32();t>=7500?e.getUint64():e.getUint32();const r=e.getUint8(),o=e.getString(r);if(s===0)return null;const l=[];for(let h=0;h0?l[0]:"",u=l.length>1?l[1]:"",d=l.length>2?l[2]:"";for(i.singleProperty=a===1&&e.getOffset()===s;s>e.getOffset();){const h=this.parseNode(e,t);h!==null&&this.parseSubNode(o,i,h)}return i.propertyList=l,typeof c=="number"&&(i.id=c),u!==""&&(i.attrName=u),d!==""&&(i.attrType=d),o!==""&&(i.name=o),i}parseSubNode(e,t,i){if(i.singleProperty===!0){const s=i.propertyList[0];Array.isArray(s)?(t[i.name]=i,i.a=s):t[i.name]=s}else if(e==="Connections"&&i.name==="C"){const s=[];i.propertyList.forEach(function(a,r){r!==0&&s.push(a)}),t.connections===void 0&&(t.connections=[]),t.connections.push(s)}else if(i.name==="Properties70")Object.keys(i).forEach(function(a){t[a]=i[a]});else if(e==="Properties70"&&i.name==="P"){let s=i.propertyList[0],a=i.propertyList[1];const r=i.propertyList[2],o=i.propertyList[3];let l;s.indexOf("Lcl ")===0&&(s=s.replace("Lcl ","Lcl_")),a.indexOf("Lcl ")===0&&(a=a.replace("Lcl ","Lcl_")),a==="Color"||a==="ColorRGB"||a==="Vector"||a==="Vector3D"||a.indexOf("Lcl_")===0?l=[i.propertyList[4],i.propertyList[5],i.propertyList[6]]:l=i.propertyList[4],t[s]={type:a,type2:r,flag:o,value:l}}else t[i.name]===void 0?typeof i.id=="number"?(t[i.name]={},t[i.name][i.id]=i):t[i.name]=i:i.name==="PoseNode"?(Array.isArray(t[i.name])||(t[i.name]=[t[i.name]]),t[i.name].push(i)):t[i.name][i.id]===void 0&&(t[i.name][i.id]=i)}parseProperty(e){const t=e.getString(1);let i;switch(t){case"C":return e.getBoolean();case"D":return e.getFloat64();case"F":return e.getFloat32();case"I":return e.getInt32();case"L":return e.getInt64();case"R":return i=e.getUint32(),e.getArrayBuffer(i);case"S":return i=e.getUint32(),e.getString(i);case"Y":return e.getInt16();case"b":case"c":case"d":case"f":case"i":case"l":const s=e.getUint32(),a=e.getUint32(),r=e.getUint32();if(a===0)switch(t){case"b":case"c":return e.getBooleanArray(s);case"d":return e.getFloat64Array(s);case"f":return e.getFloat32Array(s);case"i":return e.getInt32Array(s);case"l":return e.getInt64Array(s)}const o=kO(new Uint8Array(e.getArrayBuffer(r))),l=new av(o.buffer);switch(t){case"b":case"c":return l.getBooleanArray(s);case"d":return l.getFloat64Array(s);case"f":return l.getFloat32Array(s);case"i":return l.getInt32Array(s);case"l":return l.getInt64Array(s)}break;default:throw new Error("THREE.FBXLoader: Unknown property type "+t)}}}class av{constructor(e,t){this.dv=new DataView(e),this.offset=0,this.littleEndian=t!==void 0?t:!0,this._textDecoder=new TextDecoder}getOffset(){return this.offset}size(){return this.dv.buffer.byteLength}skip(e){this.offset+=e}getBoolean(){return(this.getUint8()&1)===1}getBooleanArray(e){const t=[];for(let i=0;i=0&&(i=new Uint8Array(this.dv.buffer,t,s)),this._textDecoder.decode(i)}}class AT{add(e,t){this[e]=t}}function jO(n){const e="Kaydara FBX Binary \0";return n.byteLength>=e.length&&e===PT(n,0,e.length)}function ZO(n){const e=["K","a","y","d","a","r","a","\\","F","B","X","\\","B","i","n","a","r","y","\\","\\"];let t=0;function i(s){const a=n[s-1];return n=n.slice(t+s),t++,a}for(let s=0;s(console.warn(`⚠️ Could not load texture ${u}:`,d.message),null))])}this._processModelMaterials(s,a,e,i.format);const o=this._calculateModelScale(s,e,i.scale);if(s.userData.scaleInfo=o,s.userData.format=i.format,i.wheelSockets){s.userData.wheelSockets=!0,s.userData.wheelModelName=i.wheelModel;const l=this._findWheelSockets(s);s.userData.wheelSocketObjects=l,console.log(`🔌 Found ${Object.keys(l).length} wheel sockets`)}return{model:s,chassisTexture:a,wheelModel:r}}_findWheelSockets(e){const t={},i=["Wheel_BL","Wheel_BR","Wheel_FL","Wheel_FR"];console.log("🔍 Searching for wheel sockets..."),e.traverse(s=>{const a=s.name,r=a.toLowerCase();for(const o of i)(a===o||r===o.toLowerCase())&&(t[o]=s,console.log(` Found socket: "${a}" at position (${s.position.x.toFixed(2)}, ${s.position.y.toFixed(2)}, ${s.position.z.toFixed(2)})`))});for(const s of i)t[s]||console.warn(` ⚠️ Missing wheel socket: ${s}`);return Object.keys(t).length===0&&(console.warn("⚠️ No wheel sockets found! Listing all objects:"),e.traverse(s=>{console.log(` - "${s.name}" (${s.type})`)})),t}_calculateModelScale(e,t,i=null){const s=new vn().setFromObject(e),a=new S;s.getSize(a),console.log(`📐 ${t.toUpperCase()} model dimensions (raw):`),console.log(` Size: X=${a.x.toFixed(2)}, Y=${a.y.toFixed(2)}, Z=${a.z.toFixed(2)}`),console.log(` Min Y: ${s.min.y.toFixed(2)}, Max Y: ${s.max.y.toFixed(2)}`);const r=this.HITBOX_DIMENSIONS[t]||this.HITBOX_DIMENSIONS.octane;let o;if(i!==null)o=i,console.log(` Using override scale: ${o}`);else{const l=a.z,u=r.length*1/l;o=u*.55,console.log(` Target RL: ${r.length} x ${r.width} x ${r.height} uu`),console.log(` Scale to RL: ${u.toFixed(4)}, Final scale: ${o.toFixed(6)}`)}return{scale:o}}_loadFBX(e){return new Promise((t,i)=>{this.fbxLoader.load(e,s=>t(s),void 0,s=>i(new Error(`Failed to load FBX: ${e} - ${s.message}`)))})}_loadGLB(e){return new Promise((t,i)=>{this.gltfLoader.load(e,s=>{t(s.scene)},void 0,s=>i(new Error(`Failed to load GLB: ${e} - ${s.message}`)))})}async loadWheelModel(e){const t=Si(`models/wheels/${e}`,this.assetBase);if(this.wheelModelCache.has(t))return this.wheelModelCache.get(t);if(this.wheelLoadingPromises.has(t))return this.wheelLoadingPromises.get(t);const i=this._loadGLB(t);this.wheelLoadingPromises.set(t,i);try{const s=await i;return console.log(`✓ Loaded wheel model: ${e}`),s.traverse(a=>{a.isMesh&&(a.castShadow=!0,a.receiveShadow=!0)}),this.wheelModelCache.set(t,s),s}catch(s){throw console.error(`Failed to load wheel model ${e}:`,s),s}finally{this.wheelLoadingPromises.delete(t)}}_loadTexture(e){return new Promise((t,i)=>{this.textureLoader.load(e,s=>{s.flipY=!1,s.colorSpace=gt,t(s)},void 0,s=>i(new Error(`Failed to load texture: ${e}`)))})}_processModelMaterials(e,t,i,s="fbx"){console.log(`📦 Processing materials for ${i} (${s}):`);const a=["body","paint"],r=[];e.traverse(o=>{o.isLight&&(r.push(o),console.log(` 🔦 Removing imported light: "${o.name||o.type}"`))}),r.forEach(o=>{o.parent&&o.parent.remove(o)}),e.traverse(o=>{o.isMesh&&(console.log(` Mesh: "${o.name}"`),(Array.isArray(o.material)?o.material:[o.material]).forEach((c,u)=>{console.log(` [${u}] Material: "${c.name}" - Color: #${c.color?.getHexString()||"none"}`);const d=(c.name||"").toLowerCase(),h=(o.name||"").toLowerCase(),f=a.some(p=>d.includes(p)||h.includes(p));if(s==="glb")(c.isMeshStandardMaterial||c.isMeshPhysicalMaterial)&&(console.log(` → GLB material (keeping as-is): metalness=${c.metalness?.toFixed(2)}, roughness=${c.roughness?.toFixed(2)}`),c.userData.originalColor=c.color?.clone(),c.userData.isBodyMaterial=f);else if(c.isMeshPhongMaterial||c.isMeshLambertMaterial||c.isMeshBasicMaterial){let p;f?(p=new Pn({color:c.color,map:c.map,metalness:.8,roughness:.15}),console.log(" → Body material: shiny metallic")):(p=new Pn({color:c.color,map:c.map,metalness:.1,roughness:.6}),console.log(" → Non-body material: matte")),p.name=c.name,Array.isArray(o.material)?o.material[u]=p:o.material=p}}))}),t?console.log(` ✓ Chassis texture loaded for ${i}`):s==="fbx"&&console.log(` ⚠️ No chassis texture for ${i}`)}getModelTypeForCar(e,t){return e&&this.carNameToModel[e]?this.carNameToModel[e]:this.hitboxToModel[t]||"octane"}getModelTypeForHitbox(e){return this.hitboxToModel[e]||"octane"}async createCarMesh(e,t=0){const i=this.getModelTypeForHitbox(e);try{const s=await this.loadModel(i);if(!s||!s.model)return console.warn(`No cached model for ${i}`),null;const a=s.model.userData.format||"fbx";let r;a==="glb"?(r=xp(s.model),r.traverse(c=>{c.isMesh&&(Array.isArray(c.material)?c.material=c.material.map(u=>u.clone()):c.material&&(c.material=c.material.clone()))})):r=s.model.clone(),this.applyTeamColor(r,t);const o=new Mt,l=s.model.userData.scaleInfo;return l&&r.scale.setScalar(l.scale),o.add(r),r.traverse(c=>{c.isMesh&&(c.castShadow=!0)}),o.userData.modelType=i,o.userData.hitboxType=e,o.userData.team=t,o.userData.isFBXModel=a==="fbx",o.userData.isGLBModel=a==="glb",o}catch(s){return console.error(`Failed to create car mesh for ${e}:`,s),null}}applyTeamColor(e,t){const i=t===0?this.TEAM_COLORS.blue:this.TEAM_COLORS.orange,s=["body","paint"];let a=!1;console.log("🔍 Analyzing car meshes for team coloring:"),e.traverse(r=>{if(r.isMesh){const o=Array.isArray(r.material)?r.material:[r.material];console.log(` Mesh: "${r.name}" with ${o.length} material(s)`),o.forEach((l,c)=>{console.log(` [${c}] Material: "${l.name}", isBodyMaterial: ${l.userData?.isBodyMaterial}`)})}}),e.traverse(r=>{r.isMesh&&(Array.isArray(r.material)?r.material:[r.material]).forEach((l,c)=>{const u=(l.name||"").toLowerCase(),d=(r.name||"").toLowerCase(),h=l.userData?.isBodyMaterial||s.some(f=>u.includes(f)||d.includes(f));if(console.log(` Checking "${l.name}" on "${r.name}": isBody=${h}`),h){a=!0;const f=l.clone();f.color=i.clone(),f.metalness=.39,f.roughness=.47,f.userData={...l.userData},Array.isArray(r.material)?r.material[c]=f:r.material=f,console.log(`🎨 Applied team color to: "${l.name}" on mesh "${r.name}" (index ${c})`)}})}),a||console.warn("⚠️ No body material found for team coloring! Check material names.")}updateTeamColor(e,t){this.applyTeamColor(e,t)}isModelReady(e,t){const i=this.getModelTypeForCar(e,t);return this.modelCache.has(this.modelCacheKey(i))}getCarMeshSync(e,t,i=0){const s=this.getModelTypeForCar(e,t),a=this.modelCache.get(this.modelCacheKey(s));if(!a||!a.model)return null;const r=a.model.userData.format||"fbx",o=a.model.userData.wheelSockets;let l;r==="glb"?(l=xp(a.model),l.traverse(d=>{d.isMesh&&(Array.isArray(d.material)?d.material=d.material.map(h=>h.clone()):d.material&&(d.material=d.material.clone()))})):l=a.model.clone(),this.applyTeamColor(l,i);const c=new Mt,u=a.model.userData.scaleInfo;return u&&l.scale.setScalar(u.scale),c.add(l),l.traverse(d=>{d.isMesh&&(d.castShadow=!0)}),c.userData.modelType=s,c.userData.carName=e,c.userData.hitboxType=t,c.userData.team=i,c.userData.isFBXModel=r==="fbx",c.userData.isGLBModel=r==="glb",c.userData.hasWheelSockets=o,o?c.userData.wheels=this._attachWheelsToSockets(l,a.wheelModel):c.userData.wheels=this._findWheelMeshes(l),c}_attachWheelsToSockets(e,t){const i=[],s={Wheel_FL:{side:"left",position:"front"},Wheel_FR:{side:"right",position:"front"},Wheel_BL:{side:"left",position:"rear"},Wheel_BR:{side:"right",position:"rear"}};if(!t)return console.warn("⚠️ No wheel model template available for socket attachment"),i;console.log("🔧 Attaching wheels to sockets...");const a={};e.traverse(r=>{const o=r.name;s[o]&&(a[o]=r)});for(const[r,o]of Object.entries(s)){const l=a[r];if(!l){console.warn(` ⚠️ Socket not found: ${r}`);continue}const c=xp(t);c.traverse(u=>{u.isMesh&&(Array.isArray(u.material)?u.material=u.material.map(d=>d.clone()):u.material&&(u.material=u.material.clone()),u.castShadow=!0)}),c.position.set(0,0,0),c.rotation.set(0,0,0),l.add(c),console.log(` ✓ Attached wheel to ${r} (${o.position} ${o.side})`),i.push({mesh:c,steeringPivot:o.position==="front"?l:null,side:o.side,position:o.position,socket:l})}return console.log(`✓ Attached ${i.length} wheels to sockets`),i}_findWheelMeshes(e){const t=[],i={fl:{side:"left",position:"front"},fr:{side:"right",position:"front"},rl:{side:"left",position:"rear"},rr:{side:"right",position:"rear"}};console.log("🔍 Searching for wheels in model...");const s={};e.traverse(a=>{const o=a.name.toLowerCase().match(/^wheel_(fl|fr|rl|rr)_(y|z)$/);if(o){const l=o[1],c=o[2];s[l]||(s[l]={}),s[l][c]=a,console.log(` Found: "${a.name}" (${c==="y"?"wheel mesh":"steering pivot"})`)}});for(const[a,r]of Object.entries(s)){const o=i[a];if(!o)continue;const l=r.y,c=r.z;l&&(a==="fr"&&(l.rotation.z+=Math.PI,console.log(" Fixed FR wheel orientation (rotation.z += PI)")),t.push({mesh:l,steeringPivot:o.position==="front"?c:null,side:o.side,position:o.position}),console.log(`🛞 Wheel ${a.toUpperCase()}: mesh="${l.name}"${c&&o.position==="front"?`, steering="${c.name}"`:""}`))}return t.length===0?(console.warn("⚠️ No wheel meshes found. Expected: Wheel_FL_Y, Wheel_FR_Y, etc."),console.warn(" Listing all objects in model:"),e.traverse(a=>{console.log(` - "${a.name}" (${a.type})`)})):console.log(`✓ Found ${t.length} wheels`),t}dispose(){}}const oF=2,wp=new Map;function lF(n){const e=Si("models/ball/scene.gltf",n);let t=wp.get(e);if(!t){const i=new Og;t=new Promise(s=>{i.load(e,a=>{console.log("✓ Ball model loaded"),s(a.scene)},void 0,a=>{console.error("Failed to load ball model:",a),wp.delete(e),s(null)})}),wp.set(e,t)}return t}class cF{constructor(e,t,i={}){this.scene=e,this.effectsManager=t,this.assetBase=i.assetBase,this.actors={},this.ballActorId=null,this.ballIndicator=null,this.ballVerticalLine=null,this.playerNames=new Set,this.actorToPlayer={},this.actorLinks={},this.playerNameToCarActorId={},this.playerNameToPriActorId={},this.playerTeams={},this.actorLoadouts={},this.carBodyIds={},this.carModelLoader=new rF({assetBase:this.assetBase}),this.pendingCarReplacements=new Map,this._lastGoalScanTime=null,this._firedGoalTimes=new Set,this._p0=new S,this._p1=new S,this._v0=new S,this._v1=new S,this._nextRot=new dt,this._q0=new dt,this._q1=new dt,this._qResult=new dt,this.onPlayerFound=null,this.lastBallTouchTeam=0,this.BALL_TOUCH_DISTANCE=200,this.ballTimeline=[],this.playerTimelineMap={},this.timelineIndices={ball:0,players:{}},this.interpolantsInitialized=!1,this.animationMixer=null,this.animationActions={},this.animationClock=new Eg(!1),this.replayDuration=0,this.useAnimationSystem=!1,this.SMOOTHING_WINDOW=5,this.positionBuffers={},this.rotationBuffers={},this.interpolationEnabled=!0,this.interpolationMethod="lerp",this.smoothingWindowSize=12,this.lastFrameInfo=null,this._lowPassState=new Map,this._lowPassAlpha=.3,this._predictState=new Map,this._predictCorrectionTime=.1,this._smoothingBuffers=new Map,this._adaptiveState=new Map,this.ballModel=null,this._ballModelReplaced=!1,this.ballModelReady=lF(this.assetBase).then(s=>(this.ballModel=s,s!==null))}async waitForBallModel(){const e=await this.ballModelReady;return e&&!this._ballModelReplaced&&this.ballActorId&&this.actors[this.ballActorId]&&(this.replaceBallWithModel(this.ballActorId),this._ballModelReplaced=!0),e}replaceBallWithModel(e){const t=this.actors[e];if(!t||!this.ballModel)return;const i=this.ballModel.clone();i.userData=t.userData,i.position.copy(t.position),i.quaternion.copy(t.quaternion),i.scale.copy(t.scale);const s=92.75;i.scale.set(s,s,s),i.traverse(a=>{a.isMesh&&(a.castShadow=!0,a.receiveShadow=!0)}),this.scene.remove(t),this.scene.add(i),t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose(),this.actors[e]=i,console.log("✓ Ball replaced with GLTF model")}reset(){Object.values(this.actors).forEach(e=>{this.scene.remove(e),e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()}),this.actors={},this.ballActorId=null,this.ballIndicator&&(this.scene.remove(this.ballIndicator),this.ballIndicator.geometry&&this.ballIndicator.geometry.dispose(),this.ballIndicator.material&&this.ballIndicator.material.dispose(),this.ballIndicator=null),this.ballVerticalLine&&(this.scene.remove(this.ballVerticalLine),this.ballVerticalLine.geometry&&this.ballVerticalLine.geometry.dispose(),this.ballVerticalLine.material&&this.ballVerticalLine.material.dispose(),this.ballVerticalLine=null),this.actorToPlayer={},this.actorLinks={},this.playerNames.clear(),this.playerNameToCarActorId={},this.playerNameToPriActorId={},this.playerTeams={},this.actorLoadouts={},this.carBodyIds={},this.pendingCarReplacements.clear(),this._lastGoalScanTime=null,this._firedGoalTimes.clear(),this.ballTimeline=[],this.playerTimelineMap={},this.ballTimelineCorrected=[],this.playerTimelineMapCorrected={},this.ballTimelineFiltered=[],this.playerTimelineMapFiltered={},this.timelineIndices={ball:0,players:{}},this.timelineIndicesFiltered={ball:0,players:{}},this.timelineIndicesCorrected={ball:0,players:{}},this.interpolantsInitialized=!1,this.animationMixer?.stopAllAction?.(),this.animationMixer=null,this.animationActions={},this.replayDuration=0,this.positionBuffers={},this.rotationBuffers={},this._lowPassState.clear(),this._predictState.clear(),this._smoothingBuffers.clear(),this._adaptiveState.clear(),this._ballModelReplaced=!1}resetGoalExplosionPlaybackState(){this._lastGoalScanTime=null,this._firedGoalTimes.clear()}setPlayerTeams(e){this.playerTeams=e}initFromFramework(e){console.log("[ActorManager] Initializing actors from framework..."),this._createBallMesh();const t=e.playerList;t.forEach((i,s)=>{this._createCarMesh(i.name,i.team,s,i.carName,i.hitboxType);const a=this.playerNameToCarActorId[i.name];this.actors[a]}),console.log(`[ActorManager] Created ${t.length} car meshes + 1 ball`)}initInterpolants(e){console.log("[ActorManager] Initializing interpolation system..."),this.ballTimeline=e.ballTimeline||[],this.playerTimelineMap=e.playerTimelines||{},this.ballTimelineCorrected=this._correctTimeShiftedPositions(this.ballTimeline),this.playerTimelineMapCorrected={},Object.entries(this.playerTimelineMap).forEach(([s,a])=>{this.playerTimelineMapCorrected[s]=this._correctTimeShiftedPositions(a)}),this.ballTimelineFiltered=this._filterBadFrames(this.ballTimeline),this.playerTimelineMapFiltered={},Object.entries(this.playerTimelineMap).forEach(([s,a])=>{this.playerTimelineMapFiltered[s]=this._filterBadFrames(a)}),this.timelineIndices={ball:0,players:{}},this.timelineIndicesFiltered={ball:0,players:{}},this.timelineIndicesCorrected={ball:0,players:{}},Object.keys(this.playerTimelineMap).forEach(s=>{this.timelineIndices.players[s]=0,this.timelineIndicesFiltered.players[s]=0,this.timelineIndicesCorrected.players[s]=0}),this.ballTimeline.length>0&&(this.replayDuration=this.ballTimeline[this.ballTimeline.length-1].time),this.useAnimationSystem&&this._initAnimationSystem(),this.interpolantsInitialized=!0;const t=this.ballTimeline.length-this.ballTimelineFiltered.length,i=this.ballTimelineCorrected._correctedCount||0;console.log(` Ball: ${this.ballTimeline.length} keyframes (${i} corrected, ${t} filtered)`),Object.entries(this.playerTimelineMap).forEach(([s,a])=>{const r=this.playerTimelineMapCorrected[s]?._correctedCount||0;console.log(` ${s}: ${a.length} keyframes (${r} corrected)`)}),console.log(` Replay duration: ${this.replayDuration.toFixed(2)}s`),console.log("[ActorManager] Animation system ready")}_initAnimationSystem(){console.log("[ActorManager] Building Three.js animation clips..."),this.animationMixer=new oT(this.scene);const e=this.actors[this.ballActorId];if(e&&this.ballTimeline.length>0){const t=this._createAnimationClip("ball",this.ballTimeline,e);if(t){const i=this.animationMixer.clipAction(t,e);i.setLoop(Jd),i.clampWhenFinished=!0,this.animationActions.ball=i,console.log(` ✓ Ball animation: ${t.duration.toFixed(2)}s`)}}Object.entries(this.playerTimelineMap).forEach(([t,i])=>{const s=this.playerNameToCarActorId[t],a=this.actors[s];if(a&&i.length>0){const r=this._createAnimationClip(t,i,a);if(r){const o=this.animationMixer.clipAction(r,a);o.setLoop(Jd),o.clampWhenFinished=!0,this.animationActions[t]=o,console.log(` ✓ ${t} animation: ${r.duration.toFixed(2)}s`)}}}),console.log("[ActorManager] Animation clips ready")}_createAnimationClip(e,t,i){if(!t||t.length<2)return null;const s=[],a=[],r=[],o=t[0];o.time>0&&(s.push(0),o.position?a.push(o.position.x,o.position.y,o.position.z):a.push(0,0,0),o.rotation?r.push(o.rotation.x,o.rotation.y,o.rotation.z,o.rotation.w):r.push(0,0,0,1));for(const h of t){if(s.push(h.time),h.position)a.push(h.position.x,h.position.y,h.position.z);else{const f=a.length-3;f>=0?a.push(a[f],a[f+1],a[f+2]):a.push(0,0,0)}if(h.rotation)r.push(h.rotation.x,h.rotation.y,h.rotation.z,h.rotation.w);else{const f=r.length-4;f>=0?r.push(r[f],r[f+1],r[f+2],r[f+3]):r.push(0,0,0,1)}}const l=new Hs(".position",s,a,or),c=new _s(".quaternion",s,r),u=s[s.length-1]-s[0];return new da(e,u,[l,c])}startAnimations(){this.animationMixer&&(Object.values(this.animationActions).forEach(e=>{e.reset(),e.play()}),this.animationClock.start(),console.log("[ActorManager] Animations started"))}pauseAnimations(){this.animationMixer&&Object.values(this.animationActions).forEach(e=>{e.paused=!0})}resumeAnimations(){this.animationMixer&&Object.values(this.animationActions).forEach(e=>{e.paused=!1})}seekAnimations(e){this.animationMixer&&(Object.values(this.animationActions).forEach(t=>{t.time=e}),this.animationMixer.setTime(e))}updateAnimations(e){!this.animationMixer||!this.useAnimationSystem||this.animationMixer.update(e)}_subsampleTimeline(e){return!e||e.length<4?e:e.filter((t,i)=>i%2===0)}_getOrCreateSmoothingBuffer(e){return this.positionBuffers[e]||(this.positionBuffers[e]=[],this.rotationBuffers[e]=[]),{positions:this.positionBuffers[e],rotations:this.rotationBuffers[e]}}_smoothPosition(e,t){const i=this._getOrCreateSmoothingBuffer(e).positions;for(i.push({x:t.x,y:t.y,z:t.z});i.length>this.SMOOTHING_WINDOW;)i.shift();if(i.length===1)return t;let s=0,a=0,r=0;for(const o of i)s+=o.x,a+=o.y,r+=o.z;return{x:s/i.length,y:a/i.length,z:r/i.length}}_smoothRotation(e,t){const i=this._getOrCreateSmoothingBuffer(e).rotations;for(i.push({x:t.x,y:t.y,z:t.z,w:t.w});i.length>this.SMOOTHING_WINDOW;)i.shift();if(i.length<3)return t;const s=Math.floor(i.length/2);return i[s]}resetSmoothingBuffers(){this.positionBuffers={},this.rotationBuffers={},this._lowPassState.clear()}_findKeyframeIndex(e,t,i=0){if(!e||e.length===0)return-1;if(t<=e[0].time)return 0;if(t>=e[e.length-1].time)return e.length-2;let s=Math.max(0,Math.min(i,e.length-2));if(e[s].time<=t&&e[s+1].time>t)return s;if(s+2t)return s+1;let a=0,r=e.length-2;for(;a<=r;){const o=Math.floor((a+r)/2);if(e[o].time<=t&&e[o+1].time>t)return o;e[o].time>t?r=o-1:a=o+1}return Math.max(0,Math.min(a,e.length-2))}_applySmoothing(e,t){this._smoothingBuffers.has(e)||this._smoothingBuffers.set(e,[]);const i=this._smoothingBuffers.get(e);for(i.push({x:t.x,y:t.y,z:t.z});i.length>this.smoothingWindowSize;)i.shift();if(i.length===1)return t;let s=0,a=0,r=0;for(const o of i)s+=o.x,a+=o.y,r+=o.z;return{x:s/i.length,y:a/i.length,z:r/i.length}}_applyEmaSmoothing(e,t){const i=`ema-${e}`;if(!this._smoothingBuffers.has(i))return this._smoothingBuffers.set(i,{x:t.x,y:t.y,z:t.z}),t;const s=this._smoothingBuffers.get(i),a=Math.max(.05,Math.min(.5,1/this.smoothingWindowSize)),r={x:a*t.x+(1-a)*s.x,y:a*t.y+(1-a)*s.y,z:a*t.z+(1-a)*s.z};return this._smoothingBuffers.set(i,r),r}_applyDoubleEmaSmoothing(e,t){const i=`dema-${e}`;if(!this._smoothingBuffers.has(i))return this._smoothingBuffers.set(i,{level:{x:t.x,y:t.y,z:t.z},trend:{x:0,y:0,z:0}}),t;const s=this._smoothingBuffers.get(i),a=Math.max(.1,Math.min(.6,2/this.smoothingWindowSize)),r=a*.5,o={x:a*t.x+(1-a)*(s.level.x+s.trend.x),y:a*t.y+(1-a)*(s.level.y+s.trend.y),z:a*t.z+(1-a)*(s.level.z+s.trend.z)},l={x:r*(o.x-s.level.x)+(1-r)*s.trend.x,y:r*(o.y-s.level.y)+(1-r)*s.trend.y,z:r*(o.z-s.level.z)+(1-r)*s.trend.z};return s.level=o,s.trend=l,{x:o.x+l.x,y:o.y+l.y,z:o.z+l.z}}_applyWeightedSmoothing(e,t){const i=`wma-${e}`;this._smoothingBuffers.has(i)||this._smoothingBuffers.set(i,[]);const s=this._smoothingBuffers.get(i);for(s.push({x:t.x,y:t.y,z:t.z});s.length>this.smoothingWindowSize;)s.shift();if(s.length===1)return t;let a=0,r=0,o=0,l=0;for(let c=0;cthis.smoothingWindowSize;)s.shift();if(s.length===1)return t;const a=s.length/3;let r=0,o=0,l=0,c=0;for(let u=0;u.001&&(s.derivedVel={x:(t.x-s.lastPos.x)/a,y:(t.y-s.lastPos.y)/a,z:(t.z-s.lastPos.z)/a});const r=Math.sqrt(s.derivedVel.x**2+s.derivedVel.y**2+s.derivedVel.z**2),o=2,l=this.smoothingWindowSize,c=300,u=1500;let d;if(ru)d=o;else{const _=(r-c)/(u-c);d=Math.round(l-_*(l-o))}if(s.buffer.length>=2){const _=s.buffer[s.buffer.length-1],m=s.buffer[s.buffer.length-2],v={x:_.x-m.x,y:_.y-m.y,z:_.z-m.z},y={x:t.x-_.x,y:t.y-_.y,z:t.z-_.z},b=Math.sqrt(v.x**2+v.y**2+v.z**2),T=Math.sqrt(y.x**2+y.y**2+y.z**2);if(b>.1&&T>.1&&(v.x*y.x+v.y*y.y+v.z*y.z)/(b*T)<.5)for(;s.buffer.length>Math.max(2,d/2);)s.buffer.shift()}for(s.buffer.push({x:t.x,y:t.y,z:t.z});s.buffer.length>d;)s.buffer.shift();if(s.lastPos={x:t.x,y:t.y,z:t.z},s.lastTime=i,s.buffer.length===1)return t;let h=0,f=0,p=0,g=0;for(let _=0;_u+10&&(h.z=t.position.z+t.velocity.z*r-.5*c*r*r,h.zu+10&&(p.z=t.position.z+t.velocity.z*o-.5*c*o*o,p.z0&&o>0){const b=d*o;m>b*2&&(v=b*2/m)}const y=_*v+(1-v)*l;return{x:h.x+g.x*y,y:h.y+g.y*y,z:h.z+g.z*y}}_physicsTickInterpolate(e,t,i){const s=t.time-e.time,a=i-e.time,r=a/s;if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};const o=(e.velocity.x+t.velocity.x)/2,l=(e.velocity.y+t.velocity.y)/2,c=(e.velocity.z+t.velocity.z)/2,u=e.position.x+o*a,d=e.position.y+l*a,h=e.position.z+c*a,f=e.position.x+o*s,p=e.position.y+l*s,g=e.position.z+c*s,_=t.position.x-f,m=t.position.y-p,v=t.position.z-g;return{x:u+_*r,y:d+m*r,z:h+v*r}}_velocityOnlyInterpolate(e,t,i){const s=i-e.time,a=t.time-e.time,r=s/a;if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};const o=e.velocity.x+(t.velocity.x-e.velocity.x)*r/2,l=e.velocity.y+(t.velocity.y-e.velocity.y)*r/2,c=e.velocity.z+(t.velocity.z-e.velocity.z)*r/2;return{x:e.position.x+o*s,y:e.position.y+l*s,z:e.position.z+c*s}}_smartHybridInterpolate(e,t,i){const s=i-e.time,a=t.time-e.time,r=Math.max(0,Math.min(1,s/a));if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};const o=Math.sqrt(e.velocity.x**2+e.velocity.y**2+e.velocity.z**2),l=Math.sqrt(t.velocity.x**2+t.velocity.y**2+t.velocity.z**2);let c=1;o>10&&l>10&&(c=(e.velocity.x*t.velocity.x+e.velocity.y*t.velocity.y+e.velocity.z*t.velocity.z)/(o*l));const u=o>10?Math.abs(l-o)/o:0;if(c<.95||u>.1){const h=r*r*(3-2*r);return{x:e.position.x+(t.position.x-e.position.x)*h,y:e.position.y+(t.position.y-e.position.y)*h,z:e.position.z+(t.position.z-e.position.z)*h}}else{const h=(e.velocity.x+t.velocity.x)/2,f=(e.velocity.y+t.velocity.y)/2,p=(e.velocity.z+t.velocity.z)/2,g=e.position.x+h*s,_=e.position.y+f*s,m=e.position.z+p*s,v=e.position.x+h*a,y=e.position.y+f*a,b=e.position.z+p*a,T=t.position.x-v,x=t.position.y-y,M=t.position.z-b;return{x:g+T*r,y:_+x*r,z:m+M*r}}}_isBadFrame(e,t){if(!e.velocity||!t.velocity||!e.position||!t.position)return!1;const i=t.time-e.time;if(i<.001)return!1;const s=(e.velocity.x+t.velocity.x)/2,a=(e.velocity.y+t.velocity.y)/2,r=(e.velocity.z+t.velocity.z)/2,o=Math.sqrt(s**2+a**2+r**2);if(o<200)return!1;const l=t.position.x-e.position.x,c=t.position.y-e.position.y,u=t.position.z-e.position.z,d=Math.sqrt(l*l+c*c+u*u),h=o*i,f=d/h;return f<.6||f>1.4}_filterBadFrames(e){if(!e||e.length<2)return e;const t=[e[0]];for(let i=1;i0&&a.position&&a.velocity){const o=e[s-1];if(o.position&&o.velocity){const l=a.time-o.time;if(l>.001){const c=(o.velocity.x+a.velocity.x)/2,u=(o.velocity.y+a.velocity.y)/2,d=(o.velocity.z+a.velocity.z)/2,h=Math.sqrt(c**2+u**2+d**2);if(h>100){const f=a.position.x-o.position.x,p=a.position.y-o.position.y,g=a.position.z-o.position.z,_=Math.sqrt(f*f+p*p+g*g),m=h*l,v=_/m;let y=0;v>.15&&v<.35?y=l*.75:v>.4&&v<.6?y=l*.5:v>.65&&v<.85&&(y=l*.25),y>0&&(r.position.x+=a.velocity.x*y,r.position.y+=a.velocity.y*y,r.position.z+=a.velocity.z*y,i++)}}}}t.push(r)}return t._correctedCount=i,t}_timeShiftedInterpolate(e,t,i){const s=i-e.time,a=t.time-e.time,r=Math.max(0,Math.min(1,s/a));return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r}}_velocityAnchoredInterpolate(e,t,i,s,a,r){if(!t.velocity||!i.velocity){const m=(s-t.time)/(i.time-t.time);return{x:t.position.x+(i.position.x-t.position.x)*m,y:t.position.y+(i.position.y-t.position.y)*m,z:t.position.z+(i.position.z-t.position.z)*m}}this._velocityAnchorState||(this._velocityAnchorState=new Map);let o=this._velocityAnchorState.get(e);(!o||Math.abs(s-o.lastTime)>.5||r%10===0)&&(o={anchorPos:{...t.position},anchorTime:t.time,anchorIdx:r,lastTime:s},this._velocityAnchorState.set(e,o)),s-o.anchorTime;let u=o.anchorPos.x,d=o.anchorPos.y,h=o.anchorPos.z;const f=(t.velocity.x+i.velocity.x)/2,p=(t.velocity.y+i.velocity.y)/2,g=(t.velocity.z+i.velocity.z)/2,_=s-t.time;return o.anchorIdx===r?(u=o.anchorPos.x+f*_,d=o.anchorPos.y+p*_,h=o.anchorPos.z+g*_):(u=t.position.x+f*_,d=t.position.y+p*_,h=t.position.z+g*_),o.lastTime=s,{x:u,y:d,z:h}}_hermiteInterpolate(e,t,i){const s=t.time-e.time,a=i-e.time,r=Math.max(0,Math.min(1,a/s)),o={x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};if(!e.velocity||!t.velocity)return o;const l=r*r,c=l*r,u=2*c-3*l+1,d=c-2*l+r,h=-2*c+3*l,f=c-l,p={x:e.velocity.x*s,y:e.velocity.y*s,z:e.velocity.z*s},g={x:t.velocity.x*s,y:t.velocity.y*s,z:t.velocity.z*s},_={x:u*e.position.x+d*p.x+h*t.position.x+f*g.x,y:u*e.position.y+d*p.y+h*t.position.y+f*g.y,z:u*e.position.z+d*p.z+h*t.position.z+f*g.z},m=_.x-o.x,v=_.y-o.y,y=_.z-o.z,b=t.position.x-e.position.x,T=t.position.y-e.position.y,x=t.position.z-e.position.z;return m*m+v*v+y*y>b*b+T*T+x*x?o:_}_physicsSimInterpolate(e,t,i,s=!1){const a=t.time-e.time,r=i-e.time,o=Math.max(0,Math.min(1,r/a));if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*o,y:e.position.y+(t.position.y-e.position.y)*o,z:e.position.z+(t.position.z-e.position.z)*o};const l=-650,c=o*o,u=c*o,d=2*u-3*c+1,h=u-2*c+o,f=-2*u+3*c,p=u-c;let g=e.velocity.y*a,_=t.velocity.y*a;if(s){const m=.5*l*a*a;g+=m*.5,_+=m*.5}return{x:d*e.position.x+h*(e.velocity.x*a)+f*t.position.x+p*(t.velocity.x*a),y:d*e.position.y+h*g+f*t.position.y+p*_,z:d*e.position.z+h*(e.velocity.z*a)+f*t.position.z+p*(t.velocity.z*a)}}getBallPositionAt(e){if(!this.ballTimeline||this.ballTimeline.length<2)return null;const t=this.ballTimeline[0];if(e2e3)return s.sleeping?null:{...s.position};if(s.sleeping)return{...s.position};const d=(e-s.time)/r;let h;switch(this.interpolationMethod){case"catmull-rom":{const f=this.ballTimeline[Math.max(0,i-1)],p=this.ballTimeline[Math.min(this.ballTimeline.length-1,i+2)];f?.position&&p?.position?h=this._catmullRomInterpolate(f.position,s.position,a.position,p.position,d):h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}case"lerp-smooth":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applySmoothing("ball",h);break}case"lerp-ema":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyEmaSmoothing("ball",h);break}case"lerp-dema":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyDoubleEmaSmoothing("ball",h);break}case"lerp-wma":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyWeightedSmoothing("ball",h);break}case"lerp-gauss":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyGaussianSmoothing("ball",h);break}case"one-euro":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyOneEuroFilter("ball",h);break}case"predict-correct":{h=this._predictCorrectInterpolate("ball",s,a,e);break}case"velocity-smooth":{h=this._velocitySmoothInterpolate("ball",s,a,e,!0);break}case"physics-tick":{h=this._physicsTickInterpolate(s,a,e);break}case"hermite":{h=this._hermiteInterpolate(s,a,e);break}case"physics-sim":{const f=this.ballTimelineCorrected;if(f&&f.length>=2){const p=this._findKeyframeIndex(f,e,this.timelineIndicesCorrected.ball);this.timelineIndicesCorrected.ball=p;const g=f[p],_=f[p+1];if(g?.position&&_?.position){h=this._physicsSimInterpolate(g,_,e,!0);break}}h=this._physicsSimInterpolate(s,a,e,!0);break}case"velocity-only":{h=this._velocityOnlyInterpolate(s,a,e);break}case"smart-hybrid":{h=this._smartHybridInterpolate(s,a,e);break}case"time-shifted":{const f=this.ballTimelineFiltered;if(!f||f.length<2){h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}const p=this._findKeyframeIndex(f,e,this.timelineIndicesFiltered.ball);this.timelineIndicesFiltered.ball=p;const g=f[p],_=f[p+1];if(!g?.position||!_?.position){h=g?.position?{...g.position}:{...s.position};break}const m=_.time-g.time,v=m>0?Math.max(0,Math.min(1,(e-g.time)/m)):0;h={x:g.position.x+(_.position.x-g.position.x)*v,y:g.position.y+(_.position.y-g.position.y)*v,z:g.position.z+(_.position.z-g.position.z)*v};break}case"position-lerp":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}case"position-catmull":{const f=this.ballTimeline[Math.max(0,i-1)],p=this.ballTimeline[Math.min(this.ballTimeline.length-1,i+2)];f?.position&&p?.position?h=this._catmullRomInterpolate(f.position,s.position,a.position,p.position,d):h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}case"position-smooth":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyLowPassFilter("ball",h);break}case"adaptive-smooth":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyAdaptiveSmoothing("ball",h,e);break}default:{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}}return h}getBallRotationAt(e){if(!this.ballTimeline||this.ballTimeline.length<2)return null;const t=this.ballTimeline[0];if(e2e3)return{...s.rotation}}if(s.sleeping)return{...s.rotation};const o=(e-s.time)/r;return this._q0.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w),this._q1.set(a.rotation.x,a.rotation.y,a.rotation.z,a.rotation.w),this._qResult.slerpQuaternions(this._q0,this._q1,o),{x:this._qResult.x,y:this._qResult.y,z:this._qResult.z,w:this._qResult.w}}getPlayerPositionAt(e,t){const i=this.playerTimelineMap[e];if(!i||i.length<2)return null;const s=i[0];if(t=2){const h=this._findKeyframeIndex(d,t,this.timelineIndicesCorrected.players[e]||0);this.timelineIndicesCorrected.players[e]=h;const f=d[h],p=d[h+1];if(f?.position&&p?.position){u=this._physicsSimInterpolate(f,p,t,!1);break}}u=this._physicsSimInterpolate(r,o,t,!1);break}case"velocity-only":{u=this._velocityOnlyInterpolate(r,o,t);break}case"smart-hybrid":{u=this._smartHybridInterpolate(r,o,t);break}case"time-shifted":{const d=this.playerTimelineMapFiltered[e];if(!d||d.length<2){u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}const h=this._findKeyframeIndex(d,t,this.timelineIndicesFiltered.players[e]||0);this.timelineIndicesFiltered.players[e]=h;const f=d[h],p=d[h+1];if(!f?.position||!p?.position){u=f?.position?{...f.position}:{...r.position};break}const g=p.time-f.time,_=g>0?Math.max(0,Math.min(1,(t-f.time)/g)):0;u={x:f.position.x+(p.position.x-f.position.x)*_,y:f.position.y+(p.position.y-f.position.y)*_,z:f.position.z+(p.position.z-f.position.z)*_};break}case"position-lerp":{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}case"position-catmull":{const d=i[Math.max(0,a-1)],h=i[Math.min(i.length-1,a+2)];d?.position&&h?.position?u=this._catmullRomInterpolate(d.position,r.position,o.position,h.position,c):u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}case"position-smooth":{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c},u=this._applyLowPassFilter(`player-${e}`,u);break}case"adaptive-smooth":{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c},u=this._applyAdaptiveSmoothing(`player-${e}`,u,t);break}default:{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}}return u}getPlayerRotationAt(e,t){const i=this.playerTimelineMap[e];if(!i||i.length<2)return null;const s=i[0];if(t=2){const r=this.getBallPositionAt(t),o=this.getBallRotationAt(t);r?i.position.set(r.x,r.y,r.z):a=!1,o&&i.quaternion.set(o.x,o.y,o.z,o.w)}else i.position.set(s.position.x,s.position.y,s.position.z),i.quaternion.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w);if(i.userData.location.copy(i.position),i.userData.rotation.copy(i.quaternion),i.userData.velocity.set(s.velocity.x,s.velocity.y,s.velocity.z),s.angularVelocity&&i.userData.angularVelocity.set(s.angularVelocity.x,s.angularVelocity.y,s.angularVelocity.z),i.userData.sleeping=s.sleeping,i.visible=a&&s.visible!==!1&&!i.userData.isHiddenByGoal,this.ballIndicator&&(this.ballIndicator.position.set(i.position.x,2,i.position.z),this.ballIndicator.visible=i.visible),this.ballVerticalLine){const o=new Float32Array([i.position.x,2,i.position.z,i.position.x,i.position.y,i.position.z]);this.ballVerticalLine.geometry.setAttribute("position",new ot(o,3)),this.ballVerticalLine.geometry.attributes.position.needsUpdate=!0,this.ballVerticalLine.visible=i.visible}if(i.userData.velocity&&i.visible){let r=this.lastBallTouchTeam,o=this.BALL_TOUCH_DISTANCE;Object.keys(this.actors).forEach(l=>{const c=this.actors[l];if(c&&c.userData.isCar&&c.userData.playerId){const u=i.position.distanceTo(c.position);u{const a=this.playerNameToCarActorId[s.name];if(!a)return;const r=this.actors[a];if(!r)return;const o=s.name;if(!this.useAnimationSystem||!this.animationMixer)if(this.interpolantsInitialized&&this.playerTimelineMap[o]){const c=this.getPlayerPositionAt(o,t),u=this.getPlayerRotationAt(o,t);c&&r.position.set(c.x,c.y,c.z),u&&r.quaternion.set(u.x,u.y,u.z,u.w)}else r.position.set(s.position.x,s.position.y,s.position.z),r.quaternion.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w);r.userData.location.copy(r.position),r.userData.rotation.copy(r.quaternion),r.userData.velocity.set(s.velocity.x,s.velocity.y,s.velocity.z),r.userData.sleeping=s.sleeping,r.userData.steer=s.steer||0;const l=r.position.length()>.1;r.visible=s.isVisible&&l&&!r.userData.sleeping}),this._updateGoalExplosions(t)}_updateGoalExplosions(e){const t=this.effectsManager,i=t&&t.explosions?t.explosions.goalEvents:null;if(!(i instanceof Map)||i.size===0)return;const s=this._lastGoalScanTime;s!==null&&e=c&&e<=c+oF&&(r=!0,o=!0),s!==null&&s=c&&!this._firedGoalTimes.has(c)){this._firedGoalTimes.add(c);const d=this.getBallPositionAt(c)||a&&a.position||null;d&&this.effectsManager.triggerGoalExplosion(d,l.team)}}a&&(a.userData.isHiddenByGoal=r,r&&(a.visible=!1)),o||this.effectsManager.clearGoalExplosions?.(),this._lastGoalScanTime=e}processFrame(e,t,i,s){if(e){if(e.new_actors&&e.new_actors.forEach(a=>{if(!this.actors[a.actor_id]){const r=t(a.object_id),o=r&&r.includes("Ball"),l=r&&r.includes("Car");if(o||l){let c;o?c=new yn(92.75,16,16):c=new Ci(118,36,84);const u=new Pn({color:o?16777215:Math.random()*16777215}),d=new we(c,u);if(d.userData={location:new S,rotation:new dt,isCar:l,isBall:o,playerId:null,lastUpdateTime:e.time,bodyId:null,hasReceivedUpdate:!1},this.scene.add(d),this.actors[a.actor_id]=d,o){this.ballActorId=a.actor_id,this.ballModel&&this.replaceBallWithModel(a.actor_id);const h=92.75,f=new ni(h*.95,h,32),p=new Ye({color:16777215,side:ct});this.ballIndicator=new we(f,p),this.ballIndicator.rotation.x=-Math.PI/2,this.ballIndicator.visible=!1,this.scene.add(this.ballIndicator);const g=new Ge().setFromPoints([new S(0,0,0),new S(0,1,0)]),_=new Rt({color:16777215,opacity:.5,transparent:!0});this.ballVerticalLine=new In(g,_),this.ballVerticalLine.frustumCulled=!1,this.ballVerticalLine.visible=!1,this.scene.add(this.ballVerticalLine)}else l&&this.effectsManager.createBoostTrail(d,a.actor_id)}}}),e.deleted_actors&&e.deleted_actors.forEach(a=>{if(this.actors[a]){const r=this.actors[a];r.userData.isCar&&this.effectsManager.removeBoostTrail(a),this.scene.remove(r),r.geometry&&r.geometry.dispose(),r.material&&r.material.dispose(),delete this.actors[a],this.ballActorId===a&&(this.ballActorId=null,this.ballIndicator&&(this.scene.remove(this.ballIndicator),this.ballIndicator.geometry&&this.ballIndicator.geometry.dispose(),this.ballIndicator.material&&this.ballIndicator.material.dispose(),this.ballIndicator=null),this.ballVerticalLine&&(this.scene.remove(this.ballVerticalLine),this.ballVerticalLine.geometry&&this.ballVerticalLine.geometry.dispose(),this.ballVerticalLine.material&&this.ballVerticalLine.material.dispose(),this.ballVerticalLine=null))}}),e.updated_actors&&e.updated_actors.forEach(a=>{const r=this.actors[a.actor_id];a.attribute.TeamLoadout&&(this.actorLoadouts[a.actor_id]=a.attribute.TeamLoadout,r&&r.userData.isCar&&(r.userData.teamLoadout=a.attribute.TeamLoadout,this.resolveBodyId(r,a.actor_id)));const o=t(a.object_id),l=o&&(o.includes("PRI_TA")||o.includes("PlayerReplicationInfo"));if(a.attribute.String&&this.playerNames.has(a.attribute.String)){const c=a.attribute.String;this.actorToPlayer[a.actor_id]=c,l&&!this.playerNameToPriActorId[c]&&(this.playerNameToPriActorId[c]=a.actor_id,console.log(`[ActorManager] Mapped ${c} -> PRI Actor ${a.actor_id} (object: ${o})`)),this.checkCarPlayerLink(a.actor_id)}if(a.attribute.Reservation&&this.playerNames.has(a.attribute.Reservation.name)){const c=a.attribute.Reservation.name;this.actorToPlayer[a.actor_id]=c,l&&!this.playerNameToPriActorId[c]&&(this.playerNameToPriActorId[c]=a.actor_id,console.log(`[ActorManager] Mapped ${c} -> PRI Actor ${a.actor_id} (object: ${o})`)),this.checkCarPlayerLink(a.actor_id)}if(a.attribute.ActiveActor){const c=a.attribute.ActiveActor.actor;this.actorLinks[a.actor_id]||(this.actorLinks[a.actor_id]=new Set),this.actorLinks[a.actor_id].add(c),r&&r.userData.isCar&&this.checkCarPlayerLink(c,a.actor_id)}if(r&&a.attribute&&a.attribute.RigidBody){const c=a.attribute.RigidBody;if(c.location&&(r.userData.location.set(c.location.x,c.location.z,c.location.y),r.userData.lastUpdateTime=e.time,r.userData.hasReceivedUpdate=!0),c.linear_velocity&&(r.userData.velocity||(r.userData.velocity=new S),r.userData.velocity.set(c.linear_velocity.x,c.linear_velocity.z,c.linear_velocity.y)),c.rotation&&r.userData.rotation.set(c.rotation.x,c.rotation.z,c.rotation.y,-c.rotation.w),c.angular_velocity&&(r.userData.angularVelocity||(r.userData.angularVelocity=new S),r.userData.angularVelocity.set(c.angular_velocity.x,c.angular_velocity.z,c.angular_velocity.y)),c.sleeping!==void 0&&(r.userData.sleeping=c.sleeping,c.sleeping&&(r.userData.velocity&&r.userData.velocity.set(0,0,0),r.userData.angularVelocity&&r.userData.angularVelocity.set(0,0,0))),r.userData.isBall&&r.userData.isHiddenByGoal&&c.location){const u=c.location.x,d=c.location.y,h=c.location.z;Math.sqrt(u*u+d*d+h*h)<500&&(r.userData.isHiddenByGoal=!1)}}}),this.effectsManager.explosions.goalEvents.has(i)){const a=this.effectsManager.explosions.goalEvents.get(i),r=this.actors[this.ballActorId];r&&(s||(this.effectsManager.triggerGoalExplosion(r.position,a.team),console.log(`🎯 GOAL! Explosion at frame ${i} for team ${a.team} by ${a.playerName}`)),r.userData.isHiddenByGoal=!0)}if(this.effectsManager.explosions.demoEvents.has(i)){const a=this.effectsManager.explosions.demoEvents.get(i),r=this.actors[a.victimActorId];if(r){if(!s){const o=r.userData.playerId,l=o&&this.playerTeams&&this.playerTeams[o]||0;this.effectsManager.triggerDemoExplosion(r.position,l),console.log(`💥 DEMO! Explosion at frame ${i} for actor ${a.victimActorId}`)}r.userData.sleeping=!0}}}}resolveBodyId(e,t){if(!e||!e.userData.isCar||!e.userData.teamLoadout)return;let i=0;e.userData.playerId&&Object.prototype.hasOwnProperty.call(this.playerTeams,e.userData.playerId)&&(i=this.playerTeams[e.userData.playerId]);const s=e.userData.teamLoadout,a=i===1?s.orange?.body:s.blue?.body;a&&e.userData.bodyId!==a&&(e.userData.bodyId=a,this.updateCarHitbox(e,a,t))}updateCarHitbox(e,t,i){const s=Aw(t),a=s?.name||"Octane",r=s?.hitboxType||"Octane";this.replaceCarWithModel(i,e,a,r)}async replaceCarWithModel(e,t,i,s){if(this.carModelLoader.isModelReady(i,s))this._doCarReplacement(e,t,i,s);else{this.pendingCarReplacements.set(e,{oldMesh:t,carName:i,hitboxType:s});try{const a=this.carModelLoader.getModelTypeForCar(i,s);await this.carModelLoader.loadModel(a);const r=this.pendingCarReplacements.get(e);r&&this.actors[e]===r.oldMesh&&this._doCarReplacement(e,r.oldMesh,r.carName,r.hitboxType),this.pendingCarReplacements.delete(e)}catch(a){console.warn(`Failed to load model for ${i} (${s}):`,a),this.pendingCarReplacements.delete(e),t&&(t.visible=!0)}}}_doCarReplacement(e,t,i,s){let a=0;t.userData.playerId&&Object.prototype.hasOwnProperty.call(this.playerTeams,t.userData.playerId)?a=this.playerTeams[t.userData.playerId]:t.userData.team!==void 0&&(a=t.userData.team);const r=this.carModelLoader.getCarMeshSync(i,s,a);if(!r){console.warn(`Could not get car mesh for ${i} (${s})`);return}const o=r.userData.wheels;r.userData={...t.userData},r.userData.isFBXModel=!0,r.userData.carName=i,r.userData.hitboxType=s,r.userData.wheels=o,r.position.copy(t.position),r.quaternion.copy(t.quaternion),this.scene.remove(t),t.geometry&&t.geometry.dispose(),t.material&&(Array.isArray(t.material)?t.material.forEach(c=>c.dispose()):t.material.dispose()),this.scene.add(r),this.actors[e]=r,this.effectsManager.removeBoostTrail(e),this.effectsManager.createBoostTrail(r,e);const l=this.carModelLoader.getModelTypeForCar(i,s);console.log(`🚗 Replaced car ${e} with ${l.toUpperCase()} model (${i}, ${s} hitbox, team ${a===0?"blue":"orange"})`)}checkCarPlayerLink(e,t){const i=this.actorToPlayer[e],s=this.actorLoadouts[e];if(!(!i&&!s))if(t){const a=this.actors[t];a&&a.userData.isCar&&(this.onPlayerFound&&this.onPlayerFound(i),a.userData.playerId=i,this.playerNameToCarActorId[i]=t,s&&(a.userData.teamLoadout=s),this.resolveBodyId(a,t))}else this.actorLinks[e]&&this.actorLinks[e].forEach(a=>{this.checkCarPlayerLink(e,a)})}updateInterpolation(e,t,i){const s=t[i];if(s&&Object.keys(this.actors).forEach(a=>{const r=this.actors[a],o=r.userData.location,l=r.userData.rotation;if(!o||!l||!r.userData.hasReceivedUpdate)return;let c=null,u=0;for(let d=i+1;dp.actor_id==a&&p.attribute&&p.attribute.RigidBody);if(f){c=f,u=h.time;break}}}if(c){const d=r.userData.lastUpdateTime||s.time,h=u;if(h>d){const f=(e-d)/(h-d),p=Math.max(0,Math.min(1,f)),g=h-d||.033,_=c.attribute.RigidBody;if(_.location)if(this._p0.copy(o),this._p1.set(_.location.x,_.location.z,_.location.y),r.userData.sleeping)r.position.copy(o);else{const m=c.attribute.RigidBody;if(r.userData.velocity&&m.linear_velocity){const v=p,y=v*v,b=y*v;if(g>.5)r.position.lerpVectors(o,this._p1,p);else{this._v0.copy(r.userData.velocity).multiplyScalar(g),this._v1.set(m.linear_velocity.x,m.linear_velocity.z,m.linear_velocity.y).multiplyScalar(g);const T=2*b-3*y+1,x=b-2*y+v,M=-2*b+3*y,C=b-y;r.position.set(T*this._p0.x+x*this._v0.x+M*this._p1.x+C*this._v1.x,T*this._p0.y+x*this._v0.y+M*this._p1.y+C*this._v1.y,T*this._p0.z+x*this._v0.z+M*this._p1.z+C*this._v1.z)}}else r.position.lerpVectors(o,this._p1,p)}else r.position.copy(o);_.rotation?(this._nextRot.set(_.rotation.x,_.rotation.z,_.rotation.y,-_.rotation.w),r.quaternion.slerpQuaternions(l,this._nextRot,p)):r.quaternion.copy(l);return}}r.position.copy(o),r.quaternion.copy(l)}),Object.keys(this.actors).forEach(a=>{const r=this.actors[a];if(r&&r.userData.isCar){const l=r.position.length()>.1,c=r.userData.sleeping===!0;r.visible=l&&!c}}),this.ballActorId&&this.actors[this.ballActorId]){const a=this.actors[this.ballActorId];if(a.visible=!a.userData.isHiddenByGoal,this.ballIndicator&&(this.ballIndicator.position.set(a.position.x,2,a.position.z),this.ballIndicator.visible=a.visible),this.ballVerticalLine){const o=new Float32Array([a.position.x,2,a.position.z,a.position.x,a.position.y,a.position.z]);this.ballVerticalLine.geometry.setAttribute("position",new ot(o,3)),this.ballVerticalLine.geometry.attributes.position.needsUpdate=!0,this.ballVerticalLine.visible=a.visible}if(a.userData.velocity&&a.visible){let r=this.lastBallTouchTeam,o=this.BALL_TOUCH_DISTANCE;Object.keys(this.actors).forEach(l=>{const c=this.actors[l];if(c&&c.userData.isCar&&c.userData.playerId){const u=a.position.distanceTo(c.position);if(u{const s=this.actors[i];if(!s||!s.userData.isCar||!s.userData.isFBXModel&&!s.userData.hasWheelSockets||!s.userData.wheels||s.userData.wheels.length===0)return;const a=s.position;let r=this._previousCarPositions.get(i);r||(r=a.clone(),this._previousCarPositions.set(i,r));const l=new S().subVectors(a,r).length();if(this._previousCarPositions.set(i,a.clone()),l<.01)return;const d=Math.min(l/e,.5)*1;let h=0;s.userData.steer!==void 0&&(h=-s.userData.steer*t),s.userData.wheels.forEach(f=>{if(f.socket){const p=f.side==="left"?1:-1;if(f.mesh.rotateZ(p*d),f.position==="front"&&f.steeringPivot){const g=f.side==="left"?-1:1;f.steeringPivot.rotation.y=g*h}}else{const p=f.side==="left"?-1:1;f.mesh.rotateY(p*d),f.position==="front"&&f.steeringPivot&&(f.steeringPivot.rotation.z=h)}})})}resetWheelTracking(){this._previousCarPositions&&this._previousCarPositions.clear()}updateSupersonicState(e,t,i){const s=this.playerNameToCarActorId[e];if(!s)return;const a=this.actors[s];if(!a||!a.userData.isCar)return;const r=a.userData.velocity||new S(0,0,0);this.effectsManager.updateSupersonicTrail(s,t,a.position,a.quaternion,r,i)}setInterpolationEnabled(e){this.interpolationEnabled=e,console.log(`[ActorManager] Interpolation ${e?"enabled":"disabled"}`)}setInterpolationMethod(e){if(!["lerp","hermite","catmull-rom","predict-correct","velocity-smooth","physics-tick","velocity-only","smart-hybrid","time-shifted","lerp-smooth","lerp-ema","lerp-dema","lerp-wma","lerp-gauss","one-euro","position-lerp","position-catmull","position-smooth","adaptive-smooth"].includes(e)){console.warn(`[ActorManager] Invalid interpolation method: ${e}`);return}this.interpolationMethod=e,this._smoothingBuffers.clear(),this._lowPassState.clear(),this._adaptiveState.clear(),this.resetSmoothingBuffers(),console.log(`[ActorManager] Interpolation method set to: ${e}`)}setSmoothingWindowSize(e){this.smoothingWindowSize=Math.max(1,Math.min(20,e)),this._smoothingBuffers.clear(),console.log(`[ActorManager] Smoothing window size set to: ${this.smoothingWindowSize}`)}getInterpolationSettings(){return{enabled:this.interpolationEnabled,method:this.interpolationMethod,smoothingWindowSize:this.smoothingWindowSize}}clearSmoothingBuffers(){this._smoothingBuffers.clear()}getFrameInfo(){return this.lastFrameInfo}createBallMeshForLive(){const e=new yn(92.75,16,16),t=new Pn({color:16777215}),i=new we(e,t);if(i.castShadow=!0,i.receiveShadow=!0,i.userData={location:new S,rotation:new dt,velocity:new S,angularVelocity:new S,isCar:!1,isBall:!0,playerId:null,sleeping:!1,isHiddenByGoal:!1},this.scene.add(i),this.ballModel){const s=this.ballModel.clone();s.position.copy(i.position),s.quaternion.copy(i.quaternion),s.userData={...i.userData};const a=92.75;return s.scale.set(a,a,a),s.traverse(r=>{r.isMesh&&(r.castShadow=!0,r.receiveShadow=!0)}),this.scene.remove(i),this.scene.add(s),i.geometry&&i.geometry.dispose(),i.material&&i.material.dispose(),console.log("✓ Live ball created with GLTF model"),s}return i}createCarMeshForLive(e,t,i,s=null){const a=`live_car_${t}`,r=new Ci(118,36,84),o=e===0?3381759:16737792,l=new Pn({color:o}),c=new we(r,l);return c.castShadow=!0,c.receiveShadow=!0,c.visible=!1,c.userData={location:new S,rotation:new dt,velocity:new S,angularVelocity:new S,isCar:!0,isBall:!1,playerId:i,team:e,sleeping:!1,steer:0,bodyId:s,liveActorId:a},this.scene.add(c),this.actors[a]=c,this.playerNameToCarActorId[i]=a,this.effectsManager.createBoostTrail(c,a),s&&s>0?this.updateCarHitbox(c,s,a):this.replaceCarWithModel(a,c,"Octane","Octane"),console.log(`[ActorManager] Created live car for ${i} (team ${e===0?"blue":"orange"}, bodyId: ${s})`),c}updateBoostParticlesLive(e,t,i,s){const a=t&&i>0,r=s.userData.velocity||new S(0,0,0);this.effectsManager.updateBoostTrail(e,a,s.position,s.quaternion,r)}updateSupersonicTrailLive(e,t,i,s){const a=s.userData.velocity||new S(0,0,0);this.effectsManager.updateSupersonicTrail(e,t,s.position,s.quaternion,a,i)}removeLiveCar(e){const t=this.actors[e];t&&(this.scene.remove(t),t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose(),delete this.actors[e],this.effectsManager.removeBoostTrail(e))}removeLiveBall(e){e&&(this.scene.remove(e),e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose())}}function Ms(n,e,t){t===-1?(n.clearUpdateRanges?.(),n.addUpdateRange?.(0,n.count*n.itemSize)):n.addUpdateRange?(n.clearUpdateRanges(),n.addUpdateRange(e,t)):(n.updateRange.offset=e,n.updateRange.count=t)}class pt extends Qe{constructor(e,t){super(),this.active=!1,this.orientToMovement=!1,t&&(this.orientToMovement=!0),this.scene=e,this.geometry=null,this.mesh=null,this.nodeCenters=null,this.lastNodeCenter=null,this.currentNodeCenter=null,this.lastOrientationDir=null,this.nodeIDs=null,this.currentLength=0,this.currentEnd=0,this.currentNodeID=0,this.advanceFrequency=60,this.advancePeriod=1/this.advanceFrequency,this.lastAdvanceTime=0,this.paused=!1,this.pauseAdvanceUpdateTimeDiff=0,this._internalTime=0,this._useInternalTime=!1}setAdvanceFrequency(e){this.advanceFrequency=e,this.advancePeriod=1/this.advanceFrequency}initialize(e,t,i,s,a,r){this.deactivate(),this.destroyMesh(),this.length=t>0?t+1:0,this.dragTexture=i?1:0,this.targetObject=r,this.initializeLocalHeadGeometry(s,a),this.nodeIDs=[],this.nodeCenters=[];for(let o=0;o=this.length?0:this.currentEnd+1;if(i?this.updateNodePositionsFromTransformMatrix(s,i):this.updateNodePositionsFromOrientationTangent(s,t.position,t.tangent),this.currentLength>=1&&(this.connectNodes(this.currentEnd,s),this.currentLength>=this.length)){const a=this.currentEnd+1>=this.length?0:this.currentEnd+1;this.disconnectNodes(a)}this.currentLength=this.length&&(this.currentEnd=0),this.currentLength>=1&&(this.currentLengththis.advancePeriod?(this.advance(),this.lastAdvanceTime=t):this.updateHead()}}updateHead=(function(){const e=new Me;return function(){this.currentEnd<0||(this.targetObject.updateMatrixWorld(),e.copy(this.targetObject.matrixWorld),this.updateNodePositionsFromTransformMatrix(this.currentEnd,e))}})();updateNodeID(e,t){this.nodeIDs[e]=t;const i=this.geometry.getAttribute("nodeID"),s=this.geometry.getAttribute("nodeVertexID");for(let a=0;a1e-4)){this.lastOrientationDir||(this.lastOrientationDir=new S),t.setFromUnitVectors(a,r),s.copy(this.currentNodeCenter);for(let f=0;fe.add(a)),this.mainTrail=this._createMainTrail(),this.secondaryTrails=this._createSecondaryTrails(),this._updateColors(),this._updateIntensity(),this.mainTrail.activate(),this.secondaryTrails.forEach(a=>a.activate())}_createMainTrail(){const e=new pt(this.scene,!1),t=tv(),i=this.config.mainTrailWidth,s=[new S(0,-i,0),new S(0,i,0),new S(-i,0,0),new S(i,0,0),new S(0,0,-i),new S(0,0,i)];return e.initialize(t,this.config.trailLength,!1,0,s,this.mainTarget),e.setAdvanceFrequency(60),e.mesh&&(e.mesh.frustumCulled=!1,e.mesh.renderOrder=100),e}_createSecondaryTrails(){const e=[];for(let t=0;t<4;t++){const i=new pt(this.scene,!1),s=tv(),a=this.config.secondaryTrailWidth,r=[new S(0,-a,0),new S(0,a,0),new S(-a,0,0),new S(a,0,0),new S(0,0,-a),new S(0,0,a)];i.initialize(s,this.config.trailLength,!1,0,r,this.secondaryTargets[t]),i.setAdvanceFrequency(60),i.mesh&&(i.mesh.frustumCulled=!1,i.mesh.renderOrder=100),e.push(i)}return e}_updateColors(){const e=this.teamColors[this.team]||this.teamColors[0];this.mainTrail?.material&&(this.mainTrail.material.uniforms.headColor.value.copy(e.head),this.mainTrail.material.uniforms.tailColor.value.copy(e.tail));const t=e.head.clone();t.w=e.head.w*.85;const i=e.tail.clone();this.secondaryTrails.forEach(s=>{s?.material&&(s.material.uniforms.headColor.value.copy(t),s.material.uniforms.tailColor.value.copy(i))})}_updateIntensity(){this.mainTrail?.material&&(this.mainTrail.material.uniforms.intensityMultiplier.value=this.intensity),this.secondaryTrails.forEach(e=>{e?.material&&(e.material.uniforms.intensityMultiplier.value=this.intensity)})}setTeam(e){this.team!==e&&(this.team=e,this._updateColors())}setIntensity(e){this.intensity=e,this.dying||this._updateIntensity()}startDying(){this.dying||(this.dying=!0,this.deathTime=0,this.mainTrail.pause(),this.secondaryTrails.forEach(e=>e.pause()))}updatePosition(e,t,i){if(this.dying)return;const s=t.clone().normalize();this.mainTarget.position.copy(e),this.mainTarget.updateMatrixWorld();for(let a=0;a<4;a++){const o=a/4*Math.PI*2+i,l=new S(Math.cos(o)*this.config.secondaryTrailOffset,Math.sin(o)*this.config.secondaryTrailOffset,0);if(s.lengthSq()>.001){const c=new S(0,0,1),u=new dt;u.setFromUnitVectors(c,s),l.applyQuaternion(u)}this.secondaryTargets[a].position.copy(e).add(l),this.secondaryTargets[a].updateMatrixWorld()}}update(e){if(this.dying){this.deathTime+=e;const t=Math.min(1,this.deathTime/this.maxDeathTime),i=this.intensity*(1-t);this.mainTrail?.material&&(this.mainTrail.material.uniforms.intensityMultiplier.value=i),this.secondaryTrails.forEach(s=>{s?.material&&(s.material.uniforms.intensityMultiplier.value=i)}),this.deathTime>=this.maxDeathTime&&(this.active=!1)}this.mainTrail.isActive&&this.mainTrail.update(e),this.secondaryTrails.forEach(t=>{t.isActive&&t.update(e)})}dispose(){this.mainTrail.deactivate(),this.secondaryTrails.forEach(e=>e.deactivate()),this.mainTrail.geometry&&this.mainTrail.geometry.dispose(),this.mainTrail.material&&this.mainTrail.material.dispose(),this.secondaryTrails.forEach(e=>{e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()}),this.scene.remove(this.mainTarget),this.secondaryTargets.forEach(e=>this.scene.remove(e))}}class eF{constructor(e,t=0){this.scene=e,this.team=t,this.active=!1,this.ballRadius=92.75,this.config={trailLength:60,mainTrailWidth:15,secondaryTrailWidth:1.5,secondaryTrailOffset:this.ballRadius*.7},this.rotationSpeed=Math.PI/3,this.currentRotation=0,this.minVelocity=1500,this.maxVelocity=6e3,this.minIntensity=.3,this.maxIntensity=1,this.wasEmitting=!1,this.segments=[],this.currentSegment=null,this.currentIntensity=1}_calculateIntensity(e){if(e<=this.minVelocity)return this.minIntensity;if(e>=this.maxVelocity)return this.maxIntensity;const t=(e-this.minVelocity)/(this.maxVelocity-this.minVelocity);return this.minIntensity+t*(this.maxIntensity-this.minIntensity)}setTeam(e){this.team!==e&&(this.team=e,this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.startDying(),this.currentSegment=null))}activate(){this.active||(this.active=!0,this.currentSegment=null,this.wasEmitting=!1)}deactivate(){this.active&&(this.active=!1,this.currentSegment&&(this.currentSegment.startDying(),this.currentSegment=null))}emit(e,t,i){const s=t.length();if(!(s>=this.minVelocity)){this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.startDying(),this.currentSegment=null),this.wasEmitting=!1;return}this.currentIntensity=this._calculateIntensity(s),this.active||this.activate(),!this.wasEmitting||!this.currentSegment?(this.currentSegment&&!this.currentSegment.dying&&this.currentSegment.startDying(),this.currentSegment=new QO(this.scene,this.team,this.config,this.currentIntensity),this.segments.push(this.currentSegment)):this.currentSegment.setIntensity(this.currentIntensity),this.wasEmitting=!0,this.currentRotation+=this.rotationSpeed*i,this.currentRotation>Math.PI*2&&(this.currentRotation-=Math.PI*2),this.currentSegment.updatePosition(e,t,this.currentRotation)}update(e){for(let t=this.segments.length-1;t>=0;t--){const i=this.segments[t];i.update(e),i.active||(i.dispose(),this.segments.splice(t,1))}}reset(){for(const e of this.segments)e.dispose();this.segments=[],this.currentSegment=null,this.currentRotation=0,this.wasEmitting=!1}addToScene(e){}removeFromScene(e){for(const t of this.segments)t.startDying();this.currentSegment=null}dispose(){for(const e of this.segments)e.dispose();this.segments=[],this.currentSegment=null}}let du=null,hu=null,fu=null,nv=!1;function tF(){nv||(aF(),rF(),oF(),nv=!0)}let di=null;class nF{constructor(e,t,i,s=2){this.scene=e,this.renderer=t,this.camera=i,this.maxExplosions=s,this.explosions=[],this.warmedUp=!1,this.initPool()}initPool(){this.sphereGeo=new yn(1,16,12),this.coreGeo=new yn(1,12,8),this.ringGeo=new ni(.5,1,32),this.particleGeo=new Dn(1,1),this.coreMaterial=new Ye({color:16777130,transparent:!0,opacity:.9,blending:Ht,side:ct,depthWrite:!1}),this.sphereMaterial=new Ye({color:16737792,transparent:!0,opacity:.5,blending:Ht,side:ct,depthWrite:!1}),this.ringMaterial=new Ye({color:16746496,transparent:!0,opacity:.7,blending:Ht,side:ct,depthWrite:!1}),this.particleMaterial=new Ye({color:16763904,transparent:!0,opacity:.8,blending:Ht,side:ct,depthWrite:!1});for(let e=0;e!i.active);t||(t=this.explosions[0],this.resetExplosion(t)),t.active=!0,t.elapsed=0,t.position.copy(e),t.container.position.copy(e),t.container.visible=!0,t.core.scale.set(.1,.1,.1),t.coreMat.opacity=1,t.sphere.scale.set(.1,.1,.1),t.sphere.material.opacity=.6,t.ring.scale.set(.1,.1,.1),t.ring.material.opacity=.8,t.particleMat.opacity=.9,t.particles.forEach((i,s)=>{i.mesh.position.set(0,0,0);const a=s/12*Math.PI*2,r=(Math.random()-.3)*Math.PI,o=350+Math.random()*250;i.velocity.set(Math.cos(a)*Math.cos(r)*o,Math.sin(r)*o+100,Math.sin(a)*Math.cos(r)*o)})}resetExplosion(e){e.active=!1,e.container.visible=!1}update(e){for(const t of this.explosions){if(!t.active)continue;t.elapsed+=e;const i=t.elapsed/t.duration;if(i>=1){this.resetExplosion(t);continue}const s=30+i*80;t.core.scale.set(s,s,s),t.coreMat.opacity=1*Math.pow(1-i,2);const a=50+i*200;t.sphere.scale.set(a,a,a),t.sphere.material.opacity=.6*(1-i);const r=80+i*350;t.ring.scale.set(r,r,r),t.ring.material.opacity=.8*(1-i*i),t.particleMat.opacity=.9*(1-i);for(const o of t.particles)o.mesh.position.add(o.velocity.clone().multiplyScalar(e)),o.velocity.y-=300*e,this.camera&&o.mesh.lookAt(this.camera.position)}}dispose(){for(const e of this.explosions)this.scene.remove(e.container),e.coreMat.dispose(),e.sphere.material.dispose(),e.ring.material.dispose(),e.particleMat.dispose();this.coreGeo.dispose(),this.sphereGeo.dispose(),this.ringGeo.dispose(),this.particleGeo.dispose(),this.coreMaterial.dispose(),this.sphereMaterial.dispose(),this.ringMaterial.dispose(),this.particleMaterial.dispose()}}function TT(n,e=null,t=null){return di&&di.scene!==n&&(di.dispose?.(),di=null),di||(di=new nF(n,e,t)),e&&t&&!di.warmedUp&&(di.renderer=e,di.camera=t,di.warmup()),di}function iF(n,e,t){TT(n,e,t),MT(n,e,t)}let Bn=null;const iv={0:{core:6737151,sphere:35071,ring:43775,particles:8969727},1:{core:16768358,sphere:16737792,ring:16746496,particles:16755268}};class sF{constructor(e,t,i,s=2){this.scene=e,this.renderer=t,this.camera=i,this.maxExplosions=s,this.explosions=[],this.warmedUp=!1,this.initPool()}initPool(){this.coreGeo=new yn(1,16,12),this.sphereGeo=new yn(1,20,14),this.ringGeo=new ni(.3,1,48),this.particleGeo=new Dn(1,1),this.rayGeo=new Dn(1,1);for(let e=0;e!l.active);i||(i=this.explosions[0],this.resetExplosion(i));const s=i.materials[t]||i.materials[0];i.core.material=s.core,i.core2.material=s.core.clone(),i.core3.material=s.sphere.clone(),i.sphere.material=s.sphere;for(const l of i.rings)l.mesh.material=s.ring.clone();for(const l of i.rays)l.mesh.material=s.rays.clone();for(const l of i.particles)l.mesh.material=s.particles.clone();i.active=!0,i.elapsed=0,i.currentTeam=t,i.position.copy(e),i.container.position.copy(e),i.container.visible=!0,i.rotationOffset=0,i.core.scale.set(.1,.1,.1),i.core.material.opacity=1,i.core2.scale.set(.1,.1,.1),i.core2.material.opacity=.8,i.core3.scale.set(.1,.1,.1),i.core3.material.opacity=.5,i.sphere.scale.set(.1,.1,.1),i.sphere.material.opacity=.4;for(const l of i.rings)l.mesh.scale.set(.1,.1,.1),l.mesh.material.opacity=.9;for(let l=0;l=i.particles.length);d++){const h=i.particles[o];h.mesh.position.set(0,0,0),h.mesh.material.opacity=1;const f=h.initialScale;h.mesh.scale.set(f,f,f);const p=c+(Math.random()-.5)*.3,g=u+(Math.random()-.5)*.2,v=1800*(1-d/r*.5)+Math.random()*300;h.velocity.set(Math.cos(p)*Math.cos(g)*v,Math.sin(g)*v+300,Math.sin(p)*Math.cos(g)*v),h.delay=d*.02,o++}}for(;o=1){this.resetExplosion(t);continue}t.rotationOffset+=e*2;const s=this.easeOutElastic(Math.min(i*2,1)),a=this.easeOutExpo(i),r=this.easeOutBack(Math.min(i*1.5,1)),o=1+Math.sin(t.elapsed*15)*.15*(1-i),l=(150+s*300)*o;t.core.scale.set(l,l,l),t.core.material.opacity=1*Math.pow(1-i,1.2);const c=1+Math.sin(t.elapsed*12+1)*.12*(1-i),u=(200+r*400)*c;t.core2.scale.set(u,u,u),t.core2.material.opacity=.7*Math.pow(1-i,1.5);const d=300+a*600;t.core3.scale.set(d,d,d),t.core3.material.opacity=.4*Math.pow(1-i,2);const h=400+a*1200;t.sphere.scale.set(h,h,h),t.sphere.material.opacity=.3*(1-i*i);for(let g=0;g0){g.mesh.position.add(g.velocity.clone().multiplyScalar(e)),g.velocity.y-=600*e,g.velocity.multiplyScalar(.995);const m=Math.max(.3,1-i*.7),v=g.initialScale*m;g.mesh.scale.set(v,v,v)}g.mesh.material.opacity=1*Math.pow(1-i,1.2),this.camera&&g.mesh.lookAt(this.camera.position)}}}dispose(){for(const e of this.explosions){this.scene.remove(e.container);for(const t of Object.values(e.materials))t.core.dispose(),t.sphere.dispose(),t.ring.dispose(),t.particles.dispose(),t.rays.dispose()}this.coreGeo.dispose(),this.sphereGeo.dispose(),this.ringGeo.dispose(),this.particleGeo.dispose(),this.rayGeo.dispose()}}function MT(n,e=null,t=null){return Bn&&Bn.scene!==n&&(Bn.dispose?.(),Bn=null),Bn||(Bn=new sF(n,e,t)),e&&t&&!Bn.warmedUp&&(Bn.renderer=e,Bn.camera=t,Bn.warmup()),Bn}function aF(){if(du)return du;const n=document.createElement("canvas");n.width=64,n.height=64;const e=n.getContext("2d"),t=e.createRadialGradient(32,32,0,32,32,32);return t.addColorStop(0,"rgba(255,255,255,1)"),t.addColorStop(.2,"rgba(255,255,255,0.8)"),t.addColorStop(.5,"rgba(255,255,255,0.3)"),t.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=t,e.fillRect(0,0,64,64),du=new oc(n),du}function rF(){if(hu)return hu;const n=document.createElement("canvas");n.width=128,n.height=128;const e=n.getContext("2d"),t=e.createRadialGradient(64,64,0,64,64,64);return t.addColorStop(0,"rgba(255,255,255,1)"),t.addColorStop(.1,"rgba(255,200,100,0.9)"),t.addColorStop(.4,"rgba(255,100,50,0.4)"),t.addColorStop(.7,"rgba(255,50,0,0.1)"),t.addColorStop(1,"rgba(0,0,0,0)"),e.fillStyle=t,e.fillRect(0,0,128,128),hu=new oc(n),hu}function oF(){if(fu)return fu;const n=document.createElement("canvas");n.width=64,n.height=64;const e=n.getContext("2d"),t=e.createImageData(64,64);for(let i=0;ie.add(a)),this.mainTrail=this._createMainTrail(),this.secondaryTrails=this._createSecondaryTrails(),this._updateColors(),this._updateIntensity(),this.mainTrail.activate(),this.secondaryTrails.forEach(a=>a.activate())}_createMainTrail(){const e=new pt(this.scene,!1),t=lv(),i=this.config.mainTrailWidth,s=[new S(0,-i,0),new S(0,i,0),new S(-i,0,0),new S(i,0,0),new S(0,0,-i),new S(0,0,i)];return e.initialize(t,this.config.trailLength,!1,0,s,this.mainTarget),e.setAdvanceFrequency(60),e.mesh&&(e.mesh.frustumCulled=!1,e.mesh.renderOrder=100),e}_createSecondaryTrails(){const e=[];for(let t=0;t<4;t++){const i=new pt(this.scene,!1),s=lv(),a=this.config.secondaryTrailWidth,r=[new S(0,-a,0),new S(0,a,0),new S(-a,0,0),new S(a,0,0),new S(0,0,-a),new S(0,0,a)];i.initialize(s,this.config.trailLength,!1,0,r,this.secondaryTargets[t]),i.setAdvanceFrequency(60),i.mesh&&(i.mesh.frustumCulled=!1,i.mesh.renderOrder=100),e.push(i)}return e}_updateColors(){const e=this.teamColors[this.team]||this.teamColors[0];this.mainTrail?.material&&(this.mainTrail.material.uniforms.headColor.value.copy(e.head),this.mainTrail.material.uniforms.tailColor.value.copy(e.tail));const t=e.head.clone();t.w=e.head.w*.85;const i=e.tail.clone();this.secondaryTrails.forEach(s=>{s?.material&&(s.material.uniforms.headColor.value.copy(t),s.material.uniforms.tailColor.value.copy(i))})}_updateIntensity(){this.mainTrail?.material&&(this.mainTrail.material.uniforms.intensityMultiplier.value=this.intensity),this.secondaryTrails.forEach(e=>{e?.material&&(e.material.uniforms.intensityMultiplier.value=this.intensity)})}setTeam(e){this.team!==e&&(this.team=e,this._updateColors())}setIntensity(e){this.intensity=e,this.dying||this._updateIntensity()}startDying(){this.dying||(this.dying=!0,this.deathTime=0,this.mainTrail.pause(),this.secondaryTrails.forEach(e=>e.pause()))}updatePosition(e,t,i){if(this.dying)return;const s=t.clone().normalize();this.mainTarget.position.copy(e),this.mainTarget.updateMatrixWorld();for(let a=0;a<4;a++){const o=a/4*Math.PI*2+i,l=new S(Math.cos(o)*this.config.secondaryTrailOffset,Math.sin(o)*this.config.secondaryTrailOffset,0);if(s.lengthSq()>.001){const c=new S(0,0,1),u=new dt;u.setFromUnitVectors(c,s),l.applyQuaternion(u)}this.secondaryTargets[a].position.copy(e).add(l),this.secondaryTargets[a].updateMatrixWorld()}}update(e){if(this.dying){this.deathTime+=e;const t=Math.min(1,this.deathTime/this.maxDeathTime),i=this.intensity*(1-t);this.mainTrail?.material&&(this.mainTrail.material.uniforms.intensityMultiplier.value=i),this.secondaryTrails.forEach(s=>{s?.material&&(s.material.uniforms.intensityMultiplier.value=i)}),this.deathTime>=this.maxDeathTime&&(this.active=!1)}this.mainTrail.isActive&&this.mainTrail.update(e),this.secondaryTrails.forEach(t=>{t.isActive&&t.update(e)})}dispose(){this.mainTrail.deactivate(),this.secondaryTrails.forEach(e=>e.deactivate()),this.mainTrail.geometry&&this.mainTrail.geometry.dispose(),this.mainTrail.material&&this.mainTrail.material.dispose(),this.secondaryTrails.forEach(e=>{e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()}),this.scene.remove(this.mainTarget),this.secondaryTargets.forEach(e=>this.scene.remove(e))}}class dF{constructor(e,t=0){this.scene=e,this.team=t,this.active=!1,this.ballRadius=92.75,this.config={trailLength:60,mainTrailWidth:15,secondaryTrailWidth:1.5,secondaryTrailOffset:this.ballRadius*.7},this.rotationSpeed=Math.PI/3,this.currentRotation=0,this.minVelocity=1500,this.maxVelocity=6e3,this.minIntensity=.3,this.maxIntensity=1,this.wasEmitting=!1,this.segments=[],this.currentSegment=null,this.currentIntensity=1}_calculateIntensity(e){if(e<=this.minVelocity)return this.minIntensity;if(e>=this.maxVelocity)return this.maxIntensity;const t=(e-this.minVelocity)/(this.maxVelocity-this.minVelocity);return this.minIntensity+t*(this.maxIntensity-this.minIntensity)}setTeam(e){this.team!==e&&(this.team=e,this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.startDying(),this.currentSegment=null))}activate(){this.active||(this.active=!0,this.currentSegment=null,this.wasEmitting=!1)}deactivate(){this.active&&(this.active=!1,this.currentSegment&&(this.currentSegment.startDying(),this.currentSegment=null))}emit(e,t,i){const s=t.length();if(!(s>=this.minVelocity)){this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.startDying(),this.currentSegment=null),this.wasEmitting=!1;return}this.currentIntensity=this._calculateIntensity(s),this.active||this.activate(),!this.wasEmitting||!this.currentSegment?(this.currentSegment&&!this.currentSegment.dying&&this.currentSegment.startDying(),this.currentSegment=new uF(this.scene,this.team,this.config,this.currentIntensity),this.segments.push(this.currentSegment)):this.currentSegment.setIntensity(this.currentIntensity),this.wasEmitting=!0,this.currentRotation+=this.rotationSpeed*i,this.currentRotation>Math.PI*2&&(this.currentRotation-=Math.PI*2),this.currentSegment.updatePosition(e,t,this.currentRotation)}update(e){for(let t=this.segments.length-1;t>=0;t--){const i=this.segments[t];i.update(e),i.active||(i.dispose(),this.segments.splice(t,1))}}reset(){for(const e of this.segments)e.dispose();this.segments=[],this.currentSegment=null,this.currentRotation=0,this.wasEmitting=!1}addToScene(e){}removeFromScene(e){for(const t of this.segments)t.startDying();this.currentSegment=null}dispose(){for(const e of this.segments)e.dispose();this.segments=[],this.currentSegment=null}}let mu=null,_u=null,gu=null,cv=!1;function hF(){cv||(_F(),gF(),yF(),cv=!0)}let di=null;class fF{constructor(e,t,i,s=2){this.scene=e,this.renderer=t,this.camera=i,this.maxExplosions=s,this.explosions=[],this.warmedUp=!1,this.initPool()}initPool(){this.sphereGeo=new yn(1,16,12),this.coreGeo=new yn(1,12,8),this.ringGeo=new ni(.5,1,32),this.particleGeo=new kn(1,1),this.coreMaterial=new Ye({color:16777130,transparent:!0,opacity:.9,blending:Ht,side:ct,depthWrite:!1}),this.sphereMaterial=new Ye({color:16737792,transparent:!0,opacity:.5,blending:Ht,side:ct,depthWrite:!1}),this.ringMaterial=new Ye({color:16746496,transparent:!0,opacity:.7,blending:Ht,side:ct,depthWrite:!1}),this.particleMaterial=new Ye({color:16763904,transparent:!0,opacity:.8,blending:Ht,side:ct,depthWrite:!1});for(let e=0;e!i.active);t||(t=this.explosions[0],this.resetExplosion(t)),t.active=!0,t.elapsed=0,t.position.copy(e),t.container.position.copy(e),t.container.visible=!0,t.core.scale.set(.1,.1,.1),t.coreMat.opacity=1,t.sphere.scale.set(.1,.1,.1),t.sphere.material.opacity=.6,t.ring.scale.set(.1,.1,.1),t.ring.material.opacity=.8,t.particleMat.opacity=.9,t.particles.forEach((i,s)=>{i.mesh.position.set(0,0,0);const a=s/12*Math.PI*2,r=(Math.random()-.3)*Math.PI,o=350+Math.random()*250;i.velocity.set(Math.cos(a)*Math.cos(r)*o,Math.sin(r)*o+100,Math.sin(a)*Math.cos(r)*o)})}resetExplosion(e){e.active=!1,e.container.visible=!1}update(e){for(const t of this.explosions){if(!t.active)continue;t.elapsed+=e;const i=t.elapsed/t.duration;if(i>=1){this.resetExplosion(t);continue}const s=30+i*80;t.core.scale.set(s,s,s),t.coreMat.opacity=1*Math.pow(1-i,2);const a=50+i*200;t.sphere.scale.set(a,a,a),t.sphere.material.opacity=.6*(1-i);const r=80+i*350;t.ring.scale.set(r,r,r),t.ring.material.opacity=.8*(1-i*i),t.particleMat.opacity=.9*(1-i);for(const o of t.particles)o.mesh.position.add(o.velocity.clone().multiplyScalar(e)),o.velocity.y-=300*e,this.camera&&o.mesh.lookAt(this.camera.position)}}dispose(){for(const e of this.explosions)this.scene.remove(e.container),e.coreMat.dispose(),e.sphere.material.dispose(),e.ring.material.dispose(),e.particleMat.dispose();this.coreGeo.dispose(),this.sphereGeo.dispose(),this.ringGeo.dispose(),this.particleGeo.dispose(),this.coreMaterial.dispose(),this.sphereMaterial.dispose(),this.ringMaterial.dispose(),this.particleMaterial.dispose()}}function LT(n,e=null,t=null){return di&&di.scene!==n&&(di.dispose?.(),di=null),di||(di=new fF(n,e,t)),e&&t&&!di.warmedUp&&(di.renderer=e,di.camera=t,di.warmup()),di}function pF(n,e,t){LT(n,e,t),kT(n,e,t)}let Bn=null;const uv={0:{core:6737151,sphere:35071,ring:43775,particles:8969727},1:{core:16768358,sphere:16737792,ring:16746496,particles:16755268}};class mF{constructor(e,t,i,s=2){this.scene=e,this.renderer=t,this.camera=i,this.maxExplosions=s,this.explosions=[],this.warmedUp=!1,this.initPool()}initPool(){this.coreGeo=new yn(1,16,12),this.sphereGeo=new yn(1,20,14),this.ringGeo=new ni(.3,1,48),this.particleGeo=new kn(1,1),this.rayGeo=new kn(1,1);for(let e=0;e!l.active);i||(i=this.explosions[0],this.resetExplosion(i));const s=i.materials[t]||i.materials[0];i.core.material=s.core,i.core2.material=s.core.clone(),i.core3.material=s.sphere.clone(),i.sphere.material=s.sphere;for(const l of i.rings)l.mesh.material=s.ring.clone();for(const l of i.rays)l.mesh.material=s.rays.clone();for(const l of i.particles)l.mesh.material=s.particles.clone();i.active=!0,i.elapsed=0,i.currentTeam=t,i.position.copy(e),i.container.position.copy(e),i.container.visible=!0,i.rotationOffset=0,i.core.scale.set(.1,.1,.1),i.core.material.opacity=1,i.core2.scale.set(.1,.1,.1),i.core2.material.opacity=.8,i.core3.scale.set(.1,.1,.1),i.core3.material.opacity=.5,i.sphere.scale.set(.1,.1,.1),i.sphere.material.opacity=.4;for(const l of i.rings)l.mesh.scale.set(.1,.1,.1),l.mesh.material.opacity=.9;for(let l=0;l=i.particles.length);d++){const h=i.particles[o];h.mesh.position.set(0,0,0),h.mesh.material.opacity=1;const f=h.initialScale;h.mesh.scale.set(f,f,f);const p=c+(Math.random()-.5)*.3,g=u+(Math.random()-.5)*.2,v=1800*(1-d/r*.5)+Math.random()*300;h.velocity.set(Math.cos(p)*Math.cos(g)*v,Math.sin(g)*v+300,Math.sin(p)*Math.cos(g)*v),h.delay=d*.02,o++}}for(;o=1){this.resetExplosion(t);continue}t.rotationOffset+=e*2;const s=this.easeOutElastic(Math.min(i*2,1)),a=this.easeOutExpo(i),r=this.easeOutBack(Math.min(i*1.5,1)),o=1+Math.sin(t.elapsed*15)*.15*(1-i),l=(150+s*300)*o;t.core.scale.set(l,l,l),t.core.material.opacity=1*Math.pow(1-i,1.2);const c=1+Math.sin(t.elapsed*12+1)*.12*(1-i),u=(200+r*400)*c;t.core2.scale.set(u,u,u),t.core2.material.opacity=.7*Math.pow(1-i,1.5);const d=300+a*600;t.core3.scale.set(d,d,d),t.core3.material.opacity=.4*Math.pow(1-i,2);const h=400+a*1200;t.sphere.scale.set(h,h,h),t.sphere.material.opacity=.3*(1-i*i);for(let g=0;g0){g.mesh.position.add(g.velocity.clone().multiplyScalar(e)),g.velocity.y-=600*e,g.velocity.multiplyScalar(.995);const m=Math.max(.3,1-i*.7),v=g.initialScale*m;g.mesh.scale.set(v,v,v)}g.mesh.material.opacity=1*Math.pow(1-i,1.2),this.camera&&g.mesh.lookAt(this.camera.position)}}}dispose(){for(const e of this.explosions){this.scene.remove(e.container);for(const t of Object.values(e.materials))t.core.dispose(),t.sphere.dispose(),t.ring.dispose(),t.particles.dispose(),t.rays.dispose()}this.coreGeo.dispose(),this.sphereGeo.dispose(),this.ringGeo.dispose(),this.particleGeo.dispose(),this.rayGeo.dispose()}}function kT(n,e=null,t=null){return Bn&&Bn.scene!==n&&(Bn.dispose?.(),Bn=null),Bn||(Bn=new mF(n,e,t)),e&&t&&!Bn.warmedUp&&(Bn.renderer=e,Bn.camera=t,Bn.warmup()),Bn}function _F(){if(mu)return mu;const n=document.createElement("canvas");n.width=64,n.height=64;const e=n.getContext("2d"),t=e.createRadialGradient(32,32,0,32,32,32);return t.addColorStop(0,"rgba(255,255,255,1)"),t.addColorStop(.2,"rgba(255,255,255,0.8)"),t.addColorStop(.5,"rgba(255,255,255,0.3)"),t.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=t,e.fillRect(0,0,64,64),mu=new dc(n),mu}function gF(){if(_u)return _u;const n=document.createElement("canvas");n.width=128,n.height=128;const e=n.getContext("2d"),t=e.createRadialGradient(64,64,0,64,64,64);return t.addColorStop(0,"rgba(255,255,255,1)"),t.addColorStop(.1,"rgba(255,200,100,0.9)"),t.addColorStop(.4,"rgba(255,100,50,0.4)"),t.addColorStop(.7,"rgba(255,50,0,0.1)"),t.addColorStop(1,"rgba(0,0,0,0)"),e.fillStyle=t,e.fillRect(0,0,128,128),_u=new dc(n),_u}function yF(){if(gu)return gu;const n=document.createElement("canvas");n.width=64,n.height=64;const e=n.getContext("2d"),t=e.createImageData(64,64);for(let i=0;i=o.maxLife){o.active=!1,i[r]=0,s[r]=0;continue}t[r*3]+=o.velocity.x*e,t[r*3+1]+=o.velocity.y*e,t[r*3+2]+=o.velocity.z*e;const l=o.life/o.maxLife;i[r]=Math.pow(1-l,.5);const c=o.initialSize||3;s[r]=c*(1-l*.7),a[r*3]=1,a[r*3+1]=Math.max(.2,.9-l*.7),a[r*3+2]=Math.max(0,.4-l*.4),o.velocity.y+=20*e}this.geometry.attributes.position.needsUpdate=!0,this.geometry.attributes.alpha.needsUpdate=!0,this.geometry.attributes.size.needsUpdate=!0,this.geometry.attributes.color.needsUpdate=!0}addToScene(e){e.add(this.points)}removeFromScene(e){e.remove(this.points)}dispose(){this.geometry.dispose(),this.points.material.dispose()}}class cF{constructor(e,t,i,s){this.scene=e,this.team=t,this.trailWidth=i,this.trailLength=s,this.active=!0,this.dying=!1,this.deathTime=0,this.maxDeathTime=1.5,this.teamColors={0:new qe(.3,.6,1,.9),1:new qe(1,.5,.15,.9)},this.leftTarget=new Qe,this.rightTarget=new Qe,e.add(this.leftTarget),e.add(this.rightTarget),this.leftTrail=this.createTrail(this.leftTarget),this.rightTrail=this.createTrail(this.rightTarget),this.updateColors(),this.leftTrail.activate(),this.rightTrail.activate()}createTrail(e){const t=new pt(this.scene,!1),i=pt.createBaseMaterial();i.blending=Ht,i.depthWrite=!1,i.side=ct;const s=this.trailWidth,a=[new S(0,0,0),new S(0,s,0),new S(-s/2,s/2,0),new S(s/2,s/2,0)];return t.initialize(i,this.trailLength,!1,0,a,e),t.setAdvanceFrequency(60),t.mesh&&(t.mesh.frustumCulled=!1),t}updateColors(){const e=this.teamColors[this.team]||this.teamColors[0],t=new qe(e.x*.3,e.y*.3,e.z*.3,0);this.leftTrail?.material&&(this.leftTrail.material.uniforms.headColor.value.copy(e),this.leftTrail.material.uniforms.tailColor.value.copy(t)),this.rightTrail?.material&&(this.rightTrail.material.uniforms.headColor.value.copy(e),this.rightTrail.material.uniforms.tailColor.value.copy(t))}startDying(){this.dying||(this.dying=!0,this.deathTime=0,this.leftTrail.pause(),this.rightTrail.pause())}updatePosition(e,t,i){this.dying||(this.leftTarget.position.copy(e),this.rightTarget.position.copy(t),this.leftTarget.quaternion.copy(i),this.rightTarget.quaternion.copy(i),this.leftTarget.updateMatrixWorld(),this.rightTarget.updateMatrixWorld())}update(e){if(this.dying){this.deathTime+=e;const i=1-Math.min(1,this.deathTime/this.maxDeathTime),s=this.teamColors[this.team]||this.teamColors[0],a=new qe(s.x,s.y,s.z,s.w*i),r=new qe(s.x*.3,s.y*.3,s.z*.3,0);this.leftTrail?.material&&(this.leftTrail.material.uniforms.headColor.value.copy(a),this.leftTrail.material.uniforms.tailColor.value.copy(r)),this.rightTrail?.material&&(this.rightTrail.material.uniforms.headColor.value.copy(a),this.rightTrail.material.uniforms.tailColor.value.copy(r)),this.deathTime>=this.maxDeathTime&&(this.active=!1)}this.leftTrail.isActive&&this.leftTrail.update(e),this.rightTrail.isActive&&this.rightTrail.update(e)}dispose(){this.leftTrail.deactivate(),this.rightTrail.deactivate(),this.leftTrail.geometry&&this.leftTrail.geometry.dispose(),this.rightTrail.geometry&&this.rightTrail.geometry.dispose(),this.leftTrail.material&&this.leftTrail.material.dispose(),this.rightTrail.material&&this.rightTrail.material.dispose(),this.scene.remove(this.leftTarget),this.scene.remove(this.rightTarget)}}class uF{constructor(e,t=0){this.scene=e,this.team=t,this.active=!1,this.trailLength=80,this.trailWidth=15,this.arenaBounds={floor:0,ceiling:2044,wallX:4096,wallZ:5120},this.groundedThreshold=50,this.segments=[],this.currentSegment=null,this.wasGrounded=!0}setTeam(e){this.team!==e&&(this.team=e,this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.team=e,this.currentSegment.updateColors()))}setActive(e){e&&!this.active?(this.currentSegment=null,this.wasGrounded=!0):!e&&this.active&&this.currentSegment&&(this.currentSegment.startDying(),this.currentSegment=null),this.active=e}isGrounded(e){const t=this.groundedThreshold,i=this.arenaBounds;if(e.yi.ceiling-t)return{grounded:!0,surface:"ceiling",normal:new S(0,-1,0)};if(Math.abs(e.x)>i.wallX-t){const s=e.x>0?-1:1;return{grounded:!0,surface:"wall",normal:new S(s,0,0)}}if(Math.abs(e.z)>i.wallZ-t){const s=e.z>0?-1:1;return{grounded:!0,surface:"wall",normal:new S(0,0,s)}}return{grounded:!1,surface:null,normal:null}}emit(e,t,i){if(!this.active)return;const s=this.isGrounded(e);if(!s.grounded){this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.startDying(),this.currentSegment=null),this.wasGrounded=!1;return}(!this.wasGrounded||!this.currentSegment)&&(this.currentSegment&&!this.currentSegment.dying&&this.currentSegment.startDying(),this.currentSegment=new cF(this.scene,this.team,this.trailWidth,this.trailLength),this.segments.push(this.currentSegment)),this.wasGrounded=!0;const r=new S(-30,5,40),o=new S(-30,5,-40);r.applyQuaternion(t),o.applyQuaternion(t);const l=e.clone().add(r),c=e.clone().add(o),u=2;if(s.surface==="floor")l.y=u,c.y=u;else if(s.surface==="ceiling")l.y=this.arenaBounds.ceiling-u,c.y=this.arenaBounds.ceiling-u;else if(s.surface==="wall"){if(s.normal.x!==0){const d=s.normal.x>0?-this.arenaBounds.wallX+u:this.arenaBounds.wallX-u;l.x=d,c.x=d}else if(s.normal.z!==0){const d=s.normal.z>0?-this.arenaBounds.wallZ+u:this.arenaBounds.wallZ-u;l.z=d,c.z=d}}this.currentSegment.updatePosition(l,c,t)}update(e){for(let t=this.segments.length-1;t>=0;t--){const i=this.segments[t];i.update(e),i.active||(i.dispose(),this.segments.splice(t,1))}}addToScene(e){}removeFromScene(e){for(const t of this.segments)t.startDying();this.currentSegment=null}dispose(){for(const e of this.segments)e.dispose();this.segments=[],this.currentSegment=null}}class dF{constructor(e){this.scene=e,this.renderer=null,this.camera=null,this.explosions={active:[],goalEvents:new Map,demoEvents:new Map},this.boostTrails=new Map,this.supersonicTrails=new Map,this.ballTrail=null,tF()}setRenderContext(e,t){this.renderer=e,this.camera=t,iF(this.scene,e,t)}reset(){this.explosions.active.forEach(e=>e.removeFromScene(this.scene)),this.explosions.active=[],this.clearGoalExplosions(),this.boostTrails.forEach(e=>{e.removeFromScene(this.scene),e.dispose()}),this.boostTrails.clear(),this.supersonicTrails.forEach(e=>{e.removeFromScene(this.scene),e.dispose()}),this.supersonicTrails.clear(),this.ballTrail&&(this.ballTrail.removeFromScene(this.scene),this.ballTrail.dispose(),this.ballTrail=null)}clearEvents(){this.explosions.goalEvents.clear(),this.explosions.demoEvents.clear()}setGoalEvents(e){this.explosions.goalEvents.clear();for(const t of e??[])Number.isFinite(t.frame)&&this.explosions.goalEvents.set(t.frame,{time:t.time,team:t.team??0,playerName:t.playerName??""})}resetBallTrail(){this.ballTrail&&this.ballTrail.reset()}clearGoalExplosions(){Bn&&Bn.clearActive();for(const e of this.explosions.active)e.removeFromScene(this.scene);this.explosions.active=[]}createBoostTrail(e,t){if(this.boostTrails.has(t)){const s=this.boostTrails.get(t);s.removeFromScene(this.scene),s.dispose()}const i=new lF(e);return i.addToScene(this.scene),this.boostTrails.set(t,i),i}removeBoostTrail(e){const t=this.boostTrails.get(e);t&&(t.removeFromScene(this.scene),t.dispose(),this.boostTrails.delete(e))}updateBoostTrail(e,t,i,s,a){const r=this.boostTrails.get(e);r&&(r.setActive(t),t&&r.emit(i,s,a,this._playbackSpeed||1))}createSupersonicTrail(e,t){if(this.supersonicTrails.has(e)){const s=this.supersonicTrails.get(e);s.removeFromScene(this.scene),s.dispose()}const i=new uF(this.scene,t);return i.addToScene(this.scene),this.supersonicTrails.set(e,i),i}removeSupersonicTrail(e){const t=this.supersonicTrails.get(e);t&&(t.removeFromScene(this.scene),t.dispose(),this.supersonicTrails.delete(e))}updateSupersonicTrail(e,t,i,s,a,r){let o=this.supersonicTrails.get(e);!o&&t&&(o=this.createSupersonicTrail(e,r)),o&&(r!==void 0&&o.team!==r&&o.setTeam(r),o.setActive(t),t&&o.emit(i,s,a))}createBallTrail(){return this.ballTrail&&(this.ballTrail.removeFromScene(this.scene),this.ballTrail.dispose()),this.ballTrail=new eF(this.scene,0),this.ballTrail.addToScene(this.scene),console.log("✓ Spiral ball trail created and added to scene"),this.ballTrail}updateBallTrail(e,t,i){this.ballTrail||this.createBallTrail(),i!==void 0&&this.ballTrail.team!==i&&this.ballTrail.setTeam(i);const s=1/60*(this._playbackSpeed||1);this.ballTrail.emit(e,t,s)}triggerGoalExplosion(e,t){const i=MT(this.scene,this.renderer,this.camera);i&&(this.camera&&(i.camera=this.camera),i.trigger(e,t))}triggerDemoExplosion(e,t,i){const s=TT(this.scene);s&&s.trigger(e)}update(e,t=!0,i=1){this._playbackSpeed=i;const s=e*i;di&&di.update(s),Bn&&Bn.update(s);for(let a=this.explosions.active.length-1;a>=0;a--){const r=this.explosions.active[a];r.update(s)&&(r.removeFromScene(this.scene),this.explosions.active.splice(a,1))}t&&(this.boostTrails.forEach(a=>{a.update(s)}),this.supersonicTrails.forEach(a=>{a.update(s)}),this.ballTrail&&this.ballTrail.update(s))}}const sv={Octane:65535,Dominus:16746496,Plank:8978176,Breakout:16711816,Hybrid:8913151,Merc:16776960},hF={0:5744895,1:16751680};function fF(n,e){return e===0||e===1?hF[e]:sv[n]||sv.Octane}class pF{constructor(e){this.scene=e,this.hitboxes=new Map,this.enabled=!1}setEnabled(e){this.enabled=e,this.hitboxes.forEach(({mesh:t})=>{t.visible=e})}createHitboxWireframe(e,t){const i=oy[e]||oy.Octane,s=fF(e,t),a=i.length,r=i.width,o=i.height,l=i.offsetX,c=i.offsetZ;console.log(`[HitboxManager] Creating hitbox for ${e}:`,{dims:i,length:a,width:r,height:o,offsetX:l,offsetY:c});const u=new Mt,d=new Ei(a,o,r),h=new Ye({color:s,transparent:!0,opacity:.35,depthTest:!1,depthWrite:!1,side:ct}),f=new we(d,h);f.frustumCulled=!1,f.renderOrder=1,f.position.set(l,c,0),u.add(f);const p=new Bh(d),g=new Rt({color:s,linewidth:2,transparent:!0,opacity:.9,depthTest:!1}),_=new Ln(p,g);_.frustumCulled=!1,_.renderOrder=2,_.position.set(l,c,0),u.add(_);const m=3.33,v=new yn(m,8,6),y=new ug(v),b=new Rt({color:16777215,linewidth:1,transparent:!0,opacity:.9,depthTest:!1}),T=new Ln(y,b);return T.frustumCulled=!1,u.add(T),u.userData.hitboxType=e,u.userData.team=t??null,u.frustumCulled=!1,u}addHitbox(e,t,i){const s=i===0||i===1?i:null;if(this.hitboxes.has(e)){const r=this.hitboxes.get(e);if(r.hitboxType===t&&r.team===s)return;this.scene.remove(r.mesh),r.mesh.traverse(o=>{o.geometry&&o.geometry.dispose(),o.material&&o.material.dispose()})}const a=this.createHitboxWireframe(t,s);a.visible=this.enabled,this.scene.add(a),this.hitboxes.set(e,{mesh:a,hitboxType:t,team:s})}removeHitbox(e){if(this.hitboxes.has(e)){const{mesh:t}=this.hitboxes.get(e);this.scene.remove(t),t.traverse(i=>{i.geometry&&i.geometry.dispose(),i.material&&i.material.dispose()}),this.hitboxes.delete(e)}}updateHitboxes(e,t,i,s){if(!this.enabled)return;for(const[r,o]of Object.entries(t)){const l=e[o];if(!l||!l.userData.isCar)continue;const c=i?i(r):"Octane",u=s?s(r):null;this.addHitbox(o,c,u);const{mesh:d}=this.hitboxes.get(o);d.position.copy(l.position),d.quaternion.copy(l.quaternion),d.visible=this.enabled&&l.visible}const a=new Set(Object.values(t));for(const r of this.hitboxes.keys())a.has(r)||this.removeHitbox(r)}reset(){this.hitboxes.forEach(({mesh:e})=>{this.scene.remove(e),e.traverse(t=>{t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose()})}),this.hitboxes.clear()}dispose(){this.reset()}}const ET=["baseGroup","glowMesh","innerGlowMesh","lensColumnMesh","lensRimMesh","topGlowMesh","coreGlowMesh","highlightMesh"];function gp(n,e,t,i){const s=new we(new Io(n,32),new Ye({color:e,transparent:!0,opacity:t,blending:Ht,side:ct,depthWrite:!1}));return s.rotation.x=-Math.PI/2,s.renderOrder=i,s}function av(n,e){n&&n.traverse(t=>{const i=t;if(!i.isMesh||!(i.material instanceof Ye))return;const s=i.userData.baseOpacity;i.material.opacity=(s??i.material.opacity)*e})}function pu(n,e,t){n.rotation.x=-Math.PI/2,n.renderOrder=t,n.frustumCulled=!1,n.userData.baseOpacity=e,n.material.transparent=!0,n.material.opacity=e,n.material.side=ct,n.material.depthWrite=!1}function mF(n){const e=new Mt;e.renderOrder=98,e.frustumCulled=!1;const t=new Ye({color:1118477}),i=new Ye({color:16752640,blending:Ht}),s=new we(new Io(n*.55,48),t.clone());pu(s,.86,98),e.add(s);const a=new we(new ni(n*.45,n*.62,48),new Ye({color:16765242,blending:Ht}));pu(a,.78,100),a.position.y=1.4,e.add(a);function r(o,l,c){const u=new Ns;return[[o*Math.cos(-c*.72),o*Math.sin(-c*.72)],[l*Math.cos(-c),l*Math.sin(-c)],[l*Math.cos(c),l*Math.sin(c)],[o*Math.cos(c*.72),o*Math.sin(c*.72)]].forEach(([h,f],p)=>{p===0?u.moveTo(h,f):u.lineTo(h,f)}),u.closePath(),u}for(let o=0;o<3;o+=1){const l=o*(Math.PI*2)/3+Math.PI/2,c=new we(new ur(r(n*.52,n*1.42,.33)),t.clone());pu(c,.86,98),c.rotation.z=l,e.add(c);const u=new we(new ur(r(n*.66,n*1.2,.21)),i.clone());pu(u,.86,99),u.position.y=1.1,u.rotation.z=l,e.add(u)}return e}function rv(n,e){for(const t of ET){const i=n.userData[t];i&&(i.visible=e)}}function _F(){let n=new Map;function e(i){const s=i.player.adapter.boostPads;!s||s.size===0||(console.log(`[boost-pads] Creating ${s.size} boost pads...`),n=new Map,s.forEach((a,r)=>{const o=a.isBig;let l,c,u;if(o){l=new yn(37,24,18),c=new ii({color:16757274,emissive:16747008,emissiveIntensity:.42,metalness:.04,roughness:.08,clearcoat:1,clearcoatRoughness:.025,transmission:.18,thickness:30,ior:1.42,envMapIntensity:1.9,blending:Ht,transparent:!0,opacity:.68,depthWrite:!1}),u=new we(l,c),u.renderOrder=100;const p=mF(37*2.05);p.position.y=-140,u.add(p),u.userData.baseGroup=p;const g=new we(new lr(37*.12,37*.18,112,24,1,!0),new Ye({color:16761664,transparent:!0,opacity:.28,blending:Ht,side:ct,depthWrite:!1}));g.position.y=-62,g.renderOrder=99,u.add(g),u.userData.lensColumnMesh=g;const _=new we(new yn(37*1.03,24,14),new Ye({color:16768890,transparent:!0,opacity:.32,blending:Ht,side:un,depthWrite:!1}));_.renderOrder=101,u.add(_),u.userData.lensRimMesh=_;const m=new yn(37*1.3,20,14),v=new Ye({color:16758315,transparent:!0,opacity:.16,blending:Ht,side:un,depthWrite:!1}),y=new we(m,v);y.renderOrder=99,u.add(y),u.userData.glowMesh=y;const b=new yn(37*1.12,20,14),T=new Ye({color:16761130,transparent:!0,opacity:.22,blending:Ht,side:un,depthWrite:!1}),x=new we(b,T);x.renderOrder=99,u.add(x),u.userData.innerGlowMesh=x,u.userData.needsLight=!0}else{l=new lr(45,45*.92,8,32),c=new ii({color:16761370,emissive:16750336,emissiveIntensity:.72,metalness:.88,roughness:.14,clearcoat:1,clearcoatRoughness:.05,envMapIntensity:2,transparent:!0,opacity:1,depthWrite:!1}),u=new we(l,c),u.renderOrder=100;const g=gp(45*1.42,16756736,.34,101);g.position.y=8/2+.15,u.add(g),u.userData.topGlowMesh=g;const _=gp(45*.74,16777114,.42,102);_.position.y=8/2+.35,u.add(_),u.userData.coreGlowMesh=_;const m=gp(45*.42,16775376,.46,103);m.position.set(-45*.18,8/2+.55,-45*.12),m.scale.y=.34,u.add(m),u.userData.highlightMesh=m}const h=o?130:10;if(u.position.set(a.position.x,h,a.position.y),u.userData.padId=r,u.userData.isBig=o,u.userData.isAvailable=!0,i.scene.add(u),n.set(r,u),u.userData.needsLight){const f=new dr(16751872,.7,480);f.decay=0,f.position.set(a.position.x,h-50,a.position.y),i.scene.add(f),u.userData.light=f}}),console.log(`[boost-pads] ✓ Created ${n.size} boost pad meshes`))}function t(i){i.player.adapter.boostPads.forEach((a,r)=>{const o=n.get(r);if(!o)return;const l=a.isAvailable;o.userData.isAvailable!==l&&(o.userData.isAvailable=l,l?(o.material.color.setHex(a.isBig?16757274:16761370),o.material.emissive.setHex(a.isBig?16747008:16750336),o.material.emissiveIntensity=a.isBig?.42:.72,o.material.opacity=a.isBig?.68:1,o.visible=!0,rv(o,!0),av(o.userData.baseGroup,1),o.userData.light&&(o.userData.light.intensity=.85),o.userData.glowMesh&&(o.userData.glowMesh.visible=!0),o.userData.innerGlowMesh&&(o.userData.innerGlowMesh.visible=!0)):(o.material.color.setHex(a.isBig?9063424:9065472),o.material.emissive.setHex(0),o.material.emissiveIntensity=0,o.material.opacity=.2,o.visible=!0,rv(o,!1),o.userData.baseGroup&&(o.userData.baseGroup.visible=!0,av(o.userData.baseGroup,.26)),o.userData.light&&(o.userData.light.intensity=0),o.userData.glowMesh&&(o.userData.glowMesh.visible=!1),o.userData.innerGlowMesh&&(o.userData.innerGlowMesh.visible=!1)))})}return{id:"boost-pads",setup(i){e(i)},beforeRender(i){t(i)},teardown(i){n.forEach(s=>{i.scene.remove(s),s.geometry.dispose(),s.material.dispose();for(const r of ET){const o=s.userData[r];o&&o.traverse(l=>{const c=l;c.isMesh&&(c.geometry.dispose(),c.material.dispose())})}const a=s.userData.light;a&&(i.scene.remove(a),a.dispose())}),n.clear()}}}const gF=2;function yF(n){if(n.frames.length===0)return null;const e=new Map;for(const s of n.frames)e.set(s.gameState,(e.get(s.gameState)??0)+1);let t=null,i=-1;for(const[s,a]of e.entries())a<=i||(t=s,i=a);return t}function vF(n,e){if(e===null)return null;for(const t of n.frames){if(t.gameState===e)break;return t.gameState}return null}function CT(n,e){return e===null?n.kickoffCountdown<=0:n.gameState===e}function Rg(n,e){return n.kickoffCountdown>0?!0:e!==null&&n.gameState===e}function bF(n,e){return n.ballFrames[e]?.position?!0:n.players.some(t=>t.frames[e]?.position)}function xF(n,e,t,i){return Rg(e,i)&&bF(n,t)}function wF(n,e){return n.timelineEvents.some(t=>t.kind==="goal"&&e.time>=t.time&&e.timec){const h=a.at(-1);h&&h.endTime>=c?h.endTime=Math.max(h.endTime,d):a.push({startTime:c,endTime:d})}o=u}return a}function TF(n,e,t){const i=vt.clamp(t,0,n);for(const s of e){if(i0&&(n.frames[s-1]?.kickoffCountdown??0)>0;)s-=1;let a=e+1;for(;a0;)a+=1;let r=0;for(let c=s;cl>s&&CT(o,t));return!r||r.time===e?null:r.time}function IF(n,e,t,i){const s=fh(n,e),a=n.frames[s];if(!a||!Wu(n,a,s,t,i))return null;const r=n.frames.find((c,u)=>u>s&&!Wu(n,c,u,t,i));if(r)return r.time===e?null:r.time;let o=s;for(;o>0&&Wu(n,n.frames[o-1],o-1,t,i);)o-=1;const l=n.frames[o]?.time;return l===void 0||l===e?null:l}function LF(n){return!!n?.position&&n?.isPresent!==!1}function DF(n,e,t){for(let i=n.length-1;i>=0;i-=1){const s=n[i],a=t-s.time;if(!(a<0)){if(a>RF)break;if(s.kind==="demo"&&s.secondaryPlayerId===e)return s}}return null}const kF="space",OF={space:{id:"space",skyboxUrl:"/skyboxes/PlanetaryEarth4k.hdr",exposure:1.45,rotation:{x:8,y:0,z:28},animation:{enabled:!0,speed:2}}};function FF(n){if(n===!1)return null;if(typeof n=="string"){const e=OF[n];return e||(console.warn(`[player] unknown environment "${n}"; using neutral default`),null)}return n}const NF=new Proxy({},{get:()=>()=>{}});function lv(n){if(!n)return null;const e={};for(const t of Object.keys(n)){const i=n[t];typeof i=="number"&&Number.isFinite(i)&&(e[t]=i)}return e}const cv=48,mu=.14,UF=16,BF=16,zF=.003,HF=.05,VF=1.08,uv=4120,dv=5140,GF=0,$F=2200,WF=new S(0,700,0),XF=new S(-1,0,0),KF=new S(0,-1,0),qF=new S(0,900,0),YF=new S(0,1,0),jF=new S(9600,-5500,12600).normalize();function ZF(n,e){const t=Number.isFinite(e)&&e>0?e:1.7777777777777777,i=n==="overhead"?WF.clone():qF.clone(),s=n==="overhead"?XF.clone():YF.clone(),a=n==="overhead"?KF.clone():jF.clone(),r=JF({aspect:t,fov:cv,forward:a,margin:VF,target:i,up:s});return{position:i.clone().addScaledVector(a,-r),target:i,up:s,fov:cv}}function JF(n){const{aspect:e,fov:t,forward:i,margin:s,target:a,up:r}=n,o=i.clone().normalize(),l=new S().crossVectors(o,r).normalize(),c=new S().crossVectors(l,o).normalize(),u=Math.tan(vt.degToRad(t)/2),d=u*e;let h=1;for(const f of[-uv,uv])for(const p of[GF,$F])for(const g of[-dv,dv]){const _=new S(f,p,g).sub(a),m=Math.abs(_.dot(l)),v=Math.abs(_.dot(c)),y=_.dot(o);h=Math.max(h,m/d-y,v/u-y)}return Math.max(1,h*s)}function QF(n){const e=new Mt;return e.name="replayRoot",e.matrixAutoUpdate=!1,e.matrix.set(1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1),n.add(e),e}class eN extends EventTarget{container;adapter;replay;options;sceneManager;arenaManager;actorManager;effectsManager;hitboxManager;controls;replayRoot;sceneState;effectsEnabled;ready;plugins=[];beforeRenderCallbacks=[];resizeObserver=null;animationFrameId=null;disposed=!1;playing=!1;readyResolved=!1;speed;loop;currentTime=0;lastTickAt=null;freeCameraTransition=null;cameraDistanceScaleValue;customCameraSettingsValue;cameraViewModeValue;attachedPlayerIdValue;ballCamEnabledValue;boostMeterEnabledValue;boostPickupAnimationEnabledValue;hitboxWireframesEnabledValue;hitboxOnlyModeEnabledValue;hitboxTypeByName=null;hitboxTeamByName=null;hitboxesActive=!1;skipPostGoalTransitionsEnabledValue;skipKickoffsEnabledValue;attachmentTouched=!1;liveGameState=null;kickoffGameState=null;timelineSegmentsCacheKey=null;timelineSegmentsCache=[];constructor(e,t,i={},s=null){super(),this.container=e,this.adapter=t,this.replay=s,this.options=i,this.updateReplayGameStates(),this.speed=Math.max(.1,i.initialPlaybackRate??i.speed??1),this.loop=i.loop??!1,this.cameraDistanceScaleValue=Math.max(.25,i.initialCameraDistanceScale??1),this.customCameraSettingsValue=lv(i.initialCustomCameraSettings),this.attachedPlayerIdValue=i.initialAttachedPlayerId??null,this.cameraViewModeValue=i.initialCameraViewMode??(this.attachedPlayerIdValue?"follow":"free"),this.ballCamEnabledValue=i.initialBallCamEnabled??null,this.boostMeterEnabledValue=i.initialBoostMeterEnabled??!1,this.boostPickupAnimationEnabledValue=i.initialBoostPickupAnimationEnabled??!0,this.hitboxWireframesEnabledValue=i.initialHitboxWireframesEnabled??!1,this.hitboxOnlyModeEnabledValue=i.initialHitboxOnlyModeEnabled??!1,this.skipPostGoalTransitionsEnabledValue=i.initialSkipPostGoalTransitionsEnabled??!0,this.skipKickoffsEnabledValue=i.initialSkipKickoffsEnabled??!1,this.sceneManager=new yk(e,{assetBase:i.assetBase,preserveDrawingBuffer:i.preserveDrawingBuffer}),this.sceneManager.initDefaultEnvironment(),this.applyEnvironmentSpec(i.environment??kF),this.arenaManager=new lO(this.scene,{assetBase:i.assetBase}),this.effectsEnabled=i.effects??!0,this.effectsManager=this.effectsEnabled?new dF(this.scene):NF,this.actorManager=new JO(this.scene,this.effectsManager,{assetBase:i.assetBase}),i.motionInterpolation&&this.setMotionInterpolation(i.motionInterpolation),this.actorManager.initFromFramework(t),this.actorManager.initInterpolants(t.getTimelines()),this.hitboxManager=new pF(this.scene),this.syncGoalEvents(),this.controls=new QD(this.camera,this.renderer.domElement),this.controls.zoomSpeed=2.5,this.camera.position.set(0,4e3,6e3),this.controls.target.set(0,200,0),this.controls.update(),this.replayRoot=QF(this.scene),this.sceneState=this.createSceneState(),this.ready=Promise.all([this.arenaManager.loadArenaMeshes().catch(a=>{console.warn("[player] arena load failed",a)}),this.prepareReplayAssets()]).then(()=>{this.markReady()}),this.installResizeHandling();for(const a of i.plugins??[])this.installPlugin(a,!1);this.plugins.some(a=>a.plugin.id==="boost-pads")||this.installPlugin(_F(),!1),this.applyInitialCameraOptions(),this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded(),this.scheduleAnimationFrame(),this.emitChange(),i.autoplay&&this.play()}get scene(){return this.sceneManager.scene}get camera(){return this.sceneManager.camera}get renderer(){return this.sceneManager.renderer}get duration(){return this.adapter.duration}async replaceReplay(e,t,i={}){if(this.disposed)throw new Error("Cannot replace replay on a disposed ReplayPlayer");const s=i.preservePlayback??this.playing;this.playing&&this.setPlayingInternal(!1),this.teardownPlugins(),this.effectsManager.reset(),this.effectsManager.clearEvents?.(),this.hitboxManager.reset(),this.actorManager.reset(),this.adapter=e,this.replay=t,this.updateReplayGameStates(),this.timelineSegmentsCacheKey=null,this.timelineSegmentsCache=[],this.hitboxTypeByName=null,this.hitboxTeamByName=null,this.hitboxesActive=!1,this.freeCameraTransition=null,this.actorManager.initFromFramework(e),this.actorManager.initInterpolants(e.getTimelines()),this.syncGoalEvents();const a=this.attachedPlayerIdValue&&this.adapter.playerList.some(r=>r.id===this.attachedPlayerIdValue)?this.attachedPlayerIdValue:null;a!==this.attachedPlayerIdValue&&(this.attachedPlayerIdValue=a,this.cameraViewModeValue==="follow"&&(this.cameraViewModeValue="free")),this.seekInternal(i.currentTime??0),this.readyResolved=!1,this.ready=this.prepareReplayAssets().then(()=>{this.markReady()}),await this.ready,this.setupPlugins(),this.applyInitialCameraOptions(),this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded(),s&&this.setPlayingInternal(!0),this.render(),this.emitChange()}setEnvironment(e){this.applyEnvironmentSpec(e)}applyEnvironmentSpec(e){const t=FF(e);if(!t){this.sceneManager.setDefaultBackground();return}this.sceneManager.applyEnvironment(t).catch(i=>{console.warn(`[player] environment "${t.id}" failed to load`,i)})}play(){this.playing||(this.setPlayingInternal(!0),this.emitChange())}pause(){this.playing&&(this.setPlayingInternal(!1),this.emitChange())}togglePlayback(){this.playing?this.pause():this.play()}seek(e){this.seekInternal(e),this.playing&&(this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded()),this.emitChange()}setPlaybackRate(e){this.speed=Math.max(.1,e),this.emitChange()}setLoop(e){this.loop=e}setMotionInterpolation(e){this.actorManager.interpolationMethod=e==="linear"?"lerp":"hermite"}setFrameIndex(e){const t=this.adapter.frameTimes;if(t.length===0||!Number.isFinite(e))return;const i=Math.min(Math.max(Math.trunc(e),0),t.length-1);this.playing&&this.setPlayingInternal(!1),this.seekInternal(t[i]),this.emitChange()}stepFrames(e){Number.isFinite(e)&&this.setFrameIndex(this.adapter.frameIndexAt(this.currentTime)+Math.trunc(e))}stepForwardFrame(){this.stepFrames(1)}stepBackwardFrame(){this.stepFrames(-1)}setCameraDistanceScale(e){this.cameraDistanceScaleValue=Math.max(.25,e),this.getCameraPlugin()?.setDistanceScale(this.cameraDistanceScaleValue),this.emitChange()}setCustomCameraSettings(e){this.applyCustomCameraSettings(e),this.emitChange()}setAttachedPlayer(e){this.attachedPlayerIdValue=e,this.cameraViewModeValue=e?"follow":"free",this.attachmentTouched=!0,this.freeCameraTransition=null,this.syncCameraAttachment(),this.emitChange()}setCameraViewMode(e){this.cameraViewModeValue=e,this.attachmentTouched=!0,this.freeCameraTransition=null,this.syncCameraAttachment(),this.emitChange()}setFreeCameraPreset(e,t={}){this.cameraViewModeValue="free",this.attachmentTouched=!0,this.syncCameraAttachment();const i=ZF(e,this.camera.aspect);t.instant?(this.camera.position.copy(i.position),this.controls.target.copy(i.target),this.camera.up.copy(i.up).normalize(),this.camera.fov=i.fov,this.camera.updateProjectionMatrix(),this.camera.lookAt(i.target),this.controls.enabled=!0,this.freeCameraTransition=null):this.freeCameraTransition=i,this.emitChange()}setBallCamEnabled(e){this.ballCamEnabledValue=e,this.getCameraPlugin()?.setBallCam(e),this.emitChange()}setBoostMeterEnabled(e){this.boostMeterEnabledValue=e,this.emitChange()}setBoostPickupAnimationEnabled(e){this.boostPickupAnimationEnabledValue=e,this.emitChange()}setHitboxWireframesEnabled(e){this.hitboxWireframesEnabledValue=e,this.emitChange()}setHitboxOnlyModeEnabled(e){this.hitboxOnlyModeEnabledValue=e,this.emitChange()}setSkipPostGoalTransitionsEnabled(e){this.skipPostGoalTransitionsEnabledValue=e,e&&this.playing&&this.skipPostGoalTransitionIfNeeded(),this.emitChange()}setSkipKickoffsEnabled(e){this.skipKickoffsEnabledValue=e,e&&this.playing&&(this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded()),this.emitChange()}setState(e){e.speed!==void 0&&(this.speed=Math.max(.1,e.speed)),e.cameraDistanceScale!==void 0&&(this.cameraDistanceScaleValue=Math.max(.25,e.cameraDistanceScale),this.getCameraPlugin()?.setDistanceScale(this.cameraDistanceScaleValue)),e.customCameraSettings!==void 0&&this.applyCustomCameraSettings(e.customCameraSettings),e.cameraViewMode!==void 0&&(this.cameraViewModeValue=e.cameraViewMode,this.attachmentTouched=!0),e.attachedPlayerId!==void 0&&(this.attachedPlayerIdValue=e.attachedPlayerId,this.attachmentTouched=!0,e.cameraViewMode===void 0&&(this.cameraViewModeValue=e.attachedPlayerId?"follow":"free")),(e.cameraViewMode!==void 0||e.attachedPlayerId!==void 0)&&(this.freeCameraTransition=null,this.syncCameraAttachment()),e.useReplayBallCam===!0?(this.ballCamEnabledValue=null,this.getCameraPlugin()?.setBallCam(null)):e.ballCamEnabled!==void 0&&(this.ballCamEnabledValue=e.ballCamEnabled,this.getCameraPlugin()?.setBallCam(e.ballCamEnabled)),e.boostMeterEnabled!==void 0&&(this.boostMeterEnabledValue=e.boostMeterEnabled),e.boostPickupAnimationEnabled!==void 0&&(this.boostPickupAnimationEnabledValue=e.boostPickupAnimationEnabled),e.hitboxWireframesEnabled!==void 0&&(this.hitboxWireframesEnabledValue=e.hitboxWireframesEnabled),e.hitboxOnlyModeEnabled!==void 0&&(this.hitboxOnlyModeEnabledValue=e.hitboxOnlyModeEnabled),e.skipPostGoalTransitionsEnabled!==void 0&&(this.skipPostGoalTransitionsEnabledValue=e.skipPostGoalTransitionsEnabled),e.skipKickoffsEnabled!==void 0&&(this.skipKickoffsEnabledValue=e.skipKickoffsEnabled),e.currentTime!==void 0&&this.seekInternal(e.currentTime),e.playing!==void 0&&e.playing!==this.playing&&this.setPlayingInternal(e.playing),this.playing&&(e.currentTime!==void 0||e.playing!==void 0)&&(this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded()),this.emitChange()}getState(){const e=this.adapter.frameIndexAt(this.currentTime),t=this.getCameraPlugin();let i=this.cameraViewModeValue,s=this.attachedPlayerIdValue;if(t)if(t.getMode()==="follow"){i="follow";const a=t.getTarget();s=(a?this.adapter.playerList.find(o=>o.name===a):void 0)?.id??s}else i="free",s=null;return{currentTime:this.currentTime,duration:this.duration,frameIndex:e,activeMetadata:this.replay?CF(this.replay,e,this.currentTime):null,playing:this.playing,speed:this.speed,cameraDistanceScale:this.cameraDistanceScaleValue,customCameraSettings:this.customCameraSettingsValue,cameraViewMode:i,attachedPlayerId:s,ballCamEnabled:t?t.getBallCam():this.ballCamEnabledValue??!1,useReplayBallCam:this.ballCamEnabledValue===null,effectiveBallCamEnabled:t?t.getBallCam():this.ballCamEnabledValue??!1,boostMeterEnabled:this.boostMeterEnabledValue,boostPickupAnimationEnabled:this.boostPickupAnimationEnabledValue,hitboxWireframesEnabled:this.hitboxWireframesEnabledValue,hitboxOnlyModeEnabled:this.hitboxOnlyModeEnabledValue,skipPostGoalTransitionsEnabled:this.skipPostGoalTransitionsEnabledValue,skipKickoffsEnabled:this.skipKickoffsEnabledValue}}getSnapshot(){return this.getState()}getTimelineDuration(){return this.replay?.duration??this.duration}getTimelineCurrentTime(){return this.projectReplayTimeToTimeline(this.currentTime).timelineTime}getTimelineSegments(){if(!this.replay)return[];const e=`${this.skipPostGoalTransitionsEnabledValue}:${this.skipKickoffsEnabledValue}`;return this.timelineSegmentsCacheKey===e?this.timelineSegmentsCache:(this.timelineSegmentsCacheKey=e,this.timelineSegmentsCache=SF(this.replay,this.skipPostGoalTransitionsEnabledValue,this.skipKickoffsEnabledValue,this.liveGameState,this.kickoffGameState),this.timelineSegmentsCache)}projectReplayTimeToTimeline(e){return TF(this.replay?.duration??this.duration,this.getTimelineSegments(),e)}projectTimelineTimeToReplay(e){return MF(this.replay?.duration??this.duration,this.getTimelineDuration(),this.getTimelineSegments(),e)}subscribe(e){const t=i=>{e(i.detail)};return this.addEventListener("change",t),e(this.getState()),()=>{this.removeEventListener("change",t)}}onBeforeRender(e){return this.beforeRenderCallbacks.push(e),()=>{const t=this.beforeRenderCallbacks.indexOf(e);t>=0&&this.beforeRenderCallbacks.splice(t,1)}}addPlugin(e){return this.installPlugin(e,!0)}removePlugin(e){const t=this.plugins.findIndex(s=>s.plugin.id===e);if(t<0)return!1;const[i]=this.plugins.splice(t,1);return i.plugin.teardown?.(this.createPluginContext()),!0}getPlugins(){return this.plugins.map(e=>e.plugin)}destroy(){if(!this.disposed){for(this.disposed=!0,this.playing=!1,this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.beforeRenderCallbacks.length=0;this.plugins.length>0;)this.plugins.pop()?.plugin.teardown?.(this.createPluginContext());this.controls.dispose(),this.effectsEnabled&&this.effectsManager.reset(),this.hitboxManager.dispose(),this.actorManager.reset(),this.sceneManager.dispose()}}dispose(){this.destroy()}setPlayingInternal(e){this.playing=e,this.lastTickAt=null,e?this.actorManager.resumeAnimations():this.actorManager.pauseAnimations()}prepareReplayAssets(){return this.actorManager.waitForBallModel().catch(()=>!1).then(()=>{if(this.effectsEnabled)try{this.effectsManager.setRenderContext(this.renderer,this.camera)}catch(e){console.warn("[player] explosion warmup failed",e)}})}markReady(){this.readyResolved=!0,this.lastTickAt=null}updateReplayGameStates(){if(!this.replay){this.liveGameState=null,this.kickoffGameState=null;return}this.liveGameState=yF(this.replay),this.kickoffGameState=vF(this.replay,this.liveGameState)}syncGoalEvents(){this.effectsEnabled&&(this.effectsManager.clearEvents?.(),this.replay&&this.effectsManager.setGoalEvents(this.replay.timelineEvents.filter(e=>e.kind==="goal").map(e=>({frame:e.frame,time:e.time,team:e.isTeamZero?0:1,playerName:e.playerName??""}))))}teardownPlugins(){const e=this.createPluginContext();for(const t of this.plugins)t.plugin.teardown?.(e)}setupPlugins(){for(const e of this.plugins)e.plugin.setup?.(this.createPluginContext()),e.plugin.id==="camera"&&this.pushCameraParityState(),e.plugin.onStateChange?.(this.createPluginStateContext(this.getState()))}seekInternal(e){this.currentTime=vt.clamp(e,0,this.duration),this.actorManager.seekAnimations(this.currentTime),this.effectsManager.resetBallTrail(),this.effectsManager.clearGoalExplosions?.(),this.actorManager.resetGoalExplosionPlaybackState(),this.actorManager.resetWheelTracking()}getPlaybackEndTime(){return this.replay?EF(this.replay.duration,this.getTimelineSegments()):this.duration}skipPastKickoffIfNeeded(){if(!this.replay||!this.skipKickoffsEnabledValue)return!1;const e=PF(this.replay,this.currentTime,this.liveGameState,this.kickoffGameState);return e===null?!1:(this.seekInternal(e),!0)}skipPostGoalTransitionIfNeeded(){if(!this.replay||!this.skipPostGoalTransitionsEnabledValue)return!1;const e=IF(this.replay,this.currentTime,this.liveGameState,this.kickoffGameState);return e===null?!1:(this.seekInternal(e),!0)}getCameraPlugin(){const e=this.plugins.find(t=>t.plugin.id==="camera")?.plugin;return e&&typeof e.follow=="function"?e:null}playerNameForId(e){return this.adapter.playerList.find(t=>t.id===e)?.name??null}applyReplayBallCam(){if(this.ballCamEnabledValue!==null||this.cameraViewModeValue!=="follow"||!this.attachedPlayerIdValue)return;const e=this.playerNameForId(this.attachedPlayerIdValue);if(!e)return;const t=this.adapter.getAllPlayers().find(i=>i.name===e);t&&this.getCameraPlugin()?.setBallCam(t.isBallCam)}syncCameraAttachment(){const e=this.getCameraPlugin();if(e){if(this.cameraViewModeValue==="follow"&&this.attachedPlayerIdValue){const t=this.playerNameForId(this.attachedPlayerIdValue);if(!t){console.warn(`[player] no player with id ${JSON.stringify(this.attachedPlayerIdValue)}`);return}this.camera.up.set(0,1,0),e.follow(t);return}e.getMode()==="follow"&&e.release()}}applyCustomCameraSettings(e){this.customCameraSettingsValue=lv(e);const t=this.getCameraPlugin();t&&(t.setCameraSettings(null),this.customCameraSettingsValue&&t.setCameraSettings(this.customCameraSettingsValue))}pushCameraParityState(){const e=this.getCameraPlugin();e&&(this.cameraDistanceScaleValue!==1&&e.setDistanceScale(this.cameraDistanceScaleValue),this.customCameraSettingsValue&&e.setCameraSettings(this.customCameraSettingsValue),this.ballCamEnabledValue!==null&&e.setBallCam(this.ballCamEnabledValue),this.attachmentTouched&&this.syncCameraAttachment())}applyInitialCameraOptions(){const e=this.options;(e.initialAttachedPlayerId!==void 0||e.initialCameraViewMode!==void 0)&&(this.attachmentTouched=!0),this.pushCameraParityState()}computeFrameRenderInfo(){const e=this.adapter.frameTimes,t=this.adapter.frameIndexAt(this.currentTime),i=Math.min(t+1,Math.max(e.length-1,0)),s=e[t]??0,a=e[i]??s,r=a>s?vt.clamp((this.currentTime-s)/(a-s),0,1):0;return{frameIndex:t,nextFrameIndex:i,alpha:r,currentTime:this.currentTime}}installResizeHandling(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>this.sceneManager.onWindowResize()),this.resizeObserver.observe(this.container))}scheduleAnimationFrame(){this.animationFrameId!==null||this.disposed||(this.animationFrameId=requestAnimationFrame(this.tick))}tick=e=>{if(this.animationFrameId=null,this.disposed)return;let t=!1,i=0;if(this.playing&&this.readyResolved){i=this.lastTickAt===null?0:Math.min(.1,(e-this.lastTickAt)/1e3),this.lastTickAt=e;let s=this.currentTime+i*this.speed;const a=this.getPlaybackEndTime();s>=a&&(this.loop?(s=0,this.actorManager.seekAnimations(0),this.effectsManager.resetBallTrail(),this.effectsManager.clearGoalExplosions?.(),this.actorManager.resetGoalExplosionPlaybackState(),this.actorManager.resetWheelTracking()):(s=a,this.playing=!1)),t=s!==this.currentTime||!this.playing,this.currentTime=s,this.playing&&(t=this.skipPostGoalTransitionIfNeeded()||t,t=this.skipPastKickoffIfNeeded()||t)}else this.playing&&(this.lastTickAt=null);this.render(i),t&&this.emitChange(),this.scheduleAnimationFrame()};renderFrame(e=0){if(this.adapter.seek(this.currentTime),this.playing&&this.actorManager.updateAnimations(e*this.speed),this.actorManager.updateFromFramework(this.adapter,this.currentTime),this.updatePlayerStates(),this.applyReplayBallCam(),this.updateHitboxVisualization(),this.effectsManager.update(e,this.playing,this.speed),this.playing&&this.actorManager.updateWheelRotations(),this.sceneManager.updateSkyboxAnimation(this.playing?e*this.speed:0),this.controls.update(),this.beforeRenderCallbacks.length>0){const t=this.computeFrameRenderInfo();for(const i of[...this.beforeRenderCallbacks])i(t)}if(this.plugins.length>0){const t=this.createRenderContext();for(const i of this.plugins)i.plugin.beforeRender?.(t)}this.updateFreeCameraTransition(),this.renderer.render(this.scene,this.camera)}render(e=0){this.renderFrame(e)}updateFreeCameraTransition(){const e=this.freeCameraTransition;if(!e)return;this.controls.enabled=!1,this.camera.position.lerp(e.position,mu),this.controls.target.lerp(e.target,mu),this.camera.up.lerp(e.up,mu).normalize(),this.camera.fov=vt.lerp(this.camera.fov,e.fov,mu),this.camera.updateProjectionMatrix(),this.camera.lookAt(this.controls.target);const t=this.camera.position.distanceToSquared(e.position)<=UF,i=this.controls.target.distanceToSquared(e.target)<=BF,s=this.camera.up.angleTo(e.up)<=zF,a=Math.abs(this.camera.fov-e.fov)<=HF;!t||!i||!s||!a||(this.camera.position.copy(e.position),this.controls.target.copy(e.target),this.camera.up.copy(e.up).normalize(),this.camera.fov=e.fov,this.camera.updateProjectionMatrix(),this.camera.lookAt(e.target),this.controls.enabled=!0,this.freeCameraTransition=null)}updatePlayerStates(){if(!this.playing)return;const e=this.hitboxOnlyModeEnabledValue;for(const t of this.adapter.getAllPlayers())this.actorManager.updateBoostState(t.name,t.isBoosting&&!e,t.isKickoffReset),this.actorManager.updateSupersonicState(t.name,t.isSupersonic&&!e,t.team)}updateHitboxVisualization(){const e=this.hitboxWireframesEnabledValue||this.hitboxOnlyModeEnabledValue;if(!e&&!this.hitboxesActive||(this.hitboxesActive=e,this.hitboxManager.setEnabled(e),!e))return;const t=this.actorManager;if(this.hitboxTypeByName||(this.hitboxTypeByName=new Map(this.adapter.getAllPlayers().map(i=>[i.name,i.hitboxType]))),this.hitboxTeamByName||(this.hitboxTeamByName=new Map(this.adapter.getAllPlayers().map(i=>[i.name,i.team]))),this.hitboxManager.updateHitboxes(t.actors,t.playerNameToCarActorId,i=>this.hitboxTypeByName?.get(i)??"Octane",i=>this.hitboxTeamByName?.get(i)??null),this.hitboxOnlyModeEnabledValue)for(const i of Object.values(t.playerNameToCarActorId)){const s=i===void 0?void 0:t.actors[i];s&&(s.visible=!1)}}installPlugin(e,t){const i=typeof e=="function"?e():e;if(this.plugins.some(a=>a.plugin.id===i.id))throw new Error(`Player plugin "${i.id}" is already installed`);const s={definition:e,plugin:i};return this.plugins.push(s),i.setup?.(this.createPluginContext()),i.id==="camera"&&this.pushCameraParityState(),i.onStateChange?.(this.createPluginStateContext(this.getState())),t&&this.render(),()=>{const a=this.plugins.indexOf(s);a<0||(this.plugins.splice(a,1),i.teardown?.(this.createPluginContext()))}}createSceneState(){const e=this.actorManager,t=this,i=new we;return{get scene(){return t.scene},replayRoot:this.replayRoot,get camera(){return t.camera},get renderer(){return t.renderer},controls:this.controls,resize:()=>this.sceneManager.onWindowResize(),dispose:()=>this.destroy(),get ballMesh(){return(e.ballActorId!=null?e.actors[e.ballActorId]:null)??i},get playerMeshes(){const s=new Map;for(const a of t.adapter.playerList){const r=e.playerNameToCarActorId[a.name],o=r!=null?e.actors[r]:void 0;o&&s.set(a.id,o)}return s},playerBodyMeshes:new Map,playerHitboxes:new Map,playerBoostTrails:new Map,playerBoostMeters:new Map,playerDemoIndicators:new Map,updateWallVisibility:()=>{}}}createPluginContext(){return{player:this,replay:this.replay,options:this.options,scene:this.scene,camera:this.camera,renderer:this.renderer,container:this.container}}createPluginStateContext(e){return{...this.createPluginContext(),state:e}}createRenderContext(){const e=this.actorManager,t=this.adapter.ball,i={position:t.position,rotation:t.rotation,velocity:t.velocity,visible:t.visible,object3d:e.ballActorId!=null?e.actors[e.ballActorId]??null:null},s=this.adapter.getAllPlayers().map(a=>{const r=e.playerNameToCarActorId[a.name];return{id:a.id,name:a.name,team:a.team,carName:a.carName,hitboxType:a.hitboxType,position:a.position,rotation:a.rotation,velocity:a.velocity,boost:a.boost,isBoosting:a.isBoosting,visible:a.isVisible,object3d:r!=null?e.actors[r]??null:null}});return{...this.createPluginContext(),...this.computeFrameRenderInfo(),state:this.getState(),time:this.currentTime,ball:i,cars:s}}emitChange(){const e=this.getState(),t=this.createPluginStateContext(e);for(const i of this.plugins)i.plugin.onStateChange?.(t);this.dispatchEvent(new CustomEvent("change",{detail:e}))}}const Wt={LEFT:1,RIGHT:2,MIDDLE:4},$=Object.freeze({NONE:0,ROTATE:1,TRUCK:2,SCREEN_PAN:4,OFFSET:8,DOLLY:16,ZOOM:32,TOUCH_ROTATE:64,TOUCH_TRUCK:128,TOUCH_SCREEN_PAN:256,TOUCH_OFFSET:512,TOUCH_DOLLY:1024,TOUCH_ZOOM:2048,TOUCH_DOLLY_TRUCK:4096,TOUCH_DOLLY_SCREEN_PAN:8192,TOUCH_DOLLY_OFFSET:16384,TOUCH_DOLLY_ROTATE:32768,TOUCH_ZOOM_TRUCK:65536,TOUCH_ZOOM_OFFSET:131072,TOUCH_ZOOM_SCREEN_PAN:262144,TOUCH_ZOOM_ROTATE:524288}),Hr={NONE:0,IN:1,OUT:-1};function La(n){return n.isPerspectiveCamera}function Js(n){return n.isOrthographicCamera}const Vr=Math.PI*2,hv=Math.PI/2,RT=1e-5,Qo=Math.PI/180;function Ni(n,e,t){return Math.max(e,Math.min(t,n))}function Ot(n,e=RT){return Math.abs(n)0==f>u&&(f=u,t.value=(f-u)/a),f}function pv(n,e,t,i,s=1/0,a,r){i=Math.max(1e-4,i);const o=2/i,l=o*a,c=1/(1+l+.48*l*l+.235*l*l*l);let u=e.x,d=e.y,h=e.z,f=n.x-u,p=n.y-d,g=n.z-h;const _=u,m=d,v=h,y=s*i,b=y*y,T=f*f+p*p+g*g;if(T>b){const U=Math.sqrt(T);f=f/U*y,p=p/U*y,g=g/U*y}u=n.x-f,d=n.y-p,h=n.z-g;const x=(t.x+o*f)*a,M=(t.y+o*p)*a,C=(t.z+o*g)*a;t.x=(t.x-o*x)*c,t.y=(t.y-o*M)*c,t.z=(t.z-o*C)*c,r.x=u+(f+x)*c,r.y=d+(p+M)*c,r.z=h+(g+C)*c;const w=_-n.x,E=m-n.y,R=v-n.z,D=r.x-_,O=r.y-m,k=r.z-v;return w*D+E*O+R*k>0&&(r.x=_,r.y=m,r.z=v,t.x=(r.x-_)/a,t.y=(r.y-m)/a,t.z=(r.z-v)/a),r}function yp(n,e){e.set(0,0),n.forEach(t=>{e.x+=t.clientX,e.y+=t.clientY}),e.x/=n.length,e.y/=n.length}function vp(n,e){return Js(n)?(console.warn(`${e} is not supported in OrthographicCamera`),!0):!1}class tN{constructor(){this._listeners={}}addEventListener(e,t){const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){const i=this._listeners;return i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){const s=this._listeners[e];if(s!==void 0){const a=s.indexOf(t);a!==-1&&s.splice(a,1)}}removeAllEventListeners(e){if(!e){this._listeners={};return}Array.isArray(this._listeners[e])&&(this._listeners[e].length=0)}dispatchEvent(e){const i=this._listeners[e.type];if(i!==void 0){e.target=this;const s=i.slice(0);for(let a=0,r=s.length;a{},this._enabled=!0,this._state=$.NONE,this._viewport=null,this._changedDolly=0,this._changedZoom=0,this._hasRested=!0,this._boundaryEnclosesCamera=!1,this._needsUpdate=!0,this._updatedLastTime=!1,this._elementRect=new DOMRect,this._isDragging=!1,this._dragNeedsUpdate=!0,this._activePointers=[],this._lockedPointer=null,this._interactiveArea=new DOMRect(0,0,1,1),this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._isUserControllingOffset=!1,this._isUserControllingZoom=!1,this._lastDollyDirection=Hr.NONE,this._thetaVelocity={value:0},this._phiVelocity={value:0},this._radiusVelocity={value:0},this._targetVelocity=new tt.Vector3,this._focalOffsetVelocity=new tt.Vector3,this._zoomVelocity={value:0},this._truckInternal=(m,v,y,b)=>{let T,x;if(La(this._camera)){const M=ft.copy(this._camera.position).sub(this._target),C=this._camera.getEffectiveFOV()*Qo,w=M.length()*Math.tan(C*.5);T=this.truckSpeed*m*w/this._elementRect.height,x=this.truckSpeed*v*w/this._elementRect.height}else if(Js(this._camera)){const M=this._camera;T=this.truckSpeed*m*(M.right-M.left)/M.zoom/this._elementRect.width,x=this.truckSpeed*v*(M.top-M.bottom)/M.zoom/this._elementRect.height}else return;b?(y?this.setFocalOffset(this._focalOffsetEnd.x+T,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(T,0,!0),this.forward(-x,!0)):y?this.setFocalOffset(this._focalOffsetEnd.x+T,this._focalOffsetEnd.y+x,this._focalOffsetEnd.z,!0):this.truck(T,x,!0)},this._rotateInternal=(m,v)=>{const y=Vr*this.azimuthRotateSpeed*m/this._elementRect.height,b=Vr*this.polarRotateSpeed*v/this._elementRect.height;this.rotate(y,b,!0)},this._dollyInternal=(m,v,y)=>{const b=Math.pow(.95,-m*this.dollySpeed),T=this._sphericalEnd.radius,x=this._sphericalEnd.radius*b,M=Ni(x,this.minDistance,this.maxDistance),C=M-x;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(x,!0):this.infinityDolly&&!this.dollyToCursor?(this.dollyInFixed(C,!0),this._dollyToNoClamp(M,!0)):this._dollyToNoClamp(M,!0),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?x:M)-T,this._dollyControlCoord.set(v,y)),this._lastDollyDirection=Math.sign(-m)},this._zoomInternal=(m,v,y)=>{const b=Math.pow(.95,m*this.dollySpeed),T=this._zoom,x=this._zoom*b;this.zoomTo(x,!0),this.dollyToCursor&&(this._changedZoom+=x-T,this._dollyControlCoord.set(v,y))},typeof tt>"u"&&console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information."),this._camera=e,this._yAxisUpSpace=new tt.Quaternion().setFromUnitVectors(this._camera.up,yu),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=$.NONE,this._target=new tt.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new tt.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=new tt.Spherical().setFromVector3(ft.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace)),this._sphericalEnd=this._spherical.clone(),this._lastDistance=this._spherical.radius,this._zoom=this._camera.zoom,this._zoomEnd=this._zoom,this._lastZoom=this._zoom,this._nearPlaneCorners=[new tt.Vector3,new tt.Vector3,new tt.Vector3,new tt.Vector3],this._updateNearPlaneCorners(),this._boundary=new tt.Box3(new tt.Vector3(-1/0,-1/0,-1/0),new tt.Vector3(1/0,1/0,1/0)),this._cameraUp0=this._camera.up.clone(),this._target0=this._target.clone(),this._position0=this._camera.position.clone(),this._zoom0=this._zoom,this._focalOffset0=this._focalOffset.clone(),this._dollyControlCoord=new tt.Vector2,this.mouseButtons={left:$.ROTATE,middle:$.DOLLY,right:$.TRUCK,wheel:La(this._camera)?$.DOLLY:Js(this._camera)?$.ZOOM:$.NONE},this.touches={one:$.TOUCH_ROTATE,two:La(this._camera)?$.TOUCH_DOLLY_TRUCK:Js(this._camera)?$.TOUCH_ZOOM_TRUCK:$.NONE,three:$.TOUCH_TRUCK};const i=new tt.Vector2,s=new tt.Vector2,a=new tt.Vector2,r=m=>{if(!this._enabled||!this._domElement)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const b=this._domElement.getBoundingClientRect(),T=m.clientX/b.width,x=m.clientY/b.height;if(Tthis._interactiveArea.right||xthis._interactiveArea.bottom)return}const v=m.pointerType!=="mouse"?null:(m.buttons&Wt.LEFT)===Wt.LEFT?Wt.LEFT:(m.buttons&Wt.MIDDLE)===Wt.MIDDLE?Wt.MIDDLE:(m.buttons&Wt.RIGHT)===Wt.RIGHT?Wt.RIGHT:null;if(v!==null){const b=this._findPointerByMouseButton(v);b&&this._disposePointer(b)}if((m.buttons&Wt.LEFT)===Wt.LEFT&&this._lockedPointer)return;const y={pointerId:m.pointerId,clientX:m.clientX,clientY:m.clientY,deltaX:0,deltaY:0,mouseButton:v};this._activePointers.push(y),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),this._isDragging=!0,h(m)},o=m=>{m.cancelable&&m.preventDefault();const v=m.pointerId,y=this._lockedPointer||this._findPointerById(v);if(y){if(y.clientX=m.clientX,y.clientY=m.clientY,y.deltaX=m.movementX,y.deltaY=m.movementY,this._state=0,m.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else(!this._isDragging&&this._lockedPointer||this._isDragging&&(m.buttons&Wt.LEFT)===Wt.LEFT)&&(this._state=this._state|this.mouseButtons.left),this._isDragging&&(m.buttons&Wt.MIDDLE)===Wt.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),this._isDragging&&(m.buttons&Wt.RIGHT)===Wt.RIGHT&&(this._state=this._state|this.mouseButtons.right);f()}},l=m=>{const v=this._findPointerById(m.pointerId);if(!(v&&v===this._lockedPointer)){if(v&&this._disposePointer(v),m.pointerType==="touch")switch(this._activePointers.length){case 0:this._state=$.NONE;break;case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else this._state=$.NONE;p()}};let c=-1;const u=m=>{if(!this._domElement||!this._enabled||this.mouseButtons.wheel===$.NONE)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const x=this._domElement.getBoundingClientRect(),M=m.clientX/x.width,C=m.clientY/x.height;if(Mthis._interactiveArea.right||Cthis._interactiveArea.bottom)return}if(m.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===$.ROTATE||this.mouseButtons.wheel===$.TRUCK){const x=performance.now();c-x<1e3&&this._getClientRect(this._elementRect),c=x}const v=iN?-1:-3,y=m.deltaMode===1||m.ctrlKey?m.deltaY/v:m.deltaY/(v*10),b=this.dollyToCursor?(m.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,T=this.dollyToCursor?(m.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case $.ROTATE:{this._rotateInternal(m.deltaX,m.deltaY),this._isUserControllingRotate=!0;break}case $.TRUCK:{this._truckInternal(m.deltaX,m.deltaY,!1,!1),this._isUserControllingTruck=!0;break}case $.SCREEN_PAN:{this._truckInternal(m.deltaX,m.deltaY,!1,!0),this._isUserControllingTruck=!0;break}case $.OFFSET:{this._truckInternal(m.deltaX,m.deltaY,!0,!1),this._isUserControllingOffset=!0;break}case $.DOLLY:{this._dollyInternal(-y,b,T),this._isUserControllingDolly=!0;break}case $.ZOOM:{this._zoomInternal(-y,b,T),this._isUserControllingZoom=!0;break}}this.dispatchEvent({type:"control"})},d=m=>{if(!(!this._domElement||!this._enabled)){if(this.mouseButtons.right===km.ACTION.NONE){const v=m instanceof PointerEvent?m.pointerId:0,y=this._findPointerById(v);y&&this._disposePointer(y),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l);return}m.preventDefault()}},h=m=>{if(!this._enabled)return;if(yp(this._activePointers,Kn),this._getClientRect(this._elementRect),i.copy(Kn),s.copy(Kn),this._activePointers.length>=2){const y=Kn.x-this._activePointers[1].clientX,b=Kn.y-this._activePointers[1].clientY,T=Math.sqrt(y*y+b*b);a.set(0,T);const x=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,M=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;s.set(x,M)}if(this._state=0,!m)this._lockedPointer&&(this._state=this._state|this.mouseButtons.left);else if("pointerType"in m&&m.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else!this._lockedPointer&&(m.buttons&Wt.LEFT)===Wt.LEFT&&(this._state=this._state|this.mouseButtons.left),(m.buttons&Wt.MIDDLE)===Wt.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),(m.buttons&Wt.RIGHT)===Wt.RIGHT&&(this._state=this._state|this.mouseButtons.right);((this._state&$.ROTATE)===$.ROTATE||(this._state&$.TOUCH_ROTATE)===$.TOUCH_ROTATE||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE)&&(this._sphericalEnd.theta=this._spherical.theta,this._sphericalEnd.phi=this._spherical.phi,this._thetaVelocity.value=0,this._phiVelocity.value=0),((this._state&$.TRUCK)===$.TRUCK||(this._state&$.SCREEN_PAN)===$.SCREEN_PAN||(this._state&$.TOUCH_TRUCK)===$.TOUCH_TRUCK||(this._state&$.TOUCH_SCREEN_PAN)===$.TOUCH_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN)&&(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),((this._state&$.DOLLY)===$.DOLLY||(this._state&$.TOUCH_DOLLY)===$.TOUCH_DOLLY||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE)&&(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),((this._state&$.ZOOM)===$.ZOOM||(this._state&$.TOUCH_ZOOM)===$.TOUCH_ZOOM||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_ZOOM_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE)&&(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),((this._state&$.OFFSET)===$.OFFSET||(this._state&$.TOUCH_OFFSET)===$.TOUCH_OFFSET||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET)&&(this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0)),this.dispatchEvent({type:"controlstart"})},f=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,yp(this._activePointers,Kn);const v=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,y=v?-v.deltaX:s.x-Kn.x,b=v?-v.deltaY:s.y-Kn.y;if(s.copy(Kn),((this._state&$.ROTATE)===$.ROTATE||(this._state&$.TOUCH_ROTATE)===$.TOUCH_ROTATE||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE)&&(this._rotateInternal(y,b),this._isUserControllingRotate=!0),(this._state&$.DOLLY)===$.DOLLY||(this._state&$.ZOOM)===$.ZOOM){const T=this.dollyToCursor?(i.x-this._elementRect.x)/this._elementRect.width*2-1:0,x=this.dollyToCursor?(i.y-this._elementRect.y)/this._elementRect.height*-2+1:0,M=this.dollyDragInverted?-1:1;(this._state&$.DOLLY)===$.DOLLY?(this._dollyInternal(M*b*gu,T,x),this._isUserControllingDolly=!0):(this._zoomInternal(M*b*gu,T,x),this._isUserControllingZoom=!0)}if((this._state&$.TOUCH_DOLLY)===$.TOUCH_DOLLY||(this._state&$.TOUCH_ZOOM)===$.TOUCH_ZOOM||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_ZOOM_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE){const T=Kn.x-this._activePointers[1].clientX,x=Kn.y-this._activePointers[1].clientY,M=Math.sqrt(T*T+x*x),C=a.y-M;a.set(0,M);const w=this.dollyToCursor?(s.x-this._elementRect.x)/this._elementRect.width*2-1:0,E=this.dollyToCursor?(s.y-this._elementRect.y)/this._elementRect.height*-2+1:0;(this._state&$.TOUCH_DOLLY)===$.TOUCH_DOLLY||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET?(this._dollyInternal(C*gu,w,E),this._isUserControllingDolly=!0):(this._zoomInternal(C*gu,w,E),this._isUserControllingZoom=!0)}((this._state&$.TRUCK)===$.TRUCK||(this._state&$.TOUCH_TRUCK)===$.TOUCH_TRUCK||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK)&&(this._truckInternal(y,b,!1,!1),this._isUserControllingTruck=!0),((this._state&$.SCREEN_PAN)===$.SCREEN_PAN||(this._state&$.TOUCH_SCREEN_PAN)===$.TOUCH_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_ZOOM_SCREEN_PAN)&&(this._truckInternal(y,b,!1,!0),this._isUserControllingTruck=!0),((this._state&$.OFFSET)===$.OFFSET||(this._state&$.TOUCH_OFFSET)===$.TOUCH_OFFSET||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET)&&(this._truckInternal(y,b,!0,!1),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},p=()=>{yp(this._activePointers,Kn),s.copy(Kn),this._dragNeedsUpdate=!1,(this._activePointers.length===0||this._activePointers.length===1&&this._activePointers[0]===this._lockedPointer)&&(this._isDragging=!1),this._activePointers.length===0&&this._domElement&&(this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this.dispatchEvent({type:"controlend"}))};this.lockPointer=()=>{!this._enabled||!this._domElement||(this.cancel(),this._lockedPointer={pointerId:-1,clientX:0,clientY:0,deltaX:0,deltaY:0,mouseButton:null},this._activePointers.push(this._lockedPointer),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.requestPointerLock(),this._domElement.ownerDocument.addEventListener("pointerlockchange",g),this._domElement.ownerDocument.addEventListener("pointerlockerror",_),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),h())},this.unlockPointer=()=>{var m,v,y;this._lockedPointer!==null&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),(m=this._domElement)===null||m===void 0||m.ownerDocument.exitPointerLock(),(v=this._domElement)===null||v===void 0||v.ownerDocument.removeEventListener("pointerlockchange",g),(y=this._domElement)===null||y===void 0||y.ownerDocument.removeEventListener("pointerlockerror",_),this.cancel()};const g=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},_=()=>{this.unlockPointer()};this._addAllEventListeners=m=>{this._domElement=m,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",r),this._domElement.addEventListener("pointercancel",l),this._domElement.addEventListener("wheel",u,{passive:!1}),this._domElement.addEventListener("contextmenu",d)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect="",this._domElement.removeEventListener("pointerdown",r),this._domElement.removeEventListener("pointercancel",l),this._domElement.removeEventListener("wheel",u,{passive:!1}),this._domElement.removeEventListener("contextmenu",d),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.removeEventListener("pointerlockchange",g),this._domElement.ownerDocument.removeEventListener("pointerlockerror",_))},this.cancel=()=>{this._state!==$.NONE&&(this._state=$.NONE,this._activePointers.length=0,p())},t&&this.connect(t),this.update(0)}get camera(){return this._camera}set camera(e){this._camera=e,this.updateCameraUp(),this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0}get enabled(){return this._enabled}set enabled(e){this._enabled=e,this._domElement&&(e?(this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none"):(this.cancel(),this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect=""))}get active(){return!this._hasRested}get currentAction(){return this._state}get distance(){return this._spherical.radius}set distance(e){this._spherical.radius===e&&this._sphericalEnd.radius===e||(this._spherical.radius=e,this._sphericalEnd.radius=e,this._needsUpdate=!0)}get azimuthAngle(){return this._spherical.theta}set azimuthAngle(e){this._spherical.theta===e&&this._sphericalEnd.theta===e||(this._spherical.theta=e,this._sphericalEnd.theta=e,this._needsUpdate=!0)}get polarAngle(){return this._spherical.phi}set polarAngle(e){this._spherical.phi===e&&this._sphericalEnd.phi===e||(this._spherical.phi=e,this._sphericalEnd.phi=e,this._needsUpdate=!0)}get boundaryEnclosesCamera(){return this._boundaryEnclosesCamera}set boundaryEnclosesCamera(e){this._boundaryEnclosesCamera=e,this._needsUpdate=!0}set interactiveArea(e){this._interactiveArea.width=Ni(e.width,0,1),this._interactiveArea.height=Ni(e.height,0,1),this._interactiveArea.x=Ni(e.x,0,1-this._interactiveArea.width),this._interactiveArea.y=Ni(e.y,0,1-this._interactiveArea.height)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}rotate(e,t,i=!1){return this.rotateTo(this._sphericalEnd.theta+e,this._sphericalEnd.phi+t,i)}rotateAzimuthTo(e,t=!1){return this.rotateTo(e,this._sphericalEnd.phi,t)}rotatePolarTo(e,t=!1){return this.rotateTo(this._sphericalEnd.theta,e,t)}rotateTo(e,t,i=!1){this._isUserControllingRotate=!1;const s=Ni(e,this.minAzimuthAngle,this.maxAzimuthAngle),a=Ni(t,this.minPolarAngle,this.maxPolarAngle);this._sphericalEnd.theta=s,this._sphericalEnd.phi=a,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,i||(this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi);const r=!i||Ct(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ct(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(r)}dolly(e,t=!1){return this.dollyTo(this._sphericalEnd.radius-e,t)}dollyTo(e,t=!1){return this._isUserControllingDolly=!1,this._lastDollyDirection=Hr.NONE,this._changedDolly=0,this._dollyToNoClamp(Ni(e,this.minDistance,this.maxDistance),t)}_dollyToNoClamp(e,t=!1){const i=this._sphericalEnd.radius;if(this.colliderMeshes.length>=1){const r=this._collisionTest(),o=Ct(r,this._spherical.radius);if(!(i>e)&&o)return Promise.resolve();this._sphericalEnd.radius=Math.min(e,r)}else this._sphericalEnd.radius=e;this._needsUpdate=!0,t||(this._spherical.radius=this._sphericalEnd.radius);const a=!t||Ct(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(a)}dollyInFixed(e,t=!1){this._targetEnd.add(this._getCameraDirection(nl).multiplyScalar(e)),t||this._target.copy(this._targetEnd);const i=!t||Ct(this._target.x,this._targetEnd.x,this.restThreshold)&&Ct(this._target.y,this._targetEnd.y,this.restThreshold)&&Ct(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(i)}zoom(e,t=!1){return this.zoomTo(this._zoomEnd+e,t)}zoomTo(e,t=!1){this._isUserControllingZoom=!1,this._zoomEnd=Ni(e,this.minZoom,this.maxZoom),this._needsUpdate=!0,t||(this._zoom=this._zoomEnd);const i=!t||Ct(this._zoom,this._zoomEnd,this.restThreshold);return this._changedZoom=0,this._createOnRestPromise(i)}pan(e,t,i=!1){return console.warn("`pan` has been renamed to `truck`"),this.truck(e,t,i)}truck(e,t,i=!1){this._camera.updateMatrix(),es.setFromMatrixColumn(this._camera.matrix,0),ts.setFromMatrixColumn(this._camera.matrix,1),es.multiplyScalar(e),ts.multiplyScalar(-t);const s=ft.copy(es).add(ts),a=Tt.copy(this._targetEnd).add(s);return this.moveTo(a.x,a.y,a.z,i)}forward(e,t=!1){ft.setFromMatrixColumn(this._camera.matrix,0),ft.crossVectors(this._camera.up,ft),ft.multiplyScalar(e);const i=Tt.copy(this._targetEnd).add(ft);return this.moveTo(i.x,i.y,i.z,t)}elevate(e,t=!1){return ft.copy(this._camera.up).multiplyScalar(e),this.moveTo(this._targetEnd.x+ft.x,this._targetEnd.y+ft.y,this._targetEnd.z+ft.z,t)}moveTo(e,t,i,s=!1){this._isUserControllingTruck=!1;const a=ft.set(e,t,i).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,a,this.boundaryFriction),this._needsUpdate=!0,s||this._target.copy(this._targetEnd);const r=!s||Ct(this._target.x,this._targetEnd.x,this.restThreshold)&&Ct(this._target.y,this._targetEnd.y,this.restThreshold)&&Ct(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(r)}lookInDirectionOf(e,t,i,s=!1){const o=ft.set(e,t,i).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd);return this.setPosition(o.x,o.y,o.z,s)}fitToBox(e,t,{cover:i=!1,paddingLeft:s=0,paddingRight:a=0,paddingBottom:r=0,paddingTop:o=0}={}){const l=[],c=e.isBox3?$r.copy(e):$r.setFromObject(e);c.isEmpty()&&(console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve());const u=fv(this._sphericalEnd.theta,hv),d=fv(this._sphericalEnd.phi,hv);l.push(this.rotateTo(u,d,t));const h=ft.setFromSpherical(this._sphericalEnd).normalize(),f=vv.setFromUnitVectors(h,xp),p=Ct(Math.abs(h.y),1);p&&f.multiply(Sp.setFromAxisAngle(yu,u)),f.multiply(this._yAxisUpSpaceInverse);const g=yv.makeEmpty();Tt.copy(c.min).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.min).setX(c.max.x).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.min).setY(c.max.y).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.max).setZ(c.min.z).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.min).setZ(c.max.z).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.max).setY(c.min.y).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.max).setX(c.min.x).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.max).applyQuaternion(f),g.expandByPoint(Tt),g.min.x-=s,g.min.y-=r,g.max.x+=a,g.max.y+=o,f.setFromUnitVectors(xp,h),p&&f.premultiply(Sp.invert()),f.premultiply(this._yAxisUpSpace);const _=g.getSize(ft),m=g.getCenter(Tt).applyQuaternion(f);if(La(this._camera)){const v=this.getDistanceToFitBox(_.x,_.y,_.z,i);l.push(this.moveTo(m.x,m.y,m.z,t)),l.push(this.dollyTo(v,t)),l.push(this.setFocalOffset(0,0,0,t))}else if(Js(this._camera)){const v=this._camera,y=v.right-v.left,b=v.top-v.bottom,T=i?Math.max(y/_.x,b/_.y):Math.min(y/_.x,b/_.y);l.push(this.moveTo(m.x,m.y,m.z,t)),l.push(this.zoomTo(T,t)),l.push(this.setFocalOffset(0,0,0,t))}return Promise.all(l)}fitToSphere(e,t){const i=[],a="isObject3D"in e?km.createBoundingSphere(e,wp):wp.copy(e);if(i.push(this.moveTo(a.center.x,a.center.y,a.center.z,t)),La(this._camera)){const r=this.getDistanceToFitSphere(a.radius);i.push(this.dollyTo(r,t))}else if(Js(this._camera)){const r=this._camera.right-this._camera.left,o=this._camera.top-this._camera.bottom,l=2*a.radius,c=Math.min(r/l,o/l);i.push(this.zoomTo(c,t))}return i.push(this.setFocalOffset(0,0,0,t)),Promise.all(i)}setLookAt(e,t,i,s,a,r,o=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Hr.NONE,this._changedDolly=0;const l=Tt.set(s,a,r),c=ft.set(e,t,i);this._targetEnd.copy(l),this._sphericalEnd.setFromVector3(c.sub(l).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,o||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const u=!o||Ct(this._target.x,this._targetEnd.x,this.restThreshold)&&Ct(this._target.y,this._targetEnd.y,this.restThreshold)&&Ct(this._target.z,this._targetEnd.z,this.restThreshold)&&Ct(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ct(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Ct(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(u)}lerpLookAt(e,t,i,s,a,r,o,l,c,u,d,h,f,p=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Hr.NONE,this._changedDolly=0;const g=ft.set(s,a,r),_=Tt.set(e,t,i);vi.setFromVector3(_.sub(g).applyQuaternion(this._yAxisUpSpace));const m=Gr.set(u,d,h),v=Tt.set(o,l,c);il.setFromVector3(v.sub(m).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(g.lerp(m,f));const y=il.theta-vi.theta,b=il.phi-vi.phi,T=il.radius-vi.radius;this._sphericalEnd.set(vi.radius+T*f,vi.phi+b*f,vi.theta+y*f),this.normalizeRotations(),this._needsUpdate=!0,p||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const x=!p||Ct(this._target.x,this._targetEnd.x,this.restThreshold)&&Ct(this._target.y,this._targetEnd.y,this.restThreshold)&&Ct(this._target.z,this._targetEnd.z,this.restThreshold)&&Ct(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ct(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Ct(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(x)}setPosition(e,t,i,s=!1){return this.setLookAt(e,t,i,this._targetEnd.x,this._targetEnd.y,this._targetEnd.z,s)}setTarget(e,t,i,s=!1){const a=this.getPosition(ft),r=this.setLookAt(a.x,a.y,a.z,e,t,i,s);return this._sphericalEnd.phi=Ni(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),r}setFocalOffset(e,t,i,s=!1){this._isUserControllingOffset=!1,this._focalOffsetEnd.set(e,t,i),this._needsUpdate=!0,s||this._focalOffset.copy(this._focalOffsetEnd);const a=!s||Ct(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&Ct(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&Ct(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(a)}setOrbitPoint(e,t,i){this._camera.updateMatrixWorld(),es.setFromMatrixColumn(this._camera.matrixWorldInverse,0),ts.setFromMatrixColumn(this._camera.matrixWorldInverse,1),Da.setFromMatrixColumn(this._camera.matrixWorldInverse,2);const s=ft.set(e,t,i),a=s.distanceTo(this._camera.position),r=s.sub(this._camera.position);es.multiplyScalar(r.x),ts.multiplyScalar(r.y),Da.multiplyScalar(r.z),ft.copy(es).add(ts).add(Da),ft.z=ft.z+a,this.dollyTo(a,!1),this.setFocalOffset(-ft.x,ft.y,-ft.z,!1),this.moveTo(e,t,i,!1)}setBoundary(e){if(!e){this._boundary.min.set(-1/0,-1/0,-1/0),this._boundary.max.set(1/0,1/0,1/0),this._needsUpdate=!0;return}this._boundary.copy(e),this._boundary.clampPoint(this._targetEnd,this._targetEnd),this._needsUpdate=!0}setViewport(e,t,i,s){if(e===null){this._viewport=null;return}this._viewport=this._viewport||new tt.Vector4,typeof e=="number"?this._viewport.set(e,t,i,s):this._viewport.copy(e)}getDistanceToFitBox(e,t,i,s=!1){if(vp(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const a=e/t,r=this._camera.getEffectiveFOV()*Qo,o=this._camera.aspect;return((s?a>o:at.pointerId===e)}_findPointerByMouseButton(e){return this._activePointers.find(t=>t.mouseButton===e)}_disposePointer(e){this._activePointers.splice(this._activePointers.indexOf(e),1)}_encloseToBoundary(e,t,i){const s=t.lengthSq();if(s===0)return e;const a=Tt.copy(t).add(e),o=this._boundary.clampPoint(a,Gr).sub(a),l=o.lengthSq();if(l===0)return e.add(t);if(l===s)return e;if(i===0)return e.add(t).add(o);{const c=1+i*l/t.dot(o);return e.add(Tt.copy(t).multiplyScalar(c)).add(o.multiplyScalar(1-i))}}_updateNearPlaneCorners(){if(La(this._camera)){const e=this._camera,t=e.near,i=e.getEffectiveFOV()*Qo,s=Math.tan(i*.5)*t,a=s*e.aspect;this._nearPlaneCorners[0].set(-a,-s,0),this._nearPlaneCorners[1].set(a,-s,0),this._nearPlaneCorners[2].set(a,s,0),this._nearPlaneCorners[3].set(-a,s,0)}else if(Js(this._camera)){const e=this._camera,t=1/e.zoom,i=e.left*t,s=e.right*t,a=e.top*t,r=e.bottom*t;this._nearPlaneCorners[0].set(i,a,0),this._nearPlaneCorners[1].set(s,a,0),this._nearPlaneCorners[2].set(s,r,0),this._nearPlaneCorners[3].set(i,r,0)}}_collisionTest(){let e=1/0;if(!(this.colliderMeshes.length>=1)||vp(this._camera,"_collisionTest"))return e;const i=this._getTargetDirection(nl);Tp.lookAt(mv,i,this._camera.up);for(let s=0;s<4;s++){const a=Tt.copy(this._nearPlaneCorners[s]);a.applyMatrix4(Tp);const r=Gr.addVectors(this._target,a);vu.set(r,i),vu.far=this._spherical.radius+1;const o=vu.intersectObjects(this.colliderMeshes);o.length!==0&&o[0].distance{const i=()=>{this.removeEventListener("rest",i),t()};this.addEventListener("rest",i)}))}_addAllEventListeners(e){}_removeAllEventListeners(){}get dampingFactor(){return console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead."),0}set dampingFactor(e){console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead.")}get draggingDampingFactor(){return console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead."),0}set draggingDampingFactor(e){console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead.")}static createBoundingSphere(e,t=new tt.Sphere){const i=t,s=i.center;$r.makeEmpty(),e.traverseVisible(r=>{r.isMesh&&$r.expandByObject(r)}),$r.getCenter(s);let a=0;return e.traverseVisible(r=>{if(!r.isMesh)return;const o=r;if(!o.geometry)return;const l=o.geometry.clone();l.applyMatrix4(o.matrixWorld);const u=l.attributes.position;for(let d=0,h=u.count;di.preventDefault()),this.isFollowingViewer=!1,this.followTargetPosition=new S,this.followTargetQuaternion=new dt,this.followPositionLerpFactor=.12,this.followRotationSlerpFactor=.1,this.hasFollowTarget=!1,this.isRightMouseDown=!1,this.lastMouseX=null,this.lastMouseY=null,this.savedCameraState=null,this.isInReplayMode=!1}setMode(e){if(this.mode=e,e==="ballOrbit"){if(this.controls.enabled=!0,this.lastBallOrbitPos=null,this.ballOrbitScrollHandler||(this.ballOrbitScrollHandler=t=>{if(this.mode==="ballOrbit"&&!this.isFollowingViewer){t.preventDefault();const i=Math.max(this.controls.distance*.2,100);t.deltaY>0?this.controls.dolly(-i,!0):this.controls.dolly(i,!0)}},this.domElement.addEventListener("wheel",this.ballOrbitScrollHandler,{passive:!1})),this.targetBall){const t=this.targetBall.position;this.camera.position.distanceTo(t),this.controls.setLookAt(this.camera.position.x,this.camera.position.y,this.camera.position.z,t.x,t.y,t.z,!1)}return}if(e==="free"){if(this.controls.enabled=!1,!this.freeCamKeys){this.freeCamKeys={forward:!1,backward:!1,left:!1,right:!1,up:!1,down:!1},this.freeCamSpeed=2e3,this.freeCamRotation={yaw:0,pitch:0};const t=new S;this.camera.getWorldDirection(t),this.freeCamRotation.yaw=Math.atan2(t.x,t.z),this.freeCamRotation.pitch=Math.asin(-t.y),this.onKeyDown=i=>this.handleFreeCamKeyDown(i),this.onKeyUp=i=>this.handleFreeCamKeyUp(i),this.onMouseMove=i=>this.handleFreeCamMouseMove(i),this.onMouseDown=i=>{i.button===2&&this.mode==="free"&&!this.isFollowingViewer&&(this.isRightMouseDown=!0,this.domElement.requestPointerLock?.())},this.onMouseUp=i=>{i.button===2&&(this.isRightMouseDown=!1,document.pointerLockElement===this.domElement&&document.exitPointerLock?.())},this.onPointerLockChange=()=>{document.pointerLockElement!==this.domElement&&(this.isRightMouseDown=!1)},this.onMouseLeave=()=>{document.pointerLockElement!==this.domElement&&(this.isRightMouseDown=!1)},this.onWindowBlur=()=>{this.isRightMouseDown=!1,document.pointerLockElement===this.domElement&&document.exitPointerLock?.(),this.freeCamKeys&&(this.freeCamKeys.forward=!1,this.freeCamKeys.backward=!1,this.freeCamKeys.left=!1,this.freeCamKeys.right=!1,this.freeCamKeys.up=!1,this.freeCamKeys.down=!1)},this.onVisibilityChange=()=>{document.hidden&&(this.isRightMouseDown=!1,document.pointerLockElement===this.domElement&&document.exitPointerLock?.(),this.freeCamKeys&&(this.freeCamKeys.forward=!1,this.freeCamKeys.backward=!1,this.freeCamKeys.left=!1,this.freeCamKeys.right=!1,this.freeCamKeys.up=!1,this.freeCamKeys.down=!1))},document.addEventListener("keydown",this.onKeyDown),document.addEventListener("keyup",this.onKeyUp),document.addEventListener("mousemove",this.onMouseMove),this.domElement.addEventListener("mousedown",this.onMouseDown),document.addEventListener("mouseup",this.onMouseUp),document.addEventListener("pointerlockchange",this.onPointerLockChange),this.domElement.addEventListener("mouseleave",this.onMouseLeave),window.addEventListener("blur",this.onWindowBlur),document.addEventListener("visibilitychange",this.onVisibilityChange)}this.isRightMouseDown=!1}else this.controls.enabled=!1,this.lastIsBallCam=null,this.currentBlend=0,this.targetBlend=0}setTargetCar(e){if(this.targetCar!==e&&(this.currentBallCamAngle=null,this.targetCar&&e)){this.targetHandoff={elapsed:0,duration:sN,startPosition:this.camera.position.clone(),startQuaternion:this.camera.quaternion.clone()};const t=new S().subVectors(this.camera.position,e.position);t.y=0,t.length()>.01&&(t.normalize(),this.smoothedCarYaw=Math.atan2(-t.x,-t.z)),this.lastCarPos&&this.lastCarPos.copy(e.position)}this.targetCar=e}setTargetBall(e){this.targetBall=e}handleFreeCamKeyDown(e){if(this.mode!=="free"||this.isFollowingViewer)return;const t=e.target;if(!(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable))switch(e.code){case"KeyW":case"ArrowUp":this.freeCamKeys.forward=!0;break;case"KeyS":case"ArrowDown":this.freeCamKeys.backward=!0;break;case"KeyA":case"ArrowLeft":this.freeCamKeys.left=!0;break;case"KeyD":case"ArrowRight":this.freeCamKeys.right=!0;break;case"Space":this.freeCamKeys.up=!0;break;case"ShiftLeft":case"ShiftRight":this.freeCamKeys.down=!0;break}}handleFreeCamKeyUp(e){switch(e.code){case"KeyW":case"ArrowUp":this.freeCamKeys.forward=!1;break;case"KeyS":case"ArrowDown":this.freeCamKeys.backward=!1;break;case"KeyA":case"ArrowLeft":this.freeCamKeys.left=!1;break;case"KeyD":case"ArrowRight":this.freeCamKeys.right=!1;break;case"Space":this.freeCamKeys.up=!1;break;case"ShiftLeft":case"ShiftRight":this.freeCamKeys.down=!1;break}}handleFreeCamMouseMove(e){if(this.mode!=="free"||!this.isRightMouseDown||this.isFollowingViewer)return;const t=e.movementX||0,i=e.movementY||0,s=.003;this.freeCamRotation.yaw-=t*s,this.freeCamRotation.pitch+=i*s,this.freeCamRotation.pitch=Math.max(-Math.PI/2+.01,Math.min(Math.PI/2-.01,this.freeCamRotation.pitch))}updateFreeCam(e){if(!this.freeCamKeys)return;const t=new S(Math.sin(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch),-Math.sin(this.freeCamRotation.pitch),Math.cos(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch));t.normalize();const i=new S(Math.sin(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch),-Math.sin(this.freeCamRotation.pitch),Math.cos(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch));i.normalize();const s=new S(Math.sin(this.freeCamRotation.yaw-Math.PI/2),0,Math.cos(this.freeCamRotation.yaw-Math.PI/2)),a=new S(0,1,0),r=new S,o=this.freeCamSpeed*e;this.freeCamKeys.forward&&r.add(i.clone().multiplyScalar(o)),this.freeCamKeys.backward&&r.add(i.clone().multiplyScalar(-o)),this.freeCamKeys.right&&r.add(s.clone().multiplyScalar(o)),this.freeCamKeys.left&&r.add(s.clone().multiplyScalar(-o)),this.freeCamKeys.up&&r.add(a.clone().multiplyScalar(o)),this.freeCamKeys.down&&r.add(a.clone().multiplyScalar(-o)),r.length()>0&&r.normalize().multiplyScalar(o),this.camera.position.add(r);const l=this.camera.position.clone().add(t);this.camera.lookAt(l),this.controls.setLookAt(this.camera.position.x,this.camera.position.y,this.camera.position.z,l.x,l.y,l.z,!1)}update(e,t=!0){if(this.isFollowingViewer){this.updateFollowInterpolation(e);return}if(this.mode==="free"){this.updateFreeCam(e),this.controls.update(e);return}if(this.mode==="ballOrbit"){if(this.targetBall){const p=this.targetBall.position;this.lastBallOrbitPos||(this.lastBallOrbitPos=p.clone());const g=new S().subVectors(p,this.lastBallOrbitPos);if(this.controls.setTarget(p.x,p.y,p.z,!1),g.lengthSq()>.01){const _=new S;this.controls.getPosition(_);const m=_.x+g.x,v=_.y+g.y,y=_.z+g.z;this.controls.setPosition(m,v,y,!1),this.lastBallOrbitPos.copy(p)}}this.controls.update(e);return}if(!this.targetCar){this.controls.update(e);return}const i=this.targetCar.position.clone(),s=this.targetCar.quaternion;if(this.lastIsBallCam!==null&&this.lastIsBallCam!==t&&!t){const p=new S().subVectors(this.camera.position,i);p.y=0,p.length()>.01&&(p.normalize(),this.smoothedCarYaw=Math.atan2(-p.x,-p.z))}this.lastIsBallCam=t;const a=this.calculateCarCamPosition(i,s,e),r=this.calculateBallCamPosition(i,s,e);this.targetBlend=t?1:0;const o=Math.max(.15,Math.min(.6,this.baseDuration/this.transitionSpeed)),l=e/o;this.currentBlendthis.targetBlend&&(this.currentBlend=Math.max(this.currentBlend-l,this.targetBlend));const c=this.currentBlend,u=c*c*(3-2*c),d=new S().lerpVectors(a.cameraPos,r.cameraPos,u);this._tempMatrix.lookAt(a.cameraPos,a.lookTarget,new S(0,1,0)),this._tempQuatCarCam.setFromRotationMatrix(this._tempMatrix),this._tempMatrix.lookAt(r.cameraPos,r.lookTarget,new S(0,1,0)),this._tempQuatBallCam.setFromRotationMatrix(this._tempMatrix),this._tempQuatCarCam.dot(this._tempQuatBallCam)<0&&this._tempQuatBallCam.set(-this._tempQuatBallCam.x,-this._tempQuatBallCam.y,-this._tempQuatBallCam.z,-this._tempQuatBallCam.w);const h=new dt().slerpQuaternions(this._tempQuatCarCam,this._tempQuatBallCam,u);if(this.targetHandoff){this.targetHandoff.elapsed+=e;const p=Math.min(1,this.targetHandoff.elapsed/this.targetHandoff.duration),g=p*p*(3-2*p),_=d.clone(),m=h.clone();d.lerpVectors(this.targetHandoff.startPosition,_,g),h.slerpQuaternions(this.targetHandoff.startQuaternion,m,g),p>=1&&(this.targetHandoff=null)}if(this.camera.position.copy(d),this.camera.quaternion.copy(h),this.followAngle!==0){const p=this.followAngle*Math.PI/180;this.camera.rotateX(-p)}this.currentCamPos||(this.currentCamPos=new S),this.currentLookTarget||(this.currentLookTarget=new S),this.currentCamPos.copy(d);const f=new S(0,0,-1).applyQuaternion(this.camera.quaternion);this.currentLookTarget.copy(d).add(f.multiplyScalar(100)),this.enforceMinHeight()}calculateBallCamPosition(e,t,i=1/60){if(!this.targetBall)return this.calculateCarCamPosition(e,t,i);const s=this.targetBall.position.clone(),a=new S().subVectors(e,s);a.y=0,a.normalize();const r=e.clone().add(a.multiplyScalar(this.followDistance)),o=s.y-e.y,c=Math.min(1,Math.max(0,o/800));r.y=e.y+this.followHeight-c*100,r.y.01)s.normalize(),u=Math.atan2(s.x,s.z);else if(a>.05){s.normalize();let y=Math.atan2(s.x,s.z)-o;for(;y>Math.PI;)y-=Math.PI*2;for(;y<-Math.PI;)y+=Math.PI*2;Math.abs(y)>Math.PI/2?u=o+Math.PI:u=o}else u=o;this.lastCarPos.copy(e),this.smoothedCarYaw===void 0&&(this.smoothedCarYaw=u);let d=u-this.smoothedCarYaw;for(;d>Math.PI;)d-=Math.PI*2;for(;d<-Math.PI;)d+=Math.PI*2;const h=c?this.swivelSpeed*.4:this.swivelSpeed;this.smoothedCarYaw+=d*Math.min(1,h*(1/60));const f=-Math.sin(this.smoothedCarYaw),p=-Math.cos(this.smoothedCarYaw),g=new S(e.x+f*this.followDistance,e.y+this.followHeight,e.z+p*this.followDistance);g.yMath.PI;)s-=Math.PI*2;for(;s<-Math.PI;)s+=Math.PI*2;this.followCurrentOrbitParams.azimuth+=s*.15,this.followCurrentOrbitParams.polar+=(this.followTargetOrbitParams.polar-this.followCurrentOrbitParams.polar)*.15,this.controls.setTarget(t.x,t.y,t.z,!1),this.controls.dollyTo(this.followCurrentOrbitParams.distance,!1),this.controls.rotateTo(this.followCurrentOrbitParams.azimuth,this.followCurrentOrbitParams.polar,!1),this.controls.update(e)}}else{if(this.camera.position.lerp(this.followTargetPosition,this.followPositionLerpFactor),this.camera.quaternion.slerp(this.followTargetQuaternion,this.followRotationSlerpFactor),this.freeCamRotation){const i=new S;this.camera.getWorldDirection(i),this.freeCamRotation.yaw=Math.atan2(i.x,i.z),this.freeCamRotation.pitch=Math.asin(-i.y)}const t=new S;this.camera.getWorldDirection(t),t.multiplyScalar(100).add(this.camera.position),this.controls.setLookAt(this.camera.position.x,this.camera.position.y,this.camera.position.z,t.x,t.y,t.z,!1)}}setDefaultFreecamPosition(){if(this.camera.position.copy(this.defaultFreecamPosition),this.camera.lookAt(this.defaultFreecamLookAt),this.freeCamRotation){const e=new S;this.camera.getWorldDirection(e),this.freeCamRotation.yaw=Math.atan2(e.x,e.z),this.freeCamRotation.pitch=Math.asin(-e.y)}this.controls.setLookAt(this.defaultFreecamPosition.x,this.defaultFreecamPosition.y,this.defaultFreecamPosition.z,this.defaultFreecamLookAt.x,this.defaultFreecamLookAt.y,this.defaultFreecamLookAt.z,!1)}getIsPointerLocked(){return this.isPointerLocked||!1}setPointerLockCallback(e){this.onPointerLockStateChange=e}dispose(){this.controls.dispose(),this.ballOrbitScrollHandler&&this.domElement.removeEventListener("wheel",this.ballOrbitScrollHandler),this.onKeyDown&&document.removeEventListener("keydown",this.onKeyDown),this.onKeyUp&&document.removeEventListener("keyup",this.onKeyUp),this.onMouseMove&&document.removeEventListener("mousemove",this.onMouseMove),this.onMouseDown&&this.domElement.removeEventListener("mousedown",this.onMouseDown),this.onMouseUp&&document.removeEventListener("mouseup",this.onMouseUp),this.onPointerLockChange&&document.removeEventListener("pointerlockchange",this.onPointerLockChange),this.onMouseLeave&&this.domElement.removeEventListener("mouseleave",this.onMouseLeave),this.onWindowBlur&&window.removeEventListener("blur",this.onWindowBlur),this.onVisibilityChange&&document.removeEventListener("visibilitychange",this.onVisibilityChange)}}function xv(n){if(n.pitch===void 0||n.angle!==void 0)return n;const{pitch:e,...t}=n;return{...t,angle:e}}const rN={distance:260,height:90,angle:-4,stiffness:.45,swivelSpeed:4.3,transitionSpeed:1.3,fov:110};function oN(n={}){let e=null,t=null,i=n.mode??(n.follow?"follow":"orbit"),s=n.follow??null,a=n.ballCam??null,r=a??!0,o=xv({...n.settings}),l=1;const c=n.useRecordedSettings!==!1;let u=null;const d=new S;let h=!1;function f(){if(!(!t||!e)){if(t.player.controls.enabled=i==="orbit",i==="free")e.setMode("free");else if(i==="ballOrbit"){const y=_();y&&e.setTargetBall(y),e.setMode("ballOrbit")}else e.setMode("car");u=null}}function p(){return!c||!t||!s?null:t.player.adapter.getPlayer(s)?.cameraSettings??null}function g(){const y={...rN,...p(),...o};return l!==1&&y.distance!==void 0&&(y.distance*=l),y}function _(){if(!t)return null;const y=t.player.actorManager;return y.ballActorId!=null?y.actors[y.ballActorId]??null:null}function m(y){const b=g().fov;if(!b)return;const T=b*Math.PI/180,x=16/9,M=2*Math.atan(Math.tan(T/2)/x),C=2*Math.atan(Math.tan(T/2)/y.aspect),w=Math.max(M,C)*180/Math.PI;Math.abs(y.fov-w)>.1&&(y.fov=w,y.updateProjectionMatrix())}function v(y,b){if(!e)return;if(i==="free"){o.freeCamSpeed&&(e.freeCamSpeed=o.freeCamSpeed),e.update(b);return}if(i==="ballOrbit"){y.ball.object3d&&e.setTargetBall(y.ball.object3d),e.update(b);return}const x=(s?y.cars.find(C=>C.name===s):void 0)?.object3d??null;if(!x){e.update(b);return}e.setTargetCar(x),y.ball.object3d&&e.setTargetBall(y.ball.object3d),e.setFollowSettings(g());const M=s?y.player.adapter.getPlayer(s):void 0;r=a??M?.isBallCam??!0,d.copy(x.position),h=!0,e.update(b,r)}return{id:"camera",setup(y){t=y,e=new aN(y.camera,y.renderer.domElement),f()},beforeRender(y){if(!e||(m(y.camera),i==="orbit"))return;const b=performance.now(),T=u===null?1/60:Math.min(.1,(b-u)/1e3);u=b,v(y,T)},teardown(){i="orbit",t&&(t.player.controls.enabled=!0),e?.dispose(),e=null,t=null},setMode(y){y!==i&&(i=y,f())},getMode(){return i},follow(y){s=y,i="follow",f()},release(){i="orbit",t&&h&&t.player.controls.target.copy(d),f()},getTarget(){return s},setBallCam(y){a=y,y!==null&&(r=y)},getBallCam(){return r},setCameraSettings(y){o=y===null?{}:{...o,...xv(y)}},setDistanceScale(y){l=Math.max(.25,y)},getDistanceScale(){return l},getCameraSettings(){return g()},getRecordedSettings(){const y=p();return y?{...y}:null}}}const lN={"top-left":"top: 8px; left: 8px;","top-right":"top: 8px; right: 8px;","bottom-left":"bottom: 8px; left: 8px;","bottom-right":"bottom: 8px; right: 8px;"};function cN(n={}){const e=n.corner??"top-right",t=n.updateIntervalMs??500,i=()=>typeof n.mount=="function"?n.mount():n.mount??null;let s=null,a=null,r=null,o=0,l=performance.now(),c=0,u=0;const d=typeof n.onSample=="function";return{id:"fps-overlay",setup(h){if(l=performance.now(),o=0,u=h.player.getState().frameIndex,c=u,d)return;const f=i(),p=f!=null;s=document.createElement("div"),s.className="player-fps-overlay",s.style.cssText=p?` + `,transparent:!0,depthWrite:!1,blending:Ht});this.points=new sr(t,o),this.points.frustumCulled=!1,this.nextParticleIndex=0}setActive(e){this.active=e}emit(e,t,i,s=1){if(!this.active)return;const a=Math.floor(Math.random()*3)+3,r=Math.max(1,Math.round(a*s));for(let o=0;o=o.maxLife){o.active=!1,i[r]=0,s[r]=0;continue}t[r*3]+=o.velocity.x*e,t[r*3+1]+=o.velocity.y*e,t[r*3+2]+=o.velocity.z*e;const l=o.life/o.maxLife;i[r]=Math.pow(1-l,.5);const c=o.initialSize||3;s[r]=c*(1-l*.7),a[r*3]=1,a[r*3+1]=Math.max(.2,.9-l*.7),a[r*3+2]=Math.max(0,.4-l*.4),o.velocity.y+=20*e}this.geometry.attributes.position.needsUpdate=!0,this.geometry.attributes.alpha.needsUpdate=!0,this.geometry.attributes.size.needsUpdate=!0,this.geometry.attributes.color.needsUpdate=!0}addToScene(e){e.add(this.points)}removeFromScene(e){e.remove(this.points)}dispose(){this.geometry.dispose(),this.points.material.dispose()}}class bF{constructor(e,t,i,s){this.scene=e,this.team=t,this.trailWidth=i,this.trailLength=s,this.active=!0,this.dying=!1,this.deathTime=0,this.maxDeathTime=1.5,this.teamColors={0:new qe(.3,.6,1,.9),1:new qe(1,.5,.15,.9)},this.leftTarget=new Qe,this.rightTarget=new Qe,e.add(this.leftTarget),e.add(this.rightTarget),this.leftTrail=this.createTrail(this.leftTarget),this.rightTrail=this.createTrail(this.rightTarget),this.updateColors(),this.leftTrail.activate(),this.rightTrail.activate()}createTrail(e){const t=new pt(this.scene,!1),i=pt.createBaseMaterial();i.blending=Ht,i.depthWrite=!1,i.side=ct;const s=this.trailWidth,a=[new S(0,0,0),new S(0,s,0),new S(-s/2,s/2,0),new S(s/2,s/2,0)];return t.initialize(i,this.trailLength,!1,0,a,e),t.setAdvanceFrequency(60),t.mesh&&(t.mesh.frustumCulled=!1),t}updateColors(){const e=this.teamColors[this.team]||this.teamColors[0],t=new qe(e.x*.3,e.y*.3,e.z*.3,0);this.leftTrail?.material&&(this.leftTrail.material.uniforms.headColor.value.copy(e),this.leftTrail.material.uniforms.tailColor.value.copy(t)),this.rightTrail?.material&&(this.rightTrail.material.uniforms.headColor.value.copy(e),this.rightTrail.material.uniforms.tailColor.value.copy(t))}startDying(){this.dying||(this.dying=!0,this.deathTime=0,this.leftTrail.pause(),this.rightTrail.pause())}updatePosition(e,t,i){this.dying||(this.leftTarget.position.copy(e),this.rightTarget.position.copy(t),this.leftTarget.quaternion.copy(i),this.rightTarget.quaternion.copy(i),this.leftTarget.updateMatrixWorld(),this.rightTarget.updateMatrixWorld())}update(e){if(this.dying){this.deathTime+=e;const i=1-Math.min(1,this.deathTime/this.maxDeathTime),s=this.teamColors[this.team]||this.teamColors[0],a=new qe(s.x,s.y,s.z,s.w*i),r=new qe(s.x*.3,s.y*.3,s.z*.3,0);this.leftTrail?.material&&(this.leftTrail.material.uniforms.headColor.value.copy(a),this.leftTrail.material.uniforms.tailColor.value.copy(r)),this.rightTrail?.material&&(this.rightTrail.material.uniforms.headColor.value.copy(a),this.rightTrail.material.uniforms.tailColor.value.copy(r)),this.deathTime>=this.maxDeathTime&&(this.active=!1)}this.leftTrail.isActive&&this.leftTrail.update(e),this.rightTrail.isActive&&this.rightTrail.update(e)}dispose(){this.leftTrail.deactivate(),this.rightTrail.deactivate(),this.leftTrail.geometry&&this.leftTrail.geometry.dispose(),this.rightTrail.geometry&&this.rightTrail.geometry.dispose(),this.leftTrail.material&&this.leftTrail.material.dispose(),this.rightTrail.material&&this.rightTrail.material.dispose(),this.scene.remove(this.leftTarget),this.scene.remove(this.rightTarget)}}class xF{constructor(e,t=0){this.scene=e,this.team=t,this.active=!1,this.trailLength=80,this.trailWidth=15,this.arenaBounds={floor:0,ceiling:2044,wallX:4096,wallZ:5120},this.groundedThreshold=50,this.segments=[],this.currentSegment=null,this.wasGrounded=!0}setTeam(e){this.team!==e&&(this.team=e,this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.team=e,this.currentSegment.updateColors()))}setActive(e){e&&!this.active?(this.currentSegment=null,this.wasGrounded=!0):!e&&this.active&&this.currentSegment&&(this.currentSegment.startDying(),this.currentSegment=null),this.active=e}isGrounded(e){const t=this.groundedThreshold,i=this.arenaBounds;if(e.yi.ceiling-t)return{grounded:!0,surface:"ceiling",normal:new S(0,-1,0)};if(Math.abs(e.x)>i.wallX-t){const s=e.x>0?-1:1;return{grounded:!0,surface:"wall",normal:new S(s,0,0)}}if(Math.abs(e.z)>i.wallZ-t){const s=e.z>0?-1:1;return{grounded:!0,surface:"wall",normal:new S(0,0,s)}}return{grounded:!1,surface:null,normal:null}}emit(e,t,i){if(!this.active)return;const s=this.isGrounded(e);if(!s.grounded){this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.startDying(),this.currentSegment=null),this.wasGrounded=!1;return}(!this.wasGrounded||!this.currentSegment)&&(this.currentSegment&&!this.currentSegment.dying&&this.currentSegment.startDying(),this.currentSegment=new bF(this.scene,this.team,this.trailWidth,this.trailLength),this.segments.push(this.currentSegment)),this.wasGrounded=!0;const r=new S(-30,5,40),o=new S(-30,5,-40);r.applyQuaternion(t),o.applyQuaternion(t);const l=e.clone().add(r),c=e.clone().add(o),u=2;if(s.surface==="floor")l.y=u,c.y=u;else if(s.surface==="ceiling")l.y=this.arenaBounds.ceiling-u,c.y=this.arenaBounds.ceiling-u;else if(s.surface==="wall"){if(s.normal.x!==0){const d=s.normal.x>0?-this.arenaBounds.wallX+u:this.arenaBounds.wallX-u;l.x=d,c.x=d}else if(s.normal.z!==0){const d=s.normal.z>0?-this.arenaBounds.wallZ+u:this.arenaBounds.wallZ-u;l.z=d,c.z=d}}this.currentSegment.updatePosition(l,c,t)}update(e){for(let t=this.segments.length-1;t>=0;t--){const i=this.segments[t];i.update(e),i.active||(i.dispose(),this.segments.splice(t,1))}}addToScene(e){}removeFromScene(e){for(const t of this.segments)t.startDying();this.currentSegment=null}dispose(){for(const e of this.segments)e.dispose();this.segments=[],this.currentSegment=null}}class wF{constructor(e){this.scene=e,this.renderer=null,this.camera=null,this.explosions={active:[],goalEvents:new Map,demoEvents:new Map},this.boostTrails=new Map,this.supersonicTrails=new Map,this.ballTrail=null,hF()}setRenderContext(e,t){this.renderer=e,this.camera=t,pF(this.scene,e,t)}reset(){this.explosions.active.forEach(e=>e.removeFromScene(this.scene)),this.explosions.active=[],this.clearGoalExplosions(),this.boostTrails.forEach(e=>{e.removeFromScene(this.scene),e.dispose()}),this.boostTrails.clear(),this.supersonicTrails.forEach(e=>{e.removeFromScene(this.scene),e.dispose()}),this.supersonicTrails.clear(),this.ballTrail&&(this.ballTrail.removeFromScene(this.scene),this.ballTrail.dispose(),this.ballTrail=null)}clearEvents(){this.explosions.goalEvents.clear(),this.explosions.demoEvents.clear()}setGoalEvents(e){this.explosions.goalEvents.clear();for(const t of e??[])Number.isFinite(t.frame)&&this.explosions.goalEvents.set(t.frame,{time:t.time,team:t.team??0,playerName:t.playerName??""})}resetBallTrail(){this.ballTrail&&this.ballTrail.reset()}clearGoalExplosions(){Bn&&Bn.clearActive();for(const e of this.explosions.active)e.removeFromScene(this.scene);this.explosions.active=[]}createBoostTrail(e,t){if(this.boostTrails.has(t)){const s=this.boostTrails.get(t);s.removeFromScene(this.scene),s.dispose()}const i=new vF(e);return i.addToScene(this.scene),this.boostTrails.set(t,i),i}removeBoostTrail(e){const t=this.boostTrails.get(e);t&&(t.removeFromScene(this.scene),t.dispose(),this.boostTrails.delete(e))}updateBoostTrail(e,t,i,s,a){const r=this.boostTrails.get(e);r&&(r.setActive(t),t&&r.emit(i,s,a,this._playbackSpeed||1))}createSupersonicTrail(e,t){if(this.supersonicTrails.has(e)){const s=this.supersonicTrails.get(e);s.removeFromScene(this.scene),s.dispose()}const i=new xF(this.scene,t);return i.addToScene(this.scene),this.supersonicTrails.set(e,i),i}removeSupersonicTrail(e){const t=this.supersonicTrails.get(e);t&&(t.removeFromScene(this.scene),t.dispose(),this.supersonicTrails.delete(e))}updateSupersonicTrail(e,t,i,s,a,r){let o=this.supersonicTrails.get(e);!o&&t&&(o=this.createSupersonicTrail(e,r)),o&&(r!==void 0&&o.team!==r&&o.setTeam(r),o.setActive(t),t&&o.emit(i,s,a))}createBallTrail(){return this.ballTrail&&(this.ballTrail.removeFromScene(this.scene),this.ballTrail.dispose()),this.ballTrail=new dF(this.scene,0),this.ballTrail.addToScene(this.scene),console.log("✓ Spiral ball trail created and added to scene"),this.ballTrail}updateBallTrail(e,t,i){this.ballTrail||this.createBallTrail(),i!==void 0&&this.ballTrail.team!==i&&this.ballTrail.setTeam(i);const s=1/60*(this._playbackSpeed||1);this.ballTrail.emit(e,t,s)}triggerGoalExplosion(e,t){const i=kT(this.scene,this.renderer,this.camera);i&&(this.camera&&(i.camera=this.camera),i.trigger(e,t))}triggerDemoExplosion(e,t,i){const s=LT(this.scene);s&&s.trigger(e)}update(e,t=!0,i=1){this._playbackSpeed=i;const s=e*i;di&&di.update(s),Bn&&Bn.update(s);for(let a=this.explosions.active.length-1;a>=0;a--){const r=this.explosions.active[a];r.update(s)&&(r.removeFromScene(this.scene),this.explosions.active.splice(a,1))}t&&(this.boostTrails.forEach(a=>{a.update(s)}),this.supersonicTrails.forEach(a=>{a.update(s)}),this.ballTrail&&this.ballTrail.update(s))}}const dv={Octane:65535,Dominus:16746496,Plank:8978176,Breakout:16711816,Hybrid:8913151,Merc:16776960},SF={0:5744895,1:16751680};function TF(n,e){return e===0||e===1?SF[e]:dv[n]||dv.Octane}class MF{constructor(e){this.scene=e,this.hitboxes=new Map,this.enabled=!1}setEnabled(e){this.enabled=e,this.hitboxes.forEach(({mesh:t})=>{t.visible=e})}createHitboxWireframe(e,t){const i=py[e]||py.Octane,s=TF(e,t),a=i.length,r=i.width,o=i.height,l=i.offsetX,c=i.offsetZ;console.log(`[HitboxManager] Creating hitbox for ${e}:`,{dims:i,length:a,width:r,height:o,offsetX:l,offsetY:c});const u=new Mt,d=new Ci(a,o,r),h=new Ye({color:s,transparent:!0,opacity:.35,depthTest:!1,depthWrite:!1,side:ct}),f=new we(d,h);f.frustumCulled=!1,f.renderOrder=1,f.position.set(l,c,0),u.add(f);const p=new Wh(d),g=new Rt({color:s,linewidth:2,transparent:!0,opacity:.9,depthTest:!1}),_=new Ln(p,g);_.frustumCulled=!1,_.renderOrder=2,_.position.set(l,c,0),u.add(_);const m=3.33,v=new yn(m,8,6),y=new gg(v),b=new Rt({color:16777215,linewidth:1,transparent:!0,opacity:.9,depthTest:!1}),T=new Ln(y,b);return T.frustumCulled=!1,u.add(T),u.userData.hitboxType=e,u.userData.team=t??null,u.frustumCulled=!1,u}addHitbox(e,t,i){const s=i===0||i===1?i:null;if(this.hitboxes.has(e)){const r=this.hitboxes.get(e);if(r.hitboxType===t&&r.team===s)return;this.scene.remove(r.mesh),r.mesh.traverse(o=>{o.geometry&&o.geometry.dispose(),o.material&&o.material.dispose()})}const a=this.createHitboxWireframe(t,s);a.visible=this.enabled,this.scene.add(a),this.hitboxes.set(e,{mesh:a,hitboxType:t,team:s})}removeHitbox(e){if(this.hitboxes.has(e)){const{mesh:t}=this.hitboxes.get(e);this.scene.remove(t),t.traverse(i=>{i.geometry&&i.geometry.dispose(),i.material&&i.material.dispose()}),this.hitboxes.delete(e)}}updateHitboxes(e,t,i,s){if(!this.enabled)return;for(const[r,o]of Object.entries(t)){const l=e[o];if(!l||!l.userData.isCar)continue;const c=i?i(r):"Octane",u=s?s(r):null;this.addHitbox(o,c,u);const{mesh:d}=this.hitboxes.get(o);d.position.copy(l.position),d.quaternion.copy(l.quaternion),d.visible=this.enabled&&l.visible}const a=new Set(Object.values(t));for(const r of this.hitboxes.keys())a.has(r)||this.removeHitbox(r)}reset(){this.hitboxes.forEach(({mesh:e})=>{this.scene.remove(e),e.traverse(t=>{t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose()})}),this.hitboxes.clear()}dispose(){this.reset()}}const DT=["baseGroup","glowMesh","innerGlowMesh","lensColumnMesh","lensRimMesh","topGlowMesh","coreGlowMesh","highlightMesh"];function Sp(n,e,t,i){const s=new we(new Do(n,32),new Ye({color:e,transparent:!0,opacity:t,blending:Ht,side:ct,depthWrite:!1}));return s.rotation.x=-Math.PI/2,s.renderOrder=i,s}function hv(n,e){n&&n.traverse(t=>{const i=t;if(!i.isMesh||!(i.material instanceof Ye))return;const s=i.userData.baseOpacity;i.material.opacity=(s??i.material.opacity)*e})}function yu(n,e,t){n.rotation.x=-Math.PI/2,n.renderOrder=t,n.frustumCulled=!1,n.userData.baseOpacity=e,n.material.transparent=!0,n.material.opacity=e,n.material.side=ct,n.material.depthWrite=!1}function EF(n){const e=new Mt;e.renderOrder=98,e.frustumCulled=!1;const t=new Ye({color:1118477}),i=new Ye({color:16752640,blending:Ht}),s=new we(new Do(n*.55,48),t.clone());yu(s,.86,98),e.add(s);const a=new we(new ni(n*.45,n*.62,48),new Ye({color:16765242,blending:Ht}));yu(a,.78,100),a.position.y=1.4,e.add(a);function r(o,l,c){const u=new Ns;return[[o*Math.cos(-c*.72),o*Math.sin(-c*.72)],[l*Math.cos(-c),l*Math.sin(-c)],[l*Math.cos(c),l*Math.sin(c)],[o*Math.cos(c*.72),o*Math.sin(c*.72)]].forEach(([h,f],p)=>{p===0?u.moveTo(h,f):u.lineTo(h,f)}),u.closePath(),u}for(let o=0;o<3;o+=1){const l=o*(Math.PI*2)/3+Math.PI/2,c=new we(new dr(r(n*.52,n*1.42,.33)),t.clone());yu(c,.86,98),c.rotation.z=l,e.add(c);const u=new we(new dr(r(n*.66,n*1.2,.21)),i.clone());yu(u,.86,99),u.position.y=1.1,u.rotation.z=l,e.add(u)}return e}function fv(n,e){for(const t of DT){const i=n.userData[t];i&&(i.visible=e)}}function CF(){let n=new Map;function e(i){const s=i.player.adapter.boostPads;!s||s.size===0||(console.log(`[boost-pads] Creating ${s.size} boost pads...`),n=new Map,s.forEach((a,r)=>{const o=a.isBig;let l,c,u;if(o){l=new yn(37,24,18),c=new ii({color:16757274,emissive:16747008,emissiveIntensity:.42,metalness:.04,roughness:.08,clearcoat:1,clearcoatRoughness:.025,transmission:.18,thickness:30,ior:1.42,envMapIntensity:1.9,blending:Ht,transparent:!0,opacity:.68,depthWrite:!1}),u=new we(l,c),u.renderOrder=100;const p=EF(37*2.05);p.position.y=-140,u.add(p),u.userData.baseGroup=p;const g=new we(new cr(37*.12,37*.18,112,24,1,!0),new Ye({color:16761664,transparent:!0,opacity:.28,blending:Ht,side:ct,depthWrite:!1}));g.position.y=-62,g.renderOrder=99,u.add(g),u.userData.lensColumnMesh=g;const _=new we(new yn(37*1.03,24,14),new Ye({color:16768890,transparent:!0,opacity:.32,blending:Ht,side:un,depthWrite:!1}));_.renderOrder=101,u.add(_),u.userData.lensRimMesh=_;const m=new yn(37*1.3,20,14),v=new Ye({color:16758315,transparent:!0,opacity:.16,blending:Ht,side:un,depthWrite:!1}),y=new we(m,v);y.renderOrder=99,u.add(y),u.userData.glowMesh=y;const b=new yn(37*1.12,20,14),T=new Ye({color:16761130,transparent:!0,opacity:.22,blending:Ht,side:un,depthWrite:!1}),x=new we(b,T);x.renderOrder=99,u.add(x),u.userData.innerGlowMesh=x,u.userData.needsLight=!0}else{l=new cr(45,45*.92,8,32),c=new ii({color:16761370,emissive:16750336,emissiveIntensity:.72,metalness:.88,roughness:.14,clearcoat:1,clearcoatRoughness:.05,envMapIntensity:2,transparent:!0,opacity:1,depthWrite:!1}),u=new we(l,c),u.renderOrder=100;const g=Sp(45*1.42,16756736,.34,101);g.position.y=8/2+.15,u.add(g),u.userData.topGlowMesh=g;const _=Sp(45*.74,16777114,.42,102);_.position.y=8/2+.35,u.add(_),u.userData.coreGlowMesh=_;const m=Sp(45*.42,16775376,.46,103);m.position.set(-45*.18,8/2+.55,-45*.12),m.scale.y=.34,u.add(m),u.userData.highlightMesh=m}const h=o?130:10;if(u.position.set(a.position.x,h,a.position.y),u.userData.padId=r,u.userData.isBig=o,u.userData.isAvailable=!0,i.scene.add(u),n.set(r,u),u.userData.needsLight){const f=new hr(16751872,.7,480);f.decay=0,f.position.set(a.position.x,h-50,a.position.y),i.scene.add(f),u.userData.light=f}}),console.log(`[boost-pads] ✓ Created ${n.size} boost pad meshes`))}function t(i){i.player.adapter.boostPads.forEach((a,r)=>{const o=n.get(r);if(!o)return;const l=a.isAvailable;o.userData.isAvailable!==l&&(o.userData.isAvailable=l,l?(o.material.color.setHex(a.isBig?16757274:16761370),o.material.emissive.setHex(a.isBig?16747008:16750336),o.material.emissiveIntensity=a.isBig?.42:.72,o.material.opacity=a.isBig?.68:1,o.visible=!0,fv(o,!0),hv(o.userData.baseGroup,1),o.userData.light&&(o.userData.light.intensity=.85),o.userData.glowMesh&&(o.userData.glowMesh.visible=!0),o.userData.innerGlowMesh&&(o.userData.innerGlowMesh.visible=!0)):(o.material.color.setHex(a.isBig?9063424:9065472),o.material.emissive.setHex(0),o.material.emissiveIntensity=0,o.material.opacity=.2,o.visible=!0,fv(o,!1),o.userData.baseGroup&&(o.userData.baseGroup.visible=!0,hv(o.userData.baseGroup,.26)),o.userData.light&&(o.userData.light.intensity=0),o.userData.glowMesh&&(o.userData.glowMesh.visible=!1),o.userData.innerGlowMesh&&(o.userData.innerGlowMesh.visible=!1)))})}return{id:"boost-pads",setup(i){e(i)},beforeRender(i){t(i)},teardown(i){n.forEach(s=>{i.scene.remove(s),s.geometry.dispose(),s.material.dispose();for(const r of DT){const o=s.userData[r];o&&o.traverse(l=>{const c=l;c.isMesh&&(c.geometry.dispose(),c.material.dispose())})}const a=s.userData.light;a&&(i.scene.remove(a),a.dispose())}),n.clear()}}}const AF=2;function RF(n){if(n.frames.length===0)return null;const e=new Map;for(const s of n.frames)e.set(s.gameState,(e.get(s.gameState)??0)+1);let t=null,i=-1;for(const[s,a]of e.entries())a<=i||(t=s,i=a);return t}function PF(n,e){if(e===null)return null;for(const t of n.frames){if(t.gameState===e)break;return t.gameState}return null}function OT(n,e){return e===null?n.kickoffCountdown<=0:n.gameState===e}function Fg(n,e){return n.kickoffCountdown>0?!0:e!==null&&n.gameState===e}function IF(n,e){return n.ballFrames[e]?.position?!0:n.players.some(t=>t.frames[e]?.position)}function LF(n,e,t,i){return Fg(e,i)&&IF(n,t)}function kF(n,e){return n.timelineEvents.some(t=>t.kind==="goal"&&e.time>=t.time&&e.timec){const h=a.at(-1);h&&h.endTime>=c?h.endTime=Math.max(h.endTime,d):a.push({startTime:c,endTime:d})}o=u}return a}function OF(n,e,t){const i=vt.clamp(t,0,n);for(const s of e){if(i0&&(n.frames[s-1]?.kickoffCountdown??0)>0;)s-=1;let a=e+1;for(;a0;)a+=1;let r=0;for(let c=s;cl>s&&OT(o,t));return!r||r.time===e?null:r.time}function VF(n,e,t,i){const s=vh(n,e),a=n.frames[s];if(!a||!Yu(n,a,s,t,i))return null;const r=n.frames.find((c,u)=>u>s&&!Yu(n,c,u,t,i));if(r)return r.time===e?null:r.time;let o=s;for(;o>0&&Yu(n,n.frames[o-1],o-1,t,i);)o-=1;const l=n.frames[o]?.time;return l===void 0||l===e?null:l}function GF(n){return!!n?.position&&n?.isPresent!==!1}function $F(n,e,t){for(let i=n.length-1;i>=0;i-=1){const s=n[i],a=t-s.time;if(!(a<0)){if(a>zF)break;if(s.kind==="demo"&&s.secondaryPlayerId===e)return s}}return null}const WF="space",XF={space:{id:"space",skyboxUrl:"/skyboxes/PlanetaryEarth4k.hdr",exposure:1.45,rotation:{x:8,y:0,z:28},animation:{enabled:!0,speed:2}}};function KF(n){if(n===!1)return null;if(typeof n=="string"){const e=XF[n];return e||(console.warn(`[player] unknown environment "${n}"; using neutral default`),null)}return n}const qF=new Proxy({},{get:()=>()=>{}});function mv(n){if(!n)return null;const e={};for(const t of Object.keys(n)){const i=n[t];typeof i=="number"&&Number.isFinite(i)&&(e[t]=i)}return e}const _v=48,vu=.14,YF=16,jF=16,ZF=.003,JF=.05,QF=1.08,gv=4120,yv=5140,eN=0,tN=2200,nN=new S(0,700,0),iN=new S(-1,0,0),sN=new S(0,-1,0),aN=new S(0,900,0),rN=new S(0,1,0),oN=new S(9600,-5500,12600).normalize();function lN(n,e){const t=Number.isFinite(e)&&e>0?e:1.7777777777777777,i=n==="overhead"?nN.clone():aN.clone(),s=n==="overhead"?iN.clone():rN.clone(),a=n==="overhead"?sN.clone():oN.clone(),r=cN({aspect:t,fov:_v,forward:a,margin:QF,target:i,up:s});return{position:i.clone().addScaledVector(a,-r),target:i,up:s,fov:_v}}function cN(n){const{aspect:e,fov:t,forward:i,margin:s,target:a,up:r}=n,o=i.clone().normalize(),l=new S().crossVectors(o,r).normalize(),c=new S().crossVectors(l,o).normalize(),u=Math.tan(vt.degToRad(t)/2),d=u*e;let h=1;for(const f of[-gv,gv])for(const p of[eN,tN])for(const g of[-yv,yv]){const _=new S(f,p,g).sub(a),m=Math.abs(_.dot(l)),v=Math.abs(_.dot(c)),y=_.dot(o);h=Math.max(h,m/d-y,v/u-y)}return Math.max(1,h*s)}function uN(n){const e=new Mt;return e.name="replayRoot",e.matrixAutoUpdate=!1,e.matrix.set(1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1),n.add(e),e}class dN extends EventTarget{container;adapter;replay;options;sceneManager;arenaManager;actorManager;effectsManager;hitboxManager;controls;replayRoot;sceneState;effectsEnabled;ready;plugins=[];beforeRenderCallbacks=[];resizeObserver=null;animationFrameId=null;disposed=!1;playing=!1;readyResolved=!1;speed;loop;currentTime=0;lastTickAt=null;freeCameraTransition=null;cameraDistanceScaleValue;customCameraSettingsValue;cameraViewModeValue;attachedPlayerIdValue;ballCamEnabledValue;boostMeterEnabledValue;boostPickupAnimationEnabledValue;hitboxWireframesEnabledValue;hitboxOnlyModeEnabledValue;hitboxTypeByName=null;hitboxTeamByName=null;hitboxesActive=!1;skipPostGoalTransitionsEnabledValue;skipKickoffsEnabledValue;attachmentTouched=!1;liveGameState=null;kickoffGameState=null;timelineSegmentsCacheKey=null;timelineSegmentsCache=[];constructor(e,t,i={},s=null){super(),this.container=e,this.adapter=t,this.replay=s,this.options=i,this.updateReplayGameStates(),this.speed=Math.max(.1,i.initialPlaybackRate??i.speed??1),this.loop=i.loop??!1,this.cameraDistanceScaleValue=Math.max(.25,i.initialCameraDistanceScale??1),this.customCameraSettingsValue=mv(i.initialCustomCameraSettings),this.attachedPlayerIdValue=i.initialAttachedPlayerId??null,this.cameraViewModeValue=i.initialCameraViewMode??(this.attachedPlayerIdValue?"follow":"free"),this.ballCamEnabledValue=i.initialBallCamEnabled??null,this.boostMeterEnabledValue=i.initialBoostMeterEnabled??!1,this.boostPickupAnimationEnabledValue=i.initialBoostPickupAnimationEnabled??!0,this.hitboxWireframesEnabledValue=i.initialHitboxWireframesEnabled??!1,this.hitboxOnlyModeEnabledValue=i.initialHitboxOnlyModeEnabled??!1,this.skipPostGoalTransitionsEnabledValue=i.initialSkipPostGoalTransitionsEnabled??!0,this.skipKickoffsEnabledValue=i.initialSkipKickoffsEnabled??!1,this.sceneManager=new RD(e,{assetBase:i.assetBase,preserveDrawingBuffer:i.preserveDrawingBuffer}),this.sceneManager.initDefaultEnvironment(),this.applyEnvironmentSpec(i.environment??WF),this.arenaManager=new vO(this.scene,{assetBase:i.assetBase}),this.effectsEnabled=i.effects??!0,this.effectsManager=this.effectsEnabled?new wF(this.scene):qF,this.actorManager=new cF(this.scene,this.effectsManager,{assetBase:i.assetBase}),i.motionInterpolation&&this.setMotionInterpolation(i.motionInterpolation),this.actorManager.initFromFramework(t),this.actorManager.initInterpolants(t.getTimelines()),this.hitboxManager=new MF(this.scene),this.syncGoalEvents(),this.controls=new uD(this.camera,this.renderer.domElement),this.controls.zoomSpeed=2.5,this.camera.position.set(0,4e3,6e3),this.controls.target.set(0,200,0),this.controls.update(),this.replayRoot=uN(this.scene),this.sceneState=this.createSceneState(),this.ready=Promise.all([this.arenaManager.loadArenaMeshes().catch(a=>{console.warn("[player] arena load failed",a)}),this.prepareReplayAssets()]).then(()=>{this.markReady()}),this.installResizeHandling();for(const a of i.plugins??[])this.installPlugin(a,!1);this.plugins.some(a=>a.plugin.id==="boost-pads")||this.installPlugin(CF(),!1),this.applyInitialCameraOptions(),this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded(),this.scheduleAnimationFrame(),this.emitChange(),i.autoplay&&this.play()}get scene(){return this.sceneManager.scene}get camera(){return this.sceneManager.camera}get renderer(){return this.sceneManager.renderer}get duration(){return this.adapter.duration}async replaceReplay(e,t,i={}){if(this.disposed)throw new Error("Cannot replace replay on a disposed ReplayPlayer");const s=i.preservePlayback??this.playing;this.playing&&this.setPlayingInternal(!1),this.teardownPlugins(),this.effectsManager.reset(),this.effectsManager.clearEvents?.(),this.hitboxManager.reset(),this.actorManager.reset(),this.adapter=e,this.replay=t,this.updateReplayGameStates(),this.timelineSegmentsCacheKey=null,this.timelineSegmentsCache=[],this.hitboxTypeByName=null,this.hitboxTeamByName=null,this.hitboxesActive=!1,this.freeCameraTransition=null,this.actorManager.initFromFramework(e),this.actorManager.initInterpolants(e.getTimelines()),this.syncGoalEvents();const a=this.attachedPlayerIdValue&&this.adapter.playerList.some(r=>r.id===this.attachedPlayerIdValue)?this.attachedPlayerIdValue:null;a!==this.attachedPlayerIdValue&&(this.attachedPlayerIdValue=a,this.cameraViewModeValue==="follow"&&(this.cameraViewModeValue="free")),this.seekInternal(i.currentTime??0),this.readyResolved=!1,this.ready=this.prepareReplayAssets().then(()=>{this.markReady()}),await this.ready,this.setupPlugins(),this.applyInitialCameraOptions(),this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded(),s&&this.setPlayingInternal(!0),this.render(),this.emitChange()}setEnvironment(e){this.applyEnvironmentSpec(e)}applyEnvironmentSpec(e){const t=KF(e);if(!t){this.sceneManager.setDefaultBackground();return}this.sceneManager.applyEnvironment(t).catch(i=>{console.warn(`[player] environment "${t.id}" failed to load`,i)})}play(){this.playing||(this.setPlayingInternal(!0),this.emitChange())}pause(){this.playing&&(this.setPlayingInternal(!1),this.emitChange())}togglePlayback(){this.playing?this.pause():this.play()}seek(e){this.seekInternal(e),this.playing&&(this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded()),this.emitChange()}setPlaybackRate(e){this.speed=Math.max(.1,e),this.emitChange()}setLoop(e){this.loop=e}setMotionInterpolation(e){this.actorManager.interpolationMethod=e==="linear"?"lerp":"hermite"}setFrameIndex(e){const t=this.adapter.frameTimes;if(t.length===0||!Number.isFinite(e))return;const i=Math.min(Math.max(Math.trunc(e),0),t.length-1);this.playing&&this.setPlayingInternal(!1),this.seekInternal(t[i]),this.emitChange()}stepFrames(e){Number.isFinite(e)&&this.setFrameIndex(this.adapter.frameIndexAt(this.currentTime)+Math.trunc(e))}stepForwardFrame(){this.stepFrames(1)}stepBackwardFrame(){this.stepFrames(-1)}setCameraDistanceScale(e){this.cameraDistanceScaleValue=Math.max(.25,e),this.getCameraPlugin()?.setDistanceScale(this.cameraDistanceScaleValue),this.emitChange()}setCustomCameraSettings(e){this.applyCustomCameraSettings(e),this.emitChange()}setAttachedPlayer(e){this.attachedPlayerIdValue=e,this.cameraViewModeValue=e?"follow":"free",this.attachmentTouched=!0,this.freeCameraTransition=null,this.syncCameraAttachment(),this.emitChange()}setCameraViewMode(e){this.cameraViewModeValue=e,this.attachmentTouched=!0,this.freeCameraTransition=null,this.syncCameraAttachment(),this.emitChange()}setFreeCameraPreset(e,t={}){this.cameraViewModeValue="free",this.attachmentTouched=!0,this.syncCameraAttachment();const i=lN(e,this.camera.aspect);t.instant?(this.camera.position.copy(i.position),this.controls.target.copy(i.target),this.camera.up.copy(i.up).normalize(),this.camera.fov=i.fov,this.camera.updateProjectionMatrix(),this.camera.lookAt(i.target),this.controls.enabled=!0,this.freeCameraTransition=null):this.freeCameraTransition=i,this.emitChange()}setBallCamEnabled(e){this.ballCamEnabledValue=e,this.getCameraPlugin()?.setBallCam(e),this.emitChange()}setBoostMeterEnabled(e){this.boostMeterEnabledValue=e,this.emitChange()}setBoostPickupAnimationEnabled(e){this.boostPickupAnimationEnabledValue=e,this.emitChange()}setHitboxWireframesEnabled(e){this.hitboxWireframesEnabledValue=e,this.emitChange()}setHitboxOnlyModeEnabled(e){this.hitboxOnlyModeEnabledValue=e,this.emitChange()}setSkipPostGoalTransitionsEnabled(e){this.skipPostGoalTransitionsEnabledValue=e,e&&this.playing&&this.skipPostGoalTransitionIfNeeded(),this.emitChange()}setSkipKickoffsEnabled(e){this.skipKickoffsEnabledValue=e,e&&this.playing&&(this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded()),this.emitChange()}setState(e){e.speed!==void 0&&(this.speed=Math.max(.1,e.speed)),e.cameraDistanceScale!==void 0&&(this.cameraDistanceScaleValue=Math.max(.25,e.cameraDistanceScale),this.getCameraPlugin()?.setDistanceScale(this.cameraDistanceScaleValue)),e.customCameraSettings!==void 0&&this.applyCustomCameraSettings(e.customCameraSettings),e.cameraViewMode!==void 0&&(this.cameraViewModeValue=e.cameraViewMode,this.attachmentTouched=!0),e.attachedPlayerId!==void 0&&(this.attachedPlayerIdValue=e.attachedPlayerId,this.attachmentTouched=!0,e.cameraViewMode===void 0&&(this.cameraViewModeValue=e.attachedPlayerId?"follow":"free")),(e.cameraViewMode!==void 0||e.attachedPlayerId!==void 0)&&(this.freeCameraTransition=null,this.syncCameraAttachment()),e.useReplayBallCam===!0?(this.ballCamEnabledValue=null,this.getCameraPlugin()?.setBallCam(null)):e.ballCamEnabled!==void 0&&(this.ballCamEnabledValue=e.ballCamEnabled,this.getCameraPlugin()?.setBallCam(e.ballCamEnabled)),e.boostMeterEnabled!==void 0&&(this.boostMeterEnabledValue=e.boostMeterEnabled),e.boostPickupAnimationEnabled!==void 0&&(this.boostPickupAnimationEnabledValue=e.boostPickupAnimationEnabled),e.hitboxWireframesEnabled!==void 0&&(this.hitboxWireframesEnabledValue=e.hitboxWireframesEnabled),e.hitboxOnlyModeEnabled!==void 0&&(this.hitboxOnlyModeEnabledValue=e.hitboxOnlyModeEnabled),e.skipPostGoalTransitionsEnabled!==void 0&&(this.skipPostGoalTransitionsEnabledValue=e.skipPostGoalTransitionsEnabled),e.skipKickoffsEnabled!==void 0&&(this.skipKickoffsEnabledValue=e.skipKickoffsEnabled),e.currentTime!==void 0&&this.seekInternal(e.currentTime),e.playing!==void 0&&e.playing!==this.playing&&this.setPlayingInternal(e.playing),this.playing&&(e.currentTime!==void 0||e.playing!==void 0)&&(this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded()),this.emitChange()}getState(){const e=this.adapter.frameIndexAt(this.currentTime),t=this.getCameraPlugin();let i=this.cameraViewModeValue,s=this.attachedPlayerIdValue;if(t)if(t.getMode()==="follow"){i="follow";const a=t.getTarget();s=(a?this.adapter.playerList.find(o=>o.name===a):void 0)?.id??s}else i="free",s=null;return{currentTime:this.currentTime,duration:this.duration,frameIndex:e,activeMetadata:this.replay?UF(this.replay,e,this.currentTime):null,playing:this.playing,speed:this.speed,cameraDistanceScale:this.cameraDistanceScaleValue,customCameraSettings:this.customCameraSettingsValue,cameraViewMode:i,attachedPlayerId:s,ballCamEnabled:t?t.getBallCam():this.ballCamEnabledValue??!1,useReplayBallCam:this.ballCamEnabledValue===null,effectiveBallCamEnabled:t?t.getBallCam():this.ballCamEnabledValue??!1,boostMeterEnabled:this.boostMeterEnabledValue,boostPickupAnimationEnabled:this.boostPickupAnimationEnabledValue,hitboxWireframesEnabled:this.hitboxWireframesEnabledValue,hitboxOnlyModeEnabled:this.hitboxOnlyModeEnabledValue,skipPostGoalTransitionsEnabled:this.skipPostGoalTransitionsEnabledValue,skipKickoffsEnabled:this.skipKickoffsEnabledValue}}getSnapshot(){return this.getState()}getTimelineDuration(){return this.replay?.duration??this.duration}getTimelineCurrentTime(){return this.projectReplayTimeToTimeline(this.currentTime).timelineTime}getTimelineSegments(){if(!this.replay)return[];const e=`${this.skipPostGoalTransitionsEnabledValue}:${this.skipKickoffsEnabledValue}`;return this.timelineSegmentsCacheKey===e?this.timelineSegmentsCache:(this.timelineSegmentsCacheKey=e,this.timelineSegmentsCache=DF(this.replay,this.skipPostGoalTransitionsEnabledValue,this.skipKickoffsEnabledValue,this.liveGameState,this.kickoffGameState),this.timelineSegmentsCache)}projectReplayTimeToTimeline(e){return OF(this.replay?.duration??this.duration,this.getTimelineSegments(),e)}projectTimelineTimeToReplay(e){return FF(this.replay?.duration??this.duration,this.getTimelineDuration(),this.getTimelineSegments(),e)}subscribe(e){const t=i=>{e(i.detail)};return this.addEventListener("change",t),e(this.getState()),()=>{this.removeEventListener("change",t)}}onBeforeRender(e){return this.beforeRenderCallbacks.push(e),()=>{const t=this.beforeRenderCallbacks.indexOf(e);t>=0&&this.beforeRenderCallbacks.splice(t,1)}}addPlugin(e){return this.installPlugin(e,!0)}removePlugin(e){const t=this.plugins.findIndex(s=>s.plugin.id===e);if(t<0)return!1;const[i]=this.plugins.splice(t,1);return i.plugin.teardown?.(this.createPluginContext()),!0}getPlugins(){return this.plugins.map(e=>e.plugin)}destroy(){if(!this.disposed){for(this.disposed=!0,this.playing=!1,this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.beforeRenderCallbacks.length=0;this.plugins.length>0;)this.plugins.pop()?.plugin.teardown?.(this.createPluginContext());this.controls.dispose(),this.effectsEnabled&&this.effectsManager.reset(),this.hitboxManager.dispose(),this.actorManager.reset(),this.sceneManager.dispose()}}dispose(){this.destroy()}setPlayingInternal(e){this.playing=e,this.lastTickAt=null,e?this.actorManager.resumeAnimations():this.actorManager.pauseAnimations()}prepareReplayAssets(){return this.actorManager.waitForBallModel().catch(()=>!1).then(()=>{if(this.effectsEnabled)try{this.effectsManager.setRenderContext(this.renderer,this.camera)}catch(e){console.warn("[player] explosion warmup failed",e)}})}markReady(){this.readyResolved=!0,this.lastTickAt=null}updateReplayGameStates(){if(!this.replay){this.liveGameState=null,this.kickoffGameState=null;return}this.liveGameState=RF(this.replay),this.kickoffGameState=PF(this.replay,this.liveGameState)}syncGoalEvents(){this.effectsEnabled&&(this.effectsManager.clearEvents?.(),this.replay&&this.effectsManager.setGoalEvents(this.replay.timelineEvents.filter(e=>e.kind==="goal").map(e=>({frame:e.frame,time:e.time,team:e.isTeamZero?0:1,playerName:e.playerName??""}))))}teardownPlugins(){const e=this.createPluginContext();for(const t of this.plugins)t.plugin.teardown?.(e)}setupPlugins(){for(const e of this.plugins)e.plugin.setup?.(this.createPluginContext()),e.plugin.id==="camera"&&this.pushCameraParityState(),e.plugin.onStateChange?.(this.createPluginStateContext(this.getState()))}seekInternal(e){this.currentTime=vt.clamp(e,0,this.duration),this.actorManager.seekAnimations(this.currentTime),this.effectsManager.resetBallTrail(),this.effectsManager.clearGoalExplosions?.(),this.actorManager.resetGoalExplosionPlaybackState(),this.actorManager.resetWheelTracking()}getPlaybackEndTime(){return this.replay?NF(this.replay.duration,this.getTimelineSegments()):this.duration}skipPastKickoffIfNeeded(){if(!this.replay||!this.skipKickoffsEnabledValue)return!1;const e=HF(this.replay,this.currentTime,this.liveGameState,this.kickoffGameState);return e===null?!1:(this.seekInternal(e),!0)}skipPostGoalTransitionIfNeeded(){if(!this.replay||!this.skipPostGoalTransitionsEnabledValue)return!1;const e=VF(this.replay,this.currentTime,this.liveGameState,this.kickoffGameState);return e===null?!1:(this.seekInternal(e),!0)}getCameraPlugin(){const e=this.plugins.find(t=>t.plugin.id==="camera")?.plugin;return e&&typeof e.follow=="function"?e:null}playerNameForId(e){return this.adapter.playerList.find(t=>t.id===e)?.name??null}applyReplayBallCam(){if(this.ballCamEnabledValue!==null||this.cameraViewModeValue!=="follow"||!this.attachedPlayerIdValue)return;const e=this.playerNameForId(this.attachedPlayerIdValue);if(!e)return;const t=this.adapter.getAllPlayers().find(i=>i.name===e);t&&this.getCameraPlugin()?.setBallCam(t.isBallCam)}syncCameraAttachment(){const e=this.getCameraPlugin();if(e){if(this.cameraViewModeValue==="follow"&&this.attachedPlayerIdValue){const t=this.playerNameForId(this.attachedPlayerIdValue);if(!t){console.warn(`[player] no player with id ${JSON.stringify(this.attachedPlayerIdValue)}`);return}this.camera.up.set(0,1,0),e.follow(t);return}e.getMode()==="follow"&&e.release()}}applyCustomCameraSettings(e){this.customCameraSettingsValue=mv(e);const t=this.getCameraPlugin();t&&(t.setCameraSettings(null),this.customCameraSettingsValue&&t.setCameraSettings(this.customCameraSettingsValue))}pushCameraParityState(){const e=this.getCameraPlugin();e&&(this.cameraDistanceScaleValue!==1&&e.setDistanceScale(this.cameraDistanceScaleValue),this.customCameraSettingsValue&&e.setCameraSettings(this.customCameraSettingsValue),this.ballCamEnabledValue!==null&&e.setBallCam(this.ballCamEnabledValue),this.attachmentTouched&&this.syncCameraAttachment())}applyInitialCameraOptions(){const e=this.options;(e.initialAttachedPlayerId!==void 0||e.initialCameraViewMode!==void 0)&&(this.attachmentTouched=!0),this.pushCameraParityState()}computeFrameRenderInfo(){const e=this.adapter.frameTimes,t=this.adapter.frameIndexAt(this.currentTime),i=Math.min(t+1,Math.max(e.length-1,0)),s=e[t]??0,a=e[i]??s,r=a>s?vt.clamp((this.currentTime-s)/(a-s),0,1):0;return{frameIndex:t,nextFrameIndex:i,alpha:r,currentTime:this.currentTime}}installResizeHandling(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>this.sceneManager.onWindowResize()),this.resizeObserver.observe(this.container))}scheduleAnimationFrame(){this.animationFrameId!==null||this.disposed||(this.animationFrameId=requestAnimationFrame(this.tick))}tick=e=>{if(this.animationFrameId=null,this.disposed)return;let t=!1,i=0;if(this.playing&&this.readyResolved){i=this.lastTickAt===null?0:Math.min(.1,(e-this.lastTickAt)/1e3),this.lastTickAt=e;let s=this.currentTime+i*this.speed;const a=this.getPlaybackEndTime();s>=a&&(this.loop?(s=0,this.actorManager.seekAnimations(0),this.effectsManager.resetBallTrail(),this.effectsManager.clearGoalExplosions?.(),this.actorManager.resetGoalExplosionPlaybackState(),this.actorManager.resetWheelTracking()):(s=a,this.playing=!1)),t=s!==this.currentTime||!this.playing,this.currentTime=s,this.playing&&(t=this.skipPostGoalTransitionIfNeeded()||t,t=this.skipPastKickoffIfNeeded()||t)}else this.playing&&(this.lastTickAt=null);this.render(i),t&&this.emitChange(),this.scheduleAnimationFrame()};renderFrame(e=0){if(this.adapter.seek(this.currentTime),this.playing&&this.actorManager.updateAnimations(e*this.speed),this.actorManager.updateFromFramework(this.adapter,this.currentTime),this.updatePlayerStates(),this.applyReplayBallCam(),this.updateHitboxVisualization(),this.effectsManager.update(e,this.playing,this.speed),this.playing&&this.actorManager.updateWheelRotations(),this.sceneManager.updateSkyboxAnimation(this.playing?e*this.speed:0),this.controls.update(),this.beforeRenderCallbacks.length>0){const t=this.computeFrameRenderInfo();for(const i of[...this.beforeRenderCallbacks])i(t)}if(this.plugins.length>0){const t=this.createRenderContext();for(const i of this.plugins)i.plugin.beforeRender?.(t)}this.updateFreeCameraTransition(),this.renderer.render(this.scene,this.camera)}render(e=0){this.renderFrame(e)}updateFreeCameraTransition(){const e=this.freeCameraTransition;if(!e)return;this.controls.enabled=!1,this.camera.position.lerp(e.position,vu),this.controls.target.lerp(e.target,vu),this.camera.up.lerp(e.up,vu).normalize(),this.camera.fov=vt.lerp(this.camera.fov,e.fov,vu),this.camera.updateProjectionMatrix(),this.camera.lookAt(this.controls.target);const t=this.camera.position.distanceToSquared(e.position)<=YF,i=this.controls.target.distanceToSquared(e.target)<=jF,s=this.camera.up.angleTo(e.up)<=ZF,a=Math.abs(this.camera.fov-e.fov)<=JF;!t||!i||!s||!a||(this.camera.position.copy(e.position),this.controls.target.copy(e.target),this.camera.up.copy(e.up).normalize(),this.camera.fov=e.fov,this.camera.updateProjectionMatrix(),this.camera.lookAt(e.target),this.controls.enabled=!0,this.freeCameraTransition=null)}updatePlayerStates(){if(!this.playing)return;const e=this.hitboxOnlyModeEnabledValue;for(const t of this.adapter.getAllPlayers())this.actorManager.updateBoostState(t.name,t.isBoosting&&!e,t.isKickoffReset),this.actorManager.updateSupersonicState(t.name,t.isSupersonic&&!e,t.team)}updateHitboxVisualization(){const e=this.hitboxWireframesEnabledValue||this.hitboxOnlyModeEnabledValue;if(!e&&!this.hitboxesActive||(this.hitboxesActive=e,this.hitboxManager.setEnabled(e),!e))return;const t=this.actorManager;if(this.hitboxTypeByName||(this.hitboxTypeByName=new Map(this.adapter.getAllPlayers().map(i=>[i.name,i.hitboxType]))),this.hitboxTeamByName||(this.hitboxTeamByName=new Map(this.adapter.getAllPlayers().map(i=>[i.name,i.team]))),this.hitboxManager.updateHitboxes(t.actors,t.playerNameToCarActorId,i=>this.hitboxTypeByName?.get(i)??"Octane",i=>this.hitboxTeamByName?.get(i)??null),this.hitboxOnlyModeEnabledValue)for(const i of Object.values(t.playerNameToCarActorId)){const s=i===void 0?void 0:t.actors[i];s&&(s.visible=!1)}}installPlugin(e,t){const i=typeof e=="function"?e():e;if(this.plugins.some(a=>a.plugin.id===i.id))throw new Error(`Player plugin "${i.id}" is already installed`);const s={definition:e,plugin:i};return this.plugins.push(s),i.setup?.(this.createPluginContext()),i.id==="camera"&&this.pushCameraParityState(),i.onStateChange?.(this.createPluginStateContext(this.getState())),t&&this.render(),()=>{const a=this.plugins.indexOf(s);a<0||(this.plugins.splice(a,1),i.teardown?.(this.createPluginContext()))}}createSceneState(){const e=this.actorManager,t=this,i=new we;return{get scene(){return t.scene},replayRoot:this.replayRoot,get camera(){return t.camera},get renderer(){return t.renderer},controls:this.controls,resize:()=>this.sceneManager.onWindowResize(),dispose:()=>this.destroy(),get ballMesh(){return(e.ballActorId!=null?e.actors[e.ballActorId]:null)??i},get playerMeshes(){const s=new Map;for(const a of t.adapter.playerList){const r=e.playerNameToCarActorId[a.name],o=r!=null?e.actors[r]:void 0;o&&s.set(a.id,o)}return s},playerBodyMeshes:new Map,playerHitboxes:new Map,playerBoostTrails:new Map,playerBoostMeters:new Map,playerDemoIndicators:new Map,updateWallVisibility:()=>{}}}createPluginContext(){return{player:this,replay:this.replay,options:this.options,scene:this.scene,camera:this.camera,renderer:this.renderer,container:this.container}}createPluginStateContext(e){return{...this.createPluginContext(),state:e}}createRenderContext(){const e=this.actorManager,t=this.adapter.ball,i={position:t.position,rotation:t.rotation,velocity:t.velocity,visible:t.visible,object3d:e.ballActorId!=null?e.actors[e.ballActorId]??null:null},s=this.adapter.getAllPlayers().map(a=>{const r=e.playerNameToCarActorId[a.name];return{id:a.id,name:a.name,team:a.team,carName:a.carName,hitboxType:a.hitboxType,position:a.position,rotation:a.rotation,velocity:a.velocity,boost:a.boost,isBoosting:a.isBoosting,visible:a.isVisible,object3d:r!=null?e.actors[r]??null:null}});return{...this.createPluginContext(),...this.computeFrameRenderInfo(),state:this.getState(),time:this.currentTime,ball:i,cars:s}}emitChange(){const e=this.getState(),t=this.createPluginStateContext(e);for(const i of this.plugins)i.plugin.onStateChange?.(t);this.dispatchEvent(new CustomEvent("change",{detail:e}))}}const Wt={LEFT:1,RIGHT:2,MIDDLE:4},$=Object.freeze({NONE:0,ROTATE:1,TRUCK:2,SCREEN_PAN:4,OFFSET:8,DOLLY:16,ZOOM:32,TOUCH_ROTATE:64,TOUCH_TRUCK:128,TOUCH_SCREEN_PAN:256,TOUCH_OFFSET:512,TOUCH_DOLLY:1024,TOUCH_ZOOM:2048,TOUCH_DOLLY_TRUCK:4096,TOUCH_DOLLY_SCREEN_PAN:8192,TOUCH_DOLLY_OFFSET:16384,TOUCH_DOLLY_ROTATE:32768,TOUCH_ZOOM_TRUCK:65536,TOUCH_ZOOM_OFFSET:131072,TOUCH_ZOOM_SCREEN_PAN:262144,TOUCH_ZOOM_ROTATE:524288}),Vr={NONE:0,IN:1,OUT:-1};function ka(n){return n.isPerspectiveCamera}function Js(n){return n.isOrthographicCamera}const Gr=Math.PI*2,vv=Math.PI/2,NT=1e-5,nl=Math.PI/180;function Ui(n,e,t){return Math.max(e,Math.min(t,n))}function Ot(n,e=NT){return Math.abs(n)0==f>u&&(f=u,t.value=(f-u)/a),f}function xv(n,e,t,i,s=1/0,a,r){i=Math.max(1e-4,i);const o=2/i,l=o*a,c=1/(1+l+.48*l*l+.235*l*l*l);let u=e.x,d=e.y,h=e.z,f=n.x-u,p=n.y-d,g=n.z-h;const _=u,m=d,v=h,y=s*i,b=y*y,T=f*f+p*p+g*g;if(T>b){const U=Math.sqrt(T);f=f/U*y,p=p/U*y,g=g/U*y}u=n.x-f,d=n.y-p,h=n.z-g;const x=(t.x+o*f)*a,M=(t.y+o*p)*a,C=(t.z+o*g)*a;t.x=(t.x-o*x)*c,t.y=(t.y-o*M)*c,t.z=(t.z-o*C)*c,r.x=u+(f+x)*c,r.y=d+(p+M)*c,r.z=h+(g+C)*c;const w=_-n.x,E=m-n.y,R=v-n.z,k=r.x-_,O=r.y-m,D=r.z-v;return w*k+E*O+R*D>0&&(r.x=_,r.y=m,r.z=v,t.x=(r.x-_)/a,t.y=(r.y-m)/a,t.z=(r.z-v)/a),r}function Tp(n,e){e.set(0,0),n.forEach(t=>{e.x+=t.clientX,e.y+=t.clientY}),e.x/=n.length,e.y/=n.length}function Mp(n,e){return Js(n)?(console.warn(`${e} is not supported in OrthographicCamera`),!0):!1}class hN{constructor(){this._listeners={}}addEventListener(e,t){const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){const i=this._listeners;return i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){const s=this._listeners[e];if(s!==void 0){const a=s.indexOf(t);a!==-1&&s.splice(a,1)}}removeAllEventListeners(e){if(!e){this._listeners={};return}Array.isArray(this._listeners[e])&&(this._listeners[e].length=0)}dispatchEvent(e){const i=this._listeners[e.type];if(i!==void 0){e.target=this;const s=i.slice(0);for(let a=0,r=s.length;a{},this._enabled=!0,this._state=$.NONE,this._viewport=null,this._changedDolly=0,this._changedZoom=0,this._hasRested=!0,this._boundaryEnclosesCamera=!1,this._needsUpdate=!0,this._updatedLastTime=!1,this._elementRect=new DOMRect,this._isDragging=!1,this._dragNeedsUpdate=!0,this._activePointers=[],this._lockedPointer=null,this._interactiveArea=new DOMRect(0,0,1,1),this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._isUserControllingOffset=!1,this._isUserControllingZoom=!1,this._lastDollyDirection=Vr.NONE,this._thetaVelocity={value:0},this._phiVelocity={value:0},this._radiusVelocity={value:0},this._targetVelocity=new tt.Vector3,this._focalOffsetVelocity=new tt.Vector3,this._zoomVelocity={value:0},this._truckInternal=(m,v,y,b)=>{let T,x;if(ka(this._camera)){const M=ft.copy(this._camera.position).sub(this._target),C=this._camera.getEffectiveFOV()*nl,w=M.length()*Math.tan(C*.5);T=this.truckSpeed*m*w/this._elementRect.height,x=this.truckSpeed*v*w/this._elementRect.height}else if(Js(this._camera)){const M=this._camera;T=this.truckSpeed*m*(M.right-M.left)/M.zoom/this._elementRect.width,x=this.truckSpeed*v*(M.top-M.bottom)/M.zoom/this._elementRect.height}else return;b?(y?this.setFocalOffset(this._focalOffsetEnd.x+T,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(T,0,!0),this.forward(-x,!0)):y?this.setFocalOffset(this._focalOffsetEnd.x+T,this._focalOffsetEnd.y+x,this._focalOffsetEnd.z,!0):this.truck(T,x,!0)},this._rotateInternal=(m,v)=>{const y=Gr*this.azimuthRotateSpeed*m/this._elementRect.height,b=Gr*this.polarRotateSpeed*v/this._elementRect.height;this.rotate(y,b,!0)},this._dollyInternal=(m,v,y)=>{const b=Math.pow(.95,-m*this.dollySpeed),T=this._sphericalEnd.radius,x=this._sphericalEnd.radius*b,M=Ui(x,this.minDistance,this.maxDistance),C=M-x;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(x,!0):this.infinityDolly&&!this.dollyToCursor?(this.dollyInFixed(C,!0),this._dollyToNoClamp(M,!0)):this._dollyToNoClamp(M,!0),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?x:M)-T,this._dollyControlCoord.set(v,y)),this._lastDollyDirection=Math.sign(-m)},this._zoomInternal=(m,v,y)=>{const b=Math.pow(.95,m*this.dollySpeed),T=this._zoom,x=this._zoom*b;this.zoomTo(x,!0),this.dollyToCursor&&(this._changedZoom+=x-T,this._dollyControlCoord.set(v,y))},typeof tt>"u"&&console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information."),this._camera=e,this._yAxisUpSpace=new tt.Quaternion().setFromUnitVectors(this._camera.up,wu),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=$.NONE,this._target=new tt.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new tt.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=new tt.Spherical().setFromVector3(ft.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace)),this._sphericalEnd=this._spherical.clone(),this._lastDistance=this._spherical.radius,this._zoom=this._camera.zoom,this._zoomEnd=this._zoom,this._lastZoom=this._zoom,this._nearPlaneCorners=[new tt.Vector3,new tt.Vector3,new tt.Vector3,new tt.Vector3],this._updateNearPlaneCorners(),this._boundary=new tt.Box3(new tt.Vector3(-1/0,-1/0,-1/0),new tt.Vector3(1/0,1/0,1/0)),this._cameraUp0=this._camera.up.clone(),this._target0=this._target.clone(),this._position0=this._camera.position.clone(),this._zoom0=this._zoom,this._focalOffset0=this._focalOffset.clone(),this._dollyControlCoord=new tt.Vector2,this.mouseButtons={left:$.ROTATE,middle:$.DOLLY,right:$.TRUCK,wheel:ka(this._camera)?$.DOLLY:Js(this._camera)?$.ZOOM:$.NONE},this.touches={one:$.TOUCH_ROTATE,two:ka(this._camera)?$.TOUCH_DOLLY_TRUCK:Js(this._camera)?$.TOUCH_ZOOM_TRUCK:$.NONE,three:$.TOUCH_TRUCK};const i=new tt.Vector2,s=new tt.Vector2,a=new tt.Vector2,r=m=>{if(!this._enabled||!this._domElement)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const b=this._domElement.getBoundingClientRect(),T=m.clientX/b.width,x=m.clientY/b.height;if(Tthis._interactiveArea.right||xthis._interactiveArea.bottom)return}const v=m.pointerType!=="mouse"?null:(m.buttons&Wt.LEFT)===Wt.LEFT?Wt.LEFT:(m.buttons&Wt.MIDDLE)===Wt.MIDDLE?Wt.MIDDLE:(m.buttons&Wt.RIGHT)===Wt.RIGHT?Wt.RIGHT:null;if(v!==null){const b=this._findPointerByMouseButton(v);b&&this._disposePointer(b)}if((m.buttons&Wt.LEFT)===Wt.LEFT&&this._lockedPointer)return;const y={pointerId:m.pointerId,clientX:m.clientX,clientY:m.clientY,deltaX:0,deltaY:0,mouseButton:v};this._activePointers.push(y),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),this._isDragging=!0,h(m)},o=m=>{m.cancelable&&m.preventDefault();const v=m.pointerId,y=this._lockedPointer||this._findPointerById(v);if(y){if(y.clientX=m.clientX,y.clientY=m.clientY,y.deltaX=m.movementX,y.deltaY=m.movementY,this._state=0,m.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else(!this._isDragging&&this._lockedPointer||this._isDragging&&(m.buttons&Wt.LEFT)===Wt.LEFT)&&(this._state=this._state|this.mouseButtons.left),this._isDragging&&(m.buttons&Wt.MIDDLE)===Wt.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),this._isDragging&&(m.buttons&Wt.RIGHT)===Wt.RIGHT&&(this._state=this._state|this.mouseButtons.right);f()}},l=m=>{const v=this._findPointerById(m.pointerId);if(!(v&&v===this._lockedPointer)){if(v&&this._disposePointer(v),m.pointerType==="touch")switch(this._activePointers.length){case 0:this._state=$.NONE;break;case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else this._state=$.NONE;p()}};let c=-1;const u=m=>{if(!this._domElement||!this._enabled||this.mouseButtons.wheel===$.NONE)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const x=this._domElement.getBoundingClientRect(),M=m.clientX/x.width,C=m.clientY/x.height;if(Mthis._interactiveArea.right||Cthis._interactiveArea.bottom)return}if(m.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===$.ROTATE||this.mouseButtons.wheel===$.TRUCK){const x=performance.now();c-x<1e3&&this._getClientRect(this._elementRect),c=x}const v=pN?-1:-3,y=m.deltaMode===1||m.ctrlKey?m.deltaY/v:m.deltaY/(v*10),b=this.dollyToCursor?(m.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,T=this.dollyToCursor?(m.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case $.ROTATE:{this._rotateInternal(m.deltaX,m.deltaY),this._isUserControllingRotate=!0;break}case $.TRUCK:{this._truckInternal(m.deltaX,m.deltaY,!1,!1),this._isUserControllingTruck=!0;break}case $.SCREEN_PAN:{this._truckInternal(m.deltaX,m.deltaY,!1,!0),this._isUserControllingTruck=!0;break}case $.OFFSET:{this._truckInternal(m.deltaX,m.deltaY,!0,!1),this._isUserControllingOffset=!0;break}case $.DOLLY:{this._dollyInternal(-y,b,T),this._isUserControllingDolly=!0;break}case $.ZOOM:{this._zoomInternal(-y,b,T),this._isUserControllingZoom=!0;break}}this.dispatchEvent({type:"control"})},d=m=>{if(!(!this._domElement||!this._enabled)){if(this.mouseButtons.right===Hm.ACTION.NONE){const v=m instanceof PointerEvent?m.pointerId:0,y=this._findPointerById(v);y&&this._disposePointer(y),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l);return}m.preventDefault()}},h=m=>{if(!this._enabled)return;if(Tp(this._activePointers,Kn),this._getClientRect(this._elementRect),i.copy(Kn),s.copy(Kn),this._activePointers.length>=2){const y=Kn.x-this._activePointers[1].clientX,b=Kn.y-this._activePointers[1].clientY,T=Math.sqrt(y*y+b*b);a.set(0,T);const x=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,M=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;s.set(x,M)}if(this._state=0,!m)this._lockedPointer&&(this._state=this._state|this.mouseButtons.left);else if("pointerType"in m&&m.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else!this._lockedPointer&&(m.buttons&Wt.LEFT)===Wt.LEFT&&(this._state=this._state|this.mouseButtons.left),(m.buttons&Wt.MIDDLE)===Wt.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),(m.buttons&Wt.RIGHT)===Wt.RIGHT&&(this._state=this._state|this.mouseButtons.right);((this._state&$.ROTATE)===$.ROTATE||(this._state&$.TOUCH_ROTATE)===$.TOUCH_ROTATE||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE)&&(this._sphericalEnd.theta=this._spherical.theta,this._sphericalEnd.phi=this._spherical.phi,this._thetaVelocity.value=0,this._phiVelocity.value=0),((this._state&$.TRUCK)===$.TRUCK||(this._state&$.SCREEN_PAN)===$.SCREEN_PAN||(this._state&$.TOUCH_TRUCK)===$.TOUCH_TRUCK||(this._state&$.TOUCH_SCREEN_PAN)===$.TOUCH_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN)&&(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),((this._state&$.DOLLY)===$.DOLLY||(this._state&$.TOUCH_DOLLY)===$.TOUCH_DOLLY||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE)&&(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),((this._state&$.ZOOM)===$.ZOOM||(this._state&$.TOUCH_ZOOM)===$.TOUCH_ZOOM||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_ZOOM_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE)&&(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),((this._state&$.OFFSET)===$.OFFSET||(this._state&$.TOUCH_OFFSET)===$.TOUCH_OFFSET||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET)&&(this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0)),this.dispatchEvent({type:"controlstart"})},f=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,Tp(this._activePointers,Kn);const v=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,y=v?-v.deltaX:s.x-Kn.x,b=v?-v.deltaY:s.y-Kn.y;if(s.copy(Kn),((this._state&$.ROTATE)===$.ROTATE||(this._state&$.TOUCH_ROTATE)===$.TOUCH_ROTATE||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE)&&(this._rotateInternal(y,b),this._isUserControllingRotate=!0),(this._state&$.DOLLY)===$.DOLLY||(this._state&$.ZOOM)===$.ZOOM){const T=this.dollyToCursor?(i.x-this._elementRect.x)/this._elementRect.width*2-1:0,x=this.dollyToCursor?(i.y-this._elementRect.y)/this._elementRect.height*-2+1:0,M=this.dollyDragInverted?-1:1;(this._state&$.DOLLY)===$.DOLLY?(this._dollyInternal(M*b*xu,T,x),this._isUserControllingDolly=!0):(this._zoomInternal(M*b*xu,T,x),this._isUserControllingZoom=!0)}if((this._state&$.TOUCH_DOLLY)===$.TOUCH_DOLLY||(this._state&$.TOUCH_ZOOM)===$.TOUCH_ZOOM||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_ZOOM_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE){const T=Kn.x-this._activePointers[1].clientX,x=Kn.y-this._activePointers[1].clientY,M=Math.sqrt(T*T+x*x),C=a.y-M;a.set(0,M);const w=this.dollyToCursor?(s.x-this._elementRect.x)/this._elementRect.width*2-1:0,E=this.dollyToCursor?(s.y-this._elementRect.y)/this._elementRect.height*-2+1:0;(this._state&$.TOUCH_DOLLY)===$.TOUCH_DOLLY||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET?(this._dollyInternal(C*xu,w,E),this._isUserControllingDolly=!0):(this._zoomInternal(C*xu,w,E),this._isUserControllingZoom=!0)}((this._state&$.TRUCK)===$.TRUCK||(this._state&$.TOUCH_TRUCK)===$.TOUCH_TRUCK||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK)&&(this._truckInternal(y,b,!1,!1),this._isUserControllingTruck=!0),((this._state&$.SCREEN_PAN)===$.SCREEN_PAN||(this._state&$.TOUCH_SCREEN_PAN)===$.TOUCH_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_ZOOM_SCREEN_PAN)&&(this._truckInternal(y,b,!1,!0),this._isUserControllingTruck=!0),((this._state&$.OFFSET)===$.OFFSET||(this._state&$.TOUCH_OFFSET)===$.TOUCH_OFFSET||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET)&&(this._truckInternal(y,b,!0,!1),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},p=()=>{Tp(this._activePointers,Kn),s.copy(Kn),this._dragNeedsUpdate=!1,(this._activePointers.length===0||this._activePointers.length===1&&this._activePointers[0]===this._lockedPointer)&&(this._isDragging=!1),this._activePointers.length===0&&this._domElement&&(this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this.dispatchEvent({type:"controlend"}))};this.lockPointer=()=>{!this._enabled||!this._domElement||(this.cancel(),this._lockedPointer={pointerId:-1,clientX:0,clientY:0,deltaX:0,deltaY:0,mouseButton:null},this._activePointers.push(this._lockedPointer),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.requestPointerLock(),this._domElement.ownerDocument.addEventListener("pointerlockchange",g),this._domElement.ownerDocument.addEventListener("pointerlockerror",_),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),h())},this.unlockPointer=()=>{var m,v,y;this._lockedPointer!==null&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),(m=this._domElement)===null||m===void 0||m.ownerDocument.exitPointerLock(),(v=this._domElement)===null||v===void 0||v.ownerDocument.removeEventListener("pointerlockchange",g),(y=this._domElement)===null||y===void 0||y.ownerDocument.removeEventListener("pointerlockerror",_),this.cancel()};const g=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},_=()=>{this.unlockPointer()};this._addAllEventListeners=m=>{this._domElement=m,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",r),this._domElement.addEventListener("pointercancel",l),this._domElement.addEventListener("wheel",u,{passive:!1}),this._domElement.addEventListener("contextmenu",d)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect="",this._domElement.removeEventListener("pointerdown",r),this._domElement.removeEventListener("pointercancel",l),this._domElement.removeEventListener("wheel",u,{passive:!1}),this._domElement.removeEventListener("contextmenu",d),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.removeEventListener("pointerlockchange",g),this._domElement.ownerDocument.removeEventListener("pointerlockerror",_))},this.cancel=()=>{this._state!==$.NONE&&(this._state=$.NONE,this._activePointers.length=0,p())},t&&this.connect(t),this.update(0)}get camera(){return this._camera}set camera(e){this._camera=e,this.updateCameraUp(),this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0}get enabled(){return this._enabled}set enabled(e){this._enabled=e,this._domElement&&(e?(this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none"):(this.cancel(),this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect=""))}get active(){return!this._hasRested}get currentAction(){return this._state}get distance(){return this._spherical.radius}set distance(e){this._spherical.radius===e&&this._sphericalEnd.radius===e||(this._spherical.radius=e,this._sphericalEnd.radius=e,this._needsUpdate=!0)}get azimuthAngle(){return this._spherical.theta}set azimuthAngle(e){this._spherical.theta===e&&this._sphericalEnd.theta===e||(this._spherical.theta=e,this._sphericalEnd.theta=e,this._needsUpdate=!0)}get polarAngle(){return this._spherical.phi}set polarAngle(e){this._spherical.phi===e&&this._sphericalEnd.phi===e||(this._spherical.phi=e,this._sphericalEnd.phi=e,this._needsUpdate=!0)}get boundaryEnclosesCamera(){return this._boundaryEnclosesCamera}set boundaryEnclosesCamera(e){this._boundaryEnclosesCamera=e,this._needsUpdate=!0}set interactiveArea(e){this._interactiveArea.width=Ui(e.width,0,1),this._interactiveArea.height=Ui(e.height,0,1),this._interactiveArea.x=Ui(e.x,0,1-this._interactiveArea.width),this._interactiveArea.y=Ui(e.y,0,1-this._interactiveArea.height)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}rotate(e,t,i=!1){return this.rotateTo(this._sphericalEnd.theta+e,this._sphericalEnd.phi+t,i)}rotateAzimuthTo(e,t=!1){return this.rotateTo(e,this._sphericalEnd.phi,t)}rotatePolarTo(e,t=!1){return this.rotateTo(this._sphericalEnd.theta,e,t)}rotateTo(e,t,i=!1){this._isUserControllingRotate=!1;const s=Ui(e,this.minAzimuthAngle,this.maxAzimuthAngle),a=Ui(t,this.minPolarAngle,this.maxPolarAngle);this._sphericalEnd.theta=s,this._sphericalEnd.phi=a,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,i||(this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi);const r=!i||Ct(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ct(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(r)}dolly(e,t=!1){return this.dollyTo(this._sphericalEnd.radius-e,t)}dollyTo(e,t=!1){return this._isUserControllingDolly=!1,this._lastDollyDirection=Vr.NONE,this._changedDolly=0,this._dollyToNoClamp(Ui(e,this.minDistance,this.maxDistance),t)}_dollyToNoClamp(e,t=!1){const i=this._sphericalEnd.radius;if(this.colliderMeshes.length>=1){const r=this._collisionTest(),o=Ct(r,this._spherical.radius);if(!(i>e)&&o)return Promise.resolve();this._sphericalEnd.radius=Math.min(e,r)}else this._sphericalEnd.radius=e;this._needsUpdate=!0,t||(this._spherical.radius=this._sphericalEnd.radius);const a=!t||Ct(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(a)}dollyInFixed(e,t=!1){this._targetEnd.add(this._getCameraDirection(al).multiplyScalar(e)),t||this._target.copy(this._targetEnd);const i=!t||Ct(this._target.x,this._targetEnd.x,this.restThreshold)&&Ct(this._target.y,this._targetEnd.y,this.restThreshold)&&Ct(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(i)}zoom(e,t=!1){return this.zoomTo(this._zoomEnd+e,t)}zoomTo(e,t=!1){this._isUserControllingZoom=!1,this._zoomEnd=Ui(e,this.minZoom,this.maxZoom),this._needsUpdate=!0,t||(this._zoom=this._zoomEnd);const i=!t||Ct(this._zoom,this._zoomEnd,this.restThreshold);return this._changedZoom=0,this._createOnRestPromise(i)}pan(e,t,i=!1){return console.warn("`pan` has been renamed to `truck`"),this.truck(e,t,i)}truck(e,t,i=!1){this._camera.updateMatrix(),ts.setFromMatrixColumn(this._camera.matrix,0),ns.setFromMatrixColumn(this._camera.matrix,1),ts.multiplyScalar(e),ns.multiplyScalar(-t);const s=ft.copy(ts).add(ns),a=Tt.copy(this._targetEnd).add(s);return this.moveTo(a.x,a.y,a.z,i)}forward(e,t=!1){ft.setFromMatrixColumn(this._camera.matrix,0),ft.crossVectors(this._camera.up,ft),ft.multiplyScalar(e);const i=Tt.copy(this._targetEnd).add(ft);return this.moveTo(i.x,i.y,i.z,t)}elevate(e,t=!1){return ft.copy(this._camera.up).multiplyScalar(e),this.moveTo(this._targetEnd.x+ft.x,this._targetEnd.y+ft.y,this._targetEnd.z+ft.z,t)}moveTo(e,t,i,s=!1){this._isUserControllingTruck=!1;const a=ft.set(e,t,i).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,a,this.boundaryFriction),this._needsUpdate=!0,s||this._target.copy(this._targetEnd);const r=!s||Ct(this._target.x,this._targetEnd.x,this.restThreshold)&&Ct(this._target.y,this._targetEnd.y,this.restThreshold)&&Ct(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(r)}lookInDirectionOf(e,t,i,s=!1){const o=ft.set(e,t,i).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd);return this.setPosition(o.x,o.y,o.z,s)}fitToBox(e,t,{cover:i=!1,paddingLeft:s=0,paddingRight:a=0,paddingBottom:r=0,paddingTop:o=0}={}){const l=[],c=e.isBox3?Wr.copy(e):Wr.setFromObject(e);c.isEmpty()&&(console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve());const u=bv(this._sphericalEnd.theta,vv),d=bv(this._sphericalEnd.phi,vv);l.push(this.rotateTo(u,d,t));const h=ft.setFromSpherical(this._sphericalEnd).normalize(),f=Ev.setFromUnitVectors(h,Cp),p=Ct(Math.abs(h.y),1);p&&f.multiply(Rp.setFromAxisAngle(wu,u)),f.multiply(this._yAxisUpSpaceInverse);const g=Mv.makeEmpty();Tt.copy(c.min).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.min).setX(c.max.x).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.min).setY(c.max.y).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.max).setZ(c.min.z).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.min).setZ(c.max.z).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.max).setY(c.min.y).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.max).setX(c.min.x).applyQuaternion(f),g.expandByPoint(Tt),Tt.copy(c.max).applyQuaternion(f),g.expandByPoint(Tt),g.min.x-=s,g.min.y-=r,g.max.x+=a,g.max.y+=o,f.setFromUnitVectors(Cp,h),p&&f.premultiply(Rp.invert()),f.premultiply(this._yAxisUpSpace);const _=g.getSize(ft),m=g.getCenter(Tt).applyQuaternion(f);if(ka(this._camera)){const v=this.getDistanceToFitBox(_.x,_.y,_.z,i);l.push(this.moveTo(m.x,m.y,m.z,t)),l.push(this.dollyTo(v,t)),l.push(this.setFocalOffset(0,0,0,t))}else if(Js(this._camera)){const v=this._camera,y=v.right-v.left,b=v.top-v.bottom,T=i?Math.max(y/_.x,b/_.y):Math.min(y/_.x,b/_.y);l.push(this.moveTo(m.x,m.y,m.z,t)),l.push(this.zoomTo(T,t)),l.push(this.setFocalOffset(0,0,0,t))}return Promise.all(l)}fitToSphere(e,t){const i=[],a="isObject3D"in e?Hm.createBoundingSphere(e,Ap):Ap.copy(e);if(i.push(this.moveTo(a.center.x,a.center.y,a.center.z,t)),ka(this._camera)){const r=this.getDistanceToFitSphere(a.radius);i.push(this.dollyTo(r,t))}else if(Js(this._camera)){const r=this._camera.right-this._camera.left,o=this._camera.top-this._camera.bottom,l=2*a.radius,c=Math.min(r/l,o/l);i.push(this.zoomTo(c,t))}return i.push(this.setFocalOffset(0,0,0,t)),Promise.all(i)}setLookAt(e,t,i,s,a,r,o=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Vr.NONE,this._changedDolly=0;const l=Tt.set(s,a,r),c=ft.set(e,t,i);this._targetEnd.copy(l),this._sphericalEnd.setFromVector3(c.sub(l).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,o||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const u=!o||Ct(this._target.x,this._targetEnd.x,this.restThreshold)&&Ct(this._target.y,this._targetEnd.y,this.restThreshold)&&Ct(this._target.z,this._targetEnd.z,this.restThreshold)&&Ct(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ct(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Ct(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(u)}lerpLookAt(e,t,i,s,a,r,o,l,c,u,d,h,f,p=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Vr.NONE,this._changedDolly=0;const g=ft.set(s,a,r),_=Tt.set(e,t,i);vi.setFromVector3(_.sub(g).applyQuaternion(this._yAxisUpSpace));const m=$r.set(u,d,h),v=Tt.set(o,l,c);rl.setFromVector3(v.sub(m).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(g.lerp(m,f));const y=rl.theta-vi.theta,b=rl.phi-vi.phi,T=rl.radius-vi.radius;this._sphericalEnd.set(vi.radius+T*f,vi.phi+b*f,vi.theta+y*f),this.normalizeRotations(),this._needsUpdate=!0,p||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const x=!p||Ct(this._target.x,this._targetEnd.x,this.restThreshold)&&Ct(this._target.y,this._targetEnd.y,this.restThreshold)&&Ct(this._target.z,this._targetEnd.z,this.restThreshold)&&Ct(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ct(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Ct(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(x)}setPosition(e,t,i,s=!1){return this.setLookAt(e,t,i,this._targetEnd.x,this._targetEnd.y,this._targetEnd.z,s)}setTarget(e,t,i,s=!1){const a=this.getPosition(ft),r=this.setLookAt(a.x,a.y,a.z,e,t,i,s);return this._sphericalEnd.phi=Ui(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),r}setFocalOffset(e,t,i,s=!1){this._isUserControllingOffset=!1,this._focalOffsetEnd.set(e,t,i),this._needsUpdate=!0,s||this._focalOffset.copy(this._focalOffsetEnd);const a=!s||Ct(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&Ct(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&Ct(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(a)}setOrbitPoint(e,t,i){this._camera.updateMatrixWorld(),ts.setFromMatrixColumn(this._camera.matrixWorldInverse,0),ns.setFromMatrixColumn(this._camera.matrixWorldInverse,1),Da.setFromMatrixColumn(this._camera.matrixWorldInverse,2);const s=ft.set(e,t,i),a=s.distanceTo(this._camera.position),r=s.sub(this._camera.position);ts.multiplyScalar(r.x),ns.multiplyScalar(r.y),Da.multiplyScalar(r.z),ft.copy(ts).add(ns).add(Da),ft.z=ft.z+a,this.dollyTo(a,!1),this.setFocalOffset(-ft.x,ft.y,-ft.z,!1),this.moveTo(e,t,i,!1)}setBoundary(e){if(!e){this._boundary.min.set(-1/0,-1/0,-1/0),this._boundary.max.set(1/0,1/0,1/0),this._needsUpdate=!0;return}this._boundary.copy(e),this._boundary.clampPoint(this._targetEnd,this._targetEnd),this._needsUpdate=!0}setViewport(e,t,i,s){if(e===null){this._viewport=null;return}this._viewport=this._viewport||new tt.Vector4,typeof e=="number"?this._viewport.set(e,t,i,s):this._viewport.copy(e)}getDistanceToFitBox(e,t,i,s=!1){if(Mp(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const a=e/t,r=this._camera.getEffectiveFOV()*nl,o=this._camera.aspect;return((s?a>o:at.pointerId===e)}_findPointerByMouseButton(e){return this._activePointers.find(t=>t.mouseButton===e)}_disposePointer(e){this._activePointers.splice(this._activePointers.indexOf(e),1)}_encloseToBoundary(e,t,i){const s=t.lengthSq();if(s===0)return e;const a=Tt.copy(t).add(e),o=this._boundary.clampPoint(a,$r).sub(a),l=o.lengthSq();if(l===0)return e.add(t);if(l===s)return e;if(i===0)return e.add(t).add(o);{const c=1+i*l/t.dot(o);return e.add(Tt.copy(t).multiplyScalar(c)).add(o.multiplyScalar(1-i))}}_updateNearPlaneCorners(){if(ka(this._camera)){const e=this._camera,t=e.near,i=e.getEffectiveFOV()*nl,s=Math.tan(i*.5)*t,a=s*e.aspect;this._nearPlaneCorners[0].set(-a,-s,0),this._nearPlaneCorners[1].set(a,-s,0),this._nearPlaneCorners[2].set(a,s,0),this._nearPlaneCorners[3].set(-a,s,0)}else if(Js(this._camera)){const e=this._camera,t=1/e.zoom,i=e.left*t,s=e.right*t,a=e.top*t,r=e.bottom*t;this._nearPlaneCorners[0].set(i,a,0),this._nearPlaneCorners[1].set(s,a,0),this._nearPlaneCorners[2].set(s,r,0),this._nearPlaneCorners[3].set(i,r,0)}}_collisionTest(){let e=1/0;if(!(this.colliderMeshes.length>=1)||Mp(this._camera,"_collisionTest"))return e;const i=this._getTargetDirection(al);Pp.lookAt(wv,i,this._camera.up);for(let s=0;s<4;s++){const a=Tt.copy(this._nearPlaneCorners[s]);a.applyMatrix4(Pp);const r=$r.addVectors(this._target,a);Su.set(r,i),Su.far=this._spherical.radius+1;const o=Su.intersectObjects(this.colliderMeshes);o.length!==0&&o[0].distance{const i=()=>{this.removeEventListener("rest",i),t()};this.addEventListener("rest",i)}))}_addAllEventListeners(e){}_removeAllEventListeners(){}get dampingFactor(){return console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead."),0}set dampingFactor(e){console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead.")}get draggingDampingFactor(){return console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead."),0}set draggingDampingFactor(e){console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead.")}static createBoundingSphere(e,t=new tt.Sphere){const i=t,s=i.center;Wr.makeEmpty(),e.traverseVisible(r=>{r.isMesh&&Wr.expandByObject(r)}),Wr.getCenter(s);let a=0;return e.traverseVisible(r=>{if(!r.isMesh)return;const o=r;if(!o.geometry)return;const l=o.geometry.clone();l.applyMatrix4(o.matrixWorld);const u=l.attributes.position;for(let d=0,h=u.count;di.preventDefault()),this.isFollowingViewer=!1,this.followTargetPosition=new S,this.followTargetQuaternion=new dt,this.followPositionLerpFactor=.12,this.followRotationSlerpFactor=.1,this.hasFollowTarget=!1,this.isRightMouseDown=!1,this.lastMouseX=null,this.lastMouseY=null,this.savedCameraState=null,this.isInReplayMode=!1}setMode(e){if(this.mode=e,e==="ballOrbit"){if(this.controls.enabled=!0,this.lastBallOrbitPos=null,this.ballOrbitScrollHandler||(this.ballOrbitScrollHandler=t=>{if(this.mode==="ballOrbit"&&!this.isFollowingViewer){t.preventDefault();const i=Math.max(this.controls.distance*.2,100);t.deltaY>0?this.controls.dolly(-i,!0):this.controls.dolly(i,!0)}},this.domElement.addEventListener("wheel",this.ballOrbitScrollHandler,{passive:!1})),this.targetBall){const t=this.targetBall.position;this.camera.position.distanceTo(t),this.controls.setLookAt(this.camera.position.x,this.camera.position.y,this.camera.position.z,t.x,t.y,t.z,!1)}return}if(e==="free"){if(this.controls.enabled=!1,!this.freeCamKeys){this.freeCamKeys={forward:!1,backward:!1,left:!1,right:!1,up:!1,down:!1},this.freeCamSpeed=2e3,this.freeCamRotation={yaw:0,pitch:0};const t=new S;this.camera.getWorldDirection(t),this.freeCamRotation.yaw=Math.atan2(t.x,t.z),this.freeCamRotation.pitch=Math.asin(-t.y),this.onKeyDown=i=>this.handleFreeCamKeyDown(i),this.onKeyUp=i=>this.handleFreeCamKeyUp(i),this.onMouseMove=i=>this.handleFreeCamMouseMove(i),this.onMouseDown=i=>{i.button===2&&this.mode==="free"&&!this.isFollowingViewer&&(this.isRightMouseDown=!0,this.domElement.requestPointerLock?.())},this.onMouseUp=i=>{i.button===2&&(this.isRightMouseDown=!1,document.pointerLockElement===this.domElement&&document.exitPointerLock?.())},this.onPointerLockChange=()=>{document.pointerLockElement!==this.domElement&&(this.isRightMouseDown=!1)},this.onMouseLeave=()=>{document.pointerLockElement!==this.domElement&&(this.isRightMouseDown=!1)},this.onWindowBlur=()=>{this.isRightMouseDown=!1,document.pointerLockElement===this.domElement&&document.exitPointerLock?.(),this.freeCamKeys&&(this.freeCamKeys.forward=!1,this.freeCamKeys.backward=!1,this.freeCamKeys.left=!1,this.freeCamKeys.right=!1,this.freeCamKeys.up=!1,this.freeCamKeys.down=!1)},this.onVisibilityChange=()=>{document.hidden&&(this.isRightMouseDown=!1,document.pointerLockElement===this.domElement&&document.exitPointerLock?.(),this.freeCamKeys&&(this.freeCamKeys.forward=!1,this.freeCamKeys.backward=!1,this.freeCamKeys.left=!1,this.freeCamKeys.right=!1,this.freeCamKeys.up=!1,this.freeCamKeys.down=!1))},document.addEventListener("keydown",this.onKeyDown),document.addEventListener("keyup",this.onKeyUp),document.addEventListener("mousemove",this.onMouseMove),this.domElement.addEventListener("mousedown",this.onMouseDown),document.addEventListener("mouseup",this.onMouseUp),document.addEventListener("pointerlockchange",this.onPointerLockChange),this.domElement.addEventListener("mouseleave",this.onMouseLeave),window.addEventListener("blur",this.onWindowBlur),document.addEventListener("visibilitychange",this.onVisibilityChange)}this.isRightMouseDown=!1}else this.controls.enabled=!1,this.lastIsBallCam=null,this.currentBlend=0,this.targetBlend=0}setTargetCar(e){if(this.targetCar!==e&&(this.currentBallCamAngle=null,this.targetCar&&e)){this.targetHandoff={elapsed:0,duration:mN,startPosition:this.camera.position.clone(),startQuaternion:this.camera.quaternion.clone()};const t=new S().subVectors(this.camera.position,e.position);t.y=0,t.length()>.01&&(t.normalize(),this.smoothedCarYaw=Math.atan2(-t.x,-t.z)),this.lastCarPos&&this.lastCarPos.copy(e.position)}this.targetCar=e}setTargetBall(e){this.targetBall=e}handleFreeCamKeyDown(e){if(this.mode!=="free"||this.isFollowingViewer)return;const t=e.target;if(!(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable))switch(e.code){case"KeyW":case"ArrowUp":this.freeCamKeys.forward=!0;break;case"KeyS":case"ArrowDown":this.freeCamKeys.backward=!0;break;case"KeyA":case"ArrowLeft":this.freeCamKeys.left=!0;break;case"KeyD":case"ArrowRight":this.freeCamKeys.right=!0;break;case"Space":this.freeCamKeys.up=!0;break;case"ShiftLeft":case"ShiftRight":this.freeCamKeys.down=!0;break}}handleFreeCamKeyUp(e){switch(e.code){case"KeyW":case"ArrowUp":this.freeCamKeys.forward=!1;break;case"KeyS":case"ArrowDown":this.freeCamKeys.backward=!1;break;case"KeyA":case"ArrowLeft":this.freeCamKeys.left=!1;break;case"KeyD":case"ArrowRight":this.freeCamKeys.right=!1;break;case"Space":this.freeCamKeys.up=!1;break;case"ShiftLeft":case"ShiftRight":this.freeCamKeys.down=!1;break}}handleFreeCamMouseMove(e){if(this.mode!=="free"||!this.isRightMouseDown||this.isFollowingViewer)return;const t=e.movementX||0,i=e.movementY||0,s=.003;this.freeCamRotation.yaw-=t*s,this.freeCamRotation.pitch+=i*s,this.freeCamRotation.pitch=Math.max(-Math.PI/2+.01,Math.min(Math.PI/2-.01,this.freeCamRotation.pitch))}updateFreeCam(e){if(!this.freeCamKeys)return;const t=new S(Math.sin(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch),-Math.sin(this.freeCamRotation.pitch),Math.cos(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch));t.normalize();const i=new S(Math.sin(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch),-Math.sin(this.freeCamRotation.pitch),Math.cos(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch));i.normalize();const s=new S(Math.sin(this.freeCamRotation.yaw-Math.PI/2),0,Math.cos(this.freeCamRotation.yaw-Math.PI/2)),a=new S(0,1,0),r=new S,o=this.freeCamSpeed*e;this.freeCamKeys.forward&&r.add(i.clone().multiplyScalar(o)),this.freeCamKeys.backward&&r.add(i.clone().multiplyScalar(-o)),this.freeCamKeys.right&&r.add(s.clone().multiplyScalar(o)),this.freeCamKeys.left&&r.add(s.clone().multiplyScalar(-o)),this.freeCamKeys.up&&r.add(a.clone().multiplyScalar(o)),this.freeCamKeys.down&&r.add(a.clone().multiplyScalar(-o)),r.length()>0&&r.normalize().multiplyScalar(o),this.camera.position.add(r);const l=this.camera.position.clone().add(t);this.camera.lookAt(l),this.controls.setLookAt(this.camera.position.x,this.camera.position.y,this.camera.position.z,l.x,l.y,l.z,!1)}update(e,t=!0){if(this.isFollowingViewer){this.updateFollowInterpolation(e);return}if(this.mode==="free"){this.updateFreeCam(e),this.controls.update(e);return}if(this.mode==="ballOrbit"){if(this.targetBall){const p=this.targetBall.position;this.lastBallOrbitPos||(this.lastBallOrbitPos=p.clone());const g=new S().subVectors(p,this.lastBallOrbitPos);if(this.controls.setTarget(p.x,p.y,p.z,!1),g.lengthSq()>.01){const _=new S;this.controls.getPosition(_);const m=_.x+g.x,v=_.y+g.y,y=_.z+g.z;this.controls.setPosition(m,v,y,!1),this.lastBallOrbitPos.copy(p)}}this.controls.update(e);return}if(!this.targetCar){this.controls.update(e);return}const i=this.targetCar.position.clone(),s=this.targetCar.quaternion;if(this.lastIsBallCam!==null&&this.lastIsBallCam!==t&&!t){const p=new S().subVectors(this.camera.position,i);p.y=0,p.length()>.01&&(p.normalize(),this.smoothedCarYaw=Math.atan2(-p.x,-p.z))}this.lastIsBallCam=t;const a=this.calculateCarCamPosition(i,s,e),r=this.calculateBallCamPosition(i,s,e);this.targetBlend=t?1:0;const o=Math.max(.15,Math.min(.6,this.baseDuration/this.transitionSpeed)),l=e/o;this.currentBlendthis.targetBlend&&(this.currentBlend=Math.max(this.currentBlend-l,this.targetBlend));const c=this.currentBlend,u=c*c*(3-2*c),d=new S().lerpVectors(a.cameraPos,r.cameraPos,u);this._tempMatrix.lookAt(a.cameraPos,a.lookTarget,new S(0,1,0)),this._tempQuatCarCam.setFromRotationMatrix(this._tempMatrix),this._tempMatrix.lookAt(r.cameraPos,r.lookTarget,new S(0,1,0)),this._tempQuatBallCam.setFromRotationMatrix(this._tempMatrix),this._tempQuatCarCam.dot(this._tempQuatBallCam)<0&&this._tempQuatBallCam.set(-this._tempQuatBallCam.x,-this._tempQuatBallCam.y,-this._tempQuatBallCam.z,-this._tempQuatBallCam.w);const h=new dt().slerpQuaternions(this._tempQuatCarCam,this._tempQuatBallCam,u);if(this.targetHandoff){this.targetHandoff.elapsed+=e;const p=Math.min(1,this.targetHandoff.elapsed/this.targetHandoff.duration),g=p*p*(3-2*p),_=d.clone(),m=h.clone();d.lerpVectors(this.targetHandoff.startPosition,_,g),h.slerpQuaternions(this.targetHandoff.startQuaternion,m,g),p>=1&&(this.targetHandoff=null)}if(this.camera.position.copy(d),this.camera.quaternion.copy(h),this.followAngle!==0){const p=this.followAngle*Math.PI/180;this.camera.rotateX(-p)}this.currentCamPos||(this.currentCamPos=new S),this.currentLookTarget||(this.currentLookTarget=new S),this.currentCamPos.copy(d);const f=new S(0,0,-1).applyQuaternion(this.camera.quaternion);this.currentLookTarget.copy(d).add(f.multiplyScalar(100)),this.enforceMinHeight()}calculateBallCamPosition(e,t,i=1/60){if(!this.targetBall)return this.calculateCarCamPosition(e,t,i);const s=this.targetBall.position.clone(),a=new S().subVectors(e,s);a.y=0,a.normalize();const r=e.clone().add(a.multiplyScalar(this.followDistance)),o=s.y-e.y,c=Math.min(1,Math.max(0,o/800));r.y=e.y+this.followHeight-c*100,r.y.01)s.normalize(),u=Math.atan2(s.x,s.z);else if(a>.05){s.normalize();let y=Math.atan2(s.x,s.z)-o;for(;y>Math.PI;)y-=Math.PI*2;for(;y<-Math.PI;)y+=Math.PI*2;Math.abs(y)>Math.PI/2?u=o+Math.PI:u=o}else u=o;this.lastCarPos.copy(e),this.smoothedCarYaw===void 0&&(this.smoothedCarYaw=u);let d=u-this.smoothedCarYaw;for(;d>Math.PI;)d-=Math.PI*2;for(;d<-Math.PI;)d+=Math.PI*2;const h=c?this.swivelSpeed*.4:this.swivelSpeed;this.smoothedCarYaw+=d*Math.min(1,h*(1/60));const f=-Math.sin(this.smoothedCarYaw),p=-Math.cos(this.smoothedCarYaw),g=new S(e.x+f*this.followDistance,e.y+this.followHeight,e.z+p*this.followDistance);g.yMath.PI;)s-=Math.PI*2;for(;s<-Math.PI;)s+=Math.PI*2;this.followCurrentOrbitParams.azimuth+=s*.15,this.followCurrentOrbitParams.polar+=(this.followTargetOrbitParams.polar-this.followCurrentOrbitParams.polar)*.15,this.controls.setTarget(t.x,t.y,t.z,!1),this.controls.dollyTo(this.followCurrentOrbitParams.distance,!1),this.controls.rotateTo(this.followCurrentOrbitParams.azimuth,this.followCurrentOrbitParams.polar,!1),this.controls.update(e)}}else{if(this.camera.position.lerp(this.followTargetPosition,this.followPositionLerpFactor),this.camera.quaternion.slerp(this.followTargetQuaternion,this.followRotationSlerpFactor),this.freeCamRotation){const i=new S;this.camera.getWorldDirection(i),this.freeCamRotation.yaw=Math.atan2(i.x,i.z),this.freeCamRotation.pitch=Math.asin(-i.y)}const t=new S;this.camera.getWorldDirection(t),t.multiplyScalar(100).add(this.camera.position),this.controls.setLookAt(this.camera.position.x,this.camera.position.y,this.camera.position.z,t.x,t.y,t.z,!1)}}setDefaultFreecamPosition(){if(this.camera.position.copy(this.defaultFreecamPosition),this.camera.lookAt(this.defaultFreecamLookAt),this.freeCamRotation){const e=new S;this.camera.getWorldDirection(e),this.freeCamRotation.yaw=Math.atan2(e.x,e.z),this.freeCamRotation.pitch=Math.asin(-e.y)}this.controls.setLookAt(this.defaultFreecamPosition.x,this.defaultFreecamPosition.y,this.defaultFreecamPosition.z,this.defaultFreecamLookAt.x,this.defaultFreecamLookAt.y,this.defaultFreecamLookAt.z,!1)}getIsPointerLocked(){return this.isPointerLocked||!1}setPointerLockCallback(e){this.onPointerLockStateChange=e}dispose(){this.controls.dispose(),this.ballOrbitScrollHandler&&this.domElement.removeEventListener("wheel",this.ballOrbitScrollHandler),this.onKeyDown&&document.removeEventListener("keydown",this.onKeyDown),this.onKeyUp&&document.removeEventListener("keyup",this.onKeyUp),this.onMouseMove&&document.removeEventListener("mousemove",this.onMouseMove),this.onMouseDown&&this.domElement.removeEventListener("mousedown",this.onMouseDown),this.onMouseUp&&document.removeEventListener("mouseup",this.onMouseUp),this.onPointerLockChange&&document.removeEventListener("pointerlockchange",this.onPointerLockChange),this.onMouseLeave&&this.domElement.removeEventListener("mouseleave",this.onMouseLeave),this.onWindowBlur&&window.removeEventListener("blur",this.onWindowBlur),this.onVisibilityChange&&document.removeEventListener("visibilitychange",this.onVisibilityChange)}}function Av(n){if(n.pitch===void 0||n.angle!==void 0)return n;const{pitch:e,...t}=n;return{...t,angle:e}}const gN={distance:260,height:90,angle:-4,stiffness:.45,swivelSpeed:4.3,transitionSpeed:1.3,fov:110};function yN(n={}){let e=null,t=null,i=n.mode??(n.follow?"follow":"orbit"),s=n.follow??null,a=n.ballCam??null,r=a??!0,o=Av({...n.settings}),l=1;const c=n.useRecordedSettings!==!1;let u=null;const d=new S;let h=!1;function f(){if(!(!t||!e)){if(t.player.controls.enabled=i==="orbit",i==="free")e.setMode("free");else if(i==="ballOrbit"){const y=_();y&&e.setTargetBall(y),e.setMode("ballOrbit")}else e.setMode("car");u=null}}function p(){return!c||!t||!s?null:t.player.adapter.getPlayer(s)?.cameraSettings??null}function g(){const y={...gN,...p(),...o};return l!==1&&y.distance!==void 0&&(y.distance*=l),y}function _(){if(!t)return null;const y=t.player.actorManager;return y.ballActorId!=null?y.actors[y.ballActorId]??null:null}function m(y){const b=g().fov;if(!b)return;const T=b*Math.PI/180,x=16/9,M=2*Math.atan(Math.tan(T/2)/x),C=2*Math.atan(Math.tan(T/2)/y.aspect),w=Math.max(M,C)*180/Math.PI;Math.abs(y.fov-w)>.1&&(y.fov=w,y.updateProjectionMatrix())}function v(y,b){if(!e)return;if(i==="free"){o.freeCamSpeed&&(e.freeCamSpeed=o.freeCamSpeed),e.update(b);return}if(i==="ballOrbit"){y.ball.object3d&&e.setTargetBall(y.ball.object3d),e.update(b);return}const x=(s?y.cars.find(C=>C.name===s):void 0)?.object3d??null;if(!x){e.update(b);return}e.setTargetCar(x),y.ball.object3d&&e.setTargetBall(y.ball.object3d),e.setFollowSettings(g());const M=s?y.player.adapter.getPlayer(s):void 0;r=a??M?.isBallCam??!0,d.copy(x.position),h=!0,e.update(b,r)}return{id:"camera",setup(y){t=y,e=new _N(y.camera,y.renderer.domElement),f()},beforeRender(y){if(!e||(m(y.camera),i==="orbit"))return;const b=performance.now(),T=u===null?1/60:Math.min(.1,(b-u)/1e3);u=b,v(y,T)},teardown(){i="orbit",t&&(t.player.controls.enabled=!0),e?.dispose(),e=null,t=null},setMode(y){y!==i&&(i=y,f())},getMode(){return i},follow(y){s=y,i="follow",f()},release(){i="orbit",t&&h&&t.player.controls.target.copy(d),f()},getTarget(){return s},setBallCam(y){a=y,y!==null&&(r=y)},getBallCam(){return r},setCameraSettings(y){o=y===null?{}:{...o,...Av(y)}},setDistanceScale(y){l=Math.max(.25,y)},getDistanceScale(){return l},getCameraSettings(){return g()},getRecordedSettings(){const y=p();return y?{...y}:null}}}const vN={"top-left":"top: 8px; left: 8px;","top-right":"top: 8px; right: 8px;","bottom-left":"bottom: 8px; left: 8px;","bottom-right":"bottom: 8px; right: 8px;"};function bN(n={}){const e=n.corner??"top-right",t=n.updateIntervalMs??500,i=()=>typeof n.mount=="function"?n.mount():n.mount??null;let s=null,a=null,r=null,o=0,l=performance.now(),c=0,u=0;const d=typeof n.onSample=="function";return{id:"fps-overlay",setup(h){if(l=performance.now(),o=0,u=h.player.getState().frameIndex,c=u,d)return;const f=i(),p=f!=null;s=document.createElement("div"),s.className="player-fps-overlay",s.style.cssText=p?` display: inline-flex; gap: 10px; align-items: center; font: 600 11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace; color: #c8d4e6; letter-spacing: 0.02em; white-space: nowrap; `:` - position: absolute; ${lN[e]} + position: absolute; ${vN[e]} z-index: 30; pointer-events: none; user-select: none; display: flex; gap: 10px; font: 600 11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace; @@ -3938,7 +3938,7 @@ void main() { border: 1px solid rgba(255, 255, 255, 0.12); border-radius: 6px; padding: 4px 8px; letter-spacing: 0.02em; white-space: nowrap; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6); - `;const g=document.createElement("span");g.append("Render "),a=document.createElement("span"),a.style.color="#7fd4ff",a.textContent="– fps",g.append(a);const _=document.createElement("span");_.append("Replay "),r=document.createElement("span"),r.style.color="#9affc0",r.textContent="– fps",_.append(r),s.append(g,_),f?f.appendChild(s):(getComputedStyle(h.container).position==="static"&&(h.container.style.position="relative"),h.container.appendChild(s))},beforeRender(h){o+=1,u=h.frameIndex;const f=performance.now(),p=f-l;if(puN(u,i,s,a,n.currentTime))}}function bu(n){return{...n,setup:n.setup?e=>{n.setup?.(Om(e,n.id))}:void 0,onStateChange:n.onStateChange?e=>{n.onStateChange?.(IT(e,n.id))}:void 0,beforeRender:n.beforeRender?e=>{n.beforeRender?.(dN(e,n.id))}:void 0,teardown:n.teardown?e=>{n.teardown?.(Om(e,n.id))}:void 0}}const hN=255;function Qh(n){return n==null?null:n*100/hN}const fN=1.35,pN="#57a8ff",mN="#ff9c40",_N=256,gN=160,yN=360,vN=225,bN=260,xN=430,LT=18,wv=120;function wN(n){return n?pN:mN}function SN(n){return n.events.filter(e=>!e.available&&e.playerId)}function DT(n,e){const t=document.createElement("canvas");t.width=_N,t.height=gN;const i=t.getContext("2d");if(!i)throw new Error("Unable to create boost pickup count canvas");i.clearRect(0,0,t.width,t.height),i.textAlign="center",i.textBaseline="middle",i.lineJoin="round",i.font="800 124px sans-serif",i.lineWidth=18,i.strokeStyle="rgba(4, 10, 18, 0.88)",i.strokeText(`${n}`,t.width/2,t.height/2),i.fillStyle=e,i.fillText(`${n}`,t.width/2,t.height/2);const s=new oc(t);return s.colorSpace=gt,s.needsUpdate=!0,s}function TN(n){n?.dispose()}function MN(n){const e=new Mt;e.visible=!1,e.renderOrder=60,e.frustumCulled=!1;const t=DT(1,n),i=new Ih({map:t,transparent:!0,depthTest:!1,depthWrite:!1}),s=new Lh(i);s.scale.set(yN,vN,1),s.renderOrder=62,s.frustumCulled=!1,e.add(s);const a=new Ye({color:n,transparent:!0,opacity:0,side:ct,depthTest:!1,depthWrite:!1,blending:Ht}),r=new we(new ni(wv*.72,wv,36),a);return r.position.z=LT,r.renderOrder=61,r.frustumCulled=!1,e.add(r),{group:e,textMaterial:i,ringMaterial:a}}function EN(n,e){n.currentCount!==e&&(TN(n.textMaterial.map),n.textMaterial.map=DT(e,n.color),n.textMaterial.needsUpdate=!0,n.currentCount=e)}function CN(n){const e=new Map;for(const s of n.replay.players)e.set(s.id,s);const t=[];for(const s of n.replay.boostPads)for(const a of SN(s))t.push({pad:s,event:a});t.sort((s,a)=>s.event.time!==a.event.time?s.event.time-a.event.time:s.event.frame!==a.event.frame?s.event.frame-a.event.frame:s.pad.index-a.pad.index);const i=[];for(const{pad:s,event:a}of t){if(!a.playerId)continue;const r=e.get(a.playerId);if(!r)continue;const o=wN(r.isTeamZero),{group:l,textMaterial:c,ringMaterial:u}=MN(o);l.position.copy(s.position),n.scene.replayRoot.add(l),i.push({time:a.time,pad:s,event:a,player:r,color:o,currentCount:1,position:new S(s.position.x,s.position.y,s.position.z),size:s.size,group:l,textMaterial:c,ringMaterial:u})}return i}function AN(n,e,t){const i=vt.clamp(e/t,0,1),s=1-Math.pow(1-i,3),a=i*i,r=n.size==="big"?xN:bN,o=n.size==="big"?360:280,l=1+Math.sin(i*Math.PI)*.22;n.group.visible=!0,n.group.position.set(n.position.x,n.position.y,n.position.z+r+s*o),n.group.scale.setScalar(l),n.textMaterial.opacity=Math.max(0,1-a),n.ringMaterial.opacity=Math.max(0,.48*(1-i));const c=n.group.children[1];if(c){const u=.75+s*(n.size==="big"?2.8:1.85);c.scale.setScalar(u),c.position.z=LT-r-s*o}}function RN(n={}){const e=Math.max(.1,n.durationSeconds??fN);let t=[];function i(a){return n.includePickup?.({pad:a.pad,event:a.event,player:a.player})??!0}function s(){for(const a of t)a.group.visible=!1}return{id:"boost-pickup-animation",setup(a){t=CN(a)},beforeRender(a){if(!a.state.boostPickupAnimationEnabled){s();return}const r=a.currentTime-e,o=new Map;for(const l of t){if(l.time>a.currentTime){l.group.visible=!1;continue}if(!i(l)){l.group.visible=!1;continue}const c=(o.get(l.player.id)??0)+1;if(o.set(l.player.id,c),l.time{(r instanceof we||r instanceof Lh)&&r.geometry?.dispose()}),a.textMaterial.map?.dispose(),a.textMaterial.dispose(),a.ringMaterial.dispose();t=[]}}}const PN=60,IN=["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"];function LN(n){if(n&&MediaRecorder.isTypeSupported(n))return n;for(const e of IN)if(MediaRecorder.isTypeSupported(e))return e;return""}function DN(n){return n instanceof Error?n.message:String(n)}function kN(n={}){let e=null,t=null,i=[],s=null,a=0,r=0,o="",l=0,c=null,u=null,d=null,h=null,f=!1,p=null;const g=new Set;function _(){return{state:t?t.state==="recording"?"recording":"stopping":c?"error":s?"ready":"idle",elapsedSeconds:r,mimeType:o,sizeBytes:l,error:c}}function m(){const x=_();n.onStatusChange?.(x);for(const M of g)M(x)}function v(){if(!e)throw new Error("Canvas recorder plugin is not installed");return e}function y(x){t=null,h=null,f=!1,s=x,l=x?.size??0,p&&e&&e.player.setState({currentTime:p.currentTime,speed:p.speed,playing:p.playing}),p=null,x&&n.onComplete?.(x),m(),d?.(x),d=null,u=null}function b(x){c=DN(x),t=null,h=null,f=!1,p=null,m(),d?.(null),d=null,u=null}const T={id:"canvas-recorder",setup(x){e=x},beforeRender(x){t?.state==="recording"&&(r=(performance.now()-a)/1e3,m()),t?.state==="recording"&&h!==null&&x.currentTime>=h&&T.stop()},onStateChange(x){f&&t?.state==="recording"&&!x.state.playing&&r>0&&T.stop()},teardown(){t?.state==="recording"&&t.stop(),e=null,t=null,h=null,f=!1,p=null,d?.(null),d=null,u=null,g.clear()},start(x={}){const M=v();if(t?.state==="recording")throw new Error("Canvas recording is already in progress");if(typeof MediaRecorder>"u")throw new Error("MediaRecorder is not available in this browser");const C=M.scene.renderer.domElement;if(!C.captureStream)throw new Error("Canvas captureStream is not available in this browser");c=null,s=null,i=[],l=0,r=0,a=performance.now(),o=LN(x.mimeType??n.mimeType);const w=Math.max(1,x.fps??n.fps??PN),E=C.captureStream(w);t=new MediaRecorder(E,{mimeType:o,videoBitsPerSecond:x.videoBitsPerSecond??n.videoBitsPerSecond}),u=new Promise(R=>{d=R}),t.addEventListener("dataavailable",R=>{R.data.size>0&&(i.push(R.data),l+=R.data.size,m())}),t.addEventListener("stop",()=>{E.getTracks().forEach(R=>R.stop()),y(new Blob(i,{type:o||"video/webm"}))},{once:!0}),t.addEventListener("error",R=>{E.getTracks().forEach(D=>D.stop()),b(R.error??R)},{once:!0}),t.start(1e3),m()},stop(){if(!t)return Promise.resolve(s);if(t.state==="inactive")return u??Promise.resolve(s);const x=u??new Promise(M=>{d=M});return t.stop(),m(),x},clear(){if(t?.state==="recording")throw new Error("Cannot clear a recording while recording is in progress");s=null,i=[],l=0,r=0,c=null,m()},getRecording(){return s},getStatus(){return _()},subscribe(x){return g.add(x),x(_()),()=>{g.delete(x)}},recordRange(x={}){const M=v(),C=M.player.getState();(x.restorePlaybackState??!0)&&(p=C);const w=x.playbackRate??C.speed,E=x.startTime??C.currentTime;h=x.endTime??C.duration,f=!0,M.player.setState({currentTime:E,speed:w,playing:!1}),T.start(x);const R=u;return M.player.play(),(R??Promise.resolve(null)).then(D=>{if(!D)throw new Error("Recording stopped without producing a video");return D})},recordFullReplay(x={}){return T.recordRange({...x,startTime:x.startTime??0,endTime:x.endTime??v().replay.duration})}};return T}const Sv="subtr-actor-timeline-overlay-styles";function ON(){if(document.getElementById(Sv))return;const n=document.createElement("style");n.id=Sv,n.textContent=` + `;const g=document.createElement("span");g.append("Render "),a=document.createElement("span"),a.style.color="#7fd4ff",a.textContent="– fps",g.append(a);const _=document.createElement("span");_.append("Replay "),r=document.createElement("span"),r.style.color="#9affc0",r.textContent="– fps",_.append(r),s.append(g,_),f?f.appendChild(s):(getComputedStyle(h.container).position==="static"&&(h.container.style.position="relative"),h.container.appendChild(s))},beforeRender(h){o+=1,u=h.frameIndex;const f=performance.now(),p=f-l;if(pxN(u,i,s,a,n.currentTime))}}function Tu(n){return{...n,setup:n.setup?e=>{n.setup?.(Vm(e,n.id))}:void 0,onStateChange:n.onStateChange?e=>{n.onStateChange?.(BT(e,n.id))}:void 0,beforeRender:n.beforeRender?e=>{n.beforeRender?.(wN(e,n.id))}:void 0,teardown:n.teardown?e=>{n.teardown?.(Vm(e,n.id))}:void 0}}const SN=255;function rf(n){return n==null?null:n*100/SN}const TN=1.35,MN="#57a8ff",EN="#ff9c40",CN=256,AN=160,RN=360,PN=225,IN=260,LN=430,zT=18,Rv=120;function kN(n){return n?MN:EN}function DN(n){return n.events.filter(e=>!e.available&&e.playerId)}function HT(n,e){const t=document.createElement("canvas");t.width=CN,t.height=AN;const i=t.getContext("2d");if(!i)throw new Error("Unable to create boost pickup count canvas");i.clearRect(0,0,t.width,t.height),i.textAlign="center",i.textBaseline="middle",i.lineJoin="round",i.font="800 124px sans-serif",i.lineWidth=18,i.strokeStyle="rgba(4, 10, 18, 0.88)",i.strokeText(`${n}`,t.width/2,t.height/2),i.fillStyle=e,i.fillText(`${n}`,t.width/2,t.height/2);const s=new dc(t);return s.colorSpace=gt,s.needsUpdate=!0,s}function ON(n){n?.dispose()}function FN(n){const e=new Mt;e.visible=!1,e.renderOrder=60,e.frustumCulled=!1;const t=HT(1,n),i=new Nh({map:t,transparent:!0,depthTest:!1,depthWrite:!1}),s=new Uh(i);s.scale.set(RN,PN,1),s.renderOrder=62,s.frustumCulled=!1,e.add(s);const a=new Ye({color:n,transparent:!0,opacity:0,side:ct,depthTest:!1,depthWrite:!1,blending:Ht}),r=new we(new ni(Rv*.72,Rv,36),a);return r.position.z=zT,r.renderOrder=61,r.frustumCulled=!1,e.add(r),{group:e,textMaterial:i,ringMaterial:a}}function NN(n,e){n.currentCount!==e&&(ON(n.textMaterial.map),n.textMaterial.map=HT(e,n.color),n.textMaterial.needsUpdate=!0,n.currentCount=e)}function UN(n){const e=new Map;for(const s of n.replay.players)e.set(s.id,s);const t=[];for(const s of n.replay.boostPads)for(const a of DN(s))t.push({pad:s,event:a});t.sort((s,a)=>s.event.time!==a.event.time?s.event.time-a.event.time:s.event.frame!==a.event.frame?s.event.frame-a.event.frame:s.pad.index-a.pad.index);const i=[];for(const{pad:s,event:a}of t){if(!a.playerId)continue;const r=e.get(a.playerId);if(!r)continue;const o=kN(r.isTeamZero),{group:l,textMaterial:c,ringMaterial:u}=FN(o);l.position.copy(s.position),n.scene.replayRoot.add(l),i.push({time:a.time,pad:s,event:a,player:r,color:o,currentCount:1,position:new S(s.position.x,s.position.y,s.position.z),size:s.size,group:l,textMaterial:c,ringMaterial:u})}return i}function BN(n,e,t){const i=vt.clamp(e/t,0,1),s=1-Math.pow(1-i,3),a=i*i,r=n.size==="big"?LN:IN,o=n.size==="big"?360:280,l=1+Math.sin(i*Math.PI)*.22;n.group.visible=!0,n.group.position.set(n.position.x,n.position.y,n.position.z+r+s*o),n.group.scale.setScalar(l),n.textMaterial.opacity=Math.max(0,1-a),n.ringMaterial.opacity=Math.max(0,.48*(1-i));const c=n.group.children[1];if(c){const u=.75+s*(n.size==="big"?2.8:1.85);c.scale.setScalar(u),c.position.z=zT-r-s*o}}function zN(n={}){const e=Math.max(.1,n.durationSeconds??TN);let t=[];function i(a){return n.includePickup?.({pad:a.pad,event:a.event,player:a.player})??!0}function s(){for(const a of t)a.group.visible=!1}return{id:"boost-pickup-animation",setup(a){t=UN(a)},beforeRender(a){if(!a.state.boostPickupAnimationEnabled){s();return}const r=a.currentTime-e,o=new Map;for(const l of t){if(l.time>a.currentTime){l.group.visible=!1;continue}if(!i(l)){l.group.visible=!1;continue}const c=(o.get(l.player.id)??0)+1;if(o.set(l.player.id,c),l.time{(r instanceof we||r instanceof Uh)&&r.geometry?.dispose()}),a.textMaterial.map?.dispose(),a.textMaterial.dispose(),a.ringMaterial.dispose();t=[]}}}const HN=60,VN=["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"];function GN(n){if(n&&MediaRecorder.isTypeSupported(n))return n;for(const e of VN)if(MediaRecorder.isTypeSupported(e))return e;return""}function $N(n){return n instanceof Error?n.message:String(n)}function WN(n={}){let e=null,t=null,i=[],s=null,a=0,r=0,o="",l=0,c=null,u=null,d=null,h=null,f=!1,p=null;const g=new Set;function _(){return{state:t?t.state==="recording"?"recording":"stopping":c?"error":s?"ready":"idle",elapsedSeconds:r,mimeType:o,sizeBytes:l,error:c}}function m(){const x=_();n.onStatusChange?.(x);for(const M of g)M(x)}function v(){if(!e)throw new Error("Canvas recorder plugin is not installed");return e}function y(x){t=null,h=null,f=!1,s=x,l=x?.size??0,p&&e&&e.player.setState({currentTime:p.currentTime,speed:p.speed,playing:p.playing}),p=null,x&&n.onComplete?.(x),m(),d?.(x),d=null,u=null}function b(x){c=$N(x),t=null,h=null,f=!1,p=null,m(),d?.(null),d=null,u=null}const T={id:"canvas-recorder",setup(x){e=x},beforeRender(x){t?.state==="recording"&&(r=(performance.now()-a)/1e3,m()),t?.state==="recording"&&h!==null&&x.currentTime>=h&&T.stop()},onStateChange(x){f&&t?.state==="recording"&&!x.state.playing&&r>0&&T.stop()},teardown(){t?.state==="recording"&&t.stop(),e=null,t=null,h=null,f=!1,p=null,d?.(null),d=null,u=null,g.clear()},start(x={}){const M=v();if(t?.state==="recording")throw new Error("Canvas recording is already in progress");if(typeof MediaRecorder>"u")throw new Error("MediaRecorder is not available in this browser");const C=M.scene.renderer.domElement;if(!C.captureStream)throw new Error("Canvas captureStream is not available in this browser");c=null,s=null,i=[],l=0,r=0,a=performance.now(),o=GN(x.mimeType??n.mimeType);const w=Math.max(1,x.fps??n.fps??HN),E=C.captureStream(w);t=new MediaRecorder(E,{mimeType:o,videoBitsPerSecond:x.videoBitsPerSecond??n.videoBitsPerSecond}),u=new Promise(R=>{d=R}),t.addEventListener("dataavailable",R=>{R.data.size>0&&(i.push(R.data),l+=R.data.size,m())}),t.addEventListener("stop",()=>{E.getTracks().forEach(R=>R.stop()),y(new Blob(i,{type:o||"video/webm"}))},{once:!0}),t.addEventListener("error",R=>{E.getTracks().forEach(k=>k.stop()),b(R.error??R)},{once:!0}),t.start(1e3),m()},stop(){if(!t)return Promise.resolve(s);if(t.state==="inactive")return u??Promise.resolve(s);const x=u??new Promise(M=>{d=M});return t.stop(),m(),x},clear(){if(t?.state==="recording")throw new Error("Cannot clear a recording while recording is in progress");s=null,i=[],l=0,r=0,c=null,m()},getRecording(){return s},getStatus(){return _()},subscribe(x){return g.add(x),x(_()),()=>{g.delete(x)}},recordRange(x={}){const M=v(),C=M.player.getState();(x.restorePlaybackState??!0)&&(p=C);const w=x.playbackRate??C.speed,E=x.startTime??C.currentTime;h=x.endTime??C.duration,f=!0,M.player.setState({currentTime:E,speed:w,playing:!1}),T.start(x);const R=u;return M.player.play(),(R??Promise.resolve(null)).then(k=>{if(!k)throw new Error("Recording stopped without producing a video");return k})},recordFullReplay(x={}){return T.recordRange({...x,startTime:x.startTime??0,endTime:x.endTime??v().replay.duration})}};return T}const Pv="subtr-actor-timeline-overlay-styles";function XN(){if(document.getElementById(Pv))return;const n=document.createElement("style");n.id=Pv,n.textContent=` .sap-tl-root { position: absolute; inset: 0; @@ -4411,8 +4411,8 @@ void main() { font-size: 0.72rem; } } - `,document.head.append(n)}const FN=new Set(["goal","save","bookmark"]),NN=.2,Mp=60,UN=2,BN=4,zN=.01,Tv=.01;function Fm(n){if(!Number.isFinite(n))return"--:--.--";const e=Math.max(0,n),t=Math.floor(e/60),i=Math.floor(e%60),s=Math.floor((e-Math.floor(e))*100);return`${t}:${String(i).padStart(2,"0")}.${String(s).padStart(2,"0")}`}function Mv(n){switch(n.kind){case"goal":return 5;case"demo":return 4;case"save":return 3;case"assist":return 2;case"shot":case"bookmark":return 1;default:return 0}}function HN(n){switch(n.kind){case"goal":case"goal-context":case"goal-tag":return BN;default:return UN}}function Pg(n){return n.seekTime!==void 0&&Number.isFinite(n.seekTime)?Math.max(0,n.seekTime):Number.isFinite(n.time)?Math.max(0,n.time-HN(n)):0}function VN(n){if(n.color)return n.color;if(n.isTeamZero===!0)return"#3b82f6";if(n.isTeamZero===!1)return"#f59e0b";switch(n.kind){case"goal":return"#f5f7fa";case"demo":return"#ef4444";case"save":return"#34d399";case"assist":return"#c084fc";case"shot":return"#60a5fa";case"bookmark":return"#facc15";default:return"#d1d9e0"}}function GN(n){if(n.events.length>1)return`${n.events.length}`;const e=n.events[0];return e?e.shortLabel&&e.shortLabel.trim()!==""?e.shortLabel.slice(0,3).toUpperCase():e.kind.slice(0,1).toUpperCase():""}function Nm(n){return[...n].sort((e,t)=>{const i=Mv(t)-Mv(e);return i!==0?i:e.time-t.time})}function $N(n){return n.events.map(e=>`${Fm(e.time)} ${e.label??e.kind}`).join(` -`)}function kT(n){const e=new Map;for(const t of n){const i=t.frame!==void 0?`frame:${t.frame}`:`time:${t.time.toFixed(2)}`,s=e.get(i);if(s){s.events.push(t);continue}e.set(i,{key:i,time:t.time,events:[t]})}return[...e.values()].map(t=>({...t,events:Nm(t.events)})).sort((t,i)=>t.time-i.time)}function Ev(n){if(n.length<=Mp)return n;const e=n[0]?.time??0,i=(n[n.length-1]?.time??e)-e;if(i<=0)return[{key:"compact:0",time:e,events:Nm(n.flatMap(r=>r.events))}];const s=i/Mp,a=new Map;for(const r of n){const o=Math.min(Mp-1,Math.max(0,Math.floor((r.time-e)/s))),l=a.get(o);if(l){l.events.push(...r.events);continue}a.set(o,{key:`compact:${o}`,time:r.time,events:[...r.events]})}return[...a.values()].map(r=>({...r,events:Nm(r.events)})).sort((r,o)=>r.time-o.time)}function OT(n,e){return n?typeof n=="function"?n(e):n:[]}function WN(n,e){const t=[];for(const i of n){const s=OT(i.source,e);s.length!==0&&t.push({key:i.key,label:i.label,buckets:kT(s)})}return t}function XN(n,e){return n?typeof n=="function"?n(e):n:[]}function KN(n,e){const t=new Set,i=[];for(const s of n)for(const a of XN(s,e)){const r=a.id;if(r!==void 0){if(t.has(r))continue;t.add(r)}i.push(a)}return i}function qN(n){const e=new Map;for(const t of n){const i=t.lane??"default",s=t.laneLabel??t.lane??"",a=e.get(i);if(a){a.ranges.push(t);continue}e.set(i,{key:i,label:s,ranges:[t]})}return[...e.values()].map(t=>({...t,ranges:[...t.ranges].sort((i,s)=>i.startTime-s.startTime)}))}function YN(n){return n.color?n.color:n.isTeamZero===!0?"#3b82f6":n.isTeamZero===!1?"#f59e0b":"#d1d9e0"}function jN(n,e){if(n.replayEvents)return OT(n.replayEvents,e);if(n.includeReplayEvents===!1)return[];const t=new Set(n.replayEventKinds??FN);return e.replay.timelineEvents.filter(i=>t.has(i.kind))}function ZN(n,e){const t=e.player.projectReplayTimeToTimeline(Pg(n));if(!t.hiddenBySkip)return t.seekTime;const i=Math.min(e.player.getTimelineDuration(),t.timelineTime+zN);return e.player.projectTimelineTimeToReplay(i)}function xu(n,e){return`${n/Math.max(e,1e-4)*100}%`}function JN(n,e,t){let i=n.timelineTime,s=e.timelineTime;return s<=i&&(n.hiddenBySkip||e.hiddenBySkip)&&(i>=t?(i=Math.max(0,t-Tv),s=t):s=Math.min(t,i+Tv)),{startTimelineTime:i,endTimelineTime:s}}function QN(n={}){const e=n.pauseWhileScrubbing??!0;let t=0;const i=n.events?[{key:"events:initial",label:n.eventsLabel??"Events",source:n.events}]:[],s=n.ranges?[n.ranges]:[];let a=null,r=null,o=null,l=null,c=null,u=null,d=null,h=null,f=null,p=null,g=null,_=null,m=!1,v="",y=!1,b=!1,T=null,x=[],M=[],C=null;const w=new Map,E=[],R=[],D=[],O=[];let k=0,U=new Set;function F(){T&&(ke(T),H({...T,state:T.player.getState()}))}function W(){T&&(Z(T),H({...T,state:T.player.getState()}))}function H(X){if(!l||!c||!u||!d||!h||!f||!r)return;const ie=X.player.getTimelineCurrentTime(),xe=X.player.getTimelineDuration(),Ae=[xe.toFixed(4),X.state.skipKickoffsEnabled?"1":"0",X.state.skipPostGoalTransitionsEnabled?"1":"0"].join(":");C!==Ae&&(ke(X),Z(X),C=Ae),l.min="0",l.max=`${xe}`,l.step="0.01",l.value=`${Math.min(ie,xe)}`,c.dataset.playing=X.state.playing?"true":"false",c.setAttribute("aria-label",X.state.playing?"Pause replay":"Play replay"),c.title=X.state.playing?"Pause replay":"Play replay",u.textContent=X.state.playing?"||":">",d.textContent=X.state.playing?"Pause":"Play",h.textContent=Fm(ie),f.textContent=`-${Fm(xe-ie)}`,r.dataset.scrubbing=y?"true":"false",De(ie);for(const G of R){const j=Math.max(0,G.startTimelineTime),Y=Math.min(xe,G.endTimelineTime);if(Math.max(0,Y-j)<=1e-4){G.element.hidden=!0;continue}G.element.hidden=!1,G.element.dataset.active=ie>=j&&ie<=Y?"true":"false"}const L=xu(Math.min(ie,xe),xe);for(const G of O)G.element.style.left=L;for(const G of D)G.element.style.left=L}function ne(X){let ie=0,xe=E.length;for(;iek)for(let G=k;G{ie.player.seek(ZN(Ae,ie))}),G.dataset.active="false",G.dataset.passed="false";const j={element:G,timelineTime:L.timelineTime,active:!1,passed:!1};return w.set(X.key,j),E.push(j),G}function ke(X){if(!g||!p)return;g.replaceChildren(),p.replaceChildren(),w.clear(),E.splice(0,E.length),k=0,U=new Set,O.splice(0,O.length);const ie=jN(n,X);x=[],ie.length>0&&x.push({key:"replay",label:n.replayEventsLabel??"Replay",buckets:kT(ie)}),x.push(...WN(i,X));const xe=Math.max(X.player.getTimelineDuration(),1e-4),Ae=x[0];if(Ae?.key==="replay")for(const G of Ev(Ae.buckets)){const j=Xe({...G,key:`${Ae.key}:${G.key}`},X,xe);j&&g.append(j)}const L=x.filter(G=>G.key!=="replay");p.hidden=L.length===0;for(const G of L){const j=document.createElement("div");j.className="sap-tl-event-lane",j.dataset.label=G.label;const Y=document.createElement("span");Y.className="sap-tl-event-lane-label",Y.textContent=G.label,Y.setAttribute("aria-label",G.label),j.append(Y);const Q=document.createElement("div");Q.className="sap-tl-event-lane-track";const _e=document.createElement("div");_e.className="sap-tl-markers";for(const ge of Ev(G.buckets)){const $e=Xe({...ge,key:`${G.key}:${ge.key}`},X,xe);$e&&_e.append($e)}const ce=document.createElement("div");ce.className="sap-tl-event-playhead",Q.append(_e,ce),O.push({element:ce}),j.append(Q),p.append(j)}E.sort((G,j)=>G.timelineTime-j.timelineTime)}function Z(X){if(!o)return;o.replaceChildren(),R.splice(0,R.length),D.splice(0,D.length);const ie=KN(s,X).filter(Ae=>Number.isFinite(Ae.startTime)&&Number.isFinite(Ae.endTime)&&Ae.endTime>Ae.startTime);M=qN(ie);const xe=Math.max(X.player.getTimelineDuration(),1e-4);if(M.length===0){o.hidden=!0;return}o.hidden=!1;for(const Ae of M){const L=document.createElement("div");L.className="sap-tl-range-lane";const G=document.createElement("div");if(G.className="sap-tl-range-lane-track",Ae.label){L.dataset.label=Ae.label;const Y=document.createElement("span");Y.className="sap-tl-range-lane-label",Y.textContent=Ae.label,Y.setAttribute("aria-label",Ae.label),L.append(Y)}for(const Y of Ae.ranges){const Q=X.player.projectReplayTimeToTimeline(Y.startTime),_e=X.player.projectReplayTimeToTimeline(Y.endTime),{startTimelineTime:ce,endTimelineTime:ge}=JN(Q,_e,xe),$e=document.createElement("div");$e.className="sap-tl-range-segment",Y.className&&$e.classList.add(Y.className),$e.style.background=YN(Y),$e.title=Y.label??Ae.label,$e.dataset.active="false",$e.style.left=xu(ce,xe),$e.style.width=xu(Math.max(0,ge-ce),xe),G.append($e),R.push({range:Y,element:$e,startTimelineTime:ce,endTimelineTime:ge})}const j=document.createElement("div");j.className="sap-tl-range-playhead",G.append(j),D.push({element:j}),L.append(G),o.append(L)}}function se(){y&&(y=!1,r?.setAttribute("data-scrubbing","false"),b&&T?.player.play(),b=!1)}function Se(){if(y||(y=!0,r?.setAttribute("data-scrubbing","true"),!e))return;const X=T?.player;X&&(b=X.getState().playing,b&&X.pause())}return{id:"timeline-overlay",addEventSource(X,ie={}){return i.push({key:ie.id??`events:${t++}`,label:ie.label??"Events",source:X}),F(),()=>{this.removeEventSource(X)}},removeEventSource(X){const ie=i.findIndex(xe=>xe.source===X);return ie<0?!1:(i.splice(ie,1),F(),!0)},refreshEvents(){F()},addRangeSource(X){return s.push(X),W(),()=>{this.removeRangeSource(X)}},removeRangeSource(X){const ie=s.indexOf(X);return ie<0?!1:(s.splice(ie,1),W(),!0)},refreshRanges(){W()},setup(X){T=X,ON(),getComputedStyle(X.container).position==="static"&&(m=!0,v=X.container.style.position,X.container.style.position="relative"),a=document.createElement("div"),a.className="sap-tl-root",r=document.createElement("div"),r.className="sap-tl-shell",r.dataset.scrubbing="false";const ie=document.createElement("div");ie.className="sap-tl-topline";const xe=document.createElement("div");xe.className="sap-tl-primary",c=document.createElement("button"),c.type="button",c.className="sap-tl-toggle sap-tl-track-toggle",u=document.createElement("span"),u.className="sap-tl-toggle-icon",u.setAttribute("aria-hidden","true"),u.textContent=">",d=document.createElement("span"),d.className="sap-tl-toggle-label",d.textContent="Play",c.append(u,d),c.addEventListener("click",()=>{X.player.togglePlayback()}),h=document.createElement("span"),h.className="sap-tl-current",h.textContent="0:00.00",f=document.createElement("span"),f.className="sap-tl-remaining",f.textContent="-0:00.00",xe.append(h),ie.append(xe,f);const Ae=document.createElement("div");Ae.className="sap-tl-track-wrap",o=document.createElement("div"),o.className="sap-tl-ranges",o.hidden=!0,p=document.createElement("div"),p.className="sap-tl-event-lanes",p.hidden=!0;const L=document.createElement("div");L.className="sap-tl-track-rail";const G=document.createElement("div");G.className="sap-tl-main-rail",g=document.createElement("div"),g.className="sap-tl-markers",l=document.createElement("input"),l.className="sap-tl-range",l.type="range",l.min="0",l.max=`${X.replay.duration}`,l.step="0.01",l.value="0";const j=()=>{Se()},Y=()=>{l&&X.player.seek(X.player.projectTimelineTimeToReplay(Number(l.value)))},Q=()=>{se()};l.addEventListener("pointerdown",j),l.addEventListener("input",Y),l.addEventListener("change",Q),window.addEventListener("pointerup",Q),window.addEventListener("pointercancel",Q),_=()=>{l?.removeEventListener("pointerdown",j),l?.removeEventListener("input",Y),l?.removeEventListener("change",Q),window.removeEventListener("pointerup",Q),window.removeEventListener("pointercancel",Q)},L.append(G,g,l),Ae.append(o,p,c,L),r.append(ie,Ae),a.append(r),X.container.append(a),ke(X),Z(X),H({...X,state:X.player.getState()})},onStateChange(X){T=X,H(X)},teardown(X){_?.(),_=null,se(),a?.remove(),a=null,r=null,o=null,p=null,l=null,c=null,u=null,d=null,h=null,f=null,g=null,T=null,x=[],M=[],C=null,w.clear(),E.splice(0,E.length),R.splice(0,R.length),D.splice(0,D.length),O.splice(0,O.length),k=0,U=new Set,m&&(X.container.style.position=v,m=!1)}}}function e3(n,e,t={}){const i=new xw(e.raw,{motionSmoothing:t.motionSmoothing,smoothingBlendFactor:t.smoothingBlendFactor,smoothingAnchorInterval:t.smoothingAnchorInterval,timelineCompaction:t.timelineCompaction,disableFrameFiltering:t.disableFrameFiltering}),s=new eN(n,i,t,e.replay);return s.getPlugins().some(a=>a.id==="camera")||s.addPlugin(oN()),s}const t3="https://ballchasing.com",n3=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function i3(n,e){const i=(e instanceof URL?e.href:e).replace(/\/+$/,"");return new URL(`${i}/${n.replace(/^\/+/,"")}`)}function Cv(n){return n3.test(n.trim())}function Ig(n){const e=n.trim();if(Cv(e))return e.toLowerCase();let t;try{t=new URL(e)}catch{throw new Error(`Invalid Ballchasing replay id: ${n}`)}if(!/(^|\.)ballchasing\.com$/i.test(t.hostname))throw new Error(`Invalid Ballchasing replay URL: ${n}`);const i=t.pathname.split("/").filter(Boolean),s=i.findIndex(o=>o==="replay"),a=i.findIndex(o=>o==="replays"),r=s>=0?i[s+1]:a>=0?i[a+1]:void 0;if(!r||!Cv(r))throw new Error(`Invalid Ballchasing replay URL: ${n}`);return r.toLowerCase()}function s3(n){return`ballchasing-${Ig(n)}.replay`}function a3(n,e=t3){const t=Ig(n);return i3(`dl/replay/${encodeURIComponent(t)}`,e)}const Um=250,Av="subtr-actor-ballchasing-overlay-styles",Ep="#3b82f6",Rv="#f59e0b";function r3(){if(document.getElementById(Av))return;const n=document.createElement("style");n.id=Av,n.textContent=` + `,document.head.append(n)}const KN=new Set(["goal","save","bookmark"]),qN=.2,Ip=60,YN=2,jN=4,ZN=.01,Iv=.01;function Gm(n){if(!Number.isFinite(n))return"--:--.--";const e=Math.max(0,n),t=Math.floor(e/60),i=Math.floor(e%60),s=Math.floor((e-Math.floor(e))*100);return`${t}:${String(i).padStart(2,"0")}.${String(s).padStart(2,"0")}`}function Lv(n){switch(n.kind){case"goal":return 5;case"demo":return 4;case"save":return 3;case"assist":return 2;case"shot":case"bookmark":return 1;default:return 0}}function JN(n){switch(n.kind){case"goal":case"goal-context":case"goal-tag":return jN;default:return YN}}function Ng(n){return n.seekTime!==void 0&&Number.isFinite(n.seekTime)?Math.max(0,n.seekTime):Number.isFinite(n.time)?Math.max(0,n.time-JN(n)):0}function QN(n){if(n.color)return n.color;if(n.isTeamZero===!0)return"#3b82f6";if(n.isTeamZero===!1)return"#f59e0b";switch(n.kind){case"goal":return"#f5f7fa";case"demo":return"#ef4444";case"save":return"#34d399";case"assist":return"#c084fc";case"shot":return"#60a5fa";case"bookmark":return"#facc15";default:return"#d1d9e0"}}function e3(n){if(n.events.length>1)return`${n.events.length}`;const e=n.events[0];return e?e.shortLabel&&e.shortLabel.trim()!==""?e.shortLabel.slice(0,3).toUpperCase():e.kind.slice(0,1).toUpperCase():""}function $m(n){return[...n].sort((e,t)=>{const i=Lv(t)-Lv(e);return i!==0?i:e.time-t.time})}function t3(n){return n.events.map(e=>`${Gm(e.time)} ${e.label??e.kind}`).join(` +`)}function VT(n){const e=new Map;for(const t of n){const i=t.frame!==void 0?`frame:${t.frame}`:`time:${t.time.toFixed(2)}`,s=e.get(i);if(s){s.events.push(t);continue}e.set(i,{key:i,time:t.time,events:[t]})}return[...e.values()].map(t=>({...t,events:$m(t.events)})).sort((t,i)=>t.time-i.time)}function kv(n){if(n.length<=Ip)return n;const e=n[0]?.time??0,i=(n[n.length-1]?.time??e)-e;if(i<=0)return[{key:"compact:0",time:e,events:$m(n.flatMap(r=>r.events))}];const s=i/Ip,a=new Map;for(const r of n){const o=Math.min(Ip-1,Math.max(0,Math.floor((r.time-e)/s))),l=a.get(o);if(l){l.events.push(...r.events);continue}a.set(o,{key:`compact:${o}`,time:r.time,events:[...r.events]})}return[...a.values()].map(r=>({...r,events:$m(r.events)})).sort((r,o)=>r.time-o.time)}function GT(n,e){return n?typeof n=="function"?n(e):n:[]}function n3(n,e){const t=[];for(const i of n){const s=GT(i.source,e);s.length!==0&&t.push({key:i.key,label:i.label,buckets:VT(s)})}return t}function i3(n,e){return n?typeof n=="function"?n(e):n:[]}function s3(n,e){const t=new Set,i=[];for(const s of n)for(const a of i3(s,e)){const r=a.id;if(r!==void 0){if(t.has(r))continue;t.add(r)}i.push(a)}return i}function a3(n){const e=new Map;for(const t of n){const i=t.lane??"default",s=t.laneLabel??t.lane??"",a=e.get(i);if(a){a.ranges.push(t);continue}e.set(i,{key:i,label:s,ranges:[t]})}return[...e.values()].map(t=>({...t,ranges:[...t.ranges].sort((i,s)=>i.startTime-s.startTime)}))}function r3(n){return n.color?n.color:n.isTeamZero===!0?"#3b82f6":n.isTeamZero===!1?"#f59e0b":"#d1d9e0"}function o3(n,e){if(n.replayEvents)return GT(n.replayEvents,e);if(n.includeReplayEvents===!1)return[];const t=new Set(n.replayEventKinds??KN);return e.replay.timelineEvents.filter(i=>t.has(i.kind))}function l3(n,e){const t=e.player.projectReplayTimeToTimeline(Ng(n));if(!t.hiddenBySkip)return t.seekTime;const i=Math.min(e.player.getTimelineDuration(),t.timelineTime+ZN);return e.player.projectTimelineTimeToReplay(i)}function Mu(n,e){return`${n/Math.max(e,1e-4)*100}%`}function c3(n,e,t){let i=n.timelineTime,s=e.timelineTime;return s<=i&&(n.hiddenBySkip||e.hiddenBySkip)&&(i>=t?(i=Math.max(0,t-Iv),s=t):s=Math.min(t,i+Iv)),{startTimelineTime:i,endTimelineTime:s}}function u3(n={}){const e=n.pauseWhileScrubbing??!0;let t=0;const i=n.events?[{key:"events:initial",label:n.eventsLabel??"Events",source:n.events}]:[],s=n.ranges?[n.ranges]:[];let a=null,r=null,o=null,l=null,c=null,u=null,d=null,h=null,f=null,p=null,g=null,_=null,m=!1,v="",y=!1,b=!1,T=null,x=[],M=[],C=null;const w=new Map,E=[],R=[],k=[],O=[];let D=0,U=new Set;function F(){T&&(De(T),H({...T,state:T.player.getState()}))}function W(){T&&(Z(T),H({...T,state:T.player.getState()}))}function H(X){if(!l||!c||!u||!d||!h||!f||!r)return;const ie=X.player.getTimelineCurrentTime(),xe=X.player.getTimelineDuration(),Ae=[xe.toFixed(4),X.state.skipKickoffsEnabled?"1":"0",X.state.skipPostGoalTransitionsEnabled?"1":"0"].join(":");C!==Ae&&(De(X),Z(X),C=Ae),l.min="0",l.max=`${xe}`,l.step="0.01",l.value=`${Math.min(ie,xe)}`,c.dataset.playing=X.state.playing?"true":"false",c.setAttribute("aria-label",X.state.playing?"Pause replay":"Play replay"),c.title=X.state.playing?"Pause replay":"Play replay",u.textContent=X.state.playing?"||":">",d.textContent=X.state.playing?"Pause":"Play",h.textContent=Gm(ie),f.textContent=`-${Gm(xe-ie)}`,r.dataset.scrubbing=y?"true":"false",ke(ie);for(const G of R){const j=Math.max(0,G.startTimelineTime),Y=Math.min(xe,G.endTimelineTime);if(Math.max(0,Y-j)<=1e-4){G.element.hidden=!0;continue}G.element.hidden=!1,G.element.dataset.active=ie>=j&&ie<=Y?"true":"false"}const L=Mu(Math.min(ie,xe),xe);for(const G of O)G.element.style.left=L;for(const G of k)G.element.style.left=L}function ne(X){let ie=0,xe=E.length;for(;ieD)for(let G=D;G{ie.player.seek(l3(Ae,ie))}),G.dataset.active="false",G.dataset.passed="false";const j={element:G,timelineTime:L.timelineTime,active:!1,passed:!1};return w.set(X.key,j),E.push(j),G}function De(X){if(!g||!p)return;g.replaceChildren(),p.replaceChildren(),w.clear(),E.splice(0,E.length),D=0,U=new Set,O.splice(0,O.length);const ie=o3(n,X);x=[],ie.length>0&&x.push({key:"replay",label:n.replayEventsLabel??"Replay",buckets:VT(ie)}),x.push(...n3(i,X));const xe=Math.max(X.player.getTimelineDuration(),1e-4),Ae=x[0];if(Ae?.key==="replay")for(const G of kv(Ae.buckets)){const j=Xe({...G,key:`${Ae.key}:${G.key}`},X,xe);j&&g.append(j)}const L=x.filter(G=>G.key!=="replay");p.hidden=L.length===0;for(const G of L){const j=document.createElement("div");j.className="sap-tl-event-lane",j.dataset.label=G.label;const Y=document.createElement("span");Y.className="sap-tl-event-lane-label",Y.textContent=G.label,Y.setAttribute("aria-label",G.label),j.append(Y);const Q=document.createElement("div");Q.className="sap-tl-event-lane-track";const _e=document.createElement("div");_e.className="sap-tl-markers";for(const ge of kv(G.buckets)){const $e=Xe({...ge,key:`${G.key}:${ge.key}`},X,xe);$e&&_e.append($e)}const ce=document.createElement("div");ce.className="sap-tl-event-playhead",Q.append(_e,ce),O.push({element:ce}),j.append(Q),p.append(j)}E.sort((G,j)=>G.timelineTime-j.timelineTime)}function Z(X){if(!o)return;o.replaceChildren(),R.splice(0,R.length),k.splice(0,k.length);const ie=s3(s,X).filter(Ae=>Number.isFinite(Ae.startTime)&&Number.isFinite(Ae.endTime)&&Ae.endTime>Ae.startTime);M=a3(ie);const xe=Math.max(X.player.getTimelineDuration(),1e-4);if(M.length===0){o.hidden=!0;return}o.hidden=!1;for(const Ae of M){const L=document.createElement("div");L.className="sap-tl-range-lane";const G=document.createElement("div");if(G.className="sap-tl-range-lane-track",Ae.label){L.dataset.label=Ae.label;const Y=document.createElement("span");Y.className="sap-tl-range-lane-label",Y.textContent=Ae.label,Y.setAttribute("aria-label",Ae.label),L.append(Y)}for(const Y of Ae.ranges){const Q=X.player.projectReplayTimeToTimeline(Y.startTime),_e=X.player.projectReplayTimeToTimeline(Y.endTime),{startTimelineTime:ce,endTimelineTime:ge}=c3(Q,_e,xe),$e=document.createElement("div");$e.className="sap-tl-range-segment",Y.className&&$e.classList.add(Y.className),$e.style.background=r3(Y),$e.title=Y.label??Ae.label,$e.dataset.active="false",$e.style.left=Mu(ce,xe),$e.style.width=Mu(Math.max(0,ge-ce),xe),G.append($e),R.push({range:Y,element:$e,startTimelineTime:ce,endTimelineTime:ge})}const j=document.createElement("div");j.className="sap-tl-range-playhead",G.append(j),k.push({element:j}),L.append(G),o.append(L)}}function ae(){y&&(y=!1,r?.setAttribute("data-scrubbing","false"),b&&T?.player.play(),b=!1)}function Se(){if(y||(y=!0,r?.setAttribute("data-scrubbing","true"),!e))return;const X=T?.player;X&&(b=X.getState().playing,b&&X.pause())}return{id:"timeline-overlay",addEventSource(X,ie={}){return i.push({key:ie.id??`events:${t++}`,label:ie.label??"Events",source:X}),F(),()=>{this.removeEventSource(X)}},removeEventSource(X){const ie=i.findIndex(xe=>xe.source===X);return ie<0?!1:(i.splice(ie,1),F(),!0)},refreshEvents(){F()},addRangeSource(X){return s.push(X),W(),()=>{this.removeRangeSource(X)}},removeRangeSource(X){const ie=s.indexOf(X);return ie<0?!1:(s.splice(ie,1),W(),!0)},refreshRanges(){W()},setup(X){T=X,XN(),getComputedStyle(X.container).position==="static"&&(m=!0,v=X.container.style.position,X.container.style.position="relative"),a=document.createElement("div"),a.className="sap-tl-root",r=document.createElement("div"),r.className="sap-tl-shell",r.dataset.scrubbing="false";const ie=document.createElement("div");ie.className="sap-tl-topline";const xe=document.createElement("div");xe.className="sap-tl-primary",c=document.createElement("button"),c.type="button",c.className="sap-tl-toggle sap-tl-track-toggle",u=document.createElement("span"),u.className="sap-tl-toggle-icon",u.setAttribute("aria-hidden","true"),u.textContent=">",d=document.createElement("span"),d.className="sap-tl-toggle-label",d.textContent="Play",c.append(u,d),c.addEventListener("click",()=>{X.player.togglePlayback()}),h=document.createElement("span"),h.className="sap-tl-current",h.textContent="0:00.00",f=document.createElement("span"),f.className="sap-tl-remaining",f.textContent="-0:00.00",xe.append(h),ie.append(xe,f);const Ae=document.createElement("div");Ae.className="sap-tl-track-wrap",o=document.createElement("div"),o.className="sap-tl-ranges",o.hidden=!0,p=document.createElement("div"),p.className="sap-tl-event-lanes",p.hidden=!0;const L=document.createElement("div");L.className="sap-tl-track-rail";const G=document.createElement("div");G.className="sap-tl-main-rail",g=document.createElement("div"),g.className="sap-tl-markers",l=document.createElement("input"),l.className="sap-tl-range",l.type="range",l.min="0",l.max=`${X.replay.duration}`,l.step="0.01",l.value="0";const j=()=>{Se()},Y=()=>{l&&X.player.seek(X.player.projectTimelineTimeToReplay(Number(l.value)))},Q=()=>{ae()};l.addEventListener("pointerdown",j),l.addEventListener("input",Y),l.addEventListener("change",Q),window.addEventListener("pointerup",Q),window.addEventListener("pointercancel",Q),_=()=>{l?.removeEventListener("pointerdown",j),l?.removeEventListener("input",Y),l?.removeEventListener("change",Q),window.removeEventListener("pointerup",Q),window.removeEventListener("pointercancel",Q)},L.append(G,g,l),Ae.append(o,p,c,L),r.append(ie,Ae),a.append(r),X.container.append(a),De(X),Z(X),H({...X,state:X.player.getState()})},onStateChange(X){T=X,H(X)},teardown(X){_?.(),_=null,ae(),a?.remove(),a=null,r=null,o=null,p=null,l=null,c=null,u=null,d=null,h=null,f=null,g=null,T=null,x=[],M=[],C=null,w.clear(),E.splice(0,E.length),R.splice(0,R.length),k.splice(0,k.length),O.splice(0,O.length),D=0,U=new Set,m&&(X.container.style.position=v,m=!1)}}}function d3(n,e,t={}){const i=new Rw(e.raw,{motionSmoothing:t.motionSmoothing,smoothingBlendFactor:t.smoothingBlendFactor,smoothingAnchorInterval:t.smoothingAnchorInterval,timelineCompaction:t.timelineCompaction,disableFrameFiltering:t.disableFrameFiltering}),s=new dN(n,i,t,e.replay);return s.getPlugins().some(a=>a.id==="camera")||s.addPlugin(yN()),s}const h3="https://ballchasing.com",f3=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function p3(n,e){const i=(e instanceof URL?e.href:e).replace(/\/+$/,"");return new URL(`${i}/${n.replace(/^\/+/,"")}`)}function Dv(n){return f3.test(n.trim())}function Ug(n){const e=n.trim();if(Dv(e))return e.toLowerCase();let t;try{t=new URL(e)}catch{throw new Error(`Invalid Ballchasing replay id: ${n}`)}if(!/(^|\.)ballchasing\.com$/i.test(t.hostname))throw new Error(`Invalid Ballchasing replay URL: ${n}`);const i=t.pathname.split("/").filter(Boolean),s=i.findIndex(o=>o==="replay"),a=i.findIndex(o=>o==="replays"),r=s>=0?i[s+1]:a>=0?i[a+1]:void 0;if(!r||!Dv(r))throw new Error(`Invalid Ballchasing replay URL: ${n}`);return r.toLowerCase()}function m3(n){return`ballchasing-${Ug(n)}.replay`}function _3(n,e=h3){const t=Ug(n);return p3(`dl/replay/${encodeURIComponent(t)}`,e)}const Wm=250,Ov="subtr-actor-ballchasing-overlay-styles",Lp="#3b82f6",Fv="#f59e0b";function g3(){if(document.getElementById(Ov))return;const n=document.createElement("style");n.id=Ov,n.textContent=` .sap-bc-overlay-root { position: absolute; inset: 0; @@ -4541,14 +4541,14 @@ void main() { right: calc(50% + 2.7rem); flex-direction: row; justify-content: flex-end; - border-bottom: 2px solid ${Ep}; + border-bottom: 2px solid ${Lp}; } .sap-bc-team-hud-orange { left: calc(50% + 2.7rem); flex-direction: row; justify-content: flex-start; - border-bottom: 2px solid ${Rv}; + border-bottom: 2px solid ${Fv}; } .sap-bc-hud-player { @@ -4656,7 +4656,7 @@ void main() { .sap-bc-followed-boost-ring { --sap-bc-followed-boost: 0%; - --sap-bc-followed-color: ${Ep}; + --sap-bc-followed-color: ${Lp}; position: relative; display: grid; place-items: center; @@ -4676,11 +4676,11 @@ void main() { } .sap-bc-followed-hud-blue .sap-bc-followed-boost-ring { - --sap-bc-followed-color: ${Ep}; + --sap-bc-followed-color: ${Lp}; } .sap-bc-followed-hud-orange .sap-bc-followed-boost-ring { - --sap-bc-followed-color: ${Rv}; + --sap-bc-followed-color: ${Fv}; } .sap-bc-followed-boost-value { @@ -4795,7 +4795,7 @@ void main() { font-size: 0.68rem; } } - `,document.head.append(n)}function o3(n,e){const t=n.players[e],i=t.frame?.boostAmount??0,s=t.nextFrame?.boostAmount??i;return vt.lerp(i,s,n.alpha)}function l3(n,e){const t=n.replay.players.find(h=>h.id===e);if(!t)return null;const i=fh(n.replay,n.state.currentTime),s=Math.min(i+1,n.replay.frames.length-1),a=n.replay.frames[i],r=n.replay.frames[s]??a,o=a?.time??n.state.currentTime,l=r?.time??o,c=l>o?vt.clamp((n.state.currentTime-o)/(l-o),0,1):0,u=t.frames[i]?.boostAmount??0,d=t.frames[s]?.boostAmount??u;return vt.lerp(u,d,c)}function Pv(n,e,t,i){if(!n||!e)return;const s=Math.max(0,Math.min(100,Math.round(Qh(t))));n.style.width=`${s}%`,e.textContent=`${s} ${i}`}function Iv(n,e,t,i){if(!n)return;const s=Math.max(0,Math.min(100,Math.round(Qh(e))));n.root.hidden=!1,n.root.classList.toggle("sap-bc-followed-hud-blue",i),n.root.classList.toggle("sap-bc-followed-hud-orange",!i),n.root.setAttribute("aria-label",`${t} boost ${s}`),n.ring.style.setProperty("--sap-bc-followed-boost",`${s}%`),n.value.textContent=`${s}`,n.name.textContent=t}function Lv(n,e,t,i){if(!n)return;const s=()=>{e.player.setAttachedPlayer(t)};n.classList.add("sap-bc-player-selectable"),n.tabIndex=0,n.setAttribute("role","button"),n.setAttribute("aria-label",`Follow ${i}`),n.title=`Follow ${i}`,n.addEventListener("click",s),n.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),s())})}function c3(n,e,t,i,s){if(n.getWorldPosition(s),s.add(e),s.project(t),s.z<-1||s.z>1)return!1;const a=i.clientWidth||1,r=i.clientHeight||1;return s.x=(s.x+1)*a/2,s.y=(1-s.y)*r/2,!(s.x<-80||s.x>a+80||s.y<-80||s.y>r+80)}function u3(n={}){const e=n.showFloatingNames??!0,t=n.showFloatingBoostBars??!0,i=n.showTeamBoostHud??!0,s=n.showFollowedPlayerHud??!0;let a=null,r=null,o=null,l=null,c=null,u=!1,d="";const h=new Map,f=n.floatingLiftUu,p=new S,g=new S;function _(){const b=typeof f=="function"?f():f;return typeof b=="number"&&Number.isFinite(b)?b:Um}function m(b){for(const[T,x]of h.entries()){const M=T===b;x.floatingRoot?.classList.toggle("sap-bc-player-following",M),x.teamHudEntry?.classList.toggle("sap-bc-player-following",M),x.floatingRoot?.setAttribute("aria-pressed",M?"true":"false"),x.teamHudEntry?.setAttribute("aria-pressed",M?"true":"false")}}function v(b){if(!c||!b.state.attachedPlayerId){c&&(c.root.hidden=!0);return}const T=b.replay.players.find(M=>M.id===b.state.attachedPlayerId);if(!T){c.root.hidden=!0;return}const x=l3(b,T.id);if(x===null){c.root.hidden=!0;return}Iv(c,x,T.name,T.isTeamZero)}function y(b,T){if(r3(),getComputedStyle(T).position==="static"&&(u=!0,d=T.style.position,T.style.position="relative"),a=document.createElement("div"),a.className="sap-bc-overlay-root",e||t?(r=document.createElement("div"),r.className="sap-bc-floating-layer",a.append(r)):r=null,i?(o=document.createElement("div"),o.className="sap-bc-team-hud sap-bc-team-hud-blue",l=document.createElement("div"),l.className="sap-bc-team-hud sap-bc-team-hud-orange",a.append(o,l)):(o=null,l=null),s){const x=document.createElement("div");x.className="sap-bc-followed-hud",x.hidden=!0;const M=document.createElement("div");M.className="sap-bc-followed-boost-ring";const C=document.createElement("span");C.className="sap-bc-followed-boost-value",M.append(C);const w=document.createElement("div");w.className="sap-bc-followed-meta",w.textContent="Boost";const E=document.createElement("span");E.className="sap-bc-followed-name",w.append(E),x.append(M,w),a.append(x),c={root:x,ring:M,value:C,name:E}}else c=null;for(const x of b.replay.players){let M=null,C=null,w=null,E=null;r&&(M=document.createElement("div"),M.className="sap-bc-floating-track",M.hidden=!0,(e||t)&&(C=document.createElement("div"),C.className=`sap-bc-boost-bar ${x.isTeamZero?"sap-bc-boost-bar-blue":"sap-bc-boost-bar-orange"}`,w=document.createElement("div"),w.className=`sap-bc-boost-fill ${x.isTeamZero?"sap-bc-boost-fill-blue":"sap-bc-boost-fill-orange"}`,E=document.createElement("span"),E.className="sap-bc-boost-text",C.append(w,E),M.append(C)),Lv(M,b,x.id,x.name),r.append(M));let R=null,D=null,O=null;if(i){R=document.createElement("div"),R.className="sap-bc-hud-player";const k=document.createElement("div");k.className=`sap-bc-hud-boost-bar ${x.isTeamZero?"sap-bc-boost-bar-blue":"sap-bc-boost-bar-orange"}`,D=document.createElement("div"),D.className=`sap-bc-hud-boost-fill ${x.isTeamZero?"sap-bc-boost-fill-blue":"sap-bc-boost-fill-orange"}`,O=document.createElement("span"),O.className="sap-bc-hud-boost-text",k.append(D,O),R.append(k),Lv(R,b,x.id,x.name),(x.isTeamZero?o:l)?.append(R)}h.set(x.id,{floatingRoot:M,floatingBoostFill:w,floatingBoostText:E,teamHudEntry:R,teamHudFill:D,teamHudText:O})}T.append(a),m(b.player.getState().attachedPlayerId),v({...b,state:b.player.getState()})}return{id:"ballchasing-overlay",setup(b){y(b,b.container)},onStateChange(b){m(b.state.attachedPlayerId),v(b)},teardown(b){a?.remove(),a=null,r=null,o=null,l=null,c=null,h.clear(),u&&(b.container.style.position=d,u=!1)},beforeRender(b){if(!a)return;g.copy(b.scene.camera.up).normalize().multiplyScalar(_()*(b.options.fieldScale??1));let T=!1;for(const[x,M]of b.players.entries()){const C=h.get(M.track.id);if(!C)continue;const w=o3(b,x),E=C.floatingRoot?.classList.contains("sap-bc-player-following")??!1;E&&(Iv(c,w,M.track.name,M.track.isTeamZero),T=!0),Pv(C.floatingBoostFill,C.floatingBoostText,w,M.track.name),Pv(C.teamHudFill,C.teamHudText,w,M.track.name);const R=M.mesh,D=R!==null&&M.interpolatedPosition!==null;if(C.teamHudEntry?.classList.toggle("sap-bc-hud-player-inactive",!D),!!C.floatingRoot){if(E||!D||!c3(R,g,b.scene.camera,b.container,p)){C.floatingRoot.hidden=!0;continue}C.floatingRoot.hidden=!1,C.floatingRoot.style.transform=`translate(${p.x.toFixed(1)}px, ${p.y.toFixed(1)}px) translate(-50%, -100%)`}}!T&&c&&(c.root.hidden=!0)}}}function d3(){return` + `,document.head.append(n)}function y3(n,e){const t=n.players[e],i=t.frame?.boostAmount??0,s=t.nextFrame?.boostAmount??i;return vt.lerp(i,s,n.alpha)}function v3(n,e){const t=n.replay.players.find(h=>h.id===e);if(!t)return null;const i=vh(n.replay,n.state.currentTime),s=Math.min(i+1,n.replay.frames.length-1),a=n.replay.frames[i],r=n.replay.frames[s]??a,o=a?.time??n.state.currentTime,l=r?.time??o,c=l>o?vt.clamp((n.state.currentTime-o)/(l-o),0,1):0,u=t.frames[i]?.boostAmount??0,d=t.frames[s]?.boostAmount??u;return vt.lerp(u,d,c)}function Nv(n,e,t,i){if(!n||!e)return;const s=Math.max(0,Math.min(100,Math.round(rf(t))));n.style.width=`${s}%`,e.textContent=`${s} ${i}`}function Uv(n,e,t,i){if(!n)return;const s=Math.max(0,Math.min(100,Math.round(rf(e))));n.root.hidden=!1,n.root.classList.toggle("sap-bc-followed-hud-blue",i),n.root.classList.toggle("sap-bc-followed-hud-orange",!i),n.root.setAttribute("aria-label",`${t} boost ${s}`),n.ring.style.setProperty("--sap-bc-followed-boost",`${s}%`),n.value.textContent=`${s}`,n.name.textContent=t}function Bv(n,e,t,i){if(!n)return;const s=()=>{e.player.setAttachedPlayer(t)};n.classList.add("sap-bc-player-selectable"),n.tabIndex=0,n.setAttribute("role","button"),n.setAttribute("aria-label",`Follow ${i}`),n.title=`Follow ${i}`,n.addEventListener("click",s),n.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),s())})}function b3(n,e,t,i,s){if(n.getWorldPosition(s),s.add(e),s.project(t),s.z<-1||s.z>1)return!1;const a=i.clientWidth||1,r=i.clientHeight||1;return s.x=(s.x+1)*a/2,s.y=(1-s.y)*r/2,!(s.x<-80||s.x>a+80||s.y<-80||s.y>r+80)}function x3(n={}){const e=n.showFloatingNames??!0,t=n.showFloatingBoostBars??!0,i=n.showTeamBoostHud??!0,s=n.showFollowedPlayerHud??!0;let a=null,r=null,o=null,l=null,c=null,u=!1,d="";const h=new Map,f=n.floatingLiftUu,p=new S,g=new S;function _(){const b=typeof f=="function"?f():f;return typeof b=="number"&&Number.isFinite(b)?b:Wm}function m(b){for(const[T,x]of h.entries()){const M=T===b;x.floatingRoot?.classList.toggle("sap-bc-player-following",M),x.teamHudEntry?.classList.toggle("sap-bc-player-following",M),x.floatingRoot?.setAttribute("aria-pressed",M?"true":"false"),x.teamHudEntry?.setAttribute("aria-pressed",M?"true":"false")}}function v(b){if(!c||!b.state.attachedPlayerId){c&&(c.root.hidden=!0);return}const T=b.replay.players.find(M=>M.id===b.state.attachedPlayerId);if(!T){c.root.hidden=!0;return}const x=v3(b,T.id);if(x===null){c.root.hidden=!0;return}Uv(c,x,T.name,T.isTeamZero)}function y(b,T){if(g3(),getComputedStyle(T).position==="static"&&(u=!0,d=T.style.position,T.style.position="relative"),a=document.createElement("div"),a.className="sap-bc-overlay-root",e||t?(r=document.createElement("div"),r.className="sap-bc-floating-layer",a.append(r)):r=null,i?(o=document.createElement("div"),o.className="sap-bc-team-hud sap-bc-team-hud-blue",l=document.createElement("div"),l.className="sap-bc-team-hud sap-bc-team-hud-orange",a.append(o,l)):(o=null,l=null),s){const x=document.createElement("div");x.className="sap-bc-followed-hud",x.hidden=!0;const M=document.createElement("div");M.className="sap-bc-followed-boost-ring";const C=document.createElement("span");C.className="sap-bc-followed-boost-value",M.append(C);const w=document.createElement("div");w.className="sap-bc-followed-meta",w.textContent="Boost";const E=document.createElement("span");E.className="sap-bc-followed-name",w.append(E),x.append(M,w),a.append(x),c={root:x,ring:M,value:C,name:E}}else c=null;for(const x of b.replay.players){let M=null,C=null,w=null,E=null;r&&(M=document.createElement("div"),M.className="sap-bc-floating-track",M.hidden=!0,(e||t)&&(C=document.createElement("div"),C.className=`sap-bc-boost-bar ${x.isTeamZero?"sap-bc-boost-bar-blue":"sap-bc-boost-bar-orange"}`,w=document.createElement("div"),w.className=`sap-bc-boost-fill ${x.isTeamZero?"sap-bc-boost-fill-blue":"sap-bc-boost-fill-orange"}`,E=document.createElement("span"),E.className="sap-bc-boost-text",C.append(w,E),M.append(C)),Bv(M,b,x.id,x.name),r.append(M));let R=null,k=null,O=null;if(i){R=document.createElement("div"),R.className="sap-bc-hud-player";const D=document.createElement("div");D.className=`sap-bc-hud-boost-bar ${x.isTeamZero?"sap-bc-boost-bar-blue":"sap-bc-boost-bar-orange"}`,k=document.createElement("div"),k.className=`sap-bc-hud-boost-fill ${x.isTeamZero?"sap-bc-boost-fill-blue":"sap-bc-boost-fill-orange"}`,O=document.createElement("span"),O.className="sap-bc-hud-boost-text",D.append(k,O),R.append(D),Bv(R,b,x.id,x.name),(x.isTeamZero?o:l)?.append(R)}h.set(x.id,{floatingRoot:M,floatingBoostFill:w,floatingBoostText:E,teamHudEntry:R,teamHudFill:k,teamHudText:O})}T.append(a),m(b.player.getState().attachedPlayerId),v({...b,state:b.player.getState()})}return{id:"ballchasing-overlay",setup(b){y(b,b.container)},onStateChange(b){m(b.state.attachedPlayerId),v(b)},teardown(b){a?.remove(),a=null,r=null,o=null,l=null,c=null,h.clear(),u&&(b.container.style.position=d,u=!1)},beforeRender(b){if(!a)return;g.copy(b.scene.camera.up).normalize().multiplyScalar(_()*(b.options.fieldScale??1));let T=!1;for(const[x,M]of b.players.entries()){const C=h.get(M.track.id);if(!C)continue;const w=y3(b,x),E=C.floatingRoot?.classList.contains("sap-bc-player-following")??!1;E&&(Uv(c,w,M.track.name,M.track.isTeamZero),T=!0),Nv(C.floatingBoostFill,C.floatingBoostText,w,M.track.name),Nv(C.teamHudFill,C.teamHudText,w,M.track.name);const R=M.mesh,k=R!==null&&M.interpolatedPosition!==null;if(C.teamHudEntry?.classList.toggle("sap-bc-hud-player-inactive",!k),!!C.floatingRoot){if(E||!k||!b3(R,g,b.scene.camera,b.container,p)){C.floatingRoot.hidden=!0;continue}C.floatingRoot.hidden=!1,C.floatingRoot.style.transform=`translate(${p.x.toFixed(1)}px, ${p.y.toFixed(1)}px) translate(-50%, -100%)`}}!T&&c&&(c.root.hidden=!0)}}}function w3(){return{guid:{a:0,b:0,c:0,d:0},code:null,name:null,training_type:"Training_None",difficulty:"D_Easy",creator_name:null,description:null,tags:[],map_name:null,created_at:0n,updated_at:0n,creator_player_id:{uid:0n,epic_account_id:null,platform:null,splitscreen_id:0},rounds:[],player_team_number:0,unowned:!1,perfect_completed:!1,shots_completed:0}}let kp=null;async function S3(){return kp||(kp=(async()=>{const n=await F1(()=>import("./rl_replay_subtr_actor-Cnltgw4Z.js"),[],import.meta.url),e=n.default;return typeof e=="function"&&await e(),n})()),kp}async function zv(n){return n?.bindings??S3()}function T3(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function Xr(n){try{return n()}catch(e){throw e instanceof Error?e:new Error(String(e))}}class ta{constructor(e,t){this.bindings=e,this.lossless=t}lossless;cachedPack=null;static async load(e,t){return ta.fromBytes(e,await zv(t))}static fromBytes(e,t){const i=Xr(()=>t.parse_training_pack_lossless(T3(e)));return new ta(t,i)}static async create(e,t){return ta.createWithBindings(await zv(t),e)}static createWithBindings(e,t){const i={...w3(),...t},s=Xr(()=>e.new_training_pack(i));return new ta(e,s)}static fromLosslessJson(e,t){const i=new ta(t,e);return i.view(),i}view(){return this.cachedPack||(this.cachedPack=Xr(()=>this.bindings.training_pack_from_lossless(this.lossless))),this.cachedPack}apply(e){this.lossless=Xr(e),this.cachedPack=null}get losslessJson(){return this.lossless}get pack(){return structuredClone(this.view())}toJSON(){return this.pack}get name(){return this.view().name}get code(){return this.view().code}get description(){return this.view().description}get creatorName(){return this.view().creator_name}get trainingType(){return this.view().training_type}get difficulty(){return this.view().difficulty}get mapName(){return this.view().map_name}get guid(){return{...this.view().guid}}get tags(){return[...this.view().tags]}get rounds(){return structuredClone(this.view().rounds)}get roundCount(){return this.view().rounds.length}updateMetadata(e){const t={...this.view(),...e};this.apply(()=>this.bindings.update_training_pack_metadata(this.lossless,t))}setName(e){this.updateMetadata({name:e})}setCode(e){this.updateMetadata({code:e})}setDescription(e){this.updateMetadata({description:e})}setCreatorName(e){this.updateMetadata({creator_name:e})}setTrainingType(e){this.updateMetadata({training_type:e})}setDifficulty(e){this.updateMetadata({difficulty:e})}setMapName(e){this.updateMetadata({map_name:e})}setTags(e){this.updateMetadata({tags:e})}setGuid(e){this.updateMetadata({guid:e})}addRound(e){this.apply(()=>this.bindings.training_pack_add_round(this.lossless,e))}insertRound(e,t){this.apply(()=>this.bindings.training_pack_insert_round(this.lossless,e,t))}removeRound(e){const t=this.view().rounds[e];return this.apply(()=>this.bindings.training_pack_remove_round(this.lossless,e)),structuredClone(t)}moveRound(e,t){this.apply(()=>this.bindings.training_pack_move_round(this.lossless,e,t))}duplicateRound(e){this.apply(()=>this.bindings.training_pack_duplicate_round(this.lossless,e))}getRoundArchetypes(e){return Xr(()=>this.bindings.training_pack_round_archetypes(this.lossless,e))}setRoundArchetype(e,t,i){this.apply(()=>this.bindings.training_pack_set_round_archetype(this.lossless,e,t,i))}addRoundArchetype(e,t){this.apply(()=>this.bindings.training_pack_add_round_archetype(this.lossless,e,t))}removeRoundArchetype(e,t){const i=this.getRoundArchetypes(e)[t];return this.apply(()=>this.bindings.training_pack_remove_round_archetype(this.lossless,e,t)),i}setRoundBall(e,t){this.apply(()=>this.bindings.training_pack_set_round_ball(this.lossless,e,t))}addRoundCar(e,t){this.addRoundArchetype(e,{kind:"CarSpawnPoint",...t})}setRoundTimeLimit(e,t){this.apply(()=>this.bindings.training_pack_set_round_time_limit(this.lossless,e,t))}appendRoundsFrom(e){const t=e.view().rounds.length;return this.apply(()=>this.bindings.training_pack_append_rounds(this.lossless,e.lossless)),t}toBytes(){return Xr(()=>this.bindings.serialize_training_pack(this.lossless))}}const $T=8,M3=17,E3=32768/Math.PI;function Ol(n){return Math.round(n*E3)}function ju(n,e){const{x:t,y:i,z:s,w:a}=e,r=2*(i*n.z-s*n.y),o=2*(s*n.x-t*n.z),l=2*(t*n.y-i*n.x);return{x:n.x+a*r+(i*l-s*o),y:n.y+a*o+(s*r-t*l),z:n.z+a*l+(t*o-i*r)}}function C3(n){const e=n?.x??0,t=n?.y??0,i=n?.z??0,s=Math.hypot(e,t),a=Math.hypot(s,i);return a===0?{rotator:{pitch:0,yaw:0,roll:0},speed:0}:{rotator:{pitch:Ol(Math.atan2(i,s)),yaw:Ol(Math.atan2(t,e)),roll:0},speed:a}}function A3(n){const e=ju({x:1,y:0,z:0},n),t=ju({x:0,y:1,z:0},n),i=ju({x:0,y:0,z:1},n);return{pitch:Ol(Math.atan2(e.z,Math.hypot(e.x,e.y))),yaw:Ol(Math.atan2(e.y,e.x)),roll:Ol(Math.atan2(t.z,i.z))}}const R3=1,P3=300,I3=400,L3=20;function k3(n,e){const t=P3,i=I3,s=L3,a=n.linearVelocity,r=a?.x??0,o=a?.y??0,l=a?.z??0,c=Math.hypot(r,o,l);if(c<=t)return null;const u=n.rotation?ju({x:1,y:0,z:0},n.rotation):{x:1,y:0,z:0},d=r*u.x+o*u.y+l*u.z,h=d(e>>>0).toString(16).padStart(8,"0").toUpperCase()).join("")}function z3(n){return`${B3(n)}.Tem`}function H3(n=Math.floor(Date.now()/1e3)){const e=BigInt(n);return{guid:U3(),name:"Captured Training Pack",training_type:"Training_Striker",difficulty:"D_Medium",map_name:"Park_P",created_at:e,updated_at:e}}function V3(){return`
@@ -4822,6 +4822,7 @@ void main() { + @@ -5219,6 +5220,70 @@ void main() {
+ +
--
--
-`}const en="#3b82f6",tn="#f59e0b",h3=new Set(["wavedash"]),f3=new Set(["air_dribble","ball_carry","ceiling_shot","double_tap","flick","flip_reset","half_flip","half_volley","one_timer","speed_flip","wall_aerial","wall_aerial_shot","wavedash"]);function Ci(n){return n.split(/[_-]+/).filter(e=>e.length>0).map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1)}`).join(" ")}function Dv(n){return f3.has(n)&&!h3.has(n)}function ef(n){return n===!0?en:n===!1?tn:null}const FT=["timeline","core_player","player_possession","possession","loose_possession","ball_half","ball_third","territorial_pressure","movement","player_activity","field_third","field_half","ball_depth","depth_role","ball_proximity","shadow_defense","rotation_role","first_man_change","goal_context","backboard","ceiling_shot","wall_aerial","wall_aerial_shot","center","flick","flip_reset","dodge_reset","double_tap","fifty_fifty","kickoff","one_timer","pass","ball_carry","controlled_play","rush","dodge","speed_flip","half_flip","half_volley","wavedash","whiff","powerslide","touch","boost_pickups","boost_respawn","bump","demolition"],NT=["air_dribble","ball_carry","ceiling_shot","double_tap","flick","flip_reset","half_flip","half_volley","one_timer","speed_flip","wall_aerial","wall_aerial_shot","wavedash"],Lg=[...new Set([...FT,...NT])],p3=new Set(NT);function io(){return Object.fromEntries(Lg.map(n=>[n,0]))}function Cp(n){return{...n??io()}}function wu(n,e){n[e]+=1}function m3(n){return Lg.includes(n)}function UT(n){if(n==null)return null;if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function Bm(n){return UT(n.meta.primary_player)}function _3(n){return n.meta.team_is_team_0??null}function g3(n){const e=n.meta.stream;return!p3.has(e)||!m3(e)?null:e}function zm(n){const e=n.meta.timing.type==="span"?n.meta.timing.end_frame:n.meta.timing.frame;return typeof e=="number"&&Number.isFinite(e)?e:null}function Hm(n){const e=n.meta.timing.type==="span"?n.meta.timing.end_time:n.meta.timing.time;return typeof e=="number"&&Number.isFinite(e)?e:null}function y3(n,e){const t=zm(n);if(t!==null)return t<=e.frame_number;const i=Hm(n);return i!==null&&i<=e.time}function v3(n){return[...n].sort((e,t)=>{const i=zm(e),s=zm(t);if(i!==s)return(i??Number.POSITIVE_INFINITY)-(s??Number.POSITIVE_INFINITY);const a=Hm(e),r=Hm(t);return a!==r?(a??Number.POSITIVE_INFINITY)-(r??Number.POSITIVE_INFINITY):(Bm(e)??"").localeCompare(Bm(t)??"")})}function BT(n){const e=zT(n);for(const t of n.frames)e.applyFrame(t);return n}function zT(n){const e=Lg.map(s=>({eventType:s,events:v3(jl(n).filter(a=>a.meta.stream===s)),index:0})),t=new Map,i={teamZero:io(),teamOne:io()};return{applyFrame(s){for(const a of e)for(;a.index({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function x3(n,e,t,i){n.is_last_backboard=i,n.time_since_last_backboard=n.last_backboard_time==null?null:Math.max(0,t-n.last_backboard_time),n.frames_since_last_backboard=n.last_backboard_frame==null?null:Math.max(0,e-n.last_backboard_frame)}function w3(n,e,t,i){n.count+=1,n.last_backboard_time=e.time,n.last_backboard_frame=e.frame,n.time_since_last_backboard=Math.max(0,i-e.time),n.frames_since_last_backboard=Math.max(0,t-e.frame)}function S3(n,e){Object.assign(n,e??HT())}function Ov(n,e){n.count=e}function T3(n){const e=VT(n);for(const t of n.frames)e.applyFrame(t);return n}function VT(n){const e=b3(ve(n,"backboard"));let t=0,i=0,s=0,a=null;const r=new Map;return{applyFrame(o){for(const[c,u]of r)x3(u,o.frame_number,o.time,c===a);let l=!1;for(;t({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function Vm(n){return`${n.key}\0${n.value}`}function Su(n){return n.map(Vm).join("")}function GT(n,e){e.sort((s,a)=>Vm(s).localeCompare(Vm(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Su(s.labels)===Su(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Su(s.labels).localeCompare(Su(a.labels))))}function Nv(n,e){return n.labeled_event_counts?.entries.filter(t=>t.labels.some(i=>i.key==="origin"&&i.value===e)).reduce((t,i)=>t+i.count,0)??0}function $T(n){return n.labeled_event_counts?.entries.reduce((e,t)=>e+t.count,0)??0}function WT(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function Uv(n,e){GT(n,[{key:"kind",value:"carry"}]),n.carry_count=$T(n),n.total_carry_time+=e.duration,n.total_straight_line_distance+=e.straight_line_distance,n.total_path_distance+=e.path_distance,n.longest_carry_time=Math.max(n.longest_carry_time,e.duration),n.furthest_carry_distance=Math.max(n.furthest_carry_distance,e.straight_line_distance),n.fastest_carry_speed=Math.max(n.fastest_carry_speed,e.average_speed),n.carry_speed_sum+=e.average_speed,n.average_horizontal_gap_sum+=e.average_horizontal_gap,n.average_vertical_gap_sum+=e.average_vertical_gap}function Bv(n,e){e.air_dribble_origin!=null&>(n,[{key:"origin",value:e.air_dribble_origin}]),n.count=$T(n),n.ground_to_air_count=Nv(n,"ground_to_air"),n.wall_to_air_count=Nv(n,"wall_to_air"),n.total_time+=e.duration,n.total_straight_line_distance+=e.straight_line_distance,n.total_path_distance+=e.path_distance,n.longest_time=Math.max(n.longest_time,e.duration),n.furthest_distance=Math.max(n.furthest_distance,e.straight_line_distance),n.fastest_speed=Math.max(n.fastest_speed,e.average_speed),n.speed_sum+=e.average_speed,n.average_horizontal_gap_sum+=e.average_horizontal_gap,n.average_vertical_gap_sum+=e.average_vertical_gap,n.total_touch_count+=e.touch_count,n.max_touch_count=Math.max(n.max_touch_count,e.touch_count)}function Ap(n,e){Object.assign(n,e??Xu()),e?.labeled_event_counts?n.labeled_event_counts=WT(e.labeled_event_counts):delete n.labeled_event_counts}function Rp(n,e){Object.assign(n,e??Ku()),e?.labeled_event_counts?n.labeled_event_counts=WT(e.labeled_event_counts):delete n.labeled_event_counts}function E3(n){const e=XT(n);for(const t of n.frames)e.applyFrame(t);return n}function XT(n){const e=M3(ve(n,"ball_carry"));let t=0;const i=new Map,s=new Map,a=Xu(),r=Xu(),o=Ku(),l=Ku();return{applyFrame(c){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function A3(n,e){n.bumps_inflicted+=1,e.is_team_bump&&(n.team_bumps_inflicted+=1),n.last_bump_time=e.time,n.last_bump_frame=e.frame,n.last_bump_strength=e.strength,n.max_bump_strength=Math.max(n.max_bump_strength,e.strength),n.cumulative_bump_strength+=e.strength}function R3(n,e){n.bumps_taken+=1,e.is_team_bump&&(n.team_bumps_taken+=1)}function P3(n,e){n.bumps_inflicted+=1,e.is_team_bump&&(n.team_bumps_inflicted+=1)}function I3(n,e){Object.assign(n,e??Gm())}function Hv(n,e){Object.assign(n,e)}function L3(n){const e=KT(n);for(const t of n.frames)e.applyFrame(t);return n}function KT(n){const e=C3(ve(n,"bump"));let t=0;const i=new Map,s=zv(),a=zv();return{applyFrame(r){for(;t=t&&n0&&(s.overfill_total=sn(s.overfill_total,i),e.field_half==="opponent"&&(s.overfill_from_stolen=sn(s.overfill_from_stolen,i)))}function $v(n,e){e.boost_granted!=null&&(n.stats.amount_respawned=sn(n.stats.amount_respawned,rn(e.boost_granted)))}class U3{constructor(e){this.points=e}index=0;sample(e){for(;this.index+1e?0:rn(t.value)}}function Km(n,e){return`${n}:${e}`}function B3(n){const e=new Map,t=n.accumulation_tracks;for(const i of t??[]){const s=pl(i.player_id);e.set(Km(s,i.quantity),new U3(i.points))}return e}function z3(n){return[...ve(n,"boost_pickup")].sort((e,t)=>e.frame-t.frame||e.time-t.time)}function H3(n){return[...ve(n,"respawn")].sort((e,t)=>e.frame-t.frame||e.time-t.time)}function Lp(n,e){for(const t of qT)n[t]=e[t]}function YT(n){const e=z3(n),t=H3(n),i=B3(n);let s=0,a=0;const r=new Map,o=Ip(),l=Ip(),c=(d,h)=>{const f=pl(d);let p=r.get(f);return p||(p=Ip(),r.set(f,p)),p.isTeamZero=h,p},u=(d,h,f)=>{const p=g=>i.get(Km(h,g))?.sample(f)??0;d.amount_used=p("boost_used"),d.amount_used_while_grounded=p("boost_used_grounded"),d.amount_used_while_airborne=p("boost_used_airborne"),d.amount_used_while_supersonic=p("boost_used_supersonic")};return{applyFrame(d,h){for(;s({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function qm(n){return`${n.key}\0${n.value}`}function Mu(n){return n.map(qm).join("")}function K3(n,e){e.sort((s,a)=>qm(s).localeCompare(qm(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Mu(s.labels)===Mu(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Mu(s.labels).localeCompare(Mu(a.labels))))}function q3(n,e){return n.labeled_event_counts?.entries.filter(t=>t.labels.some(i=>i.key==="confidence_band"&&i.value===e)).reduce((t,i)=>t+i.count,0)??0}function Y3(n){return n.labeled_event_counts?.entries.reduce((e,t)=>e+t.count,0)??0}function j3(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function Z3(n,e,t,i){n.is_last_ceiling_shot=i,n.time_since_last_ceiling_shot=n.last_ceiling_shot_time==null?null:Math.max(0,jT(t,n.last_ceiling_shot_time)),n.frames_since_last_ceiling_shot=n.last_ceiling_shot_frame==null?null:Math.max(0,e-n.last_ceiling_shot_frame)}function J3(n,e,t,i){K3(n,[{key:"confidence_band",value:e.confidence>=$3?"high":"standard"}]),n.count=Y3(n),n.high_confidence_count=q3(n,"high"),n.is_last_ceiling_shot=!0,n.last_ceiling_shot_time=e.time,n.last_ceiling_shot_frame=e.frame,n.time_since_last_ceiling_shot=Math.max(0,jT(i,e.time)),n.frames_since_last_ceiling_shot=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=W3(n.cumulative_confidence,e.confidence)}function Q3(n,e){Object.assign(n,e??ZT()),e?.labeled_event_counts?n.labeled_event_counts=j3(e.labeled_event_counts):delete n.labeled_event_counts}function eU(n){const e=JT(n);for(const t of n.frames)e.applyFrame(t);return n}function JT(n){const e=X3(ve(n,"ceiling_shot"));let t=0,i=null;const s=new Map;return{applyFrame(a){if(a.is_live_play){for(const[r,o]of s)Z3(o,a.frame_number,a.time,i===r);for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function sU(n,e){Object.assign(n,e??Dg())}function Kv(n,e){Object.assign(n,e)}function qv(n,e){n.score+=e.score_delta,n.goals+=e.goals_delta,n.assists+=e.assists_delta,n.saves+=e.saves_delta,n.shots+=e.shots_delta}function QT(n,e){if(e.time_after_kickoff!=null){const t=Math.max(0,e.time_after_kickoff);t<10?n.kickoff_goal_count+=1:t<20?n.short_goal_count+=1:t<40?n.medium_goal_count+=1:n.long_goal_count+=1}if(e.goal_buildup==="counter_attack"?n.counter_attack_goal_count+=1:e.goal_buildup==="sustained_pressure"?n.sustained_pressure_goal_count+=1:e.goal_buildup!=null&&(n.other_buildup_goal_count+=1),e.ball_air_time_before_goal!=null){const t=Math.max(0,e.ball_air_time_before_goal);n.goal_ball_air_time_sample_count+=1,n.cumulative_goal_ball_air_time=ns(n.cumulative_goal_ball_air_time,t),n.last_goal_ball_air_time=t}}function Dp(n,e){return n!=null&&e!=null&&ql(n)===ql(e)}function Yv(n,e){return n?e.y:-e.y}function aU(n,e){if(n.ball_position==null||e.position==null)return!1;const t=!n.scoring_team_is_team_0,i=Yv(t,n.ball_position);if(i>tU)return!1;const s=Yv(t,e.position);return s=iU}function rU(n,e,t){const i=t.is_team_0===e.scoring_team_is_team_0,s=Dp(t.player,e.defending_team_most_back_player),a=Dp(t.player,e.scoring_team_most_back_player);s&&(n.goals_conceded_while_last_defender+=1),a&&(n.goals_for_while_most_back+=1),s&&(n.goals_against_while_most_back+=1),!i&&aU(e,t)&&(n.caught_ahead_of_play_on_conceded_goals+=1),!i&&t.boost_amount!=null&&(n.goal_against_boost_sample_count+=1,n.cumulative_boost_on_goals_against=ns(n.cumulative_boost_on_goals_against,t.boost_amount),n.last_boost_on_goal_against=t.boost_amount),!i&&t.average_boost_in_leadup!=null&&t.min_boost_in_leadup!=null&&(n.goal_against_boost_leadup_sample_count+=1,n.cumulative_average_boost_in_goal_against_leadup=ns(n.cumulative_average_boost_in_goal_against_leadup,t.average_boost_in_leadup),n.cumulative_min_boost_in_goal_against_leadup=ns(n.cumulative_min_boost_in_goal_against_leadup,t.min_boost_in_leadup),n.last_average_boost_in_goal_against_leadup=t.average_boost_in_leadup,n.last_min_boost_in_goal_against_leadup=t.min_boost_in_leadup),!i&&t.position!=null&&(n.goal_against_position_sample_count+=1,n.cumulative_goal_against_position_x=ns(n.cumulative_goal_against_position_x,t.position.x),n.cumulative_goal_against_position_y=ns(n.cumulative_goal_against_position_y,t.position.y),n.cumulative_goal_against_position_z=ns(n.cumulative_goal_against_position_z,t.position.z),n.last_goal_against_position={...t.position});const r=Dp(t.player,e.scorer),o=r?e.scorer_last_touch?.ball_position:null;o!=null&&(n.scoring_goal_last_touch_position_sample_count+=1,n.cumulative_scoring_goal_last_touch_position_x=ns(n.cumulative_scoring_goal_last_touch_position_x,o.x),n.cumulative_scoring_goal_last_touch_position_y=ns(n.cumulative_scoring_goal_last_touch_position_y,o.y),n.cumulative_scoring_goal_last_touch_position_z=ns(n.cumulative_scoring_goal_last_touch_position_z,o.z),n.last_scoring_goal_last_touch_position={...o}),r&&QT(n,e)}function oU(n,e,t,i){QT(i.scoring_team_is_team_0?e:t,i);for(const s of i.players){const a=ql(s.player),r=n.get(a)??Dg();n.set(a,r),rU(r,i,s)}}function lU(n){const e=eM(n);for(const t of n.frames)e.applyFrame(t);return n}function eM(n){const e=Xv(ve(n,"core_player")),t=Xv(ve(n,"goal_context"));let i=0,s=0;const a=new Map,r=Ym(),o=Ym();return{applyFrame(l){for(;i({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function Jv(n,e){n.count+=1,n.total_time=jv(n.total_time,e.duration),n.longest_time=Math.max(n.longest_time,e.duration),n.touch_count+=e.touch_count,n.total_advance_distance=jv(n.total_advance_distance,e.total_advance_distance)}function Op(n,e){Object.assign(n,e??qu())}function uU(n){const e=tM(n);for(const t of n.frames)e.applyFrame(t);return n}function tM(n){const e=cU(ve(n,"controlled_play"));let t=0;const i=new Map,s=qu(),a=qu();return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function hU(n,e){n.count+=1,e.on_ball&&(n.on_ball_count+=1)}function fU(n,e){Object.assign(n,e??nM())}function pU(n){const e=iM(n);for(const t of n.frames)e.applyFrame(t);return n}function iM(n){const e=dU(ve(n,"dodge_reset"));let t=0;const i=new Map;return{applyFrame(s){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function _U(n,e,t,i){n.is_last_double_tap=i,n.time_since_last_double_tap=n.last_double_tap_time==null?null:Math.max(0,t-n.last_double_tap_time),n.frames_since_last_double_tap=n.last_double_tap_frame==null?null:Math.max(0,e-n.last_double_tap_frame)}function gU(n,e,t,i){n.count+=1,n.last_double_tap_time=e.time,n.last_double_tap_frame=e.frame,n.time_since_last_double_tap=Math.max(0,i-e.time),n.frames_since_last_double_tap=Math.max(0,t-e.frame)}function yU(n,e){Object.assign(n,e??sM())}function tb(n,e){n.count=e}function vU(n){const e=aM(n);for(const t of n.frames)e.applyFrame(t);return n}function aM(n){const e=mU(ve(n,"double_tap"));let t=0,i=0,s=0,a=null;const r=new Map;return{applyFrame(o){for(const[c,u]of r)_U(u,o.frame_number,o.time,c===a);let l=!1;for(;t({event:e,index:t})).sort((e,t)=>e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function xU(n,e){Object.assign(n,e??rM())}function sb(n,e){Object.assign(n,e)}function wU(n){const e=oM(n);for(const t of n.frames)e.applyFrame(t);return n}function oM(n){const e=bU(ve(n,"demolition"));let t=0;const i=new Map,s=ib(),a=ib();function r(o){const l=nb(o),c=i.get(l)??rM();return i.set(l,c),c}return{applyFrame(o){for(;t({event:e,index:t})).sort((e,t)=>e.event.resolve_frame!==t.event.resolve_frame?e.event.resolve_frame-t.event.resolve_frame:e.event.resolve_time!==t.event.resolve_time?e.event.resolve_time-t.event.resolve_time:e.index-t.index).map(({event:e})=>e)}function TU(n){return{key:"phase",value:n?"kickoff":"open_play"}}function MU(n,e){return e==null?{key:"outcome",value:"neutral"}:{key:"outcome",value:e===n?"win":"loss"}}function EU(n,e){return e==null?{key:"possession_after",value:"neutral"}:{key:"possession_after",value:e===n?"self":"opponent"}}function CU(n,e){return{key:"dodge_state",value:(n?e.team_zero_dodge_contact:e.team_one_dodge_contact)?"dodge":"no_dodge"}}function Zm(n){return`${n.key}\0${n.value}`}function Eu(n){return n.map(Zm).join("")}function AU(n,e){e.sort((s,a)=>Zm(s).localeCompare(Zm(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Eu(s.labels)===Eu(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Eu(s.labels).localeCompare(Eu(a.labels))))}function RU(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function rb(n,e,t){n.count+=1,t.winning_team_is_team_0==null?n.neutral_outcomes+=1:t.winning_team_is_team_0===e?n.wins+=1:n.losses+=1,t.possession_team_is_team_0==null?n.neutral_possession_after_count+=1:t.possession_team_is_team_0===e?n.possession_after_count+=1:n.opponent_possession_after_count+=1,t.is_kickoff&&(n.kickoff_count+=1,t.winning_team_is_team_0==null?n.kickoff_neutral_outcomes+=1:t.winning_team_is_team_0===e?n.kickoff_wins+=1:n.kickoff_losses+=1,t.possession_team_is_team_0==null?n.kickoff_neutral_possession_after_count+=1:t.possession_team_is_team_0===e?n.kickoff_possession_after_count+=1:n.kickoff_opponent_possession_after_count+=1)}function ob(n,e,t){AU(n,[TU(t.is_kickoff),MU(e,t.winning_team_is_team_0),EU(e,t.possession_team_is_team_0),CU(e,t)]),n.count+=1,t.winning_team_is_team_0==null?n.neutral_outcomes+=1:t.winning_team_is_team_0===e?n.wins+=1:n.losses+=1,t.possession_team_is_team_0===e&&(n.possession_after_count+=1),t.is_kickoff&&(n.kickoff_count+=1,t.winning_team_is_team_0==null?n.kickoff_neutral_outcomes+=1:t.winning_team_is_team_0===e?n.kickoff_wins+=1:n.kickoff_losses+=1,t.possession_team_is_team_0===e&&(n.kickoff_possession_after_count+=1))}function PU(n,e){Object.assign(n,e??jm()),e?.labeled_event_counts?n.labeled_event_counts=RU(e.labeled_event_counts):delete n.labeled_event_counts}function lb(n,e){Object.assign(n,e)}function IU(n){const e=lM(n);for(const t of n.frames)e.applyFrame(t);return n}function lM(n){const e=SU(ve(n,"fifty_fifty"));let t=0;const i=ab(),s=ab(),a=new Map;return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function Jm(n){return`${n.key}\0${n.value}`}function Cu(n){return n.map(Jm).join("")}function dM(n,e){e.sort((s,a)=>Jm(s).localeCompare(Jm(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Cu(s.labels)===Cu(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Cu(s.labels).localeCompare(Cu(a.labels))))}function DU(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function kU(n){return[{key:"kickoff_spawn",value:n.spawn_position},{key:"taker_outcome",value:n.outcome},{key:"kickoff_approach",value:n.approach},{key:"approach_flip_direction",value:n.approach_flip_direction}]}function OU(n){return[{key:"kickoff_spawn",value:n.spawn_position},{key:"support_behavior",value:n.support_behavior}]}function ub(n,e,t){n.count+=1,t.outcome==="neutral"?n.neutral_outcomes+=1:t.outcome===(e?"team_zero_win":"team_one_win")?n.wins+=1:t.outcome===(e?"team_one_win":"team_zero_win")&&(n.losses+=1),t.kickoff_possession_outcome==="contested"?n.contested_kickoff_possessions+=1:t.kickoff_possession_outcome===(e?"team_zero_possession":"team_one_possession")?n.kickoff_possessions+=1:t.kickoff_possession_outcome===(e?"team_one_possession":"team_zero_possession")?n.opponent_kickoff_possessions+=1:t.kickoff_possession_outcome===(e?"team_zero_advantage":"team_one_advantage")?n.kickoff_possession_advantages+=1:n.opponent_kickoff_possession_advantages+=1,t.kickoff_goal&&(n.kickoff_goal_count+=1,t.scoring_team_is_team_0===e?n.kickoff_goals_for+=1:t.scoring_team_is_team_0!=null&&(n.kickoff_goals_against+=1)),t.win_strength!=null&&(n.win_strength_sample_count+=1,n.cumulative_win_strength+=t.win_strength)}function db(n,e,t){t&&(t.boost_after!=null&&(n.boost_after_sample_count+=1,n.cumulative_boost_after+=t.boost_after,e.boost_after_sample_count+=1,e.cumulative_boost_after+=t.boost_after),t.outcome==="fake"?(n.fake_count+=1,e.fake_count+=1):t.outcome==="missed"&&(n.missed_count+=1,e.missed_count+=1))}function FU(n,e,t){n.count+=1,dM(n,kU(t)),t.outcome==="touched"?n.touches+=1:t.outcome==="fake"?n.fakes+=1:t.outcome==="missed"&&(n.misses+=1),e.kickoff_goal&&e.scoring_team_is_team_0===t.is_team_0&&(n.kickoff_goal_count+=1),t.boost_after!=null&&(n.boost_after_sample_count+=1,n.cumulative_boost_after+=t.boost_after)}function NU(n,e,t){n.count+=1,dM(n,OU(t)),t.first_touch_time!=null&&(n.touches+=1),t.support_behavior==="go_for_boost"?n.support_go_for_boosts+=1:t.support_behavior==="cheat"?n.support_cheats+=1:t.support_behavior==="other"&&(n.support_other+=1),e.kickoff_goal&&e.scoring_team_is_team_0===t.is_team_0&&(n.kickoff_goal_count+=1),t.boost_after!=null&&(n.boost_after_sample_count+=1,n.cumulative_boost_after+=t.boost_after)}function Au(n,e,t){const i=cM(t.player),s=n.get(i)??uM();n.set(i,s),"outcome"in t?FU(s,e,t):NU(s,e,t)}function hb(n,e){Object.assign(n,e)}function UU(n,e){Object.assign(n,e??uM()),e?.labeled_event_counts?n.labeled_event_counts=DU(e.labeled_event_counts):delete n.labeled_event_counts}function BU(n){const e=hM(n);for(const t of n.frames)e.applyFrame(t);return n}function hM(n){const e=LU(ve(n,"kickoff"));let t=0;const i=cb(),s=cb(),a=new Map;return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function Qm(n){return`${n.key}\0${n.value}`}function Ru(n){return n.map(Qm).join("")}function VU(n,e){e.sort((s,a)=>Qm(s).localeCompare(Qm(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Ru(s.labels)===Ru(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Ru(s.labels).localeCompare(Ru(a.labels))))}function GU(n,e){return n.labeled_event_counts?.entries.filter(t=>t.labels.some(i=>i.key==="confidence_band"&&i.value===e)).reduce((t,i)=>t+i.count,0)??0}function $U(n){return n==="forward"||n==="reverse"||n==="side"?n:"other"}function WU(n){return n==="left"||n==="right"?n:"center"}function XU(n){return n.labeled_event_counts?.entries.reduce((e,t)=>e+t.count,0)??0}function KU(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function qU(n,e,t,i){n.is_last_flick=i,n.time_since_last_flick=n.last_flick_time==null?null:Math.max(0,fM(t,n.last_flick_time)),n.frames_since_last_flick=n.last_flick_frame==null?null:Math.max(0,e-n.last_flick_frame)}function YU(n,e,t,i){VU(n,[{key:"confidence_band",value:e.confidence>=zU?"high":"standard"},{key:"kind",value:$U(e.kind)},{key:"direction",value:WU(e.direction)}]),n.count=XU(n),n.high_confidence_count=GU(n,"high"),n.is_last_flick=!0,n.last_flick_time=e.time,n.last_flick_frame=e.frame,n.time_since_last_flick=Math.max(0,fM(i,e.time)),n.frames_since_last_flick=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=Np(n.cumulative_confidence,e.confidence),n.cumulative_setup_duration=Np(n.cumulative_setup_duration,e.setup_duration),n.cumulative_ball_speed_change=Np(n.cumulative_ball_speed_change,e.ball_speed_change)}function jU(n,e){Object.assign(n,e??pM()),e?.labeled_event_counts?n.labeled_event_counts=KU(e.labeled_event_counts):delete n.labeled_event_counts}function ZU(n){const e=mM(n);for(const t of n.frames)e.applyFrame(t);return n}function mM(n){const e=HU(ve(n,"flick"));let t=0,i=null;const s=new Map;return{applyFrame(a){if(a.is_live_play){for(const[r,o]of s)qU(o,a.frame_number,a.time,r===i);for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function QU(n,e){n.count+=1,n.total_time_to_use+=e.time_since_reset,n.min_time_to_use=n.min_time_to_use===null?e.time_since_reset:Math.min(n.min_time_to_use,e.time_since_reset)}function eB(n,e){Object.assign(n,e??_M())}function tB(n){const e=gM(n);for(const t of n.frames)e.applyFrame(t);return n}function gM(n){const e=JU(ve(n,"flip_reset"));let t=0;const i=new Map;return{applyFrame(s){for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function iB(n,e,t,i){n.is_last_half_volley=i,n.time_since_last_half_volley=n.last_half_volley_time==null?null:Math.max(0,vM(t,n.last_half_volley_time)),n.frames_since_last_half_volley=n.last_half_volley_frame==null?null:Math.max(0,e-n.last_half_volley_frame)}function sB(n,e,t,i){n.count+=1,n.total_ball_speed=yM(n.total_ball_speed,e.ball_speed),n.fastest_ball_speed=Math.max(n.fastest_ball_speed,e.ball_speed),n.last_half_volley_time=e.time,n.last_half_volley_frame=e.frame,n.time_since_last_half_volley=Math.max(0,vM(i,e.time)),n.frames_since_last_half_volley=Math.max(0,t-e.frame)}function aB(n,e){Object.assign(n,e??bM())}function _b(n,e){Object.assign(n,e)}function rB(n){const e=xM(n);for(const t of n.frames)e.applyFrame(t);return n}function xM(n){const e=nB(ve(n,"half_volley"));let t=0,i=null;const s=new Map,a={count:0,total_ball_speed:0,fastest_ball_speed:0},r={count:0,total_ball_speed:0,fastest_ball_speed:0};return{applyFrame(o){for(const[l,c]of s)iB(c,o.frame_number,o.time,o.is_live_play&&l===i);if(!o.is_live_play)i=null;else{let l=!1;for(;te.frame!==t.frame?e.frame-t.frame:e.time!==t.time?e.time-t.time:Gi(e.player).localeCompare(Gi(t.player)))}function uB(n){return[...n].sort((e,t)=>e.resolved_frame!==t.resolved_frame?e.resolved_frame-t.resolved_frame:e.resolved_time!==t.resolved_time?e.resolved_time-t.resolved_time:e.frame!==t.frame?e.frame-t.frame:e.time!==t.time?e.time-t.time:Gi(e.player).localeCompare(Gi(t.player)))}function Up(){return{count:0,highConfidenceCount:0,lastTime:null,lastFrame:null,lastResolvedTime:null,lastResolvedFrame:null,lastQuality:null,bestQuality:0,cumulativeQuality:0,labeledCounts:{entries:[]}}}function oo(n){return Math.fround(n)}function dB(n,e){return oo(oo(n)+oo(e))}function hB(n,e){return{key:"confidence_band",value:n>=e?"high":"standard"}}function fB(n,e){const t=e.sort((s,a)=>s.key===a.key?s.value.localeCompare(a.value):s.key.localeCompare(a.key)),i=n.entries.find(s=>s.labels.length===t.length&&s.labels.every((a,r)=>a.key===t[r]?.key&&a.value===t[r]?.value));if(i){i.count+=1;return}n.entries.push({labels:t,count:1}),n.entries.sort((s,a)=>JSON.stringify(s.labels).localeCompare(JSON.stringify(a.labels)))}function Oo(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function Bp(n,e,t,i,s){n.count+=1,e.confidence>=s&&(n.highConfidenceCount+=1),fB(n.labeledCounts,[hB(e.confidence,s)]),n.lastTime=e.time,n.lastFrame=e.frame,n.lastResolvedTime=i,n.lastResolvedFrame=t,n.lastQuality=e.confidence,n.bestQuality=Math.max(n.bestQuality,e.confidence),n.cumulativeQuality=dB(n.cumulativeQuality,e.confidence)}function kg(n,e){return n?.lastTime==null?null:n.lastResolvedFrame===e.frame_number?0:Math.max(0,oo(oo(e.time)-oo(n.lastTime)))}function Og(n,e){return n?.lastFrame==null?null:n.lastResolvedFrame===e.frame_number?0:Math.max(0,e.frame_number-n.lastFrame)}function wM(n,e,t,i){n.count=e?.count??0,n.high_confidence_count=e?.highConfidenceCount??0,n.is_last_speed_flip=i,n.last_speed_flip_time=e?.lastTime??null,n.last_speed_flip_frame=e?.lastFrame??null,n.time_since_last_speed_flip=kg(e,t),n.frames_since_last_speed_flip=Og(e,t),n.last_quality=e?.lastQuality??null,n.best_quality=e?.bestQuality??0,n.cumulative_quality=e?.cumulativeQuality??0,e?.labeledCounts.entries.length?n.labeled_event_counts=Oo(e.labeledCounts):delete n.labeled_event_counts}function SM(n,e,t,i){n.count=e?.count??0,n.high_confidence_count=e?.highConfidenceCount??0,n.is_last_half_flip=i,n.last_half_flip_time=e?.lastTime??null,n.last_half_flip_frame=e?.lastFrame??null,n.time_since_last_half_flip=kg(e,t),n.frames_since_last_half_flip=Og(e,t),n.last_quality=e?.lastQuality??null,n.best_quality=e?.bestQuality??0,n.cumulative_quality=e?.cumulativeQuality??0,e?.labeledCounts.entries.length?n.labeled_event_counts=Oo(e.labeledCounts):delete n.labeled_event_counts}function TM(n,e,t,i){n.count=e?.count??0,n.high_confidence_count=e?.highConfidenceCount??0,n.is_last_wavedash=i,n.last_wavedash_time=e?.lastTime??null,n.last_wavedash_frame=e?.lastFrame??null,n.time_since_last_wavedash=kg(e,t),n.frames_since_last_wavedash=Og(e,t),n.last_quality=e?.lastQuality??null,n.best_quality=e?.bestQuality??0,n.cumulative_quality=e?.cumulativeQuality??0,e?.labeledCounts.entries.length?n.labeled_event_counts=Oo(e.labeledCounts):delete n.labeled_event_counts}function pB(n){const e={...n};return n.labeled_event_counts?e.labeled_event_counts=Oo(n.labeled_event_counts):delete e.labeled_event_counts,e}function mB(n){const e={...n};return n.labeled_event_counts?e.labeled_event_counts=Oo(n.labeled_event_counts):delete e.labeled_event_counts,e}function _B(n){const e={...n};return n.labeled_event_counts?e.labeled_event_counts=Oo(n.labeled_event_counts):delete e.labeled_event_counts,e}function gB(n,e){if(e){Object.assign(n,e);return}wM(n,void 0,{frame_number:0,time:0},!1)}function yB(n,e){if(e){Object.assign(n,e);return}SM(n,void 0,{frame_number:0,time:0},!1)}function vB(n,e){if(e){Object.assign(n,e);return}TM(n,void 0,{frame_number:0,time:0},!1)}function bB(n){return n.is_live_play||n.ball_has_been_hit===!1}function xB(n){const e=MM(n);for(const t of n.frames)e.applyFrame(t);return n}function MM(n){const e=uB(ve(n,"speed_flip")),t=gb(ve(n,"half_flip")),i=gb(ve(n,"wavedash"));let s=0,a=0,r=0,o=null,l=null,c=null;const u=new Map,d=new Map,h=new Map,f=new Map,p=new Map,g=new Map;return{applyFrame(_){if(bB(_)){for(;swB.map(e=>({labels:[{key:"height_band",value:n},{key:"speed_band",value:e}],value:0}))).sort((n,e)=>JSON.stringify(n.labels).localeCompare(JSON.stringify(e.labels)))}}function Yu(n=!1){return{tracked_time:0,total_distance:0,speed_integral:0,time_slow_speed:0,time_boost_speed:0,time_supersonic_speed:0,time_on_ground:0,time_low_air:0,time_high_air:0,labeled_tracked_time:n?MB():{entries:[]}}}function EB(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function CB(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function AB(n,e,t){const i=CB(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=is(s.value,t):(n.entries.push({labels:i,value:ra(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function RB(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),value:e.value}))}}function vb(n,e){const t=ra(e.dt);n.tracked_time=is(n.tracked_time,t),n.total_distance=is(n.total_distance,e.distance),n.speed_integral=is(n.speed_integral,TB(e.speed,t)),e.speed_band==="slow"?n.time_slow_speed=is(n.time_slow_speed,t):e.speed_band==="boost"?n.time_boost_speed=is(n.time_boost_speed,t):e.speed_band==="supersonic"&&(n.time_supersonic_speed=is(n.time_supersonic_speed,t)),e.height_band==="ground"?n.time_on_ground=is(n.time_on_ground,t):e.height_band==="low_air"?n.time_low_air=is(n.time_low_air,t):e.height_band==="high_air"&&(n.time_high_air=is(n.time_high_air,t));const i=n.labeled_tracked_time??{entries:[]};n.labeled_tracked_time=i,AB(i,[{key:"speed_band",value:e.speed_band},{key:"height_band",value:e.height_band}],t)}function zp(n,e){const t=e??Yu(!0),i=t.labeled_tracked_time;Object.assign(n,t,{labeled_tracked_time:i?RB(i):void 0}),i?.entries.length||delete n.labeled_tracked_time}function PB(n){const e=EM(n);for(const t of n.frames)e.applyFrame(t);return n}function EM(n){const e=EB(ve(n,"movement"));let t=0;const i=new Map,s=Yu(),a=Yu();return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function LB(n,e,t,i){n.is_last_one_timer=i,n.time_since_last_one_timer=n.last_one_timer_time==null?null:Math.max(0,t-n.last_one_timer_time),n.frames_since_last_one_timer=n.last_one_timer_frame==null?null:Math.max(0,e-n.last_one_timer_frame)}function DB(n,e,t,i){n.count+=1,n.total_ball_speed+=e.ball_speed,n.fastest_ball_speed=Math.max(n.fastest_ball_speed,e.ball_speed),n.total_pass_distance+=e.pass_travel_distance,n.last_one_timer_time=e.time,n.last_one_timer_frame=e.frame,n.time_since_last_one_timer=Math.max(0,i-e.time),n.frames_since_last_one_timer=Math.max(0,t-e.frame)}function kB(n,e){Object.assign(n,e??CM())}function xb(n,e){Object.assign(n,e)}function OB(n){const e=AM(n);for(const t of n.frames)e.applyFrame(t);return n}function AM(n){const e=IB(ve(n,"one_timer"));let t=0,i=null;const s=new Map,a={count:0,total_ball_speed:0,fastest_ball_speed:0},r={count:0,total_ball_speed:0,fastest_ball_speed:0};return{applyFrame(o){for(const[l,c]of s)LB(c,o.frame_number,o.time,o.is_live_play&&l===i);if(!o.is_live_play)i=null;else{let l=!1;for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.index-t.index}).map(({event:e})=>e)}function NB(n,e,t,i){n.is_last_completed_pass=i,n.time_since_last_completed_pass=n.last_completed_pass_time==null?null:Math.max(0,t-n.last_completed_pass_time),n.frames_since_last_completed_pass=n.last_completed_pass_frame==null?null:Math.max(0,e-n.last_completed_pass_frame)}function UB(n,e,t,i){n.completed_pass_count+=1,n.total_pass_distance+=e.ball_travel_distance,n.total_pass_advance+=e.ball_advance_distance,n.longest_pass_distance=Math.max(n.longest_pass_distance,e.ball_travel_distance),n.last_completed_pass_time=e.time,n.last_completed_pass_frame=e.frame,n.time_since_last_completed_pass=Math.max(0,i-e.time),n.frames_since_last_completed_pass=Math.max(0,t-e.frame)}function BB(n,e){Object.assign(n,e??e_())}function wb(n,e){Object.assign(n,e)}function zB(n){const e=RM(n);for(const t of n.frames)e.applyFrame(t);return n}function RM(n){const e=FB(ve(n,"pass"));let t=0,i=null;const s=new Map,a={completed_pass_count:0,total_pass_distance:0,total_pass_advance:0,longest_pass_distance:0},r={completed_pass_count:0,total_pass_distance:0,total_pass_advance:0,longest_pass_distance:0};return{applyFrame(o){for(const[l,c]of s)NB(c,o.frame_number,o.time,o.is_live_play&&l===i);if(!o.is_live_play)i=null;else{let l=!1;for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function GB(n){return t_(n)}function $B(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function PM(n,e,t){const i=$B(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=ml(s.value,t):(n.entries.push({labels:i,value:Ll(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function WB(n,e){return n.key==="possession_state"&&n.value==="team_zero"?{key:"possession_state",value:e?"own":"opponent"}:n.key==="possession_state"&&n.value==="team_one"?{key:"possession_state",value:e?"opponent":"own"}:n.key==="field_third"&&n.value==="team_zero_third"?{key:"field_third",value:e?"defensive_third":"offensive_third"}:n.key==="field_third"&&n.value==="team_one_third"?{key:"field_third",value:e?"offensive_third":"defensive_third"}:n.key==="field_half"&&n.value==="team_zero_side"?{key:"field_half",value:e?"defensive_half":"offensive_half"}:n.key==="field_half"&&n.value==="team_one_side"?{key:"field_half",value:e?"offensive_half":"defensive_half"}:{...n}}function Sb(n,e){const t={entries:[]};for(const i of n.labeled_time.entries)PM(t,i.labels.map(s=>WB(s,e)),i.value);return{tracked_time:n.tracked_time,possession_time:e?n.team_zero_time:n.team_one_time,opponent_possession_time:e?n.team_one_time:n.team_zero_time,neutral_time:n.neutral_time,labeled_time:t}}function XB(n,e){n.active=e.active,n.possessionState=e.possession_state}function KB(n,e,t){if(!e.active)return;const i=Ll(t.dt);n.tracked_time=ml(n.tracked_time,i),e.possessionState==="team_zero"?n.team_zero_time=ml(n.team_zero_time,i):e.possessionState==="team_one"?n.team_one_time=ml(n.team_one_time,i):n.neutral_time=ml(n.neutral_time,i);const s=[{key:"possession_state",value:e.possessionState}];e.fieldThird!=null&&s.push({key:"field_third",value:e.fieldThird}),e.fieldHalf!=null&&s.push({key:"field_half",value:e.fieldHalf}),PM(n.labeled_time,s,i)}function Tb(n,e){Object.assign(n,e??VB())}function qB(n){const e=IM(n);for(const t of n.frames)e.applyFrame(t);return n}function IM(n){const e=GB(ve(n,"possession")),t=t_(ve(n,"ball_third")),i=t_(ve(n,"ball_half"));let s=0,a=0,r=0;const o=HB(),l={active:!1,possessionState:"neutral",fieldThird:null,fieldHalf:null};return{applyFrame(c){for(;s({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function ka(n,e){const t=eh(e.player),i=n.get(t)??LM();return n.set(t,i),i}function jB(n,e){switch(n.active_game_time=Xt(n.active_game_time,e.duration),e.state){case"tracked":n.tracked_time=Xt(n.tracked_time,e.duration);break;case"demolished":n.time_demolished=Xt(n.time_demolished,e.duration);break}}function ZB(n,e){switch(e.state){case"defensive":n.time_defensive_third=Xt(n.time_defensive_third,e.duration);break;case"neutral":n.time_neutral_third=Xt(n.time_neutral_third,e.duration);break;case"offensive":n.time_offensive_third=Xt(n.time_offensive_third,e.duration);break}}function JB(n,e){switch(e.state){case"defensive":n.time_defensive_half=Xt(n.time_defensive_half,e.duration);break;case"offensive":n.time_offensive_half=Xt(n.time_offensive_half,e.duration);break}}function QB(n,e){switch(e.state){case"behind_ball":n.time_behind_ball=Xt(n.time_behind_ball,e.duration);break;case"level_with_ball":n.time_level_with_ball=Xt(n.time_level_with_ball,e.duration);break;case"ahead_of_ball":n.time_in_front_of_ball=Xt(n.time_in_front_of_ball,e.duration);break}}function ez(n,e){switch(e.state){case"no_teammates":n.time_no_teammates=Xt(n.time_no_teammates,e.duration);break;case"most_back":n.time_most_back=Xt(n.time_most_back,e.duration);break;case"most_forward":n.time_most_forward=Xt(n.time_most_forward,e.duration);break;case"mid":n.time_mid_role=Xt(n.time_mid_role,e.duration);break;case"other":n.time_other_role=Xt(n.time_other_role,e.duration);break}}function tz(n,e,t){t.state.closest_to_ball_team&&(e.tracked_time=Xt(e.tracked_time,t.duration),e.time_closest_to_ball_team=Xt(e.time_closest_to_ball_team,t.duration),n.time_closest_to_ball_team=Xt(n.time_closest_to_ball_team,t.duration)),t.state.closest_to_ball_absolute&&(e.time_closest_to_ball_absolute=Xt(e.time_closest_to_ball_absolute,t.duration),n.time_closest_to_ball_absolute=Xt(n.time_closest_to_ball_absolute,t.duration)),t.state.farthest_from_ball&&(n.time_farthest_from_ball=Xt(n.time_farthest_from_ball,t.duration))}function nz(n,e){e.state==="shadowing"&&(n.time_shadow_defense=Xt(n.time_shadow_defense,e.duration))}function iz(n,e){Object.assign(n,e??LM())}function Mb(n,e){Object.assign(n,e??n_())}function Oa(n,e){const t=YB(n),i=new Array(t.length).fill(0);return{applyThroughFrame(s){for(let a=0;as.frame_number)break;const o=sz(r,s),l=o-i[a];l>0&&(i[a]=o,e({...r,duration:l}))}}}}function sz(n,e){if(e.frame_number>=n.end_frame)return n.duration;const t=n.end_time-n.time;if(t<=0)return 0;const i=Math.max(0,e.time-n.time);return n.duration*Math.min(1,i/t)}function az(n){const e=DM(n);for(const t of n.frames)e.applyFrame(t);return n}function DM(n){const e=new Map,t=n_(),i=n_(),s=[Oa(ve(n,"player_activity"),a=>jB(ka(e,a),a)),Oa(ve(n,"field_third"),a=>ZB(ka(e,a),a)),Oa(ve(n,"field_half"),a=>JB(ka(e,a),a)),Oa(ve(n,"ball_depth"),a=>QB(ka(e,a),a)),Oa(ve(n,"depth_role"),a=>ez(ka(e,a),a)),Oa(ve(n,"ball_proximity"),a=>tz(ka(e,a),a.is_team_0?t:i,a)),Oa(ve(n,"shadow_defense"),a=>nz(ka(e,a),a))];return{applyFrame(a){for(const r of s)r.applyThroughFrame(a);Mb(a.team_zero.positioning,t),Mb(a.team_one.positioning,i);for(const r of a.players)iz(r.positioning,e.get(eh(r.player_id))),rz(r.positioning,n,r.player_id)}}}function rz(n,e,t){const i=e.positioning_summary;if(!Array.isArray(i))return;const s=eh(t),a=i.find(r=>!r||typeof r!="object"?!1:eh(r.player_id)===s);a?.distance&&Object.assign(n,a.distance)}function Vp(n){if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function _l(){return{total_duration:0,press_count:0}}function oz(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function lz(n){return n.gameplay_phase==="active_play"||n.gameplay_phase==="kickoff_waiting_for_touch"}function Gp(n,e){Object.assign(n,e??_l())}function cz(n){const e=kM(n);for(const t of n.frames)e.applyFrame(t);return n}function kM(n){const e=oz(ve(n,"powerslide"));let t=0;const i=new Map,s=new Map,a=_l(),r=_l();return{applyFrame(o){const l=lz(o);for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function fz(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function OM(n,e,t){const i=fz(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=gl(s.value,t):(n.entries.push({labels:i,value:Dl(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function pz(n,e){return n.key==="field_half"&&n.value==="team_zero_side"?{key:"field_half",value:e?"defensive_half":"offensive_half"}:n.key==="field_half"&&n.value==="team_one_side"?{key:"field_half",value:e?"offensive_half":"defensive_half"}:{...n}}function Eb(n,e){const t={entries:[]};for(const i of n.labeled_time.entries)OM(t,i.labels.map(s=>pz(s,e)),i.value);return{tracked_time:n.tracked_time,defensive_half_time:e?n.team_zero_side_time:n.team_one_side_time,offensive_half_time:e?n.team_one_side_time:n.team_zero_side_time,neutral_time:n.neutral_time,labeled_time:t}}function mz(n,e){n.active=e.active,n.fieldHalf=e.field_half}function _z(n,e,t){if(!e.active)return;const i=Dl(t.dt);n.tracked_time=gl(n.tracked_time,i),e.fieldHalf==="team_zero_side"?n.team_zero_side_time=gl(n.team_zero_side_time,i):e.fieldHalf==="team_one_side"?n.team_one_side_time=gl(n.team_one_side_time,i):n.neutral_time=gl(n.neutral_time,i),OM(n.labeled_time,[{key:"field_half",value:e.fieldHalf}],i)}function Cb(n,e){Object.assign(n,e??dz())}function gz(n){const e=FM(n);for(const t of n.frames)e.applyFrame(t);return n}function FM(n){const e=hz(ve(n,"ball_half"));let t=0;const i=uz(),s={active:!1,fieldHalf:"neutral"};return{applyFrame(a){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function xz(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function NM(n,e,t){const i=xz(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=yl(s.value,t):(n.entries.push({labels:i,value:kl(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function wz(n,e){return n.key==="field_third"&&n.value==="team_zero_third"?{key:"field_third",value:e?"defensive_third":"offensive_third"}:n.key==="field_third"&&n.value==="team_one_third"?{key:"field_third",value:e?"offensive_third":"defensive_third"}:{...n}}function Ab(n,e){const t={entries:[]};for(const i of n.labeled_time.entries)NM(t,i.labels.map(s=>wz(s,e)),i.value);return{tracked_time:n.tracked_time,defensive_third_time:e?n.team_zero_third_time:n.team_one_third_time,neutral_third_time:n.neutral_third_time,offensive_third_time:e?n.team_one_third_time:n.team_zero_third_time,labeled_time:t}}function Sz(n,e){n.active=e.active,n.fieldThird=e.field_third}function Tz(n,e,t){if(!e.active)return;const i=kl(t.dt);n.tracked_time=yl(n.tracked_time,i),e.fieldThird==="team_zero_third"?n.team_zero_third_time=yl(n.team_zero_third_time,i):e.fieldThird==="team_one_third"?n.team_one_third_time=yl(n.team_one_third_time,i):n.neutral_third_time=yl(n.neutral_third_time,i),NM(n.labeled_time,[{key:"field_third",value:e.fieldThird}],i)}function Rb(n,e){Object.assign(n,e??vz())}function Mz(n){const e=UM(n);for(const t of n.frames)e.applyFrame(t);return n}function UM(n){const e=bz(ve(n,"ball_third"));let t=0;const i=yz(),s={active:!1,fieldThird:"neutral_third"};return{applyFrame(a){for(;t({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function Cz(n,e,t){n.session_count+=1,n.session_time=Pu(n.session_time,t.duration),n.offensive_half_time=Pu(n.offensive_half_time,t.offensive_half_time),n.offensive_third_time=Pu(n.offensive_third_time,t.offensive_third_time),n.longest_session_time=Math.max(n.longest_session_time,t.duration),n.average_session_time=n.session_count===0?0:ju(n.session_time/n.session_count),e.opponent_session_count+=1,e.opponent_session_time=Pu(e.opponent_session_time,t.duration),e.opponent_longest_session_time=Math.max(e.opponent_longest_session_time,t.duration)}function Ib(n,e){Object.assign(n,e)}function Az(n){const e=BM(n);for(const t of n.frames)e.applyFrame(t);return n}function BM(n){const e=Ez(ve(n,"territorial_pressure"));let t=0;const i=Pb(),s=Pb();return{applyFrame(a){for(;t=e[t].end_frame;){const r=e[t];Cz(r.team_is_team_0?i:s,r.team_is_team_0?s:i,r),t+=1}Ib(a.team_zero.territorial_pressure,i),Ib(a.team_one.territorial_pressure,s)}}}function Kr(n,e){return Math.fround(Math.fround(n)+Math.fround(e))}function zM(n){if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function HM(){return{active_game_time:0,time_first_man:0,time_second_man:0,time_third_man:0,time_ambiguous_role:0,longest_first_man_stint_time:0,first_man_stint_count:0,became_first_man_count:0,lost_first_man_count:0,current_role_state:"unknown"}}function Lb(){return{first_man_changes_for_team:0,rotation_count:0}}function Db(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function Rz(n,e,t,i,s){const a=n.stats;switch(a.active_game_time=Kr(a.active_game_time,t),a.current_role_state=e.state,e.state){case"first_man":{n.lastFirstManEndTime!==null&&e.time-n.lastFirstManEndTime<=s?n.currentFirstManStintTime=Kr(n.currentFirstManStintTime,t):(n.currentFirstManStintTime=t,a.first_man_stint_count+=1),n.lastFirstManEndTime=i,a.longest_first_man_stint_time=Math.max(a.longest_first_man_stint_time,n.currentFirstManStintTime),a.time_first_man=Kr(a.time_first_man,t);break}case"second_man":a.time_second_man=Kr(a.time_second_man,t);break;case"third_man":a.time_third_man=Kr(a.time_third_man,t);break;case"ambiguous":a.time_ambiguous_role=Kr(a.time_ambiguous_role,t);break}}function Pz(n,e){if(e.frame_number>=n.end_frame)return n.duration;const t=n.end_time-n.time;if(t<=0)return 0;const i=Math.max(0,e.time-n.time);return n.duration*Math.min(1,i/t)}function i_(n,e){const t=zM(e),i=n.get(t)??{currentFirstManStintTime:0,lastFirstManEndTime:null,stats:HM()};return n.set(t,i),i}function Iz(n,e,t){n.first_man_changes_for_team+=1,n.rotation_count+=1,i_(e,t.previous_first_man).stats.lost_first_man_count+=1,i_(e,t.next_first_man).stats.became_first_man_count+=1}function Lz(n,e){Object.assign(n,e??HM())}function kb(n,e){Object.assign(n,e)}function Dz(n){const e=VM(n);for(const t of n.frames)e.applyFrame(t);return n}function VM(n){const e=Db(ve(n,"rotation_role")),t=Db(ve(n,"first_man_change")),i=n.config.rotation_first_man_stint_end_grace_seconds,s=new Array(e.length).fill(0);let a=0;const r=new Map,o=Lb(),l=Lb();return{applyFrame(c){for(let u=0;uc.frame_number)break;const h=Pz(d,c),f=h-s[u];if(f>0){s[u]=h;const p=c.frame_number>=d.end_frame?d.end_time:Math.min(c.time,d.end_time);Rz(i_(r,d.player),d,f,p,i)}}for(;a({event:e,index:t})).sort((e,t)=>e.event.start_frame!==t.event.start_frame?e.event.start_frame-t.event.start_frame:e.event.start_time!==t.event.start_time?e.event.start_time-t.event.start_time:e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.index-t.index).map(({event:e})=>e)}function Oz(n,e){n.count+=1,e.attackers===2&&e.defenders===1?n.two_v_one_count+=1:e.attackers===2&&e.defenders===2?n.two_v_two_count+=1:e.attackers===2&&e.defenders===3?n.two_v_three_count+=1:e.attackers===3&&e.defenders===1?n.three_v_one_count+=1:e.attackers===3&&e.defenders===2?n.three_v_two_count+=1:e.attackers===3&&e.defenders===3&&(n.three_v_three_count+=1)}function Fb(n,e){Object.assign(n,e)}function Fz(n){const e=GM(n);for(const t of n.frames)e.applyFrame(t);return n}function GM(n){const e=kz(ve(n,"rush"));let t=0;const i=Ob(),s=Ob(),a=n.config.rush_min_possession_retained_seconds;return{applyFrame(r){for(;t=e[t].start_frame&&r.time-e[t].start_time>=a;){const o=e[t];Oz(o.is_team_0?i:s,o),t+=1}Fb(r.team_zero.rush,i),Fb(r.team_one.rush,s)}}}const Nz=["control","hard_hit","medium_hit"],Uz=["ground","high_air","low_air"],Bz=["air","ground","wall"],zz=["dodge","no_dodge"];function lo(n){return Math.fround(n)}function Zu(n,e){return lo(lo(n)+lo(e))}function $M(n,e){return lo(lo(n)-lo(e))}function $p(n){if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function Hz(){return{entries:zz.flatMap(n=>Uz.flatMap(e=>Nz.flatMap(t=>Bz.map(i=>({labels:[{key:"dodge_state",value:n},{key:"height_band",value:e},{key:"kind",value:t},{key:"surface",value:i}],count:0}))))).sort((n,e)=>JSON.stringify(n.labels).localeCompare(JSON.stringify(e.labels)))}}function WM(){return{touch_count:0,control_touch_count:0,medium_hit_count:0,hard_hit_count:0,aerial_touch_count:0,high_aerial_touch_count:0,wall_touch_count:0,first_touch_count:0,is_last_touch:!1,last_touch_time:null,last_touch_frame:null,time_since_last_touch:null,frames_since_last_touch:null,last_ball_speed_change:null,max_ball_speed_change:0,cumulative_ball_speed_change:0,total_ball_travel_distance:0,total_ball_advance_distance:0,total_ball_retreat_distance:0,labeled_touch_counts:Hz()}}const Vz=WM();function Nb(){return{stats:WM(),labeledCountsVersion:0,labeledCountsSnapshot:void 0,labeledCountsSnapshotVersion:-1}}function Gz(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function $z(n,e){e.sort((s,a)=>s.key===a.key?s.value.localeCompare(a.value):s.key.localeCompare(a.key));const t=n.labeled_touch_counts?.entries??[];n.labeled_touch_counts={entries:t};const i=t.find(s=>s.labels.length===e.length&&s.labels.every((a,r)=>a.key===e[r]?.key&&a.value===e[r]?.value));i?i.count+=1:(t.push({labels:e,count:1}),t.sort((s,a)=>JSON.stringify(s.labels).localeCompare(JSON.stringify(a.labels))))}function Wz(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function Iu(n,e){return n.tags?.find(t=>t.group===e)?.value??null}function Xz(n,e,t){const i=Iu(e,"kind")??"control",s=Iu(e,"height_band")??"ground",a=Iu(e,"surface")??"ground",r=Iu(e,"dodge_state")??"no_dodge",o=n.stats;o.touch_count+=1,i==="control"?o.control_touch_count+=1:i==="medium_hit"?o.medium_hit_count+=1:i==="hard_hit"&&(o.hard_hit_count+=1),s==="low_air"?o.aerial_touch_count+=1:s==="high_air"&&(o.aerial_touch_count+=1,o.high_aerial_touch_count+=1),a==="wall"&&(o.wall_touch_count+=1),$z(o,[{key:"kind",value:i},{key:"height_band",value:s},{key:"surface",value:a},{key:"dodge_state",value:r}]),n.labeledCountsVersion+=1,o.last_touch_time=e.time,o.last_touch_frame=e.frame,o.time_since_last_touch=Math.max(0,$M(t.time,e.time)),o.frames_since_last_touch=Math.max(0,t.frame_number-e.frame),o.last_ball_speed_change=e.ball_speed_change,o.max_ball_speed_change=Math.max(o.max_ball_speed_change,e.ball_speed_change),o.cumulative_ball_speed_change=Zu(o.cumulative_ball_speed_change,e.ball_speed_change)}function Kz(n){return n.labeledCountsSnapshotVersion!==n.labeledCountsVersion&&(n.labeledCountsSnapshot=n.stats.labeled_touch_counts?Wz(n.stats.labeled_touch_counts):void 0,n.labeledCountsSnapshotVersion=n.labeledCountsVersion),n.labeledCountsSnapshot}function qz(n,e){if(!e){Object.assign(n,Vz);return}Object.assign(n,e.stats,{labeled_touch_counts:Kz(e)})}function Yz(n){const e=XM(n);for(const t of n.frames)e.applyFrame(t);return n}function XM(n){const e=Gz(ve(n,"touch")),t=e.flatMap(o=>o.ball_movement?[{player:o.player,movement:o.ball_movement}]:[]).sort((o,l)=>o.movement.end_frame!==l.movement.end_frame?o.movement.end_frame-l.movement.end_frame:o.movement.end_time-l.movement.end_time);let i=0,s=0,a=null;const r=new Map;return{applyFrame(o){if(!o.is_live_play)a=null;else{for(const l of r.values()){const c=l.stats;c.is_last_touch=!1,c.last_touch_time!=null&&(c.time_since_last_touch=Math.max(0,$M(o.time,c.last_touch_time))),c.last_touch_frame!=null&&(c.frames_since_last_touch=Math.max(0,o.frame_number-c.last_touch_frame))}for(;i({event:e,index:t})).sort((e,t)=>e.event.resolved_frame!==t.event.resolved_frame?e.event.resolved_frame-t.event.resolved_frame:e.event.resolved_time!==t.event.resolved_time?e.event.resolved_time-t.event.resolved_time:e.index-t.index).map(({event:e})=>e)}function Jz(n,e,t){n.is_last_whiff=!1,n.time_since_last_whiff=n.last_whiff_time==null?null:Math.max(0,t-n.last_whiff_time),n.frames_since_last_whiff=n.last_whiff_frame==null?null:Math.max(0,e-n.last_whiff_frame)}function Qz(n,e,t,i){if((e.kind??"whiff")==="beaten_to_ball"){n.beaten_to_ball_count+=1;return}n.whiff_count+=1,e.aerial?n.aerial_whiff_count+=1:n.grounded_whiff_count+=1,e.dodge_active&&(n.dodge_whiff_count+=1),n.is_last_whiff=!0,n.last_whiff_time=e.time,n.last_whiff_frame=e.frame,n.time_since_last_whiff=Math.max(0,i-e.time),n.frames_since_last_whiff=Math.max(0,t-e.frame),n.last_closest_approach_distance=e.closest_approach_distance,n.best_closest_approach_distance=n.best_closest_approach_distance==null?e.closest_approach_distance:Math.min(n.best_closest_approach_distance,e.closest_approach_distance),n.cumulative_closest_approach_distance+=e.closest_approach_distance}function Ub(n,e){Object.assign(n,e??s_())}function eH(n){const e=KM(n);for(const t of n.frames)e.applyFrame(t);return n}function KM(n){const e=Zz(ve(n,"whiff"));let t=0,i=null;const s=new Map,a=new Map;return{applyFrame(r){if(r.is_live_play){for(const o of s.values())Jz(o,r.frame_number,r.time);for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function iH(n,e,t,i){n.is_last_wall_aerial=i,n.time_since_last_wall_aerial=n.last_wall_aerial_time==null?null:Math.max(0,qM(t,n.last_wall_aerial_time)),n.frames_since_last_wall_aerial=n.last_wall_aerial_frame==null?null:Math.max(0,e-n.last_wall_aerial_frame)}function sH(n,e,t,i){n.count+=1,e.confidence>=tH&&(n.high_confidence_count+=1),n.is_last_wall_aerial=!0,n.last_wall_aerial_time=e.time,n.last_wall_aerial_frame=e.frame,n.time_since_last_wall_aerial=Math.max(0,qM(i,e.time)),n.frames_since_last_wall_aerial=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=Lu(n.cumulative_confidence,e.confidence),n.cumulative_setup_duration=Lu(n.cumulative_setup_duration,e.setup_duration),n.cumulative_takeoff_to_touch_time=Lu(n.cumulative_takeoff_to_touch_time,e.time_since_takeoff),n.cumulative_touch_height=Lu(n.cumulative_touch_height,e.player_position[2]??0)}function aH(n,e){Object.assign(n,e??YM())}function rH(n){const e=jM(n);for(const t of n.frames)e.applyFrame(t);return n}function jM(n){const e=nH(ve(n,"wall_aerial"));let t=0,i=null;const s=new Map;return{applyFrame(a){for(const[r,o]of s)iH(o,a.frame_number,a.time,a.is_live_play&&r===i);if(!a.is_live_play)i=null;else{for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function cH(n,e,t,i){n.is_last_wall_aerial_shot=i,n.time_since_last_wall_aerial_shot=n.last_wall_aerial_shot_time==null?null:Math.max(0,ZM(t,n.last_wall_aerial_shot_time)),n.frames_since_last_wall_aerial_shot=n.last_wall_aerial_shot_frame==null?null:Math.max(0,e-n.last_wall_aerial_shot_frame)}function uH(n,e,t,i){n.count+=1,e.confidence>=oH&&(n.high_confidence_count+=1),n.is_last_wall_aerial_shot=!0,n.last_wall_aerial_shot_time=e.time,n.last_wall_aerial_shot_frame=e.frame,n.time_since_last_wall_aerial_shot=Math.max(0,ZM(i,e.time)),n.frames_since_last_wall_aerial_shot=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=Xp(n.cumulative_confidence,e.confidence),n.cumulative_takeoff_to_shot_time=Xp(n.cumulative_takeoff_to_shot_time,e.time_since_takeoff),n.cumulative_shot_height=Xp(n.cumulative_shot_height,e.player_position[2]??0)}function dH(n,e){Object.assign(n,e??JM())}function hH(n){const e=QM(n);for(const t of n.frames)e.applyFrame(t);return n}function QM(n){const e=lH(ve(n,"wall_aerial_shot"));let t=0,i=null;const s=new Map;return{applyFrame(a){for(const[r,o]of s)cH(o,a.frame_number,a.time,a.is_live_play&&r===i);if(!a.is_live_play)i=null;else{let r=!1;for(;t[f.frame_number,p])),a=new Map,r={...n,frames:[]},o=_H.flatMap(f=>f.createFrameAccumulator?[f.createFrameAccumulator(r)]:[]),l=Math.max(1,t.materializationChunkSize??fH),c=Math.max(l,t.maxMaterializationChunkSize??pH);let u=-1,d=l;const h=f=>{if(f<=u)return;const p=Math.min(i.length-1,Math.max(f,u+d));for(let g=u+1;g<=p;g+=1){const _=i[g],m=_?bH(vH(_)):void 0;if(m){for(const v of o)v.applyFrame(m);a.set(m.frame_number,m)}}u=p,d=Math.min(c,i.length,d*mH)};return{get(f){const p=s.get(f);if(p!==void 0)return h(p),a.get(f)}}}function yH(n){return!n||typeof n!="object"?n:{...n}}function vH(n){return{...n,team_zero:{...n.team_zero},team_one:{...n.team_one},players:n.players.map(e=>({...e,player_id:yH(e.player_id)}))}}function bH(n){return{...n,team_zero:Yl(n.team_zero??{}),team_one:Yl(n.team_one??{}),players:n.players.map(t=>eE(t))}}function jl(n){return n.events?.events??[]}function ve(n,e){return jl(n).filter(t=>t.payload.kind===e).map(t=>t.payload.payload)}const xH=new Set(["is_team_0","name","player_id"]);function Hb(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0}function wH(n){return!n||typeof n!="object"||Array.isArray(n)?!1:Object.keys(n).every(e=>xH.has(e))}function SH(n){return Hb(n.team_zero)&&Hb(n.team_one)&&n.players.every(e=>wH(e))}function TH(n){return new Map(BT(n).frames.map(e=>[e.frame_number,e]))}function MH(n,e,t){const i=n.frames.filter(s=>SH(s)).length;if(i===n.frames.length)return gH(n,e,t);if(i>0)throw new Error("stats timeline frames must be either all compact scaffolds or all materialized snapshots");return TH(n)}function zt(n,e){return n.get(e)??null}const Ng=[{stage:"validating",index:1,total:9,label:"Parse replay",start:0,end:.08},{stage:"processing",index:2,total:9,label:"Process replay frames",start:.08,end:.62},{stage:"building-stats",index:3,total:9,label:"Build stats events",start:.62,end:.7},{stage:"serializing-replay",index:4,total:9,label:"Serialize replay data",start:.7,end:.76},{stage:"serializing-stats",index:5,total:9,label:"Serialize stats timeline",start:.76,end:.86},{stage:"normalizing",index:6,total:9,label:"Normalize replay model",start:.86,end:.91},{stage:"decoding-replay",index:7,total:9,label:"Decode replay data",start:.91,end:.94},{stage:"decoding-stats",index:8,total:9,label:"Decode stats chunks",start:.94,end:.96},{stage:"deriving-stats",index:9,total:9,label:"Derive stats snapshots",start:.96,end:1}];function tE(n){return Math.max(0,Math.min(1,n))}function Kp(n,e,t){if(n!==void 0)return tE((n-e)/(t-e))}function Ug(n){if(n.stage!=="stats-timeline")return n;const e=n.progress;return e===void 0?{...n,stage:"building-stats"}:e<.35?{...n,stage:"building-stats",progress:Kp(e,0,.35)}:e<.55?{...n,stage:"serializing-replay",progress:Kp(e,.35,.55)}:{...n,stage:"serializing-stats",progress:Kp(e,.55,.92)}}function nE(n){const e=Ug(n);return Ng.find(t=>t.stage===e.stage)}function EH(){return Ng.map(({stage:n,index:e,total:t,label:i})=>({stage:n,index:e,total:t,label:i}))}function CH(n){const e=nE(n);return{stage:e.stage,index:e.index,total:e.total,label:e.label}}function AH(n){const e=Ug(n),t=nE(e);return Ng.map(({stage:i,index:s,total:a,label:r})=>{if(st.index)return{stage:i,index:s,total:a,label:r,state:"pending",completion:0,indeterminate:!1};const o=e.progress!==void 0;return{stage:i,index:s,total:a,label:r,state:"active",completion:o?tE(e.progress??0):1,indeterminate:!o}})}function tf(n){const e=Ug(n),t=e.progress===void 0?null:Math.round(e.progress*100);switch(e.stage){case"validating":return"Parsing replay...";case"processing":return t!==null&&e.totalFrames!==void 0?`Processing replay frames... ${t}% (${e.processedFrames??0}/${e.totalFrames})`:"Processing replay frames...";case"building-stats":return t!==null?e.totalFrames!==void 0?`Building stats events... ${t}% (${e.processedFrames??0}/${e.totalFrames})`:`Building stats events... ${t}%`:"Building stats events...";case"serializing-replay":return t!==null?`Serializing replay data... ${t}%`:"Serializing replay data...";case"serializing-stats":return t!==null?`Serializing stats timeline... ${t}%`:"Serializing stats timeline...";case"decoding-replay":return t!==null?`Decoding replay data... ${t}%`:"Decoding replay data...";case"decoding-stats":return t!==null?e.totalChunks!==void 0?`Decoding stats chunks... ${t}% (${e.processedChunks??0}/${e.totalChunks})`:`Decoding stats chunks... ${t}%`:"Decoding stats chunks...";case"deriving-stats":return t!==null?`Deriving stats snapshots... ${t}%`:"Deriving stats snapshots...";case"normalizing":return t!==null?`Normalizing replay model... ${t}%`:"Normalizing replay model...";default:return"Loading replay..."}}function RH(n){return n instanceof Error?n:new Error(String(n))}function Rs(n,e){return JSON.parse(n.decode(new Uint8Array(e)))}async function PH(n,e,t){t?.({stage:"decoding-stats",progress:0});const i=Rs(n,e.configBuffer);t?.({stage:"decoding-stats",progress:.05}),await Za();const s=Rs(n,e.replayMetaBuffer);t?.({stage:"decoding-stats",progress:.1}),await Za();const a=Rs(n,e.eventsBuffer),r=Rs(n,e.activitySummaryBuffer),o=Rs(n,e.positioningSummaryBuffer),l=Rs(n,e.accumulationTracksBuffer);t?.({stage:"decoding-stats",progress:.15}),await Za();const c=[],u=e.frameChunkBuffers.length;for(let d=0;d{let t=!1,i=null;const s=()=>{t||(t=!0,i!==null&&clearTimeout(i),e())};i=setTimeout(s,n),requestAnimationFrame(()=>s())})}async function iE(n,e={}){if(typeof Worker>"u")throw new Error("Replay loading worker is not available in this environment");const t=new Worker(new URL(""+new URL("replayLoader.worker-D3pjMe81.js",import.meta.url).href,import.meta.url),{type:"module"}),i=n.slice(),s=e.reportEveryNFrames??100;return new Promise((a,r)=>{const o=()=>{t.terminate()};t.onmessage=async c=>{const u=c.data;if(u.type==="progress"){e.onProgress?.(u.progress);return}if(u.type==="error"){o(),r(new Error(u.error));return}o();try{const d=new TextDecoder;e.onProgress?.({stage:"decoding-replay",progress:0}),await Za();const h=Rs(d,u.replayBuffer);e.onProgress?.({stage:"decoding-replay",progress:.5}),await Za();const f=Rs(d,u.rawReplayBuffer);e.onProgress?.({stage:"decoding-replay",progress:1}),await Za();const p=await PH(d,u.statsTimelineParts,e.onProgress),g=MH(p);a({replay:h,raw:f,statsTimeline:p,statsFrameLookup:g})}catch(d){r(RH(d))}},t.onerror=c=>{o(),r(new Error(c.message||"Replay loading worker failed"))};const l={type:"load-replay",bytes:i.buffer,reportEveryNFrames:s};t.postMessage(l,[i.buffer])})}function IH(n){const e=document.createElement("div");e.className="replay-load-modal",e.hidden=!0;const t=document.createElement("div");t.className="replay-load-modal__dialog",t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-labelledby","replay-load-modal-title");const i=document.createElement("p");i.className="replay-load-modal__eyebrow",i.textContent="Replay loading";const s=document.createElement("h2");s.id="replay-load-modal-title",s.className="replay-load-modal__title",s.textContent="Preparing replay pipeline";const a=document.createElement("p");a.className="replay-load-modal__status",a.textContent="Preparing replay...";const r=document.createElement("div");r.className="replay-load-modal__phase-list";const o=new Map;for(const f of EH()){const p=document.createElement("div");p.className="replay-load-modal__phase-row",p.dataset.state="pending";const g=document.createElement("p");g.className="replay-load-modal__phase-label",g.textContent=`${f.index}. ${f.label}`;const _=document.createElement("div");_.className="replay-load-modal__phase-bar";const m=document.createElement("div");m.className="replay-load-modal__phase-fill",m.dataset.indeterminate="false",_.append(m),p.append(g,_),r.append(p),o.set(f.stage,{row:p,fill:m})}const l=document.createElement("p");l.className="replay-load-modal__meta",t.append(i,s,a,r,l),e.append(t),n.append(e);let c="";const u=()=>{for(const{row:f,fill:p}of o.values())f.dataset.state="pending",p.style.width="0%",p.dataset.indeterminate="false"},d=f=>{for(const p of AH(f)){const g=o.get(p.stage);g&&(g.row.dataset.state=p.state,g.fill.dataset.indeterminate=p.indeterminate?"true":"false",g.fill.style.width=`${Math.round(p.completion*100)}%`)}},h=f=>{e.hidden=!f};return{show(f,p="Preparing replay..."){c=f,h(!0),u(),s.textContent="Preparing replay pipeline",a.textContent=p,l.textContent=`Loading ${f}`},update(f){h(!0);const p=CH(f);if(d(f),s.textContent=`Phase ${p.index} of ${p.total}: ${p.label}`,a.textContent=tf(f),f.stage==="processing"&&f.totalFrames!==void 0){l.textContent=`${f.processedFrames??0}/${f.totalFrames} frames`;return}if(f.stage==="decoding-stats"&&f.totalChunks!==void 0){l.textContent=`${f.processedChunks??0}/${f.totalChunks} chunks`;return}l.textContent=c?`Loading ${c}`:""},hide(){h(!1)},destroy(){e.remove()}}}const LH=["free","follow"];function sE(n){return n.useReplayBallCam??!1?"player":n.ballCamEnabled?"on":"off"}function Vb(n){return n.useReplayBallCam?"player":n.ballCam===!0?"on":n.ballCam===!1?"off":"player"}const aE={fov:110,height:100,pitch:-4,distance:270,stiffness:0,swivelSpeed:1,transitionSpeed:1};class Bg{constructor(e){this.options=e}lastFreeCameraPreset=null;get freeCameraPreset(){return this.lastFreeCameraPreset}set freeCameraPreset(e){this.lastFreeCameraPreset=e}ballCamModeValue="player";get ballCamMode(){return this.ballCamModeValue}autoPossessionEnabledValue=!1;get autoPossessionEnabled(){return this.autoPossessionEnabledValue}static ballCamEnabledForMode(e){return e==="player"?null:e==="on"}followPlayerWithReplayCamera(e,t={}){const i=this.options.getReplayPlayer();i&&(t.preserveAutoPossession||this.setAutoPossessionEnabled(!1,{requestConfigSync:!1}),i.setAttachedPlayer(e),i.setCameraViewMode("follow"),t.usePlayerCameraSettings!==!1&&i.setCustomCameraSettings(null),this.setBallCamMode(t.ballCam??"player"),this.lastFreeCameraPreset=null,t.requestConfigSync!==!1&&this.options.requestConfigSync())}setAutoPossessionEnabled(e,t={}){if(this.autoPossessionEnabledValue===e){this.renderAutoPossessionButton();return}this.autoPossessionEnabledValue=e,this.renderAutoPossessionButton(),t.notify!==!1&&this.options.onAutoPossessionChange?.(e),t.requestConfigSync!==!1&&this.options.requestConfigSync()}renderBallCamButtons(){const{ballCamOffButton:e,ballCamOnButton:t,ballCamPlayerButton:i}=this.options.elements,s=[["off",e],["on",t],["player",i]];for(const[a,r]of s){const o=a===this.ballCamModeValue;r.dataset.active=o?"true":"false",r.setAttribute("aria-pressed",o?"true":"false")}}renderAutoPossessionButton(){this.options.elements.cameraViewAutoPossession.checked=this.autoPossessionEnabledValue}disableAutoPossessionForManualCameraControl(){this.setAutoPossessionEnabled(!1,{requestConfigSync:!1})}setBallCamMode(e){this.ballCamModeValue=e,this.options.getReplayPlayer()?.setBallCamEnabled(Bg.ballCamEnabledForMode(e)),this.renderBallCamButtons()}get nameplateLiftUu(){const e=Number(this.options.elements.nameplateLift.value);return Number.isFinite(e)?e:Um}applyNameplateLiftUu(e){const{nameplateLift:t,nameplateLiftReadout:i}=this.options.elements,s=e??Um;t.value=`${s}`,i.textContent=qn(s,"",0)}installEventListeners(e){const{elements:t}=this.options;t.usePlayerCameraSettings.addEventListener("change",()=>{const s=t.usePlayerCameraSettings.checked;t.cameraSettingsControls.hidden=s,this.options.getReplayPlayer()?.setCustomCameraSettings(s?null:this.readCustomCameraSettings()),this.options.requestConfigSync()},{signal:e});for(const s of[t.customCameraFov,t.customCameraHeight,t.customCameraPitch,t.customCameraDistance,t.customCameraStiffness,t.customCameraSwivelSpeed,t.customCameraTransitionSpeed])s.addEventListener("input",()=>{const a=this.readCustomCameraSettings();this.syncCustomCameraSettingControls(a),this.options.getReplayPlayer()?.setCustomCameraSettings(a),this.options.requestConfigSync()},{signal:e});t.attachedPlayer.addEventListener("change",()=>{const s=this.options.getReplayPlayer(),a=t.attachedPlayer.value||null;this.disableAutoPossessionForManualCameraControl(),s?.setAttachedPlayer(a),a&&(s?.setCustomCameraSettings(null),this.setBallCamMode("player")),this.lastFreeCameraPreset=null,this.options.requestConfigSync()},{signal:e}),t.cameraViewFreeButton.addEventListener("click",()=>{this.options.getReplayPlayer()?.setCameraViewMode("free"),this.disableAutoPossessionForManualCameraControl(),this.lastFreeCameraPreset=null,this.options.requestConfigSync()},{signal:e}),t.cameraViewFollowButton.addEventListener("click",()=>{const s=this.options.getReplayPlayer();this.disableAutoPossessionForManualCameraControl(),s?.setCameraViewMode("follow"),s?.getState().attachedPlayerId&&(s.setCustomCameraSettings(null),this.setBallCamMode("player")),this.lastFreeCameraPreset=null,this.options.requestConfigSync()},{signal:e}),t.cameraViewOverheadButton.addEventListener("click",()=>{this.options.getReplayPlayer()?.setFreeCameraPreset("overhead"),this.disableAutoPossessionForManualCameraControl(),this.lastFreeCameraPreset="overhead",this.options.requestConfigSync()},{signal:e}),t.cameraViewSideButton.addEventListener("click",()=>{this.options.getReplayPlayer()?.setFreeCameraPreset("side"),this.disableAutoPossessionForManualCameraControl(),this.lastFreeCameraPreset="side",this.options.requestConfigSync()},{signal:e});const i=[["off",t.ballCamOffButton],["on",t.ballCamOnButton],["player",t.ballCamPlayerButton]];for(const[s,a]of i)a.addEventListener("click",()=>{this.setBallCamMode(s),this.options.requestConfigSync()},{signal:e});t.cameraViewAutoPossession.addEventListener("change",()=>{this.setAutoPossessionEnabled(t.cameraViewAutoPossession.checked)},{signal:e}),t.nameplateLift.addEventListener("input",()=>{t.nameplateLiftReadout.textContent=qn(this.nameplateLiftUu,"",0),this.options.requestConfigSync()},{signal:e})}setTransportEnabled(e,t){this.options.elements.attachedPlayer.disabled=!e,this.syncModeButtons(e?t:void 0)}syncState(e){const{elements:t}=this.options;t.usePlayerCameraSettings.checked=e.customCameraSettings===null,t.cameraSettingsControls.hidden=t.usePlayerCameraSettings.checked,this.syncCustomCameraSettingControls(e.customCameraSettings??this.getFallbackCameraSettings()),this.ballCamModeValue=sE(e),this.renderBallCamButtons(),t.attachedPlayer.value=e.attachedPlayerId??"",this.syncAvailability(e),this.renderProfile(e)}syncAvailability(e){this.syncModeButtons(e);const i=this.options.getReplayPlayer()!==null&&e?.cameraViewMode==="follow"&&(e.attachedPlayerId??null)!==null;this.options.elements.usePlayerCameraSettings.disabled=!i,this.setCameraSettingControlsEnabled(i&&e?.customCameraSettings!==null),this.options.elements.ballCamOffButton.disabled=!i,this.options.elements.ballCamOnButton.disabled=!i,this.options.elements.ballCamPlayerButton.disabled=!i,this.renderBallCamButtons()}syncModeButtons(e){const t=e?.cameraViewMode??"free",i=this.options.getReplayPlayer()!==null&&e!==void 0,s=(e?.attachedPlayerId??null)!==null;for(const l of LH){const c=this.getCameraViewButton(l);c.disabled=!i||l==="follow"&&!s;const u=l===t;c.dataset.active=u?"true":"false",c.setAttribute("aria-pressed",u?"true":"false")}const{cameraViewOverheadButton:a,cameraViewSideButton:r}=this.options.elements,{cameraViewAutoPossession:o}=this.options.elements;a.disabled=!i,r.disabled=!i,o.disabled=!i,a.dataset.active="false",r.dataset.active="false",this.renderAutoPossessionButton(),a.setAttribute("aria-pressed","false"),r.setAttribute("aria-pressed","false")}populateAttachedPlayerOptions(e){const{attachedPlayer:t}=this.options.elements;t.replaceChildren(),t.append(new Option("Free camera",""));for(const i of e)t.append(new Option(`${i.name} (${i.isTeamZero?"Blue":"Orange"})`,i.id))}renderProfile(e){const t=this.options.elements,i=this.options.getReplayPlayer(),s=e?.attachedPlayerId??null;if(!i||e?.cameraViewMode!=="follow"||s===null){this.renderEmptyProfile("Free camera");return}const a=i.replay.players.find(o=>o.id===s);if(!a){this.renderEmptyProfile("Unknown");return}const r=this.getEffectiveCameraSettings(e);t.cameraProfileReadout.textContent=e.customCameraSettings===null?a.name:`${a.name} custom`,t.cameraFovReadout.textContent=qn(r.fov,"",0),t.cameraHeightReadout.textContent=qn(r.height,"",0),t.cameraPitchReadout.textContent=qn(r.pitch,"",0),t.cameraBaseDistanceReadout.textContent=qn(r.distance,"",0),t.cameraStiffnessReadout.textContent=qn(r.stiffness,"",2)}getFallbackCameraSettings(){return aE}getAttachedPlayerCameraSettings(e){const t=this.options.getReplayPlayer();return!t||e===null?null:t.replay.players.find(i=>i.id===e)?.cameraSettings??null}getEffectiveCameraSettings(e){return{...this.getFallbackCameraSettings(),...this.getAttachedPlayerCameraSettings(e.attachedPlayerId)??{},...e.customCameraSettings??{}}}readCustomCameraSettings(){const e=this.options.elements;return{fov:Number(e.customCameraFov.value),height:Number(e.customCameraHeight.value),pitch:Number(e.customCameraPitch.value),distance:Number(e.customCameraDistance.value),stiffness:Number(e.customCameraStiffness.value),swivelSpeed:Number(e.customCameraSwivelSpeed.value),transitionSpeed:Number(e.customCameraTransitionSpeed.value)}}setCameraSettingControlsEnabled(e){const t=this.options.elements;t.cameraSettingsControls.hidden=t.usePlayerCameraSettings.checked,t.customCameraFov.disabled=!e,t.customCameraHeight.disabled=!e,t.customCameraPitch.disabled=!e,t.customCameraDistance.disabled=!e,t.customCameraStiffness.disabled=!e,t.customCameraSwivelSpeed.disabled=!e,t.customCameraTransitionSpeed.disabled=!e}syncCustomCameraSettingControls(e){const t=this.options.elements,i=this.getFallbackCameraSettings(),s=e.fov??i.fov,a=e.height??i.height,r=e.pitch??i.pitch,o=e.distance??i.distance,l=e.stiffness??i.stiffness,c=e.swivelSpeed??i.swivelSpeed,u=e.transitionSpeed??i.transitionSpeed;t.customCameraFov.value=`${s}`,t.customCameraHeight.value=`${a}`,t.customCameraPitch.value=`${r}`,t.customCameraDistance.value=`${o}`,t.customCameraStiffness.value=`${l}`,t.customCameraSwivelSpeed.value=`${c}`,t.customCameraTransitionSpeed.value=`${u}`,t.customCameraFovReadout.textContent=qn(s,"",0),t.customCameraHeightReadout.textContent=qn(a,"",0),t.customCameraPitchReadout.textContent=qn(r,"",0),t.customCameraDistanceReadout.textContent=qn(o,"",0),t.customCameraStiffnessReadout.textContent=qn(l,"",2),t.customCameraSwivelSpeedReadout.textContent=qn(c,"",1),t.customCameraTransitionSpeedReadout.textContent=qn(u,"",2)}getCameraViewButton(e){switch(e){case"free":return this.options.elements.cameraViewFreeButton;case"follow":return this.options.elements.cameraViewFollowButton}}renderEmptyProfile(e){const t=this.options.elements;t.cameraProfileReadout.textContent=e,t.cameraFovReadout.textContent="--",t.cameraHeightReadout.textContent="--",t.cameraPitchReadout.textContent="--",t.cameraBaseDistanceReadout.textContent="--",t.cameraStiffnessReadout.textContent="--"}}function qn(n,e="",t=0){return n===void 0||Number.isNaN(n)?"--":`${n.toFixed(t)}${e}`}function DH(n){return new Bg(n)}const Gb="subtr-actor-touch-overlay-styles",zg=5882879,Hg=16761180,$b=120,Wb=4,kH=196,qp=24,Xb=210,Kb=5,OH=.1,FH=48,NH=["team","intention","kind","height_band","surface","dodge_state","flag"],UH=[{label:"Blue team",color:zg},{label:"Orange team",color:Hg}],rE=[{label:"Shot",color:16711880},{label:"Save",color:58998},{label:"Clear",color:16764928},{label:"Boom",color:16020150},{label:"Pass",color:47103},{label:"Control",color:0},{label:"Advance",color:16486972}],Ju=[{label:"Control",color:0},{label:"Medium hit",color:16436245},{label:"Hard hit",color:16735596}],Qu=[{label:"Ground",color:10741301},{label:"Low air",color:3718648},{label:"High air",color:8490232}],oE=[{label:"Ground",color:8702998},{label:"Air",color:6333946},{label:"Wall",color:16347926}],a_=[{label:"No dodge",color:9741240},{label:"Dodge",color:15235577}],r_=[{label:"First touch",color:16777215},{label:"Contested",color:15680580}],BH=[{title:"Team",entries:UH},{title:"Intention",entries:rE},{title:"Hit strength",entries:Ju},{title:"Height",entries:Qu},{title:"Surface",entries:oE},{title:"Dodge",entries:a_},{title:"Flags",entries:r_}];function fc(n){return Object.fromEntries(n.map(e=>[e.label.toLowerCase().replaceAll(" ","_"),e.color]))}const lE=fc(rE),cE={...fc(Ju),medium_hit:Ju[1].color,hard_hit:Ju[2].color},uE={...fc(Qu),low_air:Qu[1].color,high_air:Qu[2].color},dE=fc(oE),hE={...fc(a_),no_dodge:a_[0].color},o_={first_touch:r_[0].color,contested:r_[1].color},Vi=10134961;function jn(n,e){const t=n.tags;if(!Array.isArray(t))return null;const i=t.find(s=>s.group===e);return i?i.value:null}function fE(n){return jn(n,"possession")??jn(n,"action")}function At(n){const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function Yp(n,e){return Math.max(0,n-e)}function ed(n){return n==="team"||n==="intention"||n==="kind"||n==="height_band"||n==="surface"||n==="dodge_state"||n==="flag"}function ho(n){const e=Array.isArray(n)?n:n?[n]:["team"],t=new Set,i=[];for(const s of e)ed(s)&&!t.has(s)&&(t.add(s),i.push(s));return i.length>0?i:["team"]}function pE(n){return n[n.length-1]??"team"}function zH(n,e,t){const i=HH(n,pE(t)),s=i?` · ${i.replaceAll("_"," ")}`:"";if(e==="markers")return`${n.playerName}${s}`;const a=Math.round(n.totalBallAdvanceDistance),r=Math.round(n.totalBallRetreatDistance);return a>0&&r>0?`${n.playerName} +${a} / -${r} uu${s}`:r>0?`${n.playerName} -${r} uu${s}`:`${n.playerName} +${a} uu${s}`}function HH(n,e){return e==="intention"?n.intention:e==="kind"?n.kind:e==="height_band"?n.heightBand:e==="surface"?n.surface:e==="dodge_state"?n.dodgeState:e==="flag"?n.contested?"contested":n.firstTouch?"first_touch":null:null}function VH(n){return n.split("_").filter(Boolean).map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1)}`).join(" ")}function sl(n,e,t){return typeof e!="string"||e.length===0?null:{key:n,value:e,label:VH(e),color:t[e]??Vi}}function qb(n,e,t){return e!==!0?null:{key:n,value:"true",label:t,color:o_[n]??Vi}}function GH(n){const e=jn(n,"reception")==="first_touch",t=jn(n,"contested")!=null;return[sl("intention",fE(n),lE),sl("kind",jn(n,"kind"),cE),sl("height_band",jn(n,"height_band"),uE),sl("surface",jn(n,"surface"),dE),sl("dodge_state",jn(n,"dodge_state"),hE),qb("first_touch",e,"First touch"),qb("contested",t,"Contested")].filter(i=>i!=null)}function mE(n,e){return e==="intention"?lE[n.intention??""]??Vi:e==="kind"?cE[n.kind??""]??Vi:e==="height_band"?uE[n.heightBand??""]??Vi:e==="surface"?dE[n.surface??""]??Vi:e==="dodge_state"?hE[n.dodgeState??""]??Vi:e==="flag"?n.contested?o_.contested??Vi:n.firstTouch?o_.first_touch??Vi:Vi:n.isTeamZero?zg:Hg}function $H(n,e){return(e.length>0?e:["team"]).map(i=>mE(n,i))}function _E(n,e){const t=[],i=[...ve(n,"touch")].sort((s,a)=>s.frame!==a.frame?s.frame-a.frame:s.time!==a.time?s.time-a.time:0);for(const s of i){const a=At(s.player),r=e.ballFrames[s.frame]?.position;if(!r)continue;const o=s.ball_movement,c=(o?e.ballFrames[o.end_frame]?.position:null)??r,u=t.length,d=GH(s);t.push({id:`touch-stat:${s.frame}:${a}:${u+1}`,time:e.frames[s.frame]?.time??s.time,frame:s.frame,isTeamZero:s.is_team_0,playerId:a,playerName:e.players.find(h=>h.id===a)?.name??a,kind:jn(s,"kind"),intention:fE(s),heightBand:jn(s,"height_band"),surface:jn(s,"surface"),dodgeState:jn(s,"dodge_state"),firstTouch:jn(s,"reception")==="first_touch",contested:jn(s,"contested")!=null,classifications:d,position:{x:r.x,y:r.y,z:r.z},endPosition:{x:c.x,y:c.y,z:c.z},totalBallTravelDistance:o?Yp(o.travel_distance,0):0,totalBallAdvanceDistance:o?Yp(o.advance_distance,0):0,totalBallRetreatDistance:o?Yp(o.retreat_distance,0):0})}return t}function WH(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function XH(){if(document.getElementById(Gb))return;const n=document.createElement("style");n.id=Gb,n.textContent=` +`}const en="#3b82f6",tn="#f59e0b",G3=new Set(["wavedash"]),$3=new Set(["air_dribble","ball_carry","ceiling_shot","double_tap","flick","flip_reset","half_flip","half_volley","one_timer","speed_flip","wall_aerial","wall_aerial_shot","wavedash"]);function Ai(n){return n.split(/[_-]+/).filter(e=>e.length>0).map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1)}`).join(" ")}function Hv(n){return $3.has(n)&&!G3.has(n)}function of(n){return n===!0?en:n===!1?tn:null}const XT=["timeline","core_player","player_possession","possession","loose_possession","ball_half","ball_third","territorial_pressure","movement","player_activity","field_third","field_half","ball_depth","depth_role","ball_proximity","shadow_defense","rotation_role","first_man_change","goal_context","backboard","ceiling_shot","wall_aerial","wall_aerial_shot","center","flick","flip_reset","dodge_reset","double_tap","fifty_fifty","kickoff","one_timer","pass","ball_carry","controlled_play","rush","dodge","speed_flip","half_flip","half_volley","wavedash","whiff","powerslide","touch","boost_pickups","boost_respawn","bump","demolition"],KT=["air_dribble","ball_carry","ceiling_shot","double_tap","flick","flip_reset","half_flip","half_volley","one_timer","speed_flip","wall_aerial","wall_aerial_shot","wavedash"],Bg=[...new Set([...XT,...KT])],W3=new Set(KT);function ao(){return Object.fromEntries(Bg.map(n=>[n,0]))}function Dp(n){return{...n??ao()}}function Eu(n,e){n[e]+=1}function X3(n){return Bg.includes(n)}function qT(n){if(n==null)return null;if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function Xm(n){return qT(n.meta.primary_player)}function K3(n){return n.meta.team_is_team_0??null}function q3(n){const e=n.meta.stream;return!W3.has(e)||!X3(e)?null:e}function Km(n){const e=n.meta.timing.type==="span"?n.meta.timing.end_frame:n.meta.timing.frame;return typeof e=="number"&&Number.isFinite(e)?e:null}function qm(n){const e=n.meta.timing.type==="span"?n.meta.timing.end_time:n.meta.timing.time;return typeof e=="number"&&Number.isFinite(e)?e:null}function Y3(n,e){const t=Km(n);if(t!==null)return t<=e.frame_number;const i=qm(n);return i!==null&&i<=e.time}function j3(n){return[...n].sort((e,t)=>{const i=Km(e),s=Km(t);if(i!==s)return(i??Number.POSITIVE_INFINITY)-(s??Number.POSITIVE_INFINITY);const a=qm(e),r=qm(t);return a!==r?(a??Number.POSITIVE_INFINITY)-(r??Number.POSITIVE_INFINITY):(Xm(e)??"").localeCompare(Xm(t)??"")})}function YT(n){const e=jT(n);for(const t of n.frames)e.applyFrame(t);return n}function jT(n){const e=Bg.map(s=>({eventType:s,events:j3(ec(n).filter(a=>a.meta.stream===s)),index:0})),t=new Map,i={teamZero:ao(),teamOne:ao()};return{applyFrame(s){for(const a of e)for(;a.index({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function J3(n,e,t,i){n.is_last_backboard=i,n.time_since_last_backboard=n.last_backboard_time==null?null:Math.max(0,t-n.last_backboard_time),n.frames_since_last_backboard=n.last_backboard_frame==null?null:Math.max(0,e-n.last_backboard_frame)}function Q3(n,e,t,i){n.count+=1,n.last_backboard_time=e.time,n.last_backboard_frame=e.frame,n.time_since_last_backboard=Math.max(0,i-e.time),n.frames_since_last_backboard=Math.max(0,t-e.frame)}function eU(n,e){Object.assign(n,e??ZT())}function Gv(n,e){n.count=e}function tU(n){const e=JT(n);for(const t of n.frames)e.applyFrame(t);return n}function JT(n){const e=Z3(ve(n,"backboard"));let t=0,i=0,s=0,a=null;const r=new Map;return{applyFrame(o){for(const[c,u]of r)J3(u,o.frame_number,o.time,c===a);let l=!1;for(;t({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function Ym(n){return`${n.key}\0${n.value}`}function Cu(n){return n.map(Ym).join("")}function QT(n,e){e.sort((s,a)=>Ym(s).localeCompare(Ym(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Cu(s.labels)===Cu(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Cu(s.labels).localeCompare(Cu(a.labels))))}function Wv(n,e){return n.labeled_event_counts?.entries.filter(t=>t.labels.some(i=>i.key==="origin"&&i.value===e)).reduce((t,i)=>t+i.count,0)??0}function eM(n){return n.labeled_event_counts?.entries.reduce((e,t)=>e+t.count,0)??0}function tM(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function Xv(n,e){QT(n,[{key:"kind",value:"carry"}]),n.carry_count=eM(n),n.total_carry_time+=e.duration,n.total_straight_line_distance+=e.straight_line_distance,n.total_path_distance+=e.path_distance,n.longest_carry_time=Math.max(n.longest_carry_time,e.duration),n.furthest_carry_distance=Math.max(n.furthest_carry_distance,e.straight_line_distance),n.fastest_carry_speed=Math.max(n.fastest_carry_speed,e.average_speed),n.carry_speed_sum+=e.average_speed,n.average_horizontal_gap_sum+=e.average_horizontal_gap,n.average_vertical_gap_sum+=e.average_vertical_gap}function Kv(n,e){e.air_dribble_origin!=null&&QT(n,[{key:"origin",value:e.air_dribble_origin}]),n.count=eM(n),n.ground_to_air_count=Wv(n,"ground_to_air"),n.wall_to_air_count=Wv(n,"wall_to_air"),n.total_time+=e.duration,n.total_straight_line_distance+=e.straight_line_distance,n.total_path_distance+=e.path_distance,n.longest_time=Math.max(n.longest_time,e.duration),n.furthest_distance=Math.max(n.furthest_distance,e.straight_line_distance),n.fastest_speed=Math.max(n.fastest_speed,e.average_speed),n.speed_sum+=e.average_speed,n.average_horizontal_gap_sum+=e.average_horizontal_gap,n.average_vertical_gap_sum+=e.average_vertical_gap,n.total_touch_count+=e.touch_count,n.max_touch_count=Math.max(n.max_touch_count,e.touch_count)}function Op(n,e){Object.assign(n,e??Zu()),e?.labeled_event_counts?n.labeled_event_counts=tM(e.labeled_event_counts):delete n.labeled_event_counts}function Fp(n,e){Object.assign(n,e??Ju()),e?.labeled_event_counts?n.labeled_event_counts=tM(e.labeled_event_counts):delete n.labeled_event_counts}function iU(n){const e=nM(n);for(const t of n.frames)e.applyFrame(t);return n}function nM(n){const e=nU(ve(n,"ball_carry"));let t=0;const i=new Map,s=new Map,a=Zu(),r=Zu(),o=Ju(),l=Ju();return{applyFrame(c){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function aU(n,e){n.bumps_inflicted+=1,e.is_team_bump&&(n.team_bumps_inflicted+=1),n.last_bump_time=e.time,n.last_bump_frame=e.frame,n.last_bump_strength=e.strength,n.max_bump_strength=Math.max(n.max_bump_strength,e.strength),n.cumulative_bump_strength+=e.strength}function rU(n,e){n.bumps_taken+=1,e.is_team_bump&&(n.team_bumps_taken+=1)}function oU(n,e){n.bumps_inflicted+=1,e.is_team_bump&&(n.team_bumps_inflicted+=1)}function lU(n,e){Object.assign(n,e??jm())}function Yv(n,e){Object.assign(n,e)}function cU(n){const e=iM(n);for(const t of n.frames)e.applyFrame(t);return n}function iM(n){const e=sU(ve(n,"bump"));let t=0;const i=new Map,s=qv(),a=qv();return{applyFrame(r){for(;t=t&&n0&&(s.overfill_total=sn(s.overfill_total,i),e.field_half==="opponent"&&(s.overfill_from_stolen=sn(s.overfill_from_stolen,i)))}function Jv(n,e){e.boost_granted!=null&&(n.stats.amount_respawned=sn(n.stats.amount_respawned,rn(e.boost_granted)))}class mU{constructor(e){this.points=e}index=0;sample(e){for(;this.index+1e?0:rn(t.value)}}function e_(n,e){return`${n}:${e}`}function _U(n){const e=new Map,t=n.accumulation_tracks;for(const i of t??[]){const s=gl(i.player_id);e.set(e_(s,i.quantity),new mU(i.points))}return e}function gU(n){return[...ve(n,"boost_pickup")].sort((e,t)=>e.frame-t.frame||e.time-t.time)}function yU(n){return[...ve(n,"respawn")].sort((e,t)=>e.frame-t.frame||e.time-t.time)}function Bp(n,e){for(const t of sM)n[t]=e[t]}function aM(n){const e=gU(n),t=yU(n),i=_U(n);let s=0,a=0;const r=new Map,o=Up(),l=Up(),c=(d,h)=>{const f=gl(d);let p=r.get(f);return p||(p=Up(),r.set(f,p)),p.isTeamZero=h,p},u=(d,h,f)=>{const p=g=>i.get(e_(h,g))?.sample(f)??0;d.amount_used=p("boost_used"),d.amount_used_while_grounded=p("boost_used_grounded"),d.amount_used_while_airborne=p("boost_used_airborne"),d.amount_used_while_supersonic=p("boost_used_supersonic")};return{applyFrame(d,h){for(;s({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function t_(n){return`${n.key}\0${n.value}`}function Ru(n){return n.map(t_).join("")}function TU(n,e){e.sort((s,a)=>t_(s).localeCompare(t_(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Ru(s.labels)===Ru(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Ru(s.labels).localeCompare(Ru(a.labels))))}function MU(n,e){return n.labeled_event_counts?.entries.filter(t=>t.labels.some(i=>i.key==="confidence_band"&&i.value===e)).reduce((t,i)=>t+i.count,0)??0}function EU(n){return n.labeled_event_counts?.entries.reduce((e,t)=>e+t.count,0)??0}function CU(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function AU(n,e,t,i){n.is_last_ceiling_shot=i,n.time_since_last_ceiling_shot=n.last_ceiling_shot_time==null?null:Math.max(0,rM(t,n.last_ceiling_shot_time)),n.frames_since_last_ceiling_shot=n.last_ceiling_shot_frame==null?null:Math.max(0,e-n.last_ceiling_shot_frame)}function RU(n,e,t,i){TU(n,[{key:"confidence_band",value:e.confidence>=xU?"high":"standard"}]),n.count=EU(n),n.high_confidence_count=MU(n,"high"),n.is_last_ceiling_shot=!0,n.last_ceiling_shot_time=e.time,n.last_ceiling_shot_frame=e.frame,n.time_since_last_ceiling_shot=Math.max(0,rM(i,e.time)),n.frames_since_last_ceiling_shot=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=wU(n.cumulative_confidence,e.confidence)}function PU(n,e){Object.assign(n,e??oM()),e?.labeled_event_counts?n.labeled_event_counts=CU(e.labeled_event_counts):delete n.labeled_event_counts}function IU(n){const e=lM(n);for(const t of n.frames)e.applyFrame(t);return n}function lM(n){const e=SU(ve(n,"ceiling_shot"));let t=0,i=null;const s=new Map;return{applyFrame(a){if(a.is_live_play){for(const[r,o]of s)AU(o,a.frame_number,a.time,i===r);for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function OU(n,e){Object.assign(n,e??zg())}function tb(n,e){Object.assign(n,e)}function nb(n,e){n.score+=e.score_delta,n.goals+=e.goals_delta,n.assists+=e.assists_delta,n.saves+=e.saves_delta,n.shots+=e.shots_delta}function cM(n,e){if(e.time_after_kickoff!=null){const t=Math.max(0,e.time_after_kickoff);t<10?n.kickoff_goal_count+=1:t<20?n.short_goal_count+=1:t<40?n.medium_goal_count+=1:n.long_goal_count+=1}if(e.goal_buildup==="counter_attack"?n.counter_attack_goal_count+=1:e.goal_buildup==="sustained_pressure"?n.sustained_pressure_goal_count+=1:e.goal_buildup!=null&&(n.other_buildup_goal_count+=1),e.ball_air_time_before_goal!=null){const t=Math.max(0,e.ball_air_time_before_goal);n.goal_ball_air_time_sample_count+=1,n.cumulative_goal_ball_air_time=is(n.cumulative_goal_ball_air_time,t),n.last_goal_ball_air_time=t}}function zp(n,e){return n!=null&&e!=null&&Jl(n)===Jl(e)}function ib(n,e){return n?e.y:-e.y}function FU(n,e){if(n.ball_position==null||e.position==null)return!1;const t=!n.scoring_team_is_team_0,i=ib(t,n.ball_position);if(i>LU)return!1;const s=ib(t,e.position);return s=DU}function NU(n,e,t){const i=t.is_team_0===e.scoring_team_is_team_0,s=zp(t.player,e.defending_team_most_back_player),a=zp(t.player,e.scoring_team_most_back_player);s&&(n.goals_conceded_while_last_defender+=1),a&&(n.goals_for_while_most_back+=1),s&&(n.goals_against_while_most_back+=1),!i&&FU(e,t)&&(n.caught_ahead_of_play_on_conceded_goals+=1),!i&&t.boost_amount!=null&&(n.goal_against_boost_sample_count+=1,n.cumulative_boost_on_goals_against=is(n.cumulative_boost_on_goals_against,t.boost_amount),n.last_boost_on_goal_against=t.boost_amount),!i&&t.average_boost_in_leadup!=null&&t.min_boost_in_leadup!=null&&(n.goal_against_boost_leadup_sample_count+=1,n.cumulative_average_boost_in_goal_against_leadup=is(n.cumulative_average_boost_in_goal_against_leadup,t.average_boost_in_leadup),n.cumulative_min_boost_in_goal_against_leadup=is(n.cumulative_min_boost_in_goal_against_leadup,t.min_boost_in_leadup),n.last_average_boost_in_goal_against_leadup=t.average_boost_in_leadup,n.last_min_boost_in_goal_against_leadup=t.min_boost_in_leadup),!i&&t.position!=null&&(n.goal_against_position_sample_count+=1,n.cumulative_goal_against_position_x=is(n.cumulative_goal_against_position_x,t.position.x),n.cumulative_goal_against_position_y=is(n.cumulative_goal_against_position_y,t.position.y),n.cumulative_goal_against_position_z=is(n.cumulative_goal_against_position_z,t.position.z),n.last_goal_against_position={...t.position});const r=zp(t.player,e.scorer),o=r?e.scorer_last_touch?.ball_position:null;o!=null&&(n.scoring_goal_last_touch_position_sample_count+=1,n.cumulative_scoring_goal_last_touch_position_x=is(n.cumulative_scoring_goal_last_touch_position_x,o.x),n.cumulative_scoring_goal_last_touch_position_y=is(n.cumulative_scoring_goal_last_touch_position_y,o.y),n.cumulative_scoring_goal_last_touch_position_z=is(n.cumulative_scoring_goal_last_touch_position_z,o.z),n.last_scoring_goal_last_touch_position={...o}),r&&cM(n,e)}function UU(n,e,t,i){cM(i.scoring_team_is_team_0?e:t,i);for(const s of i.players){const a=Jl(s.player),r=n.get(a)??zg();n.set(a,r),NU(r,i,s)}}function BU(n){const e=uM(n);for(const t of n.frames)e.applyFrame(t);return n}function uM(n){const e=eb(ve(n,"core_player")),t=eb(ve(n,"goal_context"));let i=0,s=0;const a=new Map,r=n_(),o=n_();return{applyFrame(l){for(;i({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function rb(n,e){n.count+=1,n.total_time=sb(n.total_time,e.duration),n.longest_time=Math.max(n.longest_time,e.duration),n.touch_count+=e.touch_count,n.total_advance_distance=sb(n.total_advance_distance,e.total_advance_distance)}function Vp(n,e){Object.assign(n,e??Qu())}function HU(n){const e=dM(n);for(const t of n.frames)e.applyFrame(t);return n}function dM(n){const e=zU(ve(n,"controlled_play"));let t=0;const i=new Map,s=Qu(),a=Qu();return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function GU(n,e){n.count+=1,e.on_ball&&(n.on_ball_count+=1)}function $U(n,e){Object.assign(n,e??hM())}function WU(n){const e=fM(n);for(const t of n.frames)e.applyFrame(t);return n}function fM(n){const e=VU(ve(n,"dodge_reset"));let t=0;const i=new Map;return{applyFrame(s){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function KU(n,e,t,i){n.is_last_double_tap=i,n.time_since_last_double_tap=n.last_double_tap_time==null?null:Math.max(0,t-n.last_double_tap_time),n.frames_since_last_double_tap=n.last_double_tap_frame==null?null:Math.max(0,e-n.last_double_tap_frame)}function qU(n,e,t,i){n.count+=1,n.last_double_tap_time=e.time,n.last_double_tap_frame=e.frame,n.time_since_last_double_tap=Math.max(0,i-e.time),n.frames_since_last_double_tap=Math.max(0,t-e.frame)}function YU(n,e){Object.assign(n,e??pM())}function cb(n,e){n.count=e}function jU(n){const e=mM(n);for(const t of n.frames)e.applyFrame(t);return n}function mM(n){const e=XU(ve(n,"double_tap"));let t=0,i=0,s=0,a=null;const r=new Map;return{applyFrame(o){for(const[c,u]of r)KU(u,o.frame_number,o.time,c===a);let l=!1;for(;t({event:e,index:t})).sort((e,t)=>e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function JU(n,e){Object.assign(n,e??_M())}function hb(n,e){Object.assign(n,e)}function QU(n){const e=gM(n);for(const t of n.frames)e.applyFrame(t);return n}function gM(n){const e=ZU(ve(n,"demolition"));let t=0;const i=new Map,s=db(),a=db();function r(o){const l=ub(o),c=i.get(l)??_M();return i.set(l,c),c}return{applyFrame(o){for(;t({event:e,index:t})).sort((e,t)=>e.event.resolve_frame!==t.event.resolve_frame?e.event.resolve_frame-t.event.resolve_frame:e.event.resolve_time!==t.event.resolve_time?e.event.resolve_time-t.event.resolve_time:e.index-t.index).map(({event:e})=>e)}function tB(n){return{key:"phase",value:n?"kickoff":"open_play"}}function nB(n,e){return e==null?{key:"outcome",value:"neutral"}:{key:"outcome",value:e===n?"win":"loss"}}function iB(n,e){return e==null?{key:"possession_after",value:"neutral"}:{key:"possession_after",value:e===n?"self":"opponent"}}function sB(n,e){return{key:"dodge_state",value:(n?e.team_zero_dodge_contact:e.team_one_dodge_contact)?"dodge":"no_dodge"}}function s_(n){return`${n.key}\0${n.value}`}function Pu(n){return n.map(s_).join("")}function aB(n,e){e.sort((s,a)=>s_(s).localeCompare(s_(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Pu(s.labels)===Pu(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Pu(s.labels).localeCompare(Pu(a.labels))))}function rB(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function pb(n,e,t){n.count+=1,t.winning_team_is_team_0==null?n.neutral_outcomes+=1:t.winning_team_is_team_0===e?n.wins+=1:n.losses+=1,t.possession_team_is_team_0==null?n.neutral_possession_after_count+=1:t.possession_team_is_team_0===e?n.possession_after_count+=1:n.opponent_possession_after_count+=1,t.is_kickoff&&(n.kickoff_count+=1,t.winning_team_is_team_0==null?n.kickoff_neutral_outcomes+=1:t.winning_team_is_team_0===e?n.kickoff_wins+=1:n.kickoff_losses+=1,t.possession_team_is_team_0==null?n.kickoff_neutral_possession_after_count+=1:t.possession_team_is_team_0===e?n.kickoff_possession_after_count+=1:n.kickoff_opponent_possession_after_count+=1)}function mb(n,e,t){aB(n,[tB(t.is_kickoff),nB(e,t.winning_team_is_team_0),iB(e,t.possession_team_is_team_0),sB(e,t)]),n.count+=1,t.winning_team_is_team_0==null?n.neutral_outcomes+=1:t.winning_team_is_team_0===e?n.wins+=1:n.losses+=1,t.possession_team_is_team_0===e&&(n.possession_after_count+=1),t.is_kickoff&&(n.kickoff_count+=1,t.winning_team_is_team_0==null?n.kickoff_neutral_outcomes+=1:t.winning_team_is_team_0===e?n.kickoff_wins+=1:n.kickoff_losses+=1,t.possession_team_is_team_0===e&&(n.kickoff_possession_after_count+=1))}function oB(n,e){Object.assign(n,e??i_()),e?.labeled_event_counts?n.labeled_event_counts=rB(e.labeled_event_counts):delete n.labeled_event_counts}function _b(n,e){Object.assign(n,e)}function lB(n){const e=yM(n);for(const t of n.frames)e.applyFrame(t);return n}function yM(n){const e=eB(ve(n,"fifty_fifty"));let t=0;const i=fb(),s=fb(),a=new Map;return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function a_(n){return`${n.key}\0${n.value}`}function Iu(n){return n.map(a_).join("")}function xM(n,e){e.sort((s,a)=>a_(s).localeCompare(a_(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Iu(s.labels)===Iu(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Iu(s.labels).localeCompare(Iu(a.labels))))}function uB(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function dB(n){return[{key:"kickoff_spawn",value:n.spawn_position},{key:"taker_outcome",value:n.outcome},{key:"kickoff_approach",value:n.approach},{key:"approach_flip_direction",value:n.approach_flip_direction}]}function hB(n){return[{key:"kickoff_spawn",value:n.spawn_position},{key:"support_behavior",value:n.support_behavior}]}function yb(n,e,t){n.count+=1,t.outcome==="neutral"?n.neutral_outcomes+=1:t.outcome===(e?"team_zero_win":"team_one_win")?n.wins+=1:t.outcome===(e?"team_one_win":"team_zero_win")&&(n.losses+=1),t.kickoff_possession_outcome==="contested"?n.contested_kickoff_possessions+=1:t.kickoff_possession_outcome===(e?"team_zero_possession":"team_one_possession")?n.kickoff_possessions+=1:t.kickoff_possession_outcome===(e?"team_one_possession":"team_zero_possession")?n.opponent_kickoff_possessions+=1:t.kickoff_possession_outcome===(e?"team_zero_advantage":"team_one_advantage")?n.kickoff_possession_advantages+=1:n.opponent_kickoff_possession_advantages+=1,t.kickoff_goal&&(n.kickoff_goal_count+=1,t.scoring_team_is_team_0===e?n.kickoff_goals_for+=1:t.scoring_team_is_team_0!=null&&(n.kickoff_goals_against+=1)),t.win_strength!=null&&(n.win_strength_sample_count+=1,n.cumulative_win_strength+=t.win_strength)}function vb(n,e,t){t&&(t.boost_after!=null&&(n.boost_after_sample_count+=1,n.cumulative_boost_after+=t.boost_after,e.boost_after_sample_count+=1,e.cumulative_boost_after+=t.boost_after),t.outcome==="fake"?(n.fake_count+=1,e.fake_count+=1):t.outcome==="missed"&&(n.missed_count+=1,e.missed_count+=1))}function fB(n,e,t){n.count+=1,xM(n,dB(t)),t.outcome==="touched"?n.touches+=1:t.outcome==="fake"?n.fakes+=1:t.outcome==="missed"&&(n.misses+=1),e.kickoff_goal&&e.scoring_team_is_team_0===t.is_team_0&&(n.kickoff_goal_count+=1),t.boost_after!=null&&(n.boost_after_sample_count+=1,n.cumulative_boost_after+=t.boost_after)}function pB(n,e,t){n.count+=1,xM(n,hB(t)),t.first_touch_time!=null&&(n.touches+=1),t.support_behavior==="go_for_boost"?n.support_go_for_boosts+=1:t.support_behavior==="cheat"?n.support_cheats+=1:t.support_behavior==="other"&&(n.support_other+=1),e.kickoff_goal&&e.scoring_team_is_team_0===t.is_team_0&&(n.kickoff_goal_count+=1),t.boost_after!=null&&(n.boost_after_sample_count+=1,n.cumulative_boost_after+=t.boost_after)}function Lu(n,e,t){const i=vM(t.player),s=n.get(i)??bM();n.set(i,s),"outcome"in t?fB(s,e,t):pB(s,e,t)}function bb(n,e){Object.assign(n,e)}function mB(n,e){Object.assign(n,e??bM()),e?.labeled_event_counts?n.labeled_event_counts=uB(e.labeled_event_counts):delete n.labeled_event_counts}function _B(n){const e=wM(n);for(const t of n.frames)e.applyFrame(t);return n}function wM(n){const e=cB(ve(n,"kickoff"));let t=0;const i=gb(),s=gb(),a=new Map;return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function r_(n){return`${n.key}\0${n.value}`}function ku(n){return n.map(r_).join("")}function vB(n,e){e.sort((s,a)=>r_(s).localeCompare(r_(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>ku(s.labels)===ku(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>ku(s.labels).localeCompare(ku(a.labels))))}function bB(n,e){return n.labeled_event_counts?.entries.filter(t=>t.labels.some(i=>i.key==="confidence_band"&&i.value===e)).reduce((t,i)=>t+i.count,0)??0}function xB(n){return n==="forward"||n==="reverse"||n==="side"?n:"other"}function wB(n){return n==="left"||n==="right"?n:"center"}function SB(n){return n.labeled_event_counts?.entries.reduce((e,t)=>e+t.count,0)??0}function TB(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function MB(n,e,t,i){n.is_last_flick=i,n.time_since_last_flick=n.last_flick_time==null?null:Math.max(0,SM(t,n.last_flick_time)),n.frames_since_last_flick=n.last_flick_frame==null?null:Math.max(0,e-n.last_flick_frame)}function EB(n,e,t,i){vB(n,[{key:"confidence_band",value:e.confidence>=gB?"high":"standard"},{key:"kind",value:xB(e.kind)},{key:"direction",value:wB(e.direction)}]),n.count=SB(n),n.high_confidence_count=bB(n,"high"),n.is_last_flick=!0,n.last_flick_time=e.time,n.last_flick_frame=e.frame,n.time_since_last_flick=Math.max(0,SM(i,e.time)),n.frames_since_last_flick=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=$p(n.cumulative_confidence,e.confidence),n.cumulative_setup_duration=$p(n.cumulative_setup_duration,e.setup_duration),n.cumulative_ball_speed_change=$p(n.cumulative_ball_speed_change,e.ball_speed_change)}function CB(n,e){Object.assign(n,e??TM()),e?.labeled_event_counts?n.labeled_event_counts=TB(e.labeled_event_counts):delete n.labeled_event_counts}function AB(n){const e=MM(n);for(const t of n.frames)e.applyFrame(t);return n}function MM(n){const e=yB(ve(n,"flick"));let t=0,i=null;const s=new Map;return{applyFrame(a){if(a.is_live_play){for(const[r,o]of s)MB(o,a.frame_number,a.time,r===i);for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function PB(n,e){n.count+=1,n.total_time_to_use+=e.time_since_reset,n.min_time_to_use=n.min_time_to_use===null?e.time_since_reset:Math.min(n.min_time_to_use,e.time_since_reset)}function IB(n,e){Object.assign(n,e??EM())}function LB(n){const e=CM(n);for(const t of n.frames)e.applyFrame(t);return n}function CM(n){const e=RB(ve(n,"flip_reset"));let t=0;const i=new Map;return{applyFrame(s){for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function DB(n,e,t,i){n.is_last_half_volley=i,n.time_since_last_half_volley=n.last_half_volley_time==null?null:Math.max(0,RM(t,n.last_half_volley_time)),n.frames_since_last_half_volley=n.last_half_volley_frame==null?null:Math.max(0,e-n.last_half_volley_frame)}function OB(n,e,t,i){n.count+=1,n.total_ball_speed=AM(n.total_ball_speed,e.ball_speed),n.fastest_ball_speed=Math.max(n.fastest_ball_speed,e.ball_speed),n.last_half_volley_time=e.time,n.last_half_volley_frame=e.frame,n.time_since_last_half_volley=Math.max(0,RM(i,e.time)),n.frames_since_last_half_volley=Math.max(0,t-e.frame)}function FB(n,e){Object.assign(n,e??PM())}function Tb(n,e){Object.assign(n,e)}function NB(n){const e=IM(n);for(const t of n.frames)e.applyFrame(t);return n}function IM(n){const e=kB(ve(n,"half_volley"));let t=0,i=null;const s=new Map,a={count:0,total_ball_speed:0,fastest_ball_speed:0},r={count:0,total_ball_speed:0,fastest_ball_speed:0};return{applyFrame(o){for(const[l,c]of s)DB(c,o.frame_number,o.time,o.is_live_play&&l===i);if(!o.is_live_play)i=null;else{let l=!1;for(;te.frame!==t.frame?e.frame-t.frame:e.time!==t.time?e.time-t.time:$i(e.player).localeCompare($i(t.player)))}function HB(n){return[...n].sort((e,t)=>e.resolved_frame!==t.resolved_frame?e.resolved_frame-t.resolved_frame:e.resolved_time!==t.resolved_time?e.resolved_time-t.resolved_time:e.frame!==t.frame?e.frame-t.frame:e.time!==t.time?e.time-t.time:$i(e.player).localeCompare($i(t.player)))}function Wp(){return{count:0,highConfidenceCount:0,lastTime:null,lastFrame:null,lastResolvedTime:null,lastResolvedFrame:null,lastQuality:null,bestQuality:0,cumulativeQuality:0,labeledCounts:{entries:[]}}}function co(n){return Math.fround(n)}function VB(n,e){return co(co(n)+co(e))}function GB(n,e){return{key:"confidence_band",value:n>=e?"high":"standard"}}function $B(n,e){const t=e.sort((s,a)=>s.key===a.key?s.value.localeCompare(a.value):s.key.localeCompare(a.key)),i=n.entries.find(s=>s.labels.length===t.length&&s.labels.every((a,r)=>a.key===t[r]?.key&&a.value===t[r]?.value));if(i){i.count+=1;return}n.entries.push({labels:t,count:1}),n.entries.sort((s,a)=>JSON.stringify(s.labels).localeCompare(JSON.stringify(a.labels)))}function Uo(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function Xp(n,e,t,i,s){n.count+=1,e.confidence>=s&&(n.highConfidenceCount+=1),$B(n.labeledCounts,[GB(e.confidence,s)]),n.lastTime=e.time,n.lastFrame=e.frame,n.lastResolvedTime=i,n.lastResolvedFrame=t,n.lastQuality=e.confidence,n.bestQuality=Math.max(n.bestQuality,e.confidence),n.cumulativeQuality=VB(n.cumulativeQuality,e.confidence)}function Hg(n,e){return n?.lastTime==null?null:n.lastResolvedFrame===e.frame_number?0:Math.max(0,co(co(e.time)-co(n.lastTime)))}function Vg(n,e){return n?.lastFrame==null?null:n.lastResolvedFrame===e.frame_number?0:Math.max(0,e.frame_number-n.lastFrame)}function LM(n,e,t,i){n.count=e?.count??0,n.high_confidence_count=e?.highConfidenceCount??0,n.is_last_speed_flip=i,n.last_speed_flip_time=e?.lastTime??null,n.last_speed_flip_frame=e?.lastFrame??null,n.time_since_last_speed_flip=Hg(e,t),n.frames_since_last_speed_flip=Vg(e,t),n.last_quality=e?.lastQuality??null,n.best_quality=e?.bestQuality??0,n.cumulative_quality=e?.cumulativeQuality??0,e?.labeledCounts.entries.length?n.labeled_event_counts=Uo(e.labeledCounts):delete n.labeled_event_counts}function kM(n,e,t,i){n.count=e?.count??0,n.high_confidence_count=e?.highConfidenceCount??0,n.is_last_half_flip=i,n.last_half_flip_time=e?.lastTime??null,n.last_half_flip_frame=e?.lastFrame??null,n.time_since_last_half_flip=Hg(e,t),n.frames_since_last_half_flip=Vg(e,t),n.last_quality=e?.lastQuality??null,n.best_quality=e?.bestQuality??0,n.cumulative_quality=e?.cumulativeQuality??0,e?.labeledCounts.entries.length?n.labeled_event_counts=Uo(e.labeledCounts):delete n.labeled_event_counts}function DM(n,e,t,i){n.count=e?.count??0,n.high_confidence_count=e?.highConfidenceCount??0,n.is_last_wavedash=i,n.last_wavedash_time=e?.lastTime??null,n.last_wavedash_frame=e?.lastFrame??null,n.time_since_last_wavedash=Hg(e,t),n.frames_since_last_wavedash=Vg(e,t),n.last_quality=e?.lastQuality??null,n.best_quality=e?.bestQuality??0,n.cumulative_quality=e?.cumulativeQuality??0,e?.labeledCounts.entries.length?n.labeled_event_counts=Uo(e.labeledCounts):delete n.labeled_event_counts}function WB(n){const e={...n};return n.labeled_event_counts?e.labeled_event_counts=Uo(n.labeled_event_counts):delete e.labeled_event_counts,e}function XB(n){const e={...n};return n.labeled_event_counts?e.labeled_event_counts=Uo(n.labeled_event_counts):delete e.labeled_event_counts,e}function KB(n){const e={...n};return n.labeled_event_counts?e.labeled_event_counts=Uo(n.labeled_event_counts):delete e.labeled_event_counts,e}function qB(n,e){if(e){Object.assign(n,e);return}LM(n,void 0,{frame_number:0,time:0},!1)}function YB(n,e){if(e){Object.assign(n,e);return}kM(n,void 0,{frame_number:0,time:0},!1)}function jB(n,e){if(e){Object.assign(n,e);return}DM(n,void 0,{frame_number:0,time:0},!1)}function ZB(n){return n.is_live_play||n.ball_has_been_hit===!1}function JB(n){const e=OM(n);for(const t of n.frames)e.applyFrame(t);return n}function OM(n){const e=HB(ve(n,"speed_flip")),t=Mb(ve(n,"half_flip")),i=Mb(ve(n,"wavedash"));let s=0,a=0,r=0,o=null,l=null,c=null;const u=new Map,d=new Map,h=new Map,f=new Map,p=new Map,g=new Map;return{applyFrame(_){if(ZB(_)){for(;sQB.map(e=>({labels:[{key:"height_band",value:n},{key:"speed_band",value:e}],value:0}))).sort((n,e)=>JSON.stringify(n.labels).localeCompare(JSON.stringify(e.labels)))}}function ed(n=!1){return{tracked_time:0,total_distance:0,speed_integral:0,time_slow_speed:0,time_boost_speed:0,time_supersonic_speed:0,time_on_ground:0,time_low_air:0,time_high_air:0,labeled_tracked_time:n?nz():{entries:[]}}}function iz(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function sz(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function az(n,e,t){const i=sz(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=ss(s.value,t):(n.entries.push({labels:i,value:oa(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function rz(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),value:e.value}))}}function Cb(n,e){const t=oa(e.dt);n.tracked_time=ss(n.tracked_time,t),n.total_distance=ss(n.total_distance,e.distance),n.speed_integral=ss(n.speed_integral,tz(e.speed,t)),e.speed_band==="slow"?n.time_slow_speed=ss(n.time_slow_speed,t):e.speed_band==="boost"?n.time_boost_speed=ss(n.time_boost_speed,t):e.speed_band==="supersonic"&&(n.time_supersonic_speed=ss(n.time_supersonic_speed,t)),e.height_band==="ground"?n.time_on_ground=ss(n.time_on_ground,t):e.height_band==="low_air"?n.time_low_air=ss(n.time_low_air,t):e.height_band==="high_air"&&(n.time_high_air=ss(n.time_high_air,t));const i=n.labeled_tracked_time??{entries:[]};n.labeled_tracked_time=i,az(i,[{key:"speed_band",value:e.speed_band},{key:"height_band",value:e.height_band}],t)}function Kp(n,e){const t=e??ed(!0),i=t.labeled_tracked_time;Object.assign(n,t,{labeled_tracked_time:i?rz(i):void 0}),i?.entries.length||delete n.labeled_tracked_time}function oz(n){const e=FM(n);for(const t of n.frames)e.applyFrame(t);return n}function FM(n){const e=iz(ve(n,"movement"));let t=0;const i=new Map,s=ed(),a=ed();return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function cz(n,e,t,i){n.is_last_one_timer=i,n.time_since_last_one_timer=n.last_one_timer_time==null?null:Math.max(0,t-n.last_one_timer_time),n.frames_since_last_one_timer=n.last_one_timer_frame==null?null:Math.max(0,e-n.last_one_timer_frame)}function uz(n,e,t,i){n.count+=1,n.total_ball_speed+=e.ball_speed,n.fastest_ball_speed=Math.max(n.fastest_ball_speed,e.ball_speed),n.total_pass_distance+=e.pass_travel_distance,n.last_one_timer_time=e.time,n.last_one_timer_frame=e.frame,n.time_since_last_one_timer=Math.max(0,i-e.time),n.frames_since_last_one_timer=Math.max(0,t-e.frame)}function dz(n,e){Object.assign(n,e??NM())}function Rb(n,e){Object.assign(n,e)}function hz(n){const e=UM(n);for(const t of n.frames)e.applyFrame(t);return n}function UM(n){const e=lz(ve(n,"one_timer"));let t=0,i=null;const s=new Map,a={count:0,total_ball_speed:0,fastest_ball_speed:0},r={count:0,total_ball_speed:0,fastest_ball_speed:0};return{applyFrame(o){for(const[l,c]of s)cz(c,o.frame_number,o.time,o.is_live_play&&l===i);if(!o.is_live_play)i=null;else{let l=!1;for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.index-t.index}).map(({event:e})=>e)}function pz(n,e,t,i){n.is_last_completed_pass=i,n.time_since_last_completed_pass=n.last_completed_pass_time==null?null:Math.max(0,t-n.last_completed_pass_time),n.frames_since_last_completed_pass=n.last_completed_pass_frame==null?null:Math.max(0,e-n.last_completed_pass_frame)}function mz(n,e,t,i){n.completed_pass_count+=1,n.total_pass_distance+=e.ball_travel_distance,n.total_pass_advance+=e.ball_advance_distance,n.longest_pass_distance=Math.max(n.longest_pass_distance,e.ball_travel_distance),n.last_completed_pass_time=e.time,n.last_completed_pass_frame=e.frame,n.time_since_last_completed_pass=Math.max(0,i-e.time),n.frames_since_last_completed_pass=Math.max(0,t-e.frame)}function _z(n,e){Object.assign(n,e??o_())}function Pb(n,e){Object.assign(n,e)}function gz(n){const e=BM(n);for(const t of n.frames)e.applyFrame(t);return n}function BM(n){const e=fz(ve(n,"pass"));let t=0,i=null;const s=new Map,a={completed_pass_count:0,total_pass_distance:0,total_pass_advance:0,longest_pass_distance:0},r={completed_pass_count:0,total_pass_distance:0,total_pass_advance:0,longest_pass_distance:0};return{applyFrame(o){for(const[l,c]of s)pz(c,o.frame_number,o.time,o.is_live_play&&l===i);if(!o.is_live_play)i=null;else{let l=!1;for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function bz(n){return l_(n)}function xz(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function zM(n,e,t){const i=xz(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=yl(s.value,t):(n.entries.push({labels:i,value:Fl(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function wz(n,e){return n.key==="possession_state"&&n.value==="team_zero"?{key:"possession_state",value:e?"own":"opponent"}:n.key==="possession_state"&&n.value==="team_one"?{key:"possession_state",value:e?"opponent":"own"}:n.key==="field_third"&&n.value==="team_zero_third"?{key:"field_third",value:e?"defensive_third":"offensive_third"}:n.key==="field_third"&&n.value==="team_one_third"?{key:"field_third",value:e?"offensive_third":"defensive_third"}:n.key==="field_half"&&n.value==="team_zero_side"?{key:"field_half",value:e?"defensive_half":"offensive_half"}:n.key==="field_half"&&n.value==="team_one_side"?{key:"field_half",value:e?"offensive_half":"defensive_half"}:{...n}}function Ib(n,e){const t={entries:[]};for(const i of n.labeled_time.entries)zM(t,i.labels.map(s=>wz(s,e)),i.value);return{tracked_time:n.tracked_time,possession_time:e?n.team_zero_time:n.team_one_time,opponent_possession_time:e?n.team_one_time:n.team_zero_time,neutral_time:n.neutral_time,labeled_time:t}}function Sz(n,e){n.active=e.active,n.possessionState=e.possession_state}function Tz(n,e,t){if(!e.active)return;const i=Fl(t.dt);n.tracked_time=yl(n.tracked_time,i),e.possessionState==="team_zero"?n.team_zero_time=yl(n.team_zero_time,i):e.possessionState==="team_one"?n.team_one_time=yl(n.team_one_time,i):n.neutral_time=yl(n.neutral_time,i);const s=[{key:"possession_state",value:e.possessionState}];e.fieldThird!=null&&s.push({key:"field_third",value:e.fieldThird}),e.fieldHalf!=null&&s.push({key:"field_half",value:e.fieldHalf}),zM(n.labeled_time,s,i)}function Lb(n,e){Object.assign(n,e??vz())}function Mz(n){const e=HM(n);for(const t of n.frames)e.applyFrame(t);return n}function HM(n){const e=bz(ve(n,"possession")),t=l_(ve(n,"ball_third")),i=l_(ve(n,"ball_half"));let s=0,a=0,r=0;const o=yz(),l={active:!1,possessionState:"neutral",fieldThird:null,fieldHalf:null};return{applyFrame(c){for(;s({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function Oa(n,e){const t=rh(e.player),i=n.get(t)??VM();return n.set(t,i),i}function Cz(n,e){switch(n.active_game_time=Xt(n.active_game_time,e.duration),e.state){case"tracked":n.tracked_time=Xt(n.tracked_time,e.duration);break;case"demolished":n.time_demolished=Xt(n.time_demolished,e.duration);break}}function Az(n,e){switch(e.state){case"defensive":n.time_defensive_third=Xt(n.time_defensive_third,e.duration);break;case"neutral":n.time_neutral_third=Xt(n.time_neutral_third,e.duration);break;case"offensive":n.time_offensive_third=Xt(n.time_offensive_third,e.duration);break}}function Rz(n,e){switch(e.state){case"defensive":n.time_defensive_half=Xt(n.time_defensive_half,e.duration);break;case"offensive":n.time_offensive_half=Xt(n.time_offensive_half,e.duration);break}}function Pz(n,e){switch(e.state){case"behind_ball":n.time_behind_ball=Xt(n.time_behind_ball,e.duration);break;case"level_with_ball":n.time_level_with_ball=Xt(n.time_level_with_ball,e.duration);break;case"ahead_of_ball":n.time_in_front_of_ball=Xt(n.time_in_front_of_ball,e.duration);break}}function Iz(n,e){switch(e.state){case"no_teammates":n.time_no_teammates=Xt(n.time_no_teammates,e.duration);break;case"most_back":n.time_most_back=Xt(n.time_most_back,e.duration);break;case"most_forward":n.time_most_forward=Xt(n.time_most_forward,e.duration);break;case"mid":n.time_mid_role=Xt(n.time_mid_role,e.duration);break;case"other":n.time_other_role=Xt(n.time_other_role,e.duration);break}}function Lz(n,e,t){t.state.closest_to_ball_team&&(e.tracked_time=Xt(e.tracked_time,t.duration),e.time_closest_to_ball_team=Xt(e.time_closest_to_ball_team,t.duration),n.time_closest_to_ball_team=Xt(n.time_closest_to_ball_team,t.duration)),t.state.closest_to_ball_absolute&&(e.time_closest_to_ball_absolute=Xt(e.time_closest_to_ball_absolute,t.duration),n.time_closest_to_ball_absolute=Xt(n.time_closest_to_ball_absolute,t.duration)),t.state.farthest_from_ball&&(n.time_farthest_from_ball=Xt(n.time_farthest_from_ball,t.duration))}function kz(n,e){e.state==="shadowing"&&(n.time_shadow_defense=Xt(n.time_shadow_defense,e.duration))}function Dz(n,e){Object.assign(n,e??VM())}function kb(n,e){Object.assign(n,e??c_())}function Fa(n,e){const t=Ez(n),i=new Array(t.length).fill(0);return{applyThroughFrame(s){for(let a=0;as.frame_number)break;const o=Oz(r,s),l=o-i[a];l>0&&(i[a]=o,e({...r,duration:l}))}}}}function Oz(n,e){if(e.frame_number>=n.end_frame)return n.duration;const t=n.end_time-n.time;if(t<=0)return 0;const i=Math.max(0,e.time-n.time);return n.duration*Math.min(1,i/t)}function Fz(n){const e=GM(n);for(const t of n.frames)e.applyFrame(t);return n}function GM(n){const e=new Map,t=c_(),i=c_(),s=[Fa(ve(n,"player_activity"),a=>Cz(Oa(e,a),a)),Fa(ve(n,"field_third"),a=>Az(Oa(e,a),a)),Fa(ve(n,"field_half"),a=>Rz(Oa(e,a),a)),Fa(ve(n,"ball_depth"),a=>Pz(Oa(e,a),a)),Fa(ve(n,"depth_role"),a=>Iz(Oa(e,a),a)),Fa(ve(n,"ball_proximity"),a=>Lz(Oa(e,a),a.is_team_0?t:i,a)),Fa(ve(n,"shadow_defense"),a=>kz(Oa(e,a),a))];return{applyFrame(a){for(const r of s)r.applyThroughFrame(a);kb(a.team_zero.positioning,t),kb(a.team_one.positioning,i);for(const r of a.players)Dz(r.positioning,e.get(rh(r.player_id))),Nz(r.positioning,n,r.player_id)}}}function Nz(n,e,t){const i=e.positioning_summary;if(!Array.isArray(i))return;const s=rh(t),a=i.find(r=>!r||typeof r!="object"?!1:rh(r.player_id)===s);a?.distance&&Object.assign(n,a.distance)}function Yp(n){if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function vl(){return{total_duration:0,press_count:0}}function Uz(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function Bz(n){return n.gameplay_phase==="active_play"||n.gameplay_phase==="kickoff_waiting_for_touch"}function jp(n,e){Object.assign(n,e??vl())}function zz(n){const e=$M(n);for(const t of n.frames)e.applyFrame(t);return n}function $M(n){const e=Uz(ve(n,"powerslide"));let t=0;const i=new Map,s=new Map,a=vl(),r=vl();return{applyFrame(o){const l=Bz(o);for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function $z(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function WM(n,e,t){const i=$z(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=bl(s.value,t):(n.entries.push({labels:i,value:Nl(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function Wz(n,e){return n.key==="field_half"&&n.value==="team_zero_side"?{key:"field_half",value:e?"defensive_half":"offensive_half"}:n.key==="field_half"&&n.value==="team_one_side"?{key:"field_half",value:e?"offensive_half":"defensive_half"}:{...n}}function Db(n,e){const t={entries:[]};for(const i of n.labeled_time.entries)WM(t,i.labels.map(s=>Wz(s,e)),i.value);return{tracked_time:n.tracked_time,defensive_half_time:e?n.team_zero_side_time:n.team_one_side_time,offensive_half_time:e?n.team_one_side_time:n.team_zero_side_time,neutral_time:n.neutral_time,labeled_time:t}}function Xz(n,e){n.active=e.active,n.fieldHalf=e.field_half}function Kz(n,e,t){if(!e.active)return;const i=Nl(t.dt);n.tracked_time=bl(n.tracked_time,i),e.fieldHalf==="team_zero_side"?n.team_zero_side_time=bl(n.team_zero_side_time,i):e.fieldHalf==="team_one_side"?n.team_one_side_time=bl(n.team_one_side_time,i):n.neutral_time=bl(n.neutral_time,i),WM(n.labeled_time,[{key:"field_half",value:e.fieldHalf}],i)}function Ob(n,e){Object.assign(n,e??Vz())}function qz(n){const e=XM(n);for(const t of n.frames)e.applyFrame(t);return n}function XM(n){const e=Gz(ve(n,"ball_half"));let t=0;const i=Hz(),s={active:!1,fieldHalf:"neutral"};return{applyFrame(a){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function Jz(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function KM(n,e,t){const i=Jz(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=xl(s.value,t):(n.entries.push({labels:i,value:Ul(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function Qz(n,e){return n.key==="field_third"&&n.value==="team_zero_third"?{key:"field_third",value:e?"defensive_third":"offensive_third"}:n.key==="field_third"&&n.value==="team_one_third"?{key:"field_third",value:e?"offensive_third":"defensive_third"}:{...n}}function Fb(n,e){const t={entries:[]};for(const i of n.labeled_time.entries)KM(t,i.labels.map(s=>Qz(s,e)),i.value);return{tracked_time:n.tracked_time,defensive_third_time:e?n.team_zero_third_time:n.team_one_third_time,neutral_third_time:n.neutral_third_time,offensive_third_time:e?n.team_one_third_time:n.team_zero_third_time,labeled_time:t}}function eH(n,e){n.active=e.active,n.fieldThird=e.field_third}function tH(n,e,t){if(!e.active)return;const i=Ul(t.dt);n.tracked_time=xl(n.tracked_time,i),e.fieldThird==="team_zero_third"?n.team_zero_third_time=xl(n.team_zero_third_time,i):e.fieldThird==="team_one_third"?n.team_one_third_time=xl(n.team_one_third_time,i):n.neutral_third_time=xl(n.neutral_third_time,i),KM(n.labeled_time,[{key:"field_third",value:e.fieldThird}],i)}function Nb(n,e){Object.assign(n,e??jz())}function nH(n){const e=qM(n);for(const t of n.frames)e.applyFrame(t);return n}function qM(n){const e=Zz(ve(n,"ball_third"));let t=0;const i=Yz(),s={active:!1,fieldThird:"neutral_third"};return{applyFrame(a){for(;t({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function sH(n,e,t){n.session_count+=1,n.session_time=Du(n.session_time,t.duration),n.offensive_half_time=Du(n.offensive_half_time,t.offensive_half_time),n.offensive_third_time=Du(n.offensive_third_time,t.offensive_third_time),n.longest_session_time=Math.max(n.longest_session_time,t.duration),n.average_session_time=n.session_count===0?0:td(n.session_time/n.session_count),e.opponent_session_count+=1,e.opponent_session_time=Du(e.opponent_session_time,t.duration),e.opponent_longest_session_time=Math.max(e.opponent_longest_session_time,t.duration)}function Bb(n,e){Object.assign(n,e)}function aH(n){const e=YM(n);for(const t of n.frames)e.applyFrame(t);return n}function YM(n){const e=iH(ve(n,"territorial_pressure"));let t=0;const i=Ub(),s=Ub();return{applyFrame(a){for(;t=e[t].end_frame;){const r=e[t];sH(r.team_is_team_0?i:s,r.team_is_team_0?s:i,r),t+=1}Bb(a.team_zero.territorial_pressure,i),Bb(a.team_one.territorial_pressure,s)}}}function Yr(n,e){return Math.fround(Math.fround(n)+Math.fround(e))}function jM(n){if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function ZM(){return{active_game_time:0,time_first_man:0,time_second_man:0,time_third_man:0,time_ambiguous_role:0,longest_first_man_stint_time:0,first_man_stint_count:0,became_first_man_count:0,lost_first_man_count:0,current_role_state:"unknown"}}function zb(){return{first_man_changes_for_team:0,rotation_count:0}}function Hb(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function rH(n,e,t,i,s){const a=n.stats;switch(a.active_game_time=Yr(a.active_game_time,t),a.current_role_state=e.state,e.state){case"first_man":{n.lastFirstManEndTime!==null&&e.time-n.lastFirstManEndTime<=s?n.currentFirstManStintTime=Yr(n.currentFirstManStintTime,t):(n.currentFirstManStintTime=t,a.first_man_stint_count+=1),n.lastFirstManEndTime=i,a.longest_first_man_stint_time=Math.max(a.longest_first_man_stint_time,n.currentFirstManStintTime),a.time_first_man=Yr(a.time_first_man,t);break}case"second_man":a.time_second_man=Yr(a.time_second_man,t);break;case"third_man":a.time_third_man=Yr(a.time_third_man,t);break;case"ambiguous":a.time_ambiguous_role=Yr(a.time_ambiguous_role,t);break}}function oH(n,e){if(e.frame_number>=n.end_frame)return n.duration;const t=n.end_time-n.time;if(t<=0)return 0;const i=Math.max(0,e.time-n.time);return n.duration*Math.min(1,i/t)}function u_(n,e){const t=jM(e),i=n.get(t)??{currentFirstManStintTime:0,lastFirstManEndTime:null,stats:ZM()};return n.set(t,i),i}function lH(n,e,t){n.first_man_changes_for_team+=1,n.rotation_count+=1,u_(e,t.previous_first_man).stats.lost_first_man_count+=1,u_(e,t.next_first_man).stats.became_first_man_count+=1}function cH(n,e){Object.assign(n,e??ZM())}function Vb(n,e){Object.assign(n,e)}function uH(n){const e=JM(n);for(const t of n.frames)e.applyFrame(t);return n}function JM(n){const e=Hb(ve(n,"rotation_role")),t=Hb(ve(n,"first_man_change")),i=n.config.rotation_first_man_stint_end_grace_seconds,s=new Array(e.length).fill(0);let a=0;const r=new Map,o=zb(),l=zb();return{applyFrame(c){for(let u=0;uc.frame_number)break;const h=oH(d,c),f=h-s[u];if(f>0){s[u]=h;const p=c.frame_number>=d.end_frame?d.end_time:Math.min(c.time,d.end_time);rH(u_(r,d.player),d,f,p,i)}}for(;a({event:e,index:t})).sort((e,t)=>e.event.start_frame!==t.event.start_frame?e.event.start_frame-t.event.start_frame:e.event.start_time!==t.event.start_time?e.event.start_time-t.event.start_time:e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.index-t.index).map(({event:e})=>e)}function hH(n,e){n.count+=1,e.attackers===2&&e.defenders===1?n.two_v_one_count+=1:e.attackers===2&&e.defenders===2?n.two_v_two_count+=1:e.attackers===2&&e.defenders===3?n.two_v_three_count+=1:e.attackers===3&&e.defenders===1?n.three_v_one_count+=1:e.attackers===3&&e.defenders===2?n.three_v_two_count+=1:e.attackers===3&&e.defenders===3&&(n.three_v_three_count+=1)}function $b(n,e){Object.assign(n,e)}function fH(n){const e=QM(n);for(const t of n.frames)e.applyFrame(t);return n}function QM(n){const e=dH(ve(n,"rush"));let t=0;const i=Gb(),s=Gb(),a=n.config.rush_min_possession_retained_seconds;return{applyFrame(r){for(;t=e[t].start_frame&&r.time-e[t].start_time>=a;){const o=e[t];hH(o.is_team_0?i:s,o),t+=1}$b(r.team_zero.rush,i),$b(r.team_one.rush,s)}}}const pH=["control","hard_hit","medium_hit"],mH=["ground","high_air","low_air"],_H=["air","ground","wall"],gH=["dodge","no_dodge"];function uo(n){return Math.fround(n)}function nd(n,e){return uo(uo(n)+uo(e))}function eE(n,e){return uo(uo(n)-uo(e))}function Zp(n){if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function yH(){return{entries:gH.flatMap(n=>mH.flatMap(e=>pH.flatMap(t=>_H.map(i=>({labels:[{key:"dodge_state",value:n},{key:"height_band",value:e},{key:"kind",value:t},{key:"surface",value:i}],count:0}))))).sort((n,e)=>JSON.stringify(n.labels).localeCompare(JSON.stringify(e.labels)))}}function tE(){return{touch_count:0,control_touch_count:0,medium_hit_count:0,hard_hit_count:0,aerial_touch_count:0,high_aerial_touch_count:0,wall_touch_count:0,first_touch_count:0,is_last_touch:!1,last_touch_time:null,last_touch_frame:null,time_since_last_touch:null,frames_since_last_touch:null,last_ball_speed_change:null,max_ball_speed_change:0,cumulative_ball_speed_change:0,total_ball_travel_distance:0,total_ball_advance_distance:0,total_ball_retreat_distance:0,labeled_touch_counts:yH()}}const vH=tE();function Wb(){return{stats:tE(),labeledCountsVersion:0,labeledCountsSnapshot:void 0,labeledCountsSnapshotVersion:-1}}function bH(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function xH(n,e){e.sort((s,a)=>s.key===a.key?s.value.localeCompare(a.value):s.key.localeCompare(a.key));const t=n.labeled_touch_counts?.entries??[];n.labeled_touch_counts={entries:t};const i=t.find(s=>s.labels.length===e.length&&s.labels.every((a,r)=>a.key===e[r]?.key&&a.value===e[r]?.value));i?i.count+=1:(t.push({labels:e,count:1}),t.sort((s,a)=>JSON.stringify(s.labels).localeCompare(JSON.stringify(a.labels))))}function wH(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function Ou(n,e){return n.tags?.find(t=>t.group===e)?.value??null}function SH(n,e,t){const i=Ou(e,"kind")??"control",s=Ou(e,"height_band")??"ground",a=Ou(e,"surface")??"ground",r=Ou(e,"dodge_state")??"no_dodge",o=n.stats;o.touch_count+=1,i==="control"?o.control_touch_count+=1:i==="medium_hit"?o.medium_hit_count+=1:i==="hard_hit"&&(o.hard_hit_count+=1),s==="low_air"?o.aerial_touch_count+=1:s==="high_air"&&(o.aerial_touch_count+=1,o.high_aerial_touch_count+=1),a==="wall"&&(o.wall_touch_count+=1),xH(o,[{key:"kind",value:i},{key:"height_band",value:s},{key:"surface",value:a},{key:"dodge_state",value:r}]),n.labeledCountsVersion+=1,o.last_touch_time=e.time,o.last_touch_frame=e.frame,o.time_since_last_touch=Math.max(0,eE(t.time,e.time)),o.frames_since_last_touch=Math.max(0,t.frame_number-e.frame),o.last_ball_speed_change=e.ball_speed_change,o.max_ball_speed_change=Math.max(o.max_ball_speed_change,e.ball_speed_change),o.cumulative_ball_speed_change=nd(o.cumulative_ball_speed_change,e.ball_speed_change)}function TH(n){return n.labeledCountsSnapshotVersion!==n.labeledCountsVersion&&(n.labeledCountsSnapshot=n.stats.labeled_touch_counts?wH(n.stats.labeled_touch_counts):void 0,n.labeledCountsSnapshotVersion=n.labeledCountsVersion),n.labeledCountsSnapshot}function MH(n,e){if(!e){Object.assign(n,vH);return}Object.assign(n,e.stats,{labeled_touch_counts:TH(e)})}function EH(n){const e=nE(n);for(const t of n.frames)e.applyFrame(t);return n}function nE(n){const e=bH(ve(n,"touch")),t=e.flatMap(o=>o.ball_movement?[{player:o.player,movement:o.ball_movement}]:[]).sort((o,l)=>o.movement.end_frame!==l.movement.end_frame?o.movement.end_frame-l.movement.end_frame:o.movement.end_time-l.movement.end_time);let i=0,s=0,a=null;const r=new Map;return{applyFrame(o){if(!o.is_live_play)a=null;else{for(const l of r.values()){const c=l.stats;c.is_last_touch=!1,c.last_touch_time!=null&&(c.time_since_last_touch=Math.max(0,eE(o.time,c.last_touch_time))),c.last_touch_frame!=null&&(c.frames_since_last_touch=Math.max(0,o.frame_number-c.last_touch_frame))}for(;i({event:e,index:t})).sort((e,t)=>e.event.resolved_frame!==t.event.resolved_frame?e.event.resolved_frame-t.event.resolved_frame:e.event.resolved_time!==t.event.resolved_time?e.event.resolved_time-t.event.resolved_time:e.index-t.index).map(({event:e})=>e)}function RH(n,e,t){n.is_last_whiff=!1,n.time_since_last_whiff=n.last_whiff_time==null?null:Math.max(0,t-n.last_whiff_time),n.frames_since_last_whiff=n.last_whiff_frame==null?null:Math.max(0,e-n.last_whiff_frame)}function PH(n,e,t,i){if((e.kind??"whiff")==="beaten_to_ball"){n.beaten_to_ball_count+=1;return}n.whiff_count+=1,e.aerial?n.aerial_whiff_count+=1:n.grounded_whiff_count+=1,e.dodge_active&&(n.dodge_whiff_count+=1),n.is_last_whiff=!0,n.last_whiff_time=e.time,n.last_whiff_frame=e.frame,n.time_since_last_whiff=Math.max(0,i-e.time),n.frames_since_last_whiff=Math.max(0,t-e.frame),n.last_closest_approach_distance=e.closest_approach_distance,n.best_closest_approach_distance=n.best_closest_approach_distance==null?e.closest_approach_distance:Math.min(n.best_closest_approach_distance,e.closest_approach_distance),n.cumulative_closest_approach_distance+=e.closest_approach_distance}function Xb(n,e){Object.assign(n,e??d_())}function IH(n){const e=iE(n);for(const t of n.frames)e.applyFrame(t);return n}function iE(n){const e=AH(ve(n,"whiff"));let t=0,i=null;const s=new Map,a=new Map;return{applyFrame(r){if(r.is_live_play){for(const o of s.values())RH(o,r.frame_number,r.time);for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function DH(n,e,t,i){n.is_last_wall_aerial=i,n.time_since_last_wall_aerial=n.last_wall_aerial_time==null?null:Math.max(0,sE(t,n.last_wall_aerial_time)),n.frames_since_last_wall_aerial=n.last_wall_aerial_frame==null?null:Math.max(0,e-n.last_wall_aerial_frame)}function OH(n,e,t,i){n.count+=1,e.confidence>=LH&&(n.high_confidence_count+=1),n.is_last_wall_aerial=!0,n.last_wall_aerial_time=e.time,n.last_wall_aerial_frame=e.frame,n.time_since_last_wall_aerial=Math.max(0,sE(i,e.time)),n.frames_since_last_wall_aerial=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=Fu(n.cumulative_confidence,e.confidence),n.cumulative_setup_duration=Fu(n.cumulative_setup_duration,e.setup_duration),n.cumulative_takeoff_to_touch_time=Fu(n.cumulative_takeoff_to_touch_time,e.time_since_takeoff),n.cumulative_touch_height=Fu(n.cumulative_touch_height,e.player_position[2]??0)}function FH(n,e){Object.assign(n,e??aE())}function NH(n){const e=rE(n);for(const t of n.frames)e.applyFrame(t);return n}function rE(n){const e=kH(ve(n,"wall_aerial"));let t=0,i=null;const s=new Map;return{applyFrame(a){for(const[r,o]of s)DH(o,a.frame_number,a.time,a.is_live_play&&r===i);if(!a.is_live_play)i=null;else{for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function zH(n,e,t,i){n.is_last_wall_aerial_shot=i,n.time_since_last_wall_aerial_shot=n.last_wall_aerial_shot_time==null?null:Math.max(0,oE(t,n.last_wall_aerial_shot_time)),n.frames_since_last_wall_aerial_shot=n.last_wall_aerial_shot_frame==null?null:Math.max(0,e-n.last_wall_aerial_shot_frame)}function HH(n,e,t,i){n.count+=1,e.confidence>=UH&&(n.high_confidence_count+=1),n.is_last_wall_aerial_shot=!0,n.last_wall_aerial_shot_time=e.time,n.last_wall_aerial_shot_frame=e.frame,n.time_since_last_wall_aerial_shot=Math.max(0,oE(i,e.time)),n.frames_since_last_wall_aerial_shot=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=Qp(n.cumulative_confidence,e.confidence),n.cumulative_takeoff_to_shot_time=Qp(n.cumulative_takeoff_to_shot_time,e.time_since_takeoff),n.cumulative_shot_height=Qp(n.cumulative_shot_height,e.player_position[2]??0)}function VH(n,e){Object.assign(n,e??lE())}function GH(n){const e=cE(n);for(const t of n.frames)e.applyFrame(t);return n}function cE(n){const e=BH(ve(n,"wall_aerial_shot"));let t=0,i=null;const s=new Map;return{applyFrame(a){for(const[r,o]of s)zH(o,a.frame_number,a.time,a.is_live_play&&r===i);if(!a.is_live_play)i=null;else{let r=!1;for(;t[f.frame_number,p])),a=new Map,r={...n,frames:[]},o=KH.flatMap(f=>f.createFrameAccumulator?[f.createFrameAccumulator(r)]:[]),l=Math.max(1,t.materializationChunkSize??$H),c=Math.max(l,t.maxMaterializationChunkSize??WH);let u=-1,d=l;const h=f=>{if(f<=u)return;const p=Math.min(i.length-1,Math.max(f,u+d));for(let g=u+1;g<=p;g+=1){const _=i[g],m=_?ZH(jH(_)):void 0;if(m){for(const v of o)v.applyFrame(m);a.set(m.frame_number,m)}}u=p,d=Math.min(c,i.length,d*XH)};return{get(f){const p=s.get(f);if(p!==void 0)return h(p),a.get(f)}}}function YH(n){return!n||typeof n!="object"?n:{...n}}function jH(n){return{...n,team_zero:{...n.team_zero},team_one:{...n.team_one},players:n.players.map(e=>({...e,player_id:YH(e.player_id)}))}}function ZH(n){return{...n,team_zero:Ql(n.team_zero??{}),team_one:Ql(n.team_one??{}),players:n.players.map(t=>uE(t))}}function ec(n){return n.events?.events??[]}function ve(n,e){return ec(n).filter(t=>t.payload.kind===e).map(t=>t.payload.payload)}const JH=new Set(["is_team_0","name","player_id"]);function Yb(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0}function QH(n){return!n||typeof n!="object"||Array.isArray(n)?!1:Object.keys(n).every(e=>JH.has(e))}function eV(n){return Yb(n.team_zero)&&Yb(n.team_one)&&n.players.every(e=>QH(e))}function tV(n){return new Map(YT(n).frames.map(e=>[e.frame_number,e]))}function nV(n,e,t){const i=n.frames.filter(s=>eV(s)).length;if(i===n.frames.length)return qH(n,e,t);if(i>0)throw new Error("stats timeline frames must be either all compact scaffolds or all materialized snapshots");return tV(n)}function zt(n,e){return n.get(e)??null}const $g=[{stage:"validating",index:1,total:9,label:"Parse replay",start:0,end:.08},{stage:"processing",index:2,total:9,label:"Process replay frames",start:.08,end:.62},{stage:"building-stats",index:3,total:9,label:"Build stats events",start:.62,end:.7},{stage:"serializing-replay",index:4,total:9,label:"Serialize replay data",start:.7,end:.76},{stage:"serializing-stats",index:5,total:9,label:"Serialize stats timeline",start:.76,end:.86},{stage:"normalizing",index:6,total:9,label:"Normalize replay model",start:.86,end:.91},{stage:"decoding-replay",index:7,total:9,label:"Decode replay data",start:.91,end:.94},{stage:"decoding-stats",index:8,total:9,label:"Decode stats chunks",start:.94,end:.96},{stage:"deriving-stats",index:9,total:9,label:"Derive stats snapshots",start:.96,end:1}];function dE(n){return Math.max(0,Math.min(1,n))}function em(n,e,t){if(n!==void 0)return dE((n-e)/(t-e))}function Wg(n){if(n.stage!=="stats-timeline")return n;const e=n.progress;return e===void 0?{...n,stage:"building-stats"}:e<.35?{...n,stage:"building-stats",progress:em(e,0,.35)}:e<.55?{...n,stage:"serializing-replay",progress:em(e,.35,.55)}:{...n,stage:"serializing-stats",progress:em(e,.55,.92)}}function hE(n){const e=Wg(n);return $g.find(t=>t.stage===e.stage)}function iV(){return $g.map(({stage:n,index:e,total:t,label:i})=>({stage:n,index:e,total:t,label:i}))}function sV(n){const e=hE(n);return{stage:e.stage,index:e.index,total:e.total,label:e.label}}function aV(n){const e=Wg(n),t=hE(e);return $g.map(({stage:i,index:s,total:a,label:r})=>{if(st.index)return{stage:i,index:s,total:a,label:r,state:"pending",completion:0,indeterminate:!1};const o=e.progress!==void 0;return{stage:i,index:s,total:a,label:r,state:"active",completion:o?dE(e.progress??0):1,indeterminate:!o}})}function lf(n){const e=Wg(n),t=e.progress===void 0?null:Math.round(e.progress*100);switch(e.stage){case"validating":return"Parsing replay...";case"processing":return t!==null&&e.totalFrames!==void 0?`Processing replay frames... ${t}% (${e.processedFrames??0}/${e.totalFrames})`:"Processing replay frames...";case"building-stats":return t!==null?e.totalFrames!==void 0?`Building stats events... ${t}% (${e.processedFrames??0}/${e.totalFrames})`:`Building stats events... ${t}%`:"Building stats events...";case"serializing-replay":return t!==null?`Serializing replay data... ${t}%`:"Serializing replay data...";case"serializing-stats":return t!==null?`Serializing stats timeline... ${t}%`:"Serializing stats timeline...";case"decoding-replay":return t!==null?`Decoding replay data... ${t}%`:"Decoding replay data...";case"decoding-stats":return t!==null?e.totalChunks!==void 0?`Decoding stats chunks... ${t}% (${e.processedChunks??0}/${e.totalChunks})`:`Decoding stats chunks... ${t}%`:"Decoding stats chunks...";case"deriving-stats":return t!==null?`Deriving stats snapshots... ${t}%`:"Deriving stats snapshots...";case"normalizing":return t!==null?`Normalizing replay model... ${t}%`:"Normalizing replay model...";default:return"Loading replay..."}}function rV(n){return n instanceof Error?n:new Error(String(n))}function Rs(n,e){return JSON.parse(n.decode(new Uint8Array(e)))}async function oV(n,e,t){t?.({stage:"decoding-stats",progress:0});const i=Rs(n,e.configBuffer);t?.({stage:"decoding-stats",progress:.05}),await Ja();const s=Rs(n,e.replayMetaBuffer);t?.({stage:"decoding-stats",progress:.1}),await Ja();const a=Rs(n,e.eventsBuffer),r=Rs(n,e.activitySummaryBuffer),o=Rs(n,e.positioningSummaryBuffer),l=Rs(n,e.accumulationTracksBuffer);t?.({stage:"decoding-stats",progress:.15}),await Ja();const c=[],u=e.frameChunkBuffers.length;for(let d=0;d{let t=!1,i=null;const s=()=>{t||(t=!0,i!==null&&clearTimeout(i),e())};i=setTimeout(s,n),requestAnimationFrame(()=>s())})}async function fE(n,e={}){if(typeof Worker>"u")throw new Error("Replay loading worker is not available in this environment");const t=new Worker(new URL(""+new URL("replayLoader.worker-BOmyAjmY.js",import.meta.url).href,import.meta.url),{type:"module"}),i=n.slice(),s=e.reportEveryNFrames??100;return new Promise((a,r)=>{const o=()=>{t.terminate()};t.onmessage=async c=>{const u=c.data;if(u.type==="progress"){e.onProgress?.(u.progress);return}if(u.type==="error"){o(),r(new Error(u.error));return}o();try{const d=new TextDecoder;e.onProgress?.({stage:"decoding-replay",progress:0}),await Ja();const h=Rs(d,u.replayBuffer);e.onProgress?.({stage:"decoding-replay",progress:.5}),await Ja();const f=Rs(d,u.rawReplayBuffer);e.onProgress?.({stage:"decoding-replay",progress:1}),await Ja();const p=await oV(d,u.statsTimelineParts,e.onProgress),g=nV(p);a({replay:h,raw:f,statsTimeline:p,statsFrameLookup:g})}catch(d){r(rV(d))}},t.onerror=c=>{o(),r(new Error(c.message||"Replay loading worker failed"))};const l={type:"load-replay",bytes:i.buffer,reportEveryNFrames:s};t.postMessage(l,[i.buffer])})}function lV(n){const e=document.createElement("div");e.className="replay-load-modal",e.hidden=!0;const t=document.createElement("div");t.className="replay-load-modal__dialog",t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-labelledby","replay-load-modal-title");const i=document.createElement("p");i.className="replay-load-modal__eyebrow",i.textContent="Replay loading";const s=document.createElement("h2");s.id="replay-load-modal-title",s.className="replay-load-modal__title",s.textContent="Preparing replay pipeline";const a=document.createElement("p");a.className="replay-load-modal__status",a.textContent="Preparing replay...";const r=document.createElement("div");r.className="replay-load-modal__phase-list";const o=new Map;for(const f of iV()){const p=document.createElement("div");p.className="replay-load-modal__phase-row",p.dataset.state="pending";const g=document.createElement("p");g.className="replay-load-modal__phase-label",g.textContent=`${f.index}. ${f.label}`;const _=document.createElement("div");_.className="replay-load-modal__phase-bar";const m=document.createElement("div");m.className="replay-load-modal__phase-fill",m.dataset.indeterminate="false",_.append(m),p.append(g,_),r.append(p),o.set(f.stage,{row:p,fill:m})}const l=document.createElement("p");l.className="replay-load-modal__meta",t.append(i,s,a,r,l),e.append(t),n.append(e);let c="";const u=()=>{for(const{row:f,fill:p}of o.values())f.dataset.state="pending",p.style.width="0%",p.dataset.indeterminate="false"},d=f=>{for(const p of aV(f)){const g=o.get(p.stage);g&&(g.row.dataset.state=p.state,g.fill.dataset.indeterminate=p.indeterminate?"true":"false",g.fill.style.width=`${Math.round(p.completion*100)}%`)}},h=f=>{e.hidden=!f};return{show(f,p="Preparing replay..."){c=f,h(!0),u(),s.textContent="Preparing replay pipeline",a.textContent=p,l.textContent=`Loading ${f}`},update(f){h(!0);const p=sV(f);if(d(f),s.textContent=`Phase ${p.index} of ${p.total}: ${p.label}`,a.textContent=lf(f),f.stage==="processing"&&f.totalFrames!==void 0){l.textContent=`${f.processedFrames??0}/${f.totalFrames} frames`;return}if(f.stage==="decoding-stats"&&f.totalChunks!==void 0){l.textContent=`${f.processedChunks??0}/${f.totalChunks} chunks`;return}l.textContent=c?`Loading ${c}`:""},hide(){h(!1)},destroy(){e.remove()}}}const cV=["free","follow"];function pE(n){return n.useReplayBallCam??!1?"player":n.ballCamEnabled?"on":"off"}function jb(n){return n.useReplayBallCam?"player":n.ballCam===!0?"on":n.ballCam===!1?"off":"player"}const mE={fov:110,height:100,pitch:-4,distance:270,stiffness:0,swivelSpeed:1,transitionSpeed:1};class Xg{constructor(e){this.options=e}lastFreeCameraPreset=null;get freeCameraPreset(){return this.lastFreeCameraPreset}set freeCameraPreset(e){this.lastFreeCameraPreset=e}ballCamModeValue="player";get ballCamMode(){return this.ballCamModeValue}autoPossessionEnabledValue=!1;get autoPossessionEnabled(){return this.autoPossessionEnabledValue}static ballCamEnabledForMode(e){return e==="player"?null:e==="on"}followPlayerWithReplayCamera(e,t={}){const i=this.options.getReplayPlayer();i&&(t.preserveAutoPossession||this.setAutoPossessionEnabled(!1,{requestConfigSync:!1}),i.setAttachedPlayer(e),i.setCameraViewMode("follow"),t.usePlayerCameraSettings!==!1&&i.setCustomCameraSettings(null),this.setBallCamMode(t.ballCam??"player"),this.lastFreeCameraPreset=null,t.requestConfigSync!==!1&&this.options.requestConfigSync())}setAutoPossessionEnabled(e,t={}){if(this.autoPossessionEnabledValue===e){this.renderAutoPossessionButton();return}this.autoPossessionEnabledValue=e,this.renderAutoPossessionButton(),t.notify!==!1&&this.options.onAutoPossessionChange?.(e),t.requestConfigSync!==!1&&this.options.requestConfigSync()}renderBallCamButtons(){const{ballCamOffButton:e,ballCamOnButton:t,ballCamPlayerButton:i}=this.options.elements,s=[["off",e],["on",t],["player",i]];for(const[a,r]of s){const o=a===this.ballCamModeValue;r.dataset.active=o?"true":"false",r.setAttribute("aria-pressed",o?"true":"false")}}renderAutoPossessionButton(){this.options.elements.cameraViewAutoPossession.checked=this.autoPossessionEnabledValue}disableAutoPossessionForManualCameraControl(){this.setAutoPossessionEnabled(!1,{requestConfigSync:!1})}setBallCamMode(e){this.ballCamModeValue=e,this.options.getReplayPlayer()?.setBallCamEnabled(Xg.ballCamEnabledForMode(e)),this.renderBallCamButtons()}get nameplateLiftUu(){const e=Number(this.options.elements.nameplateLift.value);return Number.isFinite(e)?e:Wm}applyNameplateLiftUu(e){const{nameplateLift:t,nameplateLiftReadout:i}=this.options.elements,s=e??Wm;t.value=`${s}`,i.textContent=qn(s,"",0)}installEventListeners(e){const{elements:t}=this.options;t.usePlayerCameraSettings.addEventListener("change",()=>{const s=t.usePlayerCameraSettings.checked;t.cameraSettingsControls.hidden=s,this.options.getReplayPlayer()?.setCustomCameraSettings(s?null:this.readCustomCameraSettings()),this.options.requestConfigSync()},{signal:e});for(const s of[t.customCameraFov,t.customCameraHeight,t.customCameraPitch,t.customCameraDistance,t.customCameraStiffness,t.customCameraSwivelSpeed,t.customCameraTransitionSpeed])s.addEventListener("input",()=>{const a=this.readCustomCameraSettings();this.syncCustomCameraSettingControls(a),this.options.getReplayPlayer()?.setCustomCameraSettings(a),this.options.requestConfigSync()},{signal:e});t.attachedPlayer.addEventListener("change",()=>{const s=this.options.getReplayPlayer(),a=t.attachedPlayer.value||null;this.disableAutoPossessionForManualCameraControl(),s?.setAttachedPlayer(a),a&&(s?.setCustomCameraSettings(null),this.setBallCamMode("player")),this.lastFreeCameraPreset=null,this.options.requestConfigSync()},{signal:e}),t.cameraViewFreeButton.addEventListener("click",()=>{this.options.getReplayPlayer()?.setCameraViewMode("free"),this.disableAutoPossessionForManualCameraControl(),this.lastFreeCameraPreset=null,this.options.requestConfigSync()},{signal:e}),t.cameraViewFollowButton.addEventListener("click",()=>{const s=this.options.getReplayPlayer();this.disableAutoPossessionForManualCameraControl(),s?.setCameraViewMode("follow"),s?.getState().attachedPlayerId&&(s.setCustomCameraSettings(null),this.setBallCamMode("player")),this.lastFreeCameraPreset=null,this.options.requestConfigSync()},{signal:e}),t.cameraViewOverheadButton.addEventListener("click",()=>{this.options.getReplayPlayer()?.setFreeCameraPreset("overhead"),this.disableAutoPossessionForManualCameraControl(),this.lastFreeCameraPreset="overhead",this.options.requestConfigSync()},{signal:e}),t.cameraViewSideButton.addEventListener("click",()=>{this.options.getReplayPlayer()?.setFreeCameraPreset("side"),this.disableAutoPossessionForManualCameraControl(),this.lastFreeCameraPreset="side",this.options.requestConfigSync()},{signal:e});const i=[["off",t.ballCamOffButton],["on",t.ballCamOnButton],["player",t.ballCamPlayerButton]];for(const[s,a]of i)a.addEventListener("click",()=>{this.setBallCamMode(s),this.options.requestConfigSync()},{signal:e});t.cameraViewAutoPossession.addEventListener("change",()=>{this.setAutoPossessionEnabled(t.cameraViewAutoPossession.checked)},{signal:e}),t.nameplateLift.addEventListener("input",()=>{t.nameplateLiftReadout.textContent=qn(this.nameplateLiftUu,"",0),this.options.requestConfigSync()},{signal:e})}setTransportEnabled(e,t){this.options.elements.attachedPlayer.disabled=!e,this.syncModeButtons(e?t:void 0)}syncState(e){const{elements:t}=this.options;t.usePlayerCameraSettings.checked=e.customCameraSettings===null,t.cameraSettingsControls.hidden=t.usePlayerCameraSettings.checked,this.syncCustomCameraSettingControls(e.customCameraSettings??this.getFallbackCameraSettings()),this.ballCamModeValue=pE(e),this.renderBallCamButtons(),t.attachedPlayer.value=e.attachedPlayerId??"",this.syncAvailability(e),this.renderProfile(e)}syncAvailability(e){this.syncModeButtons(e);const i=this.options.getReplayPlayer()!==null&&e?.cameraViewMode==="follow"&&(e.attachedPlayerId??null)!==null;this.options.elements.usePlayerCameraSettings.disabled=!i,this.setCameraSettingControlsEnabled(i&&e?.customCameraSettings!==null),this.options.elements.ballCamOffButton.disabled=!i,this.options.elements.ballCamOnButton.disabled=!i,this.options.elements.ballCamPlayerButton.disabled=!i,this.renderBallCamButtons()}syncModeButtons(e){const t=e?.cameraViewMode??"free",i=this.options.getReplayPlayer()!==null&&e!==void 0,s=(e?.attachedPlayerId??null)!==null;for(const l of cV){const c=this.getCameraViewButton(l);c.disabled=!i||l==="follow"&&!s;const u=l===t;c.dataset.active=u?"true":"false",c.setAttribute("aria-pressed",u?"true":"false")}const{cameraViewOverheadButton:a,cameraViewSideButton:r}=this.options.elements,{cameraViewAutoPossession:o}=this.options.elements;a.disabled=!i,r.disabled=!i,o.disabled=!i,a.dataset.active="false",r.dataset.active="false",this.renderAutoPossessionButton(),a.setAttribute("aria-pressed","false"),r.setAttribute("aria-pressed","false")}populateAttachedPlayerOptions(e){const{attachedPlayer:t}=this.options.elements;t.replaceChildren(),t.append(new Option("Free camera",""));for(const i of e)t.append(new Option(`${i.name} (${i.isTeamZero?"Blue":"Orange"})`,i.id))}renderProfile(e){const t=this.options.elements,i=this.options.getReplayPlayer(),s=e?.attachedPlayerId??null;if(!i||e?.cameraViewMode!=="follow"||s===null){this.renderEmptyProfile("Free camera");return}const a=i.replay.players.find(o=>o.id===s);if(!a){this.renderEmptyProfile("Unknown");return}const r=this.getEffectiveCameraSettings(e);t.cameraProfileReadout.textContent=e.customCameraSettings===null?a.name:`${a.name} custom`,t.cameraFovReadout.textContent=qn(r.fov,"",0),t.cameraHeightReadout.textContent=qn(r.height,"",0),t.cameraPitchReadout.textContent=qn(r.pitch,"",0),t.cameraBaseDistanceReadout.textContent=qn(r.distance,"",0),t.cameraStiffnessReadout.textContent=qn(r.stiffness,"",2)}getFallbackCameraSettings(){return mE}getAttachedPlayerCameraSettings(e){const t=this.options.getReplayPlayer();return!t||e===null?null:t.replay.players.find(i=>i.id===e)?.cameraSettings??null}getEffectiveCameraSettings(e){return{...this.getFallbackCameraSettings(),...this.getAttachedPlayerCameraSettings(e.attachedPlayerId)??{},...e.customCameraSettings??{}}}readCustomCameraSettings(){const e=this.options.elements;return{fov:Number(e.customCameraFov.value),height:Number(e.customCameraHeight.value),pitch:Number(e.customCameraPitch.value),distance:Number(e.customCameraDistance.value),stiffness:Number(e.customCameraStiffness.value),swivelSpeed:Number(e.customCameraSwivelSpeed.value),transitionSpeed:Number(e.customCameraTransitionSpeed.value)}}setCameraSettingControlsEnabled(e){const t=this.options.elements;t.cameraSettingsControls.hidden=t.usePlayerCameraSettings.checked,t.customCameraFov.disabled=!e,t.customCameraHeight.disabled=!e,t.customCameraPitch.disabled=!e,t.customCameraDistance.disabled=!e,t.customCameraStiffness.disabled=!e,t.customCameraSwivelSpeed.disabled=!e,t.customCameraTransitionSpeed.disabled=!e}syncCustomCameraSettingControls(e){const t=this.options.elements,i=this.getFallbackCameraSettings(),s=e.fov??i.fov,a=e.height??i.height,r=e.pitch??i.pitch,o=e.distance??i.distance,l=e.stiffness??i.stiffness,c=e.swivelSpeed??i.swivelSpeed,u=e.transitionSpeed??i.transitionSpeed;t.customCameraFov.value=`${s}`,t.customCameraHeight.value=`${a}`,t.customCameraPitch.value=`${r}`,t.customCameraDistance.value=`${o}`,t.customCameraStiffness.value=`${l}`,t.customCameraSwivelSpeed.value=`${c}`,t.customCameraTransitionSpeed.value=`${u}`,t.customCameraFovReadout.textContent=qn(s,"",0),t.customCameraHeightReadout.textContent=qn(a,"",0),t.customCameraPitchReadout.textContent=qn(r,"",0),t.customCameraDistanceReadout.textContent=qn(o,"",0),t.customCameraStiffnessReadout.textContent=qn(l,"",2),t.customCameraSwivelSpeedReadout.textContent=qn(c,"",1),t.customCameraTransitionSpeedReadout.textContent=qn(u,"",2)}getCameraViewButton(e){switch(e){case"free":return this.options.elements.cameraViewFreeButton;case"follow":return this.options.elements.cameraViewFollowButton}}renderEmptyProfile(e){const t=this.options.elements;t.cameraProfileReadout.textContent=e,t.cameraFovReadout.textContent="--",t.cameraHeightReadout.textContent="--",t.cameraPitchReadout.textContent="--",t.cameraBaseDistanceReadout.textContent="--",t.cameraStiffnessReadout.textContent="--"}}function qn(n,e="",t=0){return n===void 0||Number.isNaN(n)?"--":`${n.toFixed(t)}${e}`}function uV(n){return new Xg(n)}const Zb="subtr-actor-touch-overlay-styles",Kg=5882879,qg=16761180,Jb=120,Qb=4,dV=196,tm=24,ex=210,tx=5,hV=.1,fV=48,pV=["team","intention","kind","height_band","surface","dodge_state","flag"],mV=[{label:"Blue team",color:Kg},{label:"Orange team",color:qg}],_E=[{label:"Shot",color:16711880},{label:"Save",color:58998},{label:"Clear",color:16764928},{label:"Boom",color:16020150},{label:"Pass",color:47103},{label:"Control",color:0},{label:"Advance",color:16486972}],id=[{label:"Control",color:0},{label:"Medium hit",color:16436245},{label:"Hard hit",color:16735596}],sd=[{label:"Ground",color:10741301},{label:"Low air",color:3718648},{label:"High air",color:8490232}],gE=[{label:"Ground",color:8702998},{label:"Air",color:6333946},{label:"Wall",color:16347926}],h_=[{label:"No dodge",color:9741240},{label:"Dodge",color:15235577}],f_=[{label:"First touch",color:16777215},{label:"Contested",color:15680580}],_V=[{title:"Team",entries:mV},{title:"Intention",entries:_E},{title:"Hit strength",entries:id},{title:"Height",entries:sd},{title:"Surface",entries:gE},{title:"Dodge",entries:h_},{title:"Flags",entries:f_}];function gc(n){return Object.fromEntries(n.map(e=>[e.label.toLowerCase().replaceAll(" ","_"),e.color]))}const yE=gc(_E),vE={...gc(id),medium_hit:id[1].color,hard_hit:id[2].color},bE={...gc(sd),low_air:sd[1].color,high_air:sd[2].color},xE=gc(gE),wE={...gc(h_),no_dodge:h_[0].color},p_={first_touch:f_[0].color,contested:f_[1].color},Gi=10134961;function jn(n,e){const t=n.tags;if(!Array.isArray(t))return null;const i=t.find(s=>s.group===e);return i?i.value:null}function SE(n){return jn(n,"possession")??jn(n,"action")}function At(n){const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function nm(n,e){return Math.max(0,n-e)}function ad(n){return n==="team"||n==="intention"||n==="kind"||n==="height_band"||n==="surface"||n==="dodge_state"||n==="flag"}function po(n){const e=Array.isArray(n)?n:n?[n]:["team"],t=new Set,i=[];for(const s of e)ad(s)&&!t.has(s)&&(t.add(s),i.push(s));return i.length>0?i:["team"]}function TE(n){return n[n.length-1]??"team"}function gV(n,e,t){const i=yV(n,TE(t)),s=i?` · ${i.replaceAll("_"," ")}`:"";if(e==="markers")return`${n.playerName}${s}`;const a=Math.round(n.totalBallAdvanceDistance),r=Math.round(n.totalBallRetreatDistance);return a>0&&r>0?`${n.playerName} +${a} / -${r} uu${s}`:r>0?`${n.playerName} -${r} uu${s}`:`${n.playerName} +${a} uu${s}`}function yV(n,e){return e==="intention"?n.intention:e==="kind"?n.kind:e==="height_band"?n.heightBand:e==="surface"?n.surface:e==="dodge_state"?n.dodgeState:e==="flag"?n.contested?"contested":n.firstTouch?"first_touch":null:null}function vV(n){return n.split("_").filter(Boolean).map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1)}`).join(" ")}function ol(n,e,t){return typeof e!="string"||e.length===0?null:{key:n,value:e,label:vV(e),color:t[e]??Gi}}function nx(n,e,t){return e!==!0?null:{key:n,value:"true",label:t,color:p_[n]??Gi}}function bV(n){const e=jn(n,"reception")==="first_touch",t=jn(n,"contested")!=null;return[ol("intention",SE(n),yE),ol("kind",jn(n,"kind"),vE),ol("height_band",jn(n,"height_band"),bE),ol("surface",jn(n,"surface"),xE),ol("dodge_state",jn(n,"dodge_state"),wE),nx("first_touch",e,"First touch"),nx("contested",t,"Contested")].filter(i=>i!=null)}function ME(n,e){return e==="intention"?yE[n.intention??""]??Gi:e==="kind"?vE[n.kind??""]??Gi:e==="height_band"?bE[n.heightBand??""]??Gi:e==="surface"?xE[n.surface??""]??Gi:e==="dodge_state"?wE[n.dodgeState??""]??Gi:e==="flag"?n.contested?p_.contested??Gi:n.firstTouch?p_.first_touch??Gi:Gi:n.isTeamZero?Kg:qg}function xV(n,e){return(e.length>0?e:["team"]).map(i=>ME(n,i))}function EE(n,e){const t=[],i=[...ve(n,"touch")].sort((s,a)=>s.frame!==a.frame?s.frame-a.frame:s.time!==a.time?s.time-a.time:0);for(const s of i){const a=At(s.player),r=e.ballFrames[s.frame]?.position;if(!r)continue;const o=s.ball_movement,c=(o?e.ballFrames[o.end_frame]?.position:null)??r,u=t.length,d=bV(s);t.push({id:`touch-stat:${s.frame}:${a}:${u+1}`,time:e.frames[s.frame]?.time??s.time,frame:s.frame,isTeamZero:s.is_team_0,playerId:a,playerName:e.players.find(h=>h.id===a)?.name??a,kind:jn(s,"kind"),intention:SE(s),heightBand:jn(s,"height_band"),surface:jn(s,"surface"),dodgeState:jn(s,"dodge_state"),firstTouch:jn(s,"reception")==="first_touch",contested:jn(s,"contested")!=null,classifications:d,position:{x:r.x,y:r.y,z:r.z},endPosition:{x:c.x,y:c.y,z:c.z},totalBallTravelDistance:o?nm(o.travel_distance,0):0,totalBallAdvanceDistance:o?nm(o.advance_distance,0):0,totalBallRetreatDistance:o?nm(o.retreat_distance,0):0})}return t}function wV(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function SV(){if(document.getElementById(Zb))return;const n=document.createElement("style");n.id=Zb,n.textContent=` .sap-touch-overlay-root { position: absolute; inset: 0; @@ -5504,45 +5569,45 @@ void main() { border-color: rgba(255, 193, 92, 0.5); background: rgba(76, 41, 7, 0.84); } - `,document.head.append(n)}function KH(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}function gE(n){return[n.line.material,n.cone.material].flatMap(e=>Array.isArray(e)?e:[e])}function Yb(n,e){for(const t of gE(n))t.transparent=!0,t.opacity=e,t.depthWrite=!1,t.depthTest=!1}function jb(n){n.removeFromParent(),n.line.geometry.dispose(),n.cone.geometry.dispose();for(const e of gE(n))e.dispose()}function l_(n){for(const e of n.ringSegments){e.removeFromParent(),e.geometry.dispose();const t=Array.isArray(e.material)?e.material:[e.material];for(const i of t)i.dispose()}n.ringSegments=[],n.ringColorsKey=""}function qH(n,e,t){const i=new ni(e,t,48,1),s=new Ye({color:n,transparent:!0,opacity:.7,side:ct,depthWrite:!1,depthTest:!1}),a=new we(i,s);return a.rotation.x=-Math.PI/2,a.renderOrder=40,a}function YH(n,e){const t=e.length>0?e:[Vi],i=t.join("|");if(n.ringColorsKey===i)return;l_(n);const s=t.length,a=Wb*Math.max(0,s-1),r=(kH-$b-a)/s,o=t.map((l,c)=>{const u=$b+c*(r+Wb);return qH(l,u,u+r)});for(const l of o)n.ring.add(l),n.ringSegments.push(l);n.ringColorsKey=i}function jH(n,e){for(const t of n.ringSegments){const i=Array.isArray(t.material)?t.material:[t.material];for(const s of i)s.opacity=e}}class ZH{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;arrowStart=new S;arrowEnd=new S;arrowDirection=new S;labelOffset=new S(0,0,Xb);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=Kb;mode="markers";colorModes=["team"];constructor(e,t,i,s,a){XH(),this.scene=e,this.container=t,this.decaySeconds=Math.max(.1,a?.decaySeconds??Kb),this.mode=a?.mode??"markers",this.colorModes=ho(a?.colorModes??a?.colorMode),this.labelOffset.set(0,0,Xb),this.markers=_E(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="touch-event-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-touch-overlay-root",this.container.append(this.labelRoot)}getDecaySeconds(){return this.decaySeconds}setDecaySeconds(e){this.decaySeconds=Math.max(.1,e)}getMode(){return this.mode}setMode(e){this.mode=e}getColorModes(){return[...this.colorModes]}setColorMode(e){this.setColorModes([e])}setColorModes(e){this.colorModes=ho([...e])}update(e){const t=WH(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.ring.removeFromParent(),l_(a),jb(a.arrow),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.1+.6*r,c=.95+(1-r)*.28,u=pE(this.colorModes),d=mE(s,u),h=$H(s,this.colorModes);YH(o,h),jH(o,l),o.arrow.setColor(d),o.ring.position.set(s.position.x,s.position.y,s.position.z+qp),o.ring.scale.setScalar(c),o.label.textContent=zH(s,this.mode,this.colorModes),o.label.classList.toggle("sap-touch-overlay-label-advancement",this.mode==="advancement");const f=u==="team";o.label.classList.toggle("sap-touch-overlay-label-blue",f&&s.isTeamZero),o.label.classList.toggle("sap-touch-overlay-label-orange",f&&!s.isTeamZero),o.label.style.borderColor=f?"":`#${d.toString(16).padStart(6,"0")}cc`,o.label.style.background=f?"":`#${d.toString(16).padStart(6,"0")}66`,this.updateArrow(o,s,l),this.worldPosition.set(s.position.x,s.position.y,s.position.z),this.worldPosition.add(this.labelOffset),this.scene.replayRoot.localToWorld(this.worldPosition),KH(this.worldPosition,this.scene.camera,this.container,this.projectedPosition)?(o.label.hidden=!1,o.label.style.opacity=`${.22+.78*r}`,o.label.style.transform=`translate(${this.projectedPosition.x.toFixed(1)}px, ${this.projectedPosition.y.toFixed(1)}px) translate(-50%, -100%)`):o.label.hidden=!0}}dispose(){for(const e of this.views.values())e.ring.removeFromParent(),l_(e),jb(e.arrow),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition,this.changedContainerPosition=!1)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=new Mt;i.renderOrder=40,this.group.add(i);const s=new Tg(new S(0,1,0),new S,1,e.isTeamZero?zg:Hg,1,1);s.visible=!1,s.renderOrder=45,s.line.renderOrder=45,s.cone.renderOrder=45,Yb(s,.7),this.group.add(s);const a=document.createElement("div");a.className=`sap-touch-overlay-label ${e.isTeamZero?"sap-touch-overlay-label-blue":"sap-touch-overlay-label-orange"}`,a.textContent=e.playerName,a.hidden=!0,this.labelRoot.append(a);const r={marker:e,ring:i,ringSegments:[],ringColorsKey:"",arrow:s,label:a};return this.views.set(e.id,r),r}updateArrow(e,t,i){if(this.mode!=="advancement"||t.totalBallTravelDistance<=OH){e.arrow.visible=!1;return}this.arrowStart.set(t.position.x,t.position.y,t.position.z+qp*2),this.arrowEnd.set(t.endPosition.x,t.endPosition.y,t.endPosition.z+qp*2),this.arrowDirection.copy(this.arrowEnd).sub(this.arrowStart);const s=this.arrowDirection.length();if(s0&&r>0)return a/r}const t=n.frames[0],i=n.frames.at(-1);if(t&&i){const s=i.frame_number-t.frame_number,a=i.time-t.time;if(s>0&&a>0)return s/a}return tV}function iV(n,e={}){if(!n)return[];const t=e.preRollSeconds??JH,i=e.minPossessionSeconds??QH,s=e.samePlayerBridgeSeconds??eV,a=ve(n,"player_possession").map(d=>({playerId:At(d.player_id),startFrame:Math.max(0,Math.trunc(al(d.start_frame))),endFrame:Math.max(0,Math.trunc(al(d.end_frame))),startTime:al(d.start_time),endTime:al(d.end_time),duration:al(d.duration),sustainedControl:d.sustained_control})).filter(d=>d.endFrame>d.startFrame&&(d.sustainedControl||d.duration>=i)).sort((d,h)=>d.startFrame-h.startFrame||d.endFrame-h.endFrame),r=nV(n,a),o=Math.max(0,Math.round(t*r)),l=Math.max(0,Math.round(s*r)),c=[];let u=null;for(const d of a){let h=Math.max(0,d.startFrame-o);u&&u.playerId!==d.playerId&&(h=Math.max(h,u.endFrame));const f=c.at(-1);if(f&&f.playerId===d.playerId&&h<=f.endFrame+l){c[c.length-1]={...f,endFrame:Math.max(f.endFrame,d.endFrame),possessionEndFrame:Math.max(f.possessionEndFrame,d.endFrame)},u=d;continue}c.push({playerId:d.playerId,startFrame:h,endFrame:d.endFrame,possessionStartFrame:d.startFrame,possessionEndFrame:d.endFrame}),u=d}return c.map((d,h)=>({...d,endFrame:c[h+1]?.startFrame??Number.POSITIVE_INFINITY}))}function sV(n,e){const t=Math.max(0,Math.trunc(e));return n.find(s=>t>=s.startFrame&&tthis.update(i))))}reset(){this.unsubscribeBeforeRender?.(),this.unsubscribeBeforeRender=null,this.sourcePlayer=null,this.sourceTimeline=null,this.spans=[]}syncCurrentFrame(){const e=this.options.getReplayPlayer();if(!e)return;const t=e.getState();this.update({frameIndex:t.frameIndex,nextFrameIndex:t.frameIndex,alpha:0,currentTime:t.currentTime})}update(e){const t=this.options.getCameraControlsController(),i=this.options.getReplayPlayer();if(!t?.autoPossessionEnabled||!i)return;const s=sV(this.spans,e.frameIndex);if(!s||!i.replay.players.some(r=>r.id===s))return;const a=i.getState();a.cameraViewMode==="follow"&&a.attachedPlayerId===s||t.followPlayerWithReplayCamera(s,{ballCam:"player",preserveAutoPossession:!0,requestConfigSync:!1,usePlayerCameraSettings:!1})}}function rV(n){return new aV(n)}const oV=236,Zl=4120,lV=2300,cV=16185075,uV=.18,dV=1118481,td=5882879,nd=16761180,hV=.55,jp=.12,Zb=.28,fV=3,pV=4,Jb=5,Qb=2,mV=6,_V=856343,gV=.42,yV=18,vV=.24,bV=10,ex=220,xV=200,yE=140,wV=220,SV=100,TV=120;function MV(n){const e=xV/2;if(n){const s=-Zl+ex,a=-e;return{minX:s,maxX:a,centerX:(s+a)/2,width:a-s}}const t=e,i=Zl-ex;return{minX:t,maxX:i,centerX:(t+i)/2,width:i-t}}function EV(n,e,t){if(n.length<2)return[];const i=Math.min(...n),s=Math.max(...n),a=s-i,r=e?-1:1,o=-r;return a<=t?[{kind:"other",centerY:(i+s)/2,halfDepth:Math.max(t-a/2,t*.35),directions:[r,o]}]:[{kind:"back",centerY:e?i:s,halfDepth:t,directions:[r]},{kind:"forward",centerY:e?s:i,halfDepth:t,directions:[o]}]}function CV(n,e){const t=new Ns;return t.moveTo(0,e/2),t.lineTo(n/2,-e/2),t.lineTo(-n/2,-e/2),t.closePath(),new ur(t)}function tx(n){const e=SV*n,t=new Ye({color:dV,transparent:!0,opacity:.9,side:ct,depthWrite:!1,depthTest:!1}),i=new Mt;i.visible=!1;const s=new Dn(yE*.55*n,1),a=new we(s,t);a.position.z=Jb,a.renderOrder=22,i.add(a);const r=CV(TV*n,e),o=new we(r,t);return o.position.z=Jb,o.renderOrder=23,i.add(o),{group:i,shaftGeom:s,shaftMesh:a,headGeom:r,headMesh:o,material:t,headLength:e}}function Zp(n,e,t,i){const s=Math.max(t-n.headLength,n.headLength*.2);n.group.position.x=e,n.group.rotation.z=i>0?0:Math.PI,n.shaftMesh.scale.y=s,n.shaftMesh.position.y=-n.headLength/2,n.headMesh.position.y=t/2-n.headLength/2,n.group.visible=!0}function th(n){n.group.visible=!1}function qr(n,e){const t=new Mt;t.visible=!1;const i=new Ye({color:cV,transparent:!0,opacity:uV,side:ct,depthWrite:!1,depthTest:!1}),s=new Dn(1,1),a=new we(s,i);a.position.z=fV,a.renderOrder=20,t.add(a);const r=new Ye({color:e,transparent:!0,opacity:hV,side:ct,depthWrite:!1,depthTest:!1}),o=new Dn(1,1),l=new we(o,r);l.position.z=pV,l.renderOrder=21,t.add(l);const c=tx(n),u=tx(n);return t.add(c.group),t.add(u.group),{group:t,floorGeom:s,floorMesh:a,floorMaterial:i,stripeGeom:o,stripeMesh:l,stripeMaterial:r,primaryMarker:c,secondaryMarker:u}}function AV(n){n.group.visible=!1,th(n.primaryMarker),th(n.secondaryMarker)}function RV(n,e,t,i){const s=e.halfDepth*2*i,a=Zl*2*i,r=t.width*i,o=t.centerX*i,l=yE*i,c=Math.max(s-32*i,n.primaryMarker.headLength*1.15),u=Math.min(c,Math.max(wV*i,s*.6));if(n.group.position.y=e.centerY*i,n.floorMesh.position.x=0,n.floorMesh.scale.set(a,s,1),n.stripeMesh.position.x=o,n.stripeMesh.scale.set(l,s,1),th(n.primaryMarker),th(n.secondaryMarker),e.directions.length===1)Zp(n.primaryMarker,o,u,e.directions[0]);else{const d=r*.18;Zp(n.primaryMarker,o-d,u,e.directions[0]),Zp(n.secondaryMarker,o+d,u,e.directions[1])}n.group.visible=!0}function nx(n){n.group.removeFromParent(),n.shaftGeom.dispose(),n.headGeom.dispose(),n.material.dispose()}class PV{replay;blueBack;blueForward;blueOther;orangeBack;orangeForward;orangeOther;constructor(e,t,i){this.replay=t,this.blueBack=qr(i,td),this.blueForward=qr(i,td),this.blueOther=qr(i,td),this.orangeBack=qr(i,nd),this.orangeForward=qr(i,nd),this.orangeOther=qr(i,nd);for(const s of this.getZones())e.add(s.group)}update(e,t){const{frameIndex:i}=e,s=oV;for(const a of[!0,!1]){const r=this.replay.players.filter(d=>d.isTeamZero===a).length,o=[];for(const d of this.replay.players){if(d.isTeamZero!==a)continue;const h=d.frames[i];h?.position&&o.push(h.position.y)}const l=MV(a),c=this.getTeamZones(a);for(const d of c.values())AV(d);if(r<2||o.length!==r)continue;const u=EV(o,a,s);for(const d of u){const h=c.get(d.kind);h&&RV(h,d,l,t)}}}dispose(){for(const e of this.getZones())e.group.removeFromParent(),e.floorGeom.dispose(),e.floorMaterial.dispose(),e.stripeGeom.dispose(),e.stripeMaterial.dispose(),nx(e.primaryMarker),nx(e.secondaryMarker)}getTeamZones(e){return e?new Map([["back",this.blueBack],["forward",this.blueForward],["other",this.blueOther]]):new Map([["back",this.orangeBack],["forward",this.orangeForward],["other",this.orangeOther]])}getZones(){return[this.blueBack,this.blueForward,this.blueOther,this.orangeBack,this.orangeForward,this.orangeOther]}}function IV(n){return n==null||Number.isNaN(n)?null:n<0?"team-zero":"team-one"}class LV{group;teamZeroSide;teamOneSide;constructor(e,t){this.group=new Mt,this.teamZeroSide=this.createHalfFieldSide(td),this.teamOneSide=this.createHalfFieldSide(nd);const i=Zl*t,s=5120*t;this.teamZeroSide.mesh.position.set(0,-s/2,Qb),this.teamZeroSide.mesh.scale.set(i*2,s,1),this.teamOneSide.mesh.position.set(0,s/2,Qb),this.teamOneSide.mesh.scale.set(i*2,s,1),this.group.add(this.teamZeroSide.mesh),this.group.add(this.teamOneSide.mesh),e.add(this.group)}update(e){const t=IV(e);this.teamZeroSide.material.opacity=t==="team-zero"?Zb:jp,this.teamOneSide.material.opacity=t==="team-one"?Zb:jp}dispose(){this.group.removeFromParent(),this.teamZeroSide.mesh.geometry.dispose(),this.teamZeroSide.material.dispose(),this.teamOneSide.mesh.geometry.dispose(),this.teamOneSide.material.dispose()}createHalfFieldSide(e){const t=new Dn(1,1),i=new Ye({color:e,transparent:!0,opacity:jp,side:ct,depthWrite:!1,depthTest:!1}),s=new we(t,i);return s.renderOrder=18,{mesh:s,material:i}}}function DV(n,e){const t=new Mt,i=Zl*2*e,s=(a,r,o)=>{const l=new Dn(i,r*e),c=new Ye({color:_V,transparent:!0,opacity:o,side:ct,depthWrite:!1,depthTest:!1}),u=new we(l,c);return u.position.set(0,a,mV),u.renderOrder=24,u};for(const a of[-1,1]){const r=a*lV*e;t.add(s(r,yV,gV))}return t.add(s(0,bV,vV)),n.add(t),t}function cn(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function c_(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function Oi(n,e){return`
${n}${e}
`}function kV(n,e){return` - ${Oi("50s",cn(n?.count))} - ${Oi("Blue wins",`${cn(n?.wins)} (${c_(n?.wins,n?.count)})`)} - ${Oi("Orange wins",`${cn(n?.losses)} (${c_(n?.losses,n?.count)})`)} - ${Oi("Neutral",cn(n?.neutral_outcomes))} - ${Oi("Blue poss after",cn(n?.possession_after_count))} - ${Oi("Orange poss after",cn(n?.opponent_possession_after_count))} - ${Oi("Kickoff 50s",cn(n?.kickoff_count))} - ${Oi("Blue kickoff wins",cn(n?.kickoff_wins))} - ${Oi("Orange kickoff wins",cn(n?.kickoff_losses))} - ${Oi("Blue kickoff poss",cn(n?.kickoff_possession_after_count))} - ${Oi("Orange kickoff poss",cn(n?.kickoff_opponent_possession_after_count))} - `}function ix(n){return` + `,document.head.append(n)}function TV(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}function CE(n){return[n.line.material,n.cone.material].flatMap(e=>Array.isArray(e)?e:[e])}function ix(n,e){for(const t of CE(n))t.transparent=!0,t.opacity=e,t.depthWrite=!1,t.depthTest=!1}function sx(n){n.removeFromParent(),n.line.geometry.dispose(),n.cone.geometry.dispose();for(const e of CE(n))e.dispose()}function m_(n){for(const e of n.ringSegments){e.removeFromParent(),e.geometry.dispose();const t=Array.isArray(e.material)?e.material:[e.material];for(const i of t)i.dispose()}n.ringSegments=[],n.ringColorsKey=""}function MV(n,e,t){const i=new ni(e,t,48,1),s=new Ye({color:n,transparent:!0,opacity:.7,side:ct,depthWrite:!1,depthTest:!1}),a=new we(i,s);return a.rotation.x=-Math.PI/2,a.renderOrder=40,a}function EV(n,e){const t=e.length>0?e:[Gi],i=t.join("|");if(n.ringColorsKey===i)return;m_(n);const s=t.length,a=Qb*Math.max(0,s-1),r=(dV-Jb-a)/s,o=t.map((l,c)=>{const u=Jb+c*(r+Qb);return MV(l,u,u+r)});for(const l of o)n.ring.add(l),n.ringSegments.push(l);n.ringColorsKey=i}function CV(n,e){for(const t of n.ringSegments){const i=Array.isArray(t.material)?t.material:[t.material];for(const s of i)s.opacity=e}}class AV{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;arrowStart=new S;arrowEnd=new S;arrowDirection=new S;labelOffset=new S(0,0,ex);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=tx;mode="markers";colorModes=["team"];constructor(e,t,i,s,a){SV(),this.scene=e,this.container=t,this.decaySeconds=Math.max(.1,a?.decaySeconds??tx),this.mode=a?.mode??"markers",this.colorModes=po(a?.colorModes??a?.colorMode),this.labelOffset.set(0,0,ex),this.markers=EE(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="touch-event-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-touch-overlay-root",this.container.append(this.labelRoot)}getDecaySeconds(){return this.decaySeconds}setDecaySeconds(e){this.decaySeconds=Math.max(.1,e)}getMode(){return this.mode}setMode(e){this.mode=e}getColorModes(){return[...this.colorModes]}setColorMode(e){this.setColorModes([e])}setColorModes(e){this.colorModes=po([...e])}update(e){const t=wV(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.ring.removeFromParent(),m_(a),sx(a.arrow),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.1+.6*r,c=.95+(1-r)*.28,u=TE(this.colorModes),d=ME(s,u),h=xV(s,this.colorModes);EV(o,h),CV(o,l),o.arrow.setColor(d),o.ring.position.set(s.position.x,s.position.y,s.position.z+tm),o.ring.scale.setScalar(c),o.label.textContent=gV(s,this.mode,this.colorModes),o.label.classList.toggle("sap-touch-overlay-label-advancement",this.mode==="advancement");const f=u==="team";o.label.classList.toggle("sap-touch-overlay-label-blue",f&&s.isTeamZero),o.label.classList.toggle("sap-touch-overlay-label-orange",f&&!s.isTeamZero),o.label.style.borderColor=f?"":`#${d.toString(16).padStart(6,"0")}cc`,o.label.style.background=f?"":`#${d.toString(16).padStart(6,"0")}66`,this.updateArrow(o,s,l),this.worldPosition.set(s.position.x,s.position.y,s.position.z),this.worldPosition.add(this.labelOffset),this.scene.replayRoot.localToWorld(this.worldPosition),TV(this.worldPosition,this.scene.camera,this.container,this.projectedPosition)?(o.label.hidden=!1,o.label.style.opacity=`${.22+.78*r}`,o.label.style.transform=`translate(${this.projectedPosition.x.toFixed(1)}px, ${this.projectedPosition.y.toFixed(1)}px) translate(-50%, -100%)`):o.label.hidden=!0}}dispose(){for(const e of this.views.values())e.ring.removeFromParent(),m_(e),sx(e.arrow),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition,this.changedContainerPosition=!1)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=new Mt;i.renderOrder=40,this.group.add(i);const s=new Ig(new S(0,1,0),new S,1,e.isTeamZero?Kg:qg,1,1);s.visible=!1,s.renderOrder=45,s.line.renderOrder=45,s.cone.renderOrder=45,ix(s,.7),this.group.add(s);const a=document.createElement("div");a.className=`sap-touch-overlay-label ${e.isTeamZero?"sap-touch-overlay-label-blue":"sap-touch-overlay-label-orange"}`,a.textContent=e.playerName,a.hidden=!0,this.labelRoot.append(a);const r={marker:e,ring:i,ringSegments:[],ringColorsKey:"",arrow:s,label:a};return this.views.set(e.id,r),r}updateArrow(e,t,i){if(this.mode!=="advancement"||t.totalBallTravelDistance<=hV){e.arrow.visible=!1;return}this.arrowStart.set(t.position.x,t.position.y,t.position.z+tm*2),this.arrowEnd.set(t.endPosition.x,t.endPosition.y,t.endPosition.z+tm*2),this.arrowDirection.copy(this.arrowEnd).sub(this.arrowStart);const s=this.arrowDirection.length();if(s0&&r>0)return a/r}const t=n.frames[0],i=n.frames.at(-1);if(t&&i){const s=i.frame_number-t.frame_number,a=i.time-t.time;if(s>0&&a>0)return s/a}return LV}function DV(n,e={}){if(!n)return[];const t=e.preRollSeconds??RV,i=e.minPossessionSeconds??PV,s=e.samePlayerBridgeSeconds??IV,a=ve(n,"player_possession").map(d=>({playerId:At(d.player_id),startFrame:Math.max(0,Math.trunc(ll(d.start_frame))),endFrame:Math.max(0,Math.trunc(ll(d.end_frame))),startTime:ll(d.start_time),endTime:ll(d.end_time),duration:ll(d.duration),sustainedControl:d.sustained_control})).filter(d=>d.endFrame>d.startFrame&&(d.sustainedControl||d.duration>=i)).sort((d,h)=>d.startFrame-h.startFrame||d.endFrame-h.endFrame),r=kV(n,a),o=Math.max(0,Math.round(t*r)),l=Math.max(0,Math.round(s*r)),c=[];let u=null;for(const d of a){let h=Math.max(0,d.startFrame-o);u&&u.playerId!==d.playerId&&(h=Math.max(h,u.endFrame));const f=c.at(-1);if(f&&f.playerId===d.playerId&&h<=f.endFrame+l){c[c.length-1]={...f,endFrame:Math.max(f.endFrame,d.endFrame),possessionEndFrame:Math.max(f.possessionEndFrame,d.endFrame)},u=d;continue}c.push({playerId:d.playerId,startFrame:h,endFrame:d.endFrame,possessionStartFrame:d.startFrame,possessionEndFrame:d.endFrame}),u=d}return c.map((d,h)=>({...d,endFrame:c[h+1]?.startFrame??Number.POSITIVE_INFINITY}))}function OV(n,e){const t=Math.max(0,Math.trunc(e));return n.find(s=>t>=s.startFrame&&tthis.update(i))))}reset(){this.unsubscribeBeforeRender?.(),this.unsubscribeBeforeRender=null,this.sourcePlayer=null,this.sourceTimeline=null,this.spans=[]}syncCurrentFrame(){const e=this.options.getReplayPlayer();if(!e)return;const t=e.getState();this.update({frameIndex:t.frameIndex,nextFrameIndex:t.frameIndex,alpha:0,currentTime:t.currentTime})}update(e){const t=this.options.getCameraControlsController(),i=this.options.getReplayPlayer();if(!t?.autoPossessionEnabled||!i)return;const s=OV(this.spans,e.frameIndex);if(!s||!i.replay.players.some(r=>r.id===s))return;const a=i.getState();a.cameraViewMode==="follow"&&a.attachedPlayerId===s||t.followPlayerWithReplayCamera(s,{ballCam:"player",preserveAutoPossession:!0,requestConfigSync:!1,usePlayerCameraSettings:!1})}}function NV(n){return new FV(n)}const UV=236,tc=4120,BV=2300,zV=16185075,HV=.18,VV=1118481,rd=5882879,od=16761180,GV=.55,im=.12,ax=.28,$V=3,WV=4,rx=5,ox=2,XV=6,KV=856343,qV=.42,YV=18,jV=.24,ZV=10,lx=220,JV=200,AE=140,QV=220,e5=100,t5=120;function n5(n){const e=JV/2;if(n){const s=-tc+lx,a=-e;return{minX:s,maxX:a,centerX:(s+a)/2,width:a-s}}const t=e,i=tc-lx;return{minX:t,maxX:i,centerX:(t+i)/2,width:i-t}}function i5(n,e,t){if(n.length<2)return[];const i=Math.min(...n),s=Math.max(...n),a=s-i,r=e?-1:1,o=-r;return a<=t?[{kind:"other",centerY:(i+s)/2,halfDepth:Math.max(t-a/2,t*.35),directions:[r,o]}]:[{kind:"back",centerY:e?i:s,halfDepth:t,directions:[r]},{kind:"forward",centerY:e?s:i,halfDepth:t,directions:[o]}]}function s5(n,e){const t=new Ns;return t.moveTo(0,e/2),t.lineTo(n/2,-e/2),t.lineTo(-n/2,-e/2),t.closePath(),new dr(t)}function cx(n){const e=e5*n,t=new Ye({color:VV,transparent:!0,opacity:.9,side:ct,depthWrite:!1,depthTest:!1}),i=new Mt;i.visible=!1;const s=new kn(AE*.55*n,1),a=new we(s,t);a.position.z=rx,a.renderOrder=22,i.add(a);const r=s5(t5*n,e),o=new we(r,t);return o.position.z=rx,o.renderOrder=23,i.add(o),{group:i,shaftGeom:s,shaftMesh:a,headGeom:r,headMesh:o,material:t,headLength:e}}function sm(n,e,t,i){const s=Math.max(t-n.headLength,n.headLength*.2);n.group.position.x=e,n.group.rotation.z=i>0?0:Math.PI,n.shaftMesh.scale.y=s,n.shaftMesh.position.y=-n.headLength/2,n.headMesh.position.y=t/2-n.headLength/2,n.group.visible=!0}function oh(n){n.group.visible=!1}function jr(n,e){const t=new Mt;t.visible=!1;const i=new Ye({color:zV,transparent:!0,opacity:HV,side:ct,depthWrite:!1,depthTest:!1}),s=new kn(1,1),a=new we(s,i);a.position.z=$V,a.renderOrder=20,t.add(a);const r=new Ye({color:e,transparent:!0,opacity:GV,side:ct,depthWrite:!1,depthTest:!1}),o=new kn(1,1),l=new we(o,r);l.position.z=WV,l.renderOrder=21,t.add(l);const c=cx(n),u=cx(n);return t.add(c.group),t.add(u.group),{group:t,floorGeom:s,floorMesh:a,floorMaterial:i,stripeGeom:o,stripeMesh:l,stripeMaterial:r,primaryMarker:c,secondaryMarker:u}}function a5(n){n.group.visible=!1,oh(n.primaryMarker),oh(n.secondaryMarker)}function r5(n,e,t,i){const s=e.halfDepth*2*i,a=tc*2*i,r=t.width*i,o=t.centerX*i,l=AE*i,c=Math.max(s-32*i,n.primaryMarker.headLength*1.15),u=Math.min(c,Math.max(QV*i,s*.6));if(n.group.position.y=e.centerY*i,n.floorMesh.position.x=0,n.floorMesh.scale.set(a,s,1),n.stripeMesh.position.x=o,n.stripeMesh.scale.set(l,s,1),oh(n.primaryMarker),oh(n.secondaryMarker),e.directions.length===1)sm(n.primaryMarker,o,u,e.directions[0]);else{const d=r*.18;sm(n.primaryMarker,o-d,u,e.directions[0]),sm(n.secondaryMarker,o+d,u,e.directions[1])}n.group.visible=!0}function ux(n){n.group.removeFromParent(),n.shaftGeom.dispose(),n.headGeom.dispose(),n.material.dispose()}class o5{replay;blueBack;blueForward;blueOther;orangeBack;orangeForward;orangeOther;constructor(e,t,i){this.replay=t,this.blueBack=jr(i,rd),this.blueForward=jr(i,rd),this.blueOther=jr(i,rd),this.orangeBack=jr(i,od),this.orangeForward=jr(i,od),this.orangeOther=jr(i,od);for(const s of this.getZones())e.add(s.group)}update(e,t){const{frameIndex:i}=e,s=UV;for(const a of[!0,!1]){const r=this.replay.players.filter(d=>d.isTeamZero===a).length,o=[];for(const d of this.replay.players){if(d.isTeamZero!==a)continue;const h=d.frames[i];h?.position&&o.push(h.position.y)}const l=n5(a),c=this.getTeamZones(a);for(const d of c.values())a5(d);if(r<2||o.length!==r)continue;const u=i5(o,a,s);for(const d of u){const h=c.get(d.kind);h&&r5(h,d,l,t)}}}dispose(){for(const e of this.getZones())e.group.removeFromParent(),e.floorGeom.dispose(),e.floorMaterial.dispose(),e.stripeGeom.dispose(),e.stripeMaterial.dispose(),ux(e.primaryMarker),ux(e.secondaryMarker)}getTeamZones(e){return e?new Map([["back",this.blueBack],["forward",this.blueForward],["other",this.blueOther]]):new Map([["back",this.orangeBack],["forward",this.orangeForward],["other",this.orangeOther]])}getZones(){return[this.blueBack,this.blueForward,this.blueOther,this.orangeBack,this.orangeForward,this.orangeOther]}}function l5(n){return n==null||Number.isNaN(n)?null:n<0?"team-zero":"team-one"}class c5{group;teamZeroSide;teamOneSide;constructor(e,t){this.group=new Mt,this.teamZeroSide=this.createHalfFieldSide(rd),this.teamOneSide=this.createHalfFieldSide(od);const i=tc*t,s=5120*t;this.teamZeroSide.mesh.position.set(0,-s/2,ox),this.teamZeroSide.mesh.scale.set(i*2,s,1),this.teamOneSide.mesh.position.set(0,s/2,ox),this.teamOneSide.mesh.scale.set(i*2,s,1),this.group.add(this.teamZeroSide.mesh),this.group.add(this.teamOneSide.mesh),e.add(this.group)}update(e){const t=l5(e);this.teamZeroSide.material.opacity=t==="team-zero"?ax:im,this.teamOneSide.material.opacity=t==="team-one"?ax:im}dispose(){this.group.removeFromParent(),this.teamZeroSide.mesh.geometry.dispose(),this.teamZeroSide.material.dispose(),this.teamOneSide.mesh.geometry.dispose(),this.teamOneSide.material.dispose()}createHalfFieldSide(e){const t=new kn(1,1),i=new Ye({color:e,transparent:!0,opacity:im,side:ct,depthWrite:!1,depthTest:!1}),s=new we(t,i);return s.renderOrder=18,{mesh:s,material:i}}}function u5(n,e){const t=new Mt,i=tc*2*e,s=(a,r,o)=>{const l=new kn(i,r*e),c=new Ye({color:KV,transparent:!0,opacity:o,side:ct,depthWrite:!1,depthTest:!1}),u=new we(l,c);return u.position.set(0,a,XV),u.renderOrder=24,u};for(const a of[-1,1]){const r=a*BV*e;t.add(s(r,YV,qV))}return t.add(s(0,ZV,jV)),n.add(t),t}function cn(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function __(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function Fi(n,e){return`
${n}${e}
`}function d5(n,e){return` + ${Fi("50s",cn(n?.count))} + ${Fi("Blue wins",`${cn(n?.wins)} (${__(n?.wins,n?.count)})`)} + ${Fi("Orange wins",`${cn(n?.losses)} (${__(n?.losses,n?.count)})`)} + ${Fi("Neutral",cn(n?.neutral_outcomes))} + ${Fi("Blue poss after",cn(n?.possession_after_count))} + ${Fi("Orange poss after",cn(n?.opponent_possession_after_count))} + ${Fi("Kickoff 50s",cn(n?.kickoff_count))} + ${Fi("Blue kickoff wins",cn(n?.kickoff_wins))} + ${Fi("Orange kickoff wins",cn(n?.kickoff_losses))} + ${Fi("Blue kickoff poss",cn(n?.kickoff_possession_after_count))} + ${Fi("Orange kickoff poss",cn(n?.kickoff_opponent_possession_after_count))} + `}function dx(n){return`
50s${cn(n?.count)}
-
Wins${cn(n?.wins)} (${c_(n?.wins,n?.count)})
+
Wins${cn(n?.wins)} (${__(n?.wins,n?.count)})
Losses${cn(n?.losses)}
Neutral${cn(n?.neutral_outcomes)}
Poss after${cn(n?.possession_after_count)}
Kickoff 50s${cn(n?.kickoff_count)}
Kickoff wins${cn(n?.kickoff_wins)}
Kickoff poss${cn(n?.kickoff_possession_after_count)}
- `}function OV(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function FV(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function sx(n,e,t=1){if(n===void 0||Number.isNaN(n))return"?";const i=FV(n,e,t);return i==="?"?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${i})`}function ax(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function u_(n,e){return`
${ax(n)}${ax(e)}
`}function NV(n){const e=new Set,t=[];for(const i of n??[])e.has(i)||(e.add(i),t.push(i));return t}function vE(n,e){return n==="neutral"?"Neutral":e.kind==="shared"?n==="own"?"Blue control":"Orange control":n==="own"?"Team control":"Opp control"}function d_(n){return n.kind==="shared"?["own","neutral","opponent"]:["own","neutral","opponent"]}function UV(n,e){return n==="neutral_third"?"Neutral third":e.kind==="shared"?n==="defensive_third"?"Blue third":"Orange third":n==="defensive_third"?"Own third":"Opp third"}function BV(n){return n.kind==="shared"?["defensive_third","neutral_third","offensive_third"]:["defensive_third","neutral_third","offensive_third"]}function zV(n,e){return n==="neutral"?"Neutral":e.kind==="shared"?n==="defensive_half"?"Blue half":"Orange half":n==="defensive_half"?"Own half":"Opp half"}function HV(n){return n.kind==="shared"?["defensive_half","neutral","offensive_half"]:["defensive_half","neutral","offensive_half"]}function VV(n,e,t,i){for(const s of t){const a=s==="possession_state"?d_(i):s==="field_third"?BV(i):HV(i),r=a.indexOf(n[s]),o=a.indexOf(e[s]),l=r===-1?Number.MAX_SAFE_INTEGER:r,c=o===-1?Number.MAX_SAFE_INTEGER:o;if(l!==c)return l-c}return 0}function GV(n,e,t){const i=(s,a)=>s==="possession_state"?vE(a,t):s==="field_third"?UV(a,t):zV(a,t);if(e.length===1){const s=e[0];return i(s,n[s])}return e.map(s=>i(s,n[s])).join(" / ")}function $V(n,e,t,i){if(e.length===0)return"";const s=new Map;if(n?.labeled_time?.entries?.length)for(const a of n.labeled_time.entries){const r=new Map(a.labels.map(d=>[d.key,d.value])),o={};let l=!0;for(const d of e){const h=r.get(d);if(h===void 0){l=!1;break}o[d]=h}if(!l)continue;const c=e.map(d=>`${d}:${o[d]}`).join("|"),u=s.get(c);u?u.total+=a.value:s.set(c,{values:o,total:a.value})}if(s.size===0&&e.length===1&&e[0]==="possession_state"){const a=new Map;return n&&(a.set("own",n.possession_time),a.set("neutral",n.neutral_time??0),a.set("opponent",n.opponent_possession_time)),d_(i).some(r=>(a.get(r)??0)>0)?d_(i).filter(r=>a.has(r)).map(r=>u_(vE(r,i),sx(a.get(r),t))).join(""):""}return[...s.values()].sort((a,r)=>VV(a.values,r.values,e,i)).map(a=>u_(GV(a.values,e,i),sx(a.total,t))).join("")}function rx(n,e){const t=n?.tracked_time,i=NV(e.breakdownClasses),s=$V(n,i,t,e.labelPerspective);return` - ${u_("Tracked",OV(t,1,"s"))} + `}function h5(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function f5(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function hx(n,e,t=1){if(n===void 0||Number.isNaN(n))return"?";const i=f5(n,e,t);return i==="?"?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${i})`}function fx(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function g_(n,e){return`
${fx(n)}${fx(e)}
`}function p5(n){const e=new Set,t=[];for(const i of n??[])e.has(i)||(e.add(i),t.push(i));return t}function RE(n,e){return n==="neutral"?"Neutral":e.kind==="shared"?n==="own"?"Blue control":"Orange control":n==="own"?"Team control":"Opp control"}function y_(n){return n.kind==="shared"?["own","neutral","opponent"]:["own","neutral","opponent"]}function m5(n,e){return n==="neutral_third"?"Neutral third":e.kind==="shared"?n==="defensive_third"?"Blue third":"Orange third":n==="defensive_third"?"Own third":"Opp third"}function _5(n){return n.kind==="shared"?["defensive_third","neutral_third","offensive_third"]:["defensive_third","neutral_third","offensive_third"]}function g5(n,e){return n==="neutral"?"Neutral":e.kind==="shared"?n==="defensive_half"?"Blue half":"Orange half":n==="defensive_half"?"Own half":"Opp half"}function y5(n){return n.kind==="shared"?["defensive_half","neutral","offensive_half"]:["defensive_half","neutral","offensive_half"]}function v5(n,e,t,i){for(const s of t){const a=s==="possession_state"?y_(i):s==="field_third"?_5(i):y5(i),r=a.indexOf(n[s]),o=a.indexOf(e[s]),l=r===-1?Number.MAX_SAFE_INTEGER:r,c=o===-1?Number.MAX_SAFE_INTEGER:o;if(l!==c)return l-c}return 0}function b5(n,e,t){const i=(s,a)=>s==="possession_state"?RE(a,t):s==="field_third"?m5(a,t):g5(a,t);if(e.length===1){const s=e[0];return i(s,n[s])}return e.map(s=>i(s,n[s])).join(" / ")}function x5(n,e,t,i){if(e.length===0)return"";const s=new Map;if(n?.labeled_time?.entries?.length)for(const a of n.labeled_time.entries){const r=new Map(a.labels.map(d=>[d.key,d.value])),o={};let l=!0;for(const d of e){const h=r.get(d);if(h===void 0){l=!1;break}o[d]=h}if(!l)continue;const c=e.map(d=>`${d}:${o[d]}`).join("|"),u=s.get(c);u?u.total+=a.value:s.set(c,{values:o,total:a.value})}if(s.size===0&&e.length===1&&e[0]==="possession_state"){const a=new Map;return n&&(a.set("own",n.possession_time),a.set("neutral",n.neutral_time??0),a.set("opponent",n.opponent_possession_time)),y_(i).some(r=>(a.get(r)??0)>0)?y_(i).filter(r=>a.has(r)).map(r=>g_(RE(r,i),hx(a.get(r),t))).join(""):""}return[...s.values()].sort((a,r)=>v5(a.values,r.values,e,i)).map(a=>g_(b5(a.values,e,i),hx(a.total,t))).join("")}function px(n,e){const t=n?.tracked_time,i=p5(e.breakdownClasses),s=x5(n,i,t,e.labelPerspective);return` + ${g_("Tracked",h5(t,1,"s"))} ${s} - `}function WV(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function XV(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function KV(n,e,t=1){if(n===void 0||Number.isNaN(n))return"?";const i=XV(n,e,t);return i==="?"?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${i})`}function ox(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function bE(n,e){return`
${ox(n)}${ox(e)}
`}function qV(n,e){return n==="neutral"?"Neutral zone":e.kind==="shared"?n==="defensive_half"?"Blue side":"Orange side":n==="defensive_half"?"Own half":"Opp half"}function YV(n,e,t){const i=new Map;if(n&&(i.set("defensive_half",n.defensive_half_time),i.set("neutral",n.neutral_time??0),i.set("offensive_half",n.offensive_half_time)),n?.labeled_time?.entries?.length){i.clear();for(const a of n.labeled_time.entries){const r=a.labels.find(o=>o.key==="field_half")?.value;r&&i.set(r,(i.get(r)??0)+a.value)}}const s=["defensive_half","neutral","offensive_half"];return s.some(a=>(i.get(a)??0)>0)?s.filter(a=>i.has(a)).map(a=>bE(qV(a,t),KV(i.get(a),e))).join(""):""}function lx(n,e){const t=n?.tracked_time,i=YV(n,t,e.labelPerspective);return` - ${i.length===0?bE("Tracked",WV(t,1,"s")):""} + `}function w5(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function S5(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function T5(n,e,t=1){if(n===void 0||Number.isNaN(n))return"?";const i=S5(n,e,t);return i==="?"?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${i})`}function mx(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function PE(n,e){return`
${mx(n)}${mx(e)}
`}function M5(n,e){return n==="neutral"?"Neutral zone":e.kind==="shared"?n==="defensive_half"?"Blue side":"Orange side":n==="defensive_half"?"Own half":"Opp half"}function E5(n,e,t){const i=new Map;if(n&&(i.set("defensive_half",n.defensive_half_time),i.set("neutral",n.neutral_time??0),i.set("offensive_half",n.offensive_half_time)),n?.labeled_time?.entries?.length){i.clear();for(const a of n.labeled_time.entries){const r=a.labels.find(o=>o.key==="field_half")?.value;r&&i.set(r,(i.get(r)??0)+a.value)}}const s=["defensive_half","neutral","offensive_half"];return s.some(a=>(i.get(a)??0)>0)?s.filter(a=>i.has(a)).map(a=>PE(M5(a,t),T5(i.get(a),e))).join(""):""}function _x(n,e){const t=n?.tracked_time,i=E5(n,t,e.labelPerspective);return` + ${i.length===0?PE("Tracked",w5(t,1,"s")):""} ${i} - `}function jV(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function ZV(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function JV(n,e,t=1){if(n===void 0||Number.isNaN(n))return"?";const i=ZV(n,e,t);return i==="?"?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${i})`}function cx(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function xE(n,e){return`
${cx(n)}${cx(e)}
`}function QV(n,e){return n==="neutral_third"?"Neutral third":e.kind==="shared"?n==="defensive_third"?"Blue third":"Orange third":n==="defensive_third"?"Own third":"Opp third"}function e5(n,e,t){const i=new Map;if(n&&(i.set("defensive_third",n.defensive_third_time),i.set("neutral_third",n.neutral_third_time??0),i.set("offensive_third",n.offensive_third_time)),n?.labeled_time?.entries?.length){i.clear();for(const a of n.labeled_time.entries){const r=a.labels.find(o=>o.key==="field_third")?.value;r&&i.set(r,(i.get(r)??0)+a.value)}}const s=["defensive_third","neutral_third","offensive_third"];return s.some(a=>(i.get(a)??0)>0)?s.filter(a=>i.has(a)).map(a=>xE(QV(a,t),JV(i.get(a),e))).join(""):""}function ux(n,e){const t=n?.tracked_time,i=e5(n,t,e.labelPerspective);return` - ${i.length===0?xE("Tracked",jV(t,1,"s")):""} + `}function C5(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function A5(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function R5(n,e,t=1){if(n===void 0||Number.isNaN(n))return"?";const i=A5(n,e,t);return i==="?"?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${i})`}function gx(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function IE(n,e){return`
${gx(n)}${gx(e)}
`}function P5(n,e){return n==="neutral_third"?"Neutral third":e.kind==="shared"?n==="defensive_third"?"Blue third":"Orange third":n==="defensive_third"?"Own third":"Opp third"}function I5(n,e,t){const i=new Map;if(n&&(i.set("defensive_third",n.defensive_third_time),i.set("neutral_third",n.neutral_third_time??0),i.set("offensive_third",n.offensive_third_time)),n?.labeled_time?.entries?.length){i.clear();for(const a of n.labeled_time.entries){const r=a.labels.find(o=>o.key==="field_third")?.value;r&&i.set(r,(i.get(r)??0)+a.value)}}const s=["defensive_third","neutral_third","offensive_third"];return s.some(a=>(i.get(a)??0)>0)?s.filter(a=>i.has(a)).map(a=>IE(P5(a,t),R5(i.get(a),e))).join(""):""}function yx(n,e){const t=n?.tracked_time,i=I5(n,t,e.labelPerspective);return` + ${i.length===0?IE("Tracked",C5(t,1,"s")):""} ${i} - `}function Fa(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function Na(n,e){return`
${n}${e}
`}function Jp(n){return` - ${Na("Rushes",Fa(n?.count))} - ${Na("2v1",Fa(n?.two_v_one_count))} - ${Na("2v2",Fa(n?.two_v_two_count))} - ${Na("2v3",Fa(n?.two_v_three_count))} - ${Na("3v1",Fa(n?.three_v_one_count))} - ${Na("3v2",Fa(n?.three_v_two_count))} - ${Na("3v3",Fa(n?.three_v_three_count))} - `}const dx="subtr-actor-fifty-fifty-overlay-styles",t5=5882879,n5=16761180,i5=15988472,s5=180,a5=4;function h_(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function hx(n,e){const t=h_(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function r5(n,e){const t=hx(e,n.team_zero_player),i=hx(e,n.team_one_player),s=n.is_kickoff?"Kickoff 50/50":"50/50",a=n.winning_team_is_team_0===void 0?null:n.winning_team_is_team_0,r=n.possession_team_is_team_0===void 0?null:n.possession_team_is_team_0,o=a===null?"neutral":a?"blue win":"orange win",l=r===null?"neutral poss":r?"blue poss":"orange poss",c=a===null?"sap-fifty-fifty-overlay-label-neutral":a?"sap-fifty-fifty-overlay-label-blue":"sap-fifty-fifty-overlay-label-orange";return{text:`${s}: ${t} vs ${i} | ${o} | ${l}`,className:c,winnerIsTeamZero:a}}function wE(n,e){return ve(n,"fifty_fifty").map(t=>{const i=r5(t,e),s=new S(...t.team_zero_position),a=new S(...t.team_one_position),r=new S(...t.midpoint),o=e.frames[t.start_frame]?.time??t.start_time;return{id:`fifty-fifty:${t.start_frame}:${h_(t.team_zero_player)}:${h_(t.team_one_player)}`,time:o,frame:t.start_frame,label:i.text,labelClassName:i.className,axisStart:s,axisEnd:a,midpoint:r,winnerIsTeamZero:i.winnerIsTeamZero}})}function o5(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function l5(){if(document.getElementById(dx))return;const n=document.createElement("style");n.id=dx,n.textContent=` + `}function Na(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function Ua(n,e){return`
${n}${e}
`}function am(n){return` + ${Ua("Rushes",Na(n?.count))} + ${Ua("2v1",Na(n?.two_v_one_count))} + ${Ua("2v2",Na(n?.two_v_two_count))} + ${Ua("2v3",Na(n?.two_v_three_count))} + ${Ua("3v1",Na(n?.three_v_one_count))} + ${Ua("3v2",Na(n?.three_v_two_count))} + ${Ua("3v3",Na(n?.three_v_three_count))} + `}const vx="subtr-actor-fifty-fifty-overlay-styles",L5=5882879,k5=16761180,D5=15988472,O5=180,F5=4;function v_(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function bx(n,e){const t=v_(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function N5(n,e){const t=bx(e,n.team_zero_player),i=bx(e,n.team_one_player),s=n.is_kickoff?"Kickoff 50/50":"50/50",a=n.winning_team_is_team_0===void 0?null:n.winning_team_is_team_0,r=n.possession_team_is_team_0===void 0?null:n.possession_team_is_team_0,o=a===null?"neutral":a?"blue win":"orange win",l=r===null?"neutral poss":r?"blue poss":"orange poss",c=a===null?"sap-fifty-fifty-overlay-label-neutral":a?"sap-fifty-fifty-overlay-label-blue":"sap-fifty-fifty-overlay-label-orange";return{text:`${s}: ${t} vs ${i} | ${o} | ${l}`,className:c,winnerIsTeamZero:a}}function LE(n,e){return ve(n,"fifty_fifty").map(t=>{const i=N5(t,e),s=new S(...t.team_zero_position),a=new S(...t.team_one_position),r=new S(...t.midpoint),o=e.frames[t.start_frame]?.time??t.start_time;return{id:`fifty-fifty:${t.start_frame}:${v_(t.team_zero_player)}:${v_(t.team_one_player)}`,time:o,frame:t.start_frame,label:i.text,labelClassName:i.className,axisStart:s,axisEnd:a,midpoint:r,winnerIsTeamZero:i.winnerIsTeamZero}})}function U5(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function B5(){if(document.getElementById(vx))return;const n=document.createElement("style");n.id=vx,n.textContent=` .sap-fifty-fifty-overlay-root { position: absolute; inset: 0; @@ -5584,7 +5649,7 @@ void main() { border-color: rgba(243, 246, 248, 0.4); background: rgba(34, 41, 47, 0.86); } - `,document.head.append(n)}function c5(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class u5{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;labelOffset=new S(0,0,s5);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=a5;constructor(e,t,i,s){l5(),this.scene=e,this.container=t,this.markers=wE(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="fifty-fifty-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-fifty-fifty-overlay-root",this.container.append(this.labelRoot)}update(e){const t=o5(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.line.removeFromParent(),a.line.geometry.dispose(),a.material.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.12+.78*r;o.material.opacity=l;const c=o.line.geometry.getAttribute("position");c.setXYZ(0,s.axisStart.x,s.axisStart.y,s.axisStart.z+24),c.setXYZ(1,s.axisEnd.x,s.axisEnd.y,s.axisEnd.z+24),c.needsUpdate=!0,this.worldPosition.copy(s.midpoint).add(this.labelOffset),this.scene.replayRoot.localToWorld(this.worldPosition),c5(this.worldPosition,this.scene.camera,this.container,this.projectedPosition)?(o.label.hidden=!1,o.label.style.opacity=`${.24+.76*r}`,o.label.style.transform=`translate(${this.projectedPosition.x.toFixed(1)}px, ${this.projectedPosition.y.toFixed(1)}px) translate(-50%, -100%)`):o.label.hidden=!0}}dispose(){for(const e of this.views.values())e.line.removeFromParent(),e.line.geometry.dispose(),e.material.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition,this.changedContainerPosition=!1)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=new Ge().setFromPoints([e.axisStart,e.axisEnd]),s=new Rt({color:e.winnerIsTeamZero===null?i5:e.winnerIsTeamZero?t5:n5,transparent:!0,opacity:.9}),a=new In(i,s);a.renderOrder=3,this.group.add(a);const r=document.createElement("div");r.className=`sap-fifty-fifty-overlay-label ${e.labelClassName}`,r.textContent=e.label,this.labelRoot.append(r);const o={marker:e,line:a,material:s,label:r};return this.views.set(e.id,o),o}}const fx="subtr-actor-ceiling-shot-overlay-styles",d5=5882879,h5=16761180,f5=16185075,p5=140,m5=215,_5=220,g5=4.5;function SE(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function y5(n,e){const t=SE(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function TE(n,e){return ve(n,"ceiling_shot").map(t=>{const i=y5(e,t.player),s=SE(t.player),a=e.frames[t.frame]?.time??t.time,r=t.confidence;return{id:`ceiling-shot:${t.frame}:${s}:${Math.round(r*1e3)}`,time:a,frame:t.frame,isTeamZero:t.is_team_0,playerId:s,playerName:i,ceilingContactPosition:{x:t.ceiling_contact_position[0],y:t.ceiling_contact_position[1],z:t.ceiling_contact_position[2]},touchPosition:{x:t.touch_position[0],y:t.touch_position[1],z:t.touch_position[2]},quality:r,qualityLabel:`${Math.round(r*100)}%`}})}function v5(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function b5(){if(document.getElementById(fx))return;const n=document.createElement("style");n.id=fx,n.textContent=` + `,document.head.append(n)}function z5(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class H5{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;labelOffset=new S(0,0,O5);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=F5;constructor(e,t,i,s){B5(),this.scene=e,this.container=t,this.markers=LE(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="fifty-fifty-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-fifty-fifty-overlay-root",this.container.append(this.labelRoot)}update(e){const t=U5(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.line.removeFromParent(),a.line.geometry.dispose(),a.material.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.12+.78*r;o.material.opacity=l;const c=o.line.geometry.getAttribute("position");c.setXYZ(0,s.axisStart.x,s.axisStart.y,s.axisStart.z+24),c.setXYZ(1,s.axisEnd.x,s.axisEnd.y,s.axisEnd.z+24),c.needsUpdate=!0,this.worldPosition.copy(s.midpoint).add(this.labelOffset),this.scene.replayRoot.localToWorld(this.worldPosition),z5(this.worldPosition,this.scene.camera,this.container,this.projectedPosition)?(o.label.hidden=!1,o.label.style.opacity=`${.24+.76*r}`,o.label.style.transform=`translate(${this.projectedPosition.x.toFixed(1)}px, ${this.projectedPosition.y.toFixed(1)}px) translate(-50%, -100%)`):o.label.hidden=!0}}dispose(){for(const e of this.views.values())e.line.removeFromParent(),e.line.geometry.dispose(),e.material.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition,this.changedContainerPosition=!1)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=new Ge().setFromPoints([e.axisStart,e.axisEnd]),s=new Rt({color:e.winnerIsTeamZero===null?D5:e.winnerIsTeamZero?L5:k5,transparent:!0,opacity:.9}),a=new In(i,s);a.renderOrder=3,this.group.add(a);const r=document.createElement("div");r.className=`sap-fifty-fifty-overlay-label ${e.labelClassName}`,r.textContent=e.label,this.labelRoot.append(r);const o={marker:e,line:a,material:s,label:r};return this.views.set(e.id,o),o}}const xx="subtr-actor-ceiling-shot-overlay-styles",V5=5882879,G5=16761180,$5=16185075,W5=140,X5=215,K5=220,q5=4.5;function kE(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function Y5(n,e){const t=kE(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function DE(n,e){return ve(n,"ceiling_shot").map(t=>{const i=Y5(e,t.player),s=kE(t.player),a=e.frames[t.frame]?.time??t.time,r=t.confidence;return{id:`ceiling-shot:${t.frame}:${s}:${Math.round(r*1e3)}`,time:a,frame:t.frame,isTeamZero:t.is_team_0,playerId:s,playerName:i,ceilingContactPosition:{x:t.ceiling_contact_position[0],y:t.ceiling_contact_position[1],z:t.ceiling_contact_position[2]},touchPosition:{x:t.touch_position[0],y:t.touch_position[1],z:t.touch_position[2]},quality:r,qualityLabel:`${Math.round(r*100)}%`}})}function j5(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function Z5(){if(document.getElementById(xx))return;const n=document.createElement("style");n.id=xx,n.textContent=` .sap-ceiling-shot-overlay-root { position: absolute; inset: 0; @@ -5621,13 +5686,13 @@ void main() { border-color: rgba(255, 193, 92, 0.5); background: rgba(76, 41, 7, 0.84); } - `,document.head.append(n)}function x5(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class w5{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;labelOffset=new S(0,0,_5);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=g5;constructor(e,t,i,s){b5(),this.scene=e,this.container=t,this.markers=TE(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="ceiling-shot-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-ceiling-shot-overlay-root",this.container.append(this.labelRoot)}update(e){const t=v5(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.ring.removeFromParent(),a.ring.geometry.dispose(),a.ringMaterial.dispose(),a.beam.removeFromParent(),a.beamGeometry.dispose(),a.beamMaterial.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.14+.6*r,c=.94+(1-r)*.18;o.ringMaterial.opacity=l,o.beamMaterial.opacity=.18+.55*r,o.ring.position.set(s.touchPosition.x,s.touchPosition.y,s.touchPosition.z+12),o.ring.scale.setScalar(c+s.quality*.08),this.worldPosition.set(s.touchPosition.x,s.touchPosition.y,s.touchPosition.z).add(this.labelOffset);const u=x5(this.worldPosition,this.scene.camera,this.container,this.projectedPosition);o.label.style.display=u?"block":"none",u&&(o.label.style.left=`${this.projectedPosition.x}px`,o.label.style.top=`${this.projectedPosition.y}px`,o.label.style.opacity=`${.42+.58*r}`)}}dispose(){for(const e of this.views.values())e.ring.removeFromParent(),e.ring.geometry.dispose(),e.ringMaterial.dispose(),e.beam.removeFromParent(),e.beamGeometry.dispose(),e.beamMaterial.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=e.quality>=.8?f5:e.isTeamZero?d5:h5,s=new Ye({color:i,transparent:!0,opacity:.8,side:ct,depthWrite:!1,depthTest:!1}),a=new ni(p5,m5,48),r=new we(a,s);r.renderOrder=30,this.group.add(r);const o=new Ge().setFromPoints([new S(e.ceilingContactPosition.x,e.ceilingContactPosition.y,e.ceilingContactPosition.z),new S(e.touchPosition.x,e.touchPosition.y,e.touchPosition.z)]),l=new Rt({color:i,transparent:!0,opacity:.7,depthWrite:!1,depthTest:!1}),c=new In(o,l);c.renderOrder=29,this.group.add(c);const u=document.createElement("div");u.className=`sap-ceiling-shot-overlay-label ${e.isTeamZero?"sap-ceiling-shot-overlay-label-blue":"sap-ceiling-shot-overlay-label-orange"}`,u.textContent=`${e.playerName} ceiling shot ${e.qualityLabel}`,this.labelRoot.append(u);const d={marker:e,ring:r,ringMaterial:s,beam:c,beamGeometry:o,beamMaterial:l,label:u};return this.views.set(e.id,d),d}}const S5="#d1d9e0",ME=new Set(["flick_goal","double_tap_goal","one_timer_goal","passing_goal","air_dribble_goal","flip_reset_goal","bump_goal","demo_goal","half_volley_goal"]);function T5(n){return n.metadata.performer==="scorer"||n.metadata.modifiers?.includes("by_scorer")?"scorer":n.metadata.performer==="teammate"?"teammate":ME.has(n.kind)?"unknown":"scorer"}function M5(n){const e=T5(n);return e==="unknown"?"performer unknown":ME.has(n.kind)?`by ${e}`:null}function ji(n,e){return n.players.find(t=>t.id===e)?.name??e}function kn(n,e,t){return n.frames[e??-1]?.time??t}function E5(n){const e=n.kind;return e!=="forward"&&e!=="reverse"&&e!=="side"?"flick":`${n.direction==="left"||n.direction==="right"?`${n.direction} `:""}${e} flick`}function C5(n){const e=new Set(n),t=new Set(["goal"]);return e.has("core")&&(t.add("save"),t.add("shot"),t.add("assist")),e.has("demo")&&t.add("demo"),[...t]}function A5(n,e){const t=new Set(C5(e));return n.timelineEvents.filter(i=>t.has(i.kind))}function R5(n,e){return wE(n,e).map(t=>({id:t.id,time:t.time,frame:t.frame,kind:"fifty-fifty",label:t.label,shortLabel:t.label.startsWith("Kickoff 50/50")?"KO":"50",isTeamZero:t.winnerIsTeamZero,color:t.winnerIsTeamZero===null?S5:t.winnerIsTeamZero?en:tn}))}function P5(n,e){return(ve(n,"flick")??[]).map((t,i)=>{const s=At(t.player),a=ji(e,s),r=E5(t);return{id:`flick:${t.frame}:${s}:${i+1}`,time:kn(e,t.frame,t.time),frame:t.frame,kind:"flick",label:`${a} ${r}`,shortLabel:"F",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function I5(n,e){return _E(n,e).map(t=>({id:t.id,time:t.time,frame:t.frame,kind:"touch",label:`${t.playerName} touch`,shortLabel:"T",playerId:t.playerId,playerName:t.playerName,isTeamZero:t.isTeamZero,color:t.isTeamZero?en:tn}))}function L5(n,e){return ve(n,"backboard").map((t,i)=>{const s=At(t.player),a=e.players.find(r=>r.id===s)?.name??s;return{id:`backboard:${t.frame}:${s}:${i}`,time:kn(e,t.frame,t.time),frame:t.frame,kind:"backboard",label:`${a} backboard`,shortLabel:"BB",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function D5(n,e){return TE(n,e).map(t=>({id:t.id,time:t.time,frame:t.frame,kind:"ceiling-shot",label:`${t.playerName} ceiling shot ${t.qualityLabel}`,shortLabel:"CS",playerId:t.playerId,playerName:t.playerName,isTeamZero:t.isTeamZero,color:t.isTeamZero?en:tn}))}function k5(n,e){return ve(n,"wall_aerial").map((t,i)=>{const s=At(t.player),a=ji(e,s),r=kn(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Ci(t.wall).toLowerCase();return{id:`wall-aerial:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"wall-aerial",label:`${a} wall-to-air setup ${o}% | ${l} wall`,shortLabel:"W2A",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function O5(n,e){return ve(n,"wall_aerial_shot").map((t,i)=>{const s=At(t.player),a=ji(e,s),r=kn(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Ci(t.wall).toLowerCase();return{id:`wall-aerial-shot:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"wall-aerial-shot",label:`${a} wall shot ${o}% | ${l} wall`,shortLabel:"WS",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function F5(n,e){return ve(n,"double_tap").map((t,i)=>{const s=At(t.player),a=ji(e,s);return{id:`double-tap:${t.frame}:${s}:${i}`,time:kn(e,t.frame,t.time),frame:t.frame,kind:"double-tap",label:`${a} double tap`,shortLabel:"DT",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function N5(n,e){return ve(n,"center").map((t,i)=>{const s=At(t.player),a=ji(e,s),r=kn(e,t.frame,t.time),o=Math.round(t.lateral_centering_distance);return{id:`center:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"center",label:`${a} center | ${o}uu lateral`,shortLabel:"C",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function U5(n,e){return ve(n,"one_timer").map((t,i)=>{const s=At(t.player),a=At(t.passer),r=ji(e,s),o=ji(e,a),l=kn(e,t.frame,t.time),c=Math.round(t.ball_speed);return{id:`one-timer:${t.frame}:${a}:${s}:${i}`,time:l,frame:t.frame,kind:"one-timer",label:`${r} one-timer from ${o} | ${c}uu/s`,shortLabel:"OT",playerId:s,playerName:r,secondaryPlayerId:a,secondaryPlayerName:o,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function B5(n){return Ci(n.replace(/_pass$/,""))}function z5(n,e){return ve(n,"pass").map((t,i)=>{const s=At(t.passer),a=At(t.receiver),r=ji(e,s),o=ji(e,a),l=kn(e,t.frame,t.time),c=Math.round(t.ball_travel_distance),u=B5(t.pass_kind);return{id:`pass:${t.frame}:${s}:${a}:${i}`,time:l,frame:t.frame,kind:"pass",label:`${r} to ${o} ${u.toLowerCase()} pass | ${c}uu`,shortLabel:"P",playerId:s,playerName:r,secondaryPlayerId:a,secondaryPlayerName:o,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function H5(n,e){return ve(n,"half_volley").map((t,i)=>{const s=At(t.player),a=ji(e,s),r=kn(e,t.frame,t.time),o=Math.round(t.ball_speed);return{id:`half-volley:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"half-volley",label:`${a} half volley | ${o}uu/s`,shortLabel:"HV",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function V5(n,e){return ve(n,"rush").map((t,i)=>{const s=kn(e,t.end_frame,t.end_time),a=`${t.attackers}v${t.defenders}`,r=t.is_team_0?"Blue":"Orange";return{id:`rush:${t.start_frame}:${t.end_frame}:${i}`,time:s,frame:t.end_frame,kind:"rush",label:`${r} rush ${a}`,shortLabel:"R",playerId:null,playerName:null,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function G5(n,e){return(ve(n,"powerslide")??[]).filter(t=>t.active).map((t,i)=>{const s=At(t.player),a=ji(e,s);return{id:`powerslide:${t.frame}:${s}:${i+1}`,time:kn(e,t.frame,t.time),frame:t.frame,kind:"powerslide",label:`${a} powerslide`,shortLabel:"PS",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function $5(n,e){return ve(n,"speed_flip").map(t=>{const i=t.player?At(t.player):null,s=i?e.players.find(o=>o.id===i)?.name??i:"Unknown",a=e.frames[t.frame]?.time??t.time,r=Math.round(t.confidence*100);return{id:`speed-flip:${t.frame}:${i}:${Math.round(t.confidence*1e3)}`,time:a,frame:t.frame,kind:"speed-flip",label:`${s} speed flip ${r}%`,shortLabel:"SF",playerId:i,playerName:s,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function W5(n,e){return(ve(n,"dodge")??[]).map((t,i)=>{const s=At(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=kn(e,t.frame,t.time),o=Math.round((t.dodge_impulse?.confidence??1)*100),l=(t.dodge_impulse?.direction_label??"dodge").replaceAll("_"," ");return{id:`dodge:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"dodge",label:`${a} flip impulse ${l} ${o}%`,shortLabel:"FI",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function X5(n,e){return ve(n,"half_flip").map((t,i)=>{const s=At(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=kn(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Math.round(t.end_speed-t.start_speed);return{id:`half-flip:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"half-flip",label:`${a} half flip ${o}% | +${l}uu/s`,shortLabel:"HF",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function K5(n,e){return ve(n,"wavedash").map((t,i)=>{const s=At(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=kn(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Math.round(t.horizontal_speed_gain);return{id:`wavedash:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"wavedash",label:`${a} wavedash ${o}% | +${l}uu/s`,shortLabel:"WD",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function q5(n,e){return ve(n,"bump").map((t,i)=>{const s=At(t.initiator),a=At(t.victim),r=e.players.find(u=>u.id===s)?.name??s,o=e.players.find(u=>u.id===a)?.name??a,l=kn(e,t.frame,t.time),c=Math.round(t.confidence*100);return{id:`bump:${t.frame}:${s}:${a}:${i}`,time:l,frame:t.frame,kind:"bump",label:`${r} bumped ${o} ${c}%`,shortLabel:"B",playerId:s,playerName:r,isTeamZero:t.initiator_is_team_0,color:t.initiator_is_team_0?en:tn}})}function Y5(n){return n.kind==="beaten_to_ball"?"BT":n.dodge_active?"DW":n.aerial?"AW":"W"}function j5(n){const e=[n.aerial?"aerial":"grounded"];return n.dodge_active&&e.push("dodge"),e.join(" ")}function Z5(n){return n.kind==="beaten_to_ball"?"beaten to ball":"whiff"}function J5(n,e){return ve(n,"whiff").map((t,i)=>{const s=At(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=kn(e,t.frame,t.time),o=Math.round(t.closest_approach_distance),l=Math.round(t.approach_speed);return{id:`whiff:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"whiff",label:`${a} ${j5(t)} ${Z5(t)} | ${o}uu closest, ${l}uu/s`,shortLabel:Y5(t),playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}const EE={flick:P5,ceiling_shot:D5,wall_aerial:k5,wall_aerial_shot:O5,double_tap:F5,center:N5,one_timer:U5,pass:z5,half_flip:X5,half_volley:H5,speed_flip:$5},CE=Object.keys(EE),AE=.02,ei=1e-4,Q5=200,RE=.08,f_={big:"rgba(245, 158, 11, 0.92)",small:"rgba(52, 211, 153, 0.86)"},px={both:"rgba(52, 211, 153, 0.86)",inferred_only:"rgba(239, 68, 68, 0.9)",reported_only:"rgba(59, 130, 246, 0.9)"};function e4(n){const e=n.config?.ball_half_neutral_zone_half_width_y;return typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):Q5}function nh(n,e,t){return n?.frames?.[e??-1]?.time??t}function t4(n,e,t,i,s,a){const r=e?.ballFrames[n]?.position?.y;return typeof r=="number"&&Number.isFinite(r)&&Math.abs(r)<=t+ei||a>ei?"neutral":i>s+ei?"team_zero_side":s>i+ei?"team_one_side":null}function PE(n,e,t){if(n==="neutral")return{id:`half-control:neutral:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"half-control",laneLabel:"Half Control",label:"Neutral half control",color:"rgba(209, 217, 224, 0.7)",isTeamZero:null};const i=n==="team_zero_side";return{id:`half-control:${n}:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"half-control",laneLabel:"Half Control",label:i?"Blue half control":"Orange half control",color:ef(i)??void 0,isTeamZero:i}}function nf(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function n4(n,e){const t=nf(ve(n,"possession")),i=[];let s=0,a=!1,r="neutral",o=null;for(const l of n.frames){for(;s0)return n4(n,e);const t=[];let i=0,s=0,a=0,r=null;for(const o of n.frames){if(!Number.isFinite(o.time)||!Number.isFinite(o.dt)||o.dt<=0){r=o;continue}const l=o,c=l.team_zero?.possession?.possession_time??0,u=l.team_one?.possession?.possession_time??0,d=l.team_zero?.possession?.neutral_time??0,h=c-i,f=u-s,p=d-a;i=c,s=u,a=d;let g=null;const{startTime:_,endTime:m}=_r(o,r,e);h>f+ei&&h>p+ei?g={id:`possession:team_zero:${_.toFixed(3)}`,startTime:_,endTime:m,lane:"possession",laneLabel:"Possession",label:"Blue possession",color:"rgba(59, 130, 246, 0.88)",isTeamZero:!0}:f>h+ei&&f>p+ei&&(g={id:`possession:team_one:${_.toFixed(3)}`,startTime:_,endTime:m,lane:"possession",laneLabel:"Possession",label:"Orange possession",color:"rgba(245, 158, 11, 0.88)",isTeamZero:!1}),Fo(t,g),r=o}return t}function s4(n,e){const t=nf(ve(n,"ball_half")),i=[];let s=0,a=!1,r="neutral",o=null;for(const l of n.frames){for(;s0)return s4(n,e);const t=[];let i=0,s=0,a=0;const r=e4(n);let o=null;for(const l of n.frames){if(!Number.isFinite(l.time)||!Number.isFinite(l.dt)||l.dt<=0){o=l;continue}const c=l,u=c.team_zero?.ball_half?.defensive_half_time??0,d=c.team_one?.ball_half?.defensive_half_time??0,h=c.team_zero?.ball_half?.neutral_time??0,f=u-i,p=d-s,g=h-a;i=u,s=d,a=h;const{startTime:_,endTime:m}=_r(l,o,e),v=t4(l.frame_number,e,r,f,p,g),y=v?PE(v,_,m):null;Fo(t,y),o=l}return t}function r4(n,e,t){return t>ei?"neutral_third":n>e+ei?"team_zero_third":e>n+ei?"team_one_third":null}function IE(n,e,t){if(n==="neutral_third")return{id:`third-control:neutral_third:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"third-control",laneLabel:"Third Control",label:"Neutral third control",color:"rgba(209, 217, 224, 0.7)",isTeamZero:null};const i=n==="team_zero_third";return{id:`third-control:${n}:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"third-control",laneLabel:"Third Control",label:i?"Blue third control":"Orange third control",color:ef(i)??void 0,isTeamZero:i}}function o4(n,e){const t=nf(ve(n,"ball_third")),i=[];let s=0,a=!1,r="neutral_third",o=null;for(const l of n.frames){for(;s0)return o4(n,e);const t=[];let i=0,s=0,a=0,r=null;for(const o of n.frames){if(!Number.isFinite(o.time)||!Number.isFinite(o.dt)||o.dt<=0){r=o;continue}const l=o,c=l.team_zero?.ball_third?.defensive_third_time??0,u=l.team_one?.ball_third?.defensive_third_time??0,d=l.team_zero?.ball_third?.neutral_third_time??0,h=c-i,f=u-s,p=d-a;i=c,s=u,a=d;const{startTime:g,endTime:_}=_r(o,r,e),m=r4(h,f,p),v=m?IE(m,g,_):null;Fo(t,v),r=o}return t}function c4(n,e){return ve(n,"fifty_fifty").map((t,i)=>{const s=nh(e,t.start_frame,t.start_time),a=Math.max(s,nh(e,t.resolve_frame,t.resolve_time)),r=t.winning_team_is_team_0==null?"Neutral":t.winning_team_is_team_0?"Blue win":"Orange win",o=t.is_kickoff?"kickoff ":"";return{id:`fifty-fifty:${t.start_frame}:${t.resolve_frame}:${i}`,startTime:s,endTime:a,lane:"fifty-fifty",laneLabel:"50/50",label:`${r} ${o}50/50`,shortLabel:t.is_kickoff?"KO":"50",color:t.winning_team_is_team_0==null?"rgba(209, 217, 224, 0.7)":t.winning_team_is_team_0?"rgba(59, 130, 246, 0.48)":"rgba(245, 158, 11, 0.48)",isTeamZero:t.winning_team_is_team_0}}).sort((t,i)=>t.startTime!==i.startTime?t.startTime-i.startTime:(t.id??"").localeCompare(i.id??""))}function u4(n,e){return ve(n,"rush").map((t,i)=>{const s=e?.frames[t.start_frame]?.time??t.start_time,a=e?.frames[t.end_frame]?.time??t.end_time,r=`${t.attackers}v${t.defenders}`,o=t.is_team_0;return{id:`rush-range:${t.start_frame}:${t.end_frame}:${i}`,startTime:s,endTime:Math.max(s,a),lane:"rush",laneLabel:"Rush",label:`${o?"Blue":"Orange"} rush ${r}`,color:o?"rgba(59, 130, 246, 0.4)":"rgba(245, 158, 11, 0.4)",isTeamZero:o}})}function d4(n,e={}){const t=LE(e),i=new Set(e.detections??["both","inferred_only","reported_only"]),s=new Set(e.activities??["active","inactive","unknown"]),a=new Set(e.fieldHalves??["own","opponent","unknown"]),r=e.playerIds?new Set(e.playerIds):null;if(t.size===0||i.size===0||!s.has("unknown")||!a.has("unknown")||r?.size===0)return[];const o=new Map(n.players.map(c=>[c.id,c.isTeamZero])),l=[];for(const c of n.boostPads)if(t.has(c.size))for(let u=0;uc.startTime!==u.startTime?c.startTime-u.startTime:(c.id??"").localeCompare(u.id??""))}function LE(n){if(n.padTypes)return new Set(n.padTypes);if(n.sizes){const e=new Set(n.sizes),t=new Set;return e.has("big")&&t.add("big"),e.has("small")&&t.add("small"),e.has("big")&&e.has("small")&&t.add("ambiguous"),t}return new Set(["big","small","ambiguous"])}function mx(n){const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function h4(n){return{big:"big",small:"small",ambiguous:"ambiguous"}[n]}function f4(n){return{both:"counted",inferred_only:"inferred",reported_only:"reported"}[n]}function p4(n,e){return n==="inferred_only"?"I":n==="reported_only"?"R":{big:"100",small:"12",ambiguous:"?"}[e]}function m4(n,e,t={}){const i=ve(n,"boost_pickup");if(i.length===0&&e)return d4(e,t);const s=LE(t),a=new Set(t.detections??["both","inferred_only","reported_only"]),r=new Set(t.activities??["active","inactive","unknown"]),o=new Set(t.fieldHalves??["own","opponent","unknown"]),l=t.playerIds?new Set(t.playerIds):null;if(s.size===0||a.size===0||r.size===0||o.size===0||l?.size===0)return[];const c=new Map((e?.players??[]).map(u=>[u.id,u.name]));return i.filter(u=>{const d=mx(u.player_id);return s.has(u.pad_type)&&a.has(u.detection)&&r.has(u.activity)&&o.has(u.field_half)&&(!l||l.has(d))}).map((u,d)=>{const h=mx(u.player_id),f=c.get(h)??h,p=Math.max(0,nh(e,u.frame,u.time)),g=f4(u.detection),_=h4(u.pad_type);return{id:`boost-pickup:${u.detection}:${u.frame}:${h}:${d}`,startTime:p,endTime:Math.max(p+RE,p),lane:"boost-pickups",laneLabel:"Boost Pickups",label:`${f} ${g} ${_} boost pickup`,shortLabel:p4(u.detection,u.pad_type),color:ef(u.is_team_0)??(u.detection==="both"?u.pad_type==="big"?f_.big:u.pad_type==="small"?f_.small:px.both:px[u.detection]),isTeamZero:u.is_team_0}}).sort((u,d)=>u.startTime!==d.startTime?u.startTime-d.startTime:(u.id??"").localeCompare(d.id??""))}const id=[{fieldName:"time_defensive_third",aliases:["time_defensive_zone"],label:"Def third",relativeColor:"own"},{fieldName:"time_neutral_third",aliases:["time_neutral_zone"],label:"Neutral third",relativeColor:"neutral"},{fieldName:"time_offensive_third",aliases:["time_offensive_zone"],label:"Off third",relativeColor:"opp"}];function DE(n,e){return n.relativeColor==="neutral"?"rgba(209, 217, 224, 0.68)":(n.relativeColor==="own"?e:!e)?"rgba(89, 195, 255, 0.74)":"rgba(255, 193, 92, 0.78)"}function Vg(n){const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function _4(n,e){const t=n.positioning;if(!t)return 0;for(const i of[e.fieldName,...e.aliases??[]]){const s=t[i];if(typeof s=="number"&&Number.isFinite(s))return s}return 0}function g4(n){switch(n){case"defensive":return id[0];case"neutral":return id[1];case"offensive":return id[2]}}function y4(n){const e=new Map;for(const t of n.frames)for(const i of t.players){const s=Vg(i.player_id);e.has(s)||e.set(s,i.name)}return e}function v4(n){const e=nf(ve(n,"field_third")),t=[],i=new Map,s=y4(n);for(const a of e){if(!Number.isFinite(a.time)||!Number.isFinite(a.end_time)||a.end_time-a.time<=ei)continue;const r=Vg(a.player),o=g4(a.state);kE(t,i,{id:`time-in-zone:${r}:${o.fieldName}:${a.time.toFixed(3)}`,startTime:a.time,endTime:a.end_time,lane:`time-in-zone:${r}`,laneLabel:s.get(r)??r,label:o.label,color:DE(o,a.is_team_0),isTeamZero:a.is_team_0})}return t}function b4(n,e){if(ve(n,"field_third").length>0)return v4(n);const t=new Map,i=[],s=new Map;let a=null;for(const r of n.frames){if(!Number.isFinite(r.time)||!Number.isFinite(r.dt)||r.dt<=0){a=r;continue}const{startTime:o,endTime:l}=_r(r,a,e);if(l-o<=ei){a=r;continue}for(const c of r.players){const u=Vg(c.player_id),d=t.get(u)??new Map;let h=null,f=0;for(const p of id){const g=_4(c,p),_=g-(d.get(p.fieldName)??0);_>f+ei&&(f=_,h=p),d.set(p.fieldName,g)}t.set(u,d),h&&kE(i,s,{id:`time-in-zone:${u}:${h.fieldName}:${o.toFixed(3)}`,startTime:o,endTime:l,lane:`time-in-zone:${u}`,laneLabel:c.name,label:h.label,color:DE(h,c.is_team_0),isTeamZero:c.is_team_0})}a=r}return i}function _r(n,e,t){const i=t?.frames[n.frame_number]?.time??n.time,s=e?t?.frames[e.frame_number]?.time??e.time:Math.max(0,i-n.dt);return{startTime:Math.max(0,s),endTime:Math.max(s,i)}}function Fo(n,e){if(!e)return;const t=n[n.length-1];if(t&&t.lane===e.lane&&t.label===e.label&&Math.abs(t.endTime-e.startTime)<=AE){t.endTime=e.endTime;return}n.push(e)}function kE(n,e,t){if(!t)return;const i=t.lane??"",s=e.get(i);if(s&&s.label===t.label&&Math.abs(s.endTime-t.startTime)<=AE){s.endTime=t.endTime;return}n.push(t),e.set(i,t)}const Qp=236,OE="relative-positioning",x4={last:"Last",upfield:"Upfield",level:"Level",mid:"Mid"};function ta(n){return n?"team-blue":"team-orange"}function FE(n,e,t){return`
+ `,document.head.append(n)}function J5(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class Q5{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;labelOffset=new S(0,0,K5);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=q5;constructor(e,t,i,s){Z5(),this.scene=e,this.container=t,this.markers=DE(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="ceiling-shot-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-ceiling-shot-overlay-root",this.container.append(this.labelRoot)}update(e){const t=j5(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.ring.removeFromParent(),a.ring.geometry.dispose(),a.ringMaterial.dispose(),a.beam.removeFromParent(),a.beamGeometry.dispose(),a.beamMaterial.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.14+.6*r,c=.94+(1-r)*.18;o.ringMaterial.opacity=l,o.beamMaterial.opacity=.18+.55*r,o.ring.position.set(s.touchPosition.x,s.touchPosition.y,s.touchPosition.z+12),o.ring.scale.setScalar(c+s.quality*.08),this.worldPosition.set(s.touchPosition.x,s.touchPosition.y,s.touchPosition.z).add(this.labelOffset);const u=J5(this.worldPosition,this.scene.camera,this.container,this.projectedPosition);o.label.style.display=u?"block":"none",u&&(o.label.style.left=`${this.projectedPosition.x}px`,o.label.style.top=`${this.projectedPosition.y}px`,o.label.style.opacity=`${.42+.58*r}`)}}dispose(){for(const e of this.views.values())e.ring.removeFromParent(),e.ring.geometry.dispose(),e.ringMaterial.dispose(),e.beam.removeFromParent(),e.beamGeometry.dispose(),e.beamMaterial.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=e.quality>=.8?$5:e.isTeamZero?V5:G5,s=new Ye({color:i,transparent:!0,opacity:.8,side:ct,depthWrite:!1,depthTest:!1}),a=new ni(W5,X5,48),r=new we(a,s);r.renderOrder=30,this.group.add(r);const o=new Ge().setFromPoints([new S(e.ceilingContactPosition.x,e.ceilingContactPosition.y,e.ceilingContactPosition.z),new S(e.touchPosition.x,e.touchPosition.y,e.touchPosition.z)]),l=new Rt({color:i,transparent:!0,opacity:.7,depthWrite:!1,depthTest:!1}),c=new In(o,l);c.renderOrder=29,this.group.add(c);const u=document.createElement("div");u.className=`sap-ceiling-shot-overlay-label ${e.isTeamZero?"sap-ceiling-shot-overlay-label-blue":"sap-ceiling-shot-overlay-label-orange"}`,u.textContent=`${e.playerName} ceiling shot ${e.qualityLabel}`,this.labelRoot.append(u);const d={marker:e,ring:r,ringMaterial:s,beam:c,beamGeometry:o,beamMaterial:l,label:u};return this.views.set(e.id,d),d}}const e4="#d1d9e0",OE=new Set(["flick_goal","double_tap_goal","one_timer_goal","passing_goal","air_dribble_goal","flip_reset_goal","bump_goal","demo_goal","half_volley_goal"]);function t4(n){return n.metadata.performer==="scorer"||n.metadata.modifiers?.includes("by_scorer")?"scorer":n.metadata.performer==="teammate"?"teammate":OE.has(n.kind)?"unknown":"scorer"}function n4(n){const e=t4(n);return e==="unknown"?"performer unknown":OE.has(n.kind)?`by ${e}`:null}function Zi(n,e){return n.players.find(t=>t.id===e)?.name??e}function Dn(n,e,t){return n.frames[e??-1]?.time??t}function i4(n){const e=n.kind;return e!=="forward"&&e!=="reverse"&&e!=="side"?"flick":`${n.direction==="left"||n.direction==="right"?`${n.direction} `:""}${e} flick`}function s4(n){const e=new Set(n),t=new Set(["goal"]);return e.has("core")&&(t.add("save"),t.add("shot"),t.add("assist")),e.has("demo")&&t.add("demo"),[...t]}function a4(n,e){const t=new Set(s4(e));return n.timelineEvents.filter(i=>t.has(i.kind))}function r4(n,e){return LE(n,e).map(t=>({id:t.id,time:t.time,frame:t.frame,kind:"fifty-fifty",label:t.label,shortLabel:t.label.startsWith("Kickoff 50/50")?"KO":"50",isTeamZero:t.winnerIsTeamZero,color:t.winnerIsTeamZero===null?e4:t.winnerIsTeamZero?en:tn}))}function o4(n,e){return(ve(n,"flick")??[]).map((t,i)=>{const s=At(t.player),a=Zi(e,s),r=i4(t);return{id:`flick:${t.frame}:${s}:${i+1}`,time:Dn(e,t.frame,t.time),frame:t.frame,kind:"flick",label:`${a} ${r}`,shortLabel:"F",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function l4(n,e){return EE(n,e).map(t=>({id:t.id,time:t.time,frame:t.frame,kind:"touch",label:`${t.playerName} touch`,shortLabel:"T",playerId:t.playerId,playerName:t.playerName,isTeamZero:t.isTeamZero,color:t.isTeamZero?en:tn}))}function c4(n,e){return ve(n,"backboard").map((t,i)=>{const s=At(t.player),a=e.players.find(r=>r.id===s)?.name??s;return{id:`backboard:${t.frame}:${s}:${i}`,time:Dn(e,t.frame,t.time),frame:t.frame,kind:"backboard",label:`${a} backboard`,shortLabel:"BB",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function u4(n,e){return DE(n,e).map(t=>({id:t.id,time:t.time,frame:t.frame,kind:"ceiling-shot",label:`${t.playerName} ceiling shot ${t.qualityLabel}`,shortLabel:"CS",playerId:t.playerId,playerName:t.playerName,isTeamZero:t.isTeamZero,color:t.isTeamZero?en:tn}))}function d4(n,e){return ve(n,"wall_aerial").map((t,i)=>{const s=At(t.player),a=Zi(e,s),r=Dn(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Ai(t.wall).toLowerCase();return{id:`wall-aerial:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"wall-aerial",label:`${a} wall-to-air setup ${o}% | ${l} wall`,shortLabel:"W2A",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function h4(n,e){return ve(n,"wall_aerial_shot").map((t,i)=>{const s=At(t.player),a=Zi(e,s),r=Dn(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Ai(t.wall).toLowerCase();return{id:`wall-aerial-shot:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"wall-aerial-shot",label:`${a} wall shot ${o}% | ${l} wall`,shortLabel:"WS",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function f4(n,e){return ve(n,"double_tap").map((t,i)=>{const s=At(t.player),a=Zi(e,s);return{id:`double-tap:${t.frame}:${s}:${i}`,time:Dn(e,t.frame,t.time),frame:t.frame,kind:"double-tap",label:`${a} double tap`,shortLabel:"DT",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function p4(n,e){return ve(n,"center").map((t,i)=>{const s=At(t.player),a=Zi(e,s),r=Dn(e,t.frame,t.time),o=Math.round(t.lateral_centering_distance);return{id:`center:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"center",label:`${a} center | ${o}uu lateral`,shortLabel:"C",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function m4(n,e){return ve(n,"one_timer").map((t,i)=>{const s=At(t.player),a=At(t.passer),r=Zi(e,s),o=Zi(e,a),l=Dn(e,t.frame,t.time),c=Math.round(t.ball_speed);return{id:`one-timer:${t.frame}:${a}:${s}:${i}`,time:l,frame:t.frame,kind:"one-timer",label:`${r} one-timer from ${o} | ${c}uu/s`,shortLabel:"OT",playerId:s,playerName:r,secondaryPlayerId:a,secondaryPlayerName:o,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function _4(n){return Ai(n.replace(/_pass$/,""))}function g4(n,e){return ve(n,"pass").map((t,i)=>{const s=At(t.passer),a=At(t.receiver),r=Zi(e,s),o=Zi(e,a),l=Dn(e,t.frame,t.time),c=Math.round(t.ball_travel_distance),u=_4(t.pass_kind);return{id:`pass:${t.frame}:${s}:${a}:${i}`,time:l,frame:t.frame,kind:"pass",label:`${r} to ${o} ${u.toLowerCase()} pass | ${c}uu`,shortLabel:"P",playerId:s,playerName:r,secondaryPlayerId:a,secondaryPlayerName:o,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function y4(n,e){return ve(n,"half_volley").map((t,i)=>{const s=At(t.player),a=Zi(e,s),r=Dn(e,t.frame,t.time),o=Math.round(t.ball_speed);return{id:`half-volley:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"half-volley",label:`${a} half volley | ${o}uu/s`,shortLabel:"HV",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function v4(n,e){return ve(n,"rush").map((t,i)=>{const s=Dn(e,t.end_frame,t.end_time),a=`${t.attackers}v${t.defenders}`,r=t.is_team_0?"Blue":"Orange";return{id:`rush:${t.start_frame}:${t.end_frame}:${i}`,time:s,frame:t.end_frame,kind:"rush",label:`${r} rush ${a}`,shortLabel:"R",playerId:null,playerName:null,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function b4(n,e){return(ve(n,"powerslide")??[]).filter(t=>t.active).map((t,i)=>{const s=At(t.player),a=Zi(e,s);return{id:`powerslide:${t.frame}:${s}:${i+1}`,time:Dn(e,t.frame,t.time),frame:t.frame,kind:"powerslide",label:`${a} powerslide`,shortLabel:"PS",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function x4(n,e){return ve(n,"speed_flip").map(t=>{const i=t.player?At(t.player):null,s=i?e.players.find(o=>o.id===i)?.name??i:"Unknown",a=e.frames[t.frame]?.time??t.time,r=Math.round(t.confidence*100);return{id:`speed-flip:${t.frame}:${i}:${Math.round(t.confidence*1e3)}`,time:a,frame:t.frame,kind:"speed-flip",label:`${s} speed flip ${r}%`,shortLabel:"SF",playerId:i,playerName:s,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function w4(n,e){return(ve(n,"dodge")??[]).map((t,i)=>{const s=At(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=Dn(e,t.frame,t.time),o=Math.round((t.dodge_impulse?.confidence??1)*100),l=(t.dodge_impulse?.direction_label??"dodge").replaceAll("_"," ");return{id:`dodge:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"dodge",label:`${a} flip impulse ${l} ${o}%`,shortLabel:"FI",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function S4(n,e){return ve(n,"half_flip").map((t,i)=>{const s=At(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=Dn(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Math.round(t.end_speed-t.start_speed);return{id:`half-flip:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"half-flip",label:`${a} half flip ${o}% | +${l}uu/s`,shortLabel:"HF",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function T4(n,e){return ve(n,"wavedash").map((t,i)=>{const s=At(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=Dn(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Math.round(t.horizontal_speed_gain);return{id:`wavedash:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"wavedash",label:`${a} wavedash ${o}% | +${l}uu/s`,shortLabel:"WD",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}function M4(n,e){return ve(n,"bump").map((t,i)=>{const s=At(t.initiator),a=At(t.victim),r=e.players.find(u=>u.id===s)?.name??s,o=e.players.find(u=>u.id===a)?.name??a,l=Dn(e,t.frame,t.time),c=Math.round(t.confidence*100);return{id:`bump:${t.frame}:${s}:${a}:${i}`,time:l,frame:t.frame,kind:"bump",label:`${r} bumped ${o} ${c}%`,shortLabel:"B",playerId:s,playerName:r,isTeamZero:t.initiator_is_team_0,color:t.initiator_is_team_0?en:tn}})}function E4(n){return n.kind==="beaten_to_ball"?"BT":n.dodge_active?"DW":n.aerial?"AW":"W"}function C4(n){const e=[n.aerial?"aerial":"grounded"];return n.dodge_active&&e.push("dodge"),e.join(" ")}function A4(n){return n.kind==="beaten_to_ball"?"beaten to ball":"whiff"}function R4(n,e){return ve(n,"whiff").map((t,i)=>{const s=At(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=Dn(e,t.frame,t.time),o=Math.round(t.closest_approach_distance),l=Math.round(t.approach_speed);return{id:`whiff:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"whiff",label:`${a} ${C4(t)} ${A4(t)} | ${o}uu closest, ${l}uu/s`,shortLabel:E4(t),playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?en:tn}})}const FE={flick:o4,ceiling_shot:u4,wall_aerial:d4,wall_aerial_shot:h4,double_tap:f4,center:p4,one_timer:m4,pass:g4,half_flip:S4,half_volley:y4,speed_flip:x4},NE=Object.keys(FE),UE=.02,ei=1e-4,P4=200,BE=.08,b_={big:"rgba(245, 158, 11, 0.92)",small:"rgba(52, 211, 153, 0.86)"},wx={both:"rgba(52, 211, 153, 0.86)",inferred_only:"rgba(239, 68, 68, 0.9)",reported_only:"rgba(59, 130, 246, 0.9)"};function I4(n){const e=n.config?.ball_half_neutral_zone_half_width_y;return typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):P4}function lh(n,e,t){return n?.frames?.[e??-1]?.time??t}function L4(n,e,t,i,s,a){const r=e?.ballFrames[n]?.position?.y;return typeof r=="number"&&Number.isFinite(r)&&Math.abs(r)<=t+ei||a>ei?"neutral":i>s+ei?"team_zero_side":s>i+ei?"team_one_side":null}function zE(n,e,t){if(n==="neutral")return{id:`half-control:neutral:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"half-control",laneLabel:"Half Control",label:"Neutral half control",color:"rgba(209, 217, 224, 0.7)",isTeamZero:null};const i=n==="team_zero_side";return{id:`half-control:${n}:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"half-control",laneLabel:"Half Control",label:i?"Blue half control":"Orange half control",color:of(i)??void 0,isTeamZero:i}}function cf(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function k4(n,e){const t=cf(ve(n,"possession")),i=[];let s=0,a=!1,r="neutral",o=null;for(const l of n.frames){for(;s0)return k4(n,e);const t=[];let i=0,s=0,a=0,r=null;for(const o of n.frames){if(!Number.isFinite(o.time)||!Number.isFinite(o.dt)||o.dt<=0){r=o;continue}const l=o,c=l.team_zero?.possession?.possession_time??0,u=l.team_one?.possession?.possession_time??0,d=l.team_zero?.possession?.neutral_time??0,h=c-i,f=u-s,p=d-a;i=c,s=u,a=d;let g=null;const{startTime:_,endTime:m}=gr(o,r,e);h>f+ei&&h>p+ei?g={id:`possession:team_zero:${_.toFixed(3)}`,startTime:_,endTime:m,lane:"possession",laneLabel:"Possession",label:"Blue possession",color:"rgba(59, 130, 246, 0.88)",isTeamZero:!0}:f>h+ei&&f>p+ei&&(g={id:`possession:team_one:${_.toFixed(3)}`,startTime:_,endTime:m,lane:"possession",laneLabel:"Possession",label:"Orange possession",color:"rgba(245, 158, 11, 0.88)",isTeamZero:!1}),Bo(t,g),r=o}return t}function O4(n,e){const t=cf(ve(n,"ball_half")),i=[];let s=0,a=!1,r="neutral",o=null;for(const l of n.frames){for(;s0)return O4(n,e);const t=[];let i=0,s=0,a=0;const r=I4(n);let o=null;for(const l of n.frames){if(!Number.isFinite(l.time)||!Number.isFinite(l.dt)||l.dt<=0){o=l;continue}const c=l,u=c.team_zero?.ball_half?.defensive_half_time??0,d=c.team_one?.ball_half?.defensive_half_time??0,h=c.team_zero?.ball_half?.neutral_time??0,f=u-i,p=d-s,g=h-a;i=u,s=d,a=h;const{startTime:_,endTime:m}=gr(l,o,e),v=L4(l.frame_number,e,r,f,p,g),y=v?zE(v,_,m):null;Bo(t,y),o=l}return t}function N4(n,e,t){return t>ei?"neutral_third":n>e+ei?"team_zero_third":e>n+ei?"team_one_third":null}function HE(n,e,t){if(n==="neutral_third")return{id:`third-control:neutral_third:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"third-control",laneLabel:"Third Control",label:"Neutral third control",color:"rgba(209, 217, 224, 0.7)",isTeamZero:null};const i=n==="team_zero_third";return{id:`third-control:${n}:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"third-control",laneLabel:"Third Control",label:i?"Blue third control":"Orange third control",color:of(i)??void 0,isTeamZero:i}}function U4(n,e){const t=cf(ve(n,"ball_third")),i=[];let s=0,a=!1,r="neutral_third",o=null;for(const l of n.frames){for(;s0)return U4(n,e);const t=[];let i=0,s=0,a=0,r=null;for(const o of n.frames){if(!Number.isFinite(o.time)||!Number.isFinite(o.dt)||o.dt<=0){r=o;continue}const l=o,c=l.team_zero?.ball_third?.defensive_third_time??0,u=l.team_one?.ball_third?.defensive_third_time??0,d=l.team_zero?.ball_third?.neutral_third_time??0,h=c-i,f=u-s,p=d-a;i=c,s=u,a=d;const{startTime:g,endTime:_}=gr(o,r,e),m=N4(h,f,p),v=m?HE(m,g,_):null;Bo(t,v),r=o}return t}function z4(n,e){return ve(n,"fifty_fifty").map((t,i)=>{const s=lh(e,t.start_frame,t.start_time),a=Math.max(s,lh(e,t.resolve_frame,t.resolve_time)),r=t.winning_team_is_team_0==null?"Neutral":t.winning_team_is_team_0?"Blue win":"Orange win",o=t.is_kickoff?"kickoff ":"";return{id:`fifty-fifty:${t.start_frame}:${t.resolve_frame}:${i}`,startTime:s,endTime:a,lane:"fifty-fifty",laneLabel:"50/50",label:`${r} ${o}50/50`,shortLabel:t.is_kickoff?"KO":"50",color:t.winning_team_is_team_0==null?"rgba(209, 217, 224, 0.7)":t.winning_team_is_team_0?"rgba(59, 130, 246, 0.48)":"rgba(245, 158, 11, 0.48)",isTeamZero:t.winning_team_is_team_0}}).sort((t,i)=>t.startTime!==i.startTime?t.startTime-i.startTime:(t.id??"").localeCompare(i.id??""))}function H4(n,e){return ve(n,"rush").map((t,i)=>{const s=e?.frames[t.start_frame]?.time??t.start_time,a=e?.frames[t.end_frame]?.time??t.end_time,r=`${t.attackers}v${t.defenders}`,o=t.is_team_0;return{id:`rush-range:${t.start_frame}:${t.end_frame}:${i}`,startTime:s,endTime:Math.max(s,a),lane:"rush",laneLabel:"Rush",label:`${o?"Blue":"Orange"} rush ${r}`,color:o?"rgba(59, 130, 246, 0.4)":"rgba(245, 158, 11, 0.4)",isTeamZero:o}})}function V4(n,e={}){const t=VE(e),i=new Set(e.detections??["both","inferred_only","reported_only"]),s=new Set(e.activities??["active","inactive","unknown"]),a=new Set(e.fieldHalves??["own","opponent","unknown"]),r=e.playerIds?new Set(e.playerIds):null;if(t.size===0||i.size===0||!s.has("unknown")||!a.has("unknown")||r?.size===0)return[];const o=new Map(n.players.map(c=>[c.id,c.isTeamZero])),l=[];for(const c of n.boostPads)if(t.has(c.size))for(let u=0;uc.startTime!==u.startTime?c.startTime-u.startTime:(c.id??"").localeCompare(u.id??""))}function VE(n){if(n.padTypes)return new Set(n.padTypes);if(n.sizes){const e=new Set(n.sizes),t=new Set;return e.has("big")&&t.add("big"),e.has("small")&&t.add("small"),e.has("big")&&e.has("small")&&t.add("ambiguous"),t}return new Set(["big","small","ambiguous"])}function Sx(n){const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function G4(n){return{big:"big",small:"small",ambiguous:"ambiguous"}[n]}function $4(n){return{both:"counted",inferred_only:"inferred",reported_only:"reported"}[n]}function W4(n,e){return n==="inferred_only"?"I":n==="reported_only"?"R":{big:"100",small:"12",ambiguous:"?"}[e]}function X4(n,e,t={}){const i=ve(n,"boost_pickup");if(i.length===0&&e)return V4(e,t);const s=VE(t),a=new Set(t.detections??["both","inferred_only","reported_only"]),r=new Set(t.activities??["active","inactive","unknown"]),o=new Set(t.fieldHalves??["own","opponent","unknown"]),l=t.playerIds?new Set(t.playerIds):null;if(s.size===0||a.size===0||r.size===0||o.size===0||l?.size===0)return[];const c=new Map((e?.players??[]).map(u=>[u.id,u.name]));return i.filter(u=>{const d=Sx(u.player_id);return s.has(u.pad_type)&&a.has(u.detection)&&r.has(u.activity)&&o.has(u.field_half)&&(!l||l.has(d))}).map((u,d)=>{const h=Sx(u.player_id),f=c.get(h)??h,p=Math.max(0,lh(e,u.frame,u.time)),g=$4(u.detection),_=G4(u.pad_type);return{id:`boost-pickup:${u.detection}:${u.frame}:${h}:${d}`,startTime:p,endTime:Math.max(p+BE,p),lane:"boost-pickups",laneLabel:"Boost Pickups",label:`${f} ${g} ${_} boost pickup`,shortLabel:W4(u.detection,u.pad_type),color:of(u.is_team_0)??(u.detection==="both"?u.pad_type==="big"?b_.big:u.pad_type==="small"?b_.small:wx.both:wx[u.detection]),isTeamZero:u.is_team_0}}).sort((u,d)=>u.startTime!==d.startTime?u.startTime-d.startTime:(u.id??"").localeCompare(d.id??""))}const ld=[{fieldName:"time_defensive_third",aliases:["time_defensive_zone"],label:"Def third",relativeColor:"own"},{fieldName:"time_neutral_third",aliases:["time_neutral_zone"],label:"Neutral third",relativeColor:"neutral"},{fieldName:"time_offensive_third",aliases:["time_offensive_zone"],label:"Off third",relativeColor:"opp"}];function GE(n,e){return n.relativeColor==="neutral"?"rgba(209, 217, 224, 0.68)":(n.relativeColor==="own"?e:!e)?"rgba(89, 195, 255, 0.74)":"rgba(255, 193, 92, 0.78)"}function Yg(n){const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function K4(n,e){const t=n.positioning;if(!t)return 0;for(const i of[e.fieldName,...e.aliases??[]]){const s=t[i];if(typeof s=="number"&&Number.isFinite(s))return s}return 0}function q4(n){switch(n){case"defensive":return ld[0];case"neutral":return ld[1];case"offensive":return ld[2]}}function Y4(n){const e=new Map;for(const t of n.frames)for(const i of t.players){const s=Yg(i.player_id);e.has(s)||e.set(s,i.name)}return e}function j4(n){const e=cf(ve(n,"field_third")),t=[],i=new Map,s=Y4(n);for(const a of e){if(!Number.isFinite(a.time)||!Number.isFinite(a.end_time)||a.end_time-a.time<=ei)continue;const r=Yg(a.player),o=q4(a.state);$E(t,i,{id:`time-in-zone:${r}:${o.fieldName}:${a.time.toFixed(3)}`,startTime:a.time,endTime:a.end_time,lane:`time-in-zone:${r}`,laneLabel:s.get(r)??r,label:o.label,color:GE(o,a.is_team_0),isTeamZero:a.is_team_0})}return t}function Z4(n,e){if(ve(n,"field_third").length>0)return j4(n);const t=new Map,i=[],s=new Map;let a=null;for(const r of n.frames){if(!Number.isFinite(r.time)||!Number.isFinite(r.dt)||r.dt<=0){a=r;continue}const{startTime:o,endTime:l}=gr(r,a,e);if(l-o<=ei){a=r;continue}for(const c of r.players){const u=Yg(c.player_id),d=t.get(u)??new Map;let h=null,f=0;for(const p of ld){const g=K4(c,p),_=g-(d.get(p.fieldName)??0);_>f+ei&&(f=_,h=p),d.set(p.fieldName,g)}t.set(u,d),h&&$E(i,s,{id:`time-in-zone:${u}:${h.fieldName}:${o.toFixed(3)}`,startTime:o,endTime:l,lane:`time-in-zone:${u}`,laneLabel:c.name,label:h.label,color:GE(h,c.is_team_0),isTeamZero:c.is_team_0})}a=r}return i}function gr(n,e,t){const i=t?.frames[n.frame_number]?.time??n.time,s=e?t?.frames[e.frame_number]?.time??e.time:Math.max(0,i-n.dt);return{startTime:Math.max(0,s),endTime:Math.max(s,i)}}function Bo(n,e){if(!e)return;const t=n[n.length-1];if(t&&t.lane===e.lane&&t.label===e.label&&Math.abs(t.endTime-e.startTime)<=UE){t.endTime=e.endTime;return}n.push(e)}function $E(n,e,t){if(!t)return;const i=t.lane??"",s=e.get(i);if(s&&s.label===t.label&&Math.abs(s.endTime-t.startTime)<=UE){s.endTime=t.endTime;return}n.push(t),e.set(i,t)}const rm=236,WE="relative-positioning",J4={last:"Last",upfield:"Upfield",level:"Level",mid:"Mid"};function na(n){return n?"team-blue":"team-orange"}function XE(n,e,t){return`
${n} ${t.metaHtml??""}
${e} -
`}function Tn(n,e,t,i=""){return FE(n,t,{metaHtml:i,tone:e?"blue":"orange"})}function si(n,e){return`
${[!0,!1].map(t=>{const i=n.filter(a=>a.is_team_0===t);if(i.length===0)return"";const s=t?"Blue":"Orange";return`
+
`}function Tn(n,e,t,i=""){return XE(n,t,{metaHtml:i,tone:e?"blue":"orange"})}function si(n,e){return`
${[!0,!1].map(t=>{const i=n.filter(a=>a.is_team_0===t);if(i.length===0)return"";const s=t?"Blue":"Orange";return`

${s} team

${i.length} player${i.length===1?"":"s"} @@ -5635,12 +5700,12 @@ void main() {
${i.map(e).join("")}
-
`}).join("")}
`}function sf(n,e,t=""){return FE(n,e,{metaHtml:t,tone:"shared"})}function wn(n,e,t){const i=zt(n.statsFrameLookup,e);return i?i.players.find(s=>At(s.player_id)===t)??null:null}function w4(n,e,t){const i=n.players.find(p=>p.id===e);if(!i||!i.frames[t]?.position)return"mid";const a=i.isTeamZero,r=n.players.filter(p=>p.isTeamZero===a).length,o=[];let l=0;for(const p of n.players){if(p.isTeamZero!==a)continue;const g=p.frames[t];if(!g?.position)continue;const _=a?g.position.y:-g.position.y;o.push(_),p.id===e&&(l=_)}if(r<2||o.length!==r)return"mid";const c=Math.min(...o),u=Math.max(...o);if(u-c<=Qp)return"level";const h=l-c<=Qp,f=u-l<=Qp;return h&&!f?"last":f&&!h?"upfield":"mid"}function S4(n){let e=null,t=null;const i=new Set,s=["possession_state","field_half","field_third"];return{id:"possession",label:"Possession",setup(){a()},teardown(){},onBeforeRender(){},getTimelineRanges(o){return i4(o.statsTimeline,o.replay)},getConfig(){return{breakdownClasses:r()}},applyConfig(o){if(i.clear(),o&&typeof o=="object"&&!Array.isArray(o)){const l=o.breakdownClasses;if(Array.isArray(l))for(const c of l)s.includes(c)&&i.add(c)}a(),n.rerenderCurrentState()},renderStats(o,l){const u=zt(l.statsFrameLookup,o)?.team_zero?.possession;return u?sf("Control State",rx(u,{labelPerspective:{kind:"shared"},breakdownClasses:r()})):""},renderFocusedPlayerStats(o,l,c){const u=zt(c.statsFrameLookup,l),d=wn(c,l,o),h=d?.is_team_0?u?.team_zero?.possession:u?.team_one?.possession;return!h||!d?"":rx(h,{labelPerspective:{kind:"team"},breakdownClasses:r()})},renderSettings(){if(!e){e=document.createElement("div"),e.className="module-settings-card";const o=document.createElement("div");o.className="module-settings-header";const l=document.createElement("div"),c=document.createElement("p");c.className="module-settings-eyebrow",c.textContent="Stat display";const u=document.createElement("h3");u.textContent="Possession breakdown",l.append(c,u),t=document.createElement("strong"),t.className="metric-readout",o.append(l,t);const d=document.createElement("div");d.className="module-settings-options";const h=document.createElement("label");h.className="toggle";const f=document.createElement("input");f.type="checkbox",f.dataset.breakdownClass="possession_state",f.addEventListener("change",()=>{f.checked?i.add("possession_state"):i.delete("possession_state"),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const p=document.createElement("span");p.textContent="Control",h.append(f,p),d.append(h);const g=document.createElement("label");g.className="toggle";const _=document.createElement("input");_.type="checkbox",_.dataset.breakdownClass="field_third",_.addEventListener("change",()=>{_.checked?i.add("field_third"):i.delete("field_third"),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const m=document.createElement("span");m.textContent="Thirds",g.append(_,m),d.append(g);const v=document.createElement("label");v.className="toggle";const y=document.createElement("input");y.type="checkbox",y.dataset.breakdownClass="field_half",y.addEventListener("change",()=>{y.checked?i.add("field_half"):i.delete("field_half"),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const b=document.createElement("span");b.textContent="Halves",v.append(y,b),d.append(v),e.append(o,d)}return a(),e}};function a(){if(e){for(const o of e.querySelectorAll("input[data-breakdown-class]")){const l=o.dataset.breakdownClass;o.checked=l?i.has(l):!1}if(t){const o=s.filter(l=>i.has(l));t.textContent=o.length===0?"Total only":o.map(l=>l==="possession_state"?"Control":l==="field_half"?"Halves":"Thirds").join(" x ")}}}function r(){return s.filter(o=>i.has(o))}}function T4(){let n=null;return{id:"fifty-fifty",label:"50/50",setup(e){n=new u5(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},getTimelineEvents(e){return R5(e.statsTimeline,e.replay)},getTimelineRanges(e){return c4(e.statsTimeline,e.replay)},renderStats(e,t){const i=zt(t.statsFrameLookup,e);if(!i)return"";const s=sf("Challenge Summary",kV(i.team_zero?.fifty_fifty)),a=si(i.players,r=>Tn(r.name,r.is_team_0,ix(r.fifty_fifty)));return s+a},renderFocusedPlayerStats(e,t,i){const s=wn(i,t,e);return s?ix(s.fifty_fifty):""}}}function M4(){let n=null,e=null;return{id:"ball_half",label:"Half Control",setup(t){e=t.replay,n=new LV(t.player.sceneState.replayRoot,t.fieldScale)},teardown(){n?.dispose(),n=null,e=null},onBeforeRender(t){const i=e?.ballFrames[t.frameIndex];n?.update(i?.position?.y??null)},getTimelineRanges(t){return a4(t.statsTimeline,t.replay)},renderStats(t,i){const a=zt(i.statsFrameLookup,t)?.team_zero?.ball_half;return a?sf("Field State",lx(a,{labelPerspective:{kind:"shared"}})):""},renderFocusedPlayerStats(t,i,s){const a=zt(s.statsFrameLookup,i),r=wn(s,i,t),o=r?.is_team_0?a?.team_zero?.ball_half:a?.team_one?.ball_half;return!o||!r?"":lx(o,{labelPerspective:{kind:"team"}})}}}function E4(){return{id:"ball_third",label:"Third Control",setup(){},teardown(){},onBeforeRender(){},getTimelineRanges(n){return l4(n.statsTimeline,n.replay)},renderStats(n,e){const i=zt(e.statsFrameLookup,n)?.team_zero?.ball_third;return i?sf("Field State",ux(i,{labelPerspective:{kind:"shared"}})):""},renderFocusedPlayerStats(n,e,t){const i=zt(t.statsFrameLookup,e),s=wn(t,e,n),a=s?.is_team_0?i?.team_zero?.ball_third:i?.team_one?.ball_third;return!a||!s?"":ux(a,{labelPerspective:{kind:"team"}})}}}function C4(){return{id:"rush",label:"Rush",setup(){},teardown(){},onBeforeRender(){},getTimelineRanges(n){return u4(n.statsTimeline,n.replay)},getTimelineEvents(n){return V5(n.statsTimeline,n.replay)},renderStats(n,e){const t=zt(e.statsFrameLookup,n),i=t?.team_zero?.rush,s=t?.team_one?.rush;return!i||!s?"":[Tn("Blue Team",!0,Jp(i)),Tn("Orange Team",!1,Jp(s))].join("")},renderFocusedPlayerStats(n,e,t){const i=zt(t.statsFrameLookup,e),s=wn(t,e,n),a=s?.is_team_0?i?.team_zero?.rush:i?.team_one?.rush;return!a||!s?"":Jp(a)}}}const p_={speed_band:{valueOrder:["slow","boost","supersonic"],formatValue:n=>({slow:"Slow",boost:"Boost",supersonic:"Supersonic"})[n]??n},height_band:{valueOrder:["ground","low_air","high_air"],formatValue:n=>({ground:"Ground",low_air:"Low air",high_air:"High air"})[n]??n}};function A4(n){const e=new Set,t=[];for(const i of n??[])e.has(i)||(e.add(i),t.push(i));return t}function em(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function R4(n,e,t=1){return n===void 0||Number.isNaN(n)?"?":e===void 0||Number.isNaN(e)||e<=0?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${(n*100/e).toFixed(t)}%)`}function _x(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function sd(n,e){return`
${_x(n)}${_x(e)}
`}function P4(n,e,t){for(const i of t){const{valueOrder:s}=p_[i],a=s.indexOf(n[i]),r=s.indexOf(e[i]),o=a===-1?Number.MAX_SAFE_INTEGER:a,l=r===-1?Number.MAX_SAFE_INTEGER:r;if(o!==l)return o-l}return 0}function I4(n,e){if(e.length===1){const t=e[0];return p_[t].formatValue(n[t])}return e.map(t=>p_[t].formatValue(n[t])).join(" / ")}function L4(n,e,t){if(e.length===0||!n?.labeled_tracked_time?.entries?.length)return"";const i=new Map,s=n?.labeled_tracked_time?.entries??[];for(const a of s){const r=new Map(a.labels.map(d=>[d.key,d.value])),o={};let l=!0;for(const d of e){const h=r.get(d);if(h===void 0){l=!1;break}o[d]=h}if(!l)continue;const c=e.map(d=>`${d}:${o[d]}`).join("|"),u=i.get(c);u?u.total+=a.value:i.set(c,{values:o,total:a.value})}return[...i.values()].sort((a,r)=>P4(a.values,r.values,e)).map(a=>sd(I4(a.values,e),R4(a.total,t))).join("")}function gx(n,e={}){const t=n?.tracked_time,i=n&&t&&t>0?n.speed_integral/t:t===0?0:void 0,s=A4(e.breakdownClasses),a=L4(n,s,t);return` - ${sd("Tracked",em(t,1,"s"))} - ${sd("Distance",em(n?.total_distance,0," uu"))} - ${sd("Avg speed",em(i,0," uu/s"))} + `}).join("")}
`}function uf(n,e,t=""){return XE(n,e,{metaHtml:t,tone:"shared"})}function wn(n,e,t){const i=zt(n.statsFrameLookup,e);return i?i.players.find(s=>At(s.player_id)===t)??null:null}function Q4(n,e,t){const i=n.players.find(p=>p.id===e);if(!i||!i.frames[t]?.position)return"mid";const a=i.isTeamZero,r=n.players.filter(p=>p.isTeamZero===a).length,o=[];let l=0;for(const p of n.players){if(p.isTeamZero!==a)continue;const g=p.frames[t];if(!g?.position)continue;const _=a?g.position.y:-g.position.y;o.push(_),p.id===e&&(l=_)}if(r<2||o.length!==r)return"mid";const c=Math.min(...o),u=Math.max(...o);if(u-c<=rm)return"level";const h=l-c<=rm,f=u-l<=rm;return h&&!f?"last":f&&!h?"upfield":"mid"}function eG(n){let e=null,t=null;const i=new Set,s=["possession_state","field_half","field_third"];return{id:"possession",label:"Possession",setup(){a()},teardown(){},onBeforeRender(){},getTimelineRanges(o){return D4(o.statsTimeline,o.replay)},getConfig(){return{breakdownClasses:r()}},applyConfig(o){if(i.clear(),o&&typeof o=="object"&&!Array.isArray(o)){const l=o.breakdownClasses;if(Array.isArray(l))for(const c of l)s.includes(c)&&i.add(c)}a(),n.rerenderCurrentState()},renderStats(o,l){const u=zt(l.statsFrameLookup,o)?.team_zero?.possession;return u?uf("Control State",px(u,{labelPerspective:{kind:"shared"},breakdownClasses:r()})):""},renderFocusedPlayerStats(o,l,c){const u=zt(c.statsFrameLookup,l),d=wn(c,l,o),h=d?.is_team_0?u?.team_zero?.possession:u?.team_one?.possession;return!h||!d?"":px(h,{labelPerspective:{kind:"team"},breakdownClasses:r()})},renderSettings(){if(!e){e=document.createElement("div"),e.className="module-settings-card";const o=document.createElement("div");o.className="module-settings-header";const l=document.createElement("div"),c=document.createElement("p");c.className="module-settings-eyebrow",c.textContent="Stat display";const u=document.createElement("h3");u.textContent="Possession breakdown",l.append(c,u),t=document.createElement("strong"),t.className="metric-readout",o.append(l,t);const d=document.createElement("div");d.className="module-settings-options";const h=document.createElement("label");h.className="toggle";const f=document.createElement("input");f.type="checkbox",f.dataset.breakdownClass="possession_state",f.addEventListener("change",()=>{f.checked?i.add("possession_state"):i.delete("possession_state"),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const p=document.createElement("span");p.textContent="Control",h.append(f,p),d.append(h);const g=document.createElement("label");g.className="toggle";const _=document.createElement("input");_.type="checkbox",_.dataset.breakdownClass="field_third",_.addEventListener("change",()=>{_.checked?i.add("field_third"):i.delete("field_third"),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const m=document.createElement("span");m.textContent="Thirds",g.append(_,m),d.append(g);const v=document.createElement("label");v.className="toggle";const y=document.createElement("input");y.type="checkbox",y.dataset.breakdownClass="field_half",y.addEventListener("change",()=>{y.checked?i.add("field_half"):i.delete("field_half"),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const b=document.createElement("span");b.textContent="Halves",v.append(y,b),d.append(v),e.append(o,d)}return a(),e}};function a(){if(e){for(const o of e.querySelectorAll("input[data-breakdown-class]")){const l=o.dataset.breakdownClass;o.checked=l?i.has(l):!1}if(t){const o=s.filter(l=>i.has(l));t.textContent=o.length===0?"Total only":o.map(l=>l==="possession_state"?"Control":l==="field_half"?"Halves":"Thirds").join(" x ")}}}function r(){return s.filter(o=>i.has(o))}}function tG(){let n=null;return{id:"fifty-fifty",label:"50/50",setup(e){n=new H5(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},getTimelineEvents(e){return r4(e.statsTimeline,e.replay)},getTimelineRanges(e){return z4(e.statsTimeline,e.replay)},renderStats(e,t){const i=zt(t.statsFrameLookup,e);if(!i)return"";const s=uf("Challenge Summary",d5(i.team_zero?.fifty_fifty)),a=si(i.players,r=>Tn(r.name,r.is_team_0,dx(r.fifty_fifty)));return s+a},renderFocusedPlayerStats(e,t,i){const s=wn(i,t,e);return s?dx(s.fifty_fifty):""}}}function nG(){let n=null,e=null;return{id:"ball_half",label:"Half Control",setup(t){e=t.replay,n=new c5(t.player.sceneState.replayRoot,t.fieldScale)},teardown(){n?.dispose(),n=null,e=null},onBeforeRender(t){const i=e?.ballFrames[t.frameIndex];n?.update(i?.position?.y??null)},getTimelineRanges(t){return F4(t.statsTimeline,t.replay)},renderStats(t,i){const a=zt(i.statsFrameLookup,t)?.team_zero?.ball_half;return a?uf("Field State",_x(a,{labelPerspective:{kind:"shared"}})):""},renderFocusedPlayerStats(t,i,s){const a=zt(s.statsFrameLookup,i),r=wn(s,i,t),o=r?.is_team_0?a?.team_zero?.ball_half:a?.team_one?.ball_half;return!o||!r?"":_x(o,{labelPerspective:{kind:"team"}})}}}function iG(){return{id:"ball_third",label:"Third Control",setup(){},teardown(){},onBeforeRender(){},getTimelineRanges(n){return B4(n.statsTimeline,n.replay)},renderStats(n,e){const i=zt(e.statsFrameLookup,n)?.team_zero?.ball_third;return i?uf("Field State",yx(i,{labelPerspective:{kind:"shared"}})):""},renderFocusedPlayerStats(n,e,t){const i=zt(t.statsFrameLookup,e),s=wn(t,e,n),a=s?.is_team_0?i?.team_zero?.ball_third:i?.team_one?.ball_third;return!a||!s?"":yx(a,{labelPerspective:{kind:"team"}})}}}function sG(){return{id:"rush",label:"Rush",setup(){},teardown(){},onBeforeRender(){},getTimelineRanges(n){return H4(n.statsTimeline,n.replay)},getTimelineEvents(n){return v4(n.statsTimeline,n.replay)},renderStats(n,e){const t=zt(e.statsFrameLookup,n),i=t?.team_zero?.rush,s=t?.team_one?.rush;return!i||!s?"":[Tn("Blue Team",!0,am(i)),Tn("Orange Team",!1,am(s))].join("")},renderFocusedPlayerStats(n,e,t){const i=zt(t.statsFrameLookup,e),s=wn(t,e,n),a=s?.is_team_0?i?.team_zero?.rush:i?.team_one?.rush;return!a||!s?"":am(a)}}}const x_={speed_band:{valueOrder:["slow","boost","supersonic"],formatValue:n=>({slow:"Slow",boost:"Boost",supersonic:"Supersonic"})[n]??n},height_band:{valueOrder:["ground","low_air","high_air"],formatValue:n=>({ground:"Ground",low_air:"Low air",high_air:"High air"})[n]??n}};function aG(n){const e=new Set,t=[];for(const i of n??[])e.has(i)||(e.add(i),t.push(i));return t}function om(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function rG(n,e,t=1){return n===void 0||Number.isNaN(n)?"?":e===void 0||Number.isNaN(e)||e<=0?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${(n*100/e).toFixed(t)}%)`}function Tx(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function cd(n,e){return`
${Tx(n)}${Tx(e)}
`}function oG(n,e,t){for(const i of t){const{valueOrder:s}=x_[i],a=s.indexOf(n[i]),r=s.indexOf(e[i]),o=a===-1?Number.MAX_SAFE_INTEGER:a,l=r===-1?Number.MAX_SAFE_INTEGER:r;if(o!==l)return o-l}return 0}function lG(n,e){if(e.length===1){const t=e[0];return x_[t].formatValue(n[t])}return e.map(t=>x_[t].formatValue(n[t])).join(" / ")}function cG(n,e,t){if(e.length===0||!n?.labeled_tracked_time?.entries?.length)return"";const i=new Map,s=n?.labeled_tracked_time?.entries??[];for(const a of s){const r=new Map(a.labels.map(d=>[d.key,d.value])),o={};let l=!0;for(const d of e){const h=r.get(d);if(h===void 0){l=!1;break}o[d]=h}if(!l)continue;const c=e.map(d=>`${d}:${o[d]}`).join("|"),u=i.get(c);u?u.total+=a.value:i.set(c,{values:o,total:a.value})}return[...i.values()].sort((a,r)=>oG(a.values,r.values,e)).map(a=>cd(lG(a.values,e),rG(a.total,t))).join("")}function Mx(n,e={}){const t=n?.tracked_time,i=n&&t&&t>0?n.speed_integral/t:t===0?0:void 0,s=aG(e.breakdownClasses),a=cG(n,s,t);return` + ${cd("Tracked",om(t,1,"s"))} + ${cd("Distance",om(n?.total_distance,0," uu"))} + ${cd("Avg speed",om(i,0," uu/s"))} ${a} - `}const yx="subtr-actor-flip-impulse-overlay-styles",D4=5882879,k4=16761180,tm=260,O4=760,F4=260,N4=2.5;function NE(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function U4(n,e){const t=NE(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function B4(n){return n.split("_").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function z4(n,e){return ve(n,"dodge").flatMap((t,i)=>{const s=t.dodge_impulse;if(!s)return[];const a=U4(e,t.player),r=NE(t.player),o=e.frames[t.frame]?.time??t.time,l=new S(s.estimated_direction[0],s.estimated_direction[1],s.estimated_direction[2]);return l.lengthSq()<=Number.EPSILON&&l.set(1,0,0),l.normalize(),{id:`dodge-impulse:${t.frame}:${r}:${i}`,time:o,frame:t.frame,isTeamZero:t.is_team_0,playerId:r,playerName:a,position:new S(s.start_position[0],s.start_position[1],s.start_position[2]+44),direction:l,magnitude:s.estimated_impulse_magnitude,confidence:s.confidence,directionLabel:s.direction_label}})}function H4(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function V4(){if(document.getElementById(yx))return;const n=document.createElement("style");n.id=yx,n.textContent=` + `}const Ex="subtr-actor-flip-impulse-overlay-styles",uG=5882879,dG=16761180,lm=260,hG=760,fG=260,pG=2.5;function KE(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function mG(n,e){const t=KE(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function _G(n){return n.split("_").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function gG(n,e){return ve(n,"dodge").flatMap((t,i)=>{const s=t.dodge_impulse;if(!s)return[];const a=mG(e,t.player),r=KE(t.player),o=e.frames[t.frame]?.time??t.time,l=new S(s.estimated_direction[0],s.estimated_direction[1],s.estimated_direction[2]);return l.lengthSq()<=Number.EPSILON&&l.set(1,0,0),l.normalize(),{id:`dodge-impulse:${t.frame}:${r}:${i}`,time:o,frame:t.frame,isTeamZero:t.is_team_0,playerId:r,playerName:a,position:new S(s.start_position[0],s.start_position[1],s.start_position[2]+44),direction:l,magnitude:s.estimated_impulse_magnitude,confidence:s.confidence,directionLabel:s.direction_label}})}function yG(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function vG(){if(document.getElementById(Ex))return;const n=document.createElement("style");n.id=Ex,n.textContent=` .sap-flip-impulse-overlay-root { position: absolute; inset: 0; @@ -5676,7 +5741,7 @@ void main() { border-color: rgba(255, 193, 92, 0.5); background: rgba(76, 41, 7, 0.84); } - `,document.head.append(n)}function G4(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class $4{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;labelOffset=new S(0,0,F4);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=N4;constructor(e,t,i,s){V4(),this.scene=e,this.container=t,this.markers=z4(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="flip-impulse-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-flip-impulse-overlay-root",this.container.append(this.labelRoot)}update(e){const t=H4(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.arrow.removeFromParent(),a.arrow.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.24+.72*r,c=tm+Math.min(1,s.magnitude/450)*(O4-tm);o.arrow.position.copy(s.position),o.arrow.setDirection(s.direction),o.arrow.setLength(c,70,38),o.arrow.cone.material.opacity=l,o.arrow.line.material.opacity=l,this.worldPosition.copy(s.position).add(this.labelOffset);const u=G4(this.worldPosition,this.scene.camera,this.container,this.projectedPosition);o.label.style.display=u?"block":"none",u&&(o.label.style.left=`${this.projectedPosition.x}px`,o.label.style.top=`${this.projectedPosition.y}px`,o.label.style.opacity=`${.42+.58*r}`)}}dispose(){for(const e of this.views.values())e.arrow.removeFromParent(),e.arrow.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=e.isTeamZero?D4:k4,s=new Tg(e.direction,e.position,tm,i);s.renderOrder=35,s.line.material=new Rt({color:i,transparent:!0,opacity:.9,depthWrite:!1,depthTest:!1}),s.cone.material=new Ye({color:i,transparent:!0,opacity:.9,depthWrite:!1,depthTest:!1}),this.group.add(s);const a=document.createElement("div");a.className=`sap-flip-impulse-overlay-label ${e.isTeamZero?"sap-flip-impulse-overlay-label-blue":"sap-flip-impulse-overlay-label-orange"}`,a.textContent=`${e.playerName} ${B4(e.directionLabel)} ${Math.round(e.confidence*100)}%`,this.labelRoot.append(a);const r={marker:e,arrow:s,label:a};return this.views.set(e.id,r),r}}const vx="subtr-actor-speed-flip-overlay-styles",W4=5882879,X4=16761180,K4=16185075,q4=150,Y4=230,j4=220,Z4=4;function UE(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function J4(n,e){const t=UE(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function Q4(n,e){return ve(n,"speed_flip").map(t=>{const i=J4(e,t.player),s=UE(t.player),a=e.frames[t.frame]?.time??t.time,r=t.confidence;return{id:`speed-flip:${t.frame}:${s}:${Math.round(r*1e3)}`,time:a,frame:t.frame,isTeamZero:t.is_team_0,playerId:s,playerName:i,position:{x:t.start_position[0],y:t.start_position[1],z:t.start_position[2]},quality:r,qualityLabel:`${Math.round(r*100)}%`}})}function eG(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function tG(){if(document.getElementById(vx))return;const n=document.createElement("style");n.id=vx,n.textContent=` + `,document.head.append(n)}function bG(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class xG{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;labelOffset=new S(0,0,fG);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=pG;constructor(e,t,i,s){vG(),this.scene=e,this.container=t,this.markers=gG(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="flip-impulse-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-flip-impulse-overlay-root",this.container.append(this.labelRoot)}update(e){const t=yG(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.arrow.removeFromParent(),a.arrow.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.24+.72*r,c=lm+Math.min(1,s.magnitude/450)*(hG-lm);o.arrow.position.copy(s.position),o.arrow.setDirection(s.direction),o.arrow.setLength(c,70,38),o.arrow.cone.material.opacity=l,o.arrow.line.material.opacity=l,this.worldPosition.copy(s.position).add(this.labelOffset);const u=bG(this.worldPosition,this.scene.camera,this.container,this.projectedPosition);o.label.style.display=u?"block":"none",u&&(o.label.style.left=`${this.projectedPosition.x}px`,o.label.style.top=`${this.projectedPosition.y}px`,o.label.style.opacity=`${.42+.58*r}`)}}dispose(){for(const e of this.views.values())e.arrow.removeFromParent(),e.arrow.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=e.isTeamZero?uG:dG,s=new Ig(e.direction,e.position,lm,i);s.renderOrder=35,s.line.material=new Rt({color:i,transparent:!0,opacity:.9,depthWrite:!1,depthTest:!1}),s.cone.material=new Ye({color:i,transparent:!0,opacity:.9,depthWrite:!1,depthTest:!1}),this.group.add(s);const a=document.createElement("div");a.className=`sap-flip-impulse-overlay-label ${e.isTeamZero?"sap-flip-impulse-overlay-label-blue":"sap-flip-impulse-overlay-label-orange"}`,a.textContent=`${e.playerName} ${_G(e.directionLabel)} ${Math.round(e.confidence*100)}%`,this.labelRoot.append(a);const r={marker:e,arrow:s,label:a};return this.views.set(e.id,r),r}}const Cx="subtr-actor-speed-flip-overlay-styles",wG=5882879,SG=16761180,TG=16185075,MG=150,EG=230,CG=220,AG=4;function qE(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function RG(n,e){const t=qE(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function PG(n,e){return ve(n,"speed_flip").map(t=>{const i=RG(e,t.player),s=qE(t.player),a=e.frames[t.frame]?.time??t.time,r=t.confidence;return{id:`speed-flip:${t.frame}:${s}:${Math.round(r*1e3)}`,time:a,frame:t.frame,isTeamZero:t.is_team_0,playerId:s,playerName:i,position:{x:t.start_position[0],y:t.start_position[1],z:t.start_position[2]},quality:r,qualityLabel:`${Math.round(r*100)}%`}})}function IG(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function LG(){if(document.getElementById(Cx))return;const n=document.createElement("style");n.id=Cx,n.textContent=` .sap-speed-flip-overlay-root { position: absolute; inset: 0; @@ -5713,7 +5778,7 @@ void main() { border-color: rgba(255, 193, 92, 0.5); background: rgba(76, 41, 7, 0.84); } - `,document.head.append(n)}function nG(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class iG{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;labelOffset=new S(0,0,j4);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=Z4;constructor(e,t,i,s){tG(),this.scene=e,this.container=t,this.markers=Q4(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="speed-flip-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-speed-flip-overlay-root",this.container.append(this.labelRoot)}update(e){const t=eG(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.ring.removeFromParent(),a.ring.geometry.dispose(),a.material.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.16+.56*r,c=.96+(1-r)*.22;o.material.opacity=l,o.ring.position.set(s.position.x,s.position.y,s.position.z+14),o.ring.scale.setScalar(c+s.quality*.08),this.worldPosition.set(s.position.x,s.position.y,s.position.z).add(this.labelOffset);const u=nG(this.worldPosition,this.scene.camera,this.container,this.projectedPosition);o.label.style.display=u?"block":"none",u&&(o.label.style.left=`${this.projectedPosition.x}px`,o.label.style.top=`${this.projectedPosition.y}px`,o.label.style.opacity=`${.42+.58*r}`)}}dispose(){for(const e of this.views.values())e.ring.removeFromParent(),e.ring.geometry.dispose(),e.material.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=new Ye({color:e.quality>=.75?K4:e.isTeamZero?W4:X4,transparent:!0,opacity:.8,side:ct,depthWrite:!1,depthTest:!1}),s=new ni(q4,Y4,48),a=new we(s,i);a.renderOrder=30,this.group.add(a);const r=document.createElement("div");r.className=`sap-speed-flip-overlay-label ${e.isTeamZero?"sap-speed-flip-overlay-label-blue":"sap-speed-flip-overlay-label-orange"}`,r.textContent=`${e.playerName} speed flip ${e.qualityLabel}`,this.labelRoot.append(r);const o={marker:e,ring:a,material:i,label:r};return this.views.set(e.id,o),o}}const Du=[{value:"big",label:"Big pads"},{value:"small",label:"Small pads"},{value:"ambiguous",label:"Ambiguous pads"}],nm=[{value:"both",label:"Both detectors"},{value:"inferred_only",label:"Inferred only"},{value:"reported_only",label:"Reported only"}],ku=[{value:"active",label:"Active play"},{value:"inactive",label:"Inactive play"},{value:"unknown",label:"Unknown activity"}],Ou=[{value:"own",label:"Own half"},{value:"opponent",label:"Opponent half"},{value:"unknown",label:"Unknown half"}];function sG(n,e){return n===e||n==="ambiguous"}function aG(n,e){const t=e?rG(e,ve(e,"boost_pickup")):[];return t.length===0?null:t.find(i=>At(i.player_id)===n.player.id&&i.detection!=="inferred_only"&&i.frame===n.event.frame&&sG(i.pad_type,n.pad.size))??null}function rG(n,e){if(e.length>0)return e;const t=n.events?.boost_pickups;return Array.isArray(t)?t:e}function BE(n={}){let e=null,t=null,i=null,s=null,a=null,r=null;const o=new Set(Du.map(M=>M.value)),l=new Set(nm.map(M=>M.value)),c=new Set(ku.map(M=>M.value)),u=new Set(Ou.map(M=>M.value));let d=null,h=!1;function f(M,C,w,E){const R=document.createElement("div");R.className="boost-pickup-filter-group";const D=document.createElement("p");D.className="module-settings-group-title",D.textContent=M;const O=document.createElement("div");O.className="boost-pickup-filter-options";for(const k of C){const U=document.createElement("label");U.className="toggle";const F=document.createElement("input");F.type="checkbox",F.dataset.boostPickupFilter=E,F.dataset.boostPickupValue=k.value,F.addEventListener("change",()=>{F.checked?w.add(k.value):w.delete(k.value),_(a),n.refreshTimelineRanges?.(),n.rerenderCurrentState?.(),n.requestConfigSync?.()});const W=document.createElement("span");W.textContent=k.label,U.append(F,W),O.append(U)}return R.append(D,O),R}function p(){const M=document.createElement("div");M.className="boost-pickup-filter-group boost-pickup-filter-group-wide",i=M;const C=document.createElement("p");return C.className="module-settings-group-title",C.textContent="Player",s=document.createElement("div"),s.className="boost-pickup-filter-options",M.append(C,s),M}function g(M){if(s&&(s.replaceChildren(),i&&(i.hidden=!M||M.players.length===0),!!M))for(const C of M.players){const w=document.createElement("label");w.className="toggle";const E=document.createElement("input");E.type="checkbox",E.dataset.boostPickupPlayerId=C.id,E.addEventListener("change",()=>{d||(d=new Set(M.players.map(D=>D.id))),E.checked?d.add(C.id):d.delete(C.id),_(M),n.refreshTimelineRanges?.(),n.rerenderCurrentState?.(),n.requestConfigSync?.()});const R=document.createElement("span");R.textContent=`${C.name} (${C.isTeamZero?"Blue":"Orange"})`,w.append(E,R),s.append(w)}}function _(M){if(e){for(const C of e.querySelectorAll("input[data-boost-pickup-filter][data-boost-pickup-value]")){const w=C.dataset.boostPickupFilter,E=C.dataset.boostPickupValue;C.checked=m(w,E)}for(const C of e.querySelectorAll("input[data-boost-pickup-player-id]")){const w=C.dataset.boostPickupPlayerId;C.checked=w?d?.has(w)??!0:!1}t&&(t.textContent=v(M))}}function m(M,C){if(!C)return!1;switch(M){case"pad-type":return o.has(C);case"detection":return l.has(C);case"activity":return c.has(C);case"field-half":return u.has(C);default:return!1}}function v(M){const C=M?.players.length??0,w=d?d.size:C;if(o.size===0||l.size===0||c.size===0||u.size===0||d!==null&&d.size===0)return"Hidden";const R=[o.sizeR.value));for(const R of w)typeof R=="string"&&E.has(R)&&M.add(R)}function T(){return{padTypes:[...o],detections:[...l],activities:[...c],fieldHalves:[...u],playerIds:d?[...d]:null}}function x(M){if(!M||typeof M!="object"||Array.isArray(M))return;const C=M;b(o,Du,C.padTypes),b(l,nm,C.detections),b(c,ku,C.activities),b(u,Ou,C.fieldHalves),d=Array.isArray(C.playerIds)?new Set(C.playerIds.filter(w=>typeof w=="string")):null,h=a===null&&d!==null,_(a),n.refreshTimelineRanges?.(),n.rerenderCurrentState?.(),n.requestConfigSync?.()}return{setup(M){a!==M.replay&&(a=M.replay,h?h=!1:d=null),r=M.statsTimeline,_(M.replay)},teardown(){},getConfig:T,applyConfig:x,getTimelineRangeOptions(){const M={padTypes:o,detections:l,activities:c,fieldHalves:u};return d&&(M.playerIds=d),M},includePickup:y,renderSettings(M,C){if(!e){e=document.createElement("div"),e.className="boost-pickup-filter-panel";const w=document.createElement("div");w.className="boost-pickup-filter-summary",t=document.createElement("strong"),t.className="metric-readout",w.append(t);const E=document.createElement("div");E.className="boost-pickup-filter-grid",E.append(f("Pad type",Du,o,"pad-type"),f("Activity",ku,c,"activity"),f("Field half",Ou,u,"field-half"),p()),(C.showHeader??!1)&&e.append(w),e.append(E)}return g(M?.replay??null),_(M?.replay??null),e}}}function ai(n){return{id:n.id,label:n.label,setup(){},teardown(){},onBeforeRender(){},getTimelineEvents:n.getTimelineEvents,getTimelineRanges:n.getTimelineRanges,renderStats(e,t){const i=zt(t.statsFrameLookup,e);return i?si(i.players,s=>Tn(s.name,s.is_team_0,n.render(n.select(s),s))):""},renderFocusedPlayerStats(e,t,i){const s=wn(i,t,e);return s?n.render(n.select(s),s):""}}}function Ui(n){return n==null?"?":Qh(n).toFixed(0)}function oG(n,e){const t=Ui(n);if(n==null||e==null)return t;const i=Ui(n+e);return`${t} (${i})`}function im(n){n&&typeof n=="object"&&"dispose"in n&&typeof n.dispose=="function"&&n.dispose()}function lG(n){n&&(n.removeFromParent(),n.traverse(e=>{const t="geometry"in e?e.geometry:null;im(t);const i="material"in e?e.material:null;if(Array.isArray(i))for(const s of i)im(s);else im(i)}))}function cG(){let n=0,e=null;return{acquire(t){e||(e=DV(t.player.sceneState.replayRoot,t.fieldScale)),n+=1},release(){n<=0||(n-=1,n===0&&(lG(e),e=null))}}}const bx=cG();function nt(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function Le(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function m_(n,e=0){return Le(n,e,"%")}function zE(n,e,t=1,i=0){if(n===void 0||Number.isNaN(n))return m_(e,i);const s=Le(n,t,"s");return e===void 0||Number.isNaN(e)?s:`${s} (${m_(e,i)})`}function za(n,e,t=1,i=0){const s=n!==void 0&&e!==void 0&&!Number.isNaN(n)&&!Number.isNaN(e)&&e>0?n*100/e:void 0;return zE(n,s,t,i)}function bt(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function ds(n){const e=bt(n);return e===void 0?void 0:e*100}function HE(n){return bt(n?.tracked_time)}function uG(n,e,t){const i=bt(n?.[e]);if(i!==void 0)return i;const s=HE(n),a=bt(n?.[t]);if(!(s===void 0||s<=0||a===void 0))return a*100/s}function An(n,e,t){return zE(bt(n?.[t]),uG(n,e,t))}function xx(n,e,t){const i=bt(n?.[e]);if(i!==void 0)return i;const s=HE(n),a=bt(n?.[t]);if(!(s===void 0||s<=0||a===void 0))return a/s}function wx(n){return` + `,document.head.append(n)}function kG(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class DG{scene;container;group=new Mt;labelRoot;projectedPosition=new S;worldPosition=new S;labelOffset=new S(0,0,CG);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=AG;constructor(e,t,i,s){LG(),this.scene=e,this.container=t,this.markers=PG(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="speed-flip-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-speed-flip-overlay-root",this.container.append(this.labelRoot)}update(e){const t=IG(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.ring.removeFromParent(),a.ring.geometry.dispose(),a.material.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.16+.56*r,c=.96+(1-r)*.22;o.material.opacity=l,o.ring.position.set(s.position.x,s.position.y,s.position.z+14),o.ring.scale.setScalar(c+s.quality*.08),this.worldPosition.set(s.position.x,s.position.y,s.position.z).add(this.labelOffset);const u=kG(this.worldPosition,this.scene.camera,this.container,this.projectedPosition);o.label.style.display=u?"block":"none",u&&(o.label.style.left=`${this.projectedPosition.x}px`,o.label.style.top=`${this.projectedPosition.y}px`,o.label.style.opacity=`${.42+.58*r}`)}}dispose(){for(const e of this.views.values())e.ring.removeFromParent(),e.ring.geometry.dispose(),e.material.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=new Ye({color:e.quality>=.75?TG:e.isTeamZero?wG:SG,transparent:!0,opacity:.8,side:ct,depthWrite:!1,depthTest:!1}),s=new ni(MG,EG,48),a=new we(s,i);a.renderOrder=30,this.group.add(a);const r=document.createElement("div");r.className=`sap-speed-flip-overlay-label ${e.isTeamZero?"sap-speed-flip-overlay-label-blue":"sap-speed-flip-overlay-label-orange"}`,r.textContent=`${e.playerName} speed flip ${e.qualityLabel}`,this.labelRoot.append(r);const o={marker:e,ring:a,material:i,label:r};return this.views.set(e.id,o),o}}const Nu=[{value:"big",label:"Big pads"},{value:"small",label:"Small pads"},{value:"ambiguous",label:"Ambiguous pads"}],cm=[{value:"both",label:"Both detectors"},{value:"inferred_only",label:"Inferred only"},{value:"reported_only",label:"Reported only"}],Uu=[{value:"active",label:"Active play"},{value:"inactive",label:"Inactive play"},{value:"unknown",label:"Unknown activity"}],Bu=[{value:"own",label:"Own half"},{value:"opponent",label:"Opponent half"},{value:"unknown",label:"Unknown half"}];function OG(n,e){return n===e||n==="ambiguous"}function FG(n,e){const t=e?NG(e,ve(e,"boost_pickup")):[];return t.length===0?null:t.find(i=>At(i.player_id)===n.player.id&&i.detection!=="inferred_only"&&i.frame===n.event.frame&&OG(i.pad_type,n.pad.size))??null}function NG(n,e){if(e.length>0)return e;const t=n.events?.boost_pickups;return Array.isArray(t)?t:e}function YE(n={}){let e=null,t=null,i=null,s=null,a=null,r=null;const o=new Set(Nu.map(M=>M.value)),l=new Set(cm.map(M=>M.value)),c=new Set(Uu.map(M=>M.value)),u=new Set(Bu.map(M=>M.value));let d=null,h=!1;function f(M,C,w,E){const R=document.createElement("div");R.className="boost-pickup-filter-group";const k=document.createElement("p");k.className="module-settings-group-title",k.textContent=M;const O=document.createElement("div");O.className="boost-pickup-filter-options";for(const D of C){const U=document.createElement("label");U.className="toggle";const F=document.createElement("input");F.type="checkbox",F.dataset.boostPickupFilter=E,F.dataset.boostPickupValue=D.value,F.addEventListener("change",()=>{F.checked?w.add(D.value):w.delete(D.value),_(a),n.refreshTimelineRanges?.(),n.rerenderCurrentState?.(),n.requestConfigSync?.()});const W=document.createElement("span");W.textContent=D.label,U.append(F,W),O.append(U)}return R.append(k,O),R}function p(){const M=document.createElement("div");M.className="boost-pickup-filter-group boost-pickup-filter-group-wide",i=M;const C=document.createElement("p");return C.className="module-settings-group-title",C.textContent="Player",s=document.createElement("div"),s.className="boost-pickup-filter-options",M.append(C,s),M}function g(M){if(s&&(s.replaceChildren(),i&&(i.hidden=!M||M.players.length===0),!!M))for(const C of M.players){const w=document.createElement("label");w.className="toggle";const E=document.createElement("input");E.type="checkbox",E.dataset.boostPickupPlayerId=C.id,E.addEventListener("change",()=>{d||(d=new Set(M.players.map(k=>k.id))),E.checked?d.add(C.id):d.delete(C.id),_(M),n.refreshTimelineRanges?.(),n.rerenderCurrentState?.(),n.requestConfigSync?.()});const R=document.createElement("span");R.textContent=`${C.name} (${C.isTeamZero?"Blue":"Orange"})`,w.append(E,R),s.append(w)}}function _(M){if(e){for(const C of e.querySelectorAll("input[data-boost-pickup-filter][data-boost-pickup-value]")){const w=C.dataset.boostPickupFilter,E=C.dataset.boostPickupValue;C.checked=m(w,E)}for(const C of e.querySelectorAll("input[data-boost-pickup-player-id]")){const w=C.dataset.boostPickupPlayerId;C.checked=w?d?.has(w)??!0:!1}t&&(t.textContent=v(M))}}function m(M,C){if(!C)return!1;switch(M){case"pad-type":return o.has(C);case"detection":return l.has(C);case"activity":return c.has(C);case"field-half":return u.has(C);default:return!1}}function v(M){const C=M?.players.length??0,w=d?d.size:C;if(o.size===0||l.size===0||c.size===0||u.size===0||d!==null&&d.size===0)return"Hidden";const R=[o.sizeR.value));for(const R of w)typeof R=="string"&&E.has(R)&&M.add(R)}function T(){return{padTypes:[...o],detections:[...l],activities:[...c],fieldHalves:[...u],playerIds:d?[...d]:null}}function x(M){if(!M||typeof M!="object"||Array.isArray(M))return;const C=M;b(o,Nu,C.padTypes),b(l,cm,C.detections),b(c,Uu,C.activities),b(u,Bu,C.fieldHalves),d=Array.isArray(C.playerIds)?new Set(C.playerIds.filter(w=>typeof w=="string")):null,h=a===null&&d!==null,_(a),n.refreshTimelineRanges?.(),n.rerenderCurrentState?.(),n.requestConfigSync?.()}return{setup(M){a!==M.replay&&(a=M.replay,h?h=!1:d=null),r=M.statsTimeline,_(M.replay)},teardown(){},getConfig:T,applyConfig:x,getTimelineRangeOptions(){const M={padTypes:o,detections:l,activities:c,fieldHalves:u};return d&&(M.playerIds=d),M},includePickup:y,renderSettings(M,C){if(!e){e=document.createElement("div"),e.className="boost-pickup-filter-panel";const w=document.createElement("div");w.className="boost-pickup-filter-summary",t=document.createElement("strong"),t.className="metric-readout",w.append(t);const E=document.createElement("div");E.className="boost-pickup-filter-grid",E.append(f("Pad type",Nu,o,"pad-type"),f("Activity",Uu,c,"activity"),f("Field half",Bu,u,"field-half"),p()),(C.showHeader??!1)&&e.append(w),e.append(E)}return g(M?.replay??null),_(M?.replay??null),e}}}function ai(n){return{id:n.id,label:n.label,setup(){},teardown(){},onBeforeRender(){},getTimelineEvents:n.getTimelineEvents,getTimelineRanges:n.getTimelineRanges,renderStats(e,t){const i=zt(t.statsFrameLookup,e);return i?si(i.players,s=>Tn(s.name,s.is_team_0,n.render(n.select(s),s))):""},renderFocusedPlayerStats(e,t,i){const s=wn(i,t,e);return s?n.render(n.select(s),s):""}}}function Bi(n){return n==null?"?":rf(n).toFixed(0)}function UG(n,e){const t=Bi(n);if(n==null||e==null)return t;const i=Bi(n+e);return`${t} (${i})`}function um(n){n&&typeof n=="object"&&"dispose"in n&&typeof n.dispose=="function"&&n.dispose()}function BG(n){n&&(n.removeFromParent(),n.traverse(e=>{const t="geometry"in e?e.geometry:null;um(t);const i="material"in e?e.material:null;if(Array.isArray(i))for(const s of i)um(s);else um(i)}))}function zG(){let n=0,e=null;return{acquire(t){e||(e=u5(t.player.sceneState.replayRoot,t.fieldScale)),n+=1},release(){n<=0||(n-=1,n===0&&(BG(e),e=null))}}}const Ax=zG();function nt(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function Le(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function w_(n,e=0){return Le(n,e,"%")}function jE(n,e,t=1,i=0){if(n===void 0||Number.isNaN(n))return w_(e,i);const s=Le(n,t,"s");return e===void 0||Number.isNaN(e)?s:`${s} (${w_(e,i)})`}function Ha(n,e,t=1,i=0){const s=n!==void 0&&e!==void 0&&!Number.isNaN(n)&&!Number.isNaN(e)&&e>0?n*100/e:void 0;return jE(n,s,t,i)}function bt(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function ds(n){const e=bt(n);return e===void 0?void 0:e*100}function ZE(n){return bt(n?.tracked_time)}function HG(n,e,t){const i=bt(n?.[e]);if(i!==void 0)return i;const s=ZE(n),a=bt(n?.[t]);if(!(s===void 0||s<=0||a===void 0))return a*100/s}function An(n,e,t){return jE(bt(n?.[t]),HG(n,e,t))}function Rx(n,e,t){const i=bt(n?.[e]);if(i!==void 0)return i;const s=ZE(n),a=bt(n?.[t]);if(!(s===void 0||s<=0||a===void 0))return a/s}function Px(n){return`
Most back${An(n,"percent_most_back","time_most_back")}
Most forward${An(n,"percent_most_forward","time_most_forward")}
Mid role${An(n,"percent_mid_role","time_mid_role")}
@@ -5725,59 +5790,59 @@ void main() {
Behind ball${An(n,"percent_behind_ball","time_behind_ball")}
Level with ball${An(n,"percent_level_with_ball","time_level_with_ball")}
In front of ball${An(n,"percent_in_front_of_ball","time_in_front_of_ball")}
- `}function Sx(n){return` + `}function Ix(n){return`
Defensive zone${An(n,"percent_defensive_third","time_defensive_third")}
Neutral zone${An(n,"percent_neutral_third","time_neutral_third")}
Offensive zone${An(n,"percent_offensive_third","time_offensive_third")}
Defensive half${An(n,"percent_defensive_half","time_defensive_half")}
Offensive half${An(n,"percent_offensive_half","time_offensive_half")}
-
To teammates${Le(xx(n,"average_distance_to_teammates","sum_distance_to_teammates"),0)}
-
To ball${Le(xx(n,"average_distance_to_ball","sum_distance_to_ball"),0)}
- `}function Fu(n,e){return za(bt(n?.[e]),bt(n?.active_game_time))}function dG(n){return n?n.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "):"?"}function hG(n){const e=n&&n.first_man_stint_count>0?n.time_first_man/n.first_man_stint_count:void 0;return` -
Current role${dG(n?.current_role_state)}
-
First man${Fu(n,"time_first_man")}
+
To teammates${Le(Rx(n,"average_distance_to_teammates","sum_distance_to_teammates"),0)}
+
To ball${Le(Rx(n,"average_distance_to_ball","sum_distance_to_ball"),0)}
+ `}function zu(n,e){return Ha(bt(n?.[e]),bt(n?.active_game_time))}function VG(n){return n?n.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "):"?"}function GG(n){const e=n&&n.first_man_stint_count>0?n.time_first_man/n.first_man_stint_count:void 0;return` +
Current role${VG(n?.current_role_state)}
+
First man${zu(n,"time_first_man")}
First stints${nt(n?.first_man_stint_count)}
Avg first stint${Le(e,2,"s")}
Longest first stint${Le(n?.longest_first_man_stint_time,2,"s")}
-
Second man${Fu(n,"time_second_man")}
-
Third man${Fu(n,"time_third_man")}
-
Ambiguous${Fu(n,"time_ambiguous_role")}
+
Second man${zu(n,"time_second_man")}
+
Third man${zu(n,"time_third_man")}
+
Ambiguous${zu(n,"time_ambiguous_role")}
Became first${nt(n?.became_first_man_count)}
Lost first${nt(n?.lost_first_man_count)}
- `}function fG(n){const e=n&&n.shots>0?n.goals*100/n.shots:void 0;return` + `}function $G(n){const e=n&&n.shots>0?n.goals*100/n.shots:void 0;return`
Score${nt(n?.score)}
Goals${nt(n?.goals)}
Assists${nt(n?.assists)}
Saves${nt(n?.saves)}
Shots${nt(n?.shots)}
-
Shooting %${m_(e)}
- `}function pG(n){return` +
Shooting %${w_(e)}
+ `}function WG(n){return`
Hits${nt(n?.count)}
Since last${Le(bt(n?.time_since_last_backboard),2,"s")}
- `}function mG(n){return` + `}function XG(n){return`
Count${nt(n?.count)}
Since last${Le(bt(n?.time_since_last_double_tap),2,"s")}
- `}function _G(n){const e=n&&n.completed_pass_count>0?n.total_pass_distance/n.completed_pass_count:void 0,t=n&&n.completed_pass_count>0?n.total_pass_advance/n.completed_pass_count:void 0;return` + `}function KG(n){const e=n&&n.completed_pass_count>0?n.total_pass_distance/n.completed_pass_count:void 0,t=n&&n.completed_pass_count>0?n.total_pass_advance/n.completed_pass_count:void 0;return`
Completed${nt(n?.completed_pass_count)}
Received${nt(n?.received_pass_count)}
Avg distance${Le(e,0)}
Avg advance${Le(t,0)}
Longest${Le(n?.longest_pass_distance,0)}
Since last${Le(bt(n?.time_since_last_completed_pass),2,"s")}
- `}function gG(n){const e=n&&n.count>0?n.total_ball_speed/n.count:void 0,t=n&&n.count>0?n.total_pass_distance/n.count:void 0;return` + `}function qG(n){const e=n&&n.count>0?n.total_ball_speed/n.count:void 0,t=n&&n.count>0?n.total_pass_distance/n.count:void 0;return`
Attempts${nt(n?.count)}
Avg speed${Le(e,0)}
Fastest${Le(n?.fastest_ball_speed,0)}
Avg pass distance${Le(t,0)}
Since last${Le(bt(n?.time_since_last_one_timer),2,"s")}
- `}function Tx(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0;return` + `}function Lx(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0;return`
Attempts${nt(n?.count)}
High conf${nt(n?.high_confidence_count)}
Last quality${Le(bt(n?.last_confidence),0,"%")}
Avg quality${Le(e,0,"%")}
Best quality${Le(bt(n?.best_confidence),0,"%")}
Since last${Le(bt(n?.time_since_last_ceiling_shot),2,"s")}
- `}function Mx(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0,t=ds(e),i=n&&n.count>0?n.cumulative_setup_duration/n.count:void 0,s=n&&n.count>0?n.cumulative_takeoff_to_touch_time/n.count:void 0,a=n&&n.count>0?n.cumulative_touch_height/n.count:void 0;return` + `}function kx(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0,t=ds(e),i=n&&n.count>0?n.cumulative_setup_duration/n.count:void 0,s=n&&n.count>0?n.cumulative_takeoff_to_touch_time/n.count:void 0,a=n&&n.count>0?n.cumulative_touch_height/n.count:void 0;return`
Plays${nt(n?.count)}
High conf${nt(n?.high_confidence_count)}
Last quality${Le(ds(n?.last_confidence),0,"%")}
@@ -5786,7 +5851,7 @@ void main() {
Avg takeoff${Le(s,2,"s")}
Avg height${Le(a,0)}
Since last${Le(bt(n?.time_since_last_wall_aerial),2,"s")}
- `}function Ex(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0,t=n&&n.count>0?n.cumulative_takeoff_to_shot_time/n.count:void 0,i=n&&n.count>0?n.cumulative_shot_height/n.count:void 0;return` + `}function Dx(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0,t=n&&n.count>0?n.cumulative_takeoff_to_shot_time/n.count:void 0,i=n&&n.count>0?n.cumulative_shot_height/n.count:void 0;return`
Shots${nt(n?.count)}
High conf${nt(n?.high_confidence_count)}
Last quality${Le(ds(n?.last_confidence),0,"%")}
@@ -5794,13 +5859,13 @@ void main() {
Avg takeoff${Le(t,2,"s")}
Avg height${Le(i,0)}
Since last${Le(bt(n?.time_since_last_wall_aerial_shot),2,"s")}
- `}function yG(n){const e=n&&n.carry_count>0?n.average_horizontal_gap_sum/n.carry_count:void 0;return` + `}function YG(n){const e=n&&n.carry_count>0?n.average_horizontal_gap_sum/n.carry_count:void 0;return`
Carries${nt(n?.carry_count)}
Total time${Le(n?.total_carry_time,1,"s")}
Longest${Le(n?.longest_carry_time,1,"s")}
Furthest${Le(n?.furthest_carry_distance,0)}
Avg gap${Le(e,0)}
- `}function vG(n){const e=n&&n.count>0?n.average_horizontal_gap_sum/n.count:void 0,t=n&&n.count>0?n.total_touch_count/n.count:void 0;return` + `}function jG(n){const e=n&&n.count>0?n.average_horizontal_gap_sum/n.count:void 0,t=n&&n.count>0?n.total_touch_count/n.count:void 0;return`
Air dribbles${nt(n?.count)}
Ground to air${nt(n?.ground_to_air_count)}
Wall to air${nt(n?.wall_to_air_count)}
@@ -5810,11 +5875,11 @@ void main() {
Longest${Le(n?.longest_time,1,"s")}
Furthest${Le(n?.furthest_distance,0)}
Avg gap${Le(e,0)}
- `}function bG(n){const e=n&&n.press_count>0?n.total_duration/n.press_count:void 0;return` + `}function ZG(n){const e=n&&n.press_count>0?n.total_duration/n.press_count:void 0;return`
Presses${nt(n?.press_count)}
Total time${Le(n?.total_duration,1,"s")}
Avg duration${Le(e,2,"s")}
- `}function xG(n){const e=n&&n.whiff_count>0?n.cumulative_closest_approach_distance/n.whiff_count:void 0;return` + `}function JG(n){const e=n&&n.whiff_count>0?n.cumulative_closest_approach_distance/n.whiff_count:void 0;return`
Whiffs${nt(n?.whiff_count)}
Beaten to ball${nt(n?.beaten_to_ball_count)}
Grounded${nt(n?.grounded_whiff_count)}
@@ -5824,10 +5889,10 @@ void main() {
Best closest${Le(bt(n?.best_closest_approach_distance),0)}
Avg closest${Le(e,0)}
Since last${Le(bt(n?.time_since_last_whiff),2,"s")}
- `}function wG(n){return` + `}function QG(n){return`
Inflicted${nt(n?.demos_inflicted)}
Taken${nt(n?.demos_taken)}
- `}function SG(n){const e=n&&n.bumps_inflicted>0?n.cumulative_bump_strength/n.bumps_inflicted:void 0;return` + `}function e$(n){const e=n&&n.bumps_inflicted>0?n.cumulative_bump_strength/n.bumps_inflicted:void 0;return`
Inflicted${nt(n?.bumps_inflicted)}
Taken${nt(n?.bumps_taken)}
Team inflicted${nt(n?.team_bumps_inflicted)}
@@ -5835,14 +5900,14 @@ void main() {
Last strength${Le(bt(n?.last_bump_strength),0)}
Max strength${Le(bt(n?.max_bump_strength),0)}
Avg strength${Le(e,0)}
- `}function TG(n){return` + `}function t$(n){return`
Refreshes${nt(n?.count)}
On ball${nt(n?.on_ball_count)}
- `}function MG(n){const e=n&&n.count>0?n.total_time_to_use/n.count:void 0;return` + `}function n$(n){const e=n&&n.count>0?n.total_time_to_use/n.count:void 0;return`
Confirmed${nt(n?.count)}
Avg use${Le(e,2,"s")}
Fastest use${Le(bt(n?.min_time_to_use),2,"s")}
- `}function Cx(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0,t=n&&n.count>0?n.cumulative_setup_duration/n.count:void 0,i=n&&n.count>0?n.cumulative_ball_speed_change/n.count:void 0;return` + `}function Ox(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0,t=n&&n.count>0?n.cumulative_setup_duration/n.count:void 0,i=n&&n.count>0?n.cumulative_ball_speed_change/n.count:void 0;return`
Attempts${nt(n?.count)}
High conf${nt(n?.high_confidence_count)}
Last quality${Le(bt(n?.last_confidence),0,"%")}
@@ -5850,56 +5915,56 @@ void main() {
Avg setup${Le(t,2,"s")}
Avg impulse${Le(i,0,"uu/s")}
Since last${Le(bt(n?.time_since_last_flick),2,"s")}
- `}function Ax(n){const e=n&&n.count>0?n.cumulative_quality/n.count:void 0;return` + `}function Fx(n){const e=n&&n.count>0?n.cumulative_quality/n.count:void 0;return`
Attempts${nt(n?.count)}
High conf${nt(n?.high_confidence_count)}
Last quality${Le(bt(n?.last_quality),0,"%")}
Avg quality${Le(e,0,"%")}
Best quality${Le(bt(n?.best_quality),0,"%")}
Since last${Le(bt(n?.time_since_last_speed_flip),2,"s")}
- `}function Rx(n){const e=n&&n.count>0?n.cumulative_quality/n.count:void 0,t=ds(n?.last_quality),i=ds(e),s=ds(n?.best_quality);return` + `}function Nx(n){const e=n&&n.count>0?n.cumulative_quality/n.count:void 0,t=ds(n?.last_quality),i=ds(e),s=ds(n?.best_quality);return`
Attempts${nt(n?.count)}
High conf${nt(n?.high_confidence_count)}
Last quality${Le(t,0,"%")}
Avg quality${Le(i,0,"%")}
Best quality${Le(s,0,"%")}
Since last${Le(bt(n?.time_since_last_half_flip),2,"s")}
- `}function Px(n){const e=n&&n.count>0?n.cumulative_quality/n.count:void 0,t=ds(n?.last_quality),i=ds(e),s=ds(n?.best_quality);return` + `}function Ux(n){const e=n&&n.count>0?n.cumulative_quality/n.count:void 0,t=ds(n?.last_quality),i=ds(e),s=ds(n?.best_quality);return`
Attempts${nt(n?.count)}
High conf${nt(n?.high_confidence_count)}
Last quality${Le(t,0,"%")}
Avg quality${Le(i,0,"%")}
Best quality${Le(s,0,"%")}
Since last${Le(bt(n?.time_since_last_wavedash),2,"s")}
- `}function Ix(n){const e=n&&n.tracked_time>0?Qh(n.boost_integral/n.tracked_time).toFixed(0):"?",t=bt(n?.tracked_time);return` -
Collected${oG(n?.amount_collected,n?.amount_respawned)}
-
Inactive collected${Ui(n?.amount_collected_inactive)}
-
Big pads amt${Ui(n?.amount_collected_big)}
-
Small pads amt${Ui(n?.amount_collected_small)}
-
Respawns${Ui(n?.amount_respawned)}
-
Overfill${Ui(n?.overfill_total)}
-
Used${Ui(n?.amount_used)}
-
Used ground${Ui(n?.amount_used_while_grounded)}
-
Used air${Ui(n?.amount_used_while_airborne)}
+ `}function Bx(n){const e=n&&n.tracked_time>0?rf(n.boost_integral/n.tracked_time).toFixed(0):"?",t=bt(n?.tracked_time);return` +
Collected${UG(n?.amount_collected,n?.amount_respawned)}
+
Inactive collected${Bi(n?.amount_collected_inactive)}
+
Big pads amt${Bi(n?.amount_collected_big)}
+
Small pads amt${Bi(n?.amount_collected_small)}
+
Respawns${Bi(n?.amount_respawned)}
+
Overfill${Bi(n?.overfill_total)}
+
Used${Bi(n?.amount_used)}
+
Used ground${Bi(n?.amount_used_while_grounded)}
+
Used air${Bi(n?.amount_used_while_airborne)}
Big pads${n?.big_pads_collected??"?"}
Small pads${n?.small_pads_collected??"?"}
Inactive big pads${n?.big_pads_collected_inactive??"?"}
Inactive small pads${n?.small_pads_collected_inactive??"?"}
-
Stolen${Ui(n?.amount_stolen)}
+
Stolen${Bi(n?.amount_stolen)}
Avg boost${e}
-
Time @ 0${za(bt(n?.time_zero_boost),t)}
-
Time 0-25${za(bt(n?.time_boost_0_25),t)}
-
Time 25-50${za(bt(n?.time_boost_25_50),t)}
-
Time 50-75${za(bt(n?.time_boost_50_75),t)}
-
Time 75-100${za(bt(n?.time_boost_75_100),t)}
-
Time @ 100${za(bt(n?.time_hundred_boost),t)}
- `}const __={kind:{label:"Kind",valueOrder:["control","medium_hit","hard_hit"],formatValue:n=>({control:"Control",medium_hit:"Medium",hard_hit:"Hard"})[n]??n},height_band:{label:"Height",valueOrder:["ground","low_air","high_air"],formatValue:n=>({ground:"Ground",low_air:"Low air",high_air:"High air"})[n]??n},surface:{label:"Surface",valueOrder:["ground","air","wall"],formatValue:n=>({ground:"Ground",air:"Air",wall:"Wall"})[n]??n},dodge_state:{label:"Dodge",valueOrder:["no_dodge","dodge"],formatValue:n=>({no_dodge:"No dodge",dodge:"Dodge"})[n]??n}};function EG(n){const e=new Set,t=[];for(const i of n??[])e.has(i)||(e.add(i),t.push(i));return t}function Qs(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function sm(n,e=0,t=""){return n===void 0||!Number.isFinite(n)?"?":`${n.toFixed(e)}${t}`}function Lx(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Xi(n,e){return`
${Lx(n)}${Lx(e)}
`}function CG(n,e,t){for(const i of t){const{valueOrder:s}=__[i],a=s.indexOf(n[i]),r=s.indexOf(e[i]),o=a===-1?Number.MAX_SAFE_INTEGER:a,l=r===-1?Number.MAX_SAFE_INTEGER:r;if(o!==l)return o-l}return 0}function AG(n,e){if(e.length===1){const t=e[0];return __[t].formatValue(n[t])}return e.map(t=>__[t].formatValue(n[t])).join(" / ")}function RG(n){return(n?.labeled_touch_counts?.entries??[]).map(e=>({labels:e.labels,count:e.count}))}function PG(n,e){if(e.length===0||n.length===0)return"";const t=new Map;for(const i of n){const s=new Map(i.labels.map(c=>[c.key,c.value])),a={};let r=!0;for(const c of e){const u=s.get(c);if(u===void 0){r=!1;break}a[c]=u}if(!r)continue;const o=e.map(c=>`${c}:${a[c]}`).join("|"),l=t.get(o);l?l.count+=i.count:t.set(o,{values:a,count:i.count})}return[...t.values()].sort((i,s)=>CG(i.values,s.values,e)).map(i=>Xi(AG(i.values,e),Qs(i.count))).join("")}function IG(n,e){if(!n||e.length!==1)return"";const[t]=e;if(t==="kind")return[Xi("Control",Qs(n.control_touch_count)),Xi("Medium",Qs(n.medium_hit_count)),Xi("Hard",Qs(n.hard_hit_count))].join("");if(t==="height_band"){const i=n.high_aerial_touch_count??0,s=(n.aerial_touch_count??0)-i,a=(n.touch_count??0)-(n.aerial_touch_count??0);return[Xi("Ground",Qs(a)),Xi("Low air",Qs(s)),Xi("High air",Qs(i))].join("")}return""}function Dx(n,e={}){const t=EG(e.breakdownClasses),i=RG(n),s=PG(i,t)||IG(n,t);return` - ${Xi("Touches",Qs(n?.touch_count))} - ${Xi("Ball advanced",sm(n?.total_ball_advance_distance,0," uu"))} - ${Xi("Ball traveled",sm(n?.total_ball_travel_distance,0," uu"))} - ${Xi("Ball retreated",sm(n?.total_ball_retreat_distance,0," uu"))} +
Time @ 0${Ha(bt(n?.time_zero_boost),t)}
+
Time 0-25${Ha(bt(n?.time_boost_0_25),t)}
+
Time 25-50${Ha(bt(n?.time_boost_25_50),t)}
+
Time 50-75${Ha(bt(n?.time_boost_50_75),t)}
+
Time 75-100${Ha(bt(n?.time_boost_75_100),t)}
+
Time @ 100${Ha(bt(n?.time_hundred_boost),t)}
+ `}const S_={kind:{label:"Kind",valueOrder:["control","medium_hit","hard_hit"],formatValue:n=>({control:"Control",medium_hit:"Medium",hard_hit:"Hard"})[n]??n},height_band:{label:"Height",valueOrder:["ground","low_air","high_air"],formatValue:n=>({ground:"Ground",low_air:"Low air",high_air:"High air"})[n]??n},surface:{label:"Surface",valueOrder:["ground","air","wall"],formatValue:n=>({ground:"Ground",air:"Air",wall:"Wall"})[n]??n},dodge_state:{label:"Dodge",valueOrder:["no_dodge","dodge"],formatValue:n=>({no_dodge:"No dodge",dodge:"Dodge"})[n]??n}};function i$(n){const e=new Set,t=[];for(const i of n??[])e.has(i)||(e.add(i),t.push(i));return t}function Qs(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function dm(n,e=0,t=""){return n===void 0||!Number.isFinite(n)?"?":`${n.toFixed(e)}${t}`}function zx(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Ki(n,e){return`
${zx(n)}${zx(e)}
`}function s$(n,e,t){for(const i of t){const{valueOrder:s}=S_[i],a=s.indexOf(n[i]),r=s.indexOf(e[i]),o=a===-1?Number.MAX_SAFE_INTEGER:a,l=r===-1?Number.MAX_SAFE_INTEGER:r;if(o!==l)return o-l}return 0}function a$(n,e){if(e.length===1){const t=e[0];return S_[t].formatValue(n[t])}return e.map(t=>S_[t].formatValue(n[t])).join(" / ")}function r$(n){return(n?.labeled_touch_counts?.entries??[]).map(e=>({labels:e.labels,count:e.count}))}function o$(n,e){if(e.length===0||n.length===0)return"";const t=new Map;for(const i of n){const s=new Map(i.labels.map(c=>[c.key,c.value])),a={};let r=!0;for(const c of e){const u=s.get(c);if(u===void 0){r=!1;break}a[c]=u}if(!r)continue;const o=e.map(c=>`${c}:${a[c]}`).join("|"),l=t.get(o);l?l.count+=i.count:t.set(o,{values:a,count:i.count})}return[...t.values()].sort((i,s)=>s$(i.values,s.values,e)).map(i=>Ki(a$(i.values,e),Qs(i.count))).join("")}function l$(n,e){if(!n||e.length!==1)return"";const[t]=e;if(t==="kind")return[Ki("Control",Qs(n.control_touch_count)),Ki("Medium",Qs(n.medium_hit_count)),Ki("Hard",Qs(n.hard_hit_count))].join("");if(t==="height_band"){const i=n.high_aerial_touch_count??0,s=(n.aerial_touch_count??0)-i,a=(n.touch_count??0)-(n.aerial_touch_count??0);return[Ki("Ground",Qs(a)),Ki("Low air",Qs(s)),Ki("High air",Qs(i))].join("")}return""}function Hx(n,e={}){const t=i$(e.breakdownClasses),i=r$(n),s=o$(i,t)||l$(n,t);return` + ${Ki("Touches",Qs(n?.touch_count))} + ${Ki("Ball advanced",dm(n?.total_ball_advance_distance,0," uu"))} + ${Ki("Ball traveled",dm(n?.total_ball_travel_distance,0," uu"))} + ${Ki("Ball retreated",dm(n?.total_ball_retreat_distance,0," uu"))} ${s} - `}const g_="subtr-actor:touch-color-modes-change",LG=[{title:"Team",mode:"team"},{title:"Intention",mode:"intention"},{title:"Hit strength",mode:"kind"},{title:"Height",mode:"height_band"},{title:"Surface",mode:"surface"},{title:"Dodge",mode:"dodge_state"},{title:"Flags",mode:"flag"}];function DG(n){return LG.find(e=>e.title===n)?.mode??"team"}function kG(n){return`#${n.toString(16).padStart(6,"0")}`}function VE(n,e){n.replaceChildren();const t=ho(e),i=new Set(t),s=document.createElement("div");s.className="touch-color-legend-explainer";const a=document.createElement("span");a.textContent="Toggle sections to add or remove rings";const r=document.createElement("span");r.textContent="The outermost enabled ring sets the label tint",s.append(a,r),n.append(s);for(const o of BH){const l=DG(o.title),c=i.has(l),u=document.createElement("section");u.className="touch-color-legend-group",u.dataset.active=c?"true":"false";const d=document.createElement("button");d.type="button",d.className="touch-color-legend-heading",d.dataset.colorMode=l,d.dataset.active=c?"true":"false",d.textContent=o.title,d.addEventListener("click",()=>{const f=new Set(i);f.has(l)?f.delete(l):f.add(l);const p=NH.filter(g=>f.has(g));n.dispatchEvent(new CustomEvent(g_,{bubbles:!0,detail:{colorModes:p}})),VE(n,p)});const h=document.createElement("div");h.className="touch-color-legend-list";for(const f of o.entries){const p=document.createElement("div");p.className="touch-color-legend-item";const g=document.createElement("span");g.className="touch-color-legend-swatch",g.style.background=kG(f.color);const _=document.createElement("span");_.textContent=f.label,p.append(g,_),h.append(p)}u.append(d,h),n.append(u)}}function OG(n){let e=null,t=5,i="advancement",s=["team"],a=null,r=null,o=null,l=null,c=null;const u=new Set,d=["kind","height_band","surface","dodge_state"];return{id:"touch",label:"Touch",setup(g){e=new ZH(g.player.sceneState,g.player.container,g.replay,g.statsTimeline,{mode:i,colorModes:s}),e.setDecaySeconds(t),c=_=>{if(!(_ instanceof CustomEvent))return;const m=_.detail?.colorModes;Array.isArray(m)&&p(m.filter(ed))},window.addEventListener(g_,c),h()},teardown(){c&&(window.removeEventListener(g_,c),c=null),e?.dispose(),e=null},onBeforeRender(g){e?.update(g.currentTime)},getTimelineEvents(g){return I5(g.statsTimeline,g.replay)},getConfig(){return{decaySeconds:t,overlayMode:i,overlayColorModes:s,breakdownClasses:f()}},applyConfig(g){if(g&&typeof g=="object"&&!Array.isArray(g)){const _=g;if(typeof _.decaySeconds=="number"&&Number.isFinite(_.decaySeconds)&&(t=Math.max(1,Math.min(10,_.decaySeconds)),e?.setDecaySeconds(t)),(_.overlayMode==="markers"||_.overlayMode==="advancement")&&(i=_.overlayMode,e?.setMode(i)),Array.isArray(_.overlayColorModes)?(s=ho(_.overlayColorModes.filter(ed)),e?.setColorModes(s)):ed(_.overlayColorMode)&&(s=ho(_.overlayColorMode),e?.setColorModes(s)),u.clear(),Array.isArray(_.breakdownClasses))for(const m of _.breakdownClasses)d.includes(m)&&u.add(m)}h(),n.rerenderCurrentState()},renderStats(g,_){const m=zt(_.statsFrameLookup,g);return m?si(m.players,v=>Tn(v.name,v.is_team_0,Dx(v.touch,{breakdownClasses:f()}),v.touch?.is_last_touch?'Last Touch':"")):""},renderFocusedPlayerStats(g,_,m){const v=wn(m,_,g);return v?Dx(v.touch,{breakdownClasses:f()}):""},renderSettings(){if(!a){a=document.createElement("div"),a.className="module-settings-card";const g=document.createElement("div");g.className="module-settings-header";const _=document.createElement("div"),m=document.createElement("p");m.className="module-settings-eyebrow",m.textContent="Touch markers";const v=document.createElement("h3");v.textContent="Touch decay",_.append(m,v),r=document.createElement("strong"),r.className="metric-readout",g.append(_,r);const y=document.createElement("label"),b=document.createElement("span");b.className="label",b.textContent="Keep each marker visible after the touch";const T=document.createElement("input");T.type="range",T.min="1",T.max="10",T.step="0.5",T.value=`${t}`,T.addEventListener("input",()=>{const H=Number(T.value);t=Number.isFinite(H)?Math.max(1,Math.min(10,H)):t,e?.setDecaySeconds(t),h(t),n.requestConfigSync?.()}),y.append(b,T);const x=document.createElement("div");x.className="module-settings-subgroup";const M=document.createElement("div");M.className="module-settings-header";const C=document.createElement("div"),w=document.createElement("p");w.className="module-settings-eyebrow",w.textContent="Overlay";const E=document.createElement("h3");E.textContent="Touch mode",C.append(w,E),o=document.createElement("strong"),o.className="metric-readout",M.append(C,o);const R=document.createElement("div");R.className="module-settings-options";for(const H of[{mode:"markers",label:"Markers"},{mode:"advancement",label:"Advancement"}]){const ne=document.createElement("label");ne.className="toggle";const oe=document.createElement("input");oe.type="radio",oe.name="touch-overlay-mode",oe.dataset.overlayMode=H.mode,oe.addEventListener("change",()=>{oe.checked&&(i=H.mode,e?.setMode(i),h(),n.requestConfigSync?.())});const pe=document.createElement("span");pe.textContent=H.label,ne.append(oe,pe),R.append(ne)}x.append(M,R);const D=document.createElement("div");D.className="module-settings-subgroup";const O=document.createElement("div");O.className="module-settings-header";const k=document.createElement("div"),U=document.createElement("p");U.className="module-settings-eyebrow",U.textContent="Stat display";const F=document.createElement("h3");F.textContent="Touch breakdown",k.append(U,F),l=document.createElement("strong"),l.className="metric-readout",O.append(k,l);const W=document.createElement("div");W.className="module-settings-options";for(const H of[{className:"kind",label:"Kind"},{className:"height_band",label:"Height"},{className:"surface",label:"Surface"},{className:"dodge_state",label:"Dodge"}]){const ne=document.createElement("label");ne.className="toggle";const oe=document.createElement("input");oe.type="checkbox",oe.dataset.breakdownClass=H.className,oe.addEventListener("change",()=>{oe.checked?u.add(H.className):u.delete(H.className),h(),n.rerenderCurrentState(),n.requestConfigSync?.()});const pe=document.createElement("span");pe.textContent=H.label,ne.append(oe,pe),W.append(ne)}D.append(O,W),a.append(g,y,x,D)}return h(),a}};function h(g){if(!a)return;const _=g??t,m=a.querySelector("input");m instanceof HTMLInputElement&&(m.value=`${_}`),r&&(r.textContent=`${_.toFixed(1)}s`);for(const v of a.querySelectorAll("input[data-overlay-mode]"))v.checked=v.dataset.overlayMode===i;o&&(o.textContent=i==="advancement"?"Advancement":"Markers");for(const v of a.querySelectorAll("input[data-breakdown-class]")){const y=v.dataset.breakdownClass;v.checked=y?u.has(y):!1}if(l){const v=f();l.textContent=v.length>0?v.map(y=>({kind:"Kind",height_band:"Height",surface:"Surface",dodge_state:"Dodge"})[y]).join(" + "):"Total only"}}function f(){return d.filter(g=>u.has(g))}function p(g){s=ho(g),e?.setColorModes(s),h(),n.requestConfigSync?.()}}function FG(n,e=BE({refreshTimelineRanges:n.refreshTimelineRanges,rerenderCurrentState:n.rerenderCurrentState})){return{id:"boost",label:"Boost",setup(t){e.setup(t)},teardown(){e.teardown()},onBeforeRender(){},getTimelineRanges(t){return m4(t.statsTimeline,t.replay,e.getTimelineRangeOptions())},getConfig(){return e.getConfig()},applyConfig(t){e.applyConfig(t)},includeBoostPickupAnimationPickup(t){return e.includePickup(t)},renderStats(t,i){const s=zt(i.statsFrameLookup,t);return s?si(s.players,a=>Tn(a.name,a.is_team_0,Ix(a.boost))):""},renderFocusedPlayerStats(t,i,s){const a=wn(s,i,t);return a?Ix(a.boost):""},renderSettings(t){return e.renderSettings(t,{showHeader:!0})}}}function NG(){return ai({id:"core",label:"Core",select:n=>n.core,render:n=>fG(n)})}function UG(){return ai({id:"backboard",label:"Backboard",select:n=>n.backboard,render:n=>pG(n),getTimelineEvents(n){return L5(n.statsTimeline,n.replay)}})}function BG(){let n=null;return{id:"ceiling-shot",label:"Ceiling Shot",setup(e){n=new w5(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},renderStats(e,t){const i=zt(t.statsFrameLookup,e);return i?si(i.players,s=>Tn(s.name,s.is_team_0,Tx(s.ceiling_shot),s.ceiling_shot?.is_last_ceiling_shot?'Last Ceiling Shot':"")):""},renderFocusedPlayerStats(e,t,i){const s=wn(i,t,e);return s?Tx(s.ceiling_shot):""}}}function zG(){return{id:"wall-aerial",label:"Wall-to-Air Setup",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Mx(i.wall_aerial),i.wall_aerial?.is_last_wall_aerial?'Last Wall-to-Air Setup':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Mx(i.wall_aerial):""}}}function HG(){return{id:"wall-aerial-shot",label:"Wall Shot",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Ex(i.wall_aerial_shot),i.wall_aerial_shot?.is_last_wall_aerial_shot?'Last Wall Shot':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Ex(i.wall_aerial_shot):""}}}function VG(){return ai({id:"ball-carry",label:"Ball Carry",select:n=>n.ball_carry,render:n=>yG(n)})}function GG(){return ai({id:"air-dribble",label:"Air Dribble",select:n=>n.air_dribble,render:n=>vG(n)})}function $G(){return ai({id:"dodge-reset",label:"Dodge Refresh",select:n=>n.dodge_reset,render:n=>TG(n)})}function WG(){return ai({id:"flip-reset",label:"Flip Reset",select:n=>n.flip_reset,render:n=>MG(n)})}function XG(){return ai({id:"double-tap",label:"Double Tap",select:n=>n.double_tap,render:n=>mG(n)})}function KG(){return ai({id:"pass",label:"Pass",select:n=>n.pass,render:n=>_G(n)})}function qG(){return ai({id:"one-timer",label:"One-timer",select:n=>n.one_timer,render:n=>gG(n)})}function YG(){return{id:"flick",label:"Flick",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Cx(i.flick),i.flick?.is_last_flick?'Last Flick':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Cx(i.flick):""}}}function jG(){let n=null;return{id:"speed-flip",label:"Speed Flip",setup(e){n=new iG(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},renderStats(e,t){const i=zt(t.statsFrameLookup,e);return i?si(i.players,s=>Tn(s.name,s.is_team_0,Ax(s.speed_flip),s.speed_flip?.is_last_speed_flip?'Last Speed Flip':"")):""},renderFocusedPlayerStats(e,t,i){const s=wn(i,t,e);return s?Ax(s.speed_flip):""}}}function ZG(){let n=null;return{id:"dodge",label:"Dodge",setup(e){n=new $4(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},getTimelineEvents(e){return W5(e.statsTimeline,e.replay)},renderStats(e,t){const i=new Map;for(const a of t.replay.players)i.set(a.id,{name:a.name,isTeamZero:a.isTeamZero,count:0});for(const a of ve(t.statsTimeline,"dodge")){const r=At(a.player),o=t.replay.players.find(c=>c.id===r)??null,l=i.get(r)??{name:o?.name??r,isTeamZero:a.is_team_0,count:0};l.count+=1,i.set(r,l)}const s=[...i.values()].filter(a=>a.count>0);return s.length===0?"":`
${[!0,!1].map(a=>{const r=s.filter(l=>l.isTeamZero===a);if(r.length===0)return"";const o=a?"Blue":"Orange";return`
+ `}const T_="subtr-actor:touch-color-modes-change",c$=[{title:"Team",mode:"team"},{title:"Intention",mode:"intention"},{title:"Hit strength",mode:"kind"},{title:"Height",mode:"height_band"},{title:"Surface",mode:"surface"},{title:"Dodge",mode:"dodge_state"},{title:"Flags",mode:"flag"}];function u$(n){return c$.find(e=>e.title===n)?.mode??"team"}function d$(n){return`#${n.toString(16).padStart(6,"0")}`}function JE(n,e){n.replaceChildren();const t=po(e),i=new Set(t),s=document.createElement("div");s.className="touch-color-legend-explainer";const a=document.createElement("span");a.textContent="Toggle sections to add or remove rings";const r=document.createElement("span");r.textContent="The outermost enabled ring sets the label tint",s.append(a,r),n.append(s);for(const o of _V){const l=u$(o.title),c=i.has(l),u=document.createElement("section");u.className="touch-color-legend-group",u.dataset.active=c?"true":"false";const d=document.createElement("button");d.type="button",d.className="touch-color-legend-heading",d.dataset.colorMode=l,d.dataset.active=c?"true":"false",d.textContent=o.title,d.addEventListener("click",()=>{const f=new Set(i);f.has(l)?f.delete(l):f.add(l);const p=pV.filter(g=>f.has(g));n.dispatchEvent(new CustomEvent(T_,{bubbles:!0,detail:{colorModes:p}})),JE(n,p)});const h=document.createElement("div");h.className="touch-color-legend-list";for(const f of o.entries){const p=document.createElement("div");p.className="touch-color-legend-item";const g=document.createElement("span");g.className="touch-color-legend-swatch",g.style.background=d$(f.color);const _=document.createElement("span");_.textContent=f.label,p.append(g,_),h.append(p)}u.append(d,h),n.append(u)}}function h$(n){let e=null,t=5,i="advancement",s=["team"],a=null,r=null,o=null,l=null,c=null;const u=new Set,d=["kind","height_band","surface","dodge_state"];return{id:"touch",label:"Touch",setup(g){e=new AV(g.player.sceneState,g.player.container,g.replay,g.statsTimeline,{mode:i,colorModes:s}),e.setDecaySeconds(t),c=_=>{if(!(_ instanceof CustomEvent))return;const m=_.detail?.colorModes;Array.isArray(m)&&p(m.filter(ad))},window.addEventListener(T_,c),h()},teardown(){c&&(window.removeEventListener(T_,c),c=null),e?.dispose(),e=null},onBeforeRender(g){e?.update(g.currentTime)},getTimelineEvents(g){return l4(g.statsTimeline,g.replay)},getConfig(){return{decaySeconds:t,overlayMode:i,overlayColorModes:s,breakdownClasses:f()}},applyConfig(g){if(g&&typeof g=="object"&&!Array.isArray(g)){const _=g;if(typeof _.decaySeconds=="number"&&Number.isFinite(_.decaySeconds)&&(t=Math.max(1,Math.min(10,_.decaySeconds)),e?.setDecaySeconds(t)),(_.overlayMode==="markers"||_.overlayMode==="advancement")&&(i=_.overlayMode,e?.setMode(i)),Array.isArray(_.overlayColorModes)?(s=po(_.overlayColorModes.filter(ad)),e?.setColorModes(s)):ad(_.overlayColorMode)&&(s=po(_.overlayColorMode),e?.setColorModes(s)),u.clear(),Array.isArray(_.breakdownClasses))for(const m of _.breakdownClasses)d.includes(m)&&u.add(m)}h(),n.rerenderCurrentState()},renderStats(g,_){const m=zt(_.statsFrameLookup,g);return m?si(m.players,v=>Tn(v.name,v.is_team_0,Hx(v.touch,{breakdownClasses:f()}),v.touch?.is_last_touch?'Last Touch':"")):""},renderFocusedPlayerStats(g,_,m){const v=wn(m,_,g);return v?Hx(v.touch,{breakdownClasses:f()}):""},renderSettings(){if(!a){a=document.createElement("div"),a.className="module-settings-card";const g=document.createElement("div");g.className="module-settings-header";const _=document.createElement("div"),m=document.createElement("p");m.className="module-settings-eyebrow",m.textContent="Touch markers";const v=document.createElement("h3");v.textContent="Touch decay",_.append(m,v),r=document.createElement("strong"),r.className="metric-readout",g.append(_,r);const y=document.createElement("label"),b=document.createElement("span");b.className="label",b.textContent="Keep each marker visible after the touch";const T=document.createElement("input");T.type="range",T.min="1",T.max="10",T.step="0.5",T.value=`${t}`,T.addEventListener("input",()=>{const H=Number(T.value);t=Number.isFinite(H)?Math.max(1,Math.min(10,H)):t,e?.setDecaySeconds(t),h(t),n.requestConfigSync?.()}),y.append(b,T);const x=document.createElement("div");x.className="module-settings-subgroup";const M=document.createElement("div");M.className="module-settings-header";const C=document.createElement("div"),w=document.createElement("p");w.className="module-settings-eyebrow",w.textContent="Overlay";const E=document.createElement("h3");E.textContent="Touch mode",C.append(w,E),o=document.createElement("strong"),o.className="metric-readout",M.append(C,o);const R=document.createElement("div");R.className="module-settings-options";for(const H of[{mode:"markers",label:"Markers"},{mode:"advancement",label:"Advancement"}]){const ne=document.createElement("label");ne.className="toggle";const oe=document.createElement("input");oe.type="radio",oe.name="touch-overlay-mode",oe.dataset.overlayMode=H.mode,oe.addEventListener("change",()=>{oe.checked&&(i=H.mode,e?.setMode(i),h(),n.requestConfigSync?.())});const pe=document.createElement("span");pe.textContent=H.label,ne.append(oe,pe),R.append(ne)}x.append(M,R);const k=document.createElement("div");k.className="module-settings-subgroup";const O=document.createElement("div");O.className="module-settings-header";const D=document.createElement("div"),U=document.createElement("p");U.className="module-settings-eyebrow",U.textContent="Stat display";const F=document.createElement("h3");F.textContent="Touch breakdown",D.append(U,F),l=document.createElement("strong"),l.className="metric-readout",O.append(D,l);const W=document.createElement("div");W.className="module-settings-options";for(const H of[{className:"kind",label:"Kind"},{className:"height_band",label:"Height"},{className:"surface",label:"Surface"},{className:"dodge_state",label:"Dodge"}]){const ne=document.createElement("label");ne.className="toggle";const oe=document.createElement("input");oe.type="checkbox",oe.dataset.breakdownClass=H.className,oe.addEventListener("change",()=>{oe.checked?u.add(H.className):u.delete(H.className),h(),n.rerenderCurrentState(),n.requestConfigSync?.()});const pe=document.createElement("span");pe.textContent=H.label,ne.append(oe,pe),W.append(ne)}k.append(O,W),a.append(g,y,x,k)}return h(),a}};function h(g){if(!a)return;const _=g??t,m=a.querySelector("input");m instanceof HTMLInputElement&&(m.value=`${_}`),r&&(r.textContent=`${_.toFixed(1)}s`);for(const v of a.querySelectorAll("input[data-overlay-mode]"))v.checked=v.dataset.overlayMode===i;o&&(o.textContent=i==="advancement"?"Advancement":"Markers");for(const v of a.querySelectorAll("input[data-breakdown-class]")){const y=v.dataset.breakdownClass;v.checked=y?u.has(y):!1}if(l){const v=f();l.textContent=v.length>0?v.map(y=>({kind:"Kind",height_band:"Height",surface:"Surface",dodge_state:"Dodge"})[y]).join(" + "):"Total only"}}function f(){return d.filter(g=>u.has(g))}function p(g){s=po(g),e?.setColorModes(s),h(),n.requestConfigSync?.()}}function f$(n,e=YE({refreshTimelineRanges:n.refreshTimelineRanges,rerenderCurrentState:n.rerenderCurrentState})){return{id:"boost",label:"Boost",setup(t){e.setup(t)},teardown(){e.teardown()},onBeforeRender(){},getTimelineRanges(t){return X4(t.statsTimeline,t.replay,e.getTimelineRangeOptions())},getConfig(){return e.getConfig()},applyConfig(t){e.applyConfig(t)},includeBoostPickupAnimationPickup(t){return e.includePickup(t)},renderStats(t,i){const s=zt(i.statsFrameLookup,t);return s?si(s.players,a=>Tn(a.name,a.is_team_0,Bx(a.boost))):""},renderFocusedPlayerStats(t,i,s){const a=wn(s,i,t);return a?Bx(a.boost):""},renderSettings(t){return e.renderSettings(t,{showHeader:!0})}}}function p$(){return ai({id:"core",label:"Core",select:n=>n.core,render:n=>$G(n)})}function m$(){return ai({id:"backboard",label:"Backboard",select:n=>n.backboard,render:n=>WG(n),getTimelineEvents(n){return c4(n.statsTimeline,n.replay)}})}function _$(){let n=null;return{id:"ceiling-shot",label:"Ceiling Shot",setup(e){n=new Q5(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},renderStats(e,t){const i=zt(t.statsFrameLookup,e);return i?si(i.players,s=>Tn(s.name,s.is_team_0,Lx(s.ceiling_shot),s.ceiling_shot?.is_last_ceiling_shot?'Last Ceiling Shot':"")):""},renderFocusedPlayerStats(e,t,i){const s=wn(i,t,e);return s?Lx(s.ceiling_shot):""}}}function g$(){return{id:"wall-aerial",label:"Wall-to-Air Setup",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,kx(i.wall_aerial),i.wall_aerial?.is_last_wall_aerial?'Last Wall-to-Air Setup':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?kx(i.wall_aerial):""}}}function y$(){return{id:"wall-aerial-shot",label:"Wall Shot",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Dx(i.wall_aerial_shot),i.wall_aerial_shot?.is_last_wall_aerial_shot?'Last Wall Shot':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Dx(i.wall_aerial_shot):""}}}function v$(){return ai({id:"ball-carry",label:"Ball Carry",select:n=>n.ball_carry,render:n=>YG(n)})}function b$(){return ai({id:"air-dribble",label:"Air Dribble",select:n=>n.air_dribble,render:n=>jG(n)})}function x$(){return ai({id:"dodge-reset",label:"Dodge Refresh",select:n=>n.dodge_reset,render:n=>t$(n)})}function w$(){return ai({id:"flip-reset",label:"Flip Reset",select:n=>n.flip_reset,render:n=>n$(n)})}function S$(){return ai({id:"double-tap",label:"Double Tap",select:n=>n.double_tap,render:n=>XG(n)})}function T$(){return ai({id:"pass",label:"Pass",select:n=>n.pass,render:n=>KG(n)})}function M$(){return ai({id:"one-timer",label:"One-timer",select:n=>n.one_timer,render:n=>qG(n)})}function E$(){return{id:"flick",label:"Flick",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Ox(i.flick),i.flick?.is_last_flick?'Last Flick':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Ox(i.flick):""}}}function C$(){let n=null;return{id:"speed-flip",label:"Speed Flip",setup(e){n=new DG(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},renderStats(e,t){const i=zt(t.statsFrameLookup,e);return i?si(i.players,s=>Tn(s.name,s.is_team_0,Fx(s.speed_flip),s.speed_flip?.is_last_speed_flip?'Last Speed Flip':"")):""},renderFocusedPlayerStats(e,t,i){const s=wn(i,t,e);return s?Fx(s.speed_flip):""}}}function A$(){let n=null;return{id:"dodge",label:"Dodge",setup(e){n=new xG(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},getTimelineEvents(e){return w4(e.statsTimeline,e.replay)},renderStats(e,t){const i=new Map;for(const a of t.replay.players)i.set(a.id,{name:a.name,isTeamZero:a.isTeamZero,count:0});for(const a of ve(t.statsTimeline,"dodge")){const r=At(a.player),o=t.replay.players.find(c=>c.id===r)??null,l=i.get(r)??{name:o?.name??r,isTeamZero:a.is_team_0,count:0};l.count+=1,i.set(r,l)}const s=[...i.values()].filter(a=>a.count>0);return s.length===0?"":`
${[!0,!1].map(a=>{const r=s.filter(l=>l.isTeamZero===a);if(r.length===0)return"";const o=a?"Blue":"Orange";return`

${o} team

${r.length} player${r.length===1?"":"s"} @@ -5907,7 +5972,7 @@ void main() {
${r.map(l=>Tn(l.name,l.isTeamZero,`
Events${l.count}
`)).join("")}
-
`}).join("")}
`},renderFocusedPlayerStats(e,t,i){return`
Events${ve(i.statsTimeline,"dodge").filter(a=>At(a.player)===e).length}
`}}}function JG(){return{id:"half-flip",label:"Half Flip",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Rx(i.half_flip),i.half_flip?.is_last_half_flip?'Last Half Flip':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Rx(i.half_flip):""}}}function QG(){return{id:"wavedash",label:"Wavedash",setup(){},teardown(){},onBeforeRender(){},getTimelineEvents(n){return K5(n.statsTimeline,n.replay)},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Px(i.wavedash),i.wavedash?.is_last_wavedash?'Last Wavedash':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Px(i.wavedash):""}}}function e$(){return ai({id:"whiff",label:"Whiff",select:n=>n.whiff,render:n=>xG(n),getTimelineEvents(n){return J5(n.statsTimeline,n.replay)}})}function t$(n){let e=null,t=null;const i=new Set,s=["speed_band","height_band"];return{id:"movement",label:"Movement",setup(){a()},teardown(){},onBeforeRender(){},getConfig(){return{breakdownClasses:r()}},applyConfig(o){if(i.clear(),o&&typeof o=="object"&&!Array.isArray(o)){const l=o.breakdownClasses;if(Array.isArray(l))for(const c of l)s.includes(c)&&i.add(c)}a(),n.rerenderCurrentState()},renderStats(o,l){const c=zt(l.statsFrameLookup,o);return c?si(c.players,u=>Tn(u.name,u.is_team_0,gx(u.movement,{breakdownClasses:r()}))):""},renderFocusedPlayerStats(o,l,c){const u=wn(c,l,o);return u?gx(u.movement,{breakdownClasses:r()}):""},renderSettings(){if(!e){e=document.createElement("div"),e.className="module-settings-card";const o=document.createElement("div");o.className="module-settings-header";const l=document.createElement("div"),c=document.createElement("p");c.className="module-settings-eyebrow",c.textContent="Stat display";const u=document.createElement("h3");u.textContent="Movement breakdown",l.append(c,u),t=document.createElement("strong"),t.className="metric-readout",o.append(l,t);const d=document.createElement("div");d.className="module-settings-options";for(const h of[{className:"speed_band",label:"Speed band"},{className:"height_band",label:"Height band"}]){const f=document.createElement("label");f.className="toggle";const p=document.createElement("input");p.type="checkbox",p.dataset.breakdownClass=h.className,p.addEventListener("change",()=>{p.checked?i.add(h.className):i.delete(h.className),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const g=document.createElement("span");g.textContent=h.label,f.append(p,g),d.append(f)}e.append(o,d)}return a(),e}};function a(){if(e){for(const o of e.querySelectorAll("input[data-breakdown-class]")){const l=o.dataset.breakdownClass;o.checked=l?i.has(l):!1}if(t){const o=r();t.textContent=o.length>0?o.map(l=>({speed_band:"Speed band",height_band:"Height band"})[l]).join(" + "):"Total only"}}}function r(){return s.filter(o=>i.has(o))}}function n$(){return ai({id:"powerslide",label:"Powerslide",select:n=>n.powerslide,render:n=>bG(n),getTimelineEvents(n){return G5(n.statsTimeline,n.replay)}})}function i$(){return ai({id:"rotation",label:"Rotation",select:n=>n.rotation,render:n=>hG(n)})}function s$(){return ai({id:"demo",label:"Demo",select:n=>n.demo,render:n=>wG(n)})}function a$(){return ai({id:"bump",label:"Bump",select:n=>n.bump,render:n=>SG(n),getTimelineEvents(n){return q5(n.statsTimeline,n.replay)}})}function r$(){let n=null,e=1;return{id:OE,label:"Relative Positioning",setup(t){e=t.fieldScale,n=new PV(t.player.sceneState.replayRoot,t.replay,e)},teardown(){n?.dispose(),n=null},onBeforeRender(t){n?.update(t,e)},renderStats(t,i){const s=zt(i.statsFrameLookup,t);return s?si(s.players,a=>{const r=w4(i.replay,At(a.player_id),t),o=x4[r];return Tn(a.name,a.is_team_0,wx(a.positioning),`${o}`)}):""},renderFocusedPlayerStats(t,i,s){const a=wn(s,i,t);return a?wx(a.positioning):""}}}function o$(){return{id:"absolute-positioning",label:"Absolute Positioning",setup(n){bx.acquire(n)},teardown(){bx.release()},onBeforeRender(){},getTimelineRanges(n){return b4(n.statsTimeline,n.replay)},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Sx(i.positioning))):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Sx(i.positioning):""}}}function l$(n,e={}){return[NG(),UG(),BG(),zG(),HG(),XG(),qG(),KG(),S4(n),T4(),M4(),E4(),C4(),r$(),o$(),i$(),ZG(),jG(),JG(),QG(),OG(n),e$(),YG(),$G(),WG(),GG(),FG(n,e.boostPickupFilters),VG(),t$(n),n$(),s$(),a$()]}const c$=new Set(["player_id","name","is_team_0"]),u$=["is_last_","time_since_last_","frames_since_last_"];function d$(n){return n===null||typeof n=="number"||typeof n=="string"||typeof n=="boolean"||Array.isArray(n)}function h$(n,e){let t=n;for(const i of e){if(!t||typeof t!="object"||Array.isArray(t))return;t=t[i]}return t}function f$(n){return n==null?"--":typeof n=="number"?Number.isFinite(n)?Number.isInteger(n)?`${n}`:`${Number(n.toFixed(3))}`:"--":typeof n=="boolean"?n?"true":"false":Array.isArray(n)?n.length===0?"[]":JSON.stringify(n):`${n}`}function p$(n,e){if(u$.some(a=>n.startsWith(a)))return!0;const t=n.match(/^last_(.+)_time$/),i=n.match(/^last_(.+)_frame$/),s=t?.[1]??i?.[1];return s?`is_last_${s}`in e||`time_since_last_${s}`in e||`frames_since_last_${s}`in e:!1}function y_(n,e,t,i){if(!n||typeof n!="object"||Array.isArray(n))return;const s=n;for(const[a,r]of Object.entries(s)){if(e==="player"&&t.length===0&&c$.has(a)||p$(a,s))continue;const o=[...t,a];if(d$(r)){const l=`${e}:${o.join(".")}`;i.push({id:l,label:o.join("."),category:o[0]??e,scope:e,path:o,read(c){return h$(c,o)},format:f$});continue}y_(r,e,o,i)}}function m$(n){const e=new Set;return n.filter(t=>e.has(t.id)?!1:(e.add(t.id),!0))}function _$(n,e){const t=[];return n&&y_(n,"player",[],t),e&&y_(e,"team",[],t),m$(t).sort((i,s)=>i.label.localeCompare(s.label))}function g$(){return _$(eE(),Yl())}function Jl(n){return g$()}function GE(n){return n.toLowerCase().replace(/[_/.-]+/g," ").replace(/\s+/g," ").trim()}function y$(n){return GE(n).split(" ").filter(Boolean)}function v$(n,e){const t=y$(e);if(t.length===0)return 0;const i=GE([n.scope,n.category,n.label,n.id,...n.path].join(" "));let s=0;for(const a of t){const r=i.indexOf(a);if(r<0)return null;s+=r}return s+i.length/1e3}function b$(n,e){return n.map((t,i)=>({definition:t,index:i,score:v$(t,e)})).filter(t=>t.score!==null).sort((t,i)=>t.score-i.score||t.index-i.index).map(t=>t.definition)}function ss(n){if(!Number.isFinite(n))return"--";const e=Math.floor(Math.max(0,n)/60),t=Math.max(0,n)-e*60;return`${e}:${t.toFixed(1).padStart(4,"0")}`}class x${constructor(e){this.options=e}statsWindows=new Map;nextStatsWindowId=1;getConfigs(){return[...this.statsWindows.values()].map(e=>({id:e.id,kind:e.kind,placement:this.options.readWindowPlacement(e.element),playerId:e.playerId,team:e.team,entries:e.entries.map(t=>({statId:t.statId,targetId:t.targetId}))}))}clear(){for(const e of this.statsWindows.values())e.element.remove();this.statsWindows.clear(),this.nextStatsWindowId=1}replaceFromConfig(e){this.clear();for(const t of e)this.create(t.kind,t)}render(e=this.options.getReplayPlayer()?.getState().frameIndex??0,t={}){for(const i of this.statsWindows.values())t.preserveOpenPickers&&(i.pickerOpen||i.element.contains(document.activeElement))||this.renderStatsWindow(i,e)}create(e,t){const i=t?.id??`stats-${this.nextStatsWindowId++}`,s=Number.parseInt(i.replace(/^stats-/,""),10);Number.isFinite(s)&&(this.nextStatsWindowId=Math.max(this.nextStatsWindowId,s+1));const{x:a,y:r}=this.getStatsWindowDefaultPosition(),o=document.createElement("section");o.className="stats-window",o.dataset.windowId=i,o.style.setProperty("--window-x",`${a}px`),o.style.setProperty("--window-y",`${r}px`),t&&this.options.applyWindowPlacement(o,t.placement);const l=document.createElement("header");l.className="stats-window-header";const c=document.createElement("div");c.className="stats-window-actions";const u=document.createElement("button");if(u.type="button",u.className="stats-window-action",u.textContent="Hide",c.append(u),this.hasStatsWindowScopeSelector(e))l.classList.add("stats-window-header-actions-only"),l.append(c);else{const f=document.createElement("h2");f.textContent=this.getStatsWindowTitle(e),l.append(f,c)}const d=document.createElement("div");d.className="stats-window-body",o.append(l,d),this.options.layer.append(o);const h={id:i,kind:e,entries:t?.entries.map(f=>({key:`${i}:${f.statId}:${f.targetId??"scope"}`,statId:f.statId,targetId:f.targetId}))??[],playerId:t?.playerId??this.options.getReplayPlayer()?.replay.players[0]?.id??null,team:t?.team??"blue",pickerOpen:!1,query:"",element:o,body:d};return u.addEventListener("click",()=>{o.hidden=!0,this.options.requestConfigSync()}),this.statsWindows.set(i,h),t||this.options.bringWindowToFront(o),this.options.setLauncherOpen(!1),this.renderStatsWindow(h),this.options.requestConfigSync(),h}getStatById(e){return this.options.getStatRegistry().find(t=>t.id===e)??null}getCurrentStatsFrame(e){const t=this.options.getStatsFrameLookup();return t?zt(t,e):null}getTeamSnapshot(e,t){return t==="blue"?e.team_zero??null:e.team_one??null}getTeamLabel(e){return e==="blue"?"Blue":"Orange"}getPlayerTeamClass(e){const t=this.options.getReplayPlayer()?.replay.players.find(i=>i.id===e);return t?ta(t.isTeamZero):null}getTeamScopeClass(e){return ta(e==="blue")}appendGroupedPlayerOptions(e,t){const i=this.options.getReplayPlayer()?.replay.players??[];for(const s of["blue","orange"]){const a=i.filter(o=>o.isTeamZero===(s==="blue"));if(a.length===0)continue;const r=document.createElement("optgroup");r.label=`${this.getTeamLabel(s)} team`;for(const o of a)r.append(new Option(o.name,o.id,o.id===t,o.id===t));e.append(r)}}getStatsWindowScopeTeamClass(e){return e.kind==="player"?this.getPlayerTeamClass(e.playerId):e.kind==="team"?this.getTeamScopeClass(e.team??"blue"):null}getStatTargetTeamClass(e,t){return e.scope==="player"?this.getPlayerTeamClass(t):this.getTeamScopeClass(t==="orange"?"orange":"blue")}getStatsWindowTitle(e){switch(e){case"player":return"Player stats";case"team":return"Team stats";case"all-players":return"All players stats";case"all-teams":return"All teams stats";case"kickoff-overview":return"Kickoff details";case"goals-overview":return"Goal labels";case"ad-hoc":return"Ad hoc stats"}}hasStatsWindowScopeSelector(e){return e==="player"||e==="team"}hasStatsWindowStatPicker(e){return e!=="goals-overview"&&e!=="kickoff-overview"}getStatsWindowAllowedScope(e){switch(e){case"player":case"all-players":return"player";case"team":case"all-teams":return"team";case"kickoff-overview":return null;case"goals-overview":return null;case"ad-hoc":return null}}getStatsWindowDefaultPosition(){const e=this.statsWindows.size*18;return{x:Math.max(12,Math.min(window.innerWidth-360,96+e)),y:Math.max(64,Math.min(window.innerHeight-240,96+e))}}renderStatsWindow(e,t=this.options.getReplayPlayer()?.getState().frameIndex??0){const i=document.activeElement,s=i instanceof HTMLInputElement&&i.dataset.statsWindowSearch===e.id,a=s?i.selectionStart:null,r=s?i.selectionEnd:null,o=s?i.selectionDirection:null;if(e.body.replaceChildren(),this.renderStatsWindowScope(e),this.hasStatsWindowStatPicker(e.kind)&&(this.renderStatsWindowAddControl(e),this.renderStatsWindowPicker(e)),this.renderStatsWindowEntries(e,t),s){const l=e.body.querySelector(`input[data-stats-window-search="${e.id}"]`);l?.focus({preventScroll:!0}),l&&a!==null&&r!==null&&l.setSelectionRange(a,r,o??"none")}}renderStatsWindowScope(e){if(e.kind!=="player"&&e.kind!=="team")return;const t=document.createElement("div");t.className="stats-window-scope-row";const i=document.createElement("select");i.className="stats-window-scope-select";const s=this.getStatsWindowScopeTeamClass(e);s&&i.classList.add(s),i.setAttribute("aria-label",e.kind==="player"?"Player stats target":"Team stats target"),e.kind==="player"?(this.appendGroupedPlayerOptions(i,e.playerId),i.value=e.playerId??"",i.addEventListener("change",()=>{e.playerId=i.value||null,this.renderStatsWindow(e),this.options.requestConfigSync()})):(i.append(new Option("Blue","blue",e.team==="blue",e.team==="blue"),new Option("Orange","orange",e.team==="orange",e.team==="orange")),i.value=e.team??"blue",i.addEventListener("change",()=>{e.team=i.value==="orange"?"orange":"blue",this.renderStatsWindow(e),this.options.requestConfigSync()})),t.append(i),e.body.append(t)}renderStatsWindowAddControl(e){const t=document.createElement("button");if(t.type="button",t.className="stats-window-add-button",t.textContent="+",t.title="Add stat",t.setAttribute("aria-label","Add stat"),t.setAttribute("aria-expanded",String(e.pickerOpen)),this.activateButton(t,()=>{e.pickerOpen=!e.pickerOpen,this.renderStatsWindow(e)}),this.hasStatsWindowScopeSelector(e.kind)){e.body.querySelector(".stats-window-scope-row")?.append(t);return}const i=document.createElement("div");i.className="stats-window-toolbar",i.append(t),e.body.append(i)}activateButton(e,t){let i=!1;e.addEventListener("pointerdown",s=>{e.disabled||(i=!0,s.preventDefault(),t())}),e.addEventListener("click",()=>{if(i){i=!1;return}e.disabled||t()})}renderStatsWindowPicker(e){const t=document.createElement("div");if(t.className="stats-window-picker",t.hidden=!e.pickerOpen,t.hidden){e.body.append(t);return}const i=this.getStatsWindowAllowedScope(e.kind),s=document.createElement("input");s.type="search",s.placeholder="Search stats",s.value=e.query,s.dataset.statsWindowSearch=e.id;const a=document.createElement("div");a.className="stats-window-picker-list",s.addEventListener("input",()=>{e.query=s.value,this.renderStatsWindowPickerList(e,a,i)}),this.renderStatsWindowPickerList(e,a,i),t.append(s,a),e.body.append(t)}renderStatsWindowPickerList(e,t,i){t.replaceChildren();const s=this.options.getStatRegistry(),a=i?s.filter(l=>l.scope===i):s,r=b$(a,e.query),o=new Map;for(const l of r){const c=o.get(l.category)??[];c.push(l),o.set(l.category,c)}for(const[l,c]of o){if(c.length<2)continue;const u=document.createElement("button");u.type="button",u.className="stats-window-picker-item",u.innerHTML=`Add all ${l}${c.length}`,this.activateButton(u,()=>{for(const d of c)this.addStatToWindow(e,d);this.renderStatsWindow(e),this.options.requestConfigSync()}),t.append(u)}for(const l of r){const c=document.createElement("button");c.type="button",c.className="stats-window-picker-item",c.innerHTML=`${l.label}${l.scope}`,c.disabled=e.kind!=="ad-hoc"&&e.entries.some(u=>u.statId===l.id),this.activateButton(c,()=>{this.addStatToWindow(e,l),this.renderStatsWindow(e),this.options.requestConfigSync()}),t.append(c)}if(r.length===0){const l=document.createElement("p");l.className="stat-window-empty",l.textContent=s.length===0?"No stats available.":"No matching stats.",t.append(l)}}addStatToWindow(e,t){const i=e.kind==="ad-hoc"?this.getDefaultAdHocTargetId(t):void 0;e.entries.some(s=>s.statId===t.id&&s.targetId===i)||e.entries.push({key:`${e.id}:${t.id}:${i??"scope"}`,statId:t.id,targetId:i})}getDefaultAdHocTargetId(e){return e.scope==="player"?this.options.getReplayPlayer()?.replay.players[0]?.id??"":"blue"}removeStatFromWindow(e,t){const i=e.entries.findIndex(s=>s.key===t);i>=0&&e.entries.splice(i,1)}renderStatsWindowEntries(e,t){if(e.kind==="goals-overview"){this.renderGoalLabelsOverview(e);return}if(e.kind==="kickoff-overview"){this.renderKickoffOverview(e,t);return}const i=this.getStatsWindowAllowedScope(e.kind),s=e.entries.map(r=>({entry:r,definition:this.getStatById(r.statId)})).filter(r=>r.definition!==null&&(!i||r.definition.scope===i));if(s.length===0){const r=document.createElement("p");r.className="stat-window-empty",r.textContent="No stats added.",e.body.append(r);return}const a=this.getCurrentStatsFrame(t);if(!a){const r=document.createElement("p");r.className="stat-window-empty",r.textContent="Load a replay to show stats.",e.body.append(r);return}if(e.kind==="all-players"){this.renderAllPlayersStats(e,a,s);return}if(e.kind==="all-teams"){this.renderAllTeamsStats(e,a,s);return}if(e.kind==="player"){const r=e.playerId?a.players.find(o=>At(o.player_id)===e.playerId)??null:null;this.renderScopedStatList(e,r,s);return}if(e.kind==="team"){this.renderScopedStatList(e,this.getTeamSnapshot(a,e.team??"blue"),s);return}e.kind==="ad-hoc"&&this.renderAdHocStats(e,a,s)}renderGoalLabelsOverview(e){const t=this.options.getStatsTimeline(),i=this.options.getReplayPlayer()?.replay??null;if(!t||!i){this.appendStatsWindowEmpty(e,"Load a replay to show goal labels.");return}const s=[...ve(t,"goal_context")].sort((o,l)=>o.time-l.time),a=s.map((o,l)=>l);if(a.length===0){this.appendStatsWindowEmpty(e,"No goals loaded.");return}const r=document.createElement("div");r.className="goal-label-list";for(const o of a){const l=s[o]??null,c=[...l?.tags??[]].sort((M,C)=>M.kind.localeCompare(C.kind)||C.metadata.confidence-M.metadata.confidence),u=l?.time??0,d=l?.scorer??null,h=d?At(d):null,f=d?i.players.find(M=>M.id===h)?.name??h:"Unknown scorer",p=l?.scoring_team_is_team_0??null,g=document.createElement("section");g.className="goal-label-item",p!==null&&g.classList.add(ta(p));const _=document.createElement("header"),m=document.createElement("h3");m.textContent=`Goal ${o+1}`;const v=document.createElement("span");v.textContent=`${ss(u)} · ${f}`,_.append(m,v);const y=document.createElement("div");if(y.className="goal-label-tags",c.length===0){const M=document.createElement("span");M.className="goal-label-tag goal-label-tag-empty",M.textContent="Unlabeled",y.append(M)}else for(const M of c){const C=document.createElement("span");C.className="goal-label-tag";const w=M5(M);C.textContent=`${Ci(M.kind)} ${Math.round(M.metadata.confidence*100)}%${w?` - ${w}`:""}`,y.append(C)}const b=document.createElement("div");b.className="goal-label-actions";const T=document.createElement("button");T.type="button",T.className="goal-label-watch",T.textContent="Watch",T.addEventListener("click",()=>{this.options.watchGoalReplay(u,h)});const x=document.createElement("button");x.type="button",x.textContent="Cue",x.addEventListener("click",()=>{this.options.cueGoalReplay(u)}),b.append(T,x),g.append(_,y,b),r.append(g)}e.body.append(r)}renderKickoffOverview(e,t){const i=this.options.getStatsTimeline(),s=this.options.getReplayPlayer()?.replay??null;if(!i||!s){this.appendStatsWindowEmpty(e,"Load a replay to show kickoff details.");return}const a=this.getClosestKickoffEvent(i,t);if(!a){this.appendStatsWindowEmpty(e,"No kickoff events loaded.");return}const r=a.payload.payload,o=document.createElement("section");o.className="kickoff-overview";const l=document.createElement("header");l.className="kickoff-overview-hero";const c=document.createElement("div"),u=document.createElement("h3");u.textContent=this.formatKickoffTitle(a);const d=document.createElement("span");d.textContent=`Nearest kickoff · resolved at ${ss(r.end_time)}`,c.append(u,d);const h=document.createElement("strong"),f=this.teamClassFromNullable(r.winning_team_is_team_0);h.className="kickoff-overview-victor",f&&h.classList.add(f),h.textContent=this.formatOutcome(r),l.append(c,h);const p=document.createElement("div");p.className="kickoff-overview-summary",p.append(this.renderKickoffMetric("Win strength",`${this.formatNullableNumber(r.win_strength,2)} · ${this.formatKickoffLabelValue("kickoff_win_strength",r.win_strength_band)}`),this.renderKickoffMetric("First touch",this.formatFirstTouch(r)),this.renderKickoffMetric("Advantage",this.formatAdvantage(r)),this.renderKickoffMetric("Contested",this.formatContested(r)));const g=document.createElement("div");g.className="kickoff-detail-grid",g.append(this.renderKickoffDetail("Kickoff start",ss(r.start_time)),this.renderKickoffDetail("Movement start",ss(r.movement_start_time)),this.renderKickoffDetail("Live action",r.live_action_start_time===null?"--":ss(r.live_action_start_time)),this.renderKickoffDetail("First touch",r.first_touch_time===null?"--":ss(r.first_touch_time)),this.renderKickoffDetail("Resolution",ss(r.end_time)),this.renderKickoffDetail("After first touch",this.formatSeconds(r.advantage_seconds_after_first_touch)));const _=document.createElement("div");_.className="kickoff-strategy-list",_.append(this.renderKickoffTeamStrategy("Blue",r.team_zero_taker,r.team_zero_non_takers),this.renderKickoffTeamStrategy("Orange",r.team_one_taker,r.team_one_non_takers)),o.append(l,p,g,_),e.body.append(o)}getClosestKickoffEvent(e,t){return jl(e).filter(s=>s.payload.kind==="kickoff").sort((s,a)=>{const r=this.kickoffFrameDistance(s.payload.payload,t),o=this.kickoffFrameDistance(a.payload.payload,t);return r!==o?r-o:s.payload.payload.start_frame-a.payload.payload.start_frame})[0]??null}kickoffFrameDistance(e,t){return t>=e.start_frame&&t<=e.end_frame?0:Math.min(Math.abs(t-e.start_frame),Math.abs(t-e.end_frame))}renderKickoffMetric(e,t){const i=document.createElement("div");i.className="kickoff-metric";const s=document.createElement("span");s.textContent=e;const a=document.createElement("strong");return a.textContent=t,i.append(s,a),i}renderKickoffDetail(e,t){const i=document.createElement("div");i.className="kickoff-detail-row";const s=document.createElement("span");s.textContent=e;const a=document.createElement("strong");return a.textContent=t,i.append(s,a),i}renderKickoffTeamStrategy(e,t,i){const s=document.createElement("section");s.className=`kickoff-strategy-team ${e==="Blue"?"team-blue":"team-orange"}`;const a=document.createElement("h4");a.textContent=e,s.append(a);const r=document.createElement("p");if(r.className="kickoff-strategy-line",r.textContent=t?`${this.getPlayerName(t.player)}: ${this.formatKickoffLabelValue("kickoff_approach",t.approach)} from ${this.formatKickoffLabelValue("kickoff_spawn",t.spawn_position)} (${this.formatKickoffLabelValue("taker_outcome",t.outcome)}, ${this.formatSeconds(t.time_to_ball)})`:"No taker detected",s.append(r),i.length>0){const o=document.createElement("ul");o.className="kickoff-support-list";for(const l of i){const c=document.createElement("li");c.textContent=`${this.getPlayerName(l.player)}: ${this.formatKickoffLabelValue("support_behavior",l.support_behavior)} from ${this.formatKickoffLabelValue("kickoff_spawn",l.spawn_position)}`,o.append(c)}s.append(o)}return s}formatOutcome(e){return e.winning_team_is_team_0===!0?"Blue wins":e.winning_team_is_team_0===!1?"Orange wins":e.outcome==="neutral"?"Neutral":"Unknown"}formatFirstTouch(e){if(!e.first_touch_player)return"--";const t=e.first_touch_team_is_team_0===!0?"Blue":e.first_touch_team_is_team_0===!1?"Orange":"Unknown",i=e.first_touch_time===null?"--":ss(e.first_touch_time);return`${t} · ${this.getPlayerName(e.first_touch_player)} · ${i}`}formatAdvantage(e){if(e.advantage==="no_advantage")return"No advantage";const t=e.advantage_team_is_team_0===!0?"Blue":e.advantage_team_is_team_0===!1?"Orange":"Unknown",i=e.advantage.replace(/^team_(zero|one)_/,""),s=e.advantage_player?` · ${this.getPlayerName(e.advantage_player)}`:"",a=e.advantage_time===null?"":` · ${ss(e.advantage_time)}`;return`${t} ${this.formatKickoffLabelValue("kickoff_advantage",i)}${s}${a}`}formatContested(e){return e.kickoff_possession_outcome==="contested"?"Yes":e.kickoff_possession_team_is_team_0===!0?`No · Blue ${this.formatPossessionOutcome(e.kickoff_possession_outcome)}`:e.kickoff_possession_team_is_team_0===!1?`No · Orange ${this.formatPossessionOutcome(e.kickoff_possession_outcome)}`:`No · ${this.formatPossessionOutcome(e.kickoff_possession_outcome)}`}formatPossessionOutcome(e){return e.endsWith("_advantage")?"advantage":e.endsWith("_possession")?"possession":this.formatKickoffLabelValue("kickoff_possession_outcome",e)}formatKickoffType(e){return this.formatKickoffLabelValue("kickoff_type",e)}formatKickoffTitle(e){const t=e.payload.payload,i=this.formatKickoffDirection(t.kickoff_direction),s=[this.formatKickoffType(t.kickoff_type),i].filter(Boolean).join(" ");return[e.meta.label,s].filter(Boolean).join(" · ")}formatKickoffDirection(e){return e==="unknown"?"":`(${this.formatKickoffLabelValue("kickoff_direction",e)})`}formatNullableNumber(e,t){return e===null||!Number.isFinite(e)?"--":e.toFixed(t)}formatSeconds(e){return e===null||!Number.isFinite(e)?"--":`${e.toFixed(2)}s`}formatLabel(e){return e.replace(/^team_zero_/,"blue_").replace(/^team_one_/,"orange_").replaceAll("_"," ").replace(/\b\w/g,t=>t.toUpperCase())}formatKickoffLabelValue(e,t){const i=t.replace(/^team_zero_/,"blue_").replace(/^team_one_/,"orange_");return e==="kickoff_advantage"?this.formatLabel(i.replace(/^blue_/,"").replace(/^orange_/,"")):e==="kickoff_possession_outcome"?this.formatLabel(i.replace(/^blue_/,"Blue ").replace(/^orange_/,"Orange ")):this.formatLabel(i)}teamClassFromNullable(e){return e===null?null:ta(e)}getPlayerName(e){const t=At(e);return this.options.getReplayPlayer()?.replay.players.find(i=>i.id===t)?.name??t}appendStatsWindowEmpty(e,t){const i=document.createElement("p");i.className="stat-window-empty",i.textContent=t,e.body.append(i)}renderScopedStatList(e,t,i){const s=document.createElement("div");s.className="stats-window-stat-list";for(const{entry:a,definition:r}of i)s.append(this.renderStatRow(e,a,r,t?r.format(r.read(t)):"--"));e.body.append(s)}renderAllPlayersStats(e,t,i){const s=document.createElement("div");s.className="stats-window-team-list";for(const a of["blue","orange"]){const r=t.players.filter(h=>h.is_team_0===(a==="blue"));if(r.length===0)continue;const o=document.createElement("section");o.className=`stats-window-team-group ${this.getTeamScopeClass(a)}`;const l=document.createElement("header");l.className="stats-window-team-header";const c=document.createElement("h3");c.textContent=`${this.getTeamLabel(a)} team`;const u=document.createElement("span");u.textContent=`${r.length} player${r.length===1?"":"s"}`,l.append(c,u),o.append(l);const d=document.createElement("div");d.className="stats-window-entity-list";for(const h of r){const f=document.createElement("section");f.className=`stats-window-entity ${ta(h.is_team_0)}`;const p=document.createElement("h4");p.className="stats-window-entity-title",p.textContent=h.name,f.append(p);for(const{entry:g,definition:_}of i)f.append(this.renderStatRow(e,g,_,_.format(_.read(h))));d.append(f)}o.append(d),s.append(o)}e.body.append(s)}renderAllTeamsStats(e,t,i){const s=document.createElement("div");s.className="stats-window-entity-list";for(const a of["blue","orange"]){const r=this.getTeamSnapshot(t,a),o=document.createElement("section");o.className=`stats-window-entity ${this.getTeamScopeClass(a)}`;const l=document.createElement("h3");l.className="stats-window-entity-title",l.textContent=this.getTeamLabel(a),o.append(l);for(const{entry:c,definition:u}of i)o.append(this.renderStatRow(e,c,u,r?u.format(u.read(r)):"--"));s.append(o)}e.body.append(s)}renderAdHocStats(e,t,i){const s=document.createElement("div");s.className="stats-window-stat-list";for(const{entry:a,definition:r}of i){const o=this.getAdHocTarget(t,r,a.targetId);s.append(this.renderStatRow(e,a,r,o?r.format(r.read(o)):"--"))}e.body.append(s)}getAdHocTarget(e,t,i){return t.scope==="player"?e.players.find(s=>At(s.player_id)===i)??e.players[0]??null:this.getTeamSnapshot(e,i==="orange"?"orange":"blue")}renderStatRow(e,t,i,s){const a=document.createElement("div");a.className="stats-window-stat-row";const r=document.createElement("span");if(r.className="stats-window-stat-name",r.textContent=i.label,e.kind==="ad-hoc"){const c=document.createElement("select");c.className="stats-window-stat-target";const u=this.getStatTargetTeamClass(i,t.targetId);u&&c.classList.add(u),i.scope==="player"?this.appendGroupedPlayerOptions(c,t.targetId):c.append(new Option("Blue","blue",t.targetId==="blue",t.targetId==="blue"),new Option("Orange","orange",t.targetId==="orange",t.targetId==="orange")),c.value=t.targetId??"",c.addEventListener("change",()=>{const d=c.value;if(e.entries.some(f=>f!==t&&f.statId===t.statId&&f.targetId===d)){this.renderStatsWindow(e);return}const h=e.entries.findIndex(f=>f.key===t.key);h>=0&&(e.entries[h]={key:`${e.id}:${t.statId}:${d}`,statId:t.statId,targetId:d}),this.renderStatsWindow(e),this.options.requestConfigSync()}),r.append(" ",c)}const o=document.createElement("span");o.className="stats-window-stat-value",o.textContent=s;const l=document.createElement("button");return l.type="button",l.className="stats-window-stat-remove",l.textContent="x",l.addEventListener("click",()=>{this.removeStatFromWindow(e,t.key),this.renderStatsWindow(e),this.options.requestConfigSync()}),a.append(r,o,l),a}}function w$(n){return new x$(n)}const S$=new Set(["module:dodge","module:touch","module:powerslide"]),T$=["stats-stream:"],ih=["#3b82f6","#06b6d4","#22c55e","#a855f7","#f97316","#ef4444","#f59e0b","#ec4899"],af="#d1d9e0",Gg=ih[0],$g=ih[4],M$=[{id:"core",label:"Shots, saves, assists",buildEvents(n){return n.replay.timelineEvents.filter(e=>e.kind==="shot"||e.kind==="save"||e.kind==="assist")}},{id:"demo",label:"Demos",buildEvents(n){return n.replay.timelineEvents.filter(e=>e.kind==="demo")}}],E$=[];function $E(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function WE(n){if(typeof n=="string"&&n.length>0)return n;if(!$E(n))return null;const[e,t]=Object.entries(n)[0]??[];return!e||t==null?null:typeof t=="string"||typeof t=="number"?`${e}:${t}`:`${e}:${JSON.stringify(t)}`}function XE(n){return n.split(/[_-]+/).filter(e=>e.length>0).map(e=>e.slice(0,1).toUpperCase()).join("").slice(0,3)||"E"}function C$(n){if(typeof n!="number"||!Number.isFinite(n))return null;const e=Math.abs(n)<1?2:1;return`${n.toFixed(e).replace(/\.0+$/,"").replace(/(\.\d*[1-9])0+$/,"$1")}s`}function $i(n){return typeof n!="string"||n.length===0?null:n.split(/[_-]+/).filter(e=>e.length>0).map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1)}`).join(" ")}function A$(n){return n==="team_zero_side"?"Blue side":n==="team_one_side"?"Orange side":n==="neutral"?"Neutral zone":$i(n)}function R$(n){const e=$i(n);return e?`${e.toLowerCase()} third`:null}function P$(n){return n==="team_zero_third"?"Blue third":n==="team_one_third"?"Orange third":n==="neutral_third"?"Neutral third":$i(n)}function I$(n){return n==="team_zero"?"Blue":n==="team_one"?"Orange":n==="neutral"?"Neutral":$i(n)}function ad(n){return $E(n.payload.payload)?n.payload.payload:{}}function KE(n){return n===!0?Gg:n===!1?$g:null}function L$(n){return n==="team_zero_side"?Gg:n==="team_one_side"?$g:n==="neutral"?af:null}function D$(n){return n==="team_zero"?Gg:n==="team_one"?$g:n==="neutral"?af:null}function k$(n){return typeof n=="boolean"?KE(n):null}const O$={ball_half(n){return L$(ad(n).field_half)},possession(n){return D$(ad(n).possession_state)},player_possession(n){return k$(ad(n).is_team_0)}};function qE(n,e,t){return O$[n]?.(e)??KE(t)??af}function ui(n){return n.filter(e=>!!e).join(" | ")}function F$({event:n,playerName:e,streamLabel:t,teamLabel:i}){const s=ad(n),a=C$(s.duration);if(n.payload.kind==="ball_half"){const r=A$(s.field_half),o=s.active===!1?"Ball half inactive":r?`Ball on ${r.toLowerCase()}`:null;return ui([o??t,a])}if(n.payload.kind==="ball_third"){const r=P$(s.field_third),o=s.active===!1?"Ball third inactive":r?`Ball in ${r.toLowerCase()}`:null;return ui([o??t,a])}if(n.payload.kind==="territorial_pressure"){const r=$i(s.end_reason),o=`${i??""} territorial pressure`.trim();return ui([r?`${o} ended: ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="possession"){const r=I$(s.possession_state),o=R$(s.field_third),l=r?`${r} possession`:t;return ui([l,o,a])}if(n.payload.kind==="controlled_play"){const r=e?`${e} controlled play`:t;return ui([r,a])}if(n.payload.kind==="ball_carry"){const r=e?`${e} ${t.toLowerCase()}`:t;return ui([r,a])}if(n.payload.kind==="player_activity"){const r=$i(s.state),o=e?`${e} positioning`:t;return ui([r?`${o} ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="field_third"){const r=$i(s.state),o=e?`${e} positioning`:t;return ui([r?`${o} in ${r.toLowerCase()} third`:o,a])}if(n.payload.kind==="field_half"){const r=$i(s.state),o=e?`${e} positioning`:t;return ui([r?`${o} in ${r.toLowerCase()} half`:o,a])}if(n.payload.kind==="ball_depth"){const r=$i(s.state),o=e?`${e} ball depth`:t;return ui([r?`${o}: ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="depth_role"){const r=$i(s.state),o=e?`${e} depth role`:t;return ui([r?`${o}: ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="shadow_defense"){const r=e?`${e} shadow defense`:t;return ui([r,a])}if(n.payload.kind==="rotation_role"){const r=$i(s.state),o=e?`${e} rotation`:t;return ui([r?`${o}: ${r.toLowerCase()}`:o,a])}return e?`${e} ${t.toLowerCase()}`:t}function N$(n,e,t){const i=Ci(e),s=new Map(n.replay.players.map(a=>[a.id,a.name]));return t.flatMap((a,r)=>{const o=a.meta.timing.type==="moment"?{time:a.meta.timing.time,frame:a.meta.timing.frame}:{time:a.meta.timing.end_time,frame:a.meta.timing.end_frame},l=WE(a.meta.primary_player),c=l?s.get(l)??l:null,u=a.meta.team_is_team_0??null,d=u==null?null:u?"Blue":"Orange",h=a.meta.id||`${e}:${o.frame??o.time}:${r}`,f=qE(e,a,u);return[{id:`stats-stream:${h}`,time:n.replay.frames[o.frame??-1]?.time??o.time,frame:o.frame,kind:e,label:F$({event:a,playerName:c,streamLabel:i,teamLabel:d}),shortLabel:XE(e),playerId:l,playerName:c,isTeamZero:u,color:f}]})}function U$(n,e,t){const i=Ci(e),s=new Map(n.replay.players.map(a=>[a.id,a.name]));return t.flatMap((a,r)=>{if(a.meta.timing.type!=="span")return[];const o={startTime:a.meta.timing.start_time,endTime:a.meta.timing.end_time,startFrame:a.meta.timing.start_frame,endFrame:a.meta.timing.end_frame},l=a.meta.team_is_team_0??null,c=l==null?null:l?"Blue":"Orange",u=WE(a.meta.primary_player),d=u?s.get(u)??u:null,h=qE(e,a,l),f=a.meta.id||`${e}:${o.startFrame??o.startTime}:${o.endFrame??o.endTime}:${r}`,p=d?`${d} ${i.toLowerCase()}`:c?`${c} ${i.toLowerCase()}`:i;let g=`stats-stream:${e}`,_=i;return a.meta.scope==="player"&&u?(g=`stats-stream:${e}:player:${u}`,_=d?`${d} ${i.toLowerCase()}`:i):a.meta.scope==="team"&&l!=null&&(g=`stats-stream:${e}:team:${l?"0":"1"}`,_=c?`${c} ${i.toLowerCase()}`:i),[{id:`stats-stream:${f}`,startTime:n.replay.frames[o.startFrame??-1]?.time??o.startTime,endTime:Math.max(n.replay.frames[o.startFrame??-1]?.time??o.startTime,n.replay.frames[o.endFrame??-1]?.time??o.endTime),lane:g,laneLabel:_,label:p,shortLabel:XE(e),isTeamZero:l,color:h}]}).sort((a,r)=>a.startTime!==r.startTime?a.startTime-r.startTime:(a.id??"").localeCompare(r.id??""))}function B$(n,e,t,i){return[...new Set([...FT,...jl(n.statsTimeline).map(a=>a.meta.stream)])].flatMap(a=>{const r=jl(n.statsTimeline).filter(u=>u.meta.stream===a);if(i.has(a)&&r.length>0)return[];const o=r.some(u=>u.meta.timing.type==="span"),l=o?U$(n,a,r):[],c=N$(n,a,r);return[{id:`stats-stream:${a}`,playlistId:`stats-stream:${a}`,timelineKey:`stats-stream:${a}`,timelineId:`stats-stream:${a}`,group:"Event streams",label:Ci(a),count:o?l.length:c.length,active:e.has(`stats-stream:${a}`),buildTimelineEvents(){return o?[]:c},buildPlaylistEvents(){return c},buildTimelineRanges:o?()=>l:void 0,setActive(u){t(`stats-stream:${a}`,u)}}]})}function z$(n){return new Set([...n.filter(e=>e.getTimelineEvents).map(e=>e.id),...CE])}function H$(){return[...CE].sort((n,e)=>Ci(n).localeCompare(Ci(e)))}function V$({ctx:n,modules:e,activeTimelineEventSourceIds:t,activeMechanicTimelineKinds:i,toggleEventSource:s,setMechanicTimelineKind:a}){if(!n)return[];const r=[];for(const o of M$){const l=o.buildEvents(n),c=l.length;r.push({id:o.id,playlistId:`replay:${o.id}`,timelineKey:`events:${o.id}`,timelineId:`events:${o.id}`,group:"Replay",label:o.label,count:c,active:t.has(o.id),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){s(o.id,u)}})}for(const o of e.filter(l=>l.getTimelineEvents)){const l=o.getTimelineEvents?.(n)??[],c=l.length;r.push({id:o.id,playlistId:`module:${o.id}`,timelineKey:`module:${o.id}`,timelineId:`module:${o.id}`,group:"Stats",label:o.label,count:c,active:t.has(o.id),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){s(o.id,u)}})}for(const o of E$){const l=o.buildEvents(n),c=l.length;r.push({id:o.id,playlistId:`extra:${o.id}`,timelineKey:`extra:${o.id}`,timelineId:`extra:${o.id}`,group:"Stats",label:o.label,count:c,active:t.has(o.id),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){s(o.id,u)}})}r.push(...B$(n,t,s,z$(e)));for(const o of H$()){const l=EE[o](n.statsTimeline,n.replay),c=l.length;r.push({id:`mechanic:${o}`,playlistId:`mechanic:${o}`,timelineKey:`mechanic:${o}`,timelineId:`mechanic:${o}`,group:"Event types",label:Ci(o),count:c,active:i.has(o),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){a(o,u)}})}return r.sort((o,l)=>o.label.localeCompare(l.label))}function G$(n,e){if(!n)return[];const t=[{id:"replay:goals",group:"Replay",label:"Goals",events:n.replay.timelineEvents.filter(s=>s.kind==="goal")}],i=e.map(s=>({id:s.playlistId,group:s.group,label:s.label,events:s.buildPlaylistEvents()}));return[...t,...i]}function v_(n,e){const t=n.map(i=>i.id);return e===null?new Set(t.filter(i=>!S$.has(i)&&!T$.some(s=>i.startsWith(s)))):new Set(t.filter(i=>e.has(i)))}function $$(n,e){const t=n.playerId??null,i=t?e.findIndex(s=>s.id===t):-1;return i>=0?ih[i%ih.length]:n.color??af}function W$({sources:n,activeSourceIds:e,replayPlayers:t}){const i=v_(n,e);return n.filter(s=>i.has(s.id)).flatMap(s=>s.events.map((a,r)=>({key:`${s.id}:${a.id??`${a.kind}:${a.time}:${r}`}`,sourceId:s.id,sourceLabel:s.label,event:a,color:$$(a,t)}))).sort((s,a)=>s.event.time!==a.event.time?s.event.time-a.event.time:(s.event.label??s.sourceLabel).localeCompare(a.event.label??a.sourceLabel))}class X${constructor(e){this.options=e}getSources(e=this.options.getContext()){return V$({ctx:e,modules:this.options.modules,activeTimelineEventSourceIds:this.options.getActiveTimelineEventSourceIds(),activeMechanicTimelineKinds:this.options.getActiveMechanicTimelineKinds(),toggleEventSource:this.options.toggleEventSource,setMechanicTimelineKind:this.options.setMechanicTimelineKind})}countVisibleSources(e){return e.replay.timelineEvents.filter(i=>i.kind==="goal").length+this.getSources(e).filter(i=>i.active).reduce((i,s)=>i+s.count,0)}render(){const{body:e}=this.options;e.replaceChildren();const t=this.getSources();if(t.length===0){const d=document.createElement("p");d.className="stat-window-empty",d.textContent="No events loaded.",e.append(d);return}const i=document.createElement("div");i.className="mechanics-actions";const s=document.createElement("button");s.type="button",s.className="module-summary-item",s.addEventListener("click",()=>{for(const d of t)d.setActive(!0);this.options.setupActiveModules(),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.render(),this.options.renderModuleSummary(),this.options.renderModuleSettings(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()});const a=document.createElement("span");a.textContent="All events";const r=document.createElement("strong");r.textContent=`${t.length}`,s.append(a,r);const o=document.createElement("button");o.type="button",o.className="module-summary-item",o.addEventListener("click",()=>{for(const d of t)d.setActive(!1);this.options.setupActiveModules(),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.render(),this.options.renderModuleSummary(),this.options.renderModuleSettings(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()});const l=document.createElement("span");l.textContent="No events";const c=document.createElement("strong");c.textContent="Off",o.append(l,c),i.append(s,o),e.append(i);const u=this.renderSourceList(t);u&&e.append(u)}renderSourceList(e){if(e.length===0)return null;const t=document.createElement("div");t.className="module-list mechanics-list mechanics-event-list",t.style.setProperty("--event-source-columns",`${K$(e.length)}`);for(const i of e){const s=document.createElement("button");s.type="button",s.className="module-summary-item",s.dataset.active=i.active?"true":"false",s.setAttribute("aria-pressed",i.active?"true":"false"),s.addEventListener("click",()=>{i.setActive(!i.active),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.render(),this.options.renderTimelineEventCount()});const a=document.createElement("span");a.textContent=i.label;const r=document.createElement("strong");r.textContent=`${i.active?"On":"Off"} ${i.count}`,s.append(a,r),t.append(s)}return t}}function K$(n){return window.innerWidth<640?1:window.innerWidth<900?n>=7?2:1:n>=13?3:n>=7?2:1}function q$(n){return new X$(n)}const Y$=new Set(["ceiling-shot","fifty-fifty","ball_half",OE,"absolute-positioning","dodge","speed-flip","touch"]),kx="touch";class j${constructor(e){this.options=e}renderSummary(){const{summary:e}=this.options.elements;e.replaceChildren();const t=this.options.getTimelineSources(),i=t.map(o=>this.renderTimelineSourceToggle(o)),s=[],a=[],r=this.options.getContext();for(const o of this.options.modules){const l=Y$.has(o.id);!o.getTimelineEvents&&!o.getTimelineRanges&&!l||(t.length===0&&o.getTimelineEvents&&i.push(this.renderCapabilityToggle(o.id,rm(o,"events"),"events")),o.getTimelineRanges&&s.push(this.renderCapabilityToggle(o.id,rm(o,"ranges"),"ranges",r?o.getTimelineRanges(r).length:void 0)),l&&a.push(this.renderCapabilityToggle(o.id,rm(o,"effects"),"effects")))}a.push(this.renderBoostPickupAnimationToggle()),e.append(am("Timeline markers",i),am("Timeline ranges",s),am("In-game visualizations",a))}renderSettings(){const{settings:e}=this.options.elements;e.replaceChildren();const t=this.options.getContext(),i=this.options.getActiveModules().filter(s=>s.id!=="boost"&&s.id!==kx).map(s=>s.renderSettings?.(t)??null).filter(s=>s instanceof HTMLElement);if(i.length===0){e.hidden=!0,this.renderBoostPickupFiltersWindow(),this.renderTouchControlsWindow();return}e.hidden=!1,e.append(...i),this.renderBoostPickupFiltersWindow(),this.renderTouchControlsWindow()}renderBoostPickupAnimationToggle(){const e=this.options.getBoostPickupAnimationEnabled(),t=document.createElement("button");t.type="button",t.className="module-summary-item",t.dataset.active=e?"true":"false",t.setAttribute("aria-pressed",e?"true":"false"),t.addEventListener("click",this.options.toggleBoostPickupAnimation);const i=document.createElement("span");i.textContent="Boost pickup animation";const s=document.createElement("strong");return s.textContent=e?"On":"Off",t.append(i,s),t}renderCapabilityToggle(e,t,i,s){const r=this.options.getActiveCapabilityIds(i).has(e),o=document.createElement("button");o.type="button",o.className="module-summary-item",o.dataset.active=r?"true":"false",o.setAttribute("aria-pressed",r?"true":"false"),o.addEventListener("click",()=>{this.options.toggleCapability(e,i,!this.options.getActiveCapabilityIds(i).has(e))});const l=document.createElement("span");l.textContent=t;const c=document.createElement("strong");return c.textContent=Ox(r,s),o.append(l,c),o}renderTimelineSourceToggle(e){const t=document.createElement("button");t.type="button",t.className="module-summary-item",t.dataset.active=e.active?"true":"false",t.setAttribute("aria-pressed",e.active?"true":"false"),t.addEventListener("click",()=>{e.setActive(!e.active),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.options.renderTimelineEventCount(),this.options.requestConfigSync(),this.renderSummary()});const i=document.createElement("span");i.textContent=Z$(e);const s=document.createElement("strong");return s.textContent=Ox(e.active,e.count),t.append(i,s),t}renderBoostPickupFiltersWindow(){const e=this.options.getContext(),t=this.options.boostPickupFilters.renderSettings(e,{showHeader:!1});this.options.elements.boostPickupFilters.replaceChildren(t)}renderTouchControlsWindow(){const e=this.options.getContext(),i=this.options.modules.find(s=>s.id===kx)?.renderSettings?.(e)??null;this.options.elements.touchControls.replaceChildren(),i instanceof HTMLElement&&this.options.elements.touchControls.append(i)}}function am(n,e){const t=document.createElement("section");t.className="module-summary-group";const i=document.createElement("h3");i.textContent=n;const s=document.createElement("div");return s.className="module-list",s.append(...e),t.append(i,s),t}function Ox(n,e){const t=n?"On":"Off";return e==null?t:`${t} ${e}`}function Z$(n){return n.group==="Replay"?n.label:`${n.label} events`}function rm(n,e){const t={"absolute-positioning:ranges":"Position zones","backboard:events":"Backboard","ball-carry:events":"Ball carry","boost:ranges":"Boost pickup timeline","bump:events":"Bump","ceiling-shot:events":"Ceiling shot","demo:events":"Demo","dodge-reset:events":"Dodge refresh","double-tap:events":"Double tap","fifty-fifty:events":"50/50","fifty-fifty:ranges":"50/50","dodge:events":"Dodge","half-flip:events":"Half flip","possession:ranges":"Possession","powerslide:events":"Powerslide","powerslide:ranges":"Powerslide","ball_half:ranges":"Half control","ball_third:ranges":"Third control","rush:ranges":"Rush","speed-flip:events":"Speed flip","touch:events":"Touch","wavedash:events":"Wavedash"},i={"absolute-positioning":"Position zones","ceiling-shot":"Ceiling shot labels","fifty-fifty":"50/50 labels",dodge:"Dodge impulse arrows",ball_half:"Half control","relative-positioning":"Player roles","speed-flip":"Speed flip labels",touch:"Touch labels"};return e==="effects"?i[n.id]??n.label:t[`${n.id}:${e}`]??`${n.label} timeline`}function J$(n){return new j$(n)}var gn=Uint8Array,fi=Uint16Array,Wg=Int32Array,rf=new gn([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),of=new gn([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),b_=new gn([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),YE=function(n,e){for(var t=new fi(31),i=0;i<31;++i)t[i]=e+=1<>1|(Ut&21845)<<1;Zs=(Zs&52428)>>2|(Zs&13107)<<2,Zs=(Zs&61680)>>4|(Zs&3855)<<4,w_[Ut]=((Zs&65280)>>8|(Zs&255)<<8)>>1}var hs=(function(n,e,t){for(var i=n.length,s=0,a=new fi(e);s>l]=c}else for(o=new fi(i),s=0;s>15-n[s]);return o}),da=new gn(288);for(var Ut=0;Ut<144;++Ut)da[Ut]=8;for(var Ut=144;Ut<256;++Ut)da[Ut]=9;for(var Ut=256;Ut<280;++Ut)da[Ut]=7;for(var Ut=280;Ut<288;++Ut)da[Ut]=8;var Ql=new gn(32);for(var Ut=0;Ut<32;++Ut)Ql[Ut]=5;var eW=hs(da,9,0),tW=hs(da,9,1),nW=hs(Ql,5,0),iW=hs(Ql,5,1),om=function(n){for(var e=n[0],t=1;te&&(e=n[t]);return e},Fi=function(n,e,t){var i=e/8|0;return(n[i]|n[i+1]<<8)>>(e&7)&t},lm=function(n,e){var t=e/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},Xg=function(n){return(n+7)/8|0},lf=function(n,e,t){return(e==null||e<0)&&(e=0),(t==null||t>n.length)&&(t=n.length),new gn(n.subarray(e,t))},sW=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],os=function(n,e,t){var i=new Error(e||sW[n]);if(i.code=n,Error.captureStackTrace&&Error.captureStackTrace(i,os),!t)throw i;return i},aW=function(n,e,t,i){var s=n.length,a=0;if(!s||e.f&&!e.l)return t||new gn(0);var r=!t,o=r||e.i!=2,l=e.i;r&&(t=new gn(s*3));var c=function(xe){var Ae=t.length;if(xe>Ae){var L=new gn(Math.max(Ae*2,xe));L.set(t),t=L}},u=e.f||0,d=e.p||0,h=e.b||0,f=e.l,p=e.d,g=e.m,_=e.n,m=s*8;do{if(!f){u=Fi(n,d,1);var v=Fi(n,d+1,3);if(d+=3,v)if(v==1)f=tW,p=iW,g=9,_=5;else if(v==2){var x=Fi(n,d,31)+257,M=Fi(n,d+10,15)+4,C=x+Fi(n,d+5,31)+1;d+=14;for(var w=new gn(C),E=new gn(19),R=0;R>4;if(y<16)w[R++]=y;else{var F=0,W=0;for(y==16?(W=3+Fi(n,d,3),d+=2,F=w[R-1]):y==17?(W=3+Fi(n,d,7),d+=3):y==18&&(W=11+Fi(n,d,127),d+=7);W--;)w[R++]=F}}var H=w.subarray(0,x),ne=w.subarray(x);g=om(H),_=om(ne),f=hs(H,g,1),p=hs(ne,_,1)}else os(1);else{var y=Xg(d)+4,b=n[y-4]|n[y-3]<<8,T=y+b;if(T>s){l&&os(0);break}o&&c(h+b),t.set(n.subarray(y,T),h),e.b=h+=b,e.p=d=T*8,e.f=u;continue}if(d>m){l&&os(0);break}}o&&c(h+131072);for(var oe=(1<>4;if(d+=F&15,d>m){l&&os(0);break}if(F||os(2),De<256)t[h++]=De;else if(De==256){Ie=d,f=null;break}else{var Xe=De-254;if(De>264){var R=De-257,ke=rf[R];Xe=Fi(n,d,(1<>4;Z||os(3),d+=Z&15;var ne=Q$[se];if(se>3){var ke=of[se];ne+=lm(n,d)&(1<m){l&&os(0);break}o&&c(h+131072);var Se=h+Xe;if(h>8},rl=function(n,e,t){t<<=e&7;var i=e/8|0;n[i]|=t,n[i+1]|=t>>8,n[i+2]|=t>>16},cm=function(n,e){for(var t=[],i=0;ih&&(h=a[i].s);var f=new fi(h+1),p=S_(t[u-1],f,0);if(p>e){var i=0,g=0,_=p-e,m=1<<_;for(a.sort(function(x,M){return f[M.s]-f[x.s]||x.f-M.f});ie)g+=m-(1<>=_;g>0;){var y=a[i].s;f[y]=0&&g;--i){var b=a[i].s;f[b]==e&&(--f[b],++g)}p=e}return{t:new gn(f),l:p}},S_=function(n,e,t){return n.s==-1?Math.max(S_(n.l,e,t+1),S_(n.r,e,t+1)):e[n.s]=t},Nx=function(n){for(var e=n.length;e&&!n[--e];);for(var t=new fi(++e),i=0,s=n[0],a=1,r=function(l){t[i++]=l},o=1;o<=e;++o)if(n[o]==s&&o!=e)++a;else{if(!s&&a>2){for(;a>138;a-=138)r(32754);a>2&&(r(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(r(s),--a;a>6;a-=6)r(8304);a>2&&(r(a-3<<5|8208),a=0)}for(;a--;)r(s);a=1,s=n[o]}return{c:t.subarray(0,i),n:e}},ol=function(n,e){for(var t=0,i=0;i>8,n[s+2]=n[s]^255,n[s+3]=n[s+1]^255;for(var a=0;a4&&!E[b_[D-1]];--D);var O=c+5<<3,k=ol(s,da)+ol(a,Ql)+r,U=ol(s,h)+ol(a,g)+r+14+3*D+ol(M,E)+2*M[16]+3*M[17]+7*M[18];if(l>=0&&O<=k&&O<=U)return QE(e,u,n.subarray(l,l+c));var F,W,H,ne;if(Es(e,u,1+(U15&&(Es(e,u,De[C]>>5&127),u+=De[C]>>12)}}else F=eW,W=da,H=nW,ne=Ql;for(var C=0;C255){var Xe=ke>>18&31;rl(e,u,F[Xe+257]),u+=W[Xe+257],Xe>7&&(Es(e,u,ke>>23&31),u+=rf[Xe]);var Z=ke&31;rl(e,u,H[Z]),u+=ne[Z],Z>3&&(rl(e,u,ke>>5&8191),u+=of[Z])}else rl(e,u,F[ke]),u+=W[ke]}return rl(e,u,F[256]),u+W[256]},rW=new Wg([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),e1=new gn(0),oW=function(n,e,t,i,s,a){var r=a.z||n.length,o=new gn(i+r+5*(1+Math.ceil(r/7e3))+s),l=o.subarray(i,o.length-s),c=a.l,u=(a.r||0)&7;if(e){u&&(l[0]=a.r>>3);for(var d=rW[e-1],h=d>>13,f=d&8191,p=(1<7e3||E>24576)&&(F>423||!c)){u=Ux(n,l,0,b,T,x,C,E,D,w-D,u),E=M=C=0,D=w;for(var W=0;W<286;++W)T[W]=0;for(var W=0;W<30;++W)x[W]=0}var H=2,ne=0,oe=f,pe=k-U&32767;if(F>2&&O==y(w-pe))for(var Ie=Math.min(h,F)-1,De=Math.min(32767,w),Xe=Math.min(258,F);pe<=De&&--oe&&k!=U;){if(n[w+H]==n[w+H-pe]){for(var ke=0;keH){if(H=ke,ne=pe,ke>Ie)break;for(var Z=Math.min(pe,ke-2),se=0,W=0;Wse&&(se=ie,U=Se)}}}k=U,U=g[k],pe+=k-U&32767}if(ne){b[E++]=268435456|x_[H]<<18|Fx[ne];var xe=x_[H]&31,Ae=Fx[ne]&31;C+=rf[xe]+of[Ae],++T[257+xe],++x[Ae],R=w+H,++M}else b[E++]=n[w],++T[n[w]]}}for(w=Math.max(w,R);w=r&&(l[u/8|0]=c,L=r),u=QE(l,u+1,n.subarray(w,L))}a.i=r}return lf(o,0,i+Xg(u)+s)},lW=function(n,e,t,i,s){if(!s&&(s={l:1},e.dictionary)){var a=e.dictionary.subarray(-32768),r=new gn(a.length+n.length);r.set(a),r.set(n,a.length),n=r,s.w=a.length}return oW(n,e.level==null?6:e.level,e.mem==null?s.l?Math.ceil(Math.max(8,Math.min(13,Math.log(n.length)))*1.5):20:12+e.mem,t,i,s)};function cW(n,e){return lW(n,e||{},0,0)}function t1(n,e){return aW(n,{i:2},e,e)}var Bx=typeof TextEncoder<"u"&&new TextEncoder,T_=typeof TextDecoder<"u"&&new TextDecoder,uW=0;try{T_.decode(e1,{stream:!0}),uW=1}catch{}var dW=function(n){for(var e="",t=0;;){var i=n[t++],s=(i>127)+(i>223)+(i>239);if(t+s>n.length)return{s:e,r:lf(n,t-1)};s?s==3?(i=((i&15)<<18|(n[t++]&63)<<12|(n[t++]&63)<<6|n[t++]&63)-65536,e+=String.fromCharCode(55296|i>>10,56320|i&1023)):s&1?e+=String.fromCharCode((i&31)<<6|n[t++]&63):e+=String.fromCharCode((i&15)<<12|(n[t++]&63)<<6|n[t++]&63):e+=String.fromCharCode(i)}};function hW(n,e){var t;if(Bx)return Bx.encode(n);for(var i=n.length,s=new gn(n.length+(n.length>>1)),a=0,r=function(c){s[a++]=c},t=0;ts.length){var o=new gn(a+8+(i-t<<1));o.set(s),s=o}var l=n.charCodeAt(t);l<128||e?r(l):l<2048?(r(192|l>>6),r(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|n.charCodeAt(++t)&1023,r(240|l>>18),r(128|l>>12&63),r(128|l>>6&63),r(128|l&63)):(r(224|l>>12),r(128|l>>6&63),r(128|l&63))}return lf(s,0,a)}function n1(n,e){var t;if(T_)return T_.decode(n);var i=dW(n),s=i.s,t=i.r;return t.length&&os(8),s}const M_=1,E_="cfg",zx="cfgDebug";function fW(n){let e="";for(const t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function pW(n){const e=n.replaceAll("-","+").replaceAll("_","/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=atob(t),s=new Uint8Array(i.length);for(let a=0;a!Ai(e)||!PW(e.id)?null:{id:e.id,placement:s1(e.placement)}).filter(e=>e!==null):[]}function AW(n){return Array.isArray(n)?n.map(e=>!Ai(e)||typeof e.id!="string"||!IW(e.kind)?null:{id:e.id,kind:e.kind,placement:s1(e.placement),playerId:a1(e.playerId)??null,team:e.team==="orange"?"orange":e.team==="blue"?"blue":null,entries:RW(e.entries)}).filter(e=>e!==null):[]}function RW(n){return Array.isArray(n)?n.map(e=>!Ai(e)||typeof e.statId!="string"?null:{statId:e.statId,targetId:typeof e.targetId=="string"?e.targetId:void 0}).filter(e=>e!==null):[]}function s1(n){const e=Ai(n)?n:{},t=Ai(e.viewport)?e.viewport:{};return{x:Rn(e.x)??8,y:Rn(e.y)??8,viewport:{width:sh(t.width)??1,height:sh(t.height)??1},zIndex:Rn(e.zIndex),visible:Zn(e.visible)??!0}}function PW(n){return n==="camera"||n==="scoreboard"||n==="playback"||n==="recording"||n==="mechanics"||n==="event-playlist"||n==="mechanics-review"||n==="replay-loading"||n==="boost-pickups"||n==="touch-controls"||n==="touch-legend"||n==="shot-visualization"||n==="missed-events"}function IW(n){return n==="player"||n==="team"||n==="all-players"||n==="all-teams"||n==="kickoff-overview"||n==="goals-overview"||n==="ad-hoc"}function Ai(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Rn(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function sh(n){const e=Rn(n);return e!==void 0&&e>0?e:void 0}function Zn(n){return typeof n=="boolean"?n:void 0}function a1(n){return n===null?null:typeof n=="string"?n:void 0}function ll(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"):[]}function Hx(n,e,t){return Math.min(t,Math.max(e,n))}const LW=["camera","scoreboard","playback","recording","mechanics","event-playlist","mechanics-review","replay-loading","boost-pickups","touch-controls","touch-legend","shot-visualization","missed-events"];class DW{constructor(e){this.options=e}nextZIndex=30;reset(){this.nextZIndex=30}bringToFront(e){e.style.zIndex=`${this.nextZIndex++}`}show(e){const t=this.mustWindow(e);t.hidden=!1,this.bringToFront(t),this.options.requestConfigSync()}toggle(e){const t=this.mustWindow(e);t.hidden=!t.hidden,t.hidden||this.bringToFront(t),this.options.requestConfigSync()}hide(e){const t=this.mustWindow(e);t.hidden=!0,this.options.requestConfigSync()}readPlacement(e){const t=Number.parseInt(e.style.zIndex,10);return{x:this.readCoordinate(e,"--window-x"),y:this.readCoordinate(e,"--window-y"),viewport:Vx(),zIndex:Number.isFinite(t)?t:void 0,visible:!e.hidden}}applyPlacement(e,t){const i=bW(t,Vx());e.style.setProperty("--window-x",`${i.x}px`),e.style.setProperty("--window-y",`${i.y}px`),e.hidden=!t.visible,t.zIndex!==void 0&&(e.style.zIndex=`${t.zIndex}`,this.nextZIndex=Math.max(this.nextZIndex,t.zIndex+1))}getSingletonConfigs(){const e=[],t=this.options.getRoot();for(const i of LW){const s=t.querySelector(`[data-window-id="${i}"]`);s&&e.push({id:i,placement:this.readPlacement(s)})}return e}applySingletonConfigs(e){const t=this.options.getRoot();for(const i of e){const s=t.querySelector(`[data-window-id="${i.id}"]`);s&&this.applyPlacement(s,i.placement)}}installDragging(e,t){e.addEventListener("pointerdown",i=>{if(!(i.target instanceof HTMLElement)||kW(i.target))return;const s=i.target.closest("[data-window-id]");if(!s||s.hidden)return;this.bringToFront(s);const a=i.clientX,r=i.clientY,o=s.getBoundingClientRect(),l=i.pointerId;s.setPointerCapture(l),i.preventDefault();const c=d=>{const h=Math.max(8,Math.min(window.innerWidth-120,o.left+d.clientX-a)),f=Math.max(8,Math.min(window.innerHeight-100,o.top+d.clientY-r));s.style.setProperty("--window-x",`${h}px`),s.style.setProperty("--window-y",`${f}px`)},u=()=>{s.releasePointerCapture(l),s.removeEventListener("pointermove",c),s.removeEventListener("pointerup",u),s.removeEventListener("pointercancel",u),this.options.requestConfigSync()};s.addEventListener("pointermove",c),s.addEventListener("pointerup",u),s.addEventListener("pointercancel",u)},{signal:t})}mustWindow(e){const t=this.options.getRoot().querySelector(`[data-window-id="${e}"]`);if(!t)throw new Error(`Missing window for id: ${e}`);return t}readCoordinate(e,t){const i=e.style.getPropertyValue(t).trim(),s=getComputedStyle(e).getPropertyValue(t).trim(),a=i||s,r=Number.parseFloat(a);if(Number.isFinite(r))return r;const o=e.getBoundingClientRect();return t==="--window-y"?o.top:o.left}}function Vx(){return{width:Math.max(1,window.innerWidth),height:Math.max(1,window.innerHeight)}}function kW(n){return n instanceof Element&&!!n.closest("button, input, select, textarea, option, label, a, [data-no-drag]")}function OW(n){return new DW(n)}class FW{constructor(e){this.options=e}activeSourceIds=null;autoFollow=!0;lastActiveKey=null;activeItem=null;renderedItems=[];reset(){this.activeSourceIds=null,this.lastActiveKey=null,this.activeItem=null,this.renderedItems=[]}render(){this.options.body.replaceChildren(),this.lastActiveKey=null,this.activeItem=null,this.renderedItems=[];const e=this.options.getSources();if(e.length===0){const _=document.createElement("p");_.className="stat-window-empty",_.textContent=this.options.getReplayPlayer()?"No events loaded.":"Load a replay to see events.",this.options.body.append(_);return}const t=v_(e,this.activeSourceIds),i=W$({sources:e,activeSourceIds:this.activeSourceIds,replayPlayers:this.options.getReplayPlayer()?.replay.players??[]}),s=document.createElement("div");s.className="event-playlist-toolbar";const a=document.createElement("details");a.className="event-playlist-filter",a.dataset.noDrag="true";const r=document.createElement("summary");r.textContent=`Filters ${t.size}/${e.length}`,a.append(r);const o=document.createElement("div");o.className="event-playlist-filter-panel";const l=document.createElement("div");l.className="event-playlist-filter-actions";const c=document.createElement("button");c.type="button",c.textContent="All",c.addEventListener("click",()=>{this.activeSourceIds=new Set(e.map(m=>m.id)),this.lastActiveKey=null,this.render();const _=this.options.getReplayPlayer()?.getState();_&&this.syncTimeline(_)});const u=document.createElement("button");u.type="button",u.textContent="None",u.addEventListener("click",()=>{this.activeSourceIds=new Set,this.lastActiveKey=null,this.render()}),l.append(c,u),o.append(l);const d=new Map;for(const _ of e){const m=d.get(_.group)??[];m.push(_),d.set(_.group,m)}for(const[_,m]of d){const v=document.createElement("section");v.className="event-playlist-filter-group";const y=document.createElement("h3");y.textContent=_,v.append(y);for(const b of m){const T=document.createElement("label");T.className="toggle event-playlist-filter-option";const x=document.createElement("input");x.type="checkbox",x.checked=t.has(b.id),x.addEventListener("change",()=>{this.setSourceSelection(e,C=>{x.checked?C.add(b.id):C.delete(b.id)})});const M=document.createElement("span");M.textContent=`${b.label} (${b.events.length})`,T.append(x,M),v.append(T)}o.append(v)}a.append(o);const h=document.createElement("label");h.className="toggle event-playlist-follow";const f=document.createElement("input");f.type="checkbox",f.checked=this.autoFollow,f.addEventListener("change",()=>{this.autoFollow=f.checked;const _=this.options.getReplayPlayer()?.getState();_&&this.syncTimeline(_,{forceScroll:!0})});const p=document.createElement("span");p.textContent="Auto-follow",h.append(f,p),s.append(a,h);const g=document.createElement("div");if(g.className="event-playlist-list",g.dataset.noDrag="true",i.length===0){const _=document.createElement("p");_.className="stat-window-empty",t.size===0?_.textContent="No event types selected.":_.textContent="No events in selected event types.",g.append(_)}else for(const _ of i){const m=document.createElement("button");m.type="button",m.className="event-playlist-item",m.dataset.eventKey=_.key,m.dataset.eventTime=`${_.event.time}`,m.style.setProperty("--event-color",_.color),Number.isFinite(_.event.time)&&this.renderedItems.push({key:_.key,time:_.event.time,element:m}),m.addEventListener("click",()=>{this.options.cueTimelineEvent(_.event)});const v=document.createElement("span");v.className="event-playlist-time",v.textContent=this.options.formatTime(_.event.time);const y=document.createElement("span");y.className="event-playlist-main";const b=document.createElement("strong");b.textContent=_.event.label??_.sourceLabel;const T=document.createElement("span");T.textContent=[_.event.playerName??null,_.event.frame!==void 0?`frame ${_.event.frame}`:null,_.sourceLabel].filter(x=>!!x).join(" · "),y.append(b,T),m.append(v,y),g.append(m)}this.options.body.append(s,g)}syncTimeline(e,t={}){if(!this.options.body.querySelector(".event-playlist-list"))return;const s=this.getActiveItem(e.currentTime),a=s?.dataset.eventKey??null;a===this.lastActiveKey&&!t.forceScroll||(this.activeItem?.isConnected?this.activeItem.dataset.active="false":this.activeItem&&(this.activeItem=null),s?(s.dataset.active="true",this.activeItem=s,(this.autoFollow||t.forceScroll)&&s.scrollIntoView({block:"nearest"})):this.activeItem=null,this.lastActiveKey=a)}setSourceSelection(e,t){const i=v_(e,this.activeSourceIds);t(i),this.activeSourceIds=i,this.lastActiveKey=null,this.render();const s=this.options.getReplayPlayer()?.getState();s&&this.syncTimeline(s)}getActiveItem(e){const t=this.renderedItems;if(t.length===0)return null;let i=0,s=t.length-1;for(;ie.getConfig||e.applyConfig).map(e=>{const t={id:e.id};return e.id==="boost"&&(t.aliases=["boost-pickup-animation"]),e.getConfig&&(t.getConfig=()=>e.getConfig?.()),e.applyConfig&&(t.applyConfig=i=>e.applyConfig?.(i)),t})}function KW(n){return HW(o1(n))}function qW({replayPlayer:n,playbackRate:e,skipPostGoalTransitions:t,skipKickoffs:i}){const s=n?.getState();return{currentTime:s?.currentTime,playing:s?.playing,rate:s?.speed??cf(Number(e?.value??1)),skipPostGoalTransitions:n?s?.skipPostGoalTransitionsEnabled:t.checked,skipKickoffs:n?s?.skipKickoffsEnabled:i.checked}}function YW({replayPlayer:n,cameraControlsController:e}){const t=n?.getState(),i=t?sE(t):e?.ballCamMode;return{mode:t?.cameraViewMode,freePreset:e?.freeCameraPreset??null,attachedPlayerId:t?.attachedPlayerId,ballCam:i===void 0?void 0:i==="on",useReplayBallCam:i===void 0?void 0:i==="player",usePlayerCameraSettings:t?.customCameraSettings===null,autoPossession:e?.autoPossessionEnabled,customSettings:t?.customCameraSettings,nameplateLiftUu:e?.nameplateLiftUu}}function jW({playback:n,camera:e,activeTimelineEventSourceIds:t,activeTimelineRangeModuleIds:i,activeMechanicTimelineKinds:s,activeRenderEffectModuleIds:a,initialConfig:r,replayPlayer:o,boostPadOverlayEnabled:l,recording:c,singletonWindows:u,statsWindows:d,moduleConfigs:h}){return{version:M_,playback:n,camera:e,overlays:{timelineEvents:[...t],timelineRanges:[...i],mechanics:[...s],renderEffects:[...a],...r?.overlays.pluginRenderEffects!==void 0?{pluginRenderEffects:[...r.overlays.pluginRenderEffects]}:{},...r?.overlays.pluginHudOverlay!==void 0?{pluginHudOverlay:r.overlays.pluginHudOverlay}:{},followedPlayerHud:!1,boostPads:l,boostPickupAnimation:o?.getState().boostPickupAnimationEnabled??!1,hitboxWireframes:o?.getState().hitboxWireframesEnabled??!1,hitboxOnlyMode:o?.getState().hitboxOnlyModeEnabled??!1},recording:c,singletonWindows:u,statsWindows:d,moduleConfigs:h}}function ZW(n,e,t){return{currentTime:n.currentTime,playing:n.playing,speed:n.rate,customCameraSettings:r1(e),cameraViewMode:e.mode,attachedPlayerId:e.attachedPlayerId,...Vb(e)==="player"?{useReplayBallCam:!0}:{ballCamEnabled:Vb(e)==="on"},boostPickupAnimationEnabled:t.overlays.boostPickupAnimation,hitboxWireframesEnabled:t.overlays.hitboxWireframes,hitboxOnlyModeEnabled:t.overlays.hitboxOnlyMode,skipPostGoalTransitionsEnabled:n.skipPostGoalTransitions,skipKickoffsEnabled:n.skipKickoffs}}function JW(n,e,t){console.groupCollapsed("[subtr-actor] stats player cfg load"),console.log("location.href",window.location.href),console.log("location.search",n.search||"(empty)"),console.log("location.hash",n.hash||"(empty)"),console.table([...n.searchParams.map(([i,s])=>({source:"search",name:i,value:s})),...n.hashParams.map(([i,s])=>({source:"hash",name:i,value:s}))]),console.log("cfg selected source",n.selectedSource??"(none)"),console.log("cfg selected raw text",n.selectedValue??"(none)"),console.log("cfg selected raw length",n.selectedValue?.length??0),console.log("cfg search values",n.searchValues),console.log("cfg hash values",n.hashValues),n.hashValues.length>0&&n.searchValues.length>0&&console.warn("Both hash and search contain cfg; hash cfg is used."),e&&(console.log("cfg normalized JSON",JSON.stringify(e,null,2)),console.log("cfg normalized object",e)),t&&console.error("cfg decode/apply error",t),console.groupEnd()}function Gx(n,e){const{style:t}=n.renderer.domElement;t.visibility=e?"hidden":"",t.pointerEvents=e?"none":""}function $x(n,e={}){const t=e.destroyPlayer??!0,i=e.clearPlayerPluginHandles??!0,s=n.getUnsubscribe();s&&(s(),n.setUnsubscribe(null)),n.teardownActiveModules(),t&&(n.getReplayPlayer()?.destroy(),n.setReplayPlayer(null)),i&&(n.setCanvasRecorder(null),n.setTimelineOverlay(null)),n.setLoadedReplayName(null),n.setStatsTimeline(null),n.setStatsFrameLookup(null),n.setStatRegistry(Jl()),n.clearTimelineEventSources(),n.clearTimelineRangeSources(),n.clearStandalonePlugins(),n.clearRenderCaches(),n.resetEventPlaylistWindow(),n.renderModuleSummary(),n.renderScoreboard(),n.renderTimelineEventCount(),n.renderMechanicsTimelineControls(),n.renderEventPlaylistWindow(),n.renderModuleSettings(),n.syncRecordingWindow()}async function QW(n,e,t){const{elements:i}=t;let s=null;i.statusReadout.textContent=n.preparingStatus,i.fileInput.disabled=!0,t.getReplayLoadModal()?.show(n.name,n.preparingStatus),t.setTransportEnabled(!1),t.getCameraControlsController()?.syncAvailability(),i.emptyState.hidden=t.getReplayPlayer()!==null,t.getReplayPlayer()?.pause();try{i.statusReadout.textContent="Parsing replay...",t.getReplayLoadModal()?.show(n.name,"Parsing replay...");const a=await e,{replay:r}=a,o=t.getReplayPlayer();if(o){$x(t,{destroyPlayer:!1,clearPlayerPluginHandles:!1});const h=new xw(a.raw);await o.replaceReplay(h,r,{preservePlayback:!1}),t.setStatsTimeline(a.statsTimeline),t.setStatsFrameLookup(a.statsFrameLookup),t.setStatRegistry(Jl(null)),t.setReplayPlayer(o),t.syncBoostPadOverlayPlugin(),t.setupActiveModules(),t.setUnsubscribe(o.subscribe(t.renderSnapshot));const f=t.getInitialConfig();if(f){t.setApplyingConfig(!0);try{t.applyConfigToReplayPlayer(f)}finally{t.setApplyingConfig(!1)}}t.getCameraControlsController()?.populateAttachedPlayerOptions(r.players),i.emptyState.hidden=!0,i.statusReadout.textContent=`Loaded ${n.name}`,t.setLoadedReplayName(n.name),i.playersReadout.textContent=r.players.map(p=>p.name).join(", "),i.framesReadout.textContent=`${r.frameCount}`,t.renderModuleSummary(),t.renderTimelineEventCount(),t.renderMechanicsTimelineControls(),t.resetEventPlaylistWindow(),t.renderEventPlaylistWindow(),t.setTransportEnabled(!0),t.getCameraControlsController()?.syncAvailability(o.getState()),t.renderSnapshot(o.getState()),t.renderStatsWindows(o.getState().frameIndex),t.renderScoreboard(o.getState().frameIndex),t.syncEventPlaylistTimeline(o.getState(),{forceScroll:!0}),t.renderModuleSettings(),t.syncRecordingWindow(),t.getReplayLoadModal()?.hide();return}const l=QN({replayEventsLabel:"Replay",replayEvents:h=>t.withTimelineEventSeekTimes(t.getReplayTimelineEvents(h.replay))}),c=kN({onStatusChange:t.syncRecordingWindow});t.setCanvasRecorder(c);const u=t.getInitialConfig(),d=e3(i.viewport,a,{initialPlaybackRate:u?.playback.rate,initialCustomCameraSettings:r1(u?.camera),initialAttachedPlayerId:u?.camera.attachedPlayerId??null,initialCameraViewMode:u?.camera.mode,initialBoostPickupAnimationEnabled:u?.overlays.boostPickupAnimation??!1,initialHitboxWireframesEnabled:u?.overlays.hitboxWireframes??i.hitboxWireframes.checked,initialHitboxOnlyModeEnabled:u?.overlays.hitboxOnlyMode??i.hitboxOnlyMode.checked,initialSkipPostGoalTransitionsEnabled:i.skipPostGoalTransitions.checked,initialSkipKickoffsEnabled:i.skipKickoffs.checked,plugins:[cN({onSample:({renderFps:h,replayFps:f})=>{const p=document.getElementById("render-fps-readout"),g=document.getElementById("replay-fps-readout");p&&(p.textContent=`${h.toFixed(0)} fps`),g&&(g.textContent=`${f.toFixed(0)} fps`)}}),bu(u3({floatingLiftUu:()=>t.getCameraControlsController()?.nameplateLiftUu})),bu(RN({includePickup:t.includeBoostPickupAnimationPickup})),bu(c),bu(l)]});if(s=d,Gx(d,!0),await d.ready,$x(t),s=null,Gx(d,!1),t.setStatsTimeline(a.statsTimeline),t.setStatsFrameLookup(a.statsFrameLookup),t.setStatRegistry(Jl(null)),t.setTimelineOverlay(l),t.setReplayPlayer(d),t.syncBoostPadOverlayPlugin(),t.setupActiveModules(),t.setUnsubscribe(d.subscribe(t.renderSnapshot)),u){t.setApplyingConfig(!0);try{t.applyConfigToReplayPlayer(u)}finally{t.setApplyingConfig(!1)}}t.getCameraControlsController()?.populateAttachedPlayerOptions(r.players),i.emptyState.hidden=!0,i.statusReadout.textContent=`Loaded ${n.name}`,t.setLoadedReplayName(n.name),i.playersReadout.textContent=r.players.map(h=>h.name).join(", "),i.framesReadout.textContent=`${r.frameCount}`,t.renderModuleSummary(),t.renderTimelineEventCount(),t.renderMechanicsTimelineControls(),t.resetEventPlaylistWindow(),t.renderEventPlaylistWindow(),t.setTransportEnabled(!0),t.getCameraControlsController()?.syncAvailability(d.getState()),t.renderSnapshot(d.getState()),t.renderStatsWindows(d.getState().frameIndex),t.renderScoreboard(d.getState().frameIndex),t.syncEventPlaylistTimeline(d.getState(),{forceScroll:!0}),t.renderModuleSettings(),t.syncRecordingWindow(),t.getReplayLoadModal()?.hide()}catch(a){throw t.getReplayLoadModal()?.hide(),s?.destroy(),t.getReplayPlayer()||(i.emptyState.hidden=!1,t.setCanvasRecorder(null)),t.syncRecordingWindow(),a}finally{i.fileInput.disabled=!1}}function e8(n){if(n<=0)return"--";const e=["B","KB","MB","GB"];let t=n,i=0;for(;t>=1024&&i=10?1:2;return`${t.toFixed(s)} ${e[i]}`}function t8(n){if(!n)return"No replay";if(n.error)return n.error;switch(n.state){case"idle":return"Idle";case"recording":return"Recording";case"stopping":return"Stopping";case"ready":return"Ready";case"error":return"Error"}}function n8({fpsValue:n,playbackRateValue:e}){const t=Number(n),i=Number(e);return{fps:Number.isFinite(t)?Math.max(1,Math.min(120,Math.trunc(t))):60,playbackRate:Number.isFinite(i)?Math.max(.1,i):1}}function i8(n,e=new Date){const i=(n?.replace(/\.replay$/i,"")||"replay").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,""),s=e.toISOString().replace(/[:.]/g,"-");return`${i||"replay"}-${s}.webm`}function s8(n,e){const t=URL.createObjectURL(n),i=document.createElement("a");i.href=t,i.download=e,document.body.append(i),i.click(),i.remove(),window.setTimeout(()=>URL.revokeObjectURL(t),0)}class a8{constructor(e){this.options=e}getConfigSnapshot(){const{elements:e}=this.options;return{fps:Number(e.fps.value),playbackRate:Number(e.playbackRate.value)}}applyConfig(e){const{elements:t}=this.options;e.fps!==void 0&&(t.fps.value=`${e.fps}`),e.playbackRate!==void 0&&(t.playbackRate.value=`${e.playbackRate}`)}sync(e=this.options.getCanvasRecorder()?.getStatus()??null){const{elements:t}=this.options,i=this.options.getCanvasRecorder()!==null&&this.options.getReplayPlayer()!==null,s=e?.state??"idle",a=s==="recording"||s==="stopping",r=(this.options.getCanvasRecorder()?.getRecording()??null)!==null;t.status.textContent=t8(e),t.elapsed.textContent=`${(e?.elapsedSeconds??0).toFixed(1)}s`,t.size.textContent=e8(e?.sizeBytes??0),t.type.textContent=e?.mimeType||"WebM",t.start.disabled=!i||a,t.fullReplay.disabled=!i||a,t.stop.disabled=!i||!a,t.download.disabled=!r||a,t.clear.disabled=!r||a,t.fps.disabled=a,t.playbackRate.disabled=a}installEventListeners(e){const{elements:t}=this.options;t.start.addEventListener("click",()=>{const i=this.options.getCanvasRecorder();if(i)try{const{fps:s}=this.getRecordingOptions();i.start({fps:s}),this.sync()}catch(s){console.error("Failed to start recording:",s),this.options.setStatus(s instanceof Error?s.message:"Failed to start recording"),this.sync(i.getStatus())}},{signal:e}),t.fullReplay.addEventListener("click",()=>{const i=this.options.getCanvasRecorder();if(!i)return;const{fps:s,playbackRate:a}=this.getRecordingOptions();i.recordFullReplay({fps:s,playbackRate:a,restorePlaybackState:!0}).catch(r=>{console.error("Failed to record replay:",r),this.options.setStatus(r instanceof Error?r.message:"Failed to record replay"),this.sync(this.options.getCanvasRecorder()?.getStatus()??null)}),this.sync()},{signal:e}),t.stop.addEventListener("click",()=>{this.options.getCanvasRecorder()?.stop().catch(i=>{console.error("Failed to stop recording:",i),this.options.setStatus(i instanceof Error?i.message:"Failed to stop recording")}),this.sync()},{signal:e}),t.download.addEventListener("click",()=>{const i=this.options.getCanvasRecorder()?.getRecording();i&&s8(i,i8(this.options.getLoadedReplayName()))},{signal:e}),t.clear.addEventListener("click",()=>{try{this.options.getCanvasRecorder()?.clear(),this.sync()}catch(i){console.error("Failed to clear recording:",i)}},{signal:e}),t.fps.addEventListener("change",this.options.requestConfigSync,{signal:e}),t.playbackRate.addEventListener("change",this.options.requestConfigSync,{signal:e})}getRecordingOptions(){const{elements:e}=this.options;return n8({fpsValue:e.fps.value,playbackRateValue:e.playbackRate.value})}}function r8(n){return new a8(n)}class o8{constructor(e){this.options=e}render(e=this.options.getReplayPlayer()?.getState().frameIndex??0){const{body:t}=this.options;t.replaceChildren();const i=this.options.getStatsFrameLookup(),s=i?zt(i,e):null,a=this.options.getReplayPlayer()?.replay??null;if(!s||!a){const o=document.createElement("p");o.className="scoreboard-empty",o.textContent="Load a replay to show the scoreboard.",t.append(o);return}const r=document.createElement("div");r.className="scoreboard-scoreline",r.append(Wx(s.team_zero?.core.goals,!0),c8(),Wx(s.team_one?.core.goals,!1)),t.append(r)}}function l8(n){return typeof n=="number"&&Number.isFinite(n)?`${Math.round(n)}`:"--"}function c8(){const n=document.createElement("span");return n.className="scoreboard-divider",n.textContent="-",n}function Wx(n,e){const t=document.createElement("strong");return t.className=`scoreboard-goal-value ${ta(e)}`,t.textContent=l8(n),t}function u8(n){return new o8(n)}class d8{constructor(e){this.options=e}setTransportEnabled(e,t){const{elements:i}=this.options;i.togglePlayback.disabled=!e,i.previousFrame.disabled=!e,i.nextFrame.disabled=!e,i.playbackRate.disabled=!e,i.skipPostGoalTransitions.disabled=!e,i.skipKickoffs.disabled=!e,i.hitboxWireframes.disabled=!e,i.hitboxOnlyMode.disabled=!e,this.options.getCameraControlsController()?.setTransportEnabled(e,t)}renderSnapshot(e){const{elements:t}=this.options;t.timeReadout.textContent=`${e.currentTime.toFixed(2)}s`,t.frameReadout.textContent=`${e.frameIndex}`,t.durationReadout.textContent=`${e.duration.toFixed(2)}s`,t.playbackStatusReadout.textContent=e.playing?"Playing":"Paused",t.togglePlayback.textContent=e.playing?"Pause":"Play";const i=Math.max(0,this.options.getFrameCount()-1);t.previousFrame.disabled=e.frameIndex<=0,t.nextFrame.disabled=e.frameIndex>=i;const s=cf(e.speed);t.playbackRate.value=`${s}`,t.playbackRateReadout.textContent=qg(s),this.options.getCameraControlsController()?.syncState(e),t.skipPostGoalTransitions.checked=e.skipPostGoalTransitionsEnabled,t.skipKickoffs.checked=e.skipKickoffsEnabled,t.hitboxWireframes.checked=e.hitboxWireframesEnabled,t.hitboxOnlyMode.checked=e.hitboxOnlyModeEnabled,t.emptyState.hidden=!0}}function h8(n){return new d8(n)}function f8({elements:n,signal:e,setLauncherOpen:t,openReplayFilePicker:i,getElementWindowId:s,toggleWindow:a,hideWindow:r,createStatsWindow:o,loadReplayFile:l,togglePlayback:c,stepFrames:u,setPlaybackRate:d,setSkipPostGoalTransitionsEnabled:h,setSkipKickoffsEnabled:f,setHitboxWireframesEnabled:p,setHitboxOnlyModeEnabled:g}){n.launcherToggle.addEventListener("click",()=>{t(n.launcherMenu.hidden)},{signal:e}),n.root.addEventListener("click",m=>{m.target instanceof Element&&(m.target.closest(".top-chrome")||t(!1))},{signal:e}),n.loadReplayAction.addEventListener("click",i,{signal:e}),n.emptyLoadReplay.addEventListener("click",i,{signal:e}),n.root.querySelectorAll("[data-window-toggle]").forEach(m=>{m.addEventListener("click",()=>{const v=m.dataset.windowToggle;v&&(a(v),t(!1))},{signal:e})}),n.root.querySelectorAll("[data-window-hide]").forEach(m=>{m.addEventListener("click",()=>{const v=m.dataset.windowHide??s(m);v&&r(v)},{signal:e})}),n.root.querySelectorAll("[data-create-stats-window]").forEach(m=>{m.addEventListener("click",()=>{o(m.dataset.createStatsWindow)},{signal:e})}),n.fileInput.addEventListener("change",()=>{const m=n.fileInput.files?.[0];m&&l(m)},{signal:e}),n.togglePlayback.addEventListener("click",c,{signal:e}),n.previousFrame.addEventListener("click",()=>u(-1),{signal:e}),n.nextFrame.addEventListener("click",()=>u(1),{signal:e});const _=()=>{const m=cf(Number(n.playbackRate.value));n.playbackRate.value=`${m}`,n.playbackRateReadout.textContent=qg(m),d(m)};n.playbackRate.addEventListener("input",_,{signal:e}),n.playbackRate.addEventListener("change",_,{signal:e}),n.skipPostGoalTransitions.addEventListener("change",()=>{h(n.skipPostGoalTransitions.checked)},{signal:e}),n.skipKickoffs.addEventListener("change",()=>{f(n.skipKickoffs.checked)},{signal:e}),n.hitboxWireframes.addEventListener("change",()=>{p(n.hitboxWireframes.checked)},{signal:e}),n.hitboxOnlyMode.addEventListener("change",()=>{g(n.hitboxOnlyMode.checked)},{signal:e})}const p8=3500;function m8(){const n=document.activeElement;if(!(n instanceof HTMLElement))return!1;if(n.isContentEditable)return!0;const e=n.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"}function _8(n){const{getReplayPlayer:e,signal:t}=n,i={forward:!1,backward:!1,left:!1,right:!1,up:!1,down:!1},s=()=>{i.forward=!1,i.backward=!1,i.left=!1,i.right=!1,i.up=!1,i.down=!1},a=(g,_)=>{switch(g){case"KeyW":return i.forward=_,!0;case"KeyS":return i.backward=_,!0;case"KeyA":return i.left=_,!0;case"KeyD":return i.right=_,!0;case"Space":return i.up=_,!0;case"ShiftLeft":case"ShiftRight":return i.down=_,!0;default:return!1}},r=g=>{g.ctrlKey||g.metaKey||g.altKey||m8()||a(g.code,!0)&&g.preventDefault()},o=g=>{a(g.code,!1)};window.addEventListener("keydown",r,{signal:t}),window.addEventListener("keyup",o,{signal:t}),window.addEventListener("blur",s,{signal:t});const l=new S,c=new S,u=new S,d=new S(0,1,0);let h=null,f=0;const p=g=>{f=requestAnimationFrame(p);const _=h===null?0:Math.min(.1,(g-h)/1e3);h=g;const m=(i.forward?1:0)-(i.backward?1:0),v=(i.right?1:0)-(i.left?1:0),y=(i.up?1:0)-(i.down?1:0);if(_===0||m===0&&v===0&&y===0)return;const b=e();if(!b||b.getState().cameraViewMode!=="free")return;const T=b.camera,x=b.controls;T.getWorldDirection(l),c.set(1,0,0).applyQuaternion(T.quaternion),u.set(0,0,0).addScaledVector(l,m).addScaledVector(c,v).addScaledVector(d,y),u.lengthSq()!==0&&(u.normalize().multiplyScalar(p8*_),T.position.add(u),x.target.add(u))};f=requestAnimationFrame(p),t.addEventListener("abort",()=>{cancelAnimationFrame(f)})}function g8(n,e){const t=new URLSearchParams(n),s=(t.get("replayId")??t.get("replay-id")??e??"").trim();return s.length>0?s:null}function y8(){const n=new URLSearchParams(window.location.search),e=n.get("reviewToken")??n.get("token")??window.localStorage.getItem("rocket_sense_access_token");return e?{Authorization:`Bearer ${e}`}:{}}function v8(n){if(!n.replayId)return null;const e={replay_id:n.replayId,reviewed_mechanic:n.mechanic,reviewed_event_frame:n.frame,reviewed_event_time:n.time,confidence:n.confidence,status:"confirmed"};return n.subjectKind&&n.subjectId&&(e.reviewed_subject_kind=n.subjectKind,e.reviewed_subject_id=n.subjectId),n.startFrame!==null&&(e.reviewed_start_frame=n.startFrame),n.endFrame!==null&&(e.reviewed_end_frame=n.endFrame),n.notes&&n.notes.trim()&&(e.notes=n.notes.trim()),Object.keys(n.context).length>0&&(e.context=n.context),e}function b8(n,e){const t=n.getState(),i=Math.max(0,Math.round(t.frameIndex??0)),s=t.currentTime??0,a=t.attachedPlayerId??null,r=a?n.replay.players.find(o=>o.id===a)?.name??null:null;return{localId:e.localId,mechanic:e.mechanic,frame:i,time:s,subjectKind:a?"player":null,subjectId:a,playerName:r,startFrame:null,endFrame:null,notes:e.notes?.trim()?e.notes.trim():null,confidence:1,replayId:e.replayId,context:{capturedFrom:"stat-evaluation-player",attachedPlayerId:a,playerName:r,durationSeconds:n.replay.duration??null}}}async function x8(n,e="/api/v1/events/reviews"){const t=v8(n);if(!t)return{record:n,ok:!1,message:"No replay id — cannot upload (export JSON instead)."};try{const i=await fetch(e,{method:"POST",headers:{"content-type":"application/json",...y8()},credentials:"same-origin",body:JSON.stringify(t)});if(!i.ok){let s=`${i.status}${i.statusText?` ${i.statusText}`:""}`;try{const a=await i.json();typeof a.error=="string"&&(s=a.error)}catch{}return{record:n,ok:!1,message:s}}return{record:n,ok:!0,message:"uploaded"}}catch(i){return{record:n,ok:!1,message:i instanceof Error?i.message:String(i)}}}const w8=["flick","whiff","double_tap","ceiling_shot","wall_aerial","flip_reset","one_timer","speed_flip","half_flip","wavedash","demo"],S8="m";function T8(){const n=document.activeElement;if(!(n instanceof HTMLElement))return!1;if(n.isContentEditable)return!0;const e=n.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"}function M8(n,e){const t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),i=URL.createObjectURL(t),s=document.createElement("a");s.href=i,s.download=n,document.body.appendChild(s),s.click(),s.remove(),URL.revokeObjectURL(i)}class E8{constructor(e){this.options=e}records=[];localIdSeq=0;installEventListeners(e){const{elements:t}=this.options;for(const i of w8){const s=document.createElement("option");s.value=i,s.textContent=i.replaceAll("_"," "),t.mechanic.appendChild(s)}t.capture.addEventListener("click",()=>this.capture(),{signal:e}),t.export.addEventListener("click",()=>this.exportJson(),{signal:e}),t.upload.addEventListener("click",()=>{this.uploadAll()},{signal:e}),t.clear.addEventListener("click",()=>{this.records.length=0,this.render(),this.setStatus("Cleared.")},{signal:e}),window.addEventListener("keydown",i=>{i.key.toLowerCase()!==S8||i.repeat||i.metaKey||i.ctrlKey||i.altKey||T8()||(i.preventDefault(),this.capture())},{signal:e}),this.render()}capture(){const e=this.options.getReplayPlayer();if(!e){this.setStatus("No replay loaded.");return}this.localIdSeq+=1;const t=b8(e,{mechanic:this.options.elements.mechanic.value||"flick",replayId:this.resolveReplayId(),localId:`missed-${this.localIdSeq}`});this.records.push(t),this.options.showWindow(),this.render(),this.setStatus(`Captured ${t.mechanic} @ ${t.time.toFixed(2)}s`+(t.replayId?".":" (no replay id — export only)."))}exportJson(){if(this.records.length===0){this.setStatus("Nothing to export.");return}M8("missed-events.json",{capturedFrom:"stat-evaluation-player",replayId:this.resolveReplayId(),missedEvents:this.records}),this.setStatus(`Exported ${this.records.length}.`)}async uploadAll(){if(this.records.length===0){this.setStatus("Nothing to upload.");return}let e=0;const t=[];for(const i of[...this.records]){const s=await x8(i);if(s.ok){e+=1;const a=this.records.findIndex(r=>r.localId===i.localId);a>=0&&this.records.splice(a,1)}else t.push(`${i.mechanic}@${i.time.toFixed(1)}s: ${s.message}`)}this.render(),this.setStatus(t.length===0?`Uploaded ${e}.`:`Uploaded ${e}, ${t.length} failed — ${t[0]}`)}render(){const{list:e}=this.options.elements;e.replaceChildren();for(const t of this.records){const i=document.createElement("li"),s=t.playerName??t.subjectId??"no subject",a=document.createElement("span");a.className="missed-event-row",a.textContent=`${t.mechanic} @ ${t.time.toFixed(2)}s · f${t.frame} · ${s}`+(t.replayId?"":" · no replay id");const r=document.createElement("button");r.type="button",r.textContent="✕",r.title="Remove",r.addEventListener("click",()=>{const o=this.records.findIndex(l=>l.localId===t.localId);o>=0&&(this.records.splice(o,1),this.render())}),i.append(a,r),e.appendChild(i)}}setStatus(e){this.options.elements.status.textContent=e}resolveReplayId(){return g8(window.location.search,this.options.getReplayId?.()??null)}}function C8(n){return new E8(n)}class A8{constructor(e){this.options=e}activeModules=[];activeTimelineEventSourceIds=new Set;activeTimelineRangeModuleIds=new Set;activeMechanicTimelineKinds=new Set;activeRenderEffectModuleIds=new Set;removeRenderHook=null;timelineSourceRemovers=new Map;timelineRangeSourceRemovers=new Map;getActiveModules(){return this.activeModules}getActiveTimelineEventSourceIds(){return this.activeTimelineEventSourceIds}getActiveTimelineRangeModuleIds(){return this.activeTimelineRangeModuleIds}getActiveMechanicTimelineKinds(){return this.activeMechanicTimelineKinds}getActiveRenderEffectModuleIds(){return this.activeRenderEffectModuleIds}getActiveCapabilityIds(e){return e==="events"?this.activeTimelineEventSourceIds:e==="ranges"?this.activeTimelineRangeModuleIds:this.activeRenderEffectModuleIds}getBoostPadOverlayEnabled(){return!0}getTimelineEventSourceIds(){return[...this.activeTimelineEventSourceIds]}getTimelineRangeModuleIds(){return[...this.activeTimelineRangeModuleIds]}getMechanicTimelineKinds(){return[...this.activeMechanicTimelineKinds]}getRenderEffectModuleIds(){return[...this.activeRenderEffectModuleIds]}applyOverlayConfig({timelineEvents:e,timelineRanges:t,mechanics:i,renderEffects:s,boostPads:a}){this.activeTimelineEventSourceIds=new Set(e),this.activeTimelineRangeModuleIds=new Set(t),this.activeMechanicTimelineKinds=new Set(i),this.activeRenderEffectModuleIds=new Set(s)}reset(){this.teardownActiveModules(),this.clearStandalonePlugins(),this.activeModules=[],this.activeTimelineEventSourceIds=new Set,this.activeTimelineRangeModuleIds=new Set,this.activeMechanicTimelineKinds=new Set,this.activeRenderEffectModuleIds=new Set,this.removeRenderHook=null}setupActiveModules(){this.teardownActiveModules();const e=this.options.getContext();if(!e)return;const t=this.getActiveModuleIds();this.activeModules=this.options.modules.filter(i=>t.has(i.id)),this.options.boostPickupFilters.setup(e);for(const i of this.activeModules)i.setup(e);this.removeRenderHook=e.player.onBeforeRender(i=>{for(const s of this.activeModules)this.activeRenderEffectModuleIds.has(s.id)&&s.onBeforeRender(i)}),this.syncTimelineEvents(),this.syncTimelineRanges()}teardownActiveModules(){this.removeRenderHook?.(),this.removeRenderHook=null,this.clearTimelineEventSources(),this.clearTimelineRangeSources();for(const e of this.activeModules)e.teardown();this.activeModules=[]}toggleCapability(e,t,i){const s=this.getMutableActiveCapabilityIds(t);i?s.add(e):s.delete(e),this.setupActiveModules(),this.options.renderModuleSummary(),this.options.renderModuleSettings(),this.options.renderStatsWindows(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()}setMechanicTimelineKind(e,t){t?this.activeMechanicTimelineKinds.add(e):this.activeMechanicTimelineKinds.delete(e),this.options.requestConfigSync()}activateMechanicTimelineKind(e){this.activeMechanicTimelineKinds.add(e),this.syncTimelineEvents(),this.syncTimelineRanges(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()}clearTimelineEventSources(){for(const e of this.timelineSourceRemovers.values())e();this.timelineSourceRemovers.clear()}clearTimelineRangeSources(){for(const e of this.timelineRangeSourceRemovers.values())e();this.timelineRangeSourceRemovers.clear()}clearStandalonePlugins(){}syncBoostPadOverlayPlugin(){}toggleBoostPadOverlay(){this.options.renderModuleSummary(),this.options.requestConfigSync()}syncTimelineEvents(){this.clearTimelineEventSources();const e=this.options.getContext(),t=this.options.getTimelineOverlay();if(!(!t||!e)){for(const i of this.options.getEventTimelineSources(e)){if(!i.active)continue;const s=i.buildTimelineEvents();s.length!==0&&this.timelineSourceRemovers.set(i.timelineKey,t.addEventSource(this.options.withTimelineEventSeekTimes(s),{id:i.timelineId,label:i.label}))}t.refreshEvents()}}syncTimelineRanges(){this.clearTimelineRangeSources();const e=this.options.getContext(),t=this.options.getTimelineOverlay();if(!(!t||!e)){for(const i of this.activeModules)!this.activeTimelineRangeModuleIds.has(i.id)||!i.getTimelineRanges||this.timelineRangeSourceRemovers.set(i.id,t.addRangeSource(()=>i.getTimelineRanges?.(e)??[]));for(const i of this.options.getEventTimelineSources(e)){if(!i.active||!i.buildTimelineRanges)continue;const s=i.buildTimelineRanges();s.length!==0&&this.timelineRangeSourceRemovers.set(i.timelineKey,t.addRangeSource(s))}t.refreshRanges()}}getActiveModuleIds(){return new Set([...this.activeTimelineEventSourceIds,...this.activeTimelineRangeModuleIds,...this.activeRenderEffectModuleIds])}getMutableActiveCapabilityIds(e){return e==="events"?this.activeTimelineEventSourceIds:e==="ranges"?this.activeTimelineRangeModuleIds:this.activeRenderEffectModuleIds}}function R8(n){return new A8(n)}function Jn(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Xx(n){return Jn(n)&&(n.kind==="time"||n.kind==="frame")&&typeof n.value=="number"&&Number.isFinite(n.value)?{kind:n.kind,value:n.value}:null}function Nu(n,e){if(n!=null){if(typeof n!="number"||!Number.isInteger(n)||!Number.isFinite(n)||n<0)throw new Error(`Review playlist page ${e} must be a non-negative integer.`);return n}}function Kx(n,e){if(n!=null){if(typeof n!="string")throw new Error(`Review playlist page ${e} must be a string.`);return n}}function P8(n){if(n!=null){if(!Jn(n))throw new Error("Review playlist page must be an object.");return{next:Kx(n.next,"next"),previous:Kx(n.previous,"previous"),total:Nu(n.total,"total"),count:Nu(n.count,"count"),limit:Nu(n.limit,"limit"),offset:Nu(n.offset,"offset")}}}function I8(n){if(n!=null){if(!Jn(n))throw new Error("Review playlist playback must be an object.");if(n.timeBase!==void 0&&n.timeBase!=="playback"&&n.timeBase!=="rawReplay")throw new Error('Review playlist playback timeBase must be "playback" or "rawReplay".');return{...n,timeBase:n.timeBase}}}function L8(n,e){if(n==null)return;if(!Jn(n))throw new Error(`Review item ${e} perspective must be an object.`);if(n.kind!=="player")throw new Error(`Review item ${e} perspective kind must be "player".`);const t=typeof n.playerId=="string"&&n.playerId.trim()?n.playerId.trim():void 0,i=typeof n.playerName=="string"&&n.playerName.trim()?n.playerName.trim():void 0;if(!t&&!i)throw new Error(`Review item ${e} player perspective needs playerId or playerName.`);if(n.ballCam!==void 0&&n.ballCam!=="off"&&n.ballCam!=="on"&&n.ballCam!=="player")throw new Error(`Review item ${e} perspective ballCam must be off, on, or player.`);if(n.usePlayerCameraSettings!==void 0&&typeof n.usePlayerCameraSettings!="boolean")throw new Error(`Review item ${e} perspective usePlayerCameraSettings must be boolean.`);return{kind:"player",playerId:t,playerName:i,ballCam:n.ballCam,usePlayerCameraSettings:n.usePlayerCameraSettings}}function D8(n){if(!Jn(n)||!Array.isArray(n.items))throw new Error("Review playlist must contain an items array.");const e=n.items.map((i,s)=>{if(!Jn(i)||typeof i.replay!="string")throw new Error(`Invalid review item at index ${s}.`);const a=Xx(i.start),r=Xx(i.end);if(!a||!r)throw new Error(`Review item ${s+1} has invalid start or end.`);return{id:typeof i.id=="string"?i.id:void 0,replay:i.replay,start:a,end:r,label:typeof i.label=="string"?i.label:void 0,perspective:L8(i.perspective,s+1),meta:Jn(i.meta)?i.meta:void 0}}),t=Array.isArray(n.replays)?n.replays.map(i=>!Jn(i)||typeof i.id!="string"?null:{id:i.id,path:typeof i.path=="string"?i.path:void 0,label:typeof i.label=="string"?i.label:void 0,locator:Jn(i.locator)?i.locator:void 0,meta:Jn(i.meta)?i.meta:void 0}).filter(i=>i!==null):void 0;return{label:typeof n.label=="string"?n.label:void 0,replays:t,items:e,page:P8(n.page),playback:I8(n.playback),meta:n.meta}}function qx(n){let e;try{e=JSON.parse(n)}catch(t){throw new Error(`Invalid review playlist JSON: ${t instanceof Error?t.message:String(t)}`)}return D8(e)}function k8(){const n=new URLSearchParams(window.location.search);return n.get("reviewPlaylist")?.trim()||n.get("review")?.trim()||n.get("playlist")?.trim()||n.get("playlistUrl")?.trim()||null}function O8(n){return/^\/(?:home|Users|tmp|var\/tmp|mnt|media|run\/user|nix\/store)\//.test(n)}function l1(n,e){const t=n.startsWith("path:")?n.slice(5):n;if(/^https?:\/\//i.test(t)||t.startsWith("/@fs/"))return t;if(t.startsWith("/")){if(O8(t))return`/@fs${t}`;if(e){const i=new URL(e,window.location.href);if(i.origin!==window.location.origin)return new URL(t,i.origin).href}return t}return e?new URL(t,e).href:t}function rd(n,e){const t=e.replaysById.get(n.replay);if(t?.path)return t.path;if(Jn(t?.locator)&&t.locator.kind==="path"&&typeof t.locator.path=="string")return t.locator.path;if(/^https?:\/\//i.test(n.replay)||n.replay.startsWith("/")||n.replay.startsWith("/@fs/")||n.replay.startsWith("path:"))return n.replay;throw new Error(`Review replay "${n.replay}" does not include a loadable path.`)}function Yx(n,e){const t=e.replaysById.get(n.replay),s=(t?.path??rd(n,e)).replace(/^path:/,"").split("/").filter(Boolean).pop();return t?.label??s??"review replay"}function od(n){return typeof n=="number"&&Number.isFinite(n)?`${n.toFixed(2)}s`:"--"}function jx(n){return n.kind==="time"?od(n.value):`frame ${Math.trunc(n.value)}`}function Ki(n,e){if(!Jn(n.meta?.target))return null;const t=n.meta.target[e];return typeof t=="number"&&Number.isFinite(t)?t:null}function ld(n,e){if(!Jn(n.meta?.target))return null;const t=n.meta.target[e];return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):null}function F8(n,e){for(const[t,i]of[["eventTime","eventFrame"],["startTime","startFrame"],["endTime","endFrame"]]){const s=Ki(n,t),a=ld(n,i),r=a===null?null:e.frames[a]?.time;if(s!==null&&typeof r=="number"&&Number.isFinite(r))return s-r}return 0}function c1(n,e,t){return t==="playback"?0:t==="rawReplay"&&typeof e.rawStartTime=="number"&&Number.isFinite(e.rawStartTime)?e.rawStartTime:F8(n,e)}function C_(n,e){return Math.min(Math.max(0,n),Math.max(0,e))}function N8(n,e,t,i){if(e.kind==="frame"){const a=Math.max(0,Math.trunc(e.value));return C_(t.frames[a]?.time??0,t.duration)}const s=c1(n,t,i);return C_(e.value-s,t.duration)}function U8(n,e,t){const i=$8(n);return i===null?null:C_(i-c1(n,e,t),e.duration)}function B8(n){const e=n.start.kind==="time"?n.start.value:null,t=n.end.kind==="time"?n.end.value:null,i=[`${jx(n.start)} to ${jx(n.end)}`];e!==null&&t!==null&&i.push(`${Math.max(0,t-e).toFixed(1)}s clip`);const s=Ki(n,"startTime")??Ki(n,"eventTime"),a=Ki(n,"endTime")??Ki(n,"eventTime");return e!==null&&s!==null&&i.push(`${Math.max(0,s-e).toFixed(1)}s preroll`),t!==null&&a!==null&&i.push(`${Math.max(0,t-a).toFixed(1)}s postroll`),i.join(" · ")}function z8(n){const e=Ki(n,"eventTime"),t=Ki(n,"startTime"),i=Ki(n,"endTime"),s=ld(n,"eventFrame"),a=ld(n,"startFrame"),r=ld(n,"endFrame"),o=t!==null&&i!==null&&Math.abs(i-t)>.001?`${od(t)} to ${od(i)}`:od(e??t??i),l=a!==null&&r!==null&&r!==a?`frames ${a}-${r}`:s!==null?`frame ${s}`:a!==null?`frame ${a}`:null;return[o,l].filter(c=>c&&c!=="--").join(" · ")||"--"}function um(n,e){return n.label??n.meta?.eventTypeLabel??n.meta?.mechanicLabel??`Review item ${e+1}`}function H8(n){if(typeof n.meta?.playerName=="string"&&n.meta.playerName.trim())return n.meta.playerName.trim();if(Jn(n.meta?.target)&&typeof n.meta.target.playerName=="string"){const e=n.meta.target.playerName.trim();return e||null}return null}function Zx(n,e){if(!n)return null;if(n.playerId){const i=e.find(s=>s.id===n.playerId);if(i)return i}const t=n.playerName?.toLowerCase();return t?e.find(i=>i.name.trim().toLowerCase()===t)??null:null}function Jx(n){if(typeof n.meta?.eventTypeLabel=="string"&&n.meta.eventTypeLabel.trim())return n.meta.eventTypeLabel;if(typeof n.meta?.mechanicLabel=="string"&&n.meta.mechanicLabel.trim())return n.meta.mechanicLabel;const e=n.meta?.eventType??n.meta?.mechanic;return typeof e=="string"?Ci(e):"--"}function V8(n){const e=n.meta?.eventCategory;return typeof e=="string"&&e.trim()?Ci(e.trim()):"--"}function G8(n){const e=n.meta?.eventType??n.meta?.mechanic;return typeof e=="string"&&e.trim()?e.trim().replaceAll("-","_"):null}function $8(n){return Ki(n,"eventTime")??Ki(n,"startTime")??Ki(n,"endTime")}class W8{constructor(e){this.options=e}createReplaySource(e,t,i){const s=rd(e,t),a=l1(s,t.sourceUrl);return{name:Yx(e,t),preparingStatus:"Loading review replay...",async readBytes(){const r=await fetch(a,{signal:i});if(!r.ok){const o=r.statusText?` ${r.statusText}`:"";throw new Error(`Failed to fetch review replay from ${a} (${r.status}${o})`)}return new Uint8Array(await r.arrayBuffer())}}}initialize(e){const t=this.getReplayClipCounts(e);for(const[i,s]of this.getReplayItems(e)){let a="",r=i;try{a=rd(s,e),r=Yx(s,e)}catch{r=e.replaysById.get(i)?.label??i}e.replayLoadStates.set(i,{replayId:i,label:r,path:a,clipCount:t.get(i)??0,status:"idle",progress:null,error:null})}}preload(e,t){if(e.preloading)return;const i=this.getNextReplayItems(e,t);i.length!==0&&(e.preloading=!0,(async()=>{try{for(const s of i){const a=s.replay,r=e.replayLoadStates.get(a);if(!(r?.status==="loaded"||r?.status==="loading"))try{await this.loadBundle(s,e)}catch{}}}finally{e.preloading=!1}})())}loadBundle(e,t){const i=t.replayLoadCache.get(e.replay);if(i)return i;const s=this.createReplaySource(e,t);this.updateLoadState(t,e.replay,{label:s.name,path:rd(e,t),status:"loading",progress:null,error:null});const a=Promise.resolve().then(async()=>{const r=await s.readBytes();return iE(r,{reportEveryNFrames:100,onProgress:o=>{this.updateLoadState(t,e.replay,{status:"loading",progress:o,error:null})}})}).then(r=>(this.updateLoadState(t,e.replay,{status:"loaded",progress:null,error:null}),r)).catch(r=>{throw t.replayLoadCache.delete(e.replay),this.updateLoadState(t,e.replay,{status:"error",error:r instanceof Error?r.message:String(r)}),r});return t.replayLoadCache.set(e.replay,a),a}render(e){const{reviewSummary:t,loadingSummary:i,loadingActive:s,loadingList:a}=this.options.elements,r=e?Array.from(e.replayLoadStates.values()):[],o=r.filter(h=>h.status==="loaded").length,l=r.filter(h=>h.status==="loading").length,c=r.filter(h=>h.status==="error").length,u=r.filter(h=>h.status==="idle").length,d=r.length===0?"0 replays":`${o}/${r.length} loaded${l>0?`, ${l} loading`:""}${c>0?`, ${c} failed`:""}`;if(t.textContent=d,i.textContent=d,s.textContent=r.length===0?"No playlist":l>0?`${l} active, ${u} pending`:c>0?`${c} failed`:e?.preloading?`Background queue, ${u} pending`:o===r.length?"Complete":`${u} pending`,a.replaceChildren(),!e||r.length===0){const h=document.createElement("p");h.className="stat-window-empty",h.textContent="No replay sources.",a.append(h);return}for(const h of r){const f=document.createElement("div");f.className=`mechanics-review-replay-load ${h.status}`;const p=document.createElement("div");p.className="mechanics-review-replay-load-main";const g=document.createElement("span");g.className="mechanics-review-replay-load-title",g.textContent=h.label;const _=document.createElement("span");_.className="mechanics-review-replay-load-meta",_.textContent=[h.replayId,`${h.clipCount} ${h.clipCount===1?"clip":"clips"}`,h.path].filter(Boolean).join(" · "),p.append(g,_);const m=document.createElement("strong");m.className="mechanics-review-replay-load-status",m.textContent=this.replayLoadStatusText(h);const v=document.createElement("div");v.className="mechanics-review-replay-load-progress";const y=document.createElement("span");y.style.width=`${Math.round(this.replayLoadProgressValue(h)*100)}%`,v.append(y),f.append(p,m,v),a.append(f)}}updateLoadState(e,t,i){const s=e.replayLoadStates.get(t)??{replayId:t,label:t,path:"",clipCount:0,status:"idle",progress:null,error:null};e.replayLoadStates.set(t,{...s,...i});const a=e.manifest.items[e.currentIndex];e.loading&&a?.replay===t&&i.progress&&this.options.onActiveLoadProgress(i.progress),this.options.isActiveReview(e)&&this.render(e)}getReplayItems(e){const t=new Map;for(const i of e.manifest.items)t.has(i.replay)||t.set(i.replay,i);return t}getReplayClipCounts(e){const t=new Map;for(const i of e.manifest.items)t.set(i.replay,(t.get(i.replay)??0)+1);return t}getNextReplayItems(e,t){const i=e.manifest.items[t]?.replay,s=new Set(i?[i]:[]),a=[];for(let r=t+1;r{const i=t.file.files?.[0];if(i)try{const s=qx(await i.text());await this.loadPlaylist(s,null)}catch(s){console.error("Failed to load review playlist:",s),this.setStatus(s instanceof Error?s.message:"Failed to load review playlist")}finally{t.file.value=""}},{signal:e}),t.loadUrl.addEventListener("click",()=>{this.loadPlaylistFromUrl(t.url.value.trim()).catch(i=>{console.error("Failed to load review playlist URL:",i),this.setStatus(i instanceof Error?i.message:"Failed to load review playlist URL")})},{signal:e}),t.previous.addEventListener("click",()=>{const i=this.activeReview;i&&this.activateItem(Math.max(0,i.currentIndex-1))},{signal:e}),t.replay.addEventListener("click",()=>this.replayClip(),{signal:e}),t.next.addEventListener("click",()=>{const i=this.activeReview;i&&this.activateItem(Math.min(i.manifest.items.length-1,i.currentIndex+1))},{signal:e}),t.confirm.addEventListener("click",()=>{this.submitDecision("confirmed")},{signal:e}),t.reject.addEventListener("click",()=>{this.submitDecision("rejected")},{signal:e}),t.uncertain.addEventListener("click",()=>{this.submitDecision("uncertain")},{signal:e})}render(){const{elements:e}=this.options,t=this.activeReview,i=t?.manifest.items??[],s=t?i[t.currentIndex]??null:null,a=i.length>0;e.count.textContent=`${i.length} item${i.length===1?"":"s"}`,e.index.textContent=a&&t?`${t.currentIndex+1} / ${i.length}`:"0 / 0",e.title.textContent=s?um(s,t?.currentIndex??0):"No candidate selected",e.mechanic.textContent=s?Jx(s):"--",e.player.textContent=s?this.getPlayerName(s):"--",e.clip.textContent=s?B8(s):"--",e.event.textContent=s?z8(s):"--",e.reason.textContent=s?.meta?.reason??"--",e.previous.disabled=!t||t.loading||t.currentIndex<=0,e.replay.disabled=!t||t.loading||!t.currentClip,e.next.disabled=!t||t.loading||t.currentIndex>=i.length-1;const r=!t||t.loading||Qx(s)===null;if(e.confirm.disabled=r,e.reject.disabled=r,e.uncertain.disabled=r,this.options.replayLoads.render(t),e.list.replaceChildren(),!t||i.length===0){const o=document.createElement("p");o.className="stat-window-empty",o.textContent="No review playlist loaded.",e.list.append(o);return}i.forEach((o,l)=>{const c=document.createElement("button");c.type="button",c.className="mechanics-review-item",c.dataset.active=l===t.currentIndex?"true":"false",c.disabled=t.loading,c.addEventListener("click",()=>{this.activateItem(l)});const u=document.createElement("span");u.textContent=um(o,l);const d=document.createElement("strong");d.textContent=[V8(o),Jx(o),this.getPlayerName(o),dm(o.meta?.reviewStatus)].filter(h=>h&&h!=="--").join(" · ")||"--",c.append(u,d),e.list.append(c)})}async loadPlaylist(e,t){const i=new Map;for(const s of e.replays??[])i.set(s.id,s);this.activeReview={manifest:e,sourceUrl:t,replaysById:i,replayLoadStates:new Map,replayLoadCache:new Map,currentIndex:0,loading:!1,preloading:!1,currentReplayId:null,currentClip:null},this.options.replayLoads.initialize(this.activeReview),this.options.showReplayLoadingWindow(),this.setStatus(e.label?`Loaded ${e.label}.`:"Loaded review playlist."),this.render(),e.items.length>0&&await this.activateItem(0)}async loadPlaylistFromUrl(e){if(!e){this.setStatus("Enter a review playlist URL.");return}const t=l1(e,window.location.href);this.setStatus("Loading review playlist...");const i=await fetch(t);if(!i.ok){const a=i.statusText?` ${i.statusText}`:"";throw new Error(`Failed to fetch review playlist from ${t} (${i.status}${a})`)}const s=qx(await i.text());await this.loadPlaylist(s,i.url||t)}async activateItem(e){const t=this.activeReview,i=t?.manifest.items[e];if(!(!t||!i||t.loading)){t.loading=!0,t.currentIndex=e,this.render(),this.setStatus(`Loading ${um(i,e)}...`);try{if(!this.options.getReplayPlayer()||t.currentReplayId!==i.replay){const d=this.options.replayLoads.createReplaySource(i,t),h=this.options.replayLoads.loadBundle(i,t);await this.options.loadReplayBundleForDisplay(d,h),t.currentReplayId=i.replay}this.options.replayLoads.preload(t,e);const a=t.manifest.playback?.timeBase,r=Math.max(0,this.getBoundTime(i,i.start,a)),o=Math.min(this.options.getReplayPlayer()?.getState().duration??Number.POSITIVE_INFINITY,Math.max(r,this.getBoundTime(i,i.end,a)));if(!Number.isFinite(r)||!Number.isFinite(o)||o<=r)throw new Error("Review item has an empty playback range.");const l=this.options.getReplayPlayer(),c=l?Zx(i.perspective,l.replay.players):null;c&&this.options.applyClipPerspective({playerId:c.id,ballCam:i.perspective?.ballCam,usePlayerCameraSettings:i.perspective?.usePlayerCameraSettings}),this.options.resetReplayTransitionControls();const u=l===null?null:U8(i,l.replay,a);t.currentClip={startTime:r,endTime:o,targetTime:u},this.options.activateTimelineSource(i),this.options.getReplayPlayer()?.setState({currentTime:r,playing:!0,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),this.setStatus(u===null?`Playing ${r.toFixed(2)}s to ${o.toFixed(2)}s`:`Playing ${r.toFixed(2)}s to ${o.toFixed(2)}s; target ${u.toFixed(2)}s`)}catch(s){console.error("Failed to activate mechanics review item:",s),t.currentClip=null,this.setStatus(s instanceof Error?s.message:"Failed to load review item")}finally{t.loading=!1,this.render()}}}replayClip(){const e=this.activeReview?.currentClip,t=this.options.getReplayPlayer();!e||!t||t.setState({currentTime:e.startTime,playing:!0,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1})}async submitDecision(e){const t=this.activeReview,i=t?.manifest.items[t.currentIndex]??null,s=Qx(i);if(!t||!i||!s){this.setStatus("Current review item has no review endpoint.");return}this.setStatus(`Submitting ${dm(e)}...`);const a=await fetch(s,{method:"POST",headers:{"content-type":"application/json",...q8()},credentials:"same-origin",body:JSON.stringify({status:e})});if(!a.ok){let r=`${a.status}${a.statusText?` ${a.statusText}`:""}`;try{const o=await a.json();typeof o.error=="string"&&(r=o.error)}catch{}this.setStatus(`Review failed: ${r}`);return}i.meta=i.meta??{},i.meta.reviewStatus=e,this.setStatus(`Marked ${dm(e)}.`),this.render()}enforceClipBoundary(e){const t=this.activeReview?.currentClip,i=this.options.getReplayPlayer();if(!t||!i||this.boundaryGuard)return!1;const s=e.currentTime=t.endTime-.025;if(!s&&!a)return!1;this.boundaryGuard=!0;try{i.setState({currentTime:s?t.startTime:t.endTime,playing:!1,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),a&&this.setStatus(`Finished clip at ${t.endTime.toFixed(2)}s`)}finally{this.boundaryGuard=!1}return!0}getBoundTime(e,t,i){const s=this.options.getReplayPlayer();return s?N8(e,t,s.replay,i):t.kind==="time"?t.value:0}getPlayerName(e){const t=H8(e);if(t)return t;const i=this.options.getReplayPlayer()?.replay.players??[];return Zx(e.perspective,i)?.name??"--"}}function dm(n){return typeof n=="string"&&n.trim()?n.replaceAll("_"," "):"unreviewed"}function Qx(n){if(!n)return null;if(typeof n.meta?.reviewEndpoint=="string"&&n.meta.reviewEndpoint)return n.meta.reviewEndpoint;const e=typeof n.meta?.eventId=="string"&&n.meta.eventId?n.meta.eventId:n.id;return e?`/api/v1/events/${encodeURIComponent(e)}/reviews`:null}function q8(){const n=new URLSearchParams(window.location.search),e=n.get("reviewToken")??n.get("token")??window.localStorage.getItem("rocket_sense_access_token");return e?{Authorization:`Bearer ${e}`}:{}}function Y8(n){return new K8(n)}const j8=["replayUrl","replay_url","replay"],Z8=["r","replayUrlZ","replay_url_z"],J8=["ballchasing","ballchasingId","ballchasingUuid","ballchasingReplay"];function Q8(n){const e=n.replaceAll("-","+").replaceAll("_","/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=atob(t),s=new Uint8Array(i.length);for(let a=0;a{n.signal.aborted||(console.error("Failed to load replay URL:",t),n.statusReadout.textContent=t instanceof Error?t.message:"Failed to load replay URL")})}function r6(n){n.initialBundle?n.loadReplayBundleForDisplay({name:n.initialReplayName??"replay",preparingStatus:"Preparing replay...",async readBytes(){throw new Error("Replay bytes are not available for this preloaded replay")}},Promise.resolve(n.initialBundle)).catch(i=>{n.signal.aborted||(console.error("Failed to load preprocessed replay bundle:",i),n.statusReadout.textContent=i instanceof Error?i.message:"Failed to load preprocessed replay bundle")}):n.loadFromLocation!==!1&&a6(n);const e=k8();if(!e)return;const t=n.getMechanicsReviewController();t?.setUrl(e),n.showMechanicsReviewWindow(),t?.loadPlaylistFromUrl(e).catch(i=>{n.signal.aborted||(console.error("Failed to load mechanics review playlist from URL:",i),t?.setStatus(i instanceof Error?i.message:"Failed to load mechanics review playlist from URL"))})}function o6(n){const e=()=>{n.getSkipPostGoalTransitions().checked=!1,n.getSkipKickoffs().checked=!1},t=(i,s)=>{const a=n.getReplayPlayer();!a||!Number.isFinite(i)||(n.getMechanicsReviewController()?.clearCurrentClip(),e(),a.setState({currentTime:Math.max(0,i-n.goalWatchLeadSeconds),playing:s,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),n.scheduleConfigUrlUpdate())};return{watchGoalReplay(i,s){const a=n.getReplayPlayer();if(!a||!Number.isFinite(i))return;if(n.getMechanicsReviewController()?.clearCurrentClip(),s!==null&&a.replay.players.some(o=>o.id===s)){a.setAttachedPlayer(s),a.setCameraViewMode("follow");const o=n.getCameraControlsController();o&&(o.freeCameraPreset=null)}e(),a.setState({currentTime:Math.max(0,i-n.goalWatchLeadSeconds),playing:!0,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),n.scheduleConfigUrlUpdate()},cueGoalReplay(i){t(i,!1)},cueTimelineEvent(i){const s=n.getReplayPlayer();s&&(n.getMechanicsReviewController()?.clearCurrentClip(),e(),s.setState({currentTime:Pg(i),skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),n.scheduleConfigUrlUpdate())},applyConfigToReplayPlayer(i){const s=n.getReplayPlayer();if(!s)return;s.setState(ZW(i.playback,i.camera,i));const a=n.getCameraControlsController();a&&(a.freeCameraPreset=i.camera.freePreset??null),i.camera.mode==="free"&&i.camera.freePreset&&s.setFreeCameraPreset(i.camera.freePreset),n.syncBoostPadOverlayPlugin(),n.setupActiveModules(),n.renderModuleSummary(),n.renderModuleSettings(),n.renderStatsWindows(s.getState().frameIndex)}}}function l6(n){let e=!1,t=null;const i=()=>n.getFloatingWindowController()?.getSingletonConfigs()??[],s=()=>n.getStatsWindowsController()?.getConfigs()??[],a=()=>{const o=n.getActiveModulesRuntime(),l=n.getReplayPlayer();return jW({playback:qW({replayPlayer:l,playbackRate:n.playbackRate,skipPostGoalTransitions:n.skipPostGoalTransitions,skipKickoffs:n.skipKickoffs}),camera:YW({replayPlayer:l,cameraControlsController:n.getCameraControlsController()}),activeTimelineEventSourceIds:o.getActiveTimelineEventSourceIds(),activeTimelineRangeModuleIds:o.getActiveTimelineRangeModuleIds(),activeMechanicTimelineKinds:o.getActiveMechanicTimelineKinds(),activeRenderEffectModuleIds:o.getActiveRenderEffectModuleIds(),initialConfig:n.getInitialConfig(),replayPlayer:l,boostPadOverlayEnabled:o.getBoostPadOverlayEnabled(),recording:n.getRecordingWindowController()?.getConfigSnapshot()??{},singletonWindows:i(),statsWindows:s(),moduleConfigs:KW(n.modules)})},r=o=>{VW(o1(n.modules),o)};return{setApplyingConfig(o){e=o},reset(){t!==null&&(window.clearTimeout(t),t=null),e=!1},scheduleConfigUrlUpdate(){e||(t!==null&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null;const o=vW(new URL(window.location.href),a());window.history.replaceState(window.history.state,"",o)},150))},applyConfigToStaticControls(o){if(n.getActiveModulesRuntime().applyOverlayConfig(o.overlays),n.skipPostGoalTransitions.checked=o.playback.skipPostGoalTransitions??n.skipPostGoalTransitions.checked,n.skipKickoffs.checked=o.playback.skipKickoffs??n.skipKickoffs.checked,n.hitboxWireframes.checked=o.overlays.hitboxWireframes,n.hitboxOnlyMode.checked=o.overlays.hitboxOnlyMode,n.getCameraControlsController()?.applyNameplateLiftUu(o.camera.nameplateLiftUu),n.getCameraControlsController()?.setAutoPossessionEnabled(o.camera.autoPossession??!1,{requestConfigSync:!1}),o.playback.rate!==void 0){const l=cf(o.playback.rate);n.playbackRate.value=`${l}`,n.playbackRateReadout.textContent=qg(l)}n.getRecordingWindowController()?.applyConfig(o.recording),r(o.moduleConfigs),n.getFloatingWindowController()?.applySingletonConfigs(o.singletonWindows),n.getStatsWindowsController()?.replaceFromConfig(o.statsWindows),n.renderModuleSummary(),n.renderModuleSettings(),n.renderTimelineEventCount()}}}function c6(n){const e=t=>{const i=n.getLauncherToggle();n.getLauncherMenu().hidden=!t,i.setAttribute("aria-label",t?"Close menu":"Open menu"),i.setAttribute("aria-expanded",t?"true":"false")};return{bringWindowToFront(t){n.getFloatingWindowController()?.bringToFront(t)},showWindow(t){n.getFloatingWindowController()?.show(t)},toggleWindow(t){n.getFloatingWindowController()?.toggle(t)},hideWindow(t){n.getFloatingWindowController()?.hide(t)},setLauncherOpen:e,openReplayFilePicker(){n.getFileInput().click(),e(!1)},installWindowDragging(t,i){n.getFloatingWindowController()?.installDragging(t,i)},getElementWindowId(t){return t.closest("[data-window-id]")?.dataset.windowId??null}}}const A_=4096,hr=5120,u6=893,d6=642,qi=1/105;class h6{constructor(e){this.options=e,this.options.body.innerHTML=` +
`}).join("")}
`},renderFocusedPlayerStats(e,t,i){return`
Events${ve(i.statsTimeline,"dodge").filter(a=>At(a.player)===e).length}
`}}}function R$(){return{id:"half-flip",label:"Half Flip",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Nx(i.half_flip),i.half_flip?.is_last_half_flip?'Last Half Flip':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Nx(i.half_flip):""}}}function P$(){return{id:"wavedash",label:"Wavedash",setup(){},teardown(){},onBeforeRender(){},getTimelineEvents(n){return T4(n.statsTimeline,n.replay)},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Ux(i.wavedash),i.wavedash?.is_last_wavedash?'Last Wavedash':"")):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Ux(i.wavedash):""}}}function I$(){return ai({id:"whiff",label:"Whiff",select:n=>n.whiff,render:n=>JG(n),getTimelineEvents(n){return R4(n.statsTimeline,n.replay)}})}function L$(n){let e=null,t=null;const i=new Set,s=["speed_band","height_band"];return{id:"movement",label:"Movement",setup(){a()},teardown(){},onBeforeRender(){},getConfig(){return{breakdownClasses:r()}},applyConfig(o){if(i.clear(),o&&typeof o=="object"&&!Array.isArray(o)){const l=o.breakdownClasses;if(Array.isArray(l))for(const c of l)s.includes(c)&&i.add(c)}a(),n.rerenderCurrentState()},renderStats(o,l){const c=zt(l.statsFrameLookup,o);return c?si(c.players,u=>Tn(u.name,u.is_team_0,Mx(u.movement,{breakdownClasses:r()}))):""},renderFocusedPlayerStats(o,l,c){const u=wn(c,l,o);return u?Mx(u.movement,{breakdownClasses:r()}):""},renderSettings(){if(!e){e=document.createElement("div"),e.className="module-settings-card";const o=document.createElement("div");o.className="module-settings-header";const l=document.createElement("div"),c=document.createElement("p");c.className="module-settings-eyebrow",c.textContent="Stat display";const u=document.createElement("h3");u.textContent="Movement breakdown",l.append(c,u),t=document.createElement("strong"),t.className="metric-readout",o.append(l,t);const d=document.createElement("div");d.className="module-settings-options";for(const h of[{className:"speed_band",label:"Speed band"},{className:"height_band",label:"Height band"}]){const f=document.createElement("label");f.className="toggle";const p=document.createElement("input");p.type="checkbox",p.dataset.breakdownClass=h.className,p.addEventListener("change",()=>{p.checked?i.add(h.className):i.delete(h.className),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const g=document.createElement("span");g.textContent=h.label,f.append(p,g),d.append(f)}e.append(o,d)}return a(),e}};function a(){if(e){for(const o of e.querySelectorAll("input[data-breakdown-class]")){const l=o.dataset.breakdownClass;o.checked=l?i.has(l):!1}if(t){const o=r();t.textContent=o.length>0?o.map(l=>({speed_band:"Speed band",height_band:"Height band"})[l]).join(" + "):"Total only"}}}function r(){return s.filter(o=>i.has(o))}}function k$(){return ai({id:"powerslide",label:"Powerslide",select:n=>n.powerslide,render:n=>ZG(n),getTimelineEvents(n){return b4(n.statsTimeline,n.replay)}})}function D$(){return ai({id:"rotation",label:"Rotation",select:n=>n.rotation,render:n=>GG(n)})}function O$(){return ai({id:"demo",label:"Demo",select:n=>n.demo,render:n=>QG(n)})}function F$(){return ai({id:"bump",label:"Bump",select:n=>n.bump,render:n=>e$(n),getTimelineEvents(n){return M4(n.statsTimeline,n.replay)}})}function N$(){let n=null,e=1;return{id:WE,label:"Relative Positioning",setup(t){e=t.fieldScale,n=new o5(t.player.sceneState.replayRoot,t.replay,e)},teardown(){n?.dispose(),n=null},onBeforeRender(t){n?.update(t,e)},renderStats(t,i){const s=zt(i.statsFrameLookup,t);return s?si(s.players,a=>{const r=Q4(i.replay,At(a.player_id),t),o=J4[r];return Tn(a.name,a.is_team_0,Px(a.positioning),`${o}`)}):""},renderFocusedPlayerStats(t,i,s){const a=wn(s,i,t);return a?Px(a.positioning):""}}}function U$(){return{id:"absolute-positioning",label:"Absolute Positioning",setup(n){Ax.acquire(n)},teardown(){Ax.release()},onBeforeRender(){},getTimelineRanges(n){return Z4(n.statsTimeline,n.replay)},renderStats(n,e){const t=zt(e.statsFrameLookup,n);return t?si(t.players,i=>Tn(i.name,i.is_team_0,Ix(i.positioning))):""},renderFocusedPlayerStats(n,e,t){const i=wn(t,e,n);return i?Ix(i.positioning):""}}}function B$(n,e={}){return[p$(),m$(),_$(),g$(),y$(),S$(),M$(),T$(),eG(n),tG(),nG(),iG(),sG(),N$(),U$(),D$(),A$(),C$(),R$(),P$(),h$(n),I$(),E$(),x$(),w$(),b$(),f$(n,e.boostPickupFilters),v$(),L$(n),k$(),O$(),F$()]}const z$=new Set(["player_id","name","is_team_0"]),H$=["is_last_","time_since_last_","frames_since_last_"];function V$(n){return n===null||typeof n=="number"||typeof n=="string"||typeof n=="boolean"||Array.isArray(n)}function G$(n,e){let t=n;for(const i of e){if(!t||typeof t!="object"||Array.isArray(t))return;t=t[i]}return t}function $$(n){return n==null?"--":typeof n=="number"?Number.isFinite(n)?Number.isInteger(n)?`${n}`:`${Number(n.toFixed(3))}`:"--":typeof n=="boolean"?n?"true":"false":Array.isArray(n)?n.length===0?"[]":JSON.stringify(n):`${n}`}function W$(n,e){if(H$.some(a=>n.startsWith(a)))return!0;const t=n.match(/^last_(.+)_time$/),i=n.match(/^last_(.+)_frame$/),s=t?.[1]??i?.[1];return s?`is_last_${s}`in e||`time_since_last_${s}`in e||`frames_since_last_${s}`in e:!1}function M_(n,e,t,i){if(!n||typeof n!="object"||Array.isArray(n))return;const s=n;for(const[a,r]of Object.entries(s)){if(e==="player"&&t.length===0&&z$.has(a)||W$(a,s))continue;const o=[...t,a];if(V$(r)){const l=`${e}:${o.join(".")}`;i.push({id:l,label:o.join("."),category:o[0]??e,scope:e,path:o,read(c){return G$(c,o)},format:$$});continue}M_(r,e,o,i)}}function X$(n){const e=new Set;return n.filter(t=>e.has(t.id)?!1:(e.add(t.id),!0))}function K$(n,e){const t=[];return n&&M_(n,"player",[],t),e&&M_(e,"team",[],t),X$(t).sort((i,s)=>i.label.localeCompare(s.label))}function q$(){return K$(uE(),Ql())}function nc(n){return q$()}function QE(n){return n.toLowerCase().replace(/[_/.-]+/g," ").replace(/\s+/g," ").trim()}function Y$(n){return QE(n).split(" ").filter(Boolean)}function j$(n,e){const t=Y$(e);if(t.length===0)return 0;const i=QE([n.scope,n.category,n.label,n.id,...n.path].join(" "));let s=0;for(const a of t){const r=i.indexOf(a);if(r<0)return null;s+=r}return s+i.length/1e3}function Z$(n,e){return n.map((t,i)=>({definition:t,index:i,score:j$(t,e)})).filter(t=>t.score!==null).sort((t,i)=>t.score-i.score||t.index-i.index).map(t=>t.definition)}function wi(n){if(!Number.isFinite(n))return"--";const e=Math.floor(Math.max(0,n)/60),t=Math.max(0,n)-e*60;return`${e}:${t.toFixed(1).padStart(4,"0")}`}class J${constructor(e){this.options=e}statsWindows=new Map;nextStatsWindowId=1;getConfigs(){return[...this.statsWindows.values()].map(e=>({id:e.id,kind:e.kind,placement:this.options.readWindowPlacement(e.element),playerId:e.playerId,team:e.team,entries:e.entries.map(t=>({statId:t.statId,targetId:t.targetId}))}))}clear(){for(const e of this.statsWindows.values())e.element.remove();this.statsWindows.clear(),this.nextStatsWindowId=1}replaceFromConfig(e){this.clear();for(const t of e)this.create(t.kind,t)}render(e=this.options.getReplayPlayer()?.getState().frameIndex??0,t={}){for(const i of this.statsWindows.values())t.preserveOpenPickers&&(i.pickerOpen||i.element.contains(document.activeElement))||this.renderStatsWindow(i,e)}create(e,t){const i=t?.id??`stats-${this.nextStatsWindowId++}`,s=Number.parseInt(i.replace(/^stats-/,""),10);Number.isFinite(s)&&(this.nextStatsWindowId=Math.max(this.nextStatsWindowId,s+1));const{x:a,y:r}=this.getStatsWindowDefaultPosition(),o=document.createElement("section");o.className="stats-window",o.dataset.windowId=i,o.style.setProperty("--window-x",`${a}px`),o.style.setProperty("--window-y",`${r}px`),t&&this.options.applyWindowPlacement(o,t.placement);const l=document.createElement("header");l.className="stats-window-header";const c=document.createElement("div");c.className="stats-window-actions";const u=document.createElement("button");if(u.type="button",u.className="stats-window-action",u.textContent="Hide",c.append(u),this.hasStatsWindowScopeSelector(e))l.classList.add("stats-window-header-actions-only"),l.append(c);else{const f=document.createElement("h2");f.textContent=this.getStatsWindowTitle(e),l.append(f,c)}const d=document.createElement("div");d.className="stats-window-body",o.append(l,d),this.options.layer.append(o);const h={id:i,kind:e,entries:t?.entries.map(f=>({key:`${i}:${f.statId}:${f.targetId??"scope"}`,statId:f.statId,targetId:f.targetId}))??[],playerId:t?.playerId??this.options.getReplayPlayer()?.replay.players[0]?.id??null,team:t?.team??"blue",pickerOpen:!1,query:"",element:o,body:d};return u.addEventListener("click",()=>{o.hidden=!0,this.options.requestConfigSync()}),this.statsWindows.set(i,h),t||this.options.bringWindowToFront(o),this.options.setLauncherOpen(!1),this.renderStatsWindow(h),this.options.requestConfigSync(),h}getStatById(e){return this.options.getStatRegistry().find(t=>t.id===e)??null}getCurrentStatsFrame(e){const t=this.options.getStatsFrameLookup();return t?zt(t,e):null}getTeamSnapshot(e,t){return t==="blue"?e.team_zero??null:e.team_one??null}getTeamLabel(e){return e==="blue"?"Blue":"Orange"}getPlayerTeamClass(e){const t=this.options.getReplayPlayer()?.replay.players.find(i=>i.id===e);return t?na(t.isTeamZero):null}getTeamScopeClass(e){return na(e==="blue")}appendGroupedPlayerOptions(e,t){const i=this.options.getReplayPlayer()?.replay.players??[];for(const s of["blue","orange"]){const a=i.filter(o=>o.isTeamZero===(s==="blue"));if(a.length===0)continue;const r=document.createElement("optgroup");r.label=`${this.getTeamLabel(s)} team`;for(const o of a)r.append(new Option(o.name,o.id,o.id===t,o.id===t));e.append(r)}}getStatsWindowScopeTeamClass(e){return e.kind==="player"?this.getPlayerTeamClass(e.playerId):e.kind==="team"?this.getTeamScopeClass(e.team??"blue"):null}getStatTargetTeamClass(e,t){return e.scope==="player"?this.getPlayerTeamClass(t):this.getTeamScopeClass(t==="orange"?"orange":"blue")}getStatsWindowTitle(e){switch(e){case"player":return"Player stats";case"team":return"Team stats";case"all-players":return"All players stats";case"all-teams":return"All teams stats";case"kickoff-overview":return"Kickoff details";case"goals-overview":return"Goal labels";case"ad-hoc":return"Ad hoc stats"}}hasStatsWindowScopeSelector(e){return e==="player"||e==="team"}hasStatsWindowStatPicker(e){return e!=="goals-overview"&&e!=="kickoff-overview"}getStatsWindowAllowedScope(e){switch(e){case"player":case"all-players":return"player";case"team":case"all-teams":return"team";case"kickoff-overview":return null;case"goals-overview":return null;case"ad-hoc":return null}}getStatsWindowDefaultPosition(){const e=this.statsWindows.size*18;return{x:Math.max(12,Math.min(window.innerWidth-360,96+e)),y:Math.max(64,Math.min(window.innerHeight-240,96+e))}}renderStatsWindow(e,t=this.options.getReplayPlayer()?.getState().frameIndex??0){const i=document.activeElement,s=i instanceof HTMLInputElement&&i.dataset.statsWindowSearch===e.id,a=s?i.selectionStart:null,r=s?i.selectionEnd:null,o=s?i.selectionDirection:null;if(e.body.replaceChildren(),this.renderStatsWindowScope(e),this.hasStatsWindowStatPicker(e.kind)&&(this.renderStatsWindowAddControl(e),this.renderStatsWindowPicker(e)),this.renderStatsWindowEntries(e,t),s){const l=e.body.querySelector(`input[data-stats-window-search="${e.id}"]`);l?.focus({preventScroll:!0}),l&&a!==null&&r!==null&&l.setSelectionRange(a,r,o??"none")}}renderStatsWindowScope(e){if(e.kind!=="player"&&e.kind!=="team")return;const t=document.createElement("div");t.className="stats-window-scope-row";const i=document.createElement("select");i.className="stats-window-scope-select";const s=this.getStatsWindowScopeTeamClass(e);s&&i.classList.add(s),i.setAttribute("aria-label",e.kind==="player"?"Player stats target":"Team stats target"),e.kind==="player"?(this.appendGroupedPlayerOptions(i,e.playerId),i.value=e.playerId??"",i.addEventListener("change",()=>{e.playerId=i.value||null,this.renderStatsWindow(e),this.options.requestConfigSync()})):(i.append(new Option("Blue","blue",e.team==="blue",e.team==="blue"),new Option("Orange","orange",e.team==="orange",e.team==="orange")),i.value=e.team??"blue",i.addEventListener("change",()=>{e.team=i.value==="orange"?"orange":"blue",this.renderStatsWindow(e),this.options.requestConfigSync()})),t.append(i),e.body.append(t)}renderStatsWindowAddControl(e){const t=document.createElement("button");if(t.type="button",t.className="stats-window-add-button",t.textContent="+",t.title="Add stat",t.setAttribute("aria-label","Add stat"),t.setAttribute("aria-expanded",String(e.pickerOpen)),this.activateButton(t,()=>{e.pickerOpen=!e.pickerOpen,this.renderStatsWindow(e)}),this.hasStatsWindowScopeSelector(e.kind)){e.body.querySelector(".stats-window-scope-row")?.append(t);return}const i=document.createElement("div");i.className="stats-window-toolbar",i.append(t),e.body.append(i)}activateButton(e,t){let i=!1;e.addEventListener("pointerdown",s=>{e.disabled||(i=!0,s.preventDefault(),t())}),e.addEventListener("click",()=>{if(i){i=!1;return}e.disabled||t()})}renderStatsWindowPicker(e){const t=document.createElement("div");if(t.className="stats-window-picker",t.hidden=!e.pickerOpen,t.hidden){e.body.append(t);return}const i=this.getStatsWindowAllowedScope(e.kind),s=document.createElement("input");s.type="search",s.placeholder="Search stats",s.value=e.query,s.dataset.statsWindowSearch=e.id;const a=document.createElement("div");a.className="stats-window-picker-list",s.addEventListener("input",()=>{e.query=s.value,this.renderStatsWindowPickerList(e,a,i)}),this.renderStatsWindowPickerList(e,a,i),t.append(s,a),e.body.append(t)}renderStatsWindowPickerList(e,t,i){t.replaceChildren();const s=this.options.getStatRegistry(),a=i?s.filter(l=>l.scope===i):s,r=Z$(a,e.query),o=new Map;for(const l of r){const c=o.get(l.category)??[];c.push(l),o.set(l.category,c)}for(const[l,c]of o){if(c.length<2)continue;const u=document.createElement("button");u.type="button",u.className="stats-window-picker-item",u.innerHTML=`Add all ${l}${c.length}`,this.activateButton(u,()=>{for(const d of c)this.addStatToWindow(e,d);this.renderStatsWindow(e),this.options.requestConfigSync()}),t.append(u)}for(const l of r){const c=document.createElement("button");c.type="button",c.className="stats-window-picker-item",c.innerHTML=`${l.label}${l.scope}`,c.disabled=e.kind!=="ad-hoc"&&e.entries.some(u=>u.statId===l.id),this.activateButton(c,()=>{this.addStatToWindow(e,l),this.renderStatsWindow(e),this.options.requestConfigSync()}),t.append(c)}if(r.length===0){const l=document.createElement("p");l.className="stat-window-empty",l.textContent=s.length===0?"No stats available.":"No matching stats.",t.append(l)}}addStatToWindow(e,t){const i=e.kind==="ad-hoc"?this.getDefaultAdHocTargetId(t):void 0;e.entries.some(s=>s.statId===t.id&&s.targetId===i)||e.entries.push({key:`${e.id}:${t.id}:${i??"scope"}`,statId:t.id,targetId:i})}getDefaultAdHocTargetId(e){return e.scope==="player"?this.options.getReplayPlayer()?.replay.players[0]?.id??"":"blue"}removeStatFromWindow(e,t){const i=e.entries.findIndex(s=>s.key===t);i>=0&&e.entries.splice(i,1)}renderStatsWindowEntries(e,t){if(e.kind==="goals-overview"){this.renderGoalLabelsOverview(e);return}if(e.kind==="kickoff-overview"){this.renderKickoffOverview(e,t);return}const i=this.getStatsWindowAllowedScope(e.kind),s=e.entries.map(r=>({entry:r,definition:this.getStatById(r.statId)})).filter(r=>r.definition!==null&&(!i||r.definition.scope===i));if(s.length===0){const r=document.createElement("p");r.className="stat-window-empty",r.textContent="No stats added.",e.body.append(r);return}const a=this.getCurrentStatsFrame(t);if(!a){const r=document.createElement("p");r.className="stat-window-empty",r.textContent="Load a replay to show stats.",e.body.append(r);return}if(e.kind==="all-players"){this.renderAllPlayersStats(e,a,s);return}if(e.kind==="all-teams"){this.renderAllTeamsStats(e,a,s);return}if(e.kind==="player"){const r=e.playerId?a.players.find(o=>At(o.player_id)===e.playerId)??null:null;this.renderScopedStatList(e,r,s);return}if(e.kind==="team"){this.renderScopedStatList(e,this.getTeamSnapshot(a,e.team??"blue"),s);return}e.kind==="ad-hoc"&&this.renderAdHocStats(e,a,s)}renderGoalLabelsOverview(e){const t=this.options.getStatsTimeline(),i=this.options.getReplayPlayer()?.replay??null;if(!t||!i){this.appendStatsWindowEmpty(e,"Load a replay to show goal labels.");return}const s=[...ve(t,"goal_context")].sort((o,l)=>o.time-l.time),a=s.map((o,l)=>l);if(a.length===0){this.appendStatsWindowEmpty(e,"No goals loaded.");return}const r=document.createElement("div");r.className="goal-label-list";for(const o of a){const l=s[o]??null,c=[...l?.tags??[]].sort((M,C)=>M.kind.localeCompare(C.kind)||C.metadata.confidence-M.metadata.confidence),u=l?.time??0,d=l?.scorer??null,h=d?At(d):null,f=d?i.players.find(M=>M.id===h)?.name??h:"Unknown scorer",p=l?.scoring_team_is_team_0??null,g=document.createElement("section");g.className="goal-label-item",p!==null&&g.classList.add(na(p));const _=document.createElement("header"),m=document.createElement("h3");m.textContent=`Goal ${o+1}`;const v=document.createElement("span");v.textContent=`${wi(u)} · ${f}`,_.append(m,v);const y=document.createElement("div");if(y.className="goal-label-tags",c.length===0){const M=document.createElement("span");M.className="goal-label-tag goal-label-tag-empty",M.textContent="Unlabeled",y.append(M)}else for(const M of c){const C=document.createElement("span");C.className="goal-label-tag";const w=n4(M);C.textContent=`${Ai(M.kind)} ${Math.round(M.metadata.confidence*100)}%${w?` - ${w}`:""}`,y.append(C)}const b=document.createElement("div");b.className="goal-label-actions";const T=document.createElement("button");T.type="button",T.className="goal-label-watch",T.textContent="Watch",T.addEventListener("click",()=>{this.options.watchGoalReplay(u,h)});const x=document.createElement("button");x.type="button",x.textContent="Cue",x.addEventListener("click",()=>{this.options.cueGoalReplay(u)}),b.append(T,x),g.append(_,y,b),r.append(g)}e.body.append(r)}renderKickoffOverview(e,t){const i=this.options.getStatsTimeline(),s=this.options.getReplayPlayer()?.replay??null;if(!i||!s){this.appendStatsWindowEmpty(e,"Load a replay to show kickoff details.");return}const a=this.getClosestKickoffEvent(i,t);if(!a){this.appendStatsWindowEmpty(e,"No kickoff events loaded.");return}const r=a.payload.payload,o=document.createElement("section");o.className="kickoff-overview";const l=document.createElement("header");l.className="kickoff-overview-hero";const c=document.createElement("div"),u=document.createElement("h3");u.textContent=this.formatKickoffTitle(a);const d=document.createElement("span");d.textContent=`Nearest kickoff · resolved at ${wi(r.end_time)}`,c.append(u,d);const h=document.createElement("strong"),f=this.teamClassFromNullable(r.winning_team_is_team_0);h.className="kickoff-overview-victor",f&&h.classList.add(f),h.textContent=this.formatOutcome(r),l.append(c,h);const p=document.createElement("div");p.className="kickoff-overview-summary",p.append(this.renderKickoffMetric("Win strength",`${this.formatNullableNumber(r.win_strength,2)} · ${this.formatKickoffLabelValue("kickoff_win_strength",r.win_strength_band)}`),this.renderKickoffMetric("First touch",this.formatFirstTouch(r)),this.renderKickoffMetric("Advantage",this.formatAdvantage(r)),this.renderKickoffMetric("Contested",this.formatContested(r)));const g=document.createElement("div");g.className="kickoff-detail-grid",g.append(this.renderKickoffDetail("Kickoff start",wi(r.start_time)),this.renderKickoffDetail("Movement start",wi(r.movement_start_time)),this.renderKickoffDetail("Live action",r.live_action_start_time===null?"--":wi(r.live_action_start_time)),this.renderKickoffDetail("First touch",r.first_touch_time===null?"--":wi(r.first_touch_time)),this.renderKickoffDetail("Resolution",wi(r.end_time)),this.renderKickoffDetail("After first touch",this.formatSeconds(r.advantage_seconds_after_first_touch)));const _=document.createElement("div");_.className="kickoff-strategy-list",_.append(this.renderKickoffTeamStrategy("Blue",r.team_zero_taker,r.team_zero_non_takers),this.renderKickoffTeamStrategy("Orange",r.team_one_taker,r.team_one_non_takers)),o.append(l,p,g,_),e.body.append(o)}getClosestKickoffEvent(e,t){return ec(e).filter(s=>s.payload.kind==="kickoff").sort((s,a)=>{const r=this.kickoffFrameDistance(s.payload.payload,t),o=this.kickoffFrameDistance(a.payload.payload,t);return r!==o?r-o:s.payload.payload.start_frame-a.payload.payload.start_frame})[0]??null}kickoffFrameDistance(e,t){return t>=e.start_frame&&t<=e.end_frame?0:Math.min(Math.abs(t-e.start_frame),Math.abs(t-e.end_frame))}renderKickoffMetric(e,t){const i=document.createElement("div");i.className="kickoff-metric";const s=document.createElement("span");s.textContent=e;const a=document.createElement("strong");return a.textContent=t,i.append(s,a),i}renderKickoffDetail(e,t){const i=document.createElement("div");i.className="kickoff-detail-row";const s=document.createElement("span");s.textContent=e;const a=document.createElement("strong");return a.textContent=t,i.append(s,a),i}renderKickoffTeamStrategy(e,t,i){const s=document.createElement("section");s.className=`kickoff-strategy-team ${e==="Blue"?"team-blue":"team-orange"}`;const a=document.createElement("h4");a.textContent=e,s.append(a);const r=document.createElement("p");if(r.className="kickoff-strategy-line",r.textContent=t?`${this.getPlayerName(t.player)}: ${this.formatKickoffLabelValue("kickoff_approach",t.approach)} from ${this.formatKickoffLabelValue("kickoff_spawn",t.spawn_position)} (${this.formatKickoffLabelValue("taker_outcome",t.outcome)}, ${this.formatSeconds(t.time_to_ball)})`:"No taker detected",s.append(r),i.length>0){const o=document.createElement("ul");o.className="kickoff-support-list";for(const l of i){const c=document.createElement("li");c.textContent=`${this.getPlayerName(l.player)}: ${this.formatKickoffLabelValue("support_behavior",l.support_behavior)} from ${this.formatKickoffLabelValue("kickoff_spawn",l.spawn_position)}`,o.append(c)}s.append(o)}return s}formatOutcome(e){return e.winning_team_is_team_0===!0?"Blue wins":e.winning_team_is_team_0===!1?"Orange wins":e.outcome==="neutral"?"Neutral":"Unknown"}formatFirstTouch(e){if(!e.first_touch_player)return"--";const t=e.first_touch_team_is_team_0===!0?"Blue":e.first_touch_team_is_team_0===!1?"Orange":"Unknown",i=e.first_touch_time===null?"--":wi(e.first_touch_time);return`${t} · ${this.getPlayerName(e.first_touch_player)} · ${i}`}formatAdvantage(e){if(e.advantage==="no_advantage")return"No advantage";const t=e.advantage_team_is_team_0===!0?"Blue":e.advantage_team_is_team_0===!1?"Orange":"Unknown",i=e.advantage.replace(/^team_(zero|one)_/,""),s=e.advantage_player?` · ${this.getPlayerName(e.advantage_player)}`:"",a=e.advantage_time===null?"":` · ${wi(e.advantage_time)}`;return`${t} ${this.formatKickoffLabelValue("kickoff_advantage",i)}${s}${a}`}formatContested(e){return e.kickoff_possession_outcome==="contested"?"Yes":e.kickoff_possession_team_is_team_0===!0?`No · Blue ${this.formatPossessionOutcome(e.kickoff_possession_outcome)}`:e.kickoff_possession_team_is_team_0===!1?`No · Orange ${this.formatPossessionOutcome(e.kickoff_possession_outcome)}`:`No · ${this.formatPossessionOutcome(e.kickoff_possession_outcome)}`}formatPossessionOutcome(e){return e.endsWith("_advantage")?"advantage":e.endsWith("_possession")?"possession":this.formatKickoffLabelValue("kickoff_possession_outcome",e)}formatKickoffType(e){return this.formatKickoffLabelValue("kickoff_type",e)}formatKickoffTitle(e){const t=e.payload.payload,i=this.formatKickoffDirection(t.kickoff_direction),s=[this.formatKickoffType(t.kickoff_type),i].filter(Boolean).join(" ");return[e.meta.label,s].filter(Boolean).join(" · ")}formatKickoffDirection(e){return e==="unknown"?"":`(${this.formatKickoffLabelValue("kickoff_direction",e)})`}formatNullableNumber(e,t){return e===null||!Number.isFinite(e)?"--":e.toFixed(t)}formatSeconds(e){return e===null||!Number.isFinite(e)?"--":`${e.toFixed(2)}s`}formatLabel(e){return e.replace(/^team_zero_/,"blue_").replace(/^team_one_/,"orange_").replaceAll("_"," ").replace(/\b\w/g,t=>t.toUpperCase())}formatKickoffLabelValue(e,t){const i=t.replace(/^team_zero_/,"blue_").replace(/^team_one_/,"orange_");return e==="kickoff_advantage"?this.formatLabel(i.replace(/^blue_/,"").replace(/^orange_/,"")):e==="kickoff_possession_outcome"?this.formatLabel(i.replace(/^blue_/,"Blue ").replace(/^orange_/,"Orange ")):this.formatLabel(i)}teamClassFromNullable(e){return e===null?null:na(e)}getPlayerName(e){const t=At(e);return this.options.getReplayPlayer()?.replay.players.find(i=>i.id===t)?.name??t}appendStatsWindowEmpty(e,t){const i=document.createElement("p");i.className="stat-window-empty",i.textContent=t,e.body.append(i)}renderScopedStatList(e,t,i){const s=document.createElement("div");s.className="stats-window-stat-list";for(const{entry:a,definition:r}of i)s.append(this.renderStatRow(e,a,r,t?r.format(r.read(t)):"--"));e.body.append(s)}renderAllPlayersStats(e,t,i){const s=document.createElement("div");s.className="stats-window-team-list";for(const a of["blue","orange"]){const r=t.players.filter(h=>h.is_team_0===(a==="blue"));if(r.length===0)continue;const o=document.createElement("section");o.className=`stats-window-team-group ${this.getTeamScopeClass(a)}`;const l=document.createElement("header");l.className="stats-window-team-header";const c=document.createElement("h3");c.textContent=`${this.getTeamLabel(a)} team`;const u=document.createElement("span");u.textContent=`${r.length} player${r.length===1?"":"s"}`,l.append(c,u),o.append(l);const d=document.createElement("div");d.className="stats-window-entity-list";for(const h of r){const f=document.createElement("section");f.className=`stats-window-entity ${na(h.is_team_0)}`;const p=document.createElement("h4");p.className="stats-window-entity-title",p.textContent=h.name,f.append(p);for(const{entry:g,definition:_}of i)f.append(this.renderStatRow(e,g,_,_.format(_.read(h))));d.append(f)}o.append(d),s.append(o)}e.body.append(s)}renderAllTeamsStats(e,t,i){const s=document.createElement("div");s.className="stats-window-entity-list";for(const a of["blue","orange"]){const r=this.getTeamSnapshot(t,a),o=document.createElement("section");o.className=`stats-window-entity ${this.getTeamScopeClass(a)}`;const l=document.createElement("h3");l.className="stats-window-entity-title",l.textContent=this.getTeamLabel(a),o.append(l);for(const{entry:c,definition:u}of i)o.append(this.renderStatRow(e,c,u,r?u.format(u.read(r)):"--"));s.append(o)}e.body.append(s)}renderAdHocStats(e,t,i){const s=document.createElement("div");s.className="stats-window-stat-list";for(const{entry:a,definition:r}of i){const o=this.getAdHocTarget(t,r,a.targetId);s.append(this.renderStatRow(e,a,r,o?r.format(r.read(o)):"--"))}e.body.append(s)}getAdHocTarget(e,t,i){return t.scope==="player"?e.players.find(s=>At(s.player_id)===i)??e.players[0]??null:this.getTeamSnapshot(e,i==="orange"?"orange":"blue")}renderStatRow(e,t,i,s){const a=document.createElement("div");a.className="stats-window-stat-row";const r=document.createElement("span");if(r.className="stats-window-stat-name",r.textContent=i.label,e.kind==="ad-hoc"){const c=document.createElement("select");c.className="stats-window-stat-target";const u=this.getStatTargetTeamClass(i,t.targetId);u&&c.classList.add(u),i.scope==="player"?this.appendGroupedPlayerOptions(c,t.targetId):c.append(new Option("Blue","blue",t.targetId==="blue",t.targetId==="blue"),new Option("Orange","orange",t.targetId==="orange",t.targetId==="orange")),c.value=t.targetId??"",c.addEventListener("change",()=>{const d=c.value;if(e.entries.some(f=>f!==t&&f.statId===t.statId&&f.targetId===d)){this.renderStatsWindow(e);return}const h=e.entries.findIndex(f=>f.key===t.key);h>=0&&(e.entries[h]={key:`${e.id}:${t.statId}:${d}`,statId:t.statId,targetId:d}),this.renderStatsWindow(e),this.options.requestConfigSync()}),r.append(" ",c)}const o=document.createElement("span");o.className="stats-window-stat-value",o.textContent=s;const l=document.createElement("button");return l.type="button",l.className="stats-window-stat-remove",l.textContent="x",l.addEventListener("click",()=>{this.removeStatFromWindow(e,t.key),this.renderStatsWindow(e),this.options.requestConfigSync()}),a.append(r,o,l),a}}function Q$(n){return new J$(n)}const eW=new Set(["module:dodge","module:touch","module:powerslide"]),tW=["stats-stream:"],ch=["#3b82f6","#06b6d4","#22c55e","#a855f7","#f97316","#ef4444","#f59e0b","#ec4899"],df="#d1d9e0",jg=ch[0],Zg=ch[4],nW=[{id:"core",label:"Shots, saves, assists",buildEvents(n){return n.replay.timelineEvents.filter(e=>e.kind==="shot"||e.kind==="save"||e.kind==="assist")}},{id:"demo",label:"Demos",buildEvents(n){return n.replay.timelineEvents.filter(e=>e.kind==="demo")}}],iW=[];function e1(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function t1(n){if(typeof n=="string"&&n.length>0)return n;if(!e1(n))return null;const[e,t]=Object.entries(n)[0]??[];return!e||t==null?null:typeof t=="string"||typeof t=="number"?`${e}:${t}`:`${e}:${JSON.stringify(t)}`}function n1(n){return n.split(/[_-]+/).filter(e=>e.length>0).map(e=>e.slice(0,1).toUpperCase()).join("").slice(0,3)||"E"}function sW(n){if(typeof n!="number"||!Number.isFinite(n))return null;const e=Math.abs(n)<1?2:1;return`${n.toFixed(e).replace(/\.0+$/,"").replace(/(\.\d*[1-9])0+$/,"$1")}s`}function Wi(n){return typeof n!="string"||n.length===0?null:n.split(/[_-]+/).filter(e=>e.length>0).map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1)}`).join(" ")}function aW(n){return n==="team_zero_side"?"Blue side":n==="team_one_side"?"Orange side":n==="neutral"?"Neutral zone":Wi(n)}function rW(n){const e=Wi(n);return e?`${e.toLowerCase()} third`:null}function oW(n){return n==="team_zero_third"?"Blue third":n==="team_one_third"?"Orange third":n==="neutral_third"?"Neutral third":Wi(n)}function lW(n){return n==="team_zero"?"Blue":n==="team_one"?"Orange":n==="neutral"?"Neutral":Wi(n)}function ud(n){return e1(n.payload.payload)?n.payload.payload:{}}function i1(n){return n===!0?jg:n===!1?Zg:null}function cW(n){return n==="team_zero_side"?jg:n==="team_one_side"?Zg:n==="neutral"?df:null}function uW(n){return n==="team_zero"?jg:n==="team_one"?Zg:n==="neutral"?df:null}function dW(n){return typeof n=="boolean"?i1(n):null}const hW={ball_half(n){return cW(ud(n).field_half)},possession(n){return uW(ud(n).possession_state)},player_possession(n){return dW(ud(n).is_team_0)}};function s1(n,e,t){return hW[n]?.(e)??i1(t)??df}function ui(n){return n.filter(e=>!!e).join(" | ")}function fW({event:n,playerName:e,streamLabel:t,teamLabel:i}){const s=ud(n),a=sW(s.duration);if(n.payload.kind==="ball_half"){const r=aW(s.field_half),o=s.active===!1?"Ball half inactive":r?`Ball on ${r.toLowerCase()}`:null;return ui([o??t,a])}if(n.payload.kind==="ball_third"){const r=oW(s.field_third),o=s.active===!1?"Ball third inactive":r?`Ball in ${r.toLowerCase()}`:null;return ui([o??t,a])}if(n.payload.kind==="territorial_pressure"){const r=Wi(s.end_reason),o=`${i??""} territorial pressure`.trim();return ui([r?`${o} ended: ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="possession"){const r=lW(s.possession_state),o=rW(s.field_third),l=r?`${r} possession`:t;return ui([l,o,a])}if(n.payload.kind==="controlled_play"){const r=e?`${e} controlled play`:t;return ui([r,a])}if(n.payload.kind==="ball_carry"){const r=e?`${e} ${t.toLowerCase()}`:t;return ui([r,a])}if(n.payload.kind==="player_activity"){const r=Wi(s.state),o=e?`${e} positioning`:t;return ui([r?`${o} ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="field_third"){const r=Wi(s.state),o=e?`${e} positioning`:t;return ui([r?`${o} in ${r.toLowerCase()} third`:o,a])}if(n.payload.kind==="field_half"){const r=Wi(s.state),o=e?`${e} positioning`:t;return ui([r?`${o} in ${r.toLowerCase()} half`:o,a])}if(n.payload.kind==="ball_depth"){const r=Wi(s.state),o=e?`${e} ball depth`:t;return ui([r?`${o}: ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="depth_role"){const r=Wi(s.state),o=e?`${e} depth role`:t;return ui([r?`${o}: ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="shadow_defense"){const r=e?`${e} shadow defense`:t;return ui([r,a])}if(n.payload.kind==="rotation_role"){const r=Wi(s.state),o=e?`${e} rotation`:t;return ui([r?`${o}: ${r.toLowerCase()}`:o,a])}return e?`${e} ${t.toLowerCase()}`:t}function pW(n,e,t){const i=Ai(e),s=new Map(n.replay.players.map(a=>[a.id,a.name]));return t.flatMap((a,r)=>{const o=a.meta.timing.type==="moment"?{time:a.meta.timing.time,frame:a.meta.timing.frame}:{time:a.meta.timing.end_time,frame:a.meta.timing.end_frame},l=t1(a.meta.primary_player),c=l?s.get(l)??l:null,u=a.meta.team_is_team_0??null,d=u==null?null:u?"Blue":"Orange",h=a.meta.id||`${e}:${o.frame??o.time}:${r}`,f=s1(e,a,u);return[{id:`stats-stream:${h}`,time:n.replay.frames[o.frame??-1]?.time??o.time,frame:o.frame,kind:e,label:fW({event:a,playerName:c,streamLabel:i,teamLabel:d}),shortLabel:n1(e),playerId:l,playerName:c,isTeamZero:u,color:f}]})}function mW(n,e,t){const i=Ai(e),s=new Map(n.replay.players.map(a=>[a.id,a.name]));return t.flatMap((a,r)=>{if(a.meta.timing.type!=="span")return[];const o={startTime:a.meta.timing.start_time,endTime:a.meta.timing.end_time,startFrame:a.meta.timing.start_frame,endFrame:a.meta.timing.end_frame},l=a.meta.team_is_team_0??null,c=l==null?null:l?"Blue":"Orange",u=t1(a.meta.primary_player),d=u?s.get(u)??u:null,h=s1(e,a,l),f=a.meta.id||`${e}:${o.startFrame??o.startTime}:${o.endFrame??o.endTime}:${r}`,p=d?`${d} ${i.toLowerCase()}`:c?`${c} ${i.toLowerCase()}`:i;let g=`stats-stream:${e}`,_=i;return a.meta.scope==="player"&&u?(g=`stats-stream:${e}:player:${u}`,_=d?`${d} ${i.toLowerCase()}`:i):a.meta.scope==="team"&&l!=null&&(g=`stats-stream:${e}:team:${l?"0":"1"}`,_=c?`${c} ${i.toLowerCase()}`:i),[{id:`stats-stream:${f}`,startTime:n.replay.frames[o.startFrame??-1]?.time??o.startTime,endTime:Math.max(n.replay.frames[o.startFrame??-1]?.time??o.startTime,n.replay.frames[o.endFrame??-1]?.time??o.endTime),lane:g,laneLabel:_,label:p,shortLabel:n1(e),isTeamZero:l,color:h}]}).sort((a,r)=>a.startTime!==r.startTime?a.startTime-r.startTime:(a.id??"").localeCompare(r.id??""))}function _W(n,e,t,i){return[...new Set([...XT,...ec(n.statsTimeline).map(a=>a.meta.stream)])].flatMap(a=>{const r=ec(n.statsTimeline).filter(u=>u.meta.stream===a);if(i.has(a)&&r.length>0)return[];const o=r.some(u=>u.meta.timing.type==="span"),l=o?mW(n,a,r):[],c=pW(n,a,r);return[{id:`stats-stream:${a}`,playlistId:`stats-stream:${a}`,timelineKey:`stats-stream:${a}`,timelineId:`stats-stream:${a}`,group:"Event streams",label:Ai(a),count:o?l.length:c.length,active:e.has(`stats-stream:${a}`),buildTimelineEvents(){return o?[]:c},buildPlaylistEvents(){return c},buildTimelineRanges:o?()=>l:void 0,setActive(u){t(`stats-stream:${a}`,u)}}]})}function gW(n){return new Set([...n.filter(e=>e.getTimelineEvents).map(e=>e.id),...NE])}function yW(){return[...NE].sort((n,e)=>Ai(n).localeCompare(Ai(e)))}function vW({ctx:n,modules:e,activeTimelineEventSourceIds:t,activeMechanicTimelineKinds:i,toggleEventSource:s,setMechanicTimelineKind:a}){if(!n)return[];const r=[];for(const o of nW){const l=o.buildEvents(n),c=l.length;r.push({id:o.id,playlistId:`replay:${o.id}`,timelineKey:`events:${o.id}`,timelineId:`events:${o.id}`,group:"Replay",label:o.label,count:c,active:t.has(o.id),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){s(o.id,u)}})}for(const o of e.filter(l=>l.getTimelineEvents)){const l=o.getTimelineEvents?.(n)??[],c=l.length;r.push({id:o.id,playlistId:`module:${o.id}`,timelineKey:`module:${o.id}`,timelineId:`module:${o.id}`,group:"Stats",label:o.label,count:c,active:t.has(o.id),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){s(o.id,u)}})}for(const o of iW){const l=o.buildEvents(n),c=l.length;r.push({id:o.id,playlistId:`extra:${o.id}`,timelineKey:`extra:${o.id}`,timelineId:`extra:${o.id}`,group:"Stats",label:o.label,count:c,active:t.has(o.id),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){s(o.id,u)}})}r.push(..._W(n,t,s,gW(e)));for(const o of yW()){const l=FE[o](n.statsTimeline,n.replay),c=l.length;r.push({id:`mechanic:${o}`,playlistId:`mechanic:${o}`,timelineKey:`mechanic:${o}`,timelineId:`mechanic:${o}`,group:"Event types",label:Ai(o),count:c,active:i.has(o),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){a(o,u)}})}return r.sort((o,l)=>o.label.localeCompare(l.label))}function bW(n,e){if(!n)return[];const t=[{id:"replay:goals",group:"Replay",label:"Goals",events:n.replay.timelineEvents.filter(s=>s.kind==="goal")}],i=e.map(s=>({id:s.playlistId,group:s.group,label:s.label,events:s.buildPlaylistEvents()}));return[...t,...i]}function E_(n,e){const t=n.map(i=>i.id);return e===null?new Set(t.filter(i=>!eW.has(i)&&!tW.some(s=>i.startsWith(s)))):new Set(t.filter(i=>e.has(i)))}function xW(n,e){const t=n.playerId??null,i=t?e.findIndex(s=>s.id===t):-1;return i>=0?ch[i%ch.length]:n.color??df}function wW({sources:n,activeSourceIds:e,replayPlayers:t}){const i=E_(n,e);return n.filter(s=>i.has(s.id)).flatMap(s=>s.events.map((a,r)=>({key:`${s.id}:${a.id??`${a.kind}:${a.time}:${r}`}`,sourceId:s.id,sourceLabel:s.label,event:a,color:xW(a,t)}))).sort((s,a)=>s.event.time!==a.event.time?s.event.time-a.event.time:(s.event.label??s.sourceLabel).localeCompare(a.event.label??a.sourceLabel))}class SW{constructor(e){this.options=e}getSources(e=this.options.getContext()){return vW({ctx:e,modules:this.options.modules,activeTimelineEventSourceIds:this.options.getActiveTimelineEventSourceIds(),activeMechanicTimelineKinds:this.options.getActiveMechanicTimelineKinds(),toggleEventSource:this.options.toggleEventSource,setMechanicTimelineKind:this.options.setMechanicTimelineKind})}countVisibleSources(e){return e.replay.timelineEvents.filter(i=>i.kind==="goal").length+this.getSources(e).filter(i=>i.active).reduce((i,s)=>i+s.count,0)}render(){const{body:e}=this.options;e.replaceChildren();const t=this.getSources();if(t.length===0){const d=document.createElement("p");d.className="stat-window-empty",d.textContent="No events loaded.",e.append(d);return}const i=document.createElement("div");i.className="mechanics-actions";const s=document.createElement("button");s.type="button",s.className="module-summary-item",s.addEventListener("click",()=>{for(const d of t)d.setActive(!0);this.options.setupActiveModules(),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.render(),this.options.renderModuleSummary(),this.options.renderModuleSettings(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()});const a=document.createElement("span");a.textContent="All events";const r=document.createElement("strong");r.textContent=`${t.length}`,s.append(a,r);const o=document.createElement("button");o.type="button",o.className="module-summary-item",o.addEventListener("click",()=>{for(const d of t)d.setActive(!1);this.options.setupActiveModules(),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.render(),this.options.renderModuleSummary(),this.options.renderModuleSettings(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()});const l=document.createElement("span");l.textContent="No events";const c=document.createElement("strong");c.textContent="Off",o.append(l,c),i.append(s,o),e.append(i);const u=this.renderSourceList(t);u&&e.append(u)}renderSourceList(e){if(e.length===0)return null;const t=document.createElement("div");t.className="module-list mechanics-list mechanics-event-list",t.style.setProperty("--event-source-columns",`${TW(e.length)}`);for(const i of e){const s=document.createElement("button");s.type="button",s.className="module-summary-item",s.dataset.active=i.active?"true":"false",s.setAttribute("aria-pressed",i.active?"true":"false"),s.addEventListener("click",()=>{i.setActive(!i.active),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.render(),this.options.renderTimelineEventCount()});const a=document.createElement("span");a.textContent=i.label;const r=document.createElement("strong");r.textContent=`${i.active?"On":"Off"} ${i.count}`,s.append(a,r),t.append(s)}return t}}function TW(n){return window.innerWidth<640?1:window.innerWidth<900?n>=7?2:1:n>=13?3:n>=7?2:1}function MW(n){return new SW(n)}const EW=new Set(["ceiling-shot","fifty-fifty","ball_half",WE,"absolute-positioning","dodge","speed-flip","touch"]),Vx="touch";class CW{constructor(e){this.options=e}renderSummary(){const{summary:e}=this.options.elements;e.replaceChildren();const t=this.options.getTimelineSources(),i=t.map(o=>this.renderTimelineSourceToggle(o)),s=[],a=[],r=this.options.getContext();for(const o of this.options.modules){const l=EW.has(o.id);!o.getTimelineEvents&&!o.getTimelineRanges&&!l||(t.length===0&&o.getTimelineEvents&&i.push(this.renderCapabilityToggle(o.id,fm(o,"events"),"events")),o.getTimelineRanges&&s.push(this.renderCapabilityToggle(o.id,fm(o,"ranges"),"ranges",r?o.getTimelineRanges(r).length:void 0)),l&&a.push(this.renderCapabilityToggle(o.id,fm(o,"effects"),"effects")))}a.push(this.renderBoostPickupAnimationToggle()),e.append(hm("Timeline markers",i),hm("Timeline ranges",s),hm("In-game visualizations",a))}renderSettings(){const{settings:e}=this.options.elements;e.replaceChildren();const t=this.options.getContext(),i=this.options.getActiveModules().filter(s=>s.id!=="boost"&&s.id!==Vx).map(s=>s.renderSettings?.(t)??null).filter(s=>s instanceof HTMLElement);if(i.length===0){e.hidden=!0,this.renderBoostPickupFiltersWindow(),this.renderTouchControlsWindow();return}e.hidden=!1,e.append(...i),this.renderBoostPickupFiltersWindow(),this.renderTouchControlsWindow()}renderBoostPickupAnimationToggle(){const e=this.options.getBoostPickupAnimationEnabled(),t=document.createElement("button");t.type="button",t.className="module-summary-item",t.dataset.active=e?"true":"false",t.setAttribute("aria-pressed",e?"true":"false"),t.addEventListener("click",this.options.toggleBoostPickupAnimation);const i=document.createElement("span");i.textContent="Boost pickup animation";const s=document.createElement("strong");return s.textContent=e?"On":"Off",t.append(i,s),t}renderCapabilityToggle(e,t,i,s){const r=this.options.getActiveCapabilityIds(i).has(e),o=document.createElement("button");o.type="button",o.className="module-summary-item",o.dataset.active=r?"true":"false",o.setAttribute("aria-pressed",r?"true":"false"),o.addEventListener("click",()=>{this.options.toggleCapability(e,i,!this.options.getActiveCapabilityIds(i).has(e))});const l=document.createElement("span");l.textContent=t;const c=document.createElement("strong");return c.textContent=Gx(r,s),o.append(l,c),o}renderTimelineSourceToggle(e){const t=document.createElement("button");t.type="button",t.className="module-summary-item",t.dataset.active=e.active?"true":"false",t.setAttribute("aria-pressed",e.active?"true":"false"),t.addEventListener("click",()=>{e.setActive(!e.active),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.options.renderTimelineEventCount(),this.options.requestConfigSync(),this.renderSummary()});const i=document.createElement("span");i.textContent=AW(e);const s=document.createElement("strong");return s.textContent=Gx(e.active,e.count),t.append(i,s),t}renderBoostPickupFiltersWindow(){const e=this.options.getContext(),t=this.options.boostPickupFilters.renderSettings(e,{showHeader:!1});this.options.elements.boostPickupFilters.replaceChildren(t)}renderTouchControlsWindow(){const e=this.options.getContext(),i=this.options.modules.find(s=>s.id===Vx)?.renderSettings?.(e)??null;this.options.elements.touchControls.replaceChildren(),i instanceof HTMLElement&&this.options.elements.touchControls.append(i)}}function hm(n,e){const t=document.createElement("section");t.className="module-summary-group";const i=document.createElement("h3");i.textContent=n;const s=document.createElement("div");return s.className="module-list",s.append(...e),t.append(i,s),t}function Gx(n,e){const t=n?"On":"Off";return e==null?t:`${t} ${e}`}function AW(n){return n.group==="Replay"?n.label:`${n.label} events`}function fm(n,e){const t={"absolute-positioning:ranges":"Position zones","backboard:events":"Backboard","ball-carry:events":"Ball carry","boost:ranges":"Boost pickup timeline","bump:events":"Bump","ceiling-shot:events":"Ceiling shot","demo:events":"Demo","dodge-reset:events":"Dodge refresh","double-tap:events":"Double tap","fifty-fifty:events":"50/50","fifty-fifty:ranges":"50/50","dodge:events":"Dodge","half-flip:events":"Half flip","possession:ranges":"Possession","powerslide:events":"Powerslide","powerslide:ranges":"Powerslide","ball_half:ranges":"Half control","ball_third:ranges":"Third control","rush:ranges":"Rush","speed-flip:events":"Speed flip","touch:events":"Touch","wavedash:events":"Wavedash"},i={"absolute-positioning":"Position zones","ceiling-shot":"Ceiling shot labels","fifty-fifty":"50/50 labels",dodge:"Dodge impulse arrows",ball_half:"Half control","relative-positioning":"Player roles","speed-flip":"Speed flip labels",touch:"Touch labels"};return e==="effects"?i[n.id]??n.label:t[`${n.id}:${e}`]??`${n.label} timeline`}function RW(n){return new CW(n)}var gn=Uint8Array,fi=Uint16Array,Jg=Int32Array,hf=new gn([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ff=new gn([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),C_=new gn([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a1=function(n,e){for(var t=new fi(31),i=0;i<31;++i)t[i]=e+=1<>1|(Ut&21845)<<1;Zs=(Zs&52428)>>2|(Zs&13107)<<2,Zs=(Zs&61680)>>4|(Zs&3855)<<4,R_[Ut]=((Zs&65280)>>8|(Zs&255)<<8)>>1}var hs=(function(n,e,t){for(var i=n.length,s=0,a=new fi(e);s>l]=c}else for(o=new fi(i),s=0;s>15-n[s]);return o}),ha=new gn(288);for(var Ut=0;Ut<144;++Ut)ha[Ut]=8;for(var Ut=144;Ut<256;++Ut)ha[Ut]=9;for(var Ut=256;Ut<280;++Ut)ha[Ut]=7;for(var Ut=280;Ut<288;++Ut)ha[Ut]=8;var ic=new gn(32);for(var Ut=0;Ut<32;++Ut)ic[Ut]=5;var IW=hs(ha,9,0),LW=hs(ha,9,1),kW=hs(ic,5,0),DW=hs(ic,5,1),pm=function(n){for(var e=n[0],t=1;te&&(e=n[t]);return e},Ni=function(n,e,t){var i=e/8|0;return(n[i]|n[i+1]<<8)>>(e&7)&t},mm=function(n,e){var t=e/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},Qg=function(n){return(n+7)/8|0},pf=function(n,e,t){return(e==null||e<0)&&(e=0),(t==null||t>n.length)&&(t=n.length),new gn(n.subarray(e,t))},OW=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],os=function(n,e,t){var i=new Error(e||OW[n]);if(i.code=n,Error.captureStackTrace&&Error.captureStackTrace(i,os),!t)throw i;return i},FW=function(n,e,t,i){var s=n.length,a=0;if(!s||e.f&&!e.l)return t||new gn(0);var r=!t,o=r||e.i!=2,l=e.i;r&&(t=new gn(s*3));var c=function(xe){var Ae=t.length;if(xe>Ae){var L=new gn(Math.max(Ae*2,xe));L.set(t),t=L}},u=e.f||0,d=e.p||0,h=e.b||0,f=e.l,p=e.d,g=e.m,_=e.n,m=s*8;do{if(!f){u=Ni(n,d,1);var v=Ni(n,d+1,3);if(d+=3,v)if(v==1)f=LW,p=DW,g=9,_=5;else if(v==2){var x=Ni(n,d,31)+257,M=Ni(n,d+10,15)+4,C=x+Ni(n,d+5,31)+1;d+=14;for(var w=new gn(C),E=new gn(19),R=0;R>4;if(y<16)w[R++]=y;else{var F=0,W=0;for(y==16?(W=3+Ni(n,d,3),d+=2,F=w[R-1]):y==17?(W=3+Ni(n,d,7),d+=3):y==18&&(W=11+Ni(n,d,127),d+=7);W--;)w[R++]=F}}var H=w.subarray(0,x),ne=w.subarray(x);g=pm(H),_=pm(ne),f=hs(H,g,1),p=hs(ne,_,1)}else os(1);else{var y=Qg(d)+4,b=n[y-4]|n[y-3]<<8,T=y+b;if(T>s){l&&os(0);break}o&&c(h+b),t.set(n.subarray(y,T),h),e.b=h+=b,e.p=d=T*8,e.f=u;continue}if(d>m){l&&os(0);break}}o&&c(h+131072);for(var oe=(1<>4;if(d+=F&15,d>m){l&&os(0);break}if(F||os(2),ke<256)t[h++]=ke;else if(ke==256){Ie=d,f=null;break}else{var Xe=ke-254;if(ke>264){var R=ke-257,De=hf[R];Xe=Ni(n,d,(1<>4;Z||os(3),d+=Z&15;var ne=PW[ae];if(ae>3){var De=ff[ae];ne+=mm(n,d)&(1<m){l&&os(0);break}o&&c(h+131072);var Se=h+Xe;if(h>8},cl=function(n,e,t){t<<=e&7;var i=e/8|0;n[i]|=t,n[i+1]|=t>>8,n[i+2]|=t>>16},_m=function(n,e){for(var t=[],i=0;ih&&(h=a[i].s);var f=new fi(h+1),p=P_(t[u-1],f,0);if(p>e){var i=0,g=0,_=p-e,m=1<<_;for(a.sort(function(x,M){return f[M.s]-f[x.s]||x.f-M.f});ie)g+=m-(1<>=_;g>0;){var y=a[i].s;f[y]=0&&g;--i){var b=a[i].s;f[b]==e&&(--f[b],++g)}p=e}return{t:new gn(f),l:p}},P_=function(n,e,t){return n.s==-1?Math.max(P_(n.l,e,t+1),P_(n.r,e,t+1)):e[n.s]=t},Wx=function(n){for(var e=n.length;e&&!n[--e];);for(var t=new fi(++e),i=0,s=n[0],a=1,r=function(l){t[i++]=l},o=1;o<=e;++o)if(n[o]==s&&o!=e)++a;else{if(!s&&a>2){for(;a>138;a-=138)r(32754);a>2&&(r(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(r(s),--a;a>6;a-=6)r(8304);a>2&&(r(a-3<<5|8208),a=0)}for(;a--;)r(s);a=1,s=n[o]}return{c:t.subarray(0,i),n:e}},ul=function(n,e){for(var t=0,i=0;i>8,n[s+2]=n[s]^255,n[s+3]=n[s+1]^255;for(var a=0;a4&&!E[C_[k-1]];--k);var O=c+5<<3,D=ul(s,ha)+ul(a,ic)+r,U=ul(s,h)+ul(a,g)+r+14+3*k+ul(M,E)+2*M[16]+3*M[17]+7*M[18];if(l>=0&&O<=D&&O<=U)return c1(e,u,n.subarray(l,l+c));var F,W,H,ne;if(Es(e,u,1+(U15&&(Es(e,u,ke[C]>>5&127),u+=ke[C]>>12)}}else F=IW,W=ha,H=kW,ne=ic;for(var C=0;C255){var Xe=De>>18&31;cl(e,u,F[Xe+257]),u+=W[Xe+257],Xe>7&&(Es(e,u,De>>23&31),u+=hf[Xe]);var Z=De&31;cl(e,u,H[Z]),u+=ne[Z],Z>3&&(cl(e,u,De>>5&8191),u+=ff[Z])}else cl(e,u,F[De]),u+=W[De]}return cl(e,u,F[256]),u+W[256]},NW=new Jg([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),u1=new gn(0),UW=function(n,e,t,i,s,a){var r=a.z||n.length,o=new gn(i+r+5*(1+Math.ceil(r/7e3))+s),l=o.subarray(i,o.length-s),c=a.l,u=(a.r||0)&7;if(e){u&&(l[0]=a.r>>3);for(var d=NW[e-1],h=d>>13,f=d&8191,p=(1<7e3||E>24576)&&(F>423||!c)){u=Xx(n,l,0,b,T,x,C,E,k,w-k,u),E=M=C=0,k=w;for(var W=0;W<286;++W)T[W]=0;for(var W=0;W<30;++W)x[W]=0}var H=2,ne=0,oe=f,pe=D-U&32767;if(F>2&&O==y(w-pe))for(var Ie=Math.min(h,F)-1,ke=Math.min(32767,w),Xe=Math.min(258,F);pe<=ke&&--oe&&D!=U;){if(n[w+H]==n[w+H-pe]){for(var De=0;DeH){if(H=De,ne=pe,De>Ie)break;for(var Z=Math.min(pe,De-2),ae=0,W=0;Wae&&(ae=ie,U=Se)}}}D=U,U=g[D],pe+=D-U&32767}if(ne){b[E++]=268435456|A_[H]<<18|$x[ne];var xe=A_[H]&31,Ae=$x[ne]&31;C+=hf[xe]+ff[Ae],++T[257+xe],++x[Ae],R=w+H,++M}else b[E++]=n[w],++T[n[w]]}}for(w=Math.max(w,R);w=r&&(l[u/8|0]=c,L=r),u=c1(l,u+1,n.subarray(w,L))}a.i=r}return pf(o,0,i+Qg(u)+s)},BW=function(n,e,t,i,s){if(!s&&(s={l:1},e.dictionary)){var a=e.dictionary.subarray(-32768),r=new gn(a.length+n.length);r.set(a),r.set(n,a.length),n=r,s.w=a.length}return UW(n,e.level==null?6:e.level,e.mem==null?s.l?Math.ceil(Math.max(8,Math.min(13,Math.log(n.length)))*1.5):20:12+e.mem,t,i,s)};function zW(n,e){return BW(n,e||{},0,0)}function d1(n,e){return FW(n,{i:2},e,e)}var Kx=typeof TextEncoder<"u"&&new TextEncoder,I_=typeof TextDecoder<"u"&&new TextDecoder,HW=0;try{I_.decode(u1,{stream:!0}),HW=1}catch{}var VW=function(n){for(var e="",t=0;;){var i=n[t++],s=(i>127)+(i>223)+(i>239);if(t+s>n.length)return{s:e,r:pf(n,t-1)};s?s==3?(i=((i&15)<<18|(n[t++]&63)<<12|(n[t++]&63)<<6|n[t++]&63)-65536,e+=String.fromCharCode(55296|i>>10,56320|i&1023)):s&1?e+=String.fromCharCode((i&31)<<6|n[t++]&63):e+=String.fromCharCode((i&15)<<12|(n[t++]&63)<<6|n[t++]&63):e+=String.fromCharCode(i)}};function GW(n,e){var t;if(Kx)return Kx.encode(n);for(var i=n.length,s=new gn(n.length+(n.length>>1)),a=0,r=function(c){s[a++]=c},t=0;ts.length){var o=new gn(a+8+(i-t<<1));o.set(s),s=o}var l=n.charCodeAt(t);l<128||e?r(l):l<2048?(r(192|l>>6),r(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|n.charCodeAt(++t)&1023,r(240|l>>18),r(128|l>>12&63),r(128|l>>6&63),r(128|l&63)):(r(224|l>>12),r(128|l>>6&63),r(128|l&63))}return pf(s,0,a)}function h1(n,e){var t;if(I_)return I_.decode(n);var i=VW(n),s=i.s,t=i.r;return t.length&&os(8),s}const L_=1,k_="cfg",qx="cfgDebug";function $W(n){let e="";for(const t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function WW(n){const e=n.replaceAll("-","+").replaceAll("_","/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=atob(t),s=new Uint8Array(i.length);for(let a=0;a!Ri(e)||!o8(e.id)?null:{id:e.id,placement:p1(e.placement)}).filter(e=>e!==null):[]}function a8(n){return Array.isArray(n)?n.map(e=>!Ri(e)||typeof e.id!="string"||!l8(e.kind)?null:{id:e.id,kind:e.kind,placement:p1(e.placement),playerId:m1(e.playerId)??null,team:e.team==="orange"?"orange":e.team==="blue"?"blue":null,entries:r8(e.entries)}).filter(e=>e!==null):[]}function r8(n){return Array.isArray(n)?n.map(e=>!Ri(e)||typeof e.statId!="string"?null:{statId:e.statId,targetId:typeof e.targetId=="string"?e.targetId:void 0}).filter(e=>e!==null):[]}function p1(n){const e=Ri(n)?n:{},t=Ri(e.viewport)?e.viewport:{};return{x:Rn(e.x)??8,y:Rn(e.y)??8,viewport:{width:uh(t.width)??1,height:uh(t.height)??1},zIndex:Rn(e.zIndex),visible:Zn(e.visible)??!0}}function o8(n){return n==="camera"||n==="scoreboard"||n==="playback"||n==="recording"||n==="training-pack"||n==="mechanics"||n==="event-playlist"||n==="mechanics-review"||n==="replay-loading"||n==="boost-pickups"||n==="touch-controls"||n==="touch-legend"||n==="shot-visualization"||n==="missed-events"}function l8(n){return n==="player"||n==="team"||n==="all-players"||n==="all-teams"||n==="kickoff-overview"||n==="goals-overview"||n==="ad-hoc"}function Ri(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Rn(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function uh(n){const e=Rn(n);return e!==void 0&&e>0?e:void 0}function Zn(n){return typeof n=="boolean"?n:void 0}function m1(n){return n===null?null:typeof n=="string"?n:void 0}function dl(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"):[]}function Yx(n,e,t){return Math.min(t,Math.max(e,n))}const c8=["camera","scoreboard","playback","recording","training-pack","mechanics","event-playlist","mechanics-review","replay-loading","boost-pickups","touch-controls","touch-legend","shot-visualization","missed-events"];class u8{constructor(e){this.options=e}nextZIndex=30;reset(){this.nextZIndex=30}bringToFront(e){e.style.zIndex=`${this.nextZIndex++}`}show(e){const t=this.mustWindow(e);t.hidden=!1,this.bringToFront(t),this.options.requestConfigSync()}toggle(e){const t=this.mustWindow(e);t.hidden=!t.hidden,t.hidden||this.bringToFront(t),this.options.requestConfigSync()}hide(e){const t=this.mustWindow(e);t.hidden=!0,this.options.requestConfigSync()}readPlacement(e){const t=Number.parseInt(e.style.zIndex,10);return{x:this.readCoordinate(e,"--window-x"),y:this.readCoordinate(e,"--window-y"),viewport:jx(),zIndex:Number.isFinite(t)?t:void 0,visible:!e.hidden}}applyPlacement(e,t){const i=ZW(t,jx());e.style.setProperty("--window-x",`${i.x}px`),e.style.setProperty("--window-y",`${i.y}px`),e.hidden=!t.visible,t.zIndex!==void 0&&(e.style.zIndex=`${t.zIndex}`,this.nextZIndex=Math.max(this.nextZIndex,t.zIndex+1))}getSingletonConfigs(){const e=[],t=this.options.getRoot();for(const i of c8){const s=t.querySelector(`[data-window-id="${i}"]`);s&&e.push({id:i,placement:this.readPlacement(s)})}return e}applySingletonConfigs(e){const t=this.options.getRoot();for(const i of e){const s=t.querySelector(`[data-window-id="${i.id}"]`);s&&this.applyPlacement(s,i.placement)}}installDragging(e,t){e.addEventListener("pointerdown",i=>{if(!(i.target instanceof HTMLElement)||d8(i.target))return;const s=i.target.closest("[data-window-id]");if(!s||s.hidden)return;this.bringToFront(s);const a=i.clientX,r=i.clientY,o=s.getBoundingClientRect(),l=i.pointerId;s.setPointerCapture(l),i.preventDefault();const c=d=>{const h=Math.max(8,Math.min(window.innerWidth-120,o.left+d.clientX-a)),f=Math.max(8,Math.min(window.innerHeight-100,o.top+d.clientY-r));s.style.setProperty("--window-x",`${h}px`),s.style.setProperty("--window-y",`${f}px`)},u=()=>{s.releasePointerCapture(l),s.removeEventListener("pointermove",c),s.removeEventListener("pointerup",u),s.removeEventListener("pointercancel",u),this.options.requestConfigSync()};s.addEventListener("pointermove",c),s.addEventListener("pointerup",u),s.addEventListener("pointercancel",u)},{signal:t})}mustWindow(e){const t=this.options.getRoot().querySelector(`[data-window-id="${e}"]`);if(!t)throw new Error(`Missing window for id: ${e}`);return t}readCoordinate(e,t){const i=e.style.getPropertyValue(t).trim(),s=getComputedStyle(e).getPropertyValue(t).trim(),a=i||s,r=Number.parseFloat(a);if(Number.isFinite(r))return r;const o=e.getBoundingClientRect();return t==="--window-y"?o.top:o.left}}function jx(){return{width:Math.max(1,window.innerWidth),height:Math.max(1,window.innerHeight)}}function d8(n){return n instanceof Element&&!!n.closest("button, input, select, textarea, option, label, a, [data-no-drag]")}function h8(n){return new u8(n)}class f8{constructor(e){this.options=e}activeSourceIds=null;autoFollow=!0;lastActiveKey=null;activeItem=null;renderedItems=[];reset(){this.activeSourceIds=null,this.lastActiveKey=null,this.activeItem=null,this.renderedItems=[]}render(){this.options.body.replaceChildren(),this.lastActiveKey=null,this.activeItem=null,this.renderedItems=[];const e=this.options.getSources();if(e.length===0){const _=document.createElement("p");_.className="stat-window-empty",_.textContent=this.options.getReplayPlayer()?"No events loaded.":"Load a replay to see events.",this.options.body.append(_);return}const t=E_(e,this.activeSourceIds),i=wW({sources:e,activeSourceIds:this.activeSourceIds,replayPlayers:this.options.getReplayPlayer()?.replay.players??[]}),s=document.createElement("div");s.className="event-playlist-toolbar";const a=document.createElement("details");a.className="event-playlist-filter",a.dataset.noDrag="true";const r=document.createElement("summary");r.textContent=`Filters ${t.size}/${e.length}`,a.append(r);const o=document.createElement("div");o.className="event-playlist-filter-panel";const l=document.createElement("div");l.className="event-playlist-filter-actions";const c=document.createElement("button");c.type="button",c.textContent="All",c.addEventListener("click",()=>{this.activeSourceIds=new Set(e.map(m=>m.id)),this.lastActiveKey=null,this.render();const _=this.options.getReplayPlayer()?.getState();_&&this.syncTimeline(_)});const u=document.createElement("button");u.type="button",u.textContent="None",u.addEventListener("click",()=>{this.activeSourceIds=new Set,this.lastActiveKey=null,this.render()}),l.append(c,u),o.append(l);const d=new Map;for(const _ of e){const m=d.get(_.group)??[];m.push(_),d.set(_.group,m)}for(const[_,m]of d){const v=document.createElement("section");v.className="event-playlist-filter-group";const y=document.createElement("h3");y.textContent=_,v.append(y);for(const b of m){const T=document.createElement("label");T.className="toggle event-playlist-filter-option";const x=document.createElement("input");x.type="checkbox",x.checked=t.has(b.id),x.addEventListener("change",()=>{this.setSourceSelection(e,C=>{x.checked?C.add(b.id):C.delete(b.id)})});const M=document.createElement("span");M.textContent=`${b.label} (${b.events.length})`,T.append(x,M),v.append(T)}o.append(v)}a.append(o);const h=document.createElement("label");h.className="toggle event-playlist-follow";const f=document.createElement("input");f.type="checkbox",f.checked=this.autoFollow,f.addEventListener("change",()=>{this.autoFollow=f.checked;const _=this.options.getReplayPlayer()?.getState();_&&this.syncTimeline(_,{forceScroll:!0})});const p=document.createElement("span");p.textContent="Auto-follow",h.append(f,p),s.append(a,h);const g=document.createElement("div");if(g.className="event-playlist-list",g.dataset.noDrag="true",i.length===0){const _=document.createElement("p");_.className="stat-window-empty",t.size===0?_.textContent="No event types selected.":_.textContent="No events in selected event types.",g.append(_)}else for(const _ of i){const m=document.createElement("button");m.type="button",m.className="event-playlist-item",m.dataset.eventKey=_.key,m.dataset.eventTime=`${_.event.time}`,m.style.setProperty("--event-color",_.color),Number.isFinite(_.event.time)&&this.renderedItems.push({key:_.key,time:_.event.time,element:m}),m.addEventListener("click",()=>{this.options.cueTimelineEvent(_.event)});const v=document.createElement("span");v.className="event-playlist-time",v.textContent=this.options.formatTime(_.event.time);const y=document.createElement("span");y.className="event-playlist-main";const b=document.createElement("strong");b.textContent=_.event.label??_.sourceLabel;const T=document.createElement("span");T.textContent=[_.event.playerName??null,_.event.frame!==void 0?`frame ${_.event.frame}`:null,_.sourceLabel].filter(x=>!!x).join(" · "),y.append(b,T),m.append(v,y),g.append(m)}this.options.body.append(s,g)}syncTimeline(e,t={}){if(!this.options.body.querySelector(".event-playlist-list"))return;const s=this.getActiveItem(e.currentTime),a=s?.dataset.eventKey??null;a===this.lastActiveKey&&!t.forceScroll||(this.activeItem?.isConnected?this.activeItem.dataset.active="false":this.activeItem&&(this.activeItem=null),s?(s.dataset.active="true",this.activeItem=s,(this.autoFollow||t.forceScroll)&&s.scrollIntoView({block:"nearest"})):this.activeItem=null,this.lastActiveKey=a)}setSourceSelection(e,t){const i=E_(e,this.activeSourceIds);t(i),this.activeSourceIds=i,this.lastActiveKey=null,this.render();const s=this.options.getReplayPlayer()?.getState();s&&this.syncTimeline(s)}getActiveItem(e){const t=this.renderedItems;if(t.length===0)return null;let i=0,s=t.length-1;for(;ie.getConfig||e.applyConfig).map(e=>{const t={id:e.id};return e.id==="boost"&&(t.aliases=["boost-pickup-animation"]),e.getConfig&&(t.getConfig=()=>e.getConfig?.()),e.applyConfig&&(t.applyConfig=i=>e.applyConfig?.(i)),t})}function T8(n){return y8(g1(n))}function M8({replayPlayer:n,playbackRate:e,skipPostGoalTransitions:t,skipKickoffs:i}){const s=n?.getState();return{currentTime:s?.currentTime,playing:s?.playing,rate:s?.speed??mf(Number(e?.value??1)),skipPostGoalTransitions:n?s?.skipPostGoalTransitionsEnabled:t.checked,skipKickoffs:n?s?.skipKickoffsEnabled:i.checked}}function E8({replayPlayer:n,cameraControlsController:e}){const t=n?.getState(),i=t?pE(t):e?.ballCamMode;return{mode:t?.cameraViewMode,freePreset:e?.freeCameraPreset??null,attachedPlayerId:t?.attachedPlayerId,ballCam:i===void 0?void 0:i==="on",useReplayBallCam:i===void 0?void 0:i==="player",usePlayerCameraSettings:t?.customCameraSettings===null,autoPossession:e?.autoPossessionEnabled,customSettings:t?.customCameraSettings,nameplateLiftUu:e?.nameplateLiftUu}}function C8({playback:n,camera:e,activeTimelineEventSourceIds:t,activeTimelineRangeModuleIds:i,activeMechanicTimelineKinds:s,activeRenderEffectModuleIds:a,initialConfig:r,replayPlayer:o,boostPadOverlayEnabled:l,recording:c,singletonWindows:u,statsWindows:d,moduleConfigs:h}){return{version:L_,playback:n,camera:e,overlays:{timelineEvents:[...t],timelineRanges:[...i],mechanics:[...s],renderEffects:[...a],...r?.overlays.pluginRenderEffects!==void 0?{pluginRenderEffects:[...r.overlays.pluginRenderEffects]}:{},...r?.overlays.pluginHudOverlay!==void 0?{pluginHudOverlay:r.overlays.pluginHudOverlay}:{},followedPlayerHud:!1,boostPads:l,boostPickupAnimation:o?.getState().boostPickupAnimationEnabled??!1,hitboxWireframes:o?.getState().hitboxWireframesEnabled??!1,hitboxOnlyMode:o?.getState().hitboxOnlyModeEnabled??!1},recording:c,singletonWindows:u,statsWindows:d,moduleConfigs:h}}function A8(n,e,t){return{currentTime:n.currentTime,playing:n.playing,speed:n.rate,customCameraSettings:_1(e),cameraViewMode:e.mode,attachedPlayerId:e.attachedPlayerId,...jb(e)==="player"?{useReplayBallCam:!0}:{ballCamEnabled:jb(e)==="on"},boostPickupAnimationEnabled:t.overlays.boostPickupAnimation,hitboxWireframesEnabled:t.overlays.hitboxWireframes,hitboxOnlyModeEnabled:t.overlays.hitboxOnlyMode,skipPostGoalTransitionsEnabled:n.skipPostGoalTransitions,skipKickoffsEnabled:n.skipKickoffs}}function R8(n,e,t){console.groupCollapsed("[subtr-actor] stats player cfg load"),console.log("location.href",window.location.href),console.log("location.search",n.search||"(empty)"),console.log("location.hash",n.hash||"(empty)"),console.table([...n.searchParams.map(([i,s])=>({source:"search",name:i,value:s})),...n.hashParams.map(([i,s])=>({source:"hash",name:i,value:s}))]),console.log("cfg selected source",n.selectedSource??"(none)"),console.log("cfg selected raw text",n.selectedValue??"(none)"),console.log("cfg selected raw length",n.selectedValue?.length??0),console.log("cfg search values",n.searchValues),console.log("cfg hash values",n.hashValues),n.hashValues.length>0&&n.searchValues.length>0&&console.warn("Both hash and search contain cfg; hash cfg is used."),e&&(console.log("cfg normalized JSON",JSON.stringify(e,null,2)),console.log("cfg normalized object",e)),t&&console.error("cfg decode/apply error",t),console.groupEnd()}function Zx(n,e){const{style:t}=n.renderer.domElement;t.visibility=e?"hidden":"",t.pointerEvents=e?"none":""}function Jx(n,e={}){const t=e.destroyPlayer??!0,i=e.clearPlayerPluginHandles??!0,s=n.getUnsubscribe();s&&(s(),n.setUnsubscribe(null)),n.teardownActiveModules(),t&&(n.getReplayPlayer()?.destroy(),n.setReplayPlayer(null)),i&&(n.setCanvasRecorder(null),n.setTimelineOverlay(null)),n.setLoadedReplayName(null),n.setStatsTimeline(null),n.setStatsFrameLookup(null),n.setStatRegistry(nc()),n.clearTimelineEventSources(),n.clearTimelineRangeSources(),n.clearStandalonePlugins(),n.clearRenderCaches(),n.resetEventPlaylistWindow(),n.renderModuleSummary(),n.renderScoreboard(),n.renderTimelineEventCount(),n.renderMechanicsTimelineControls(),n.renderEventPlaylistWindow(),n.renderModuleSettings(),n.syncRecordingWindow()}async function P8(n,e,t){const{elements:i}=t;let s=null;i.statusReadout.textContent=n.preparingStatus,i.fileInput.disabled=!0,t.getReplayLoadModal()?.show(n.name,n.preparingStatus),t.setTransportEnabled(!1),t.getCameraControlsController()?.syncAvailability(),i.emptyState.hidden=t.getReplayPlayer()!==null,t.getReplayPlayer()?.pause();try{i.statusReadout.textContent="Parsing replay...",t.getReplayLoadModal()?.show(n.name,"Parsing replay...");const a=await e,{replay:r}=a,o=t.getReplayPlayer();if(o){Jx(t,{destroyPlayer:!1,clearPlayerPluginHandles:!1});const h=new Rw(a.raw);await o.replaceReplay(h,r,{preservePlayback:!1}),t.setStatsTimeline(a.statsTimeline),t.setStatsFrameLookup(a.statsFrameLookup),t.setStatRegistry(nc(null)),t.setReplayPlayer(o),t.syncBoostPadOverlayPlugin(),t.setupActiveModules(),t.setUnsubscribe(o.subscribe(t.renderSnapshot));const f=t.getInitialConfig();if(f){t.setApplyingConfig(!0);try{t.applyConfigToReplayPlayer(f)}finally{t.setApplyingConfig(!1)}}t.getCameraControlsController()?.populateAttachedPlayerOptions(r.players),i.emptyState.hidden=!0,i.statusReadout.textContent=`Loaded ${n.name}`,t.setLoadedReplayName(n.name),i.playersReadout.textContent=r.players.map(p=>p.name).join(", "),i.framesReadout.textContent=`${r.frameCount}`,t.renderModuleSummary(),t.renderTimelineEventCount(),t.renderMechanicsTimelineControls(),t.resetEventPlaylistWindow(),t.renderEventPlaylistWindow(),t.setTransportEnabled(!0),t.getCameraControlsController()?.syncAvailability(o.getState()),t.renderSnapshot(o.getState()),t.renderStatsWindows(o.getState().frameIndex),t.renderScoreboard(o.getState().frameIndex),t.syncEventPlaylistTimeline(o.getState(),{forceScroll:!0}),t.renderModuleSettings(),t.syncRecordingWindow(),t.getReplayLoadModal()?.hide();return}const l=u3({replayEventsLabel:"Replay",replayEvents:h=>t.withTimelineEventSeekTimes(t.getReplayTimelineEvents(h.replay))}),c=WN({onStatusChange:t.syncRecordingWindow});t.setCanvasRecorder(c);const u=t.getInitialConfig(),d=d3(i.viewport,a,{initialPlaybackRate:u?.playback.rate,initialCustomCameraSettings:_1(u?.camera),initialAttachedPlayerId:u?.camera.attachedPlayerId??null,initialCameraViewMode:u?.camera.mode,initialBoostPickupAnimationEnabled:u?.overlays.boostPickupAnimation??!1,initialHitboxWireframesEnabled:u?.overlays.hitboxWireframes??i.hitboxWireframes.checked,initialHitboxOnlyModeEnabled:u?.overlays.hitboxOnlyMode??i.hitboxOnlyMode.checked,initialSkipPostGoalTransitionsEnabled:i.skipPostGoalTransitions.checked,initialSkipKickoffsEnabled:i.skipKickoffs.checked,plugins:[bN({onSample:({renderFps:h,replayFps:f})=>{const p=document.getElementById("render-fps-readout"),g=document.getElementById("replay-fps-readout");p&&(p.textContent=`${h.toFixed(0)} fps`),g&&(g.textContent=`${f.toFixed(0)} fps`)}}),Tu(x3({floatingLiftUu:()=>t.getCameraControlsController()?.nameplateLiftUu})),Tu(zN({includePickup:t.includeBoostPickupAnimationPickup})),Tu(c),Tu(l)]});if(s=d,Zx(d,!0),await d.ready,Jx(t),s=null,Zx(d,!1),t.setStatsTimeline(a.statsTimeline),t.setStatsFrameLookup(a.statsFrameLookup),t.setStatRegistry(nc(null)),t.setTimelineOverlay(l),t.setReplayPlayer(d),t.syncBoostPadOverlayPlugin(),t.setupActiveModules(),t.setUnsubscribe(d.subscribe(t.renderSnapshot)),u){t.setApplyingConfig(!0);try{t.applyConfigToReplayPlayer(u)}finally{t.setApplyingConfig(!1)}}t.getCameraControlsController()?.populateAttachedPlayerOptions(r.players),i.emptyState.hidden=!0,i.statusReadout.textContent=`Loaded ${n.name}`,t.setLoadedReplayName(n.name),i.playersReadout.textContent=r.players.map(h=>h.name).join(", "),i.framesReadout.textContent=`${r.frameCount}`,t.renderModuleSummary(),t.renderTimelineEventCount(),t.renderMechanicsTimelineControls(),t.resetEventPlaylistWindow(),t.renderEventPlaylistWindow(),t.setTransportEnabled(!0),t.getCameraControlsController()?.syncAvailability(d.getState()),t.renderSnapshot(d.getState()),t.renderStatsWindows(d.getState().frameIndex),t.renderScoreboard(d.getState().frameIndex),t.syncEventPlaylistTimeline(d.getState(),{forceScroll:!0}),t.renderModuleSettings(),t.syncRecordingWindow(),t.getReplayLoadModal()?.hide()}catch(a){throw t.getReplayLoadModal()?.hide(),s?.destroy(),t.getReplayPlayer()||(i.emptyState.hidden=!1,t.setCanvasRecorder(null)),t.syncRecordingWindow(),a}finally{i.fileInput.disabled=!1}}function I8(n){if(n<=0)return"--";const e=["B","KB","MB","GB"];let t=n,i=0;for(;t>=1024&&i=10?1:2;return`${t.toFixed(s)} ${e[i]}`}function L8(n){if(!n)return"No replay";if(n.error)return n.error;switch(n.state){case"idle":return"Idle";case"recording":return"Recording";case"stopping":return"Stopping";case"ready":return"Ready";case"error":return"Error"}}function k8({fpsValue:n,playbackRateValue:e}){const t=Number(n),i=Number(e);return{fps:Number.isFinite(t)?Math.max(1,Math.min(120,Math.trunc(t))):60,playbackRate:Number.isFinite(i)?Math.max(.1,i):1}}function D8(n,e=new Date){const i=(n?.replace(/\.replay$/i,"")||"replay").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,""),s=e.toISOString().replace(/[:.]/g,"-");return`${i||"replay"}-${s}.webm`}function O8(n,e){const t=URL.createObjectURL(n),i=document.createElement("a");i.href=t,i.download=e,document.body.append(i),i.click(),i.remove(),window.setTimeout(()=>URL.revokeObjectURL(t),0)}class F8{constructor(e){this.options=e}getConfigSnapshot(){const{elements:e}=this.options;return{fps:Number(e.fps.value),playbackRate:Number(e.playbackRate.value)}}applyConfig(e){const{elements:t}=this.options;e.fps!==void 0&&(t.fps.value=`${e.fps}`),e.playbackRate!==void 0&&(t.playbackRate.value=`${e.playbackRate}`)}sync(e=this.options.getCanvasRecorder()?.getStatus()??null){const{elements:t}=this.options,i=this.options.getCanvasRecorder()!==null&&this.options.getReplayPlayer()!==null,s=e?.state??"idle",a=s==="recording"||s==="stopping",r=(this.options.getCanvasRecorder()?.getRecording()??null)!==null;t.status.textContent=L8(e),t.elapsed.textContent=`${(e?.elapsedSeconds??0).toFixed(1)}s`,t.size.textContent=I8(e?.sizeBytes??0),t.type.textContent=e?.mimeType||"WebM",t.start.disabled=!i||a,t.fullReplay.disabled=!i||a,t.stop.disabled=!i||!a,t.download.disabled=!r||a,t.clear.disabled=!r||a,t.fps.disabled=a,t.playbackRate.disabled=a}installEventListeners(e){const{elements:t}=this.options;t.start.addEventListener("click",()=>{const i=this.options.getCanvasRecorder();if(i)try{const{fps:s}=this.getRecordingOptions();i.start({fps:s}),this.sync()}catch(s){console.error("Failed to start recording:",s),this.options.setStatus(s instanceof Error?s.message:"Failed to start recording"),this.sync(i.getStatus())}},{signal:e}),t.fullReplay.addEventListener("click",()=>{const i=this.options.getCanvasRecorder();if(!i)return;const{fps:s,playbackRate:a}=this.getRecordingOptions();i.recordFullReplay({fps:s,playbackRate:a,restorePlaybackState:!0}).catch(r=>{console.error("Failed to record replay:",r),this.options.setStatus(r instanceof Error?r.message:"Failed to record replay"),this.sync(this.options.getCanvasRecorder()?.getStatus()??null)}),this.sync()},{signal:e}),t.stop.addEventListener("click",()=>{this.options.getCanvasRecorder()?.stop().catch(i=>{console.error("Failed to stop recording:",i),this.options.setStatus(i instanceof Error?i.message:"Failed to stop recording")}),this.sync()},{signal:e}),t.download.addEventListener("click",()=>{const i=this.options.getCanvasRecorder()?.getRecording();i&&O8(i,D8(this.options.getLoadedReplayName()))},{signal:e}),t.clear.addEventListener("click",()=>{try{this.options.getCanvasRecorder()?.clear(),this.sync()}catch(i){console.error("Failed to clear recording:",i)}},{signal:e}),t.fps.addEventListener("change",this.options.requestConfigSync,{signal:e}),t.playbackRate.addEventListener("change",this.options.requestConfigSync,{signal:e})}getRecordingOptions(){const{elements:e}=this.options;return k8({fpsValue:e.fps.value,playbackRateValue:e.playbackRate.value})}}function N8(n){return new F8(n)}class U8{constructor(e){this.options=e}render(e=this.options.getReplayPlayer()?.getState().frameIndex??0){const{body:t}=this.options;t.replaceChildren();const i=this.options.getStatsFrameLookup(),s=i?zt(i,e):null,a=this.options.getReplayPlayer()?.replay??null;if(!s||!a){const o=document.createElement("p");o.className="scoreboard-empty",o.textContent="Load a replay to show the scoreboard.",t.append(o);return}const r=document.createElement("div");r.className="scoreboard-scoreline",r.append(Qx(s.team_zero?.core.goals,!0),z8(),Qx(s.team_one?.core.goals,!1)),t.append(r)}}function B8(n){return typeof n=="number"&&Number.isFinite(n)?`${Math.round(n)}`:"--"}function z8(){const n=document.createElement("span");return n.className="scoreboard-divider",n.textContent="-",n}function Qx(n,e){const t=document.createElement("strong");return t.className=`scoreboard-goal-value ${na(e)}`,t.textContent=B8(n),t}function H8(n){return new U8(n)}class V8{constructor(e){this.options=e}setTransportEnabled(e,t){const{elements:i}=this.options;i.togglePlayback.disabled=!e,i.previousFrame.disabled=!e,i.nextFrame.disabled=!e,i.playbackRate.disabled=!e,i.skipPostGoalTransitions.disabled=!e,i.skipKickoffs.disabled=!e,i.hitboxWireframes.disabled=!e,i.hitboxOnlyMode.disabled=!e,this.options.getCameraControlsController()?.setTransportEnabled(e,t)}renderSnapshot(e){const{elements:t}=this.options;t.timeReadout.textContent=`${e.currentTime.toFixed(2)}s`,t.frameReadout.textContent=`${e.frameIndex}`,t.durationReadout.textContent=`${e.duration.toFixed(2)}s`,t.playbackStatusReadout.textContent=e.playing?"Playing":"Paused",t.togglePlayback.textContent=e.playing?"Pause":"Play";const i=Math.max(0,this.options.getFrameCount()-1);t.previousFrame.disabled=e.frameIndex<=0,t.nextFrame.disabled=e.frameIndex>=i;const s=mf(e.speed);t.playbackRate.value=`${s}`,t.playbackRateReadout.textContent=ty(s),this.options.getCameraControlsController()?.syncState(e),t.skipPostGoalTransitions.checked=e.skipPostGoalTransitionsEnabled,t.skipKickoffs.checked=e.skipKickoffsEnabled,t.hitboxWireframes.checked=e.hitboxWireframesEnabled,t.hitboxOnlyMode.checked=e.hitboxOnlyModeEnabled,t.emptyState.hidden=!0}}function G8(n){return new V8(n)}function $8({elements:n,signal:e,setLauncherOpen:t,openReplayFilePicker:i,getElementWindowId:s,toggleWindow:a,hideWindow:r,createStatsWindow:o,loadReplayFile:l,togglePlayback:c,stepFrames:u,setPlaybackRate:d,setSkipPostGoalTransitionsEnabled:h,setSkipKickoffsEnabled:f,setHitboxWireframesEnabled:p,setHitboxOnlyModeEnabled:g}){n.launcherToggle.addEventListener("click",()=>{t(n.launcherMenu.hidden)},{signal:e}),n.root.addEventListener("click",m=>{m.target instanceof Element&&(m.target.closest(".top-chrome")||t(!1))},{signal:e}),n.loadReplayAction.addEventListener("click",i,{signal:e}),n.emptyLoadReplay.addEventListener("click",i,{signal:e}),n.root.querySelectorAll("[data-window-toggle]").forEach(m=>{m.addEventListener("click",()=>{const v=m.dataset.windowToggle;v&&(a(v),t(!1))},{signal:e})}),n.root.querySelectorAll("[data-window-hide]").forEach(m=>{m.addEventListener("click",()=>{const v=m.dataset.windowHide??s(m);v&&r(v)},{signal:e})}),n.root.querySelectorAll("[data-create-stats-window]").forEach(m=>{m.addEventListener("click",()=>{o(m.dataset.createStatsWindow)},{signal:e})}),n.fileInput.addEventListener("change",()=>{const m=n.fileInput.files?.[0];m&&l(m)},{signal:e}),n.togglePlayback.addEventListener("click",c,{signal:e}),n.previousFrame.addEventListener("click",()=>u(-1),{signal:e}),n.nextFrame.addEventListener("click",()=>u(1),{signal:e});const _=()=>{const m=mf(Number(n.playbackRate.value));n.playbackRate.value=`${m}`,n.playbackRateReadout.textContent=ty(m),d(m)};n.playbackRate.addEventListener("input",_,{signal:e}),n.playbackRate.addEventListener("change",_,{signal:e}),n.skipPostGoalTransitions.addEventListener("change",()=>{h(n.skipPostGoalTransitions.checked)},{signal:e}),n.skipKickoffs.addEventListener("change",()=>{f(n.skipKickoffs.checked)},{signal:e}),n.hitboxWireframes.addEventListener("change",()=>{p(n.hitboxWireframes.checked)},{signal:e}),n.hitboxOnlyMode.addEventListener("change",()=>{g(n.hitboxOnlyMode.checked)},{signal:e})}const W8=3500;function X8(){const n=document.activeElement;if(!(n instanceof HTMLElement))return!1;if(n.isContentEditable)return!0;const e=n.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"}function K8(n){const{getReplayPlayer:e,signal:t}=n,i={forward:!1,backward:!1,left:!1,right:!1,up:!1,down:!1},s=()=>{i.forward=!1,i.backward=!1,i.left=!1,i.right=!1,i.up=!1,i.down=!1},a=(g,_)=>{switch(g){case"KeyW":return i.forward=_,!0;case"KeyS":return i.backward=_,!0;case"KeyA":return i.left=_,!0;case"KeyD":return i.right=_,!0;case"Space":return i.up=_,!0;case"ShiftLeft":case"ShiftRight":return i.down=_,!0;default:return!1}},r=g=>{g.ctrlKey||g.metaKey||g.altKey||X8()||a(g.code,!0)&&g.preventDefault()},o=g=>{a(g.code,!1)};window.addEventListener("keydown",r,{signal:t}),window.addEventListener("keyup",o,{signal:t}),window.addEventListener("blur",s,{signal:t});const l=new S,c=new S,u=new S,d=new S(0,1,0);let h=null,f=0;const p=g=>{f=requestAnimationFrame(p);const _=h===null?0:Math.min(.1,(g-h)/1e3);h=g;const m=(i.forward?1:0)-(i.backward?1:0),v=(i.right?1:0)-(i.left?1:0),y=(i.up?1:0)-(i.down?1:0);if(_===0||m===0&&v===0&&y===0)return;const b=e();if(!b||b.getState().cameraViewMode!=="free")return;const T=b.camera,x=b.controls;T.getWorldDirection(l),c.set(1,0,0).applyQuaternion(T.quaternion),u.set(0,0,0).addScaledVector(l,m).addScaledVector(c,v).addScaledVector(d,y),u.lengthSq()!==0&&(u.normalize().multiplyScalar(W8*_),T.position.add(u),x.target.add(u))};f=requestAnimationFrame(p),t.addEventListener("abort",()=>{cancelAnimationFrame(f)})}function q8(n,e){const t=new URLSearchParams(n),s=(t.get("replayId")??t.get("replay-id")??e??"").trim();return s.length>0?s:null}function Y8(){const n=new URLSearchParams(window.location.search),e=n.get("reviewToken")??n.get("token")??window.localStorage.getItem("rocket_sense_access_token");return e?{Authorization:`Bearer ${e}`}:{}}function j8(n){if(!n.replayId)return null;const e={replay_id:n.replayId,reviewed_mechanic:n.mechanic,reviewed_event_frame:n.frame,reviewed_event_time:n.time,confidence:n.confidence,status:"confirmed"};return n.subjectKind&&n.subjectId&&(e.reviewed_subject_kind=n.subjectKind,e.reviewed_subject_id=n.subjectId),n.startFrame!==null&&(e.reviewed_start_frame=n.startFrame),n.endFrame!==null&&(e.reviewed_end_frame=n.endFrame),n.notes&&n.notes.trim()&&(e.notes=n.notes.trim()),Object.keys(n.context).length>0&&(e.context=n.context),e}function Z8(n,e){const t=n.getState(),i=Math.max(0,Math.round(t.frameIndex??0)),s=t.currentTime??0,a=t.attachedPlayerId??null,r=a?n.replay.players.find(o=>o.id===a)?.name??null:null;return{localId:e.localId,mechanic:e.mechanic,frame:i,time:s,subjectKind:a?"player":null,subjectId:a,playerName:r,startFrame:null,endFrame:null,notes:e.notes?.trim()?e.notes.trim():null,confidence:1,replayId:e.replayId,context:{capturedFrom:"stat-evaluation-player",attachedPlayerId:a,playerName:r,durationSeconds:n.replay.duration??null}}}async function J8(n,e="/api/v1/events/reviews"){const t=j8(n);if(!t)return{record:n,ok:!1,message:"No replay id — cannot upload (export JSON instead)."};try{const i=await fetch(e,{method:"POST",headers:{"content-type":"application/json",...Y8()},credentials:"same-origin",body:JSON.stringify(t)});if(!i.ok){let s=`${i.status}${i.statusText?` ${i.statusText}`:""}`;try{const a=await i.json();typeof a.error=="string"&&(s=a.error)}catch{}return{record:n,ok:!1,message:s}}return{record:n,ok:!0,message:"uploaded"}}catch(i){return{record:n,ok:!1,message:i instanceof Error?i.message:String(i)}}}const Q8=["flick","whiff","double_tap","ceiling_shot","wall_aerial","flip_reset","one_timer","speed_flip","half_flip","wavedash","demo"],e6="m";function t6(){const n=document.activeElement;if(!(n instanceof HTMLElement))return!1;if(n.isContentEditable)return!0;const e=n.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"}function n6(n,e){const t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),i=URL.createObjectURL(t),s=document.createElement("a");s.href=i,s.download=n,document.body.appendChild(s),s.click(),s.remove(),URL.revokeObjectURL(i)}class i6{constructor(e){this.options=e}records=[];localIdSeq=0;installEventListeners(e){const{elements:t}=this.options;for(const i of Q8){const s=document.createElement("option");s.value=i,s.textContent=i.replaceAll("_"," "),t.mechanic.appendChild(s)}t.capture.addEventListener("click",()=>this.capture(),{signal:e}),t.export.addEventListener("click",()=>this.exportJson(),{signal:e}),t.upload.addEventListener("click",()=>{this.uploadAll()},{signal:e}),t.clear.addEventListener("click",()=>{this.records.length=0,this.render(),this.setStatus("Cleared.")},{signal:e}),window.addEventListener("keydown",i=>{i.key.toLowerCase()!==e6||i.repeat||i.metaKey||i.ctrlKey||i.altKey||t6()||(i.preventDefault(),this.capture())},{signal:e}),this.render()}capture(){const e=this.options.getReplayPlayer();if(!e){this.setStatus("No replay loaded.");return}this.localIdSeq+=1;const t=Z8(e,{mechanic:this.options.elements.mechanic.value||"flick",replayId:this.resolveReplayId(),localId:`missed-${this.localIdSeq}`});this.records.push(t),this.options.showWindow(),this.render(),this.setStatus(`Captured ${t.mechanic} @ ${t.time.toFixed(2)}s`+(t.replayId?".":" (no replay id — export only)."))}exportJson(){if(this.records.length===0){this.setStatus("Nothing to export.");return}n6("missed-events.json",{capturedFrom:"stat-evaluation-player",replayId:this.resolveReplayId(),missedEvents:this.records}),this.setStatus(`Exported ${this.records.length}.`)}async uploadAll(){if(this.records.length===0){this.setStatus("Nothing to upload.");return}let e=0;const t=[];for(const i of[...this.records]){const s=await J8(i);if(s.ok){e+=1;const a=this.records.findIndex(r=>r.localId===i.localId);a>=0&&this.records.splice(a,1)}else t.push(`${i.mechanic}@${i.time.toFixed(1)}s: ${s.message}`)}this.render(),this.setStatus(t.length===0?`Uploaded ${e}.`:`Uploaded ${e}, ${t.length} failed — ${t[0]}`)}render(){const{list:e}=this.options.elements;e.replaceChildren();for(const t of this.records){const i=document.createElement("li"),s=t.playerName??t.subjectId??"no subject",a=document.createElement("span");a.className="missed-event-row",a.textContent=`${t.mechanic} @ ${t.time.toFixed(2)}s · f${t.frame} · ${s}`+(t.replayId?"":" · no replay id");const r=document.createElement("button");r.type="button",r.textContent="✕",r.title="Remove",r.addEventListener("click",()=>{const o=this.records.findIndex(l=>l.localId===t.localId);o>=0&&(this.records.splice(o,1),this.render())}),i.append(a,r),e.appendChild(i)}}setStatus(e){this.options.elements.status.textContent=e}resolveReplayId(){return q8(window.location.search,this.options.getReplayId?.()??null)}}function s6(n){return new i6(n)}class mo{constructor(e,t){this.file=e,this.sourceTimes=t}sourceTimes;dirty=!1;static async createNew(e){const t=await ta.create(H3(),e);return new mo(t,[])}static async loadFromBytes(e,t){const i=await ta.load(e,t);return new mo(i,new Array(i.roundCount).fill(null))}get shotCount(){return this.file.roundCount}get hasUnsavedShots(){return this.dirty}shots(){return this.file.rounds.map((e,t)=>({index:t,timeLimit:e.time_limit,sourceReplayTime:this.sourceTimes[t]??null}))}captureShot(e,t=null){const i=N3(this.file,e);return this.sourceTimes[i]=t,this.dirty=!0,i}removeShot(e){this.file.removeRound(e),this.sourceTimes.splice(e,1),this.dirty=!0}setShotTimeLimit(e,t){this.file.setRoundTimeLimit(e,t),this.dirty=!0}downloadFileName(){return z3(this.file.guid)}toBytes(e=Math.floor(Date.now()/1e3)){this.file.updateMetadata({updated_at:BigInt(e)});const t=this.file.toBytes();return this.dirty=!1,t}}function a6(n,e,t,i){const s=`Captured shot ${n} (${e} at ${t})`;return i===null?`${s}.`:`${s}; warning: ${i}.`}function r6(n,e){const t=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),i=new Blob([t],{type:"application/octet-stream"}),s=URL.createObjectURL(i),a=document.createElement("a");a.href=s,a.download=e,document.body.appendChild(a),a.click(),a.remove(),window.setTimeout(()=>URL.revokeObjectURL(s),0)}class o6{constructor(e){this.options=e}session=null;sessionPromise=null;installEventListeners(e){const{elements:t}=this.options;t.capture.addEventListener("click",()=>{this.captureShot()},{signal:e}),t.newPack.addEventListener("click",()=>{this.newPack()},{signal:e}),t.download.addEventListener("click",()=>{this.download()},{signal:e}),t.load.addEventListener("click",()=>t.loadInput.click(),{signal:e}),t.loadInput.addEventListener("change",()=>{const i=t.loadInput.files?.[0]??null;t.loadInput.value="",i&&this.loadPackFile(i)},{signal:e}),t.name.addEventListener("change",()=>this.session?.file.setName(t.name.value||null),{signal:e}),t.creator.addEventListener("change",()=>this.session?.file.setCreatorName(t.creator.value||null),{signal:e}),t.description.addEventListener("change",()=>this.session?.file.setDescription(t.description.value||null),{signal:e}),t.difficulty.addEventListener("change",()=>this.session?.file.setDifficulty(t.difficulty.value),{signal:e}),this.sync()}sync(){const{elements:e}=this.options,t=this.options.getReplayPlayer();e.capture.disabled=!t,e.shooter.disabled=!t,this.populateShooterOptions(t),this.renderShotList()}populateShooterOptions(e){const{shooter:t}=this.options.elements,i=t.value;t.replaceChildren(),t.append(new Option("Followed player (camera)",""));for(const s of e?.replay.players??[])t.append(new Option(s.name,s.id));[...t.options].some(s=>s.value===i)&&(t.value=i)}async ensureSession(){if(this.session)return this.session;this.sessionPromise??=mo.createNew();const e=await this.sessionPromise;return this.session||this.adoptSession(e),this.session??e}adoptSession(e){this.session=e,this.sessionPromise=null;const{elements:t}=this.options;t.name.value=e.file.name??"",t.creator.value=e.file.creatorName??"",t.description.value=e.file.description??"";const i=e.file.difficulty;[...t.difficulty.options].some(s=>s.value===i)&&(t.difficulty.value=i),this.renderShotList()}resolveShooter(e,t){const i=this.options.elements.shooter.value||null,s=e.getState().attachedPlayerId,a=e.replay.players,r=[...a.filter(o=>o.id===(i??s)),...a];for(const o of r){const l=o.frames[t];if(l?.position)return i&&o.id!==i?null:{track:o,sample:l}}return null}timeLimitSeconds(){const e=Number(this.options.elements.timeLimit.value);return!Number.isFinite(e)||e<0?$T:e}async captureShot(){const e=this.options.getReplayPlayer();if(!e){this.setStatus("No replay loaded.");return}const t=e.getState(),i=e.replay.ballFrames[t.frameIndex];if(!i?.position){this.setStatus("No ball state on the current frame.");return}const s=this.resolveShooter(e,t.frameIndex);if(!s){this.setStatus("Selected shooter has no car state on the current frame.");return}const a=await this.ensureSession(),r={position:s.sample.position,rotation:s.sample.rotation,linearVelocity:s.sample.linearVelocity},o=a.captureShot({ball:{position:i.position,linearVelocity:i.linearVelocity},shooter:r,timeLimit:this.timeLimitSeconds()},t.currentTime);this.renderShotList(),this.setStatus(a6(o+1,s.track.name,wi(t.currentTime),k3(r)))}async loadPackFile(e){if(!(this.session?.hasUnsavedShots&&!window.confirm("Discard unsaved captured shots and open this pack?")))try{const t=await mo.loadFromBytes(await e.arrayBuffer());this.adoptSession(t),this.setStatus(`Opened ${e.name} (${t.shotCount} shot${t.shotCount===1?"":"s"}); captures will append.`)}catch(t){console.error("Failed to load training pack:",t),this.setStatus(t instanceof Error?t.message:"Failed to load training pack.")}}async newPack(){if(!(this.session?.hasUnsavedShots&&!window.confirm("Discard unsaved captured shots and start a new pack?")))try{this.adoptSession(await mo.createNew()),this.setStatus("Started a new pack.")}catch(e){console.error("Failed to create training pack:",e),this.setStatus(e instanceof Error?e.message:"Failed to create training pack.")}}async download(){const e=await this.ensureSession();if(e.shotCount===0){this.setStatus("No shots to download; capture one first.");return}try{r6(e.toBytes(),e.downloadFileName()),this.setStatus(`Downloaded ${e.downloadFileName()}.`)}catch(t){console.error("Failed to serialize training pack:",t),this.setStatus(t instanceof Error?t.message:"Failed to serialize pack.")}}renderShotList(){const{shotList:e}=this.options.elements;e.replaceChildren();const t=this.session;if(t)for(const i of t.shots()){const s=document.createElement("li"),a=document.createElement("span"),r=i.sourceReplayTime===null?"loaded":`at ${wi(i.sourceReplayTime)}`,o=i.timeLimit===0?"no limit":`${i.timeLimit}s`;a.textContent=`Shot ${i.index+1} — ${r} — ${o}`;const l=document.createElement("button");l.type="button",l.textContent="Remove",l.addEventListener("click",()=>{t.removeShot(i.index),this.renderShotList(),this.setStatus(`Removed shot ${i.index+1}.`)}),s.append(a,l),e.appendChild(s)}}setStatus(e){this.options.elements.status.textContent=e}}function l6(n){return new o6(n)}class c6{constructor(e){this.options=e}activeModules=[];activeTimelineEventSourceIds=new Set;activeTimelineRangeModuleIds=new Set;activeMechanicTimelineKinds=new Set;activeRenderEffectModuleIds=new Set;removeRenderHook=null;timelineSourceRemovers=new Map;timelineRangeSourceRemovers=new Map;getActiveModules(){return this.activeModules}getActiveTimelineEventSourceIds(){return this.activeTimelineEventSourceIds}getActiveTimelineRangeModuleIds(){return this.activeTimelineRangeModuleIds}getActiveMechanicTimelineKinds(){return this.activeMechanicTimelineKinds}getActiveRenderEffectModuleIds(){return this.activeRenderEffectModuleIds}getActiveCapabilityIds(e){return e==="events"?this.activeTimelineEventSourceIds:e==="ranges"?this.activeTimelineRangeModuleIds:this.activeRenderEffectModuleIds}getBoostPadOverlayEnabled(){return!0}getTimelineEventSourceIds(){return[...this.activeTimelineEventSourceIds]}getTimelineRangeModuleIds(){return[...this.activeTimelineRangeModuleIds]}getMechanicTimelineKinds(){return[...this.activeMechanicTimelineKinds]}getRenderEffectModuleIds(){return[...this.activeRenderEffectModuleIds]}applyOverlayConfig({timelineEvents:e,timelineRanges:t,mechanics:i,renderEffects:s,boostPads:a}){this.activeTimelineEventSourceIds=new Set(e),this.activeTimelineRangeModuleIds=new Set(t),this.activeMechanicTimelineKinds=new Set(i),this.activeRenderEffectModuleIds=new Set(s)}reset(){this.teardownActiveModules(),this.clearStandalonePlugins(),this.activeModules=[],this.activeTimelineEventSourceIds=new Set,this.activeTimelineRangeModuleIds=new Set,this.activeMechanicTimelineKinds=new Set,this.activeRenderEffectModuleIds=new Set,this.removeRenderHook=null}setupActiveModules(){this.teardownActiveModules();const e=this.options.getContext();if(!e)return;const t=this.getActiveModuleIds();this.activeModules=this.options.modules.filter(i=>t.has(i.id)),this.options.boostPickupFilters.setup(e);for(const i of this.activeModules)i.setup(e);this.removeRenderHook=e.player.onBeforeRender(i=>{for(const s of this.activeModules)this.activeRenderEffectModuleIds.has(s.id)&&s.onBeforeRender(i)}),this.syncTimelineEvents(),this.syncTimelineRanges()}teardownActiveModules(){this.removeRenderHook?.(),this.removeRenderHook=null,this.clearTimelineEventSources(),this.clearTimelineRangeSources();for(const e of this.activeModules)e.teardown();this.activeModules=[]}toggleCapability(e,t,i){const s=this.getMutableActiveCapabilityIds(t);i?s.add(e):s.delete(e),this.setupActiveModules(),this.options.renderModuleSummary(),this.options.renderModuleSettings(),this.options.renderStatsWindows(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()}setMechanicTimelineKind(e,t){t?this.activeMechanicTimelineKinds.add(e):this.activeMechanicTimelineKinds.delete(e),this.options.requestConfigSync()}activateMechanicTimelineKind(e){this.activeMechanicTimelineKinds.add(e),this.syncTimelineEvents(),this.syncTimelineRanges(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()}clearTimelineEventSources(){for(const e of this.timelineSourceRemovers.values())e();this.timelineSourceRemovers.clear()}clearTimelineRangeSources(){for(const e of this.timelineRangeSourceRemovers.values())e();this.timelineRangeSourceRemovers.clear()}clearStandalonePlugins(){}syncBoostPadOverlayPlugin(){}toggleBoostPadOverlay(){this.options.renderModuleSummary(),this.options.requestConfigSync()}syncTimelineEvents(){this.clearTimelineEventSources();const e=this.options.getContext(),t=this.options.getTimelineOverlay();if(!(!t||!e)){for(const i of this.options.getEventTimelineSources(e)){if(!i.active)continue;const s=i.buildTimelineEvents();s.length!==0&&this.timelineSourceRemovers.set(i.timelineKey,t.addEventSource(this.options.withTimelineEventSeekTimes(s),{id:i.timelineId,label:i.label}))}t.refreshEvents()}}syncTimelineRanges(){this.clearTimelineRangeSources();const e=this.options.getContext(),t=this.options.getTimelineOverlay();if(!(!t||!e)){for(const i of this.activeModules)!this.activeTimelineRangeModuleIds.has(i.id)||!i.getTimelineRanges||this.timelineRangeSourceRemovers.set(i.id,t.addRangeSource(()=>i.getTimelineRanges?.(e)??[]));for(const i of this.options.getEventTimelineSources(e)){if(!i.active||!i.buildTimelineRanges)continue;const s=i.buildTimelineRanges();s.length!==0&&this.timelineRangeSourceRemovers.set(i.timelineKey,t.addRangeSource(s))}t.refreshRanges()}}getActiveModuleIds(){return new Set([...this.activeTimelineEventSourceIds,...this.activeTimelineRangeModuleIds,...this.activeRenderEffectModuleIds])}getMutableActiveCapabilityIds(e){return e==="events"?this.activeTimelineEventSourceIds:e==="ranges"?this.activeTimelineRangeModuleIds:this.activeRenderEffectModuleIds}}function u6(n){return new c6(n)}function Jn(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function ew(n){return Jn(n)&&(n.kind==="time"||n.kind==="frame")&&typeof n.value=="number"&&Number.isFinite(n.value)?{kind:n.kind,value:n.value}:null}function Hu(n,e){if(n!=null){if(typeof n!="number"||!Number.isInteger(n)||!Number.isFinite(n)||n<0)throw new Error(`Review playlist page ${e} must be a non-negative integer.`);return n}}function tw(n,e){if(n!=null){if(typeof n!="string")throw new Error(`Review playlist page ${e} must be a string.`);return n}}function d6(n){if(n!=null){if(!Jn(n))throw new Error("Review playlist page must be an object.");return{next:tw(n.next,"next"),previous:tw(n.previous,"previous"),total:Hu(n.total,"total"),count:Hu(n.count,"count"),limit:Hu(n.limit,"limit"),offset:Hu(n.offset,"offset")}}}function h6(n){if(n!=null){if(!Jn(n))throw new Error("Review playlist playback must be an object.");if(n.timeBase!==void 0&&n.timeBase!=="playback"&&n.timeBase!=="rawReplay")throw new Error('Review playlist playback timeBase must be "playback" or "rawReplay".');return{...n,timeBase:n.timeBase}}}function f6(n,e){if(n==null)return;if(!Jn(n))throw new Error(`Review item ${e} perspective must be an object.`);if(n.kind!=="player")throw new Error(`Review item ${e} perspective kind must be "player".`);const t=typeof n.playerId=="string"&&n.playerId.trim()?n.playerId.trim():void 0,i=typeof n.playerName=="string"&&n.playerName.trim()?n.playerName.trim():void 0;if(!t&&!i)throw new Error(`Review item ${e} player perspective needs playerId or playerName.`);if(n.ballCam!==void 0&&n.ballCam!=="off"&&n.ballCam!=="on"&&n.ballCam!=="player")throw new Error(`Review item ${e} perspective ballCam must be off, on, or player.`);if(n.usePlayerCameraSettings!==void 0&&typeof n.usePlayerCameraSettings!="boolean")throw new Error(`Review item ${e} perspective usePlayerCameraSettings must be boolean.`);return{kind:"player",playerId:t,playerName:i,ballCam:n.ballCam,usePlayerCameraSettings:n.usePlayerCameraSettings}}function p6(n){if(!Jn(n)||!Array.isArray(n.items))throw new Error("Review playlist must contain an items array.");const e=n.items.map((i,s)=>{if(!Jn(i)||typeof i.replay!="string")throw new Error(`Invalid review item at index ${s}.`);const a=ew(i.start),r=ew(i.end);if(!a||!r)throw new Error(`Review item ${s+1} has invalid start or end.`);return{id:typeof i.id=="string"?i.id:void 0,replay:i.replay,start:a,end:r,label:typeof i.label=="string"?i.label:void 0,perspective:f6(i.perspective,s+1),meta:Jn(i.meta)?i.meta:void 0}}),t=Array.isArray(n.replays)?n.replays.map(i=>!Jn(i)||typeof i.id!="string"?null:{id:i.id,path:typeof i.path=="string"?i.path:void 0,label:typeof i.label=="string"?i.label:void 0,locator:Jn(i.locator)?i.locator:void 0,meta:Jn(i.meta)?i.meta:void 0}).filter(i=>i!==null):void 0;return{label:typeof n.label=="string"?n.label:void 0,replays:t,items:e,page:d6(n.page),playback:h6(n.playback),meta:n.meta}}function nw(n){let e;try{e=JSON.parse(n)}catch(t){throw new Error(`Invalid review playlist JSON: ${t instanceof Error?t.message:String(t)}`)}return p6(e)}function m6(){const n=new URLSearchParams(window.location.search);return n.get("reviewPlaylist")?.trim()||n.get("review")?.trim()||n.get("playlist")?.trim()||n.get("playlistUrl")?.trim()||null}function _6(n){return/^\/(?:home|Users|tmp|var\/tmp|mnt|media|run\/user|nix\/store)\//.test(n)}function y1(n,e){const t=n.startsWith("path:")?n.slice(5):n;if(/^https?:\/\//i.test(t)||t.startsWith("/@fs/"))return t;if(t.startsWith("/")){if(_6(t))return`/@fs${t}`;if(e){const i=new URL(e,window.location.href);if(i.origin!==window.location.origin)return new URL(t,i.origin).href}return t}return e?new URL(t,e).href:t}function dd(n,e){const t=e.replaysById.get(n.replay);if(t?.path)return t.path;if(Jn(t?.locator)&&t.locator.kind==="path"&&typeof t.locator.path=="string")return t.locator.path;if(/^https?:\/\//i.test(n.replay)||n.replay.startsWith("/")||n.replay.startsWith("/@fs/")||n.replay.startsWith("path:"))return n.replay;throw new Error(`Review replay "${n.replay}" does not include a loadable path.`)}function iw(n,e){const t=e.replaysById.get(n.replay),s=(t?.path??dd(n,e)).replace(/^path:/,"").split("/").filter(Boolean).pop();return t?.label??s??"review replay"}function hd(n){return typeof n=="number"&&Number.isFinite(n)?`${n.toFixed(2)}s`:"--"}function sw(n){return n.kind==="time"?hd(n.value):`frame ${Math.trunc(n.value)}`}function qi(n,e){if(!Jn(n.meta?.target))return null;const t=n.meta.target[e];return typeof t=="number"&&Number.isFinite(t)?t:null}function fd(n,e){if(!Jn(n.meta?.target))return null;const t=n.meta.target[e];return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):null}function g6(n,e){for(const[t,i]of[["eventTime","eventFrame"],["startTime","startFrame"],["endTime","endFrame"]]){const s=qi(n,t),a=fd(n,i),r=a===null?null:e.frames[a]?.time;if(s!==null&&typeof r=="number"&&Number.isFinite(r))return s-r}return 0}function v1(n,e,t){return t==="playback"?0:t==="rawReplay"&&typeof e.rawStartTime=="number"&&Number.isFinite(e.rawStartTime)?e.rawStartTime:g6(n,e)}function D_(n,e){return Math.min(Math.max(0,n),Math.max(0,e))}function y6(n,e,t,i){if(e.kind==="frame"){const a=Math.max(0,Math.trunc(e.value));return D_(t.frames[a]?.time??0,t.duration)}const s=v1(n,t,i);return D_(e.value-s,t.duration)}function v6(n,e,t){const i=M6(n);return i===null?null:D_(i-v1(n,e,t),e.duration)}function b6(n){const e=n.start.kind==="time"?n.start.value:null,t=n.end.kind==="time"?n.end.value:null,i=[`${sw(n.start)} to ${sw(n.end)}`];e!==null&&t!==null&&i.push(`${Math.max(0,t-e).toFixed(1)}s clip`);const s=qi(n,"startTime")??qi(n,"eventTime"),a=qi(n,"endTime")??qi(n,"eventTime");return e!==null&&s!==null&&i.push(`${Math.max(0,s-e).toFixed(1)}s preroll`),t!==null&&a!==null&&i.push(`${Math.max(0,t-a).toFixed(1)}s postroll`),i.join(" · ")}function x6(n){const e=qi(n,"eventTime"),t=qi(n,"startTime"),i=qi(n,"endTime"),s=fd(n,"eventFrame"),a=fd(n,"startFrame"),r=fd(n,"endFrame"),o=t!==null&&i!==null&&Math.abs(i-t)>.001?`${hd(t)} to ${hd(i)}`:hd(e??t??i),l=a!==null&&r!==null&&r!==a?`frames ${a}-${r}`:s!==null?`frame ${s}`:a!==null?`frame ${a}`:null;return[o,l].filter(c=>c&&c!=="--").join(" · ")||"--"}function gm(n,e){return n.label??n.meta?.eventTypeLabel??n.meta?.mechanicLabel??`Review item ${e+1}`}function w6(n){if(typeof n.meta?.playerName=="string"&&n.meta.playerName.trim())return n.meta.playerName.trim();if(Jn(n.meta?.target)&&typeof n.meta.target.playerName=="string"){const e=n.meta.target.playerName.trim();return e||null}return null}function aw(n,e){if(!n)return null;if(n.playerId){const i=e.find(s=>s.id===n.playerId);if(i)return i}const t=n.playerName?.toLowerCase();return t?e.find(i=>i.name.trim().toLowerCase()===t)??null:null}function rw(n){if(typeof n.meta?.eventTypeLabel=="string"&&n.meta.eventTypeLabel.trim())return n.meta.eventTypeLabel;if(typeof n.meta?.mechanicLabel=="string"&&n.meta.mechanicLabel.trim())return n.meta.mechanicLabel;const e=n.meta?.eventType??n.meta?.mechanic;return typeof e=="string"?Ai(e):"--"}function S6(n){const e=n.meta?.eventCategory;return typeof e=="string"&&e.trim()?Ai(e.trim()):"--"}function T6(n){const e=n.meta?.eventType??n.meta?.mechanic;return typeof e=="string"&&e.trim()?e.trim().replaceAll("-","_"):null}function M6(n){return qi(n,"eventTime")??qi(n,"startTime")??qi(n,"endTime")}class E6{constructor(e){this.options=e}createReplaySource(e,t,i){const s=dd(e,t),a=y1(s,t.sourceUrl);return{name:iw(e,t),preparingStatus:"Loading review replay...",async readBytes(){const r=await fetch(a,{signal:i});if(!r.ok){const o=r.statusText?` ${r.statusText}`:"";throw new Error(`Failed to fetch review replay from ${a} (${r.status}${o})`)}return new Uint8Array(await r.arrayBuffer())}}}initialize(e){const t=this.getReplayClipCounts(e);for(const[i,s]of this.getReplayItems(e)){let a="",r=i;try{a=dd(s,e),r=iw(s,e)}catch{r=e.replaysById.get(i)?.label??i}e.replayLoadStates.set(i,{replayId:i,label:r,path:a,clipCount:t.get(i)??0,status:"idle",progress:null,error:null})}}preload(e,t){if(e.preloading)return;const i=this.getNextReplayItems(e,t);i.length!==0&&(e.preloading=!0,(async()=>{try{for(const s of i){const a=s.replay,r=e.replayLoadStates.get(a);if(!(r?.status==="loaded"||r?.status==="loading"))try{await this.loadBundle(s,e)}catch{}}}finally{e.preloading=!1}})())}loadBundle(e,t){const i=t.replayLoadCache.get(e.replay);if(i)return i;const s=this.createReplaySource(e,t);this.updateLoadState(t,e.replay,{label:s.name,path:dd(e,t),status:"loading",progress:null,error:null});const a=Promise.resolve().then(async()=>{const r=await s.readBytes();return fE(r,{reportEveryNFrames:100,onProgress:o=>{this.updateLoadState(t,e.replay,{status:"loading",progress:o,error:null})}})}).then(r=>(this.updateLoadState(t,e.replay,{status:"loaded",progress:null,error:null}),r)).catch(r=>{throw t.replayLoadCache.delete(e.replay),this.updateLoadState(t,e.replay,{status:"error",error:r instanceof Error?r.message:String(r)}),r});return t.replayLoadCache.set(e.replay,a),a}render(e){const{reviewSummary:t,loadingSummary:i,loadingActive:s,loadingList:a}=this.options.elements,r=e?Array.from(e.replayLoadStates.values()):[],o=r.filter(h=>h.status==="loaded").length,l=r.filter(h=>h.status==="loading").length,c=r.filter(h=>h.status==="error").length,u=r.filter(h=>h.status==="idle").length,d=r.length===0?"0 replays":`${o}/${r.length} loaded${l>0?`, ${l} loading`:""}${c>0?`, ${c} failed`:""}`;if(t.textContent=d,i.textContent=d,s.textContent=r.length===0?"No playlist":l>0?`${l} active, ${u} pending`:c>0?`${c} failed`:e?.preloading?`Background queue, ${u} pending`:o===r.length?"Complete":`${u} pending`,a.replaceChildren(),!e||r.length===0){const h=document.createElement("p");h.className="stat-window-empty",h.textContent="No replay sources.",a.append(h);return}for(const h of r){const f=document.createElement("div");f.className=`mechanics-review-replay-load ${h.status}`;const p=document.createElement("div");p.className="mechanics-review-replay-load-main";const g=document.createElement("span");g.className="mechanics-review-replay-load-title",g.textContent=h.label;const _=document.createElement("span");_.className="mechanics-review-replay-load-meta",_.textContent=[h.replayId,`${h.clipCount} ${h.clipCount===1?"clip":"clips"}`,h.path].filter(Boolean).join(" · "),p.append(g,_);const m=document.createElement("strong");m.className="mechanics-review-replay-load-status",m.textContent=this.replayLoadStatusText(h);const v=document.createElement("div");v.className="mechanics-review-replay-load-progress";const y=document.createElement("span");y.style.width=`${Math.round(this.replayLoadProgressValue(h)*100)}%`,v.append(y),f.append(p,m,v),a.append(f)}}updateLoadState(e,t,i){const s=e.replayLoadStates.get(t)??{replayId:t,label:t,path:"",clipCount:0,status:"idle",progress:null,error:null};e.replayLoadStates.set(t,{...s,...i});const a=e.manifest.items[e.currentIndex];e.loading&&a?.replay===t&&i.progress&&this.options.onActiveLoadProgress(i.progress),this.options.isActiveReview(e)&&this.render(e)}getReplayItems(e){const t=new Map;for(const i of e.manifest.items)t.has(i.replay)||t.set(i.replay,i);return t}getReplayClipCounts(e){const t=new Map;for(const i of e.manifest.items)t.set(i.replay,(t.get(i.replay)??0)+1);return t}getNextReplayItems(e,t){const i=e.manifest.items[t]?.replay,s=new Set(i?[i]:[]),a=[];for(let r=t+1;r{const i=t.file.files?.[0];if(i)try{const s=nw(await i.text());await this.loadPlaylist(s,null)}catch(s){console.error("Failed to load review playlist:",s),this.setStatus(s instanceof Error?s.message:"Failed to load review playlist")}finally{t.file.value=""}},{signal:e}),t.loadUrl.addEventListener("click",()=>{this.loadPlaylistFromUrl(t.url.value.trim()).catch(i=>{console.error("Failed to load review playlist URL:",i),this.setStatus(i instanceof Error?i.message:"Failed to load review playlist URL")})},{signal:e}),t.previous.addEventListener("click",()=>{const i=this.activeReview;i&&this.activateItem(Math.max(0,i.currentIndex-1))},{signal:e}),t.replay.addEventListener("click",()=>this.replayClip(),{signal:e}),t.next.addEventListener("click",()=>{const i=this.activeReview;i&&this.activateItem(Math.min(i.manifest.items.length-1,i.currentIndex+1))},{signal:e}),t.confirm.addEventListener("click",()=>{this.submitDecision("confirmed")},{signal:e}),t.reject.addEventListener("click",()=>{this.submitDecision("rejected")},{signal:e}),t.uncertain.addEventListener("click",()=>{this.submitDecision("uncertain")},{signal:e})}render(){const{elements:e}=this.options,t=this.activeReview,i=t?.manifest.items??[],s=t?i[t.currentIndex]??null:null,a=i.length>0;e.count.textContent=`${i.length} item${i.length===1?"":"s"}`,e.index.textContent=a&&t?`${t.currentIndex+1} / ${i.length}`:"0 / 0",e.title.textContent=s?gm(s,t?.currentIndex??0):"No candidate selected",e.mechanic.textContent=s?rw(s):"--",e.player.textContent=s?this.getPlayerName(s):"--",e.clip.textContent=s?b6(s):"--",e.event.textContent=s?x6(s):"--",e.reason.textContent=s?.meta?.reason??"--",e.previous.disabled=!t||t.loading||t.currentIndex<=0,e.replay.disabled=!t||t.loading||!t.currentClip,e.next.disabled=!t||t.loading||t.currentIndex>=i.length-1;const r=!t||t.loading||ow(s)===null;if(e.confirm.disabled=r,e.reject.disabled=r,e.uncertain.disabled=r,this.options.replayLoads.render(t),e.list.replaceChildren(),!t||i.length===0){const o=document.createElement("p");o.className="stat-window-empty",o.textContent="No review playlist loaded.",e.list.append(o);return}i.forEach((o,l)=>{const c=document.createElement("button");c.type="button",c.className="mechanics-review-item",c.dataset.active=l===t.currentIndex?"true":"false",c.disabled=t.loading,c.addEventListener("click",()=>{this.activateItem(l)});const u=document.createElement("span");u.textContent=gm(o,l);const d=document.createElement("strong");d.textContent=[S6(o),rw(o),this.getPlayerName(o),ym(o.meta?.reviewStatus)].filter(h=>h&&h!=="--").join(" · ")||"--",c.append(u,d),e.list.append(c)})}async loadPlaylist(e,t){const i=new Map;for(const s of e.replays??[])i.set(s.id,s);this.activeReview={manifest:e,sourceUrl:t,replaysById:i,replayLoadStates:new Map,replayLoadCache:new Map,currentIndex:0,loading:!1,preloading:!1,currentReplayId:null,currentClip:null},this.options.replayLoads.initialize(this.activeReview),this.options.showReplayLoadingWindow(),this.setStatus(e.label?`Loaded ${e.label}.`:"Loaded review playlist."),this.render(),e.items.length>0&&await this.activateItem(0)}async loadPlaylistFromUrl(e){if(!e){this.setStatus("Enter a review playlist URL.");return}const t=y1(e,window.location.href);this.setStatus("Loading review playlist...");const i=await fetch(t);if(!i.ok){const a=i.statusText?` ${i.statusText}`:"";throw new Error(`Failed to fetch review playlist from ${t} (${i.status}${a})`)}const s=nw(await i.text());await this.loadPlaylist(s,i.url||t)}async activateItem(e){const t=this.activeReview,i=t?.manifest.items[e];if(!(!t||!i||t.loading)){t.loading=!0,t.currentIndex=e,this.render(),this.setStatus(`Loading ${gm(i,e)}...`);try{if(!this.options.getReplayPlayer()||t.currentReplayId!==i.replay){const d=this.options.replayLoads.createReplaySource(i,t),h=this.options.replayLoads.loadBundle(i,t);await this.options.loadReplayBundleForDisplay(d,h),t.currentReplayId=i.replay}this.options.replayLoads.preload(t,e);const a=t.manifest.playback?.timeBase,r=Math.max(0,this.getBoundTime(i,i.start,a)),o=Math.min(this.options.getReplayPlayer()?.getState().duration??Number.POSITIVE_INFINITY,Math.max(r,this.getBoundTime(i,i.end,a)));if(!Number.isFinite(r)||!Number.isFinite(o)||o<=r)throw new Error("Review item has an empty playback range.");const l=this.options.getReplayPlayer(),c=l?aw(i.perspective,l.replay.players):null;c&&this.options.applyClipPerspective({playerId:c.id,ballCam:i.perspective?.ballCam,usePlayerCameraSettings:i.perspective?.usePlayerCameraSettings}),this.options.resetReplayTransitionControls();const u=l===null?null:v6(i,l.replay,a);t.currentClip={startTime:r,endTime:o,targetTime:u},this.options.activateTimelineSource(i),this.options.getReplayPlayer()?.setState({currentTime:r,playing:!0,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),this.setStatus(u===null?`Playing ${r.toFixed(2)}s to ${o.toFixed(2)}s`:`Playing ${r.toFixed(2)}s to ${o.toFixed(2)}s; target ${u.toFixed(2)}s`)}catch(s){console.error("Failed to activate mechanics review item:",s),t.currentClip=null,this.setStatus(s instanceof Error?s.message:"Failed to load review item")}finally{t.loading=!1,this.render()}}}replayClip(){const e=this.activeReview?.currentClip,t=this.options.getReplayPlayer();!e||!t||t.setState({currentTime:e.startTime,playing:!0,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1})}async submitDecision(e){const t=this.activeReview,i=t?.manifest.items[t.currentIndex]??null,s=ow(i);if(!t||!i||!s){this.setStatus("Current review item has no review endpoint.");return}this.setStatus(`Submitting ${ym(e)}...`);const a=await fetch(s,{method:"POST",headers:{"content-type":"application/json",...R6()},credentials:"same-origin",body:JSON.stringify({status:e})});if(!a.ok){let r=`${a.status}${a.statusText?` ${a.statusText}`:""}`;try{const o=await a.json();typeof o.error=="string"&&(r=o.error)}catch{}this.setStatus(`Review failed: ${r}`);return}i.meta=i.meta??{},i.meta.reviewStatus=e,this.setStatus(`Marked ${ym(e)}.`),this.render()}enforceClipBoundary(e){const t=this.activeReview?.currentClip,i=this.options.getReplayPlayer();if(!t||!i||this.boundaryGuard)return!1;const s=e.currentTime=t.endTime-.025;if(!s&&!a)return!1;this.boundaryGuard=!0;try{i.setState({currentTime:s?t.startTime:t.endTime,playing:!1,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),a&&this.setStatus(`Finished clip at ${t.endTime.toFixed(2)}s`)}finally{this.boundaryGuard=!1}return!0}getBoundTime(e,t,i){const s=this.options.getReplayPlayer();return s?y6(e,t,s.replay,i):t.kind==="time"?t.value:0}getPlayerName(e){const t=w6(e);if(t)return t;const i=this.options.getReplayPlayer()?.replay.players??[];return aw(e.perspective,i)?.name??"--"}}function ym(n){return typeof n=="string"&&n.trim()?n.replaceAll("_"," "):"unreviewed"}function ow(n){if(!n)return null;if(typeof n.meta?.reviewEndpoint=="string"&&n.meta.reviewEndpoint)return n.meta.reviewEndpoint;const e=typeof n.meta?.eventId=="string"&&n.meta.eventId?n.meta.eventId:n.id;return e?`/api/v1/events/${encodeURIComponent(e)}/reviews`:null}function R6(){const n=new URLSearchParams(window.location.search),e=n.get("reviewToken")??n.get("token")??window.localStorage.getItem("rocket_sense_access_token");return e?{Authorization:`Bearer ${e}`}:{}}function P6(n){return new A6(n)}const I6=["replayUrl","replay_url","replay"],L6=["r","replayUrlZ","replay_url_z"],k6=["ballchasing","ballchasingId","ballchasingUuid","ballchasingReplay"];function D6(n){const e=n.replaceAll("-","+").replaceAll("_","/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=atob(t),s=new Uint8Array(i.length);for(let a=0;a{n.signal.aborted||(console.error("Failed to load replay URL:",t),n.statusReadout.textContent=t instanceof Error?t.message:"Failed to load replay URL")})}function H6(n){n.initialBundle?n.loadReplayBundleForDisplay({name:n.initialReplayName??"replay",preparingStatus:"Preparing replay...",async readBytes(){throw new Error("Replay bytes are not available for this preloaded replay")}},Promise.resolve(n.initialBundle)).catch(i=>{n.signal.aborted||(console.error("Failed to load preprocessed replay bundle:",i),n.statusReadout.textContent=i instanceof Error?i.message:"Failed to load preprocessed replay bundle")}):n.loadFromLocation!==!1&&z6(n);const e=m6();if(!e)return;const t=n.getMechanicsReviewController();t?.setUrl(e),n.showMechanicsReviewWindow(),t?.loadPlaylistFromUrl(e).catch(i=>{n.signal.aborted||(console.error("Failed to load mechanics review playlist from URL:",i),t?.setStatus(i instanceof Error?i.message:"Failed to load mechanics review playlist from URL"))})}function V6(n){const e=()=>{n.getSkipPostGoalTransitions().checked=!1,n.getSkipKickoffs().checked=!1},t=(i,s)=>{const a=n.getReplayPlayer();!a||!Number.isFinite(i)||(n.getMechanicsReviewController()?.clearCurrentClip(),e(),a.setState({currentTime:Math.max(0,i-n.goalWatchLeadSeconds),playing:s,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),n.scheduleConfigUrlUpdate())};return{watchGoalReplay(i,s){const a=n.getReplayPlayer();if(!a||!Number.isFinite(i))return;if(n.getMechanicsReviewController()?.clearCurrentClip(),s!==null&&a.replay.players.some(o=>o.id===s)){a.setAttachedPlayer(s),a.setCameraViewMode("follow");const o=n.getCameraControlsController();o&&(o.freeCameraPreset=null)}e(),a.setState({currentTime:Math.max(0,i-n.goalWatchLeadSeconds),playing:!0,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),n.scheduleConfigUrlUpdate()},cueGoalReplay(i){t(i,!1)},cueTimelineEvent(i){const s=n.getReplayPlayer();s&&(n.getMechanicsReviewController()?.clearCurrentClip(),e(),s.setState({currentTime:Ng(i),skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),n.scheduleConfigUrlUpdate())},applyConfigToReplayPlayer(i){const s=n.getReplayPlayer();if(!s)return;s.setState(A8(i.playback,i.camera,i));const a=n.getCameraControlsController();a&&(a.freeCameraPreset=i.camera.freePreset??null),i.camera.mode==="free"&&i.camera.freePreset&&s.setFreeCameraPreset(i.camera.freePreset),n.syncBoostPadOverlayPlugin(),n.setupActiveModules(),n.renderModuleSummary(),n.renderModuleSettings(),n.renderStatsWindows(s.getState().frameIndex)}}}function G6(n){let e=!1,t=null;const i=()=>n.getFloatingWindowController()?.getSingletonConfigs()??[],s=()=>n.getStatsWindowsController()?.getConfigs()??[],a=()=>{const o=n.getActiveModulesRuntime(),l=n.getReplayPlayer();return C8({playback:M8({replayPlayer:l,playbackRate:n.playbackRate,skipPostGoalTransitions:n.skipPostGoalTransitions,skipKickoffs:n.skipKickoffs}),camera:E8({replayPlayer:l,cameraControlsController:n.getCameraControlsController()}),activeTimelineEventSourceIds:o.getActiveTimelineEventSourceIds(),activeTimelineRangeModuleIds:o.getActiveTimelineRangeModuleIds(),activeMechanicTimelineKinds:o.getActiveMechanicTimelineKinds(),activeRenderEffectModuleIds:o.getActiveRenderEffectModuleIds(),initialConfig:n.getInitialConfig(),replayPlayer:l,boostPadOverlayEnabled:o.getBoostPadOverlayEnabled(),recording:n.getRecordingWindowController()?.getConfigSnapshot()??{},singletonWindows:i(),statsWindows:s(),moduleConfigs:T8(n.modules)})},r=o=>{v8(g1(n.modules),o)};return{setApplyingConfig(o){e=o},reset(){t!==null&&(window.clearTimeout(t),t=null),e=!1},scheduleConfigUrlUpdate(){e||(t!==null&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null;const o=jW(new URL(window.location.href),a());window.history.replaceState(window.history.state,"",o)},150))},applyConfigToStaticControls(o){if(n.getActiveModulesRuntime().applyOverlayConfig(o.overlays),n.skipPostGoalTransitions.checked=o.playback.skipPostGoalTransitions??n.skipPostGoalTransitions.checked,n.skipKickoffs.checked=o.playback.skipKickoffs??n.skipKickoffs.checked,n.hitboxWireframes.checked=o.overlays.hitboxWireframes,n.hitboxOnlyMode.checked=o.overlays.hitboxOnlyMode,n.getCameraControlsController()?.applyNameplateLiftUu(o.camera.nameplateLiftUu),n.getCameraControlsController()?.setAutoPossessionEnabled(o.camera.autoPossession??!1,{requestConfigSync:!1}),o.playback.rate!==void 0){const l=mf(o.playback.rate);n.playbackRate.value=`${l}`,n.playbackRateReadout.textContent=ty(l)}n.getRecordingWindowController()?.applyConfig(o.recording),r(o.moduleConfigs),n.getFloatingWindowController()?.applySingletonConfigs(o.singletonWindows),n.getStatsWindowsController()?.replaceFromConfig(o.statsWindows),n.renderModuleSummary(),n.renderModuleSettings(),n.renderTimelineEventCount()}}}function $6(n){const e=t=>{const i=n.getLauncherToggle();n.getLauncherMenu().hidden=!t,i.setAttribute("aria-label",t?"Close menu":"Open menu"),i.setAttribute("aria-expanded",t?"true":"false")};return{bringWindowToFront(t){n.getFloatingWindowController()?.bringToFront(t)},showWindow(t){n.getFloatingWindowController()?.show(t)},toggleWindow(t){n.getFloatingWindowController()?.toggle(t)},hideWindow(t){n.getFloatingWindowController()?.hide(t)},setLauncherOpen:e,openReplayFilePicker(){n.getFileInput().click(),e(!1)},installWindowDragging(t,i){n.getFloatingWindowController()?.installDragging(t,i)},getElementWindowId(t){return t.closest("[data-window-id]")?.dataset.windowId??null}}}const O_=4096,fr=5120,W6=893,X6=642,Yi=1/105;class K6{constructor(e){this.options=e,this.options.body.innerHTML=`
@@ -5920,4 +5985,4 @@ void main() {

Load a replay with shot events.

- `,this.chartCanvas=this.mustElement("#shot-chart-canvas"),this.shotList=this.mustElement("#shot-list"),this.summary=this.mustElement("#shot-visualization-summary"),this.details=this.mustElement("#shot-details"),this.sceneRoot=this.mustElement("#shot-demo-scene"),this.emptyState=this.mustElement("#shot-visualization-empty"),this.chartCanvas.addEventListener("click",t=>this.handleChartClick(t))}chartCanvas;shotList;summary;details;sceneRoot;emptyState;renderer=null;scene=null;camera=null;resizeObserver=null;selectedShotId=null;cachedReplay=null;cachedShots=[];lastShotsSignature="";lastListSelectionKey=null;lastSelectedShotKey=null;shotButtons=new Map;destroy(){this.resizeObserver?.disconnect(),this.renderer?.dispose(),this.renderer=null,this.scene=null,this.camera=null}render(e=this.options.getReplayPlayer()?.getState()??null){const t=this.shotEvents(),i=e?.currentTime??null;this.findSelectedShot(t)||(this.selectedShotId=t[0]?this.shotKey(t[0],0):null);const s=this.findSelectedShot(t),a=s?.key??null,r=this.shotsSignature(t),o=r!==this.lastShotsSignature;this.emptyState.hidden=t.length>0,o&&(this.summary.textContent=this.summaryText(t)),o||a!==this.lastListSelectionKey?(this.renderShotList(t,i,a),this.lastListSelectionKey=a):this.updateShotListActiveState(t,i),this.renderChart(t,i),(o||a!==this.lastSelectedShotKey)&&(this.renderSelectedShot(s?.shot??null),this.lastSelectedShotKey=a),this.lastShotsSignature=r}shotEvents(){const e=this.options.getReplayPlayer()?.replay;return e?e===this.cachedReplay?this.cachedShots:(this.cachedReplay=e,this.cachedShots=e.timelineEvents.filter(f6),this.cachedShots):(this.cachedReplay=null,this.cachedShots=[],[])}summaryText(e){if(e.length===0)return"No shots";const t=e.filter(a=>a.shot.resulting_save).length,i=e.map(a=>a.shot.ball_speed).filter(a=>Number.isFinite(a)),s=i.length===0?null:i.reduce((a,r)=>a+r,0)/i.length;return`${e.length} shots | ${t} saved | avg ${Uu(s)}`}renderShotList(e,t,i){this.shotButtons.clear(),this.shotList.replaceChildren(...e.map((s,a)=>{const r=this.shotKey(s,a),o=document.createElement("button");o.type="button",o.className="shot-list-item",o.dataset.selected=String(r===i),o.dataset.active=String(hm(s,t)),o.addEventListener("click",()=>{this.selectedShotId=r,this.options.cueTimelineEvent(s),this.render()});const l=document.createElement("span");l.className="shot-list-title",l.textContent=s.playerName??s.playerId??`Shot ${a+1}`;const c=document.createElement("span");return c.className="shot-list-meta",c.textContent=`${nw(s.time)} | ${Uu(s.shot.ball_speed)} | ${s.shot.resulting_save?"saved":"unsaved"}`,o.append(l,c),this.shotButtons.set(r,o),o}))}updateShotListActiveState(e,t){e.forEach((i,s)=>{const a=this.shotButtons.get(this.shotKey(i,s));a&&(a.dataset.active=String(hm(i,t)))})}renderChart(e,t){const i=this.chartCanvas.getContext("2d");if(!i)return;const s=window.devicePixelRatio||1,a=this.chartCanvas.getBoundingClientRect(),r=Math.max(320,Math.round(a.width*s)),o=Math.max(220,Math.round(a.height*s));(this.chartCanvas.width!==r||this.chartCanvas.height!==o)&&(this.chartCanvas.width=r,this.chartCanvas.height=o),i.setTransform(s,0,0,s,0,0);const l=r/s,c=o/s;i.clearRect(0,0,l,c),p6(i,l,c),e.forEach((u,d)=>{const h=u.shot.shot_touch_position??u.shot.ball_position,f=ah(h,l,c),p=!!u.shot.resulting_save,g=hm(u,t),_=this.shotKey(u,d)===this.selectedShotId,m=_?6:g?5:4;i.beginPath(),i.arc(f.x,f.y,m,0,Math.PI*2),i.fillStyle=p?"#f2c14e":"#62d2a2",i.fill(),i.lineWidth=_?2.5:1.25,i.strokeStyle=_?"#f8fafc":g?"#e11d48":"rgba(4, 12, 20, 0.85)",i.stroke()})}renderSelectedShot(e){if(!e){this.details.replaceChildren(),this.clearThreeScene();return}this.details.replaceChildren(cl("Player",e.playerName??e.playerId??"--"),cl("Speed",Uu(e.shot.ball_speed)),cl("Toward goal",Uu(e.shot.ball_speed_toward_goal)),cl("Touch",_6(e.shot.shot_touch_position??e.shot.ball_position)),cl("Save",e.shot.resulting_save?nw(e.shot.resulting_save.time):"--")),this.renderThreeScene(e)}renderThreeScene(e){const t=this.ensureRenderer(),i=this.scene,s=this.camera;i.clear(),i.add(new dc(16777215,1.2));const a=new Do(16777215,1.7);a.position.set(18,28,22),i.add(a);const r=new we(new Dn(A_*2*qi,hr*2*qi),new Ye({color:1520422,side:ct}));r.rotation.x=-Math.PI/2,i.add(r);const o=new Rt({color:14280674,transparent:!0,opacity:.55});i.add(new Ln(new Bh(r.geometry),o)),i.add(ew(!0)),i.add(ew(!1));const l=tw(e.shot.shot_touch_position??e.shot.ball_position),c=tw(e.shot.target_goal_position),u=e.shot.ball_velocity,d=u?l.clone().add(m6(u).normalize().multiplyScalar(22)):c.clone(),h=new sg([l,l.clone().lerp(d,.45).setY(Math.max(l.y,d.y)+2.8),d]),f=new Ge().setFromPoints(h.getPoints(36));i.add(new In(f,new Rt({color:e.shot.resulting_save?15909198:6476450,linewidth:2})));const p=new we(new yn(.9,24,16),new Pn({color:16317180,roughness:.36}));p.position.copy(l),i.add(p);const g=new we(new ni(1.05,1.45,32),new Ye({color:8892372,side:ct}));g.position.copy(c),g.rotation.y=Math.PI/2,i.add(g),s.position.set(0,54,72),s.lookAt(0,0,0),t.render(i,s)}ensureRenderer(){if(this.renderer&&this.scene&&this.camera)return this.resizeThreeScene(),this.renderer;const e=new Eg({antialias:!0,alpha:!0,preserveDrawingBuffer:!0});return e.setPixelRatio(window.devicePixelRatio||1),this.sceneRoot.replaceChildren(e.domElement),this.renderer=e,this.scene=new ac,this.scene.background=new ue(463132),this.camera=new Jt(42,1,.1,500),this.resizeObserver=new ResizeObserver(()=>{this.resizeThreeScene();const t=this.shotEvents().find(i=>i.id===this.selectedShotId)??null;t&&this.renderThreeScene(t)}),this.resizeObserver.observe(this.sceneRoot),this.resizeThreeScene(),e}resizeThreeScene(){if(!this.renderer||!this.camera)return;const e=this.sceneRoot.getBoundingClientRect(),t=Math.max(240,Math.round(e.width)),i=Math.max(170,Math.round(e.height));this.camera.aspect=t/i,this.camera.updateProjectionMatrix(),this.renderer.setSize(t,i,!1)}clearThreeScene(){this.sceneRoot.replaceChildren(),this.renderer?.dispose(),this.renderer=null,this.scene=null,this.camera=null}handleChartClick(e){const t=this.shotEvents(),i=this.chartCanvas.getBoundingClientRect(),s={x:e.clientX-i.left,y:e.clientY-i.top};let a=null,r=Number.POSITIVE_INFINITY;for(const o of t){const l=ah(o.shot.shot_touch_position??o.shot.ball_position,i.width,i.height),c=Math.hypot(l.x-s.x,l.y-s.y);c`${this.shotKey(t,i)}:${t.time}:${t.shot.ball_speed}`).join("|")}}function f6(n){return n.kind==="shot"&&!!n.shot}function hm(n,e){return e!==null&&Math.abs(e-n.time)<1.5}function p6(n,e,t){n.fillStyle="#0f2b24",n.fillRect(0,0,e,t),n.strokeStyle="rgba(226, 241, 236, 0.74)",n.lineWidth=1.2,n.strokeRect(18,18,e-36,t-36),n.beginPath(),n.moveTo(18,t/2),n.lineTo(e-18,t/2),n.stroke(),n.beginPath(),n.arc(e/2,t/2,34,0,Math.PI*2),n.stroke();const s=ah({x:0,y:-hr},e,t),a=ah({x:0,y:hr},e,t);n.fillStyle="#4fa3ff",n.fillRect(s.x-28,s.y-4,56,8),n.fillStyle="#ff8a4c",n.fillRect(a.x-28,a.y-4,56,8)}function ah(n,e,t){const s=e-36,a=t-36;return{x:18+(n.x+A_)/(A_*2)*s,y:18+(1-(n.y+hr)/(hr*2))*a}}function ew(n){const e=new Mt,t=new Rt({color:n?16747084:5219327}),i=(n?hr:-hr)*qi,s=u6*qi,a=d6*qi,r=[new S(-s,0,i),new S(-s,a,i),new S(s,a,i),new S(s,0,i)];return e.add(new In(new Ge().setFromPoints(r),t)),e}function tw(n){return new S(n.x*qi,n.z*qi,n.y*qi)}function m6(n){return new S(n.x*qi,n.z*qi,n.y*qi)}function cl(n,e){const t=document.createElement("div"),i=document.createElement("dt");i.textContent=n;const s=document.createElement("dd");return s.textContent=e,t.append(i,s),t}function nw(n){return Number.isFinite(n)?`${n.toFixed(2)}s`:"--"}function Uu(n){return Number.isFinite(n)?`${Math.round(n)} uu/s`:"--"}function _6(n){return n?`${Math.round(n.x)}, ${Math.round(n.y)}, ${Math.round(n.z)}`:"--"}const g6=4,y6=100;let ot=null,Yg=null,rh=null,fo=null,po=null,oh=null,iw=0,Va=null;const uf=BE({refreshTimelineRanges(){hh()},rerenderCurrentState(){ot&&ot.setBoostPickupAnimationEnabled(ot.getState().boostPickupAnimationEnabled)},requestConfigSync(){mn()}}),cd=l$({rerenderCurrentState(){if(!ot)return;const n=ot.getState();pc(n.frameIndex)},refreshTimelineRanges(){hh()},requestConfigSync(){mn()}},{boostPickupFilters:uf}),_n=R8({modules:cd,boostPickupFilters:uf,getContext:_o,getReplayPlayer:()=>ot,getTimelineOverlay:()=>Yg,getEventTimelineSources:jg,withTimelineEventSeekTimes:m1,renderModuleSummary:Ja,renderModuleSettings:Qa,renderStatsWindows(){ot&&pc(ot.getState().frameIndex)},renderTimelineEventCount:Qr,requestConfigSync:mn}),vl=o6({goalWatchLeadSeconds:g6,getReplayPlayer:()=>ot,getCameraControlsController:()=>Bi,getMechanicsReviewController:()=>zi,getSkipPostGoalTransitions:()=>Ga,getSkipKickoffs:()=>$a,syncBoostPadOverlayPlugin:p1,setupActiveModules:dh,renderModuleSummary:Ja,renderModuleSettings:Qa,renderStatsWindows(n){pc(n)},scheduleConfigUrlUpdate:mn}),bi=c6({getFloatingWindowController:()=>aa,getLauncherMenu:()=>I_,getLauncherToggle:()=>P_,getFileInput:()=>lh});let bl=null,lh,u1,R_,sw,P_,I_,aw,rw,ow,lw,cw,uw,fm,pm,mm,_m,Bu,zu,dw,hw,fw,pw,ea,d1,h1,L_,Ga,Jr=null,$a,xl,wl,Hu=null,D_=Jl(),Bi=null,Sl=null,mw=null,mo=null,ec=null,tc=null,ch=null,zi=null,aa=null,k_=null,uh=null,ud=null,na=null,O_=null,As=null;function v6(n){return _n.getActiveCapabilityIds(n)}function b6(){}function _o(){return!ot||!fo||!po?null:{player:ot,replay:ot.replay,statsTimeline:fo,statsFrameLookup:po,fieldScale:1}}function dh(){_n.setupActiveModules()}function f1(){_n.teardownActiveModules()}function _w(n,e,t){_n.toggleCapability(n,e,t)}function x6(){_n.clearTimelineEventSources()}function w6(){_n.clearTimelineRangeSources()}function S6(){_n.clearStandalonePlugins()}function p1(){_n.syncBoostPadOverlayPlugin()}function gw(){_n.syncTimelineEvents()}function hh(){_n.syncTimelineRanges()}function Qr(){const n=_o();if(!n){L_.textContent="--";return}L_.textContent=`${T6(n)}`}function T6(n){return tc?.countVisibleSources(n)??0}function ae(n,e){const t=n.querySelector(e);if(!(t instanceof HTMLElement))throw new Error(`Missing element for selector: ${e}`);return t}function M6(n){if(!aa)throw new Error("Floating windows are not initialized.");return aa.readPlacement(n)}function E6(n,e){aa?.applyPlacement(n,e)}function pc(n=ot?.getState().frameIndex??0,e={}){mo?.render(n,e)}function C6(n){mo?.create(n)}function A6(){mo?.clear()}function mn(){na?.scheduleConfigUrlUpdate()}function R6(n){na?.applyConfigToStaticControls(n)}function m1(n){return n.map(e=>({...e,seekTime:Pg(e)}))}function Ja(){ch?.renderSummary()}function _1(){tc?.render()}function jg(n){return tc?.getSources(n)??[]}function P6(){const n=_o();return G$(n,jg(n))}function Zg(){ec?.render()}function Jg(n){const e=bl?.querySelector(`[data-window-id="${n}"]`);return!!(e&&!e.hidden)}function Qg(n,e={}){!e.forceScroll&&!Jg("event-playlist")||ec?.syncTimeline(n,e)}function g1(){ec?.reset()}function I6(n){const e=G8(n);e&&(_n.activateMechanicTimelineKind(e),_1())}function L6(n){return zi?.enforceClipBoundary(n)??!1}function Qa(){ch?.renderSettings()}function ey(n=ot?.getState().frameIndex??0){k_?.render(n)}function y1(n=ot?.getState()??null){Jg("shot-visualization")&&ud?.render(n)}function D6(n){if(bi.toggleWindow(n),!!Jg(n)){if(n==="event-playlist"){Zg();const e=ot?.getState();e&&Qg(e,{forceScroll:!0})}n==="shot-visualization"&&y1(ot?.getState()??null)}}function k6(n){uh?.setTransportEnabled(n,ot?.getState())}function v1(n=rh?.getStatus()??null){Sl?.sync(n)}function O6(n){if(L6(n))return;const e=performance.now();n.playing&&e-iwzW(n,e=>{ea.textContent=tf(e),Jr?.update(e)})))}async function F_(n,e){await QW(n,e,{elements:{fileInput:lh,viewport:u1,emptyState:R_,statusReadout:ea,playersReadout:d1,framesReadout:h1,skipPostGoalTransitions:Ga,skipKickoffs:$a,hitboxWireframes:xl,hitboxOnlyMode:wl},getReplayLoadModal:()=>Jr,getReplayPlayer:()=>ot,setReplayPlayer(t){ot=t,Va?.syncSource()},getUnsubscribe:()=>oh,setUnsubscribe(t){oh=t},setCanvasRecorder(t){rh=t},setLoadedReplayName(t){O_=t},setTimelineOverlay(t){Yg=t},setStatsTimeline(t){fo=t,Va?.syncSource()},setStatsFrameLookup(t){po=t},setStatRegistry(t){D_=t},getInitialConfig:()=>As,setApplyingConfig(t){na?.setApplyingConfig(t)},getReplayTimelineEvents(t){return A5(t,_n.getActiveTimelineEventSourceIds())},withTimelineEventSeekTimes:m1,includeBoostPickupAnimationPickup:F6,syncRecordingWindow:v1,setTransportEnabled:k6,teardownActiveModules:f1,clearTimelineEventSources:x6,clearTimelineRangeSources:w6,clearStandalonePlugins:S6,clearRenderCaches:b6,resetEventPlaylistWindow:g1,renderModuleSummary:Ja,renderScoreboard:ey,renderTimelineEventCount:Qr,renderMechanicsTimelineControls:_1,renderEventPlaylistWindow:Zg,renderModuleSettings:Qa,syncBoostPadOverlayPlugin:p1,setupActiveModules:dh,renderSnapshot:O6,applyConfigToReplayPlayer:vl.applyConfigToReplayPlayer,renderStatsWindows:pc,syncEventPlaylistTimeline:Qg,getCameraControlsController:()=>Bi})}function U6(n,e={}){Hu?.(),n.innerHTML=d3(),bl=n,Jr=IH(n),aa=OW({getRoot:()=>bl??document,requestConfigSync:mn}),lh=ae(n,"#replay-file"),u1=ae(n,"#viewport"),R_=ae(n,"#empty-state"),sw=ae(n,"#empty-load-replay"),P_=ae(n,"#launcher-toggle"),I_=ae(n,"#launcher-menu"),aw=ae(n,"#load-replay-action"),rw=ae(n,"#floating-window-layer"),k_=u8({body:ae(n,"#scoreboard-window-body"),getReplayPlayer:()=>ot,getStatsFrameLookup:()=>po});const t=ae(n,"#mechanics-timeline-window-body");tc=q$({body:t,modules:cd,getContext:_o,getActiveTimelineEventSourceIds:()=>_n.getActiveTimelineEventSourceIds(),getActiveMechanicTimelineKinds:()=>_n.getActiveMechanicTimelineKinds(),toggleEventSource(d,h){_w(d,"events",h)},setMechanicTimelineKind(d,h){_n.setMechanicTimelineKind(d,h)},setupActiveModules:dh,syncTimelineEvents:gw,syncTimelineRanges:hh,renderModuleSummary:Ja,renderModuleSettings:Qa,renderTimelineEventCount:Qr,requestConfigSync:mn}),ow=ae(n,"#event-playlist-window-body"),ec=NW({body:ow,getReplayPlayer:()=>ot,getSources:P6,cueTimelineEvent:vl.cueTimelineEvent,formatTime:ss}),ud=new h6({body:ae(n,"#shot-visualization-window-body"),getReplayPlayer:()=>ot,cueTimelineEvent:vl.cueTimelineEvent}),lw=ae(n,"#replay-loading-summary"),cw=ae(n,"#replay-loading-active"),uw=ae(n,"#replay-loading-list");const i=X8({elements:{reviewSummary:ae(n,"#mechanics-review-replay-load-summary"),loadingSummary:lw,loadingActive:cw,loadingList:uw},isActiveReview(d){return zi?.review===d},onActiveLoadProgress(d){ea.textContent=tf(d),Jr?.update(d)}});zi=Y8({elements:{file:ae(n,"#mechanics-review-file"),url:ae(n,"#mechanics-review-url"),loadUrl:ae(n,"#mechanics-review-load-url"),status:ae(n,"#mechanics-review-status"),index:ae(n,"#mechanics-review-index"),title:ae(n,"#mechanics-review-title"),mechanic:ae(n,"#mechanics-review-mechanic"),player:ae(n,"#mechanics-review-player"),clip:ae(n,"#mechanics-review-clip"),event:ae(n,"#mechanics-review-event"),reason:ae(n,"#mechanics-review-reason"),previous:ae(n,"#mechanics-review-prev"),replay:ae(n,"#mechanics-review-replay"),next:ae(n,"#mechanics-review-next"),confirm:ae(n,"#mechanics-review-confirm"),reject:ae(n,"#mechanics-review-reject"),uncertain:ae(n,"#mechanics-review-uncertain"),count:ae(n,"#mechanics-review-count"),list:ae(n,"#mechanics-review-list")},replayLoads:i,getReplayPlayer:()=>ot,resetReplayTransitionControls(){Ga.checked=!1,$a.checked=!1},activateTimelineSource:I6,loadReplayBundleForDisplay:F_,applyClipPerspective(d){Bi?.followPlayerWithReplayCamera(d.playerId,{ballCam:d.ballCam,usePlayerCameraSettings:d.usePlayerCameraSettings})},showReplayLoadingWindow(){bi.showWindow("replay-loading")}});const s=ae(n,"#boost-pickup-filters-window-body"),a=ae(n,"#touch-controls-window-body");fm=ae(n,"#stats-window-layer"),mo=w$({layer:fm,getReplayPlayer:()=>ot,getStatsTimeline:()=>fo,getStatsFrameLookup:()=>po,getStatRegistry:()=>D_,readWindowPlacement:M6,applyWindowPlacement:E6,bringWindowToFront:bi.bringWindowToFront,setLauncherOpen:bi.setLauncherOpen,requestConfigSync:mn,watchGoalReplay:vl.watchGoalReplay,cueGoalReplay:vl.cueGoalReplay}),pm=ae(n,"#toggle-playback"),mm=ae(n,"#previous-frame"),_m=ae(n,"#next-frame"),Bu=ae(n,"#playback-rate"),Bi=DH({elements:{attachedPlayer:ae(n,"#attached-player"),cameraViewFreeButton:ae(n,"#camera-view-free"),cameraViewFollowButton:ae(n,"#camera-view-follow"),cameraViewAutoPossession:ae(n,"#camera-view-auto-possession"),cameraViewOverheadButton:ae(n,"#camera-view-overhead"),cameraViewSideButton:ae(n,"#camera-view-side"),usePlayerCameraSettings:ae(n,"#use-player-camera-settings"),cameraSettingsControls:ae(n,"#camera-settings-controls"),customCameraFov:ae(n,"#custom-camera-fov"),customCameraHeight:ae(n,"#custom-camera-height"),customCameraPitch:ae(n,"#custom-camera-pitch"),customCameraDistance:ae(n,"#custom-camera-distance"),customCameraStiffness:ae(n,"#custom-camera-stiffness"),customCameraSwivelSpeed:ae(n,"#custom-camera-swivel-speed"),customCameraTransitionSpeed:ae(n,"#custom-camera-transition-speed"),customCameraFovReadout:ae(n,"#custom-camera-fov-readout"),customCameraHeightReadout:ae(n,"#custom-camera-height-readout"),customCameraPitchReadout:ae(n,"#custom-camera-pitch-readout"),customCameraDistanceReadout:ae(n,"#custom-camera-distance-readout"),customCameraStiffnessReadout:ae(n,"#custom-camera-stiffness-readout"),customCameraSwivelSpeedReadout:ae(n,"#custom-camera-swivel-speed-readout"),customCameraTransitionSpeedReadout:ae(n,"#custom-camera-transition-speed-readout"),ballCamOffButton:ae(n,"#ball-cam-off"),ballCamOnButton:ae(n,"#ball-cam-on"),ballCamPlayerButton:ae(n,"#ball-cam-player"),nameplateLift:ae(n,"#custom-nameplate-lift"),nameplateLiftReadout:ae(n,"#custom-nameplate-lift-readout"),cameraProfileReadout:ae(n,"#camera-profile-readout"),cameraFovReadout:ae(n,"#camera-fov-readout"),cameraHeightReadout:ae(n,"#camera-height-readout"),cameraPitchReadout:ae(n,"#camera-pitch-readout"),cameraBaseDistanceReadout:ae(n,"#camera-base-distance-readout"),cameraStiffnessReadout:ae(n,"#camera-stiffness-readout")},getReplayPlayer:()=>ot,requestConfigSync:mn,onAutoPossessionChange(d){Va?.syncSource(),d&&Va?.syncCurrentFrame()}}),Va=rV({getReplayPlayer:()=>ot,getStatsTimeline:()=>fo,getCameraControlsController:()=>Bi}),VE(ae(n,"#touch-color-legend-body"),["team"]),ch=J$({elements:{summary:ae(n,"#module-summary"),settings:ae(n,"#module-settings"),boostPickupFilters:s,touchControls:a},modules:cd,boostPickupFilters:uf,getContext:_o,getTimelineSources:()=>jg(_o()),getActiveModules:()=>_n.getActiveModules(),getActiveCapabilityIds:v6,getBoostPickupAnimationEnabled:()=>ot?.getState().boostPickupAnimationEnabled??!1,toggleCapability:_w,toggleBoostPickupAnimation(){const d=!(ot?.getState().boostPickupAnimationEnabled??!1);ot?.setBoostPickupAnimationEnabled(d),dh(),Ja(),Qa(),mn()},syncTimelineEvents:gw,syncTimelineRanges:hh,renderTimelineEventCount:Qr,requestConfigSync:mn}),dw=ae(n,"#time-readout"),hw=ae(n,"#frame-readout"),fw=ae(n,"#duration-readout"),pw=ae(n,"#playback-status-readout"),ea=ae(n,"#status-readout"),d1=ae(n,"#players-readout"),h1=ae(n,"#frames-readout"),L_=ae(n,"#events-readout"),zu=ae(n,"#playback-rate-readout"),Ga=ae(n,"#skip-post-goal-transitions"),$a=ae(n,"#skip-kickoffs"),xl=ae(n,"#hitbox-wireframes"),wl=ae(n,"#hitbox-only-mode"),uh=h8({elements:{togglePlayback:pm,previousFrame:mm,nextFrame:_m,playbackRate:Bu,playbackRateReadout:zu,skipPostGoalTransitions:Ga,skipKickoffs:$a,hitboxWireframes:xl,hitboxOnlyMode:wl,emptyState:R_,timeReadout:dw,frameReadout:hw,durationReadout:fw,playbackStatusReadout:pw},getFrameCount:()=>ot?.replay.frameCount??0,getCameraControlsController:()=>Bi}),Sl=r8({elements:{fps:ae(n,"#recording-fps"),playbackRate:ae(n,"#recording-playback-rate"),start:ae(n,"#recording-start"),fullReplay:ae(n,"#recording-full-replay"),stop:ae(n,"#recording-stop"),download:ae(n,"#recording-download"),clear:ae(n,"#recording-clear"),status:ae(n,"#recording-status"),elapsed:ae(n,"#recording-elapsed"),size:ae(n,"#recording-size"),type:ae(n,"#recording-type")},getCanvasRecorder:()=>rh,getReplayPlayer:()=>ot,getLoadedReplayName:()=>O_,setStatus(d){ea.textContent=d},requestConfigSync:mn}),mw=C8({elements:{mechanic:ae(n,"#missed-event-mechanic"),capture:ae(n,"#missed-event-capture"),list:ae(n,"#missed-event-list"),export:ae(n,"#missed-event-export"),upload:ae(n,"#missed-event-upload"),clear:ae(n,"#missed-event-clear"),status:ae(n,"#missed-event-status")},getReplayPlayer:()=>ot,showWindow:()=>bi.showWindow("missed-events")}),na=l6({modules:cd,playbackRate:Bu,playbackRateReadout:zu,skipPostGoalTransitions:Ga,skipKickoffs:$a,hitboxWireframes:xl,hitboxOnlyMode:wl,getReplayPlayer:()=>ot,getCameraControlsController:()=>Bi,getRecordingWindowController:()=>Sl,getFloatingWindowController:()=>aa,getStatsWindowsController:()=>mo,getActiveModulesRuntime:()=>_n,getInitialConfig:()=>As,renderModuleSummary:Ja,renderModuleSettings:Qa,renderTimelineEventCount:Qr});const r=i1(window.location),o=yW(window.location);let l=null;if(e.initialConfig!==void 0)As=e.initialConfig;else{try{As=gW(window.location)}catch(d){l=d,console.error("Invalid stats player config:",d),ea.textContent=d instanceof Error?d.message:"Invalid stats player config",As=null}o&&JW(r,As,l)}const c=new AbortController;bi.installWindowDragging(rw,c.signal),bi.installWindowDragging(fm,c.signal);const u=()=>{c.abort(),oh?.(),oh=null,f1(),ot?.destroy(),ot=null,rh=null,Yg=null,fo=null,po=null,D_=Jl(),A6(),mo=null,_n.reset(),Jr?.destroy(),Jr=null,g1(),tc=null,ec=null,zi?.reset(),zi=null,O_=null,Va?.reset(),Va=null,Bi=null,Sl=null,ch=null,k_=null,uh=null,ud?.destroy(),ud=null,As=null,na?.reset(),na=null,aa?.reset(),aa=null,bl===n&&(bl=null,n.replaceChildren()),Hu===u&&(Hu=null)};if(Hu=u,As){na?.setApplyingConfig(!0);try{R6(As)}finally{na?.setApplyingConfig(!1)}}return f8({elements:{root:n,launcherToggle:P_,launcherMenu:I_,loadReplayAction:aw,emptyLoadReplay:sw,fileInput:lh,togglePlayback:pm,previousFrame:mm,nextFrame:_m,playbackRate:Bu,playbackRateReadout:zu,skipPostGoalTransitions:Ga,skipKickoffs:$a,hitboxWireframes:xl,hitboxOnlyMode:wl},signal:c.signal,setLauncherOpen:bi.setLauncherOpen,openReplayFilePicker:bi.openReplayFilePicker,getElementWindowId:bi.getElementWindowId,toggleWindow:D6,hideWindow:bi.hideWindow,createStatsWindow:C6,async loadReplayFile(d){try{zi?.clearCurrentClip({resetReplayId:!0,render:!0}),await yw(UW(d))}catch(h){console.error("Failed to load replay:",h),ea.textContent=h instanceof Error?h.message:"Failed to load replay"}},togglePlayback(){ot?.togglePlayback(),mn()},stepFrames(d){ot?.stepFrames(d),mn()},setPlaybackRate(d){ot?.setPlaybackRate(d),mn()},setSkipPostGoalTransitionsEnabled(d){ot?.setSkipPostGoalTransitionsEnabled(d),mn()},setSkipKickoffsEnabled(d){ot?.setSkipKickoffsEnabled(d),mn()},setHitboxWireframesEnabled(d){ot?.setHitboxWireframesEnabled(d),mn()},setHitboxOnlyModeEnabled(d){ot?.setHitboxOnlyModeEnabled(d),mn()}}),zi?.installEventListeners(c.signal),Sl?.installEventListeners(c.signal),mw?.installEventListeners(c.signal),Bi?.installEventListeners(c.signal),_8({getReplayPlayer:()=>ot,signal:c.signal}),window.addEventListener("message",d=>{if(d.origin!==window.location.origin)return;const h=d.data;!h||typeof h!="object"||h.source!=="rocket-sense"||h.type==="activateReviewItem"&&typeof h.index=="number"&&Number.isInteger(h.index)&&zi?.activateItem(h.index)},{signal:c.signal}),Ja(),Qa(),ey(),Bi?.renderProfile(),Bi?.syncModeButtons(),v1(),Qr(),zi?.render(),Zg(),r6({signal:c.signal,location:window.location,statusReadout:ea,initialBundle:e.initialBundle,initialReplayName:e.initialReplayName,loadFromLocation:e.loadFromLocation,loadReplay:yw,loadReplayBundleForDisplay:F_,getMechanicsReviewController:()=>zi,showMechanicsReviewWindow(){bi.showWindow("mechanics-review")}}),{root:n,destroy:u}}export{U6 as mountStatEvaluationPlayer}; + `,this.chartCanvas=this.mustElement("#shot-chart-canvas"),this.shotList=this.mustElement("#shot-list"),this.summary=this.mustElement("#shot-visualization-summary"),this.details=this.mustElement("#shot-details"),this.sceneRoot=this.mustElement("#shot-demo-scene"),this.emptyState=this.mustElement("#shot-visualization-empty"),this.chartCanvas.addEventListener("click",t=>this.handleChartClick(t))}chartCanvas;shotList;summary;details;sceneRoot;emptyState;renderer=null;scene=null;camera=null;resizeObserver=null;selectedShotId=null;cachedReplay=null;cachedShots=[];lastShotsSignature="";lastListSelectionKey=null;lastSelectedShotKey=null;shotButtons=new Map;destroy(){this.resizeObserver?.disconnect(),this.renderer?.dispose(),this.renderer=null,this.scene=null,this.camera=null}render(e=this.options.getReplayPlayer()?.getState()??null){const t=this.shotEvents(),i=e?.currentTime??null;this.findSelectedShot(t)||(this.selectedShotId=t[0]?this.shotKey(t[0],0):null);const s=this.findSelectedShot(t),a=s?.key??null,r=this.shotsSignature(t),o=r!==this.lastShotsSignature;this.emptyState.hidden=t.length>0,o&&(this.summary.textContent=this.summaryText(t)),o||a!==this.lastListSelectionKey?(this.renderShotList(t,i,a),this.lastListSelectionKey=a):this.updateShotListActiveState(t,i),this.renderChart(t,i),(o||a!==this.lastSelectedShotKey)&&(this.renderSelectedShot(s?.shot??null),this.lastSelectedShotKey=a),this.lastShotsSignature=r}shotEvents(){const e=this.options.getReplayPlayer()?.replay;return e?e===this.cachedReplay?this.cachedShots:(this.cachedReplay=e,this.cachedShots=e.timelineEvents.filter(q6),this.cachedShots):(this.cachedReplay=null,this.cachedShots=[],[])}summaryText(e){if(e.length===0)return"No shots";const t=e.filter(a=>a.shot.resulting_save).length,i=e.map(a=>a.shot.ball_speed).filter(a=>Number.isFinite(a)),s=i.length===0?null:i.reduce((a,r)=>a+r,0)/i.length;return`${e.length} shots | ${t} saved | avg ${Vu(s)}`}renderShotList(e,t,i){this.shotButtons.clear(),this.shotList.replaceChildren(...e.map((s,a)=>{const r=this.shotKey(s,a),o=document.createElement("button");o.type="button",o.className="shot-list-item",o.dataset.selected=String(r===i),o.dataset.active=String(vm(s,t)),o.addEventListener("click",()=>{this.selectedShotId=r,this.options.cueTimelineEvent(s),this.render()});const l=document.createElement("span");l.className="shot-list-title",l.textContent=s.playerName??s.playerId??`Shot ${a+1}`;const c=document.createElement("span");return c.className="shot-list-meta",c.textContent=`${uw(s.time)} | ${Vu(s.shot.ball_speed)} | ${s.shot.resulting_save?"saved":"unsaved"}`,o.append(l,c),this.shotButtons.set(r,o),o}))}updateShotListActiveState(e,t){e.forEach((i,s)=>{const a=this.shotButtons.get(this.shotKey(i,s));a&&(a.dataset.active=String(vm(i,t)))})}renderChart(e,t){const i=this.chartCanvas.getContext("2d");if(!i)return;const s=window.devicePixelRatio||1,a=this.chartCanvas.getBoundingClientRect(),r=Math.max(320,Math.round(a.width*s)),o=Math.max(220,Math.round(a.height*s));(this.chartCanvas.width!==r||this.chartCanvas.height!==o)&&(this.chartCanvas.width=r,this.chartCanvas.height=o),i.setTransform(s,0,0,s,0,0);const l=r/s,c=o/s;i.clearRect(0,0,l,c),Y6(i,l,c),e.forEach((u,d)=>{const h=u.shot.shot_touch_position??u.shot.ball_position,f=dh(h,l,c),p=!!u.shot.resulting_save,g=vm(u,t),_=this.shotKey(u,d)===this.selectedShotId,m=_?6:g?5:4;i.beginPath(),i.arc(f.x,f.y,m,0,Math.PI*2),i.fillStyle=p?"#f2c14e":"#62d2a2",i.fill(),i.lineWidth=_?2.5:1.25,i.strokeStyle=_?"#f8fafc":g?"#e11d48":"rgba(4, 12, 20, 0.85)",i.stroke()})}renderSelectedShot(e){if(!e){this.details.replaceChildren(),this.clearThreeScene();return}this.details.replaceChildren(hl("Player",e.playerName??e.playerId??"--"),hl("Speed",Vu(e.shot.ball_speed)),hl("Toward goal",Vu(e.shot.ball_speed_toward_goal)),hl("Touch",Z6(e.shot.shot_touch_position??e.shot.ball_position)),hl("Save",e.shot.resulting_save?uw(e.shot.resulting_save.time):"--")),this.renderThreeScene(e)}renderThreeScene(e){const t=this.ensureRenderer(),i=this.scene,s=this.camera;i.clear(),i.add(new mc(16777215,1.2));const a=new Fo(16777215,1.7);a.position.set(18,28,22),i.add(a);const r=new we(new kn(O_*2*Yi,fr*2*Yi),new Ye({color:1520422,side:ct}));r.rotation.x=-Math.PI/2,i.add(r);const o=new Rt({color:14280674,transparent:!0,opacity:.55});i.add(new Ln(new Wh(r.geometry),o)),i.add(lw(!0)),i.add(lw(!1));const l=cw(e.shot.shot_touch_position??e.shot.ball_position),c=cw(e.shot.target_goal_position),u=e.shot.ball_velocity,d=u?l.clone().add(j6(u).normalize().multiplyScalar(22)):c.clone(),h=new dg([l,l.clone().lerp(d,.45).setY(Math.max(l.y,d.y)+2.8),d]),f=new Ge().setFromPoints(h.getPoints(36));i.add(new In(f,new Rt({color:e.shot.resulting_save?15909198:6476450,linewidth:2})));const p=new we(new yn(.9,24,16),new Pn({color:16317180,roughness:.36}));p.position.copy(l),i.add(p);const g=new we(new ni(1.05,1.45,32),new Ye({color:8892372,side:ct}));g.position.copy(c),g.rotation.y=Math.PI/2,i.add(g),s.position.set(0,54,72),s.lookAt(0,0,0),t.render(i,s)}ensureRenderer(){if(this.renderer&&this.scene&&this.camera)return this.resizeThreeScene(),this.renderer;const e=new kg({antialias:!0,alpha:!0,preserveDrawingBuffer:!0});return e.setPixelRatio(window.devicePixelRatio||1),this.sceneRoot.replaceChildren(e.domElement),this.renderer=e,this.scene=new cc,this.scene.background=new ue(463132),this.camera=new Jt(42,1,.1,500),this.resizeObserver=new ResizeObserver(()=>{this.resizeThreeScene();const t=this.shotEvents().find(i=>i.id===this.selectedShotId)??null;t&&this.renderThreeScene(t)}),this.resizeObserver.observe(this.sceneRoot),this.resizeThreeScene(),e}resizeThreeScene(){if(!this.renderer||!this.camera)return;const e=this.sceneRoot.getBoundingClientRect(),t=Math.max(240,Math.round(e.width)),i=Math.max(170,Math.round(e.height));this.camera.aspect=t/i,this.camera.updateProjectionMatrix(),this.renderer.setSize(t,i,!1)}clearThreeScene(){this.sceneRoot.replaceChildren(),this.renderer?.dispose(),this.renderer=null,this.scene=null,this.camera=null}handleChartClick(e){const t=this.shotEvents(),i=this.chartCanvas.getBoundingClientRect(),s={x:e.clientX-i.left,y:e.clientY-i.top};let a=null,r=Number.POSITIVE_INFINITY;for(const o of t){const l=dh(o.shot.shot_touch_position??o.shot.ball_position,i.width,i.height),c=Math.hypot(l.x-s.x,l.y-s.y);c`${this.shotKey(t,i)}:${t.time}:${t.shot.ball_speed}`).join("|")}}function q6(n){return n.kind==="shot"&&!!n.shot}function vm(n,e){return e!==null&&Math.abs(e-n.time)<1.5}function Y6(n,e,t){n.fillStyle="#0f2b24",n.fillRect(0,0,e,t),n.strokeStyle="rgba(226, 241, 236, 0.74)",n.lineWidth=1.2,n.strokeRect(18,18,e-36,t-36),n.beginPath(),n.moveTo(18,t/2),n.lineTo(e-18,t/2),n.stroke(),n.beginPath(),n.arc(e/2,t/2,34,0,Math.PI*2),n.stroke();const s=dh({x:0,y:-fr},e,t),a=dh({x:0,y:fr},e,t);n.fillStyle="#4fa3ff",n.fillRect(s.x-28,s.y-4,56,8),n.fillStyle="#ff8a4c",n.fillRect(a.x-28,a.y-4,56,8)}function dh(n,e,t){const s=e-36,a=t-36;return{x:18+(n.x+O_)/(O_*2)*s,y:18+(1-(n.y+fr)/(fr*2))*a}}function lw(n){const e=new Mt,t=new Rt({color:n?16747084:5219327}),i=(n?fr:-fr)*Yi,s=W6*Yi,a=X6*Yi,r=[new S(-s,0,i),new S(-s,a,i),new S(s,a,i),new S(s,0,i)];return e.add(new In(new Ge().setFromPoints(r),t)),e}function cw(n){return new S(n.x*Yi,n.z*Yi,n.y*Yi)}function j6(n){return new S(n.x*Yi,n.z*Yi,n.y*Yi)}function hl(n,e){const t=document.createElement("div"),i=document.createElement("dt");i.textContent=n;const s=document.createElement("dd");return s.textContent=e,t.append(i,s),t}function uw(n){return Number.isFinite(n)?`${n.toFixed(2)}s`:"--"}function Vu(n){return Number.isFinite(n)?`${Math.round(n)} uu/s`:"--"}function Z6(n){return n?`${Math.round(n.x)}, ${Math.round(n.y)}, ${Math.round(n.z)}`:"--"}const J6=4,Q6=100;let st=null,ny=null,hh=null,_o=null,go=null,fh=null,dw=0,Ga=null;const _f=YE({refreshTimelineRanges(){yh()},rerenderCurrentState(){st&&st.setBoostPickupAnimationEnabled(st.getState().boostPickupAnimationEnabled)},requestConfigSync(){mn()}}),pd=B$({rerenderCurrentState(){if(!st)return;const n=st.getState();yc(n.frameIndex)},refreshTimelineRanges(){yh()},requestConfigSync(){mn()}},{boostPickupFilters:_f}),_n=u6({modules:pd,boostPickupFilters:_f,getContext:vo,getReplayPlayer:()=>st,getTimelineOverlay:()=>ny,getEventTimelineSources:iy,withTimelineEventSeekTimes:M1,renderModuleSummary:Qa,renderModuleSettings:er,renderStatsWindows(){st&&yc(st.getState().frameIndex)},renderTimelineEventCount:to,requestConfigSync:mn}),wl=V6({goalWatchLeadSeconds:J6,getReplayPlayer:()=>st,getCameraControlsController:()=>zi,getMechanicsReviewController:()=>Hi,getSkipPostGoalTransitions:()=>$a,getSkipKickoffs:()=>Wa,syncBoostPadOverlayPlugin:T1,setupActiveModules:gh,renderModuleSummary:Qa,renderModuleSettings:er,renderStatsWindows(n){yc(n)},scheduleConfigUrlUpdate:mn}),bi=$6({getFloatingWindowController:()=>ra,getLauncherMenu:()=>U_,getLauncherToggle:()=>N_,getFileInput:()=>ph});let Sl=null,ph,b1,F_,hw,N_,U_,fw,pw,mw,_w,gw,yw,bm,xm,wm,Sm,Gu,$u,vw,bw,xw,ww,ea,x1,w1,B_,$a,eo=null,Wa,Tl,Ml,Wu=null,z_=nc(),zi=null,El=null,Sw=null,md=null,yo=null,sc=null,ac=null,mh=null,Hi=null,ra=null,H_=null,_h=null,_d=null,ia=null,V_=null,As=null;function e9(n){return _n.getActiveCapabilityIds(n)}function t9(){}function vo(){return!st||!_o||!go?null:{player:st,replay:st.replay,statsTimeline:_o,statsFrameLookup:go,fieldScale:1}}function gh(){_n.setupActiveModules()}function S1(){_n.teardownActiveModules()}function Tw(n,e,t){_n.toggleCapability(n,e,t)}function n9(){_n.clearTimelineEventSources()}function i9(){_n.clearTimelineRangeSources()}function s9(){_n.clearStandalonePlugins()}function T1(){_n.syncBoostPadOverlayPlugin()}function Mw(){_n.syncTimelineEvents()}function yh(){_n.syncTimelineRanges()}function to(){const n=vo();if(!n){B_.textContent="--";return}B_.textContent=`${a9(n)}`}function a9(n){return ac?.countVisibleSources(n)??0}function se(n,e){const t=n.querySelector(e);if(!(t instanceof HTMLElement))throw new Error(`Missing element for selector: ${e}`);return t}function r9(n){if(!ra)throw new Error("Floating windows are not initialized.");return ra.readPlacement(n)}function o9(n,e){ra?.applyPlacement(n,e)}function yc(n=st?.getState().frameIndex??0,e={}){yo?.render(n,e)}function l9(n){yo?.create(n)}function c9(){yo?.clear()}function mn(){ia?.scheduleConfigUrlUpdate()}function u9(n){ia?.applyConfigToStaticControls(n)}function M1(n){return n.map(e=>({...e,seekTime:Ng(e)}))}function Qa(){mh?.renderSummary()}function E1(){ac?.render()}function iy(n){return ac?.getSources(n)??[]}function d9(){const n=vo();return bW(n,iy(n))}function sy(){sc?.render()}function ay(n){const e=Sl?.querySelector(`[data-window-id="${n}"]`);return!!(e&&!e.hidden)}function ry(n,e={}){!e.forceScroll&&!ay("event-playlist")||sc?.syncTimeline(n,e)}function C1(){sc?.reset()}function h9(n){const e=T6(n);e&&(_n.activateMechanicTimelineKind(e),E1())}function f9(n){return Hi?.enforceClipBoundary(n)??!1}function er(){mh?.renderSettings()}function oy(n=st?.getState().frameIndex??0){H_?.render(n)}function A1(n=st?.getState()??null){ay("shot-visualization")&&_d?.render(n)}function p9(n){if(bi.toggleWindow(n),!!ay(n)){if(n==="event-playlist"){sy();const e=st?.getState();e&&ry(e,{forceScroll:!0})}n==="shot-visualization"&&A1(st?.getState()??null)}}function m9(n){_h?.setTransportEnabled(n,st?.getState())}function R1(n=hh?.getStatus()??null){El?.sync(n),md?.sync()}function _9(n){if(f9(n))return;const e=performance.now();n.playing&&e-dwg8(n,e=>{ea.textContent=lf(e),eo?.update(e)})))}async function G_(n,e){await P8(n,e,{elements:{fileInput:ph,viewport:b1,emptyState:F_,statusReadout:ea,playersReadout:x1,framesReadout:w1,skipPostGoalTransitions:$a,skipKickoffs:Wa,hitboxWireframes:Tl,hitboxOnlyMode:Ml},getReplayLoadModal:()=>eo,getReplayPlayer:()=>st,setReplayPlayer(t){st=t,Ga?.syncSource()},getUnsubscribe:()=>fh,setUnsubscribe(t){fh=t},setCanvasRecorder(t){hh=t},setLoadedReplayName(t){V_=t},setTimelineOverlay(t){ny=t},setStatsTimeline(t){_o=t,Ga?.syncSource()},setStatsFrameLookup(t){go=t},setStatRegistry(t){z_=t},getInitialConfig:()=>As,setApplyingConfig(t){ia?.setApplyingConfig(t)},getReplayTimelineEvents(t){return a4(t,_n.getActiveTimelineEventSourceIds())},withTimelineEventSeekTimes:M1,includeBoostPickupAnimationPickup:g9,syncRecordingWindow:R1,setTransportEnabled:m9,teardownActiveModules:S1,clearTimelineEventSources:n9,clearTimelineRangeSources:i9,clearStandalonePlugins:s9,clearRenderCaches:t9,resetEventPlaylistWindow:C1,renderModuleSummary:Qa,renderScoreboard:oy,renderTimelineEventCount:to,renderMechanicsTimelineControls:E1,renderEventPlaylistWindow:sy,renderModuleSettings:er,syncBoostPadOverlayPlugin:T1,setupActiveModules:gh,renderSnapshot:_9,applyConfigToReplayPlayer:wl.applyConfigToReplayPlayer,renderStatsWindows:yc,syncEventPlaylistTimeline:ry,getCameraControlsController:()=>zi})}function b9(n,e={}){Wu?.(),n.innerHTML=V3(),Sl=n,eo=lV(n),ra=h8({getRoot:()=>Sl??document,requestConfigSync:mn}),ph=se(n,"#replay-file"),b1=se(n,"#viewport"),F_=se(n,"#empty-state"),hw=se(n,"#empty-load-replay"),N_=se(n,"#launcher-toggle"),U_=se(n,"#launcher-menu"),fw=se(n,"#load-replay-action"),pw=se(n,"#floating-window-layer"),H_=H8({body:se(n,"#scoreboard-window-body"),getReplayPlayer:()=>st,getStatsFrameLookup:()=>go});const t=se(n,"#mechanics-timeline-window-body");ac=MW({body:t,modules:pd,getContext:vo,getActiveTimelineEventSourceIds:()=>_n.getActiveTimelineEventSourceIds(),getActiveMechanicTimelineKinds:()=>_n.getActiveMechanicTimelineKinds(),toggleEventSource(d,h){Tw(d,"events",h)},setMechanicTimelineKind(d,h){_n.setMechanicTimelineKind(d,h)},setupActiveModules:gh,syncTimelineEvents:Mw,syncTimelineRanges:yh,renderModuleSummary:Qa,renderModuleSettings:er,renderTimelineEventCount:to,requestConfigSync:mn}),mw=se(n,"#event-playlist-window-body"),sc=p8({body:mw,getReplayPlayer:()=>st,getSources:d9,cueTimelineEvent:wl.cueTimelineEvent,formatTime:wi}),_d=new K6({body:se(n,"#shot-visualization-window-body"),getReplayPlayer:()=>st,cueTimelineEvent:wl.cueTimelineEvent}),_w=se(n,"#replay-loading-summary"),gw=se(n,"#replay-loading-active"),yw=se(n,"#replay-loading-list");const i=C6({elements:{reviewSummary:se(n,"#mechanics-review-replay-load-summary"),loadingSummary:_w,loadingActive:gw,loadingList:yw},isActiveReview(d){return Hi?.review===d},onActiveLoadProgress(d){ea.textContent=lf(d),eo?.update(d)}});Hi=P6({elements:{file:se(n,"#mechanics-review-file"),url:se(n,"#mechanics-review-url"),loadUrl:se(n,"#mechanics-review-load-url"),status:se(n,"#mechanics-review-status"),index:se(n,"#mechanics-review-index"),title:se(n,"#mechanics-review-title"),mechanic:se(n,"#mechanics-review-mechanic"),player:se(n,"#mechanics-review-player"),clip:se(n,"#mechanics-review-clip"),event:se(n,"#mechanics-review-event"),reason:se(n,"#mechanics-review-reason"),previous:se(n,"#mechanics-review-prev"),replay:se(n,"#mechanics-review-replay"),next:se(n,"#mechanics-review-next"),confirm:se(n,"#mechanics-review-confirm"),reject:se(n,"#mechanics-review-reject"),uncertain:se(n,"#mechanics-review-uncertain"),count:se(n,"#mechanics-review-count"),list:se(n,"#mechanics-review-list")},replayLoads:i,getReplayPlayer:()=>st,resetReplayTransitionControls(){$a.checked=!1,Wa.checked=!1},activateTimelineSource:h9,loadReplayBundleForDisplay:G_,applyClipPerspective(d){zi?.followPlayerWithReplayCamera(d.playerId,{ballCam:d.ballCam,usePlayerCameraSettings:d.usePlayerCameraSettings})},showReplayLoadingWindow(){bi.showWindow("replay-loading")}});const s=se(n,"#boost-pickup-filters-window-body"),a=se(n,"#touch-controls-window-body");bm=se(n,"#stats-window-layer"),yo=Q$({layer:bm,getReplayPlayer:()=>st,getStatsTimeline:()=>_o,getStatsFrameLookup:()=>go,getStatRegistry:()=>z_,readWindowPlacement:r9,applyWindowPlacement:o9,bringWindowToFront:bi.bringWindowToFront,setLauncherOpen:bi.setLauncherOpen,requestConfigSync:mn,watchGoalReplay:wl.watchGoalReplay,cueGoalReplay:wl.cueGoalReplay}),xm=se(n,"#toggle-playback"),wm=se(n,"#previous-frame"),Sm=se(n,"#next-frame"),Gu=se(n,"#playback-rate"),zi=uV({elements:{attachedPlayer:se(n,"#attached-player"),cameraViewFreeButton:se(n,"#camera-view-free"),cameraViewFollowButton:se(n,"#camera-view-follow"),cameraViewAutoPossession:se(n,"#camera-view-auto-possession"),cameraViewOverheadButton:se(n,"#camera-view-overhead"),cameraViewSideButton:se(n,"#camera-view-side"),usePlayerCameraSettings:se(n,"#use-player-camera-settings"),cameraSettingsControls:se(n,"#camera-settings-controls"),customCameraFov:se(n,"#custom-camera-fov"),customCameraHeight:se(n,"#custom-camera-height"),customCameraPitch:se(n,"#custom-camera-pitch"),customCameraDistance:se(n,"#custom-camera-distance"),customCameraStiffness:se(n,"#custom-camera-stiffness"),customCameraSwivelSpeed:se(n,"#custom-camera-swivel-speed"),customCameraTransitionSpeed:se(n,"#custom-camera-transition-speed"),customCameraFovReadout:se(n,"#custom-camera-fov-readout"),customCameraHeightReadout:se(n,"#custom-camera-height-readout"),customCameraPitchReadout:se(n,"#custom-camera-pitch-readout"),customCameraDistanceReadout:se(n,"#custom-camera-distance-readout"),customCameraStiffnessReadout:se(n,"#custom-camera-stiffness-readout"),customCameraSwivelSpeedReadout:se(n,"#custom-camera-swivel-speed-readout"),customCameraTransitionSpeedReadout:se(n,"#custom-camera-transition-speed-readout"),ballCamOffButton:se(n,"#ball-cam-off"),ballCamOnButton:se(n,"#ball-cam-on"),ballCamPlayerButton:se(n,"#ball-cam-player"),nameplateLift:se(n,"#custom-nameplate-lift"),nameplateLiftReadout:se(n,"#custom-nameplate-lift-readout"),cameraProfileReadout:se(n,"#camera-profile-readout"),cameraFovReadout:se(n,"#camera-fov-readout"),cameraHeightReadout:se(n,"#camera-height-readout"),cameraPitchReadout:se(n,"#camera-pitch-readout"),cameraBaseDistanceReadout:se(n,"#camera-base-distance-readout"),cameraStiffnessReadout:se(n,"#camera-stiffness-readout")},getReplayPlayer:()=>st,requestConfigSync:mn,onAutoPossessionChange(d){Ga?.syncSource(),d&&Ga?.syncCurrentFrame()}}),Ga=NV({getReplayPlayer:()=>st,getStatsTimeline:()=>_o,getCameraControlsController:()=>zi}),JE(se(n,"#touch-color-legend-body"),["team"]),mh=RW({elements:{summary:se(n,"#module-summary"),settings:se(n,"#module-settings"),boostPickupFilters:s,touchControls:a},modules:pd,boostPickupFilters:_f,getContext:vo,getTimelineSources:()=>iy(vo()),getActiveModules:()=>_n.getActiveModules(),getActiveCapabilityIds:e9,getBoostPickupAnimationEnabled:()=>st?.getState().boostPickupAnimationEnabled??!1,toggleCapability:Tw,toggleBoostPickupAnimation(){const d=!(st?.getState().boostPickupAnimationEnabled??!1);st?.setBoostPickupAnimationEnabled(d),gh(),Qa(),er(),mn()},syncTimelineEvents:Mw,syncTimelineRanges:yh,renderTimelineEventCount:to,requestConfigSync:mn}),vw=se(n,"#time-readout"),bw=se(n,"#frame-readout"),xw=se(n,"#duration-readout"),ww=se(n,"#playback-status-readout"),ea=se(n,"#status-readout"),x1=se(n,"#players-readout"),w1=se(n,"#frames-readout"),B_=se(n,"#events-readout"),$u=se(n,"#playback-rate-readout"),$a=se(n,"#skip-post-goal-transitions"),Wa=se(n,"#skip-kickoffs"),Tl=se(n,"#hitbox-wireframes"),Ml=se(n,"#hitbox-only-mode"),_h=G8({elements:{togglePlayback:xm,previousFrame:wm,nextFrame:Sm,playbackRate:Gu,playbackRateReadout:$u,skipPostGoalTransitions:$a,skipKickoffs:Wa,hitboxWireframes:Tl,hitboxOnlyMode:Ml,emptyState:F_,timeReadout:vw,frameReadout:bw,durationReadout:xw,playbackStatusReadout:ww},getFrameCount:()=>st?.replay.frameCount??0,getCameraControlsController:()=>zi}),El=N8({elements:{fps:se(n,"#recording-fps"),playbackRate:se(n,"#recording-playback-rate"),start:se(n,"#recording-start"),fullReplay:se(n,"#recording-full-replay"),stop:se(n,"#recording-stop"),download:se(n,"#recording-download"),clear:se(n,"#recording-clear"),status:se(n,"#recording-status"),elapsed:se(n,"#recording-elapsed"),size:se(n,"#recording-size"),type:se(n,"#recording-type")},getCanvasRecorder:()=>hh,getReplayPlayer:()=>st,getLoadedReplayName:()=>V_,setStatus(d){ea.textContent=d},requestConfigSync:mn}),Sw=s6({elements:{mechanic:se(n,"#missed-event-mechanic"),capture:se(n,"#missed-event-capture"),list:se(n,"#missed-event-list"),export:se(n,"#missed-event-export"),upload:se(n,"#missed-event-upload"),clear:se(n,"#missed-event-clear"),status:se(n,"#missed-event-status")},getReplayPlayer:()=>st,showWindow:()=>bi.showWindow("missed-events")}),md=l6({elements:{name:se(n,"#training-pack-name"),creator:se(n,"#training-pack-creator"),description:se(n,"#training-pack-description"),difficulty:se(n,"#training-pack-difficulty"),shooter:se(n,"#training-pack-shooter"),timeLimit:se(n,"#training-pack-time-limit"),capture:se(n,"#training-pack-capture"),load:se(n,"#training-pack-load"),loadInput:se(n,"#training-pack-load-input"),newPack:se(n,"#training-pack-new"),download:se(n,"#training-pack-download"),shotList:se(n,"#training-pack-shots"),status:se(n,"#training-pack-status")},getReplayPlayer:()=>st}),ia=G6({modules:pd,playbackRate:Gu,playbackRateReadout:$u,skipPostGoalTransitions:$a,skipKickoffs:Wa,hitboxWireframes:Tl,hitboxOnlyMode:Ml,getReplayPlayer:()=>st,getCameraControlsController:()=>zi,getRecordingWindowController:()=>El,getFloatingWindowController:()=>ra,getStatsWindowsController:()=>yo,getActiveModulesRuntime:()=>_n,getInitialConfig:()=>As,renderModuleSummary:Qa,renderModuleSettings:er,renderTimelineEventCount:to});const r=f1(window.location),o=YW(window.location);let l=null;if(e.initialConfig!==void 0)As=e.initialConfig;else{try{As=qW(window.location)}catch(d){l=d,console.error("Invalid stats player config:",d),ea.textContent=d instanceof Error?d.message:"Invalid stats player config",As=null}o&&R8(r,As,l)}const c=new AbortController;bi.installWindowDragging(pw,c.signal),bi.installWindowDragging(bm,c.signal);const u=()=>{c.abort(),fh?.(),fh=null,S1(),st?.destroy(),st=null,hh=null,ny=null,_o=null,go=null,z_=nc(),c9(),yo=null,_n.reset(),eo?.destroy(),eo=null,C1(),ac=null,sc=null,Hi?.reset(),Hi=null,V_=null,Ga?.reset(),Ga=null,zi=null,El=null,md=null,mh=null,H_=null,_h=null,_d?.destroy(),_d=null,As=null,ia?.reset(),ia=null,ra?.reset(),ra=null,Sl===n&&(Sl=null,n.replaceChildren()),Wu===u&&(Wu=null)};if(Wu=u,As){ia?.setApplyingConfig(!0);try{u9(As)}finally{ia?.setApplyingConfig(!1)}}return $8({elements:{root:n,launcherToggle:N_,launcherMenu:U_,loadReplayAction:fw,emptyLoadReplay:hw,fileInput:ph,togglePlayback:xm,previousFrame:wm,nextFrame:Sm,playbackRate:Gu,playbackRateReadout:$u,skipPostGoalTransitions:$a,skipKickoffs:Wa,hitboxWireframes:Tl,hitboxOnlyMode:Ml},signal:c.signal,setLauncherOpen:bi.setLauncherOpen,openReplayFilePicker:bi.openReplayFilePicker,getElementWindowId:bi.getElementWindowId,toggleWindow:p9,hideWindow:bi.hideWindow,createStatsWindow:l9,async loadReplayFile(d){try{Hi?.clearCurrentClip({resetReplayId:!0,render:!0}),await Ew(m8(d))}catch(h){console.error("Failed to load replay:",h),ea.textContent=h instanceof Error?h.message:"Failed to load replay"}},togglePlayback(){st?.togglePlayback(),mn()},stepFrames(d){st?.stepFrames(d),mn()},setPlaybackRate(d){st?.setPlaybackRate(d),mn()},setSkipPostGoalTransitionsEnabled(d){st?.setSkipPostGoalTransitionsEnabled(d),mn()},setSkipKickoffsEnabled(d){st?.setSkipKickoffsEnabled(d),mn()},setHitboxWireframesEnabled(d){st?.setHitboxWireframesEnabled(d),mn()},setHitboxOnlyModeEnabled(d){st?.setHitboxOnlyModeEnabled(d),mn()}}),Hi?.installEventListeners(c.signal),El?.installEventListeners(c.signal),Sw?.installEventListeners(c.signal),md?.installEventListeners(c.signal),zi?.installEventListeners(c.signal),K8({getReplayPlayer:()=>st,signal:c.signal}),window.addEventListener("message",d=>{if(d.origin!==window.location.origin)return;const h=d.data;!h||typeof h!="object"||h.source!=="rocket-sense"||h.type==="activateReviewItem"&&typeof h.index=="number"&&Number.isInteger(h.index)&&Hi?.activateItem(h.index)},{signal:c.signal}),Qa(),er(),oy(),zi?.renderProfile(),zi?.syncModeButtons(),R1(),to(),Hi?.render(),sy(),H6({signal:c.signal,location:window.location,statusReadout:ea,initialBundle:e.initialBundle,initialReplayName:e.initialReplayName,loadFromLocation:e.loadFromLocation,loadReplay:Ew,loadReplayBundleForDisplay:G_,getMechanicsReviewController:()=>Hi,showMechanicsReviewWindow(){bi.showWindow("mechanics-review")}}),{root:n,destroy:u}}export{b9 as mountStatEvaluationPlayer}; diff --git a/crates/rocket-sense-server/static/subtr-actor/review/assets/preload-helper-PPVm8Dsz.js b/crates/rocket-sense-server/static/subtr-actor/review/assets/preload-helper-PPVm8Dsz.js new file mode 100644 index 00000000..f5001933 --- /dev/null +++ b/crates/rocket-sense-server/static/subtr-actor/review/assets/preload-helper-PPVm8Dsz.js @@ -0,0 +1 @@ +const p="modulepreload",y=function(u,i){return new URL(u,i).href},v={},w=function(i,a,f){let d=Promise.resolve();if(a&&a.length>0){let E=function(e){return Promise.all(e.map(o=>Promise.resolve(o).then(s=>({status:"fulfilled",value:s}),s=>({status:"rejected",reason:s}))))};const r=document.getElementsByTagName("link"),t=document.querySelector("meta[property=csp-nonce]"),m=t?.nonce||t?.getAttribute("nonce");d=E(a.map(e=>{if(e=y(e,f),e in v)return;v[e]=!0;const o=e.endsWith(".css"),s=o?'[rel="stylesheet"]':"";if(f)for(let c=r.length-1;c>=0;c--){const l=r[c];if(l.href===e&&(!o||l.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${e}"]${s}`))return;const n=document.createElement("link");if(n.rel=o?"stylesheet":p,o||(n.as="script"),n.crossOrigin="",n.href=e,m&&n.setAttribute("nonce",m),document.head.appendChild(n),o)return new Promise((c,l)=>{n.addEventListener("load",c),n.addEventListener("error",()=>l(new Error(`Unable to preload CSS for ${e}`)))})}))}function h(r){const t=new Event("vite:preloadError",{cancelable:!0});if(t.payload=r,window.dispatchEvent(t),!t.defaultPrevented)throw r}return d.then(r=>{for(const t of r||[])t.status==="rejected"&&h(t.reason);return i().catch(h)})};export{w as _}; diff --git a/crates/rocket-sense-server/static/subtr-actor/review/assets/replayLoader.worker-BOmyAjmY.js b/crates/rocket-sense-server/static/subtr-actor/review/assets/replayLoader.worker-BOmyAjmY.js new file mode 100644 index 00000000..34a9e71b --- /dev/null +++ b/crates/rocket-sense-server/static/subtr-actor/review/assets/replayLoader.worker-BOmyAjmY.js @@ -0,0 +1,2 @@ +(function(){"use strict";function be(e,t,n,r){const o=pe(e,u.__wbindgen_malloc),i=x,a=u.get_replay_bundle_json_parts_with_progress(o,i,t,k(n)?4294967297:n>>>0,k(r)?4294967297:r>>>0);if(a[2])throw G(a[1]);return G(a[0])}function ge(){return{__proto__:null,"./rl_replay_subtr_actor_bg.js":{__proto__:null,__wbg_Error_8c4e43fe74559d73:function(t,n){return Error(P(t,n))},__wbg_Number_04624de7d0e8332d:function(t){return Number(t)},__wbg_String_8f0eb39a4a4c2f66:function(t,n){const r=String(n),o=F(r,u.__wbindgen_malloc,u.__wbindgen_realloc),i=x;y().setInt32(t+4,i,!0),y().setInt32(t+0,o,!0)},__wbg___wbindgen_bigint_get_as_i64_8fcf4ce7f1ca72a2:function(t,n){const r=n,o=typeof r=="bigint"?r:void 0;y().setBigInt64(t+8,k(o)?BigInt(0):o,!0),y().setInt32(t+0,!k(o),!0)},__wbg___wbindgen_boolean_get_bbbb1c18aa2f5e25:function(t){const n=t,r=typeof n=="boolean"?n:void 0;return k(r)?16777215:r?1:0},__wbg___wbindgen_debug_string_0bc8482c6e3508ae:function(t,n){const r=U(n),o=F(r,u.__wbindgen_malloc,u.__wbindgen_realloc),i=x;y().setInt32(t+4,i,!0),y().setInt32(t+0,o,!0)},__wbg___wbindgen_in_47fa6863be6f2f25:function(t,n){return t in n},__wbg___wbindgen_is_bigint_31b12575b56f32fc:function(t){return typeof t=="bigint"},__wbg___wbindgen_is_function_0095a73b8b156f76:function(t){return typeof t=="function"},__wbg___wbindgen_is_object_5ae8e5880f2c1fbd:function(t){const n=t;return typeof n=="object"&&n!==null},__wbg___wbindgen_is_string_cd444516edc5b180:function(t){return typeof t=="string"},__wbg___wbindgen_is_undefined_9e4d92534c42d778:function(t){return t===void 0},__wbg___wbindgen_jsval_eq_11888390b0186270:function(t,n){return t===n},__wbg___wbindgen_jsval_loose_eq_9dd77d8cd6671811:function(t,n){return t==n},__wbg___wbindgen_number_get_8ff4255516ccad3e:function(t,n){const r=n,o=typeof r=="number"?r:void 0;y().setFloat64(t+8,k(o)?0:o,!0),y().setInt32(t+0,!k(o),!0)},__wbg___wbindgen_string_get_72fb696202c56729:function(t,n){const r=n,o=typeof r=="string"?r:void 0;var i=k(o)?0:F(o,u.__wbindgen_malloc,u.__wbindgen_realloc),a=x;y().setInt32(t+4,a,!0),y().setInt32(t+0,i,!0)},__wbg___wbindgen_throw_be289d5034ed271b:function(t,n){throw new Error(P(t,n))},__wbg_call_389efe28435a9388:function(){return E(function(t,n){return t.call(n)},arguments)},__wbg_call_4708e0c13bdc8e95:function(){return E(function(t,n,r){return t.call(n,r)},arguments)},__wbg_done_57b39ecd9addfe81:function(t){return t.done},__wbg_entries_58c7934c745daac7:function(t){return Object.entries(t)},__wbg_error_7534b8e9a36f1ab4:function(t,n){let r,o;try{r=t,o=n,console.error(P(t,n))}finally{u.__wbindgen_free(r,o,1)}},__wbg_get_9b94d73e6221f75c:function(t,n){return t[n>>>0]},__wbg_get_b3ed3ad4be2bc8ac:function(){return E(function(t,n){return Reflect.get(t,n)},arguments)},__wbg_get_with_ref_key_1dc361bd10053bfe:function(t,n){return t[n]},__wbg_instanceof_ArrayBuffer_c367199e2fa2aa04:function(t){let n;try{n=t instanceof ArrayBuffer}catch{n=!1}return n},__wbg_instanceof_Map_53af74335dec57f4:function(t){let n;try{n=t instanceof Map}catch{n=!1}return n},__wbg_instanceof_Uint8Array_9b9075935c74707c:function(t){let n;try{n=t instanceof Uint8Array}catch{n=!1}return n},__wbg_isArray_d314bb98fcf08331:function(t){return Array.isArray(t)},__wbg_isSafeInteger_bfbc7332a9768d2a:function(t){return Number.isSafeInteger(t)},__wbg_iterator_6ff6560ca1568e55:function(){return Symbol.iterator},__wbg_length_32ed9a279acd054c:function(t){return t.length},__wbg_length_35a7bace40f36eac:function(t){return t.length},__wbg_log_f1a1b5cd3f9c7822:function(t,n){console.log(P(t,n))},__wbg_new_361308b2356cecd0:function(){return new Object},__wbg_new_3eb36ae241fe6f44:function(){return new Array},__wbg_new_8a6f238a6ece86ea:function(){return new Error},__wbg_new_dca287b076112a51:function(){return new Map},__wbg_new_dd2b680c8bf6ae29:function(t){return new Uint8Array(t)},__wbg_new_from_slice_a3d2629dc1826784:function(t,n){return new Uint8Array(Z(t,n))},__wbg_next_3482f54c49e8af19:function(){return E(function(t){return t.next()},arguments)},__wbg_next_418f80d8f5303233:function(t){return t.next},__wbg_prototypesetcall_bdcdcc5842e4d77d:function(t,n,r){Uint8Array.prototype.set.call(Z(t,n),r)},__wbg_push_8ffdcb2063340ba5:function(t,n){return t.push(n)},__wbg_set_1eb0999cf5d27fc8:function(t,n,r){return t.set(n,r)},__wbg_set_3f1d0b984ed272ed:function(t,n,r){t[n]=r},__wbg_set_6cb8631f80447a67:function(){return E(function(t,n,r){return Reflect.set(t,n,r)},arguments)},__wbg_set_f43e577aea94465b:function(t,n,r){t[n>>>0]=r},__wbg_stack_0ed75d68575b0f3c:function(t,n){const r=n.stack,o=F(r,u.__wbindgen_malloc,u.__wbindgen_realloc),i=x;y().setInt32(t+4,i,!0),y().setInt32(t+0,o,!0)},__wbg_value_0546255b415e96c1:function(t){return t.value},__wbindgen_cast_0000000000000001:function(t){return t},__wbindgen_cast_0000000000000002:function(t){return t},__wbindgen_cast_0000000000000003:function(t,n){return P(t,n)},__wbindgen_cast_0000000000000004:function(t){return BigInt.asUintN(64,t)},__wbindgen_init_externref_table:function(){const t=u.__wbindgen_externrefs,n=t.grow(4);t.set(0,void 0),t.set(n+0,void 0),t.set(n+1,null),t.set(n+2,!0),t.set(n+3,!1)}}}}function ye(e){const t=u.__externref_table_alloc();return u.__wbindgen_externrefs.set(t,e),t}function U(e){const t=typeof e;if(t=="number"||t=="boolean"||e==null)return`${e}`;if(t=="string")return`"${e}"`;if(t=="symbol"){const o=e.description;return o==null?"Symbol":`Symbol(${o})`}if(t=="function"){const o=e.name;return typeof o=="string"&&o.length>0?`Function(${o})`:"Function"}if(Array.isArray(e)){const o=e.length;let i="[";o>0&&(i+=U(e[0]));for(let a=1;a1)r=n[1];else return toString.call(e);if(r=="Object")try{return"Object("+JSON.stringify(e)+")"}catch{return"Object"}return e instanceof Error?`${e.name}: ${e.message} +${e.stack}`:r}function Z(e,t){return e=e>>>0,O().subarray(e/1,e/1+t)}let T=null;function y(){return(T===null||T.buffer.detached===!0||T.buffer.detached===void 0&&T.buffer!==u.memory.buffer)&&(T=new DataView(u.memory.buffer)),T}function P(e,t){return e=e>>>0,we(e,t)}let B=null;function O(){return(B===null||B.byteLength===0)&&(B=new Uint8Array(u.memory.buffer)),B}function E(e,t){try{return e.apply(this,t)}catch(n){const r=ye(n);u.__wbindgen_exn_store(r)}}function k(e){return e==null}function pe(e,t){const n=t(e.length*1,1)>>>0;return O().set(e,n/1),x=e.length,n}function F(e,t,n){if(n===void 0){const s=D.encode(e),l=t(s.length,1)>>>0;return O().subarray(l,l+s.length).set(s),x=s.length,l}let r=e.length,o=t(r,1)>>>0;const i=O();let a=0;for(;a127)break;i[o+a]=s}if(a!==r){a!==0&&(e=e.slice(a)),o=n(o,r,r=a+e.length*3,1)>>>0;const s=O().subarray(o+a,o+r),l=D.encodeInto(e,s);a+=l.written,o=n(o,r,a,1)>>>0}return x=a,o}function G(e){const t=u.__wbindgen_externrefs.get(e);return u.__externref_table_dealloc(e),t}let z=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});z.decode();const he=2146435072;let H=0;function we(e,t){return H+=t,H>=he&&(z=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),z.decode(),H=t),z.decode(O().subarray(e,e+t))}const D=new TextEncoder;"encodeInto"in D||(D.encodeInto=function(e,t){const n=D.encode(e);return t.set(n),{read:e.length,written:n.length}});let x=0,u;function ke(e,t){return u=e.exports,T=null,B=null,u.__wbindgen_start(),u}async function xe(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(o){if(e.ok&&n(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",o);else throw o}const r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{const r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}async function Ae(e){if(u!==void 0)return u;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0&&(e=new URL(""+new URL("rl_replay_subtr_actor_bg-BjSK7HJ9.wasm",self.location.href).href,self.location.href));const t=ge();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));const{instance:n,module:r}=await xe(await e,t);return ke(n)}const q="octane",Te={breakout:{kind:"breakout",label:"Breakout",length:131.4924,width:80.521,height:30.3,slopeDegrees:-.9795,groundHeightFront:43.8976,groundHeightBack:46.1454,offset:13.88,elevation:17.05},dominus:{kind:"dominus",label:"Dominus",length:127.9268,width:83.27995,height:31.3,slopeDegrees:-.9635,groundHeightFront:47.2238,groundHeightBack:49.3749,offset:13.88,elevation:17.05},hybrid:{kind:"hybrid",label:"Hybrid",length:127.0192,width:82.18787,height:34.15907,slopeDegrees:-.5499,groundHeightFront:54.0982,groundHeightBack:55.3173,offset:13.88,elevation:17.05},merc:{kind:"merc",label:"Merc",length:120.72,width:76.71,height:41.66,slopeDegrees:.28,groundHeightFront:60.76,groundHeightBack:61.35,offset:13.88,elevation:17.05},octane:{kind:"octane",label:"Octane",length:118.0074,width:84.19941,height:36.15907,slopeDegrees:-.5518,groundHeightFront:55.1449,groundHeightBack:56.2814,offset:13.88,elevation:17.05},plank:{kind:"plank",label:"Plank",length:128.8198,width:84.67036,height:29.3944,slopeDegrees:-.3447,groundHeightFront:44.998,groundHeightBack:45.773,offset:13.88,elevation:17.05}},Se={"16batmobile":"plank","70dodgechargerrt":"dominus","89batmobile":"dominus","99nissanskylinegtrr34":"hybrid",aftershock:"dominus",animusgp:"breakout",artemis:"plank",artemisg1:"plank",artemisgxt:"plank",astonmartinvalhalla:"breakout",backfire:"octane",backtothefuturetimemachine:"dominus",batmobile1989:"dominus",battlebus:"merc",breakout:"breakout",breakouttypes:"breakout",centio:"plank",centiov17:"plank",cyclone:"breakout",deloreantimemachine:"dominus",diestro:"dominus",dominus:"dominus",dominusgt:"dominus",endo:"hybrid",esper:"hybrid",fast4wd:"octane",fennec:"octane",gazellagt:"dominus",gizmo:"octane",grog:"octane",guardian:"dominus",guardiang1:"dominus",guardiangxt:"dominus",hotshot:"dominus",icecharger:"dominus",imperatordt5:"dominus",jager619rs:"hybrid",jurassicjeepwrangler:"octane",mantis:"plank",marauder:"octane",masamune:"dominus",maverick:"dominus",maverickg1:"dominus",maverickgxt:"dominus",mclaren570s:"dominus",merc:"merc",mr11:"dominus",nimbus:"hybrid",octane:"octane",octanezsr:"octane",paladin:"plank",proteus:"octane",ripper:"dominus",roadhog:"octane",roadhogxl:"octane",samurai:"breakout",scarab:"octane",takumi:"octane",takumirxt:"octane",thedarkknightstumbler:"octane",thedarkknightrisestumbler:"octane",triton:"octane",twinmilliii:"plank",twinzer:"octane",venom:"hybrid",vulcan:"octane",werewolf:"dominus",xdevil:"hybrid",xdevilmk2:"hybrid",zippy:"octane","1966cadillacdeville":"breakout",ace:"breakout",admiral:"dominus",azura:"breakout",behemoth:"merc",beskar:"hybrid",bmwm3e30:"dominus",bmwm2racing:"dominus",bmwm4gt3evo:"dominus",bmw1series:"octane",bmw1seriesrle:"octane",bmwm240i:"dominus",bugatticentodieci:"plank",bumblebee:"dominus",bumblebeecar:"dominus",chevroletastro:"merc",chevroletcorvettestingray:"breakout",chevroletcorvettezr1:"breakout",chryslerpacifica:"hybrid",corlay:"octane",cyberpunkquadra:"breakout",defenderd7xr:"merc",diesel:"breakout",dodgechargerdaytonascatpack:"dominus",dodgerchargerdaytonascatpack:"dominus",dominusneon:"dominus",emperor:"breakout",emperorii:"breakout",emperoriifrozen:"breakout",emperoriiscorched:"breakout",fastfuriousdodgecharger:"dominus",fastandfuriousdodgecharger:"dominus",fastandfuriousdodgechargersrthellcat:"dominus",fastfuriousmazdarx7:"breakout",fastandfuriousmazdarx7:"breakout",fastfuriousnissanskyline:"hybrid",fastandfuriousnissanskyline:"hybrid",fastfuriouspontiacfiero:"hybrid",fastandfuriouspontiacfiero:"hybrid",fenneczrf:"octane",ferrari296gtb:"dominus",ferrarif40:"breakout",fordbroncoraptorrle:"merc",fordf150rle:"octane",fordmustanggtd:"dominus",fordmustangshelbygt500:"dominus",fordmustangmacherle:"octane",fordmustangshelbygt350rrle:"dominus",formula12021:"plank",formula12022:"plank",fuse:"breakout",havoc:"breakout",hearse:"hybrid",homerscar:"dominus",hondacivictyper:"octane",hondacivictyperle:"octane",jackal:"octane",jeepwranglerrubicon:"octane",kitt:"dominus",knightindustries2000:"dominus",komodo:"breakout",lamborghinicountachlpi8004:"dominus",lamborghinihuracansto:"dominus",lamborghiniurus:"hybrid",lamborghiniurusse:"hybrid",lightningmcqueen:"dominus",lightningmcqueencar:"dominus",lockjaw:"dominus",luiginsr:"octane",maestro:"dominus",magnifique:"dominus",magnifiquegxt:"dominus",mako:"breakout",mamba:"dominus",mario:"octane",marionsr:"octane",maven:"dominus",mclaren765lt:"dominus",mclarenp1:"dominus",mclarensenna:"breakout",megastar:"breakout",mercedesamggt63s:"dominus",mercedesbenzcla:"dominus",mudcat:"octane",mudcatg1:"octane",mudcatgxt:"octane",nissan350z:"dominus",nissanfairladyz:"dominus",nissanfairladyzrle:"dominus",nissansilvia:"hybrid",nissansilviarle:"hybrid",nissanskylinegtr:"hybrid",nissanskylinegtrr32:"hybrid",nissanzperformance:"dominus",nissanzperformancecar:"dominus",outlaw:"octane",outlawgxt:"octane",pattywagon:"octane",pizzaplanetdeliverytruck:"merc",pontiacfirebird:"breakout",porsche918spyder:"breakout",porsche911gt3rs:"dominus",porsche911turbo:"dominus",porsche911turborle:"dominus",primo:"hybrid",psyclops:"octane",quadraturbor:"breakout",ram1500rho:"hybrid",recoilav:"merc",redline:"breakout",revolver:"breakout",rivianr1s:"hybrid",scorpion:"dominus",shokunin:"octane",shokuningxt:"octane",stampede:"merc",teslacybertruck:"hybrid",themysterymachine:"merc",theincredibile:"breakout",turtlevan:"merc",voidburn:"hybrid",volkswagengolfgti:"octane",volkswagengolfgtirle:"octane",xentari:"octane",zefira:"dominus",breakoutx:"breakout",nexus:"breakout",nexussc:"breakout",whiplash:"breakout","007sastonmartindbs":"dominus","007sastonmartinvalhalla":"dominus",batmobile2022:"dominus",chikara:"dominus",chikarag1:"dominus",chikaragxt:"dominus",ecto1:"dominus",ecto1ghostbusters:"dominus",fastfuriousdodgechargersrthellcat:"dominus",gazellagthotwheels:"dominus",kittknightrider:"dominus",lamborghinihuracnsto:"dominus",mr11hotwheels:"dominus",nascarchevroletcamaro:"dominus",nascarfordmustang:"dominus",nascartoyotacamry:"dominus",nascarnextgenchevroletcamaro:"dominus",nascarnextgenchevroletcamaro2022:"dominus",nascarnextgenfordmustang:"dominus",nascarnextgenfordmustang2022:"dominus",nascarnextgentoyotacamry:"dominus",nascarnextgentoyotacamry2022:"dominus",nemesis:"dominus",peregrinett:"dominus",perigrinett:"dominus",ronin:"dominus",roning1:"dominus",roningxt:"dominus",samusgunship:"dominus",samusgunshipnintendoexclusive:"dominus",tyranno:"dominus",tyrannogxt:"dominus",insidio:"hybrid",jager619:"hybrid",jger619:"hybrid",jger619rs:"hybrid",r3mx:"hybrid",r3mxgxt:"hybrid",tygris:"hybrid",nomad:"merc",nomadgxt:"merc","007sastonmartindb5":"octane",armadillo:"octane",armadilloxboxexclusive:"octane",boneshaker:"octane",dingo:"octane",fast4wdhotwheels:"octane",harbinger:"octane",harbingergxt:"octane",hogsticker:"octane",hogstickerxboxexclusive:"octane",sweettooth:"octane",sweettoothplaystationexclusive:"octane",thedarkknighttumbler:"octane",batmobile2016:"plank",sentinel:"plank"};function ve(e){const t={};for(const[n,r]of e)for(const o of n)t[o]=r;return t}const Oe=ve([[[22,1416,1894,1932,3031,3311,6243,6489,7651,7696,7890,7901,8006,8360,8361,8565,8566,8669,9357,10697,10698,10817,10822,11038,11394,11505,11677,11800,11933,11949,12173,12315,12361,12484],"breakout"],[[29,403,597,600,1018,1171,1286,1675,1689,1883,2070,2268,2666,2950,2951,3155,3156,3157,3265,3426,3875,3879,3880,4014,4155,4367,4472,4473,4745,4770,4781,4861,4864,5709,5773,5823,5858,5964,5979,6122,6244,6247,6260,6836,7211,7337,7338,7341,7343,7415,7512,7532,7593,7772,8454,9053,9088,9089,9140,9388,9894,10094,10440,10441,10694,10695,11016,11095,11315,11336,11534,11941,11996,12106,12142,12262,12286,12325,12382,12563,12669],"dominus"],[[28,31,1159,1317,1624,1856,2269,3451,3582,3702,5470,5488,5879,7012,9084,9085,9427,10044,10805,11138,11141,11379,11932,12569,12652],"hybrid"],[[30,4780,7336,7477,7815,7979,10689,11098,11736,11905,11950,12318,12335],"merc"],[[21,23,25,26,27,402,404,523,607,625,723,1172,1295,1300,1475,1478,1533,1568,1623,2665,2853,2919,2949,4284,4318,4319,4320,4782,4906,5020,5039,5188,5361,5547,5713,5837,5951,6939,7947,7948,8383,8806,8807,10896,10897,10900,10901,11314,11603,12104,12105],"octane"],[[24,803,1603,1691,1919,3594,3614,3622,4268,5265,7052,8524],"plank"]]);function J(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function Q(e){if(!e)return null;switch(J(e)){case"breakout":return"breakout";case"dominus":return"dominus";case"hybrid":return"hybrid";case"merc":return"merc";case"octane":return"octane";case"batmobile":case"plank":return"plank";default:return null}}function ee(e){return e?Se[J(e)]??null:null}function Ie(e){return Q(e)??ee(e)}function Pe(e){return Te[e]}function Y(e,t){if(!(!e||typeof e!="object")){if("Str"in e&&typeof e.Str=="string"){t.push(e.Str);return}if("Name"in e&&typeof e.Name=="string"){t.push(e.Name);return}if("Byte"in e&&e.Byte&&typeof e.Byte=="object"){const n=e.Byte;typeof n.kind=="string"&&t.push(n.kind),typeof n.value=="string"&&t.push(n.value);return}if("Struct"in e&&e.Struct&&typeof e.Struct=="object"){const n=e.Struct;if(typeof n.name=="string"&&t.push(n.name),Array.isArray(n.fields))for(const r of n.fields)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),Y(r[1],t));return}if("Array"in e&&Array.isArray(e.Array)){for(const n of e.Array)if(Array.isArray(n))for(const r of n)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),Y(r[1],t))}}}function Be(e){const t=Q(e?.car_hitbox_family);if(t)return t;const n=e?.car_body_id;if(typeof n=="number"){const a=Oe[n];if(a)return a}const r=ee(e?.car_body_name);if(r)return r;const o=e?.stats;if(!o)return q;const i=[];for(const[a,s]of Object.entries(o))i.push(a),Y(s,i);for(const a of i){const s=Ie(a);if(s)return s}return q}function A(e){const[t,n]=Object.entries(e)[0]??["Unknown","unknown"];return typeof n=="string"||typeof n=="number"?`${t}:${n}`:n&&typeof n=="object"?`${t}:${JSON.stringify(n)}`:`${t}:${JSON.stringify(n)}`}function N(e,t){return Math.max(0,e-t)}function te(e){return new Map(e.map(t=>[t.id,t]))}const p=70,ne=73,Ee=3072,De=4096,Ne=1792,Me=4184,Re=940,Fe=3308,ze=2816,re=3584,Ce=2484,je=1788,Le=2300,Ve=2048,Ue=1036,He=1024,Ye=1024,$e=4240,oe=34;function C(e,t,n,r,o){e.push({index:e.length,padId:null,size:o,position:{x:t,y:n,z:r},events:[]})}function j(e,t,n,r,o){C(e,-t,n,r,o),C(e,t,n,r,o)}function $(e,t,n,r,o){C(e,t,-n,r,o),C(e,t,n,r,o)}function I(e,t,n,r,o){j(e,t,-n,r,o),j(e,t,n,r,o)}function Xe(){const e=[];return $(e,0,$e,p,"small"),I(e,Ne,Me,p,"small"),I(e,Ee,De,ne,"big"),I(e,Re,Fe,p,"small"),$(e,0,ze,p,"small"),I(e,re,Ce,p,"small"),I(e,je,Le,p,"small"),I(e,Ve,Ue,p,"small"),$(e,0,Ye,p,"small"),j(e,re,0,ne,"big"),j(e,He,0,p,"small"),e}function X(e){if(e==="Available")return!0;if(e&&typeof e=="object"){if("Available"in e)return!0;if("PickedUp"in e)return!1;const t=e.kind;if(t==="Available")return!0;if(t==="PickedUp")return!1}return null}function We(e){return e==="big"||e==="Big"?"big":e==="small"||e==="Small"?"small":null}function Ke(e){let t=null;for(const n of e){const r=X(n.kind);if(r===!1){t=n.time;continue}if(r===!0&&t!==null)return n.time-t>=7?"big":"small"}return null}function Ze(e,t,n,r){const o=te(t),i=new Map;for(const c of e.boost_pad_events??[]){if(X(c.kind)===null){r?.advance();continue}const d=i.get(c.pad_id);d?d.push(c):i.set(c.pad_id,[c]),r?.advance()}const a=e.boost_pads;if(!a||a.length===0)return r?.advance(oe),Xe();const s=[...a].sort((c,f)=>c.index-f.index),l=new Array(s.length);for(let c=0;c=72?"big":"small"),h=g.sort((_,w)=>_.time-w.time),m=new Array(h.length);for(let _=0;_=0?e.frame:null}function Ge(e,t){if(typeof e.time=="number"&&Number.isFinite(e.time))return e.time;const n=W(e);if(n===null)return null;const r=t.frame_data.metadata_frames[n]?.time;return typeof r=="number"&&Number.isFinite(r)?r:null}function qe(e,t){return`bookmark:${W(e)??"unknown"}:${e.description||"tick-mark"}:${t}`}function Je(e,t,n){return(e.replay_tick_marks??[]).flatMap((r,o)=>{n?.advance();const i=Ge(r,e);return i===null?[]:[{id:qe(r,o),description:r.description,frame:W(r),time:N(i,t)}]})}function Qe(e){const t=e.description.trim()||"Replay bookmark";return{id:e.id,time:e.time,seekTime:e.time,frame:e.frame??void 0,kind:"bookmark",label:t,shortLabel:"BM",iconName:"bookmark"}}const S={distance:270,height:100,pitch:-4,fov:110},et=.005,tt=Number.POSITIVE_INFINITY,nt=!0,rt=.15,ot=10,at=.1,it=10;function ae(e){const t=Math.hypot(e.x,e.y,e.z);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t}}function ie(e){const t=Math.hypot(e.x,e.y,e.z,e.w);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t,w:e.w/t}}function se(e,t){return{w:e.w*t.w-e.x*t.x-e.y*t.y-e.z*t.z,x:e.w*t.x+e.x*t.w+e.y*t.z-e.z*t.y,y:e.w*t.y-e.x*t.z+e.y*t.w+e.z*t.x,z:e.w*t.z+e.x*t.y-e.y*t.x+e.z*t.w}}function ce(e,t){const n=se(se(t,{x:e.x,y:e.y,z:e.z,w:0}),{x:-t.x,y:-t.y,z:-t.z,w:t.w});return{x:n.x,y:n.y,z:n.z}}function st(e){if(e==="Empty")return{position:null,linearVelocity:null,angularVelocity:null,rotation:null};const t=e.Data.rigid_body;return{position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:ie(t.rotation)}}function ue(e){return e==null?null:Math.max(-1,Math.min(1,(e-128)/128))}function le(e){return e==null?null:(e>127?e-256:e)*Math.PI/128}function de(e){return e?{x:e[0],y:e[1],z:e[2]}:null}const ct={cameraPitch:null,cameraYaw:null,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null};function ut(e){if(e==="Empty")return{isPresent:!1,position:null,linearVelocity:null,angularVelocity:null,rotation:null,forward:null,up:null,boostAmount:0,boostFraction:0,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,...ct};const t=e.Data.rigid_body,n=ie(t.rotation),r=n?ae(ce({x:1,y:0,z:0},n)):null,o=n?ae(ce({x:0,y:0,z:1},n)):null,i=e.Data.camera,a=e.Data.input;return{isPresent:!0,position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:n,forward:r,up:o,boostAmount:e.Data.boost_amount,boostFraction:Math.max(0,Math.min(1,e.Data.boost_amount/255)),boostActive:e.Data.boost_active,powerslideActive:e.Data.powerslide_active,jumpActive:e.Data.jump_active,doubleJumpActive:e.Data.double_jump_active,dodgeActive:e.Data.dodge_active,cameraPitch:le(i?.pitch),cameraYaw:le(i?.yaw),throttle:ue(a?.throttle),steer:ue(a?.steer),dodgeImpulse:de(a?.dodge_impulse),dodgeTorque:de(a?.dodge_torque)}}function lt(e){return e.position!==null}function dt(e){return{...e,isPresent:!1,linearVelocity:null,angularVelocity:null,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null}}function ft(e){let t=null,n=null;for(let r=0;r=t.length-1)return;let o=M(t[r].position);for(let i=r+1;iat){o=M(s.position);continue}if(mt(o,s.position)>it){o=M(s.position);continue}const d={x:(a.linearVelocity.x+s.linearVelocity.x)/2,y:(a.linearVelocity.y+s.linearVelocity.y)/2,z:(a.linearVelocity.z+s.linearVelocity.z)/2},g={x:o.x+d.x*f,y:o.y+d.y*f,z:o.z+d.z*f},b=(i-r)%n.smoothingAnchorInterval===0?.5:n.smoothingBlendFactor;o={x:g.x*(1-b)+s.position.x*b,y:g.y*(1-b)+s.position.y*b,z:g.z*(1-b)+s.position.z*b},s.position=M(o)}}function _t(e){return{motionSmoothing:e.motionSmoothing??nt,smoothingBlendFactor:e.smoothingBlendFactor??rt,smoothingAnchorInterval:Math.max(1,e.smoothingAnchorInterval??ot)}}function _e(){return typeof performance>"u"?Date.now():performance.now()}function bt(e){const t=e.meta.team_zero.length+e.meta.team_one.length,n=e.frame_data.players.reduce((a,[,s])=>a+s.frames.length,0),r=e.boost_pads?.length??oe,o=e.boost_pad_events?.length??0,i=(e.goal_events?.length??0)+(e.player_stat_events?.length??0)+(e.demolish_infos?.length??0)+(e.replay_tick_marks?.length??0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,n),Math.max(1,e.frame_data.ball_data.frames.length),Math.max(1,r+o),Math.max(1,i)].reduce((a,s)=>a+s,0)}function gt(e){const t=e.frame_data.players.reduce((n,[,r])=>n+r.frames.length,0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,e.frame_data.ball_data.frames.length)].reduce((n,r)=>n+r,0)}function yt(e,t,n={}){const r=bt(e),o=gt(e);let i=0,a=0,s=-1,l=-1,c=_e();const f=n.yieldEveryMs??Number.POSITIVE_INFINITY,d=n.progressReportMinDelta??et,g=Math.max(1,n.progressReportFrameInterval??tt),b=()=>{if(!t)return!1;const m=Math.max(0,Math.min(1,i/r));if(m<=s)return!1;const w=a-l>=g;return m>=1||m-s>=d||w?(s=m,l=a,t(m,{progress:m,processedFrames:Math.min(a,o),totalFrames:o,processedUnits:i,totalUnits:r}),!0):!1},h=(m=!1)=>{const _=_e();return!m&&_-cr===t)?.[1];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function kt(e){const t=wt(e?.stats);return{fov:v(t,"CameraFOV")??S.fov,height:v(t,"CameraHeight")??S.height,pitch:v(t,"CameraPitch")??S.pitch,distance:v(t,"CameraDistance")??S.distance,stiffness:v(t,"CameraStiffness")??S.stiffness,swivelSpeed:v(t,"CameraSwivelSpeed")??S.swivelSpeed,transitionSpeed:v(t,"CameraTransitionSpeed")??S.transitionSpeed}}function xt(e,t){const n=new Map,r=new Map,o=[...e.meta.team_zero,...e.meta.team_one];if(o.length===0)return t?.advance(),{byId:n,byName:r};for(const i of o)r.set(i.name,i),i.remote_id&&n.set(A(i.remote_id),i),t?.advance();return{byId:n,byName:r}}function At(e){const t=new Map;for(const[n,r]of e.player_camera_events??[])t.set(A(n),r.map(o=>({frame:o.frame,ballCamActive:o.ball_cam_active,behindViewActive:o.behind_view_active,driving:o.driving})));return t}function Tt(e,t){const n=new Set(e.meta.team_zero.map(l=>l.name)),r=new Set(e.meta.team_one.map(l=>l.name)),o=xt(e,t),i=At(e),a=[];let s=0;for(const[l,c]of e.frame_data.players){const f=new Array(c.frames.length);let d;for(let m=0;mt.time!==n.time?t.time-n.time:(t.frame??0)-(n.frame??0))}function Ot(e,t,n){const r=e.player?A(e.player):null,o=r?t.get(r)?.name??r:null,i=o?`${o} scored`:"Goal";return{id:K("goal",e.frame,r??"team"),time:N(e.time,n),frame:e.frame,kind:"goal",label:i,shortLabel:"G",playerId:r,playerName:o,isTeamZero:e.scoring_team_is_team_0}}function It(e,t,n){const r=A(e.player),o=t.get(r)?.name??r,i=e.kind.toLowerCase(),a=e.kind==="Shot"?"shot":e.kind==="Save"?"save":"assist",s=e.kind==="Shot"?"SH":e.kind==="Save"?"SV":"A";return{id:K(i,e.frame,r),time:N(e.time,n),frame:e.frame,kind:i,label:`${o} ${a}`,shortLabel:s,playerId:r,playerName:o,location:e.shot?.shot_touch_position??e.shot?.ball_position??null,shot:e.shot??null,isTeamZero:e.is_team_0}}function Pt(e,t,n){const r=A(e.attacker),o=A(e.victim),i=t.get(r),a=t.get(o);return{id:K("demo",e.frame,`${r}:${o}`),time:N(e.time,n),frame:e.frame,kind:"demo",label:`${i?.name??r} demoed ${a?.name??o}`,shortLabel:"D",playerId:r,playerName:i?.name??r,secondaryPlayerId:o,secondaryPlayerName:a?.name??o,location:e.victim_location,isTeamZero:i?.isTeamZero??null}}function Bt(e,t,n,r,o){const i=te(t),a=[];for(const s of e.goal_events??[])a.push(Ot(s,i,r)),o?.advance();for(const s of e.player_stat_events??[])a.push(It(s,i,r)),o?.advance();for(const s of e.demolish_infos??[])a.push(Pt(s,i,r)),o?.advance();for(const s of n)a.push(Qe(s));return a.length===0&&o?.advance(),vt(a)}function Et(e,t={}){const n=yt(e,t.onProgress,{progressReportMinDelta:t.progressReportMinDelta,progressReportFrameInterval:t.progressReportFrameInterval}),r=e.frame_data.metadata_frames[0]?.time??0,o=pt(e,n),i=Tt(e,n),a=St(e,n),s=_t(t);me(o,a,s);for(const d of i)me(o,d.frames,s);const l=Ze(e,i,r,n),c=Je(e,r,n),f=Bt(e,i,c,r,n);return n.finish(),{frameCount:o.length,duration:o.at(-1)?.time??0,rawStartTime:r,frames:o,ballFrames:a,boostPads:l,players:i,tickMarks:c,timelineEvents:f,teamZeroNames:e.meta.team_zero.map(d=>d.name),teamOneNames:e.meta.team_one.map(d=>d.name)}}function L(e){if(e instanceof Map)return Object.fromEntries(Array.from(e.entries()).map(([t,n])=>[t,L(n)]));if(Array.isArray(e))return e.map(t=>L(t));if(e&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=L(r);return t}return e}async function Dt(){const e=Ae;typeof e=="function"&&await e()}function R(e){self.postMessage(e)}self.onmessage=async e=>{if(e.data.type==="load-replay")try{await Dt();const t=new Uint8Array(e.data.bytes);R({type:"progress",progress:{stage:"validating",progress:0}});const n=be(t,c=>{R({type:"progress",progress:L(c)})},e.data.reportEveryNFrames,32*1024*1024);R({type:"progress",progress:{stage:"normalizing",progress:0}});const r=JSON.parse(new TextDecoder().decode(n.rawReplayData)),o=Et(r,{progressReportFrameInterval:e.data.reportEveryNFrames,onProgress(c){R({type:"progress",progress:{stage:"normalizing",progress:c}})}}),i=new TextEncoder().encode(JSON.stringify(o)),a=n.rawReplayData,s=a.byteOffset===0&&a.byteLength===a.buffer.byteLength?a.buffer:a.slice().buffer,l=Array.from(n.statsTimelineParts.frameChunks,c=>c.buffer);self.postMessage({type:"done",replayBuffer:i.buffer,rawReplayBuffer:s,statsTimelineParts:{configBuffer:n.statsTimelineParts.config.buffer,replayMetaBuffer:n.statsTimelineParts.replayMeta.buffer,eventsBuffer:n.statsTimelineParts.events.buffer,activitySummaryBuffer:n.statsTimelineParts.activitySummary.buffer,positioningSummaryBuffer:n.statsTimelineParts.positioningSummary.buffer,accumulationTracksBuffer:n.statsTimelineParts.accumulationTracks.buffer,frameChunkBuffers:l}},[i.buffer,s,n.statsTimelineParts.config.buffer,n.statsTimelineParts.replayMeta.buffer,n.statsTimelineParts.events.buffer,n.statsTimelineParts.activitySummary.buffer,n.statsTimelineParts.positioningSummary.buffer,n.statsTimelineParts.accumulationTracks.buffer,...l])}catch(t){R({type:"error",error:t instanceof Error?t.message:String(t)})}}})(); diff --git a/crates/rocket-sense-server/static/subtr-actor/review/assets/replayLoader.worker-D3pjMe81.js b/crates/rocket-sense-server/static/subtr-actor/review/assets/replayLoader.worker-D3pjMe81.js deleted file mode 100644 index 1217437e..00000000 --- a/crates/rocket-sense-server/static/subtr-actor/review/assets/replayLoader.worker-D3pjMe81.js +++ /dev/null @@ -1 +0,0 @@ -(function(){"use strict";function fe(e,t,n,r){const o=ge(e,m.__wbindgen_malloc),i=x,a=m.get_replay_bundle_json_parts_with_progress(o,i,t,L(n)?4294967297:n>>>0,L(r)?4294967297:r>>>0);if(a[2])throw K(a[1]);return K(a[0])}function be(){return{__proto__:null,"./rl_replay_subtr_actor_bg.js":{__proto__:null,__wbg_Error_8c4e43fe74559d73:function(t,n){return Error(I(t,n))},__wbg_String_8f0eb39a4a4c2f66:function(t,n){const r=String(n),o=V(r,m.__wbindgen_malloc,m.__wbindgen_realloc),i=x;T().setInt32(t+4,i,!0),T().setInt32(t+0,o,!0)},__wbg___wbindgen_is_string_cd444516edc5b180:function(t){return typeof t=="string"},__wbg___wbindgen_string_get_72fb696202c56729:function(t,n){const r=n,o=typeof r=="string"?r:void 0;var i=L(o)?0:V(o,m.__wbindgen_malloc,m.__wbindgen_realloc),a=x;T().setInt32(t+4,a,!0),T().setInt32(t+0,i,!0)},__wbg___wbindgen_throw_be289d5034ed271b:function(t,n){throw new Error(I(t,n))},__wbg_call_4708e0c13bdc8e95:function(){return W(function(t,n,r){return t.call(n,r)},arguments)},__wbg_error_7534b8e9a36f1ab4:function(t,n){let r,o;try{r=t,o=n,console.error(I(t,n))}finally{m.__wbindgen_free(r,o,1)}},__wbg_log_d095c16a726a937c:function(t,n){console.log(I(t,n))},__wbg_new_361308b2356cecd0:function(){return new Object},__wbg_new_3eb36ae241fe6f44:function(){return new Array},__wbg_new_8a6f238a6ece86ea:function(){return new Error},__wbg_new_dca287b076112a51:function(){return new Map},__wbg_new_from_slice_a3d2629dc1826784:function(t,n){return new Uint8Array(ye(t,n))},__wbg_push_8ffdcb2063340ba5:function(t,n){return t.push(n)},__wbg_set_1eb0999cf5d27fc8:function(t,n,r){return t.set(n,r)},__wbg_set_3f1d0b984ed272ed:function(t,n,r){t[n]=r},__wbg_set_6cb8631f80447a67:function(){return W(function(t,n,r){return Reflect.set(t,n,r)},arguments)},__wbg_set_f43e577aea94465b:function(t,n,r){t[n>>>0]=r},__wbg_stack_0ed75d68575b0f3c:function(t,n){const r=n.stack,o=V(r,m.__wbindgen_malloc,m.__wbindgen_realloc),i=x;T().setInt32(t+4,i,!0),T().setInt32(t+0,o,!0)},__wbindgen_cast_0000000000000001:function(t){return t},__wbindgen_cast_0000000000000002:function(t){return t},__wbindgen_cast_0000000000000003:function(t,n){return I(t,n)},__wbindgen_cast_0000000000000004:function(t){return BigInt.asUintN(64,t)},__wbindgen_init_externref_table:function(){const t=m.__wbindgen_externrefs,n=t.grow(4);t.set(0,void 0),t.set(n+0,void 0),t.set(n+1,null),t.set(n+2,!0),t.set(n+3,!1)}}}}function _e(e){const t=m.__externref_table_alloc();return m.__wbindgen_externrefs.set(t,e),t}function ye(e,t){return e=e>>>0,S().subarray(e/1,e/1+t)}let w=null;function T(){return(w===null||w.buffer.detached===!0||w.buffer.detached===void 0&&w.buffer!==m.memory.buffer)&&(w=new DataView(m.memory.buffer)),w}function I(e,t){return e=e>>>0,he(e,t)}let P=null;function S(){return(P===null||P.byteLength===0)&&(P=new Uint8Array(m.memory.buffer)),P}function W(e,t){try{return e.apply(this,t)}catch(n){const r=_e(n);m.__wbindgen_exn_store(r)}}function L(e){return e==null}function ge(e,t){const n=t(e.length*1,1)>>>0;return S().set(e,n/1),x=e.length,n}function V(e,t,n){if(n===void 0){const s=B.encode(e),l=t(s.length,1)>>>0;return S().subarray(l,l+s.length).set(s),x=s.length,l}let r=e.length,o=t(r,1)>>>0;const i=S();let a=0;for(;a127)break;i[o+a]=s}if(a!==r){a!==0&&(e=e.slice(a)),o=n(o,r,r=a+e.length*3,1)>>>0;const s=S().subarray(o+a,o+r),l=B.encodeInto(e,s);a+=l.written,o=n(o,r,a,1)>>>0}return x=a,o}function K(e){const t=m.__wbindgen_externrefs.get(e);return m.__externref_table_dealloc(e),t}let M=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});M.decode();const pe=2146435072;let j=0;function he(e,t){return j+=t,j>=pe&&(M=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),M.decode(),j=t),M.decode(S().subarray(e,e+t))}const B=new TextEncoder;"encodeInto"in B||(B.encodeInto=function(e,t){const n=B.encode(e);return t.set(n),{read:e.length,written:n.length}});let x=0,m;function ke(e,t){return m=e.exports,w=null,P=null,m.__wbindgen_start(),m}async function we(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(o){if(e.ok&&n(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",o);else throw o}const r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{const r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}async function xe(e){if(m!==void 0)return m;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0&&(e=new URL(""+new URL("rl_replay_subtr_actor_bg-Xy9_Ya42.wasm",self.location.href).href,self.location.href));const t=be();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));const{instance:n,module:r}=await we(await e,t);return ke(n)}const Z="octane",Ae={breakout:{kind:"breakout",label:"Breakout",length:131.4924,width:80.521,height:30.3,slopeDegrees:-.9795,groundHeightFront:43.8976,groundHeightBack:46.1454,offset:13.88,elevation:17.05},dominus:{kind:"dominus",label:"Dominus",length:127.9268,width:83.27995,height:31.3,slopeDegrees:-.9635,groundHeightFront:47.2238,groundHeightBack:49.3749,offset:13.88,elevation:17.05},hybrid:{kind:"hybrid",label:"Hybrid",length:127.0192,width:82.18787,height:34.15907,slopeDegrees:-.5499,groundHeightFront:54.0982,groundHeightBack:55.3173,offset:13.88,elevation:17.05},merc:{kind:"merc",label:"Merc",length:120.72,width:76.71,height:41.66,slopeDegrees:.28,groundHeightFront:60.76,groundHeightBack:61.35,offset:13.88,elevation:17.05},octane:{kind:"octane",label:"Octane",length:118.0074,width:84.19941,height:36.15907,slopeDegrees:-.5518,groundHeightFront:55.1449,groundHeightBack:56.2814,offset:13.88,elevation:17.05},plank:{kind:"plank",label:"Plank",length:128.8198,width:84.67036,height:29.3944,slopeDegrees:-.3447,groundHeightFront:44.998,groundHeightBack:45.773,offset:13.88,elevation:17.05}},ve={"16batmobile":"plank","70dodgechargerrt":"dominus","89batmobile":"dominus","99nissanskylinegtrr34":"hybrid",aftershock:"dominus",animusgp:"breakout",artemis:"plank",artemisg1:"plank",artemisgxt:"plank",astonmartinvalhalla:"breakout",backfire:"octane",backtothefuturetimemachine:"dominus",batmobile1989:"dominus",battlebus:"merc",breakout:"breakout",breakouttypes:"breakout",centio:"plank",centiov17:"plank",cyclone:"breakout",deloreantimemachine:"dominus",diestro:"dominus",dominus:"dominus",dominusgt:"dominus",endo:"hybrid",esper:"hybrid",fast4wd:"octane",fennec:"octane",gazellagt:"dominus",gizmo:"octane",grog:"octane",guardian:"dominus",guardiang1:"dominus",guardiangxt:"dominus",hotshot:"dominus",icecharger:"dominus",imperatordt5:"dominus",jager619rs:"hybrid",jurassicjeepwrangler:"octane",mantis:"plank",marauder:"octane",masamune:"dominus",maverick:"dominus",maverickg1:"dominus",maverickgxt:"dominus",mclaren570s:"dominus",merc:"merc",mr11:"dominus",nimbus:"hybrid",octane:"octane",octanezsr:"octane",paladin:"plank",proteus:"octane",ripper:"dominus",roadhog:"octane",roadhogxl:"octane",samurai:"breakout",scarab:"octane",takumi:"octane",takumirxt:"octane",thedarkknightstumbler:"octane",thedarkknightrisestumbler:"octane",triton:"octane",twinmilliii:"plank",twinzer:"octane",venom:"hybrid",vulcan:"octane",werewolf:"dominus",xdevil:"hybrid",xdevilmk2:"hybrid",zippy:"octane","1966cadillacdeville":"breakout",ace:"breakout",admiral:"dominus",azura:"breakout",behemoth:"merc",beskar:"hybrid",bmwm3e30:"dominus",bmwm2racing:"dominus",bmwm4gt3evo:"dominus",bmw1series:"octane",bmw1seriesrle:"octane",bmwm240i:"dominus",bugatticentodieci:"plank",bumblebee:"dominus",bumblebeecar:"dominus",chevroletastro:"merc",chevroletcorvettestingray:"breakout",chevroletcorvettezr1:"breakout",chryslerpacifica:"hybrid",corlay:"octane",cyberpunkquadra:"breakout",defenderd7xr:"merc",diesel:"breakout",dodgechargerdaytonascatpack:"dominus",dodgerchargerdaytonascatpack:"dominus",dominusneon:"dominus",emperor:"breakout",emperorii:"breakout",emperoriifrozen:"breakout",emperoriiscorched:"breakout",fastfuriousdodgecharger:"dominus",fastandfuriousdodgecharger:"dominus",fastandfuriousdodgechargersrthellcat:"dominus",fastfuriousmazdarx7:"breakout",fastandfuriousmazdarx7:"breakout",fastfuriousnissanskyline:"hybrid",fastandfuriousnissanskyline:"hybrid",fastfuriouspontiacfiero:"hybrid",fastandfuriouspontiacfiero:"hybrid",fenneczrf:"octane",ferrari296gtb:"dominus",ferrarif40:"breakout",fordbroncoraptorrle:"merc",fordf150rle:"octane",fordmustanggtd:"dominus",fordmustangshelbygt500:"dominus",fordmustangmacherle:"octane",fordmustangshelbygt350rrle:"dominus",formula12021:"plank",formula12022:"plank",fuse:"breakout",havoc:"breakout",hearse:"hybrid",homerscar:"dominus",hondacivictyper:"octane",hondacivictyperle:"octane",jackal:"octane",jeepwranglerrubicon:"octane",kitt:"dominus",knightindustries2000:"dominus",komodo:"breakout",lamborghinicountachlpi8004:"dominus",lamborghinihuracansto:"dominus",lamborghiniurus:"hybrid",lamborghiniurusse:"hybrid",lightningmcqueen:"dominus",lightningmcqueencar:"dominus",lockjaw:"dominus",luiginsr:"octane",maestro:"dominus",magnifique:"dominus",magnifiquegxt:"dominus",mako:"breakout",mamba:"dominus",mario:"octane",marionsr:"octane",maven:"dominus",mclaren765lt:"dominus",mclarenp1:"dominus",mclarensenna:"breakout",megastar:"breakout",mercedesamggt63s:"dominus",mercedesbenzcla:"dominus",mudcat:"octane",mudcatg1:"octane",mudcatgxt:"octane",nissan350z:"dominus",nissanfairladyz:"dominus",nissanfairladyzrle:"dominus",nissansilvia:"hybrid",nissansilviarle:"hybrid",nissanskylinegtr:"hybrid",nissanskylinegtrr32:"hybrid",nissanzperformance:"dominus",nissanzperformancecar:"dominus",outlaw:"octane",outlawgxt:"octane",pattywagon:"octane",pizzaplanetdeliverytruck:"merc",pontiacfirebird:"breakout",porsche918spyder:"breakout",porsche911gt3rs:"dominus",porsche911turbo:"dominus",porsche911turborle:"dominus",primo:"hybrid",psyclops:"octane",quadraturbor:"breakout",ram1500rho:"hybrid",recoilav:"merc",redline:"breakout",revolver:"breakout",rivianr1s:"hybrid",scorpion:"dominus",shokunin:"octane",shokuningxt:"octane",stampede:"merc",teslacybertruck:"hybrid",themysterymachine:"merc",theincredibile:"breakout",turtlevan:"merc",voidburn:"hybrid",volkswagengolfgti:"octane",volkswagengolfgtirle:"octane",xentari:"octane",zefira:"dominus",breakoutx:"breakout",nexus:"breakout",nexussc:"breakout",whiplash:"breakout","007sastonmartindbs":"dominus","007sastonmartinvalhalla":"dominus",batmobile2022:"dominus",chikara:"dominus",chikarag1:"dominus",chikaragxt:"dominus",ecto1:"dominus",ecto1ghostbusters:"dominus",fastfuriousdodgechargersrthellcat:"dominus",gazellagthotwheels:"dominus",kittknightrider:"dominus",lamborghinihuracnsto:"dominus",mr11hotwheels:"dominus",nascarchevroletcamaro:"dominus",nascarfordmustang:"dominus",nascartoyotacamry:"dominus",nascarnextgenchevroletcamaro:"dominus",nascarnextgenchevroletcamaro2022:"dominus",nascarnextgenfordmustang:"dominus",nascarnextgenfordmustang2022:"dominus",nascarnextgentoyotacamry:"dominus",nascarnextgentoyotacamry2022:"dominus",nemesis:"dominus",peregrinett:"dominus",perigrinett:"dominus",ronin:"dominus",roning1:"dominus",roningxt:"dominus",samusgunship:"dominus",samusgunshipnintendoexclusive:"dominus",tyranno:"dominus",tyrannogxt:"dominus",insidio:"hybrid",jager619:"hybrid",jger619:"hybrid",jger619rs:"hybrid",r3mx:"hybrid",r3mxgxt:"hybrid",tygris:"hybrid",nomad:"merc",nomadgxt:"merc","007sastonmartindb5":"octane",armadillo:"octane",armadilloxboxexclusive:"octane",boneshaker:"octane",dingo:"octane",fast4wdhotwheels:"octane",harbinger:"octane",harbingergxt:"octane",hogsticker:"octane",hogstickerxboxexclusive:"octane",sweettooth:"octane",sweettoothplaystationexclusive:"octane",thedarkknighttumbler:"octane",batmobile2016:"plank",sentinel:"plank"};function Te(e){const t={};for(const[n,r]of e)for(const o of n)t[o]=r;return t}const Se=Te([[[22,1416,1894,1932,3031,3311,6243,6489,7651,7696,7890,7901,8006,8360,8361,8565,8566,8669,9357,10697,10698,10817,10822,11038,11394,11505,11677,11800,11933,11949,12173,12315,12361,12484],"breakout"],[[29,403,597,600,1018,1171,1286,1675,1689,1883,2070,2268,2666,2950,2951,3155,3156,3157,3265,3426,3875,3879,3880,4014,4155,4367,4472,4473,4745,4770,4781,4861,4864,5709,5773,5823,5858,5964,5979,6122,6244,6247,6260,6836,7211,7337,7338,7341,7343,7415,7512,7532,7593,7772,8454,9053,9088,9089,9140,9388,9894,10094,10440,10441,10694,10695,11016,11095,11315,11336,11534,11941,11996,12106,12142,12262,12286,12325,12382,12563,12669],"dominus"],[[28,31,1159,1317,1624,1856,2269,3451,3582,3702,5470,5488,5879,7012,9084,9085,9427,10044,10805,11138,11141,11379,11932,12569,12652],"hybrid"],[[30,4780,7336,7477,7815,7979,10689,11098,11736,11905,11950,12318,12335],"merc"],[[21,23,25,26,27,402,404,523,607,625,723,1172,1295,1300,1475,1478,1533,1568,1623,2665,2853,2919,2949,4284,4318,4319,4320,4782,4906,5020,5039,5188,5361,5547,5713,5837,5951,6939,7947,7948,8383,8806,8807,10896,10897,10900,10901,11314,11603,12104,12105],"octane"],[[24,803,1603,1691,1919,3594,3614,3622,4268,5265,7052,8524],"plank"]]);function G(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function q(e){if(!e)return null;switch(G(e)){case"breakout":return"breakout";case"dominus":return"dominus";case"hybrid":return"hybrid";case"merc":return"merc";case"octane":return"octane";case"batmobile":case"plank":return"plank";default:return null}}function J(e){return e?ve[G(e)]??null:null}function Oe(e){return q(e)??J(e)}function Ie(e){return Ae[e]}function H(e,t){if(!(!e||typeof e!="object")){if("Str"in e&&typeof e.Str=="string"){t.push(e.Str);return}if("Name"in e&&typeof e.Name=="string"){t.push(e.Name);return}if("Byte"in e&&e.Byte&&typeof e.Byte=="object"){const n=e.Byte;typeof n.kind=="string"&&t.push(n.kind),typeof n.value=="string"&&t.push(n.value);return}if("Struct"in e&&e.Struct&&typeof e.Struct=="object"){const n=e.Struct;if(typeof n.name=="string"&&t.push(n.name),Array.isArray(n.fields))for(const r of n.fields)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),H(r[1],t));return}if("Array"in e&&Array.isArray(e.Array)){for(const n of e.Array)if(Array.isArray(n))for(const r of n)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),H(r[1],t))}}}function Pe(e){const t=q(e?.car_hitbox_family);if(t)return t;const n=e?.car_body_id;if(typeof n=="number"){const a=Se[n];if(a)return a}const r=J(e?.car_body_name);if(r)return r;const o=e?.stats;if(!o)return Z;const i=[];for(const[a,s]of Object.entries(o))i.push(a),H(s,i);for(const a of i){const s=Oe(a);if(s)return s}return Z}function k(e){const[t,n]=Object.entries(e)[0]??["Unknown","unknown"];return typeof n=="string"||typeof n=="number"?`${t}:${n}`:n&&typeof n=="object"?`${t}:${JSON.stringify(n)}`:`${t}:${JSON.stringify(n)}`}function E(e,t){return Math.max(0,e-t)}function Q(e){return new Map(e.map(t=>[t.id,t]))}const g=70,ee=73,Be=3072,Ee=4096,De=1792,Re=4184,Me=940,Ne=3308,ze=2816,te=3584,Fe=2484,Ce=1788,Le=2300,Ve=2048,je=1036,He=1024,Ue=1024,Ye=4240,ne=34;function N(e,t,n,r,o){e.push({index:e.length,padId:null,size:o,position:{x:t,y:n,z:r},events:[]})}function z(e,t,n,r,o){N(e,-t,n,r,o),N(e,t,n,r,o)}function U(e,t,n,r,o){N(e,t,-n,r,o),N(e,t,n,r,o)}function O(e,t,n,r,o){z(e,t,-n,r,o),z(e,t,n,r,o)}function $e(){const e=[];return U(e,0,Ye,g,"small"),O(e,De,Re,g,"small"),O(e,Be,Ee,ee,"big"),O(e,Me,Ne,g,"small"),U(e,0,ze,g,"small"),O(e,te,Fe,g,"small"),O(e,Ce,Le,g,"small"),O(e,Ve,je,g,"small"),U(e,0,Ue,g,"small"),z(e,te,0,ee,"big"),z(e,He,0,g,"small"),e}function Y(e){if(e==="Available")return!0;if(e&&typeof e=="object"){if("Available"in e)return!0;if("PickedUp"in e)return!1;const t=e.kind;if(t==="Available")return!0;if(t==="PickedUp")return!1}return null}function Xe(e){return e==="big"||e==="Big"?"big":e==="small"||e==="Small"?"small":null}function We(e){let t=null;for(const n of e){const r=Y(n.kind);if(r===!1){t=n.time;continue}if(r===!0&&t!==null)return n.time-t>=7?"big":"small"}return null}function Ke(e,t,n,r){const o=Q(t),i=new Map;for(const c of e.boost_pad_events??[]){if(Y(c.kind)===null){r?.advance();continue}const u=i.get(c.pad_id);u?u.push(c):i.set(c.pad_id,[c]),r?.advance()}const a=e.boost_pads;if(!a||a.length===0)return r?.advance(ne),$e();const s=[...a].sort((c,d)=>c.index-d.index),l=new Array(s.length);for(let c=0;c=72?"big":"small"),p=y.sort((b,h)=>b.time-h.time),f=new Array(p.length);for(let b=0;b=0?e.frame:null}function Ze(e,t){if(typeof e.time=="number"&&Number.isFinite(e.time))return e.time;const n=$(e);if(n===null)return null;const r=t.frame_data.metadata_frames[n]?.time;return typeof r=="number"&&Number.isFinite(r)?r:null}function Ge(e,t){return`bookmark:${$(e)??"unknown"}:${e.description||"tick-mark"}:${t}`}function qe(e,t,n){return(e.replay_tick_marks??[]).flatMap((r,o)=>{n?.advance();const i=Ze(r,e);return i===null?[]:[{id:Ge(r,o),description:r.description,frame:$(r),time:E(i,t)}]})}function Je(e){const t=e.description.trim()||"Replay bookmark";return{id:e.id,time:e.time,seekTime:e.time,frame:e.frame??void 0,kind:"bookmark",label:t,shortLabel:"BM",iconName:"bookmark"}}const A={distance:270,height:100,pitch:-4,fov:110},Qe=.005,et=Number.POSITIVE_INFINITY,tt=!0,nt=.15,rt=10,ot=.1,at=10;function re(e){const t=Math.hypot(e.x,e.y,e.z);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t}}function oe(e){const t=Math.hypot(e.x,e.y,e.z,e.w);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t,w:e.w/t}}function ae(e,t){return{w:e.w*t.w-e.x*t.x-e.y*t.y-e.z*t.z,x:e.w*t.x+e.x*t.w+e.y*t.z-e.z*t.y,y:e.w*t.y-e.x*t.z+e.y*t.w+e.z*t.x,z:e.w*t.z+e.x*t.y-e.y*t.x+e.z*t.w}}function ie(e,t){const n=ae(ae(t,{x:e.x,y:e.y,z:e.z,w:0}),{x:-t.x,y:-t.y,z:-t.z,w:t.w});return{x:n.x,y:n.y,z:n.z}}function it(e){if(e==="Empty")return{position:null,linearVelocity:null,angularVelocity:null,rotation:null};const t=e.Data.rigid_body;return{position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:oe(t.rotation)}}function se(e){return e==null?null:Math.max(-1,Math.min(1,(e-128)/128))}function ce(e){return e==null?null:(e>127?e-256:e)*Math.PI/128}function le(e){return e?{x:e[0],y:e[1],z:e[2]}:null}const st={cameraPitch:null,cameraYaw:null,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null};function ct(e){if(e==="Empty")return{isPresent:!1,position:null,linearVelocity:null,angularVelocity:null,rotation:null,forward:null,up:null,boostAmount:0,boostFraction:0,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,...st};const t=e.Data.rigid_body,n=oe(t.rotation),r=n?re(ie({x:1,y:0,z:0},n)):null,o=n?re(ie({x:0,y:0,z:1},n)):null,i=e.Data.camera,a=e.Data.input;return{isPresent:!0,position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:n,forward:r,up:o,boostAmount:e.Data.boost_amount,boostFraction:Math.max(0,Math.min(1,e.Data.boost_amount/255)),boostActive:e.Data.boost_active,powerslideActive:e.Data.powerslide_active,jumpActive:e.Data.jump_active,doubleJumpActive:e.Data.double_jump_active,dodgeActive:e.Data.dodge_active,cameraPitch:ce(i?.pitch),cameraYaw:ce(i?.yaw),throttle:se(a?.throttle),steer:se(a?.steer),dodgeImpulse:le(a?.dodge_impulse),dodgeTorque:le(a?.dodge_torque)}}function lt(e){return e.position!==null}function ut(e){return{...e,isPresent:!1,linearVelocity:null,angularVelocity:null,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null}}function mt(e){let t=null,n=null;for(let r=0;r=t.length-1)return;let o=D(t[r].position);for(let i=r+1;iot){o=D(s.position);continue}if(dt(o,s.position)>at){o=D(s.position);continue}const u={x:(a.linearVelocity.x+s.linearVelocity.x)/2,y:(a.linearVelocity.y+s.linearVelocity.y)/2,z:(a.linearVelocity.z+s.linearVelocity.z)/2},y={x:o.x+u.x*d,y:o.y+u.y*d,z:o.z+u.z*d},_=(i-r)%n.smoothingAnchorInterval===0?.5:n.smoothingBlendFactor;o={x:y.x*(1-_)+s.position.x*_,y:y.y*(1-_)+s.position.y*_,z:y.z*(1-_)+s.position.z*_},s.position=D(o)}}function ft(e){return{motionSmoothing:e.motionSmoothing??tt,smoothingBlendFactor:e.smoothingBlendFactor??nt,smoothingAnchorInterval:Math.max(1,e.smoothingAnchorInterval??rt)}}function de(){return typeof performance>"u"?Date.now():performance.now()}function bt(e){const t=e.meta.team_zero.length+e.meta.team_one.length,n=e.frame_data.players.reduce((a,[,s])=>a+s.frames.length,0),r=e.boost_pads?.length??ne,o=e.boost_pad_events?.length??0,i=(e.goal_events?.length??0)+(e.player_stat_events?.length??0)+(e.demolish_infos?.length??0)+(e.replay_tick_marks?.length??0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,n),Math.max(1,e.frame_data.ball_data.frames.length),Math.max(1,r+o),Math.max(1,i)].reduce((a,s)=>a+s,0)}function _t(e){const t=e.frame_data.players.reduce((n,[,r])=>n+r.frames.length,0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,e.frame_data.ball_data.frames.length)].reduce((n,r)=>n+r,0)}function yt(e,t,n={}){const r=bt(e),o=_t(e);let i=0,a=0,s=-1,l=-1,c=de();const d=n.yieldEveryMs??Number.POSITIVE_INFINITY,u=n.progressReportMinDelta??Qe,y=Math.max(1,n.progressReportFrameInterval??et),_=()=>{if(!t)return!1;const f=Math.max(0,Math.min(1,i/r));if(f<=s)return!1;const h=a-l>=y;return f>=1||f-s>=u||h?(s=f,l=a,t(f,{progress:f,processedFrames:Math.min(a,o),totalFrames:o,processedUnits:i,totalUnits:r}),!0):!1},p=(f=!1)=>{const b=de();return!f&&b-cr===t)?.[1];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function kt(e){const t=ht(e?.stats);return{fov:v(t,"CameraFOV")??A.fov,height:v(t,"CameraHeight")??A.height,pitch:v(t,"CameraPitch")??A.pitch,distance:v(t,"CameraDistance")??A.distance,stiffness:v(t,"CameraStiffness")??A.stiffness,swivelSpeed:v(t,"CameraSwivelSpeed")??A.swivelSpeed,transitionSpeed:v(t,"CameraTransitionSpeed")??A.transitionSpeed}}function wt(e,t){const n=new Map,r=new Map,o=[...e.meta.team_zero,...e.meta.team_one];if(o.length===0)return t?.advance(),{byId:n,byName:r};for(const i of o)r.set(i.name,i),i.remote_id&&n.set(k(i.remote_id),i),t?.advance();return{byId:n,byName:r}}function xt(e){const t=new Map;for(const[n,r]of e.player_camera_events??[])t.set(k(n),r.map(o=>({frame:o.frame,ballCamActive:o.ball_cam_active,behindViewActive:o.behind_view_active,driving:o.driving})));return t}function At(e,t){const n=new Set(e.meta.team_zero.map(l=>l.name)),r=new Set(e.meta.team_one.map(l=>l.name)),o=wt(e,t),i=xt(e),a=[];let s=0;for(const[l,c]of e.frame_data.players){const d=new Array(c.frames.length);let u;for(let f=0;ft.time!==n.time?t.time-n.time:(t.frame??0)-(n.frame??0))}function St(e,t,n){const r=e.player?k(e.player):null,o=r?t.get(r)?.name??r:null,i=o?`${o} scored`:"Goal";return{id:X("goal",e.frame,r??"team"),time:E(e.time,n),frame:e.frame,kind:"goal",label:i,shortLabel:"G",playerId:r,playerName:o,isTeamZero:e.scoring_team_is_team_0}}function Ot(e,t,n){const r=k(e.player),o=t.get(r)?.name??r,i=e.kind.toLowerCase(),a=e.kind==="Shot"?"shot":e.kind==="Save"?"save":"assist",s=e.kind==="Shot"?"SH":e.kind==="Save"?"SV":"A";return{id:X(i,e.frame,r),time:E(e.time,n),frame:e.frame,kind:i,label:`${o} ${a}`,shortLabel:s,playerId:r,playerName:o,location:e.shot?.shot_touch_position??e.shot?.ball_position??null,shot:e.shot??null,isTeamZero:e.is_team_0}}function It(e,t,n){const r=k(e.attacker),o=k(e.victim),i=t.get(r),a=t.get(o);return{id:X("demo",e.frame,`${r}:${o}`),time:E(e.time,n),frame:e.frame,kind:"demo",label:`${i?.name??r} demoed ${a?.name??o}`,shortLabel:"D",playerId:r,playerName:i?.name??r,secondaryPlayerId:o,secondaryPlayerName:a?.name??o,location:e.victim_location,isTeamZero:i?.isTeamZero??null}}function Pt(e,t,n,r,o){const i=Q(t),a=[];for(const s of e.goal_events??[])a.push(St(s,i,r)),o?.advance();for(const s of e.player_stat_events??[])a.push(Ot(s,i,r)),o?.advance();for(const s of e.demolish_infos??[])a.push(It(s,i,r)),o?.advance();for(const s of n)a.push(Je(s));return a.length===0&&o?.advance(),Tt(a)}function Bt(e,t={}){const n=yt(e,t.onProgress,{progressReportMinDelta:t.progressReportMinDelta,progressReportFrameInterval:t.progressReportFrameInterval}),r=e.frame_data.metadata_frames[0]?.time??0,o=gt(e,n),i=At(e,n),a=vt(e,n),s=ft(t);me(o,a,s);for(const u of i)me(o,u.frames,s);const l=Ke(e,i,r,n),c=qe(e,r,n),d=Pt(e,i,c,r,n);return n.finish(),{frameCount:o.length,duration:o.at(-1)?.time??0,rawStartTime:r,frames:o,ballFrames:a,boostPads:l,players:i,tickMarks:c,timelineEvents:d,teamZeroNames:e.meta.team_zero.map(u=>u.name),teamOneNames:e.meta.team_one.map(u=>u.name)}}function F(e){if(e instanceof Map)return Object.fromEntries(Array.from(e.entries()).map(([t,n])=>[t,F(n)]));if(Array.isArray(e))return e.map(t=>F(t));if(e&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=F(r);return t}return e}async function Et(){const e=xe;typeof e=="function"&&await e()}function R(e){self.postMessage(e)}self.onmessage=async e=>{if(e.data.type==="load-replay")try{await Et();const t=new Uint8Array(e.data.bytes);R({type:"progress",progress:{stage:"validating",progress:0}});const n=fe(t,c=>{R({type:"progress",progress:F(c)})},e.data.reportEveryNFrames,32*1024*1024);R({type:"progress",progress:{stage:"normalizing",progress:0}});const r=JSON.parse(new TextDecoder().decode(n.rawReplayData)),o=Bt(r,{progressReportFrameInterval:e.data.reportEveryNFrames,onProgress(c){R({type:"progress",progress:{stage:"normalizing",progress:c}})}}),i=new TextEncoder().encode(JSON.stringify(o)),a=n.rawReplayData,s=a.byteOffset===0&&a.byteLength===a.buffer.byteLength?a.buffer:a.slice().buffer,l=Array.from(n.statsTimelineParts.frameChunks,c=>c.buffer);self.postMessage({type:"done",replayBuffer:i.buffer,rawReplayBuffer:s,statsTimelineParts:{configBuffer:n.statsTimelineParts.config.buffer,replayMetaBuffer:n.statsTimelineParts.replayMeta.buffer,eventsBuffer:n.statsTimelineParts.events.buffer,activitySummaryBuffer:n.statsTimelineParts.activitySummary.buffer,positioningSummaryBuffer:n.statsTimelineParts.positioningSummary.buffer,accumulationTracksBuffer:n.statsTimelineParts.accumulationTracks.buffer,frameChunkBuffers:l}},[i.buffer,s,n.statsTimelineParts.config.buffer,n.statsTimelineParts.replayMeta.buffer,n.statsTimelineParts.events.buffer,n.statsTimelineParts.activitySummary.buffer,n.statsTimelineParts.positioningSummary.buffer,n.statsTimelineParts.accumulationTracks.buffer,...l])}catch(t){R({type:"error",error:t instanceof Error?t.message:String(t)})}}})(); diff --git a/crates/rocket-sense-server/static/subtr-actor/review/assets/rl_replay_subtr_actor-Cnltgw4Z.js b/crates/rocket-sense-server/static/subtr-actor/review/assets/rl_replay_subtr_actor-Cnltgw4Z.js new file mode 100644 index 00000000..d2cb4f7d --- /dev/null +++ b/crates/rocket-sense-server/static/subtr-actor/review/assets/rl_replay_subtr_actor-Cnltgw4Z.js @@ -0,0 +1,2 @@ +function U(r,n){var e=g(r)?0:k(r,_.__wbindgen_malloc),t=a,i=g(n)?0:k(n,_.__wbindgen_malloc),c=a;const o=_.get_column_headers(e,t,i,c);if(o[2])throw s(o[1]);return s(o[0])}function B(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.get_legacy_stats_timeline_json(n,e);if(t[3])throw s(t[2]);var i=v(t[0],t[1]).slice();return _.__wbindgen_free(t[0],t[1]*1,1),i}function D(r,n,e,t){const i=w(r,_.__wbindgen_malloc),c=a;var o=g(n)?0:k(n,_.__wbindgen_malloc),l=a,f=g(e)?0:k(e,_.__wbindgen_malloc),u=a;const p=_.get_ndarray_with_info(i,c,o,l,f,u,g(t)?4294967297:Math.fround(t));if(p[2])throw s(p[1]);return s(p[0])}function N(r,n,e,t){const i=w(r,_.__wbindgen_malloc),c=a,o=_.get_replay_bundle_json_parts_with_progress(i,c,n,g(e)?4294967297:e>>>0,g(t)?4294967297:t>>>0);if(o[2])throw s(o[1]);return s(o[0])}function L(r,n,e){const t=w(r,_.__wbindgen_malloc),i=a,c=_.get_replay_bundle_json_with_progress(t,i,n,g(e)?4294967297:e>>>0);if(c[2])throw s(c[1]);return s(c[0])}function $(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.get_replay_frames_data(n,e);if(t[2])throw s(t[1]);return s(t[0])}function V(r,n,e){const t=w(r,_.__wbindgen_malloc),i=a,c=_.get_replay_frames_data_json_with_progress(t,i,n,g(e)?4294967297:e>>>0);if(c[3])throw s(c[2]);var o=v(c[0],c[1]).slice();return _.__wbindgen_free(c[0],c[1]*1,1),o}function q(r,n,e){const t=w(r,_.__wbindgen_malloc),i=a,c=_.get_replay_frames_data_with_progress(t,i,n,g(e)?4294967297:e>>>0);if(c[2])throw s(c[1]);return s(c[0])}function z(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.get_replay_info(n,e);if(t[2])throw s(t[1]);return s(t[0])}function C(r,n,e){const t=w(r,_.__wbindgen_malloc),i=a;var c=g(n)?0:k(n,_.__wbindgen_malloc),o=a,l=g(e)?0:k(e,_.__wbindgen_malloc),f=a;const u=_.get_replay_meta(t,i,c,o,l,f);if(u[2])throw s(u[1]);return s(u[0])}function J(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.get_stats_timeline(n,e);if(t[2])throw s(t[1]);return s(t[0])}function P(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.get_stats_timeline_json(n,e);if(t[3])throw s(t[2]);var i=v(t[0],t[1]).slice();return _.__wbindgen_free(t[0],t[1]*1,1),i}function H(r,n){const e=w(r,_.__wbindgen_malloc),t=a,i=_.get_stats_timeline_json_parts(e,t,g(n)?4294967297:n>>>0);if(i[2])throw s(i[1]);return s(i[0])}function K(){_.main()}function X(r){let n,e;try{const c=_.new_training_pack(r);var t=c[0],i=c[1];if(c[3])throw t=0,i=0,s(c[2]);return n=t,e=i,b(t,i)}finally{_.__wbindgen_free(n,e,1)}}function Y(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.parse_replay(n,e);if(t[2])throw s(t[1]);return s(t[0])}function G(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.parse_training_pack(n,e);if(t[2])throw s(t[1]);return s(t[0])}function Q(r){let n,e;try{const c=w(r,_.__wbindgen_malloc),o=a,l=_.parse_training_pack_lossless(c,o);var t=l[0],i=l[1];if(l[3])throw t=0,i=0,s(l[2]);return n=t,e=i,b(t,i)}finally{_.__wbindgen_free(n,e,1)}}function Z(r){const n=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),e=a,t=_.serialize_training_pack(n,e);if(t[3])throw s(t[2]);var i=v(t[0],t[1]).slice();return _.__wbindgen_free(t[0],t[1]*1,1),i}function nn(r,n){let e,t;try{const o=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),l=a,f=_.training_pack_add_round(o,l,n);var i=f[0],c=f[1];if(f[3])throw i=0,c=0,s(f[2]);return e=i,t=c,b(i,c)}finally{_.__wbindgen_free(e,t,1)}}function en(r,n,e){let t,i;try{const l=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),f=a,u=_.training_pack_add_round_archetype(l,f,n,e);var c=u[0],o=u[1];if(u[3])throw c=0,o=0,s(u[2]);return t=c,i=o,b(c,o)}finally{_.__wbindgen_free(t,i,1)}}function tn(r,n){let e,t;try{const o=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),l=a,f=d(n,_.__wbindgen_malloc,_.__wbindgen_realloc),u=a,p=_.training_pack_append_rounds(o,l,f,u);var i=p[0],c=p[1];if(p[3])throw i=0,c=0,s(p[2]);return e=i,t=c,b(i,c)}finally{_.__wbindgen_free(e,t,1)}}function rn(r,n){let e,t;try{const o=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),l=a,f=_.training_pack_duplicate_round(o,l,n);var i=f[0],c=f[1];if(f[3])throw i=0,c=0,s(f[2]);return e=i,t=c,b(i,c)}finally{_.__wbindgen_free(e,t,1)}}function _n(r){const n=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),e=a,t=_.training_pack_from_lossless(n,e);if(t[2])throw s(t[1]);return s(t[0])}function cn(r,n,e){let t,i;try{const l=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),f=a,u=_.training_pack_insert_round(l,f,n,e);var c=u[0],o=u[1];if(u[3])throw c=0,o=0,s(u[2]);return t=c,i=o,b(c,o)}finally{_.__wbindgen_free(t,i,1)}}function on(r,n,e){let t,i;try{const l=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),f=a,u=_.training_pack_move_round(l,f,n,e);var c=u[0],o=u[1];if(u[3])throw c=0,o=0,s(u[2]);return t=c,i=o,b(c,o)}finally{_.__wbindgen_free(t,i,1)}}function sn(r,n){let e,t;try{const o=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),l=a,f=_.training_pack_remove_round(o,l,n);var i=f[0],c=f[1];if(f[3])throw i=0,c=0,s(f[2]);return e=i,t=c,b(i,c)}finally{_.__wbindgen_free(e,t,1)}}function an(r,n,e){let t,i;try{const l=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),f=a,u=_.training_pack_remove_round_archetype(l,f,n,e);var c=u[0],o=u[1];if(u[3])throw c=0,o=0,s(u[2]);return t=c,i=o,b(c,o)}finally{_.__wbindgen_free(t,i,1)}}function fn(r,n){const e=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),t=a,i=_.training_pack_round_archetypes(e,t,n);if(i[2])throw s(i[1]);return s(i[0])}function ln(r,n,e,t){let i,c;try{const f=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),u=a,p=_.training_pack_set_round_archetype(f,u,n,e,t);var o=p[0],l=p[1];if(p[3])throw o=0,l=0,s(p[2]);return i=o,c=l,b(o,l)}finally{_.__wbindgen_free(i,c,1)}}function un(r,n,e){let t,i;try{const l=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),f=a,u=_.training_pack_set_round_ball(l,f,n,e);var c=u[0],o=u[1];if(u[3])throw c=0,o=0,s(u[2]);return t=c,i=o,b(c,o)}finally{_.__wbindgen_free(t,i,1)}}function dn(r,n,e){let t,i;try{const l=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),f=a,u=_.training_pack_set_round_time_limit(l,f,n,e);var c=u[0],o=u[1];if(u[3])throw c=0,o=0,s(u[2]);return t=c,i=o,b(c,o)}finally{_.__wbindgen_free(t,i,1)}}function gn(r,n){let e,t;try{const o=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),l=a,f=_.update_training_pack_metadata(o,l,n);var i=f[0],c=f[1];if(f[3])throw i=0,c=0,s(f[2]);return e=i,t=c,b(i,c)}finally{_.__wbindgen_free(e,t,1)}}function bn(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.validate_replay(n,e);if(t[2])throw s(t[1]);return s(t[0])}function O(){return{__proto__:null,"./rl_replay_subtr_actor_bg.js":{__proto__:null,__wbg_Error_8c4e43fe74559d73:function(n,e){return Error(b(n,e))},__wbg_Number_04624de7d0e8332d:function(n){return Number(n)},__wbg_String_8f0eb39a4a4c2f66:function(n,e){const t=String(e),i=d(t,_.__wbindgen_malloc,_.__wbindgen_realloc),c=a;y().setInt32(n+4,c,!0),y().setInt32(n+0,i,!0)},__wbg___wbindgen_bigint_get_as_i64_8fcf4ce7f1ca72a2:function(n,e){const t=e,i=typeof t=="bigint"?t:void 0;y().setBigInt64(n+8,g(i)?BigInt(0):i,!0),y().setInt32(n+0,!g(i),!0)},__wbg___wbindgen_boolean_get_bbbb1c18aa2f5e25:function(n){const e=n,t=typeof e=="boolean"?e:void 0;return g(t)?16777215:t?1:0},__wbg___wbindgen_debug_string_0bc8482c6e3508ae:function(n,e){const t=M(e),i=d(t,_.__wbindgen_malloc,_.__wbindgen_realloc),c=a;y().setInt32(n+4,c,!0),y().setInt32(n+0,i,!0)},__wbg___wbindgen_in_47fa6863be6f2f25:function(n,e){return n in e},__wbg___wbindgen_is_bigint_31b12575b56f32fc:function(n){return typeof n=="bigint"},__wbg___wbindgen_is_function_0095a73b8b156f76:function(n){return typeof n=="function"},__wbg___wbindgen_is_object_5ae8e5880f2c1fbd:function(n){const e=n;return typeof e=="object"&&e!==null},__wbg___wbindgen_is_string_cd444516edc5b180:function(n){return typeof n=="string"},__wbg___wbindgen_is_undefined_9e4d92534c42d778:function(n){return n===void 0},__wbg___wbindgen_jsval_eq_11888390b0186270:function(n,e){return n===e},__wbg___wbindgen_jsval_loose_eq_9dd77d8cd6671811:function(n,e){return n==e},__wbg___wbindgen_number_get_8ff4255516ccad3e:function(n,e){const t=e,i=typeof t=="number"?t:void 0;y().setFloat64(n+8,g(i)?0:i,!0),y().setInt32(n+0,!g(i),!0)},__wbg___wbindgen_string_get_72fb696202c56729:function(n,e){const t=e,i=typeof t=="string"?t:void 0;var c=g(i)?0:d(i,_.__wbindgen_malloc,_.__wbindgen_realloc),o=a;y().setInt32(n+4,o,!0),y().setInt32(n+0,c,!0)},__wbg___wbindgen_throw_be289d5034ed271b:function(n,e){throw new Error(b(n,e))},__wbg_call_389efe28435a9388:function(){return A(function(n,e){return n.call(e)},arguments)},__wbg_call_4708e0c13bdc8e95:function(){return A(function(n,e,t){return n.call(e,t)},arguments)},__wbg_done_57b39ecd9addfe81:function(n){return n.done},__wbg_entries_58c7934c745daac7:function(n){return Object.entries(n)},__wbg_error_7534b8e9a36f1ab4:function(n,e){let t,i;try{t=n,i=e,console.error(b(n,e))}finally{_.__wbindgen_free(t,i,1)}},__wbg_get_9b94d73e6221f75c:function(n,e){return n[e>>>0]},__wbg_get_b3ed3ad4be2bc8ac:function(){return A(function(n,e){return Reflect.get(n,e)},arguments)},__wbg_get_with_ref_key_1dc361bd10053bfe:function(n,e){return n[e]},__wbg_instanceof_ArrayBuffer_c367199e2fa2aa04:function(n){let e;try{e=n instanceof ArrayBuffer}catch{e=!1}return e},__wbg_instanceof_Map_53af74335dec57f4:function(n){let e;try{e=n instanceof Map}catch{e=!1}return e},__wbg_instanceof_Uint8Array_9b9075935c74707c:function(n){let e;try{e=n instanceof Uint8Array}catch{e=!1}return e},__wbg_isArray_d314bb98fcf08331:function(n){return Array.isArray(n)},__wbg_isSafeInteger_bfbc7332a9768d2a:function(n){return Number.isSafeInteger(n)},__wbg_iterator_6ff6560ca1568e55:function(){return Symbol.iterator},__wbg_length_32ed9a279acd054c:function(n){return n.length},__wbg_length_35a7bace40f36eac:function(n){return n.length},__wbg_log_f1a1b5cd3f9c7822:function(n,e){console.log(b(n,e))},__wbg_new_361308b2356cecd0:function(){return new Object},__wbg_new_3eb36ae241fe6f44:function(){return new Array},__wbg_new_8a6f238a6ece86ea:function(){return new Error},__wbg_new_dca287b076112a51:function(){return new Map},__wbg_new_dd2b680c8bf6ae29:function(n){return new Uint8Array(n)},__wbg_new_from_slice_a3d2629dc1826784:function(n,e){return new Uint8Array(v(n,e))},__wbg_next_3482f54c49e8af19:function(){return A(function(n){return n.next()},arguments)},__wbg_next_418f80d8f5303233:function(n){return n.next},__wbg_prototypesetcall_bdcdcc5842e4d77d:function(n,e,t){Uint8Array.prototype.set.call(v(n,e),t)},__wbg_push_8ffdcb2063340ba5:function(n,e){return n.push(e)},__wbg_set_1eb0999cf5d27fc8:function(n,e,t){return n.set(e,t)},__wbg_set_3f1d0b984ed272ed:function(n,e,t){n[e]=t},__wbg_set_6cb8631f80447a67:function(){return A(function(n,e,t){return Reflect.set(n,e,t)},arguments)},__wbg_set_f43e577aea94465b:function(n,e,t){n[e>>>0]=t},__wbg_stack_0ed75d68575b0f3c:function(n,e){const t=e.stack,i=d(t,_.__wbindgen_malloc,_.__wbindgen_realloc),c=a;y().setInt32(n+4,c,!0),y().setInt32(n+0,i,!0)},__wbg_value_0546255b415e96c1:function(n){return n.value},__wbindgen_cast_0000000000000001:function(n){return n},__wbindgen_cast_0000000000000002:function(n){return n},__wbindgen_cast_0000000000000003:function(n,e){return b(n,e)},__wbindgen_cast_0000000000000004:function(n){return BigInt.asUintN(64,n)},__wbindgen_init_externref_table:function(){const n=_.__wbindgen_externrefs,e=n.grow(4);n.set(0,void 0),n.set(e+0,void 0),n.set(e+1,null),n.set(e+2,!0),n.set(e+3,!1)}}}}function W(r){const n=_.__externref_table_alloc();return _.__wbindgen_externrefs.set(n,r),n}function M(r){const n=typeof r;if(n=="number"||n=="boolean"||r==null)return`${r}`;if(n=="string")return`"${r}"`;if(n=="symbol"){const i=r.description;return i==null?"Symbol":`Symbol(${i})`}if(n=="function"){const i=r.name;return typeof i=="string"&&i.length>0?`Function(${i})`:"Function"}if(Array.isArray(r)){const i=r.length;let c="[";i>0&&(c+=M(r[0]));for(let o=1;o1)t=e[1];else return toString.call(r);if(t=="Object")try{return"Object("+JSON.stringify(r)+")"}catch{return"Object"}return r instanceof Error?`${r.name}: ${r.message} +${r.stack}`:t}function v(r,n){return r=r>>>0,h().subarray(r/1,r/1+n)}let m=null;function y(){return(m===null||m.buffer.detached===!0||m.buffer.detached===void 0&&m.buffer!==_.memory.buffer)&&(m=new DataView(_.memory.buffer)),m}function b(r,n){return r=r>>>0,F(r,n)}let j=null;function h(){return(j===null||j.byteLength===0)&&(j=new Uint8Array(_.memory.buffer)),j}function A(r,n){try{return r.apply(this,n)}catch(e){const t=W(e);_.__wbindgen_exn_store(t)}}function g(r){return r==null}function w(r,n){const e=n(r.length*1,1)>>>0;return h().set(r,e/1),a=r.length,e}function k(r,n){const e=n(r.length*4,4)>>>0;for(let t=0;t>>0;return h().subarray(f,f+l.length).set(l),a=l.length,f}let t=r.length,i=n(t,1)>>>0;const c=h();let o=0;for(;o127)break;c[i+o]=l}if(o!==t){o!==0&&(r=r.slice(o)),i=e(i,t,t=o+r.length*3,1)>>>0;const l=h().subarray(i+o,i+t),f=x.encodeInto(r,l);o+=f.written,i=e(i,t,o,1)>>>0}return a=o,i}function s(r){const n=_.__wbindgen_externrefs.get(r);return _.__externref_table_dealloc(r),n}let I=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});I.decode();const T=2146435072;let S=0;function F(r,n){return S+=n,S>=T&&(I=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),I.decode(),S=n),I.decode(h().subarray(r,r+n))}const x=new TextEncoder;"encodeInto"in x||(x.encodeInto=function(r,n){const e=x.encode(r);return n.set(e),{read:r.length,written:e.length}});let a=0,_;function E(r,n){return _=r.exports,m=null,j=null,_.__wbindgen_start(),_}async function R(r,n){if(typeof Response=="function"&&r instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(r,n)}catch(i){if(r.ok&&e(r.type)&&r.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",i);else throw i}const t=await r.arrayBuffer();return await WebAssembly.instantiate(t,n)}else{const t=await WebAssembly.instantiate(r,n);return t instanceof WebAssembly.Instance?{instance:t,module:r}:t}function e(t){switch(t){case"basic":case"cors":case"default":return!0}return!1}}function wn(r){if(_!==void 0)return _;r!==void 0&&(Object.getPrototypeOf(r)===Object.prototype?{module:r}=r:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));const n=O();r instanceof WebAssembly.Module||(r=new WebAssembly.Module(r));const e=new WebAssembly.Instance(r,n);return E(e)}async function pn(r){if(_!==void 0)return _;r!==void 0&&(Object.getPrototypeOf(r)===Object.prototype?{module_or_path:r}=r:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),r===void 0&&(r=new URL(""+new URL("rl_replay_subtr_actor_bg-BjSK7HJ9.wasm",import.meta.url).href,import.meta.url));const n=O();(typeof r=="string"||typeof Request=="function"&&r instanceof Request||typeof URL=="function"&&r instanceof URL)&&(r=fetch(r));const{instance:e,module:t}=await R(await r,n);return E(e)}export{pn as default,U as get_column_headers,B as get_legacy_stats_timeline_json,D as get_ndarray_with_info,N as get_replay_bundle_json_parts_with_progress,L as get_replay_bundle_json_with_progress,$ as get_replay_frames_data,V as get_replay_frames_data_json_with_progress,q as get_replay_frames_data_with_progress,z as get_replay_info,C as get_replay_meta,J as get_stats_timeline,P as get_stats_timeline_json,H as get_stats_timeline_json_parts,wn as initSync,K as main,X as new_training_pack,Y as parse_replay,G as parse_training_pack,Q as parse_training_pack_lossless,Z as serialize_training_pack,nn as training_pack_add_round,en as training_pack_add_round_archetype,tn as training_pack_append_rounds,rn as training_pack_duplicate_round,_n as training_pack_from_lossless,cn as training_pack_insert_round,on as training_pack_move_round,sn as training_pack_remove_round,an as training_pack_remove_round_archetype,fn as training_pack_round_archetypes,ln as training_pack_set_round_archetype,un as training_pack_set_round_ball,dn as training_pack_set_round_time_limit,gn as update_training_pack_metadata,bn as validate_replay}; diff --git a/crates/rocket-sense-server/static/subtr-actor/review/assets/rl_replay_subtr_actor_bg-Xy9_Ya42.wasm b/crates/rocket-sense-server/static/subtr-actor/review/assets/rl_replay_subtr_actor_bg-BjSK7HJ9.wasm similarity index 50% rename from crates/rocket-sense-server/static/subtr-actor/review/assets/rl_replay_subtr_actor_bg-Xy9_Ya42.wasm rename to crates/rocket-sense-server/static/subtr-actor/review/assets/rl_replay_subtr_actor_bg-BjSK7HJ9.wasm index 28187c21..140cd489 100644 Binary files a/crates/rocket-sense-server/static/subtr-actor/review/assets/rl_replay_subtr_actor_bg-Xy9_Ya42.wasm and b/crates/rocket-sense-server/static/subtr-actor/review/assets/rl_replay_subtr_actor_bg-BjSK7HJ9.wasm differ diff --git a/crates/rocket-sense-server/static/subtr-actor/review/assets/wasm.worker-Bj4v8ZR2.js b/crates/rocket-sense-server/static/subtr-actor/review/assets/wasm.worker-Bj4v8ZR2.js deleted file mode 100644 index 5e7d7d50..00000000 --- a/crates/rocket-sense-server/static/subtr-actor/review/assets/wasm.worker-Bj4v8ZR2.js +++ /dev/null @@ -1 +0,0 @@ -(function(){"use strict";function ge(e,t,n){const r=G(e,c.__wbindgen_malloc),o=w,a=c.get_replay_frames_data_json_with_progress(r,o,t,Z(n)?4294967297:n>>>0);if(a[3])throw V(a[2]);var i=W(a[0],a[1]).slice();return c.__wbindgen_free(a[0],a[1]*1,1),i}function be(e){const t=G(e,c.__wbindgen_malloc),n=w,r=c.validate_replay(t,n);if(r[2])throw V(r[1]);return V(r[0])}function ye(){return{__proto__:null,"./rl_replay_subtr_actor_bg.js":{__proto__:null,__wbg_Error_8c4e43fe74559d73:function(t,n){return Error(I(t,n))},__wbg_String_8f0eb39a4a4c2f66:function(t,n){const r=String(n),o=L(r,c.__wbindgen_malloc,c.__wbindgen_realloc),a=w;O().setInt32(t+4,a,!0),O().setInt32(t+0,o,!0)},__wbg___wbindgen_is_string_cd444516edc5b180:function(t){return typeof t=="string"},__wbg___wbindgen_string_get_72fb696202c56729:function(t,n){const r=n,o=typeof r=="string"?r:void 0;var a=Z(o)?0:L(o,c.__wbindgen_malloc,c.__wbindgen_realloc),i=w;O().setInt32(t+4,i,!0),O().setInt32(t+0,a,!0)},__wbg___wbindgen_throw_be289d5034ed271b:function(t,n){throw new Error(I(t,n))},__wbg_call_4708e0c13bdc8e95:function(){return K(function(t,n,r){return t.call(n,r)},arguments)},__wbg_error_7534b8e9a36f1ab4:function(t,n){let r,o;try{r=t,o=n,console.error(I(t,n))}finally{c.__wbindgen_free(r,o,1)}},__wbg_log_d095c16a726a937c:function(t,n){console.log(I(t,n))},__wbg_new_361308b2356cecd0:function(){return new Object},__wbg_new_3eb36ae241fe6f44:function(){return new Array},__wbg_new_8a6f238a6ece86ea:function(){return new Error},__wbg_new_dca287b076112a51:function(){return new Map},__wbg_new_from_slice_a3d2629dc1826784:function(t,n){return new Uint8Array(W(t,n))},__wbg_push_8ffdcb2063340ba5:function(t,n){return t.push(n)},__wbg_set_1eb0999cf5d27fc8:function(t,n,r){return t.set(n,r)},__wbg_set_3f1d0b984ed272ed:function(t,n,r){t[n]=r},__wbg_set_6cb8631f80447a67:function(){return K(function(t,n,r){return Reflect.set(t,n,r)},arguments)},__wbg_set_f43e577aea94465b:function(t,n,r){t[n>>>0]=r},__wbg_stack_0ed75d68575b0f3c:function(t,n){const r=n.stack,o=L(r,c.__wbindgen_malloc,c.__wbindgen_realloc),a=w;O().setInt32(t+4,a,!0),O().setInt32(t+0,o,!0)},__wbindgen_cast_0000000000000001:function(t){return t},__wbindgen_cast_0000000000000002:function(t){return t},__wbindgen_cast_0000000000000003:function(t,n){return I(t,n)},__wbindgen_cast_0000000000000004:function(t){return BigInt.asUintN(64,t)},__wbindgen_init_externref_table:function(){const t=c.__wbindgen_externrefs,n=t.grow(4);t.set(0,void 0),t.set(n+0,void 0),t.set(n+1,null),t.set(n+2,!0),t.set(n+3,!1)}}}}function pe(e){const t=c.__externref_table_alloc();return c.__wbindgen_externrefs.set(t,e),t}function W(e,t){return e=e>>>0,S().subarray(e/1,e/1+t)}let x=null;function O(){return(x===null||x.buffer.detached===!0||x.buffer.detached===void 0&&x.buffer!==c.memory.buffer)&&(x=new DataView(c.memory.buffer)),x}function I(e,t){return e=e>>>0,we(e,t)}let E=null;function S(){return(E===null||E.byteLength===0)&&(E=new Uint8Array(c.memory.buffer)),E}function K(e,t){try{return e.apply(this,t)}catch(n){const r=pe(n);c.__wbindgen_exn_store(r)}}function Z(e){return e==null}function G(e,t){const n=t(e.length*1,1)>>>0;return S().set(e,n/1),w=e.length,n}function L(e,t,n){if(n===void 0){const s=D.encode(e),f=t(s.length,1)>>>0;return S().subarray(f,f+s.length).set(s),w=s.length,f}let r=e.length,o=t(r,1)>>>0;const a=S();let i=0;for(;i127)break;a[o+i]=s}if(i!==r){i!==0&&(e=e.slice(i)),o=n(o,r,r=i+e.length*3,1)>>>0;const s=S().subarray(o+i,o+r),f=D.encodeInto(e,s);i+=f.written,o=n(o,r,i,1)>>>0}return w=i,o}function V(e){const t=c.__wbindgen_externrefs.get(e);return c.__externref_table_dealloc(e),t}let R=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});R.decode();const he=2146435072;let j=0;function we(e,t){return j+=t,j>=he&&(R=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),R.decode(),j=t),R.decode(S().subarray(e,e+t))}const D=new TextEncoder;"encodeInto"in D||(D.encodeInto=function(e,t){const n=D.encode(e);return t.set(n),{read:e.length,written:n.length}});let w=0,c;function ke(e,t){return c=e.exports,x=null,E=null,c.__wbindgen_start(),c}async function xe(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(o){if(e.ok&&n(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",o);else throw o}const r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{const r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}async function Ae(e){if(c!==void 0)return c;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0&&(e=new URL(""+new URL("rl_replay_subtr_actor_bg-Xy9_Ya42.wasm",self.location.href).href,self.location.href));const t=ye();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));const{instance:n,module:r}=await xe(await e,t);return ke(n)}const q="octane",ve={breakout:{kind:"breakout",label:"Breakout",length:131.4924,width:80.521,height:30.3,slopeDegrees:-.9795,groundHeightFront:43.8976,groundHeightBack:46.1454,offset:13.88,elevation:17.05},dominus:{kind:"dominus",label:"Dominus",length:127.9268,width:83.27995,height:31.3,slopeDegrees:-.9635,groundHeightFront:47.2238,groundHeightBack:49.3749,offset:13.88,elevation:17.05},hybrid:{kind:"hybrid",label:"Hybrid",length:127.0192,width:82.18787,height:34.15907,slopeDegrees:-.5499,groundHeightFront:54.0982,groundHeightBack:55.3173,offset:13.88,elevation:17.05},merc:{kind:"merc",label:"Merc",length:120.72,width:76.71,height:41.66,slopeDegrees:.28,groundHeightFront:60.76,groundHeightBack:61.35,offset:13.88,elevation:17.05},octane:{kind:"octane",label:"Octane",length:118.0074,width:84.19941,height:36.15907,slopeDegrees:-.5518,groundHeightFront:55.1449,groundHeightBack:56.2814,offset:13.88,elevation:17.05},plank:{kind:"plank",label:"Plank",length:128.8198,width:84.67036,height:29.3944,slopeDegrees:-.3447,groundHeightFront:44.998,groundHeightBack:45.773,offset:13.88,elevation:17.05}},Oe={"16batmobile":"plank","70dodgechargerrt":"dominus","89batmobile":"dominus","99nissanskylinegtrr34":"hybrid",aftershock:"dominus",animusgp:"breakout",artemis:"plank",artemisg1:"plank",artemisgxt:"plank",astonmartinvalhalla:"breakout",backfire:"octane",backtothefuturetimemachine:"dominus",batmobile1989:"dominus",battlebus:"merc",breakout:"breakout",breakouttypes:"breakout",centio:"plank",centiov17:"plank",cyclone:"breakout",deloreantimemachine:"dominus",diestro:"dominus",dominus:"dominus",dominusgt:"dominus",endo:"hybrid",esper:"hybrid",fast4wd:"octane",fennec:"octane",gazellagt:"dominus",gizmo:"octane",grog:"octane",guardian:"dominus",guardiang1:"dominus",guardiangxt:"dominus",hotshot:"dominus",icecharger:"dominus",imperatordt5:"dominus",jager619rs:"hybrid",jurassicjeepwrangler:"octane",mantis:"plank",marauder:"octane",masamune:"dominus",maverick:"dominus",maverickg1:"dominus",maverickgxt:"dominus",mclaren570s:"dominus",merc:"merc",mr11:"dominus",nimbus:"hybrid",octane:"octane",octanezsr:"octane",paladin:"plank",proteus:"octane",ripper:"dominus",roadhog:"octane",roadhogxl:"octane",samurai:"breakout",scarab:"octane",takumi:"octane",takumirxt:"octane",thedarkknightstumbler:"octane",thedarkknightrisestumbler:"octane",triton:"octane",twinmilliii:"plank",twinzer:"octane",venom:"hybrid",vulcan:"octane",werewolf:"dominus",xdevil:"hybrid",xdevilmk2:"hybrid",zippy:"octane","1966cadillacdeville":"breakout",ace:"breakout",admiral:"dominus",azura:"breakout",behemoth:"merc",beskar:"hybrid",bmwm3e30:"dominus",bmwm2racing:"dominus",bmwm4gt3evo:"dominus",bmw1series:"octane",bmw1seriesrle:"octane",bmwm240i:"dominus",bugatticentodieci:"plank",bumblebee:"dominus",bumblebeecar:"dominus",chevroletastro:"merc",chevroletcorvettestingray:"breakout",chevroletcorvettezr1:"breakout",chryslerpacifica:"hybrid",corlay:"octane",cyberpunkquadra:"breakout",defenderd7xr:"merc",diesel:"breakout",dodgechargerdaytonascatpack:"dominus",dodgerchargerdaytonascatpack:"dominus",dominusneon:"dominus",emperor:"breakout",emperorii:"breakout",emperoriifrozen:"breakout",emperoriiscorched:"breakout",fastfuriousdodgecharger:"dominus",fastandfuriousdodgecharger:"dominus",fastandfuriousdodgechargersrthellcat:"dominus",fastfuriousmazdarx7:"breakout",fastandfuriousmazdarx7:"breakout",fastfuriousnissanskyline:"hybrid",fastandfuriousnissanskyline:"hybrid",fastfuriouspontiacfiero:"hybrid",fastandfuriouspontiacfiero:"hybrid",fenneczrf:"octane",ferrari296gtb:"dominus",ferrarif40:"breakout",fordbroncoraptorrle:"merc",fordf150rle:"octane",fordmustanggtd:"dominus",fordmustangshelbygt500:"dominus",fordmustangmacherle:"octane",fordmustangshelbygt350rrle:"dominus",formula12021:"plank",formula12022:"plank",fuse:"breakout",havoc:"breakout",hearse:"hybrid",homerscar:"dominus",hondacivictyper:"octane",hondacivictyperle:"octane",jackal:"octane",jeepwranglerrubicon:"octane",kitt:"dominus",knightindustries2000:"dominus",komodo:"breakout",lamborghinicountachlpi8004:"dominus",lamborghinihuracansto:"dominus",lamborghiniurus:"hybrid",lamborghiniurusse:"hybrid",lightningmcqueen:"dominus",lightningmcqueencar:"dominus",lockjaw:"dominus",luiginsr:"octane",maestro:"dominus",magnifique:"dominus",magnifiquegxt:"dominus",mako:"breakout",mamba:"dominus",mario:"octane",marionsr:"octane",maven:"dominus",mclaren765lt:"dominus",mclarenp1:"dominus",mclarensenna:"breakout",megastar:"breakout",mercedesamggt63s:"dominus",mercedesbenzcla:"dominus",mudcat:"octane",mudcatg1:"octane",mudcatgxt:"octane",nissan350z:"dominus",nissanfairladyz:"dominus",nissanfairladyzrle:"dominus",nissansilvia:"hybrid",nissansilviarle:"hybrid",nissanskylinegtr:"hybrid",nissanskylinegtrr32:"hybrid",nissanzperformance:"dominus",nissanzperformancecar:"dominus",outlaw:"octane",outlawgxt:"octane",pattywagon:"octane",pizzaplanetdeliverytruck:"merc",pontiacfirebird:"breakout",porsche918spyder:"breakout",porsche911gt3rs:"dominus",porsche911turbo:"dominus",porsche911turborle:"dominus",primo:"hybrid",psyclops:"octane",quadraturbor:"breakout",ram1500rho:"hybrid",recoilav:"merc",redline:"breakout",revolver:"breakout",rivianr1s:"hybrid",scorpion:"dominus",shokunin:"octane",shokuningxt:"octane",stampede:"merc",teslacybertruck:"hybrid",themysterymachine:"merc",theincredibile:"breakout",turtlevan:"merc",voidburn:"hybrid",volkswagengolfgti:"octane",volkswagengolfgtirle:"octane",xentari:"octane",zefira:"dominus",breakoutx:"breakout",nexus:"breakout",nexussc:"breakout",whiplash:"breakout","007sastonmartindbs":"dominus","007sastonmartinvalhalla":"dominus",batmobile2022:"dominus",chikara:"dominus",chikarag1:"dominus",chikaragxt:"dominus",ecto1:"dominus",ecto1ghostbusters:"dominus",fastfuriousdodgechargersrthellcat:"dominus",gazellagthotwheels:"dominus",kittknightrider:"dominus",lamborghinihuracnsto:"dominus",mr11hotwheels:"dominus",nascarchevroletcamaro:"dominus",nascarfordmustang:"dominus",nascartoyotacamry:"dominus",nascarnextgenchevroletcamaro:"dominus",nascarnextgenchevroletcamaro2022:"dominus",nascarnextgenfordmustang:"dominus",nascarnextgenfordmustang2022:"dominus",nascarnextgentoyotacamry:"dominus",nascarnextgentoyotacamry2022:"dominus",nemesis:"dominus",peregrinett:"dominus",perigrinett:"dominus",ronin:"dominus",roning1:"dominus",roningxt:"dominus",samusgunship:"dominus",samusgunshipnintendoexclusive:"dominus",tyranno:"dominus",tyrannogxt:"dominus",insidio:"hybrid",jager619:"hybrid",jger619:"hybrid",jger619rs:"hybrid",r3mx:"hybrid",r3mxgxt:"hybrid",tygris:"hybrid",nomad:"merc",nomadgxt:"merc","007sastonmartindb5":"octane",armadillo:"octane",armadilloxboxexclusive:"octane",boneshaker:"octane",dingo:"octane",fast4wdhotwheels:"octane",harbinger:"octane",harbingergxt:"octane",hogsticker:"octane",hogstickerxboxexclusive:"octane",sweettooth:"octane",sweettoothplaystationexclusive:"octane",thedarkknighttumbler:"octane",batmobile2016:"plank",sentinel:"plank"};function Se(e){const t={};for(const[n,r]of e)for(const o of n)t[o]=r;return t}const Te=Se([[[22,1416,1894,1932,3031,3311,6243,6489,7651,7696,7890,7901,8006,8360,8361,8565,8566,8669,9357,10697,10698,10817,10822,11038,11394,11505,11677,11800,11933,11949,12173,12315,12361,12484],"breakout"],[[29,403,597,600,1018,1171,1286,1675,1689,1883,2070,2268,2666,2950,2951,3155,3156,3157,3265,3426,3875,3879,3880,4014,4155,4367,4472,4473,4745,4770,4781,4861,4864,5709,5773,5823,5858,5964,5979,6122,6244,6247,6260,6836,7211,7337,7338,7341,7343,7415,7512,7532,7593,7772,8454,9053,9088,9089,9140,9388,9894,10094,10440,10441,10694,10695,11016,11095,11315,11336,11534,11941,11996,12106,12142,12262,12286,12325,12382,12563,12669],"dominus"],[[28,31,1159,1317,1624,1856,2269,3451,3582,3702,5470,5488,5879,7012,9084,9085,9427,10044,10805,11138,11141,11379,11932,12569,12652],"hybrid"],[[30,4780,7336,7477,7815,7979,10689,11098,11736,11905,11950,12318,12335],"merc"],[[21,23,25,26,27,402,404,523,607,625,723,1172,1295,1300,1475,1478,1533,1568,1623,2665,2853,2919,2949,4284,4318,4319,4320,4782,4906,5020,5039,5188,5361,5547,5713,5837,5951,6939,7947,7948,8383,8806,8807,10896,10897,10900,10901,11314,11603,12104,12105],"octane"],[[24,803,1603,1691,1919,3594,3614,3622,4268,5265,7052,8524],"plank"]]);function J(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function Q(e){if(!e)return null;switch(J(e)){case"breakout":return"breakout";case"dominus":return"dominus";case"hybrid":return"hybrid";case"merc":return"merc";case"octane":return"octane";case"batmobile":case"plank":return"plank";default:return null}}function ee(e){return e?Oe[J(e)]??null:null}function Ie(e){return Q(e)??ee(e)}function Ee(e){return ve[e]}function H(e,t){if(!(!e||typeof e!="object")){if("Str"in e&&typeof e.Str=="string"){t.push(e.Str);return}if("Name"in e&&typeof e.Name=="string"){t.push(e.Name);return}if("Byte"in e&&e.Byte&&typeof e.Byte=="object"){const n=e.Byte;typeof n.kind=="string"&&t.push(n.kind),typeof n.value=="string"&&t.push(n.value);return}if("Struct"in e&&e.Struct&&typeof e.Struct=="object"){const n=e.Struct;if(typeof n.name=="string"&&t.push(n.name),Array.isArray(n.fields))for(const r of n.fields)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),H(r[1],t));return}if("Array"in e&&Array.isArray(e.Array)){for(const n of e.Array)if(Array.isArray(n))for(const r of n)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),H(r[1],t))}}}function De(e){const t=Q(e?.car_hitbox_family);if(t)return t;const n=e?.car_body_id;if(typeof n=="number"){const i=Te[n];if(i)return i}const r=ee(e?.car_body_name);if(r)return r;const o=e?.stats;if(!o)return q;const a=[];for(const[i,s]of Object.entries(o))a.push(i),H(s,a);for(const i of a){const s=Ie(i);if(s)return s}return q}function k(e){const[t,n]=Object.entries(e)[0]??["Unknown","unknown"];return typeof n=="string"||typeof n=="number"?`${t}:${n}`:n&&typeof n=="object"?`${t}:${JSON.stringify(n)}`:`${t}:${JSON.stringify(n)}`}function B(e,t){return Math.max(0,e-t)}function te(e){return new Map(e.map(t=>[t.id,t]))}const y=70,ne=73,Be=3072,Pe=4096,Ne=1792,Re=4184,ze=940,Me=3308,Fe=2816,re=3584,Ce=2484,Le=1788,Ve=2300,je=2048,He=1036,Ue=1024,Ye=1024,$e=4240,oe=34;function z(e,t,n,r,o){e.push({index:e.length,padId:null,size:o,position:{x:t,y:n,z:r},events:[]})}function M(e,t,n,r,o){z(e,-t,n,r,o),z(e,t,n,r,o)}function U(e,t,n,r,o){z(e,t,-n,r,o),z(e,t,n,r,o)}function T(e,t,n,r,o){M(e,t,-n,r,o),M(e,t,n,r,o)}function Xe(){const e=[];return U(e,0,$e,y,"small"),T(e,Ne,Re,y,"small"),T(e,Be,Pe,ne,"big"),T(e,ze,Me,y,"small"),U(e,0,Fe,y,"small"),T(e,re,Ce,y,"small"),T(e,Le,Ve,y,"small"),T(e,je,He,y,"small"),U(e,0,Ye,y,"small"),M(e,re,0,ne,"big"),M(e,Ue,0,y,"small"),e}function Y(e){if(e==="Available")return!0;if(e&&typeof e=="object"){if("Available"in e)return!0;if("PickedUp"in e)return!1;const t=e.kind;if(t==="Available")return!0;if(t==="PickedUp")return!1}return null}function We(e){return e==="big"||e==="Big"?"big":e==="small"||e==="Small"?"small":null}function Ke(e){let t=null;for(const n of e){const r=Y(n.kind);if(r===!1){t=n.time;continue}if(r===!0&&t!==null)return n.time-t>=7?"big":"small"}return null}function Ze(e,t,n,r){const o=te(t),a=new Map;for(const l of e.boost_pad_events??[]){if(Y(l.kind)===null){r?.advance();continue}const u=a.get(l.pad_id);u?u.push(l):a.set(l.pad_id,[l]),r?.advance()}const i=e.boost_pads;if(!i||i.length===0)return r?.advance(oe),Xe();const s=[...i].sort((l,d)=>l.index-d.index),f=new Array(s.length);for(let l=0;l=72?"big":"small"),p=b.sort((_,h)=>_.time-h.time),m=new Array(p.length);for(let _=0;_=0?e.frame:null}function Ge(e,t){if(typeof e.time=="number"&&Number.isFinite(e.time))return e.time;const n=$(e);if(n===null)return null;const r=t.frame_data.metadata_frames[n]?.time;return typeof r=="number"&&Number.isFinite(r)?r:null}function qe(e,t){return`bookmark:${$(e)??"unknown"}:${e.description||"tick-mark"}:${t}`}function Je(e,t,n){return(e.replay_tick_marks??[]).flatMap((r,o)=>{n?.advance();const a=Ge(r,e);return a===null?[]:[{id:qe(r,o),description:r.description,frame:$(r),time:B(a,t)}]})}function Qe(e){const t=e.description.trim()||"Replay bookmark";return{id:e.id,time:e.time,seekTime:e.time,frame:e.frame??void 0,kind:"bookmark",label:t,shortLabel:"BM",iconName:"bookmark"}}const A={distance:270,height:100,pitch:-4,fov:110},et=.005,tt=Number.POSITIVE_INFINITY,nt=!0,rt=.15,ot=10,at=.1,it=10;function ae(e){const t=Math.hypot(e.x,e.y,e.z);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t}}function ie(e){const t=Math.hypot(e.x,e.y,e.z,e.w);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t,w:e.w/t}}function se(e,t){return{w:e.w*t.w-e.x*t.x-e.y*t.y-e.z*t.z,x:e.w*t.x+e.x*t.w+e.y*t.z-e.z*t.y,y:e.w*t.y-e.x*t.z+e.y*t.w+e.z*t.x,z:e.w*t.z+e.x*t.y-e.y*t.x+e.z*t.w}}function ce(e,t){const n=se(se(t,{x:e.x,y:e.y,z:e.z,w:0}),{x:-t.x,y:-t.y,z:-t.z,w:t.w});return{x:n.x,y:n.y,z:n.z}}function st(e){if(e==="Empty")return{position:null,linearVelocity:null,angularVelocity:null,rotation:null};const t=e.Data.rigid_body;return{position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:ie(t.rotation)}}function le(e){return e==null?null:Math.max(-1,Math.min(1,(e-128)/128))}function ue(e){return e==null?null:(e>127?e-256:e)*Math.PI/128}function de(e){return e?{x:e[0],y:e[1],z:e[2]}:null}const ct={cameraPitch:null,cameraYaw:null,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null};function lt(e){if(e==="Empty")return{isPresent:!1,position:null,linearVelocity:null,angularVelocity:null,rotation:null,forward:null,up:null,boostAmount:0,boostFraction:0,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,...ct};const t=e.Data.rigid_body,n=ie(t.rotation),r=n?ae(ce({x:1,y:0,z:0},n)):null,o=n?ae(ce({x:0,y:0,z:1},n)):null,a=e.Data.camera,i=e.Data.input;return{isPresent:!0,position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:n,forward:r,up:o,boostAmount:e.Data.boost_amount,boostFraction:Math.max(0,Math.min(1,e.Data.boost_amount/255)),boostActive:e.Data.boost_active,powerslideActive:e.Data.powerslide_active,jumpActive:e.Data.jump_active,doubleJumpActive:e.Data.double_jump_active,dodgeActive:e.Data.dodge_active,cameraPitch:ue(a?.pitch),cameraYaw:ue(a?.yaw),throttle:le(i?.throttle),steer:le(i?.steer),dodgeImpulse:de(i?.dodge_impulse),dodgeTorque:de(i?.dodge_torque)}}function ut(e){return e.position!==null}function dt(e){return{...e,isPresent:!1,linearVelocity:null,angularVelocity:null,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null}}function mt(e){let t=null,n=null;for(let r=0;r=t.length-1)return;let o=P(t[r].position);for(let a=r+1;aat){o=P(s.position);continue}if(ft(o,s.position)>it){o=P(s.position);continue}const u={x:(i.linearVelocity.x+s.linearVelocity.x)/2,y:(i.linearVelocity.y+s.linearVelocity.y)/2,z:(i.linearVelocity.z+s.linearVelocity.z)/2},b={x:o.x+u.x*d,y:o.y+u.y*d,z:o.z+u.z*d},g=(a-r)%n.smoothingAnchorInterval===0?.5:n.smoothingBlendFactor;o={x:b.x*(1-g)+s.position.x*g,y:b.y*(1-g)+s.position.y*g,z:b.z*(1-g)+s.position.z*g},s.position=P(o)}}function _t(e){return{motionSmoothing:e.motionSmoothing??nt,smoothingBlendFactor:e.smoothingBlendFactor??rt,smoothingAnchorInterval:Math.max(1,e.smoothingAnchorInterval??ot)}}function _e(){return typeof performance>"u"?Date.now():performance.now()}function gt(e){const t=e.meta.team_zero.length+e.meta.team_one.length,n=e.frame_data.players.reduce((i,[,s])=>i+s.frames.length,0),r=e.boost_pads?.length??oe,o=e.boost_pad_events?.length??0,a=(e.goal_events?.length??0)+(e.player_stat_events?.length??0)+(e.demolish_infos?.length??0)+(e.replay_tick_marks?.length??0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,n),Math.max(1,e.frame_data.ball_data.frames.length),Math.max(1,r+o),Math.max(1,a)].reduce((i,s)=>i+s,0)}function bt(e){const t=e.frame_data.players.reduce((n,[,r])=>n+r.frames.length,0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,e.frame_data.ball_data.frames.length)].reduce((n,r)=>n+r,0)}function yt(e,t,n={}){const r=gt(e),o=bt(e);let a=0,i=0,s=-1,f=-1,l=_e();const d=n.yieldEveryMs??Number.POSITIVE_INFINITY,u=n.progressReportMinDelta??et,b=Math.max(1,n.progressReportFrameInterval??tt),g=()=>{if(!t)return!1;const m=Math.max(0,Math.min(1,a/r));if(m<=s)return!1;const h=i-f>=b;return m>=1||m-s>=u||h?(s=m,f=i,t(m,{progress:m,processedFrames:Math.min(i,o),totalFrames:o,processedUnits:a,totalUnits:r}),!0):!1},p=(m=!1)=>{const _=_e();return!m&&_-lr===t)?.[1];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function kt(e){const t=wt(e?.stats);return{fov:v(t,"CameraFOV")??A.fov,height:v(t,"CameraHeight")??A.height,pitch:v(t,"CameraPitch")??A.pitch,distance:v(t,"CameraDistance")??A.distance,stiffness:v(t,"CameraStiffness")??A.stiffness,swivelSpeed:v(t,"CameraSwivelSpeed")??A.swivelSpeed,transitionSpeed:v(t,"CameraTransitionSpeed")??A.transitionSpeed}}function xt(e,t){const n=new Map,r=new Map,o=[...e.meta.team_zero,...e.meta.team_one];if(o.length===0)return t?.advance(),{byId:n,byName:r};for(const a of o)r.set(a.name,a),a.remote_id&&n.set(k(a.remote_id),a),t?.advance();return{byId:n,byName:r}}function At(e){const t=new Map;for(const[n,r]of e.player_camera_events??[])t.set(k(n),r.map(o=>({frame:o.frame,ballCamActive:o.ball_cam_active,behindViewActive:o.behind_view_active,driving:o.driving})));return t}function vt(e,t){const n=new Set(e.meta.team_zero.map(f=>f.name)),r=new Set(e.meta.team_one.map(f=>f.name)),o=xt(e,t),a=At(e),i=[];let s=0;for(const[f,l]of e.frame_data.players){const d=new Array(l.frames.length);let u;for(let m=0;mt.time!==n.time?t.time-n.time:(t.frame??0)-(n.frame??0))}function Tt(e,t,n){const r=e.player?k(e.player):null,o=r?t.get(r)?.name??r:null,a=o?`${o} scored`:"Goal";return{id:X("goal",e.frame,r??"team"),time:B(e.time,n),frame:e.frame,kind:"goal",label:a,shortLabel:"G",playerId:r,playerName:o,isTeamZero:e.scoring_team_is_team_0}}function It(e,t,n){const r=k(e.player),o=t.get(r)?.name??r,a=e.kind.toLowerCase(),i=e.kind==="Shot"?"shot":e.kind==="Save"?"save":"assist",s=e.kind==="Shot"?"SH":e.kind==="Save"?"SV":"A";return{id:X(a,e.frame,r),time:B(e.time,n),frame:e.frame,kind:a,label:`${o} ${i}`,shortLabel:s,playerId:r,playerName:o,location:e.shot?.shot_touch_position??e.shot?.ball_position??null,shot:e.shot??null,isTeamZero:e.is_team_0}}function Et(e,t,n){const r=k(e.attacker),o=k(e.victim),a=t.get(r),i=t.get(o);return{id:X("demo",e.frame,`${r}:${o}`),time:B(e.time,n),frame:e.frame,kind:"demo",label:`${a?.name??r} demoed ${i?.name??o}`,shortLabel:"D",playerId:r,playerName:a?.name??r,secondaryPlayerId:o,secondaryPlayerName:i?.name??o,location:e.victim_location,isTeamZero:a?.isTeamZero??null}}function Dt(e,t,n,r,o){const a=te(t),i=[];for(const s of e.goal_events??[])i.push(Tt(s,a,r)),o?.advance();for(const s of e.player_stat_events??[])i.push(It(s,a,r)),o?.advance();for(const s of e.demolish_infos??[])i.push(Et(s,a,r)),o?.advance();for(const s of n)i.push(Qe(s));return i.length===0&&o?.advance(),St(i)}function Bt(e,t={}){const n=yt(e,t.onProgress,{progressReportMinDelta:t.progressReportMinDelta,progressReportFrameInterval:t.progressReportFrameInterval}),r=e.frame_data.metadata_frames[0]?.time??0,o=pt(e,n),a=vt(e,n),i=Ot(e,n),s=_t(t);fe(o,i,s);for(const u of a)fe(o,u.frames,s);const f=Ze(e,a,r,n),l=Je(e,r,n),d=Dt(e,a,l,r,n);return n.finish(),{frameCount:o.length,duration:o.at(-1)?.time??0,rawStartTime:r,frames:o,ballFrames:i,boostPads:f,players:a,tickMarks:l,timelineEvents:d,teamZeroNames:e.meta.team_zero.map(u=>u.name),teamOneNames:e.meta.team_one.map(u=>u.name)}}function F(e){if(e instanceof Map)return Object.fromEntries(Array.from(e.entries()).map(([t,n])=>[t,F(n)]));if(Array.isArray(e))return e.map(t=>F(t));if(e&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=F(r);return t}return e}async function Pt(){const e=Ae;typeof e=="function"&&await e()}function N(e){self.postMessage(e)}self.onmessage=async e=>{if(e.data.type==="load-replay")try{await Pt();const t=new Uint8Array(e.data.bytes);N({type:"progress",progress:{stage:"validating",progress:0}});const n=F(be(t));if(!n.valid)throw new Error(n.error??"Replay validation failed");const r=ge(t,s=>{N({type:"progress",progress:s})},e.data.reportEveryNFrames);N({type:"progress",progress:{stage:"normalizing",progress:0}});const o=JSON.parse(new TextDecoder().decode(r)),a=Bt(o,{motionSmoothing:e.data.motionSmoothing,smoothingBlendFactor:e.data.smoothingBlendFactor,smoothingAnchorInterval:e.data.smoothingAnchorInterval,progressReportFrameInterval:e.data.reportEveryNFrames,onProgress(s){N({type:"progress",progress:{stage:"normalizing",progress:s}})}}),i=new TextEncoder().encode(JSON.stringify(a));self.postMessage({type:"done",rawBuffer:r.buffer,replayBuffer:i.buffer},[r.buffer,i.buffer])}catch(t){N({type:"error",error:t instanceof Error?t.message:String(t)})}}})(); diff --git a/crates/rocket-sense-server/static/subtr-actor/review/assets/wasm.worker-zm5sJFWS.js b/crates/rocket-sense-server/static/subtr-actor/review/assets/wasm.worker-zm5sJFWS.js new file mode 100644 index 00000000..1f671e38 --- /dev/null +++ b/crates/rocket-sense-server/static/subtr-actor/review/assets/wasm.worker-zm5sJFWS.js @@ -0,0 +1,2 @@ +(function(){"use strict";function ge(e,t,n){const r=q(e,c.__wbindgen_malloc),o=p,a=c.get_replay_frames_data_json_with_progress(r,o,t,v(n)?4294967297:n>>>0);if(a[3])throw Y(a[2]);var i=H(a[0],a[1]).slice();return c.__wbindgen_free(a[0],a[1]*1,1),i}function ye(e){const t=q(e,c.__wbindgen_malloc),n=p,r=c.validate_replay(t,n);if(r[2])throw Y(r[1]);return Y(r[0])}function pe(){return{__proto__:null,"./rl_replay_subtr_actor_bg.js":{__proto__:null,__wbg_Error_8c4e43fe74559d73:function(t,n){return Error(E(t,n))},__wbg_Number_04624de7d0e8332d:function(t){return Number(t)},__wbg_String_8f0eb39a4a4c2f66:function(t,n){const r=String(n),o=M(r,c.__wbindgen_malloc,c.__wbindgen_realloc),a=p;y().setInt32(t+4,a,!0),y().setInt32(t+0,o,!0)},__wbg___wbindgen_bigint_get_as_i64_8fcf4ce7f1ca72a2:function(t,n){const r=n,o=typeof r=="bigint"?r:void 0;y().setBigInt64(t+8,v(o)?BigInt(0):o,!0),y().setInt32(t+0,!v(o),!0)},__wbg___wbindgen_boolean_get_bbbb1c18aa2f5e25:function(t){const n=t,r=typeof n=="boolean"?n:void 0;return v(r)?16777215:r?1:0},__wbg___wbindgen_debug_string_0bc8482c6e3508ae:function(t,n){const r=U(n),o=M(r,c.__wbindgen_malloc,c.__wbindgen_realloc),a=p;y().setInt32(t+4,a,!0),y().setInt32(t+0,o,!0)},__wbg___wbindgen_in_47fa6863be6f2f25:function(t,n){return t in n},__wbg___wbindgen_is_bigint_31b12575b56f32fc:function(t){return typeof t=="bigint"},__wbg___wbindgen_is_function_0095a73b8b156f76:function(t){return typeof t=="function"},__wbg___wbindgen_is_object_5ae8e5880f2c1fbd:function(t){const n=t;return typeof n=="object"&&n!==null},__wbg___wbindgen_is_string_cd444516edc5b180:function(t){return typeof t=="string"},__wbg___wbindgen_is_undefined_9e4d92534c42d778:function(t){return t===void 0},__wbg___wbindgen_jsval_eq_11888390b0186270:function(t,n){return t===n},__wbg___wbindgen_jsval_loose_eq_9dd77d8cd6671811:function(t,n){return t==n},__wbg___wbindgen_number_get_8ff4255516ccad3e:function(t,n){const r=n,o=typeof r=="number"?r:void 0;y().setFloat64(t+8,v(o)?0:o,!0),y().setInt32(t+0,!v(o),!0)},__wbg___wbindgen_string_get_72fb696202c56729:function(t,n){const r=n,o=typeof r=="string"?r:void 0;var a=v(o)?0:M(o,c.__wbindgen_malloc,c.__wbindgen_realloc),i=p;y().setInt32(t+4,i,!0),y().setInt32(t+0,a,!0)},__wbg___wbindgen_throw_be289d5034ed271b:function(t,n){throw new Error(E(t,n))},__wbg_call_389efe28435a9388:function(){return D(function(t,n){return t.call(n)},arguments)},__wbg_call_4708e0c13bdc8e95:function(){return D(function(t,n,r){return t.call(n,r)},arguments)},__wbg_done_57b39ecd9addfe81:function(t){return t.done},__wbg_entries_58c7934c745daac7:function(t){return Object.entries(t)},__wbg_error_7534b8e9a36f1ab4:function(t,n){let r,o;try{r=t,o=n,console.error(E(t,n))}finally{c.__wbindgen_free(r,o,1)}},__wbg_get_9b94d73e6221f75c:function(t,n){return t[n>>>0]},__wbg_get_b3ed3ad4be2bc8ac:function(){return D(function(t,n){return Reflect.get(t,n)},arguments)},__wbg_get_with_ref_key_1dc361bd10053bfe:function(t,n){return t[n]},__wbg_instanceof_ArrayBuffer_c367199e2fa2aa04:function(t){let n;try{n=t instanceof ArrayBuffer}catch{n=!1}return n},__wbg_instanceof_Map_53af74335dec57f4:function(t){let n;try{n=t instanceof Map}catch{n=!1}return n},__wbg_instanceof_Uint8Array_9b9075935c74707c:function(t){let n;try{n=t instanceof Uint8Array}catch{n=!1}return n},__wbg_isArray_d314bb98fcf08331:function(t){return Array.isArray(t)},__wbg_isSafeInteger_bfbc7332a9768d2a:function(t){return Number.isSafeInteger(t)},__wbg_iterator_6ff6560ca1568e55:function(){return Symbol.iterator},__wbg_length_32ed9a279acd054c:function(t){return t.length},__wbg_length_35a7bace40f36eac:function(t){return t.length},__wbg_log_f1a1b5cd3f9c7822:function(t,n){console.log(E(t,n))},__wbg_new_361308b2356cecd0:function(){return new Object},__wbg_new_3eb36ae241fe6f44:function(){return new Array},__wbg_new_8a6f238a6ece86ea:function(){return new Error},__wbg_new_dca287b076112a51:function(){return new Map},__wbg_new_dd2b680c8bf6ae29:function(t){return new Uint8Array(t)},__wbg_new_from_slice_a3d2629dc1826784:function(t,n){return new Uint8Array(H(t,n))},__wbg_next_3482f54c49e8af19:function(){return D(function(t){return t.next()},arguments)},__wbg_next_418f80d8f5303233:function(t){return t.next},__wbg_prototypesetcall_bdcdcc5842e4d77d:function(t,n,r){Uint8Array.prototype.set.call(H(t,n),r)},__wbg_push_8ffdcb2063340ba5:function(t,n){return t.push(n)},__wbg_set_1eb0999cf5d27fc8:function(t,n,r){return t.set(n,r)},__wbg_set_3f1d0b984ed272ed:function(t,n,r){t[n]=r},__wbg_set_6cb8631f80447a67:function(){return D(function(t,n,r){return Reflect.set(t,n,r)},arguments)},__wbg_set_f43e577aea94465b:function(t,n,r){t[n>>>0]=r},__wbg_stack_0ed75d68575b0f3c:function(t,n){const r=n.stack,o=M(r,c.__wbindgen_malloc,c.__wbindgen_realloc),a=p;y().setInt32(t+4,a,!0),y().setInt32(t+0,o,!0)},__wbg_value_0546255b415e96c1:function(t){return t.value},__wbindgen_cast_0000000000000001:function(t){return t},__wbindgen_cast_0000000000000002:function(t){return t},__wbindgen_cast_0000000000000003:function(t,n){return E(t,n)},__wbindgen_cast_0000000000000004:function(t){return BigInt.asUintN(64,t)},__wbindgen_init_externref_table:function(){const t=c.__wbindgen_externrefs,n=t.grow(4);t.set(0,void 0),t.set(n+0,void 0),t.set(n+1,null),t.set(n+2,!0),t.set(n+3,!1)}}}}function he(e){const t=c.__externref_table_alloc();return c.__wbindgen_externrefs.set(t,e),t}function U(e){const t=typeof e;if(t=="number"||t=="boolean"||e==null)return`${e}`;if(t=="string")return`"${e}"`;if(t=="symbol"){const o=e.description;return o==null?"Symbol":`Symbol(${o})`}if(t=="function"){const o=e.name;return typeof o=="string"&&o.length>0?`Function(${o})`:"Function"}if(Array.isArray(e)){const o=e.length;let a="[";o>0&&(a+=U(e[0]));for(let i=1;i1)r=n[1];else return toString.call(e);if(r=="Object")try{return"Object("+JSON.stringify(e)+")"}catch{return"Object"}return e instanceof Error?`${e.name}: ${e.message} +${e.stack}`:r}function H(e,t){return e=e>>>0,I().subarray(e/1,e/1+t)}let A=null;function y(){return(A===null||A.buffer.detached===!0||A.buffer.detached===void 0&&A.buffer!==c.memory.buffer)&&(A=new DataView(c.memory.buffer)),A}function E(e,t){return e=e>>>0,ke(e,t)}let B=null;function I(){return(B===null||B.byteLength===0)&&(B=new Uint8Array(c.memory.buffer)),B}function D(e,t){try{return e.apply(this,t)}catch(n){const r=he(n);c.__wbindgen_exn_store(r)}}function v(e){return e==null}function q(e,t){const n=t(e.length*1,1)>>>0;return I().set(e,n/1),p=e.length,n}function M(e,t,n){if(n===void 0){const s=N.encode(e),m=t(s.length,1)>>>0;return I().subarray(m,m+s.length).set(s),p=s.length,m}let r=e.length,o=t(r,1)>>>0;const a=I();let i=0;for(;i127)break;a[o+i]=s}if(i!==r){i!==0&&(e=e.slice(i)),o=n(o,r,r=i+e.length*3,1)>>>0;const s=I().subarray(o+i,o+r),m=N.encodeInto(e,s);i+=m.written,o=n(o,r,i,1)>>>0}return p=i,o}function Y(e){const t=c.__wbindgen_externrefs.get(e);return c.__externref_table_dealloc(e),t}let z=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});z.decode();const we=2146435072;let $=0;function ke(e,t){return $+=t,$>=we&&(z=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),z.decode(),$=t),z.decode(I().subarray(e,e+t))}const N=new TextEncoder;"encodeInto"in N||(N.encodeInto=function(e,t){const n=N.encode(e);return t.set(n),{read:e.length,written:n.length}});let p=0,c;function xe(e,t){return c=e.exports,A=null,B=null,c.__wbindgen_start(),c}async function Ae(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(o){if(e.ok&&n(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",o);else throw o}const r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{const r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}async function ve(e){if(c!==void 0)return c;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0&&(e=new URL(""+new URL("rl_replay_subtr_actor_bg-BjSK7HJ9.wasm",self.location.href).href,self.location.href));const t=pe();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));const{instance:n,module:r}=await Ae(await e,t);return xe(n)}const J="octane",Se={breakout:{kind:"breakout",label:"Breakout",length:131.4924,width:80.521,height:30.3,slopeDegrees:-.9795,groundHeightFront:43.8976,groundHeightBack:46.1454,offset:13.88,elevation:17.05},dominus:{kind:"dominus",label:"Dominus",length:127.9268,width:83.27995,height:31.3,slopeDegrees:-.9635,groundHeightFront:47.2238,groundHeightBack:49.3749,offset:13.88,elevation:17.05},hybrid:{kind:"hybrid",label:"Hybrid",length:127.0192,width:82.18787,height:34.15907,slopeDegrees:-.5499,groundHeightFront:54.0982,groundHeightBack:55.3173,offset:13.88,elevation:17.05},merc:{kind:"merc",label:"Merc",length:120.72,width:76.71,height:41.66,slopeDegrees:.28,groundHeightFront:60.76,groundHeightBack:61.35,offset:13.88,elevation:17.05},octane:{kind:"octane",label:"Octane",length:118.0074,width:84.19941,height:36.15907,slopeDegrees:-.5518,groundHeightFront:55.1449,groundHeightBack:56.2814,offset:13.88,elevation:17.05},plank:{kind:"plank",label:"Plank",length:128.8198,width:84.67036,height:29.3944,slopeDegrees:-.3447,groundHeightFront:44.998,groundHeightBack:45.773,offset:13.88,elevation:17.05}},Oe={"16batmobile":"plank","70dodgechargerrt":"dominus","89batmobile":"dominus","99nissanskylinegtrr34":"hybrid",aftershock:"dominus",animusgp:"breakout",artemis:"plank",artemisg1:"plank",artemisgxt:"plank",astonmartinvalhalla:"breakout",backfire:"octane",backtothefuturetimemachine:"dominus",batmobile1989:"dominus",battlebus:"merc",breakout:"breakout",breakouttypes:"breakout",centio:"plank",centiov17:"plank",cyclone:"breakout",deloreantimemachine:"dominus",diestro:"dominus",dominus:"dominus",dominusgt:"dominus",endo:"hybrid",esper:"hybrid",fast4wd:"octane",fennec:"octane",gazellagt:"dominus",gizmo:"octane",grog:"octane",guardian:"dominus",guardiang1:"dominus",guardiangxt:"dominus",hotshot:"dominus",icecharger:"dominus",imperatordt5:"dominus",jager619rs:"hybrid",jurassicjeepwrangler:"octane",mantis:"plank",marauder:"octane",masamune:"dominus",maverick:"dominus",maverickg1:"dominus",maverickgxt:"dominus",mclaren570s:"dominus",merc:"merc",mr11:"dominus",nimbus:"hybrid",octane:"octane",octanezsr:"octane",paladin:"plank",proteus:"octane",ripper:"dominus",roadhog:"octane",roadhogxl:"octane",samurai:"breakout",scarab:"octane",takumi:"octane",takumirxt:"octane",thedarkknightstumbler:"octane",thedarkknightrisestumbler:"octane",triton:"octane",twinmilliii:"plank",twinzer:"octane",venom:"hybrid",vulcan:"octane",werewolf:"dominus",xdevil:"hybrid",xdevilmk2:"hybrid",zippy:"octane","1966cadillacdeville":"breakout",ace:"breakout",admiral:"dominus",azura:"breakout",behemoth:"merc",beskar:"hybrid",bmwm3e30:"dominus",bmwm2racing:"dominus",bmwm4gt3evo:"dominus",bmw1series:"octane",bmw1seriesrle:"octane",bmwm240i:"dominus",bugatticentodieci:"plank",bumblebee:"dominus",bumblebeecar:"dominus",chevroletastro:"merc",chevroletcorvettestingray:"breakout",chevroletcorvettezr1:"breakout",chryslerpacifica:"hybrid",corlay:"octane",cyberpunkquadra:"breakout",defenderd7xr:"merc",diesel:"breakout",dodgechargerdaytonascatpack:"dominus",dodgerchargerdaytonascatpack:"dominus",dominusneon:"dominus",emperor:"breakout",emperorii:"breakout",emperoriifrozen:"breakout",emperoriiscorched:"breakout",fastfuriousdodgecharger:"dominus",fastandfuriousdodgecharger:"dominus",fastandfuriousdodgechargersrthellcat:"dominus",fastfuriousmazdarx7:"breakout",fastandfuriousmazdarx7:"breakout",fastfuriousnissanskyline:"hybrid",fastandfuriousnissanskyline:"hybrid",fastfuriouspontiacfiero:"hybrid",fastandfuriouspontiacfiero:"hybrid",fenneczrf:"octane",ferrari296gtb:"dominus",ferrarif40:"breakout",fordbroncoraptorrle:"merc",fordf150rle:"octane",fordmustanggtd:"dominus",fordmustangshelbygt500:"dominus",fordmustangmacherle:"octane",fordmustangshelbygt350rrle:"dominus",formula12021:"plank",formula12022:"plank",fuse:"breakout",havoc:"breakout",hearse:"hybrid",homerscar:"dominus",hondacivictyper:"octane",hondacivictyperle:"octane",jackal:"octane",jeepwranglerrubicon:"octane",kitt:"dominus",knightindustries2000:"dominus",komodo:"breakout",lamborghinicountachlpi8004:"dominus",lamborghinihuracansto:"dominus",lamborghiniurus:"hybrid",lamborghiniurusse:"hybrid",lightningmcqueen:"dominus",lightningmcqueencar:"dominus",lockjaw:"dominus",luiginsr:"octane",maestro:"dominus",magnifique:"dominus",magnifiquegxt:"dominus",mako:"breakout",mamba:"dominus",mario:"octane",marionsr:"octane",maven:"dominus",mclaren765lt:"dominus",mclarenp1:"dominus",mclarensenna:"breakout",megastar:"breakout",mercedesamggt63s:"dominus",mercedesbenzcla:"dominus",mudcat:"octane",mudcatg1:"octane",mudcatgxt:"octane",nissan350z:"dominus",nissanfairladyz:"dominus",nissanfairladyzrle:"dominus",nissansilvia:"hybrid",nissansilviarle:"hybrid",nissanskylinegtr:"hybrid",nissanskylinegtrr32:"hybrid",nissanzperformance:"dominus",nissanzperformancecar:"dominus",outlaw:"octane",outlawgxt:"octane",pattywagon:"octane",pizzaplanetdeliverytruck:"merc",pontiacfirebird:"breakout",porsche918spyder:"breakout",porsche911gt3rs:"dominus",porsche911turbo:"dominus",porsche911turborle:"dominus",primo:"hybrid",psyclops:"octane",quadraturbor:"breakout",ram1500rho:"hybrid",recoilav:"merc",redline:"breakout",revolver:"breakout",rivianr1s:"hybrid",scorpion:"dominus",shokunin:"octane",shokuningxt:"octane",stampede:"merc",teslacybertruck:"hybrid",themysterymachine:"merc",theincredibile:"breakout",turtlevan:"merc",voidburn:"hybrid",volkswagengolfgti:"octane",volkswagengolfgtirle:"octane",xentari:"octane",zefira:"dominus",breakoutx:"breakout",nexus:"breakout",nexussc:"breakout",whiplash:"breakout","007sastonmartindbs":"dominus","007sastonmartinvalhalla":"dominus",batmobile2022:"dominus",chikara:"dominus",chikarag1:"dominus",chikaragxt:"dominus",ecto1:"dominus",ecto1ghostbusters:"dominus",fastfuriousdodgechargersrthellcat:"dominus",gazellagthotwheels:"dominus",kittknightrider:"dominus",lamborghinihuracnsto:"dominus",mr11hotwheels:"dominus",nascarchevroletcamaro:"dominus",nascarfordmustang:"dominus",nascartoyotacamry:"dominus",nascarnextgenchevroletcamaro:"dominus",nascarnextgenchevroletcamaro2022:"dominus",nascarnextgenfordmustang:"dominus",nascarnextgenfordmustang2022:"dominus",nascarnextgentoyotacamry:"dominus",nascarnextgentoyotacamry2022:"dominus",nemesis:"dominus",peregrinett:"dominus",perigrinett:"dominus",ronin:"dominus",roning1:"dominus",roningxt:"dominus",samusgunship:"dominus",samusgunshipnintendoexclusive:"dominus",tyranno:"dominus",tyrannogxt:"dominus",insidio:"hybrid",jager619:"hybrid",jger619:"hybrid",jger619rs:"hybrid",r3mx:"hybrid",r3mxgxt:"hybrid",tygris:"hybrid",nomad:"merc",nomadgxt:"merc","007sastonmartindb5":"octane",armadillo:"octane",armadilloxboxexclusive:"octane",boneshaker:"octane",dingo:"octane",fast4wdhotwheels:"octane",harbinger:"octane",harbingergxt:"octane",hogsticker:"octane",hogstickerxboxexclusive:"octane",sweettooth:"octane",sweettoothplaystationexclusive:"octane",thedarkknighttumbler:"octane",batmobile2016:"plank",sentinel:"plank"};function Ie(e){const t={};for(const[n,r]of e)for(const o of n)t[o]=r;return t}const Te=Ie([[[22,1416,1894,1932,3031,3311,6243,6489,7651,7696,7890,7901,8006,8360,8361,8565,8566,8669,9357,10697,10698,10817,10822,11038,11394,11505,11677,11800,11933,11949,12173,12315,12361,12484],"breakout"],[[29,403,597,600,1018,1171,1286,1675,1689,1883,2070,2268,2666,2950,2951,3155,3156,3157,3265,3426,3875,3879,3880,4014,4155,4367,4472,4473,4745,4770,4781,4861,4864,5709,5773,5823,5858,5964,5979,6122,6244,6247,6260,6836,7211,7337,7338,7341,7343,7415,7512,7532,7593,7772,8454,9053,9088,9089,9140,9388,9894,10094,10440,10441,10694,10695,11016,11095,11315,11336,11534,11941,11996,12106,12142,12262,12286,12325,12382,12563,12669],"dominus"],[[28,31,1159,1317,1624,1856,2269,3451,3582,3702,5470,5488,5879,7012,9084,9085,9427,10044,10805,11138,11141,11379,11932,12569,12652],"hybrid"],[[30,4780,7336,7477,7815,7979,10689,11098,11736,11905,11950,12318,12335],"merc"],[[21,23,25,26,27,402,404,523,607,625,723,1172,1295,1300,1475,1478,1533,1568,1623,2665,2853,2919,2949,4284,4318,4319,4320,4782,4906,5020,5039,5188,5361,5547,5713,5837,5951,6939,7947,7948,8383,8806,8807,10896,10897,10900,10901,11314,11603,12104,12105],"octane"],[[24,803,1603,1691,1919,3594,3614,3622,4268,5265,7052,8524],"plank"]]);function Q(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function ee(e){if(!e)return null;switch(Q(e)){case"breakout":return"breakout";case"dominus":return"dominus";case"hybrid":return"hybrid";case"merc":return"merc";case"octane":return"octane";case"batmobile":case"plank":return"plank";default:return null}}function te(e){return e?Oe[Q(e)]??null:null}function Ee(e){return ee(e)??te(e)}function Be(e){return Se[e]}function X(e,t){if(!(!e||typeof e!="object")){if("Str"in e&&typeof e.Str=="string"){t.push(e.Str);return}if("Name"in e&&typeof e.Name=="string"){t.push(e.Name);return}if("Byte"in e&&e.Byte&&typeof e.Byte=="object"){const n=e.Byte;typeof n.kind=="string"&&t.push(n.kind),typeof n.value=="string"&&t.push(n.value);return}if("Struct"in e&&e.Struct&&typeof e.Struct=="object"){const n=e.Struct;if(typeof n.name=="string"&&t.push(n.name),Array.isArray(n.fields))for(const r of n.fields)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),X(r[1],t));return}if("Array"in e&&Array.isArray(e.Array)){for(const n of e.Array)if(Array.isArray(n))for(const r of n)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),X(r[1],t))}}}function De(e){const t=ee(e?.car_hitbox_family);if(t)return t;const n=e?.car_body_id;if(typeof n=="number"){const i=Te[n];if(i)return i}const r=te(e?.car_body_name);if(r)return r;const o=e?.stats;if(!o)return J;const a=[];for(const[i,s]of Object.entries(o))a.push(i),X(s,a);for(const i of a){const s=Ee(i);if(s)return s}return J}function x(e){const[t,n]=Object.entries(e)[0]??["Unknown","unknown"];return typeof n=="string"||typeof n=="number"?`${t}:${n}`:n&&typeof n=="object"?`${t}:${JSON.stringify(n)}`:`${t}:${JSON.stringify(n)}`}function P(e,t){return Math.max(0,e-t)}function ne(e){return new Map(e.map(t=>[t.id,t]))}const h=70,re=73,Ne=3072,Pe=4096,Fe=1792,Re=4184,Me=940,ze=3308,Ce=2816,oe=3584,je=2484,Le=1788,Ve=2300,Ue=2048,He=1036,Ye=1024,$e=1024,Xe=4240,ae=34;function C(e,t,n,r,o){e.push({index:e.length,padId:null,size:o,position:{x:t,y:n,z:r},events:[]})}function j(e,t,n,r,o){C(e,-t,n,r,o),C(e,t,n,r,o)}function W(e,t,n,r,o){C(e,t,-n,r,o),C(e,t,n,r,o)}function T(e,t,n,r,o){j(e,t,-n,r,o),j(e,t,n,r,o)}function We(){const e=[];return W(e,0,Xe,h,"small"),T(e,Fe,Re,h,"small"),T(e,Ne,Pe,re,"big"),T(e,Me,ze,h,"small"),W(e,0,Ce,h,"small"),T(e,oe,je,h,"small"),T(e,Le,Ve,h,"small"),T(e,Ue,He,h,"small"),W(e,0,$e,h,"small"),j(e,oe,0,re,"big"),j(e,Ye,0,h,"small"),e}function K(e){if(e==="Available")return!0;if(e&&typeof e=="object"){if("Available"in e)return!0;if("PickedUp"in e)return!1;const t=e.kind;if(t==="Available")return!0;if(t==="PickedUp")return!1}return null}function Ke(e){return e==="big"||e==="Big"?"big":e==="small"||e==="Small"?"small":null}function Ze(e){let t=null;for(const n of e){const r=K(n.kind);if(r===!1){t=n.time;continue}if(r===!0&&t!==null)return n.time-t>=7?"big":"small"}return null}function Ge(e,t,n,r){const o=ne(t),a=new Map;for(const u of e.boost_pad_events??[]){if(K(u.kind)===null){r?.advance();continue}const l=a.get(u.pad_id);l?l.push(u):a.set(u.pad_id,[u]),r?.advance()}const i=e.boost_pads;if(!i||i.length===0)return r?.advance(ae),We();const s=[...i].sort((u,d)=>u.index-d.index),m=new Array(s.length);for(let u=0;u=72?"big":"small"),w=g.sort((_,k)=>_.time-k.time),f=new Array(w.length);for(let _=0;_=0?e.frame:null}function qe(e,t){if(typeof e.time=="number"&&Number.isFinite(e.time))return e.time;const n=Z(e);if(n===null)return null;const r=t.frame_data.metadata_frames[n]?.time;return typeof r=="number"&&Number.isFinite(r)?r:null}function Je(e,t){return`bookmark:${Z(e)??"unknown"}:${e.description||"tick-mark"}:${t}`}function Qe(e,t,n){return(e.replay_tick_marks??[]).flatMap((r,o)=>{n?.advance();const a=qe(r,e);return a===null?[]:[{id:Je(r,o),description:r.description,frame:Z(r),time:P(a,t)}]})}function et(e){const t=e.description.trim()||"Replay bookmark";return{id:e.id,time:e.time,seekTime:e.time,frame:e.frame??void 0,kind:"bookmark",label:t,shortLabel:"BM",iconName:"bookmark"}}const S={distance:270,height:100,pitch:-4,fov:110},tt=.005,nt=Number.POSITIVE_INFINITY,rt=!0,ot=.15,at=10,it=.1,st=10;function ie(e){const t=Math.hypot(e.x,e.y,e.z);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t}}function se(e){const t=Math.hypot(e.x,e.y,e.z,e.w);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t,w:e.w/t}}function ce(e,t){return{w:e.w*t.w-e.x*t.x-e.y*t.y-e.z*t.z,x:e.w*t.x+e.x*t.w+e.y*t.z-e.z*t.y,y:e.w*t.y-e.x*t.z+e.y*t.w+e.z*t.x,z:e.w*t.z+e.x*t.y-e.y*t.x+e.z*t.w}}function ue(e,t){const n=ce(ce(t,{x:e.x,y:e.y,z:e.z,w:0}),{x:-t.x,y:-t.y,z:-t.z,w:t.w});return{x:n.x,y:n.y,z:n.z}}function ct(e){if(e==="Empty")return{position:null,linearVelocity:null,angularVelocity:null,rotation:null};const t=e.Data.rigid_body;return{position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:se(t.rotation)}}function le(e){return e==null?null:Math.max(-1,Math.min(1,(e-128)/128))}function de(e){return e==null?null:(e>127?e-256:e)*Math.PI/128}function fe(e){return e?{x:e[0],y:e[1],z:e[2]}:null}const ut={cameraPitch:null,cameraYaw:null,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null};function lt(e){if(e==="Empty")return{isPresent:!1,position:null,linearVelocity:null,angularVelocity:null,rotation:null,forward:null,up:null,boostAmount:0,boostFraction:0,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,...ut};const t=e.Data.rigid_body,n=se(t.rotation),r=n?ie(ue({x:1,y:0,z:0},n)):null,o=n?ie(ue({x:0,y:0,z:1},n)):null,a=e.Data.camera,i=e.Data.input;return{isPresent:!0,position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:n,forward:r,up:o,boostAmount:e.Data.boost_amount,boostFraction:Math.max(0,Math.min(1,e.Data.boost_amount/255)),boostActive:e.Data.boost_active,powerslideActive:e.Data.powerslide_active,jumpActive:e.Data.jump_active,doubleJumpActive:e.Data.double_jump_active,dodgeActive:e.Data.dodge_active,cameraPitch:de(a?.pitch),cameraYaw:de(a?.yaw),throttle:le(i?.throttle),steer:le(i?.steer),dodgeImpulse:fe(i?.dodge_impulse),dodgeTorque:fe(i?.dodge_torque)}}function dt(e){return e.position!==null}function ft(e){return{...e,isPresent:!1,linearVelocity:null,angularVelocity:null,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null}}function mt(e){let t=null,n=null;for(let r=0;r=t.length-1)return;let o=F(t[r].position);for(let a=r+1;ait){o=F(s.position);continue}if(_t(o,s.position)>st){o=F(s.position);continue}const l={x:(i.linearVelocity.x+s.linearVelocity.x)/2,y:(i.linearVelocity.y+s.linearVelocity.y)/2,z:(i.linearVelocity.z+s.linearVelocity.z)/2},g={x:o.x+l.x*d,y:o.y+l.y*d,z:o.z+l.z*d},b=(a-r)%n.smoothingAnchorInterval===0?.5:n.smoothingBlendFactor;o={x:g.x*(1-b)+s.position.x*b,y:g.y*(1-b)+s.position.y*b,z:g.z*(1-b)+s.position.z*b},s.position=F(o)}}function bt(e){return{motionSmoothing:e.motionSmoothing??rt,smoothingBlendFactor:e.smoothingBlendFactor??ot,smoothingAnchorInterval:Math.max(1,e.smoothingAnchorInterval??at)}}function be(){return typeof performance>"u"?Date.now():performance.now()}function gt(e){const t=e.meta.team_zero.length+e.meta.team_one.length,n=e.frame_data.players.reduce((i,[,s])=>i+s.frames.length,0),r=e.boost_pads?.length??ae,o=e.boost_pad_events?.length??0,a=(e.goal_events?.length??0)+(e.player_stat_events?.length??0)+(e.demolish_infos?.length??0)+(e.replay_tick_marks?.length??0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,n),Math.max(1,e.frame_data.ball_data.frames.length),Math.max(1,r+o),Math.max(1,a)].reduce((i,s)=>i+s,0)}function yt(e){const t=e.frame_data.players.reduce((n,[,r])=>n+r.frames.length,0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,e.frame_data.ball_data.frames.length)].reduce((n,r)=>n+r,0)}function pt(e,t,n={}){const r=gt(e),o=yt(e);let a=0,i=0,s=-1,m=-1,u=be();const d=n.yieldEveryMs??Number.POSITIVE_INFINITY,l=n.progressReportMinDelta??tt,g=Math.max(1,n.progressReportFrameInterval??nt),b=()=>{if(!t)return!1;const f=Math.max(0,Math.min(1,a/r));if(f<=s)return!1;const k=i-m>=g;return f>=1||f-s>=l||k?(s=f,m=i,t(f,{progress:f,processedFrames:Math.min(i,o),totalFrames:o,processedUnits:a,totalUnits:r}),!0):!1},w=(f=!1)=>{const _=be();return!f&&_-ur===t)?.[1];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function xt(e){const t=kt(e?.stats);return{fov:O(t,"CameraFOV")??S.fov,height:O(t,"CameraHeight")??S.height,pitch:O(t,"CameraPitch")??S.pitch,distance:O(t,"CameraDistance")??S.distance,stiffness:O(t,"CameraStiffness")??S.stiffness,swivelSpeed:O(t,"CameraSwivelSpeed")??S.swivelSpeed,transitionSpeed:O(t,"CameraTransitionSpeed")??S.transitionSpeed}}function At(e,t){const n=new Map,r=new Map,o=[...e.meta.team_zero,...e.meta.team_one];if(o.length===0)return t?.advance(),{byId:n,byName:r};for(const a of o)r.set(a.name,a),a.remote_id&&n.set(x(a.remote_id),a),t?.advance();return{byId:n,byName:r}}function vt(e){const t=new Map;for(const[n,r]of e.player_camera_events??[])t.set(x(n),r.map(o=>({frame:o.frame,ballCamActive:o.ball_cam_active,behindViewActive:o.behind_view_active,driving:o.driving})));return t}function St(e,t){const n=new Set(e.meta.team_zero.map(m=>m.name)),r=new Set(e.meta.team_one.map(m=>m.name)),o=At(e,t),a=vt(e),i=[];let s=0;for(const[m,u]of e.frame_data.players){const d=new Array(u.frames.length);let l;for(let f=0;ft.time!==n.time?t.time-n.time:(t.frame??0)-(n.frame??0))}function Tt(e,t,n){const r=e.player?x(e.player):null,o=r?t.get(r)?.name??r:null,a=o?`${o} scored`:"Goal";return{id:G("goal",e.frame,r??"team"),time:P(e.time,n),frame:e.frame,kind:"goal",label:a,shortLabel:"G",playerId:r,playerName:o,isTeamZero:e.scoring_team_is_team_0}}function Et(e,t,n){const r=x(e.player),o=t.get(r)?.name??r,a=e.kind.toLowerCase(),i=e.kind==="Shot"?"shot":e.kind==="Save"?"save":"assist",s=e.kind==="Shot"?"SH":e.kind==="Save"?"SV":"A";return{id:G(a,e.frame,r),time:P(e.time,n),frame:e.frame,kind:a,label:`${o} ${i}`,shortLabel:s,playerId:r,playerName:o,location:e.shot?.shot_touch_position??e.shot?.ball_position??null,shot:e.shot??null,isTeamZero:e.is_team_0}}function Bt(e,t,n){const r=x(e.attacker),o=x(e.victim),a=t.get(r),i=t.get(o);return{id:G("demo",e.frame,`${r}:${o}`),time:P(e.time,n),frame:e.frame,kind:"demo",label:`${a?.name??r} demoed ${i?.name??o}`,shortLabel:"D",playerId:r,playerName:a?.name??r,secondaryPlayerId:o,secondaryPlayerName:i?.name??o,location:e.victim_location,isTeamZero:a?.isTeamZero??null}}function Dt(e,t,n,r,o){const a=ne(t),i=[];for(const s of e.goal_events??[])i.push(Tt(s,a,r)),o?.advance();for(const s of e.player_stat_events??[])i.push(Et(s,a,r)),o?.advance();for(const s of e.demolish_infos??[])i.push(Bt(s,a,r)),o?.advance();for(const s of n)i.push(et(s));return i.length===0&&o?.advance(),It(i)}function Nt(e,t={}){const n=pt(e,t.onProgress,{progressReportMinDelta:t.progressReportMinDelta,progressReportFrameInterval:t.progressReportFrameInterval}),r=e.frame_data.metadata_frames[0]?.time??0,o=ht(e,n),a=St(e,n),i=Ot(e,n),s=bt(t);_e(o,i,s);for(const l of a)_e(o,l.frames,s);const m=Ge(e,a,r,n),u=Qe(e,r,n),d=Dt(e,a,u,r,n);return n.finish(),{frameCount:o.length,duration:o.at(-1)?.time??0,rawStartTime:r,frames:o,ballFrames:i,boostPads:m,players:a,tickMarks:u,timelineEvents:d,teamZeroNames:e.meta.team_zero.map(l=>l.name),teamOneNames:e.meta.team_one.map(l=>l.name)}}function L(e){if(e instanceof Map)return Object.fromEntries(Array.from(e.entries()).map(([t,n])=>[t,L(n)]));if(Array.isArray(e))return e.map(t=>L(t));if(e&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=L(r);return t}return e}async function Pt(){const e=ve;typeof e=="function"&&await e()}function R(e){self.postMessage(e)}self.onmessage=async e=>{if(e.data.type==="load-replay")try{await Pt();const t=new Uint8Array(e.data.bytes);R({type:"progress",progress:{stage:"validating",progress:0}});const n=L(ye(t));if(!n.valid)throw new Error(n.error??"Replay validation failed");const r=ge(t,s=>{R({type:"progress",progress:s})},e.data.reportEveryNFrames);R({type:"progress",progress:{stage:"normalizing",progress:0}});const o=JSON.parse(new TextDecoder().decode(r)),a=Nt(o,{motionSmoothing:e.data.motionSmoothing,smoothingBlendFactor:e.data.smoothingBlendFactor,smoothingAnchorInterval:e.data.smoothingAnchorInterval,progressReportFrameInterval:e.data.reportEveryNFrames,onProgress(s){R({type:"progress",progress:{stage:"normalizing",progress:s}})}}),i=new TextEncoder().encode(JSON.stringify(a));self.postMessage({type:"done",rawBuffer:r.buffer,replayBuffer:i.buffer},[r.buffer,i.buffer])}catch(t){R({type:"error",error:t instanceof Error?t.message:String(t)})}}})(); diff --git a/crates/rocket-sense-server/static/subtr-actor/review/index.html b/crates/rocket-sense-server/static/subtr-actor/review/index.html index 3f930690..132f6a76 100644 --- a/crates/rocket-sense-server/static/subtr-actor/review/index.html +++ b/crates/rocket-sense-server/static/subtr-actor/review/index.html @@ -5,7 +5,8 @@ stat evaluation player - + +
diff --git a/crates/rocket-sense-server/static/subtr-actor/stats/assets/index-rme7XOnQ.css b/crates/rocket-sense-server/static/subtr-actor/stats/assets/index-BBR8rq7J.css similarity index 76% rename from crates/rocket-sense-server/static/subtr-actor/stats/assets/index-rme7XOnQ.css rename to crates/rocket-sense-server/static/subtr-actor/stats/assets/index-BBR8rq7J.css index 8c843e63..c3d19f60 100644 --- a/crates/rocket-sense-server/static/subtr-actor/stats/assets/index-rme7XOnQ.css +++ b/crates/rocket-sense-server/static/subtr-actor/stats/assets/index-BBR8rq7J.css @@ -1 +1 @@ -:root{color-scheme:dark;font-family:IBM Plex Sans,Avenir Next,sans-serif;font-size:13px;--surface: rgba(8, 20, 30, .82);--surface-strong: rgba(7, 16, 24, .94);--surface-soft: rgba(12, 28, 40, .72);--border: rgba(167, 199, 222, .14);--text: #edf5fa;--muted: #9eb4c6;--blue: #4b94ff;--blue-soft: rgba(75, 148, 255, .18);--orange: #f39a37;--orange-soft: rgba(243, 154, 55, .18);--ui-gap-xs: .22rem;--ui-gap-sm: .34rem;--ui-gap-md: .5rem;--ui-panel-padding: .52rem;--ui-control-font-size: .72rem;--ui-control-line-height: 1.15;--ui-control-padding-block: .22rem;--ui-control-padding-inline: .38rem;--ui-control-height: 1.55rem;--ui-radius-sm: .36rem;--ui-radius-md: .5rem;--ui-radius-lg: .72rem;--ui-radius-pill: 999px;--ui-border-subtle: rgba(255, 255, 255, .1);--ui-border-hover: rgba(255, 255, 255, .18);--ui-overlay-bg: rgba(4, 12, 18, .82);--ui-overlay-bg-strong: rgba(4, 12, 18, .9);background:radial-gradient(circle at top left,rgba(73,112,158,.28),transparent 32%),radial-gradient(circle at top right,rgba(243,154,55,.12),transparent 24%),linear-gradient(180deg,#071018,#0b1721);color:var(--text)}html,body,#app{width:100%;height:100%;overflow:hidden}.shell{min-height:100dvh;height:100dvh;padding:0;display:block}.workspace{height:100%;display:block;min-height:0}.panel h2,.stats-panel h2{margin:0}.panel-copy{color:#bdd0de}.viewport-panel,.panel,.stats-panel{position:relative;border:1px solid var(--border);border-radius:1.4rem;background:var(--surface);box-shadow:0 22px 56px #0000003d;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}.viewport-panel{width:100%;height:100%;min-height:100dvh;overflow:hidden;border:0;border-radius:0;background:#061019;box-shadow:none}.viewport{position:absolute;inset:0}.top-chrome{position:absolute;top:.8rem;left:.8rem;z-index:20}.launcher-toggle{width:2.65rem;min-width:0;aspect-ratio:1;display:grid;place-items:center;padding:0;border-color:transparent;border-radius:var(--ui-radius-md);background:#050e16ad;box-shadow:0 12px 30px #0000004d;-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px)}.launcher-toggle:hover,.launcher-toggle[aria-expanded=true]{border-color:#ffffff29;background:#081824d1}.launcher-toggle-bars,.launcher-toggle-bars:before,.launcher-toggle-bars:after{display:block;width:1.18rem;height:.12rem;border-radius:var(--ui-radius-pill);background:#edf5fa}.launcher-toggle-bars{position:relative}.launcher-toggle-bars:before,.launcher-toggle-bars:after{content:"";position:absolute;left:0}.launcher-toggle-bars:before{top:-.38rem}.launcher-toggle-bars:after{top:.38rem}.launcher-menu{position:absolute;top:calc(100% + .55rem);left:0;width:min(22rem,calc(100vw - 1.6rem));max-height:calc(100dvh - 7.5rem);overflow:auto;display:grid;gap:var(--ui-gap-md);padding:var(--ui-panel-padding);border:1px solid rgba(255,255,255,.12);border-radius:var(--ui-radius-lg);background:var(--ui-overlay-bg-strong);box-shadow:0 18px 54px #0000005c;-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px)}.launcher-menu[hidden]{display:none}.launcher-section{display:grid;gap:var(--ui-gap-xs)}.launcher-section h2{margin:0;color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase}.launcher-section button{width:100%;text-align:left}.hidden-file-input,.visually-hidden{position:fixed;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap}.team-blue{--team-accent: var(--blue);--team-soft: var(--blue-soft)}.team-orange{--team-accent: var(--orange);--team-soft: var(--orange-soft)}.floating-window-layer,.stats-window-layer{position:absolute;inset:0;z-index:12;pointer-events:none}.floating-window,.stats-window,.scoreboard-window{position:absolute;left:clamp(.8rem,var(--window-x, 1rem),calc(100vw - 18rem));top:clamp(.8rem,var(--window-y, 1rem),calc(100dvh - 12rem));width:min(26rem,calc(100vw - 1.6rem));overflow:visible;display:grid;gap:var(--ui-gap-md);padding:var(--ui-panel-padding);border:1px solid rgba(255,255,255,.12);border-radius:var(--ui-radius-lg);background:var(--ui-overlay-bg);box-shadow:0 16px 44px #00000052;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);pointer-events:auto;-webkit-user-select:none;user-select:none}.floating-window[hidden],.stats-window[hidden],.scoreboard-window[hidden]{display:none}.scoreboard-window{left:50%;top:.7rem;width:auto;min-width:4.4rem;transform:translate(-50%);gap:var(--ui-gap-sm);padding:.34rem .62rem;border-radius:999px}.scoreboard-window-body{display:grid;gap:.42rem}.scoreboard-scoreline{display:grid;grid-template-columns:minmax(1.2rem,auto) auto minmax(1.2rem,auto);align-items:center;justify-content:center;gap:.3rem;min-width:0;font-variant-numeric:tabular-nums}.scoreboard-goal-value{color:var(--team-accent);font-size:1rem;font-weight:850;line-height:1;text-align:center}.scoreboard-divider{color:var(--muted);font-size:1rem;font-weight:800;line-height:1}.scoreboard-empty{margin:0;color:var(--muted);font-size:.74rem;text-align:center}@media(max-width:900px){.scoreboard-window{top:3.25rem}}@media(max-width:640px){.scoreboard-window{min-width:4rem;padding:.32rem .56rem}.scoreboard-scoreline{gap:.24rem}.scoreboard-goal-value{font-size:.92rem}}.floating-window-camera{width:min(26rem,calc(100vw - 1.6rem))}.floating-window-recording{--window-x: calc(100vw - 27rem) ;width:min(26rem,calc(100vw - 1.6rem))}.floating-window-playback{--window-x: calc(100vw - 23rem) ;width:min(21rem,calc(100vw - 1.6rem))}.floating-window-mechanics{width:auto;min-width:min(18rem,calc(100vw - 1.6rem));max-width:min(42rem,calc(100vw - 1.6rem))}.mechanics-timeline-window-body{display:grid;gap:var(--ui-gap-sm);max-height:min(72dvh,42rem);overflow:auto}.floating-window-event-playlist{width:min(27rem,calc(100vw - 1.6rem))}.floating-window-mechanics-review{width:min(30rem,calc(100vw - 1.6rem))}.floating-window-replay-loading{width:min(32rem,calc(100vw - 1.6rem))}.floating-window-boost-pickups{width:min(34rem,calc(100vw - 1.6rem))}.floating-window-touch-controls,.floating-window-touch-legend{width:min(24rem,calc(100vw - 1.6rem))}.floating-window-shot-visualization{width:min(38rem,calc(100vw - 1.6rem))}.floating-window-header,.stats-window-header{display:flex;align-items:start;justify-content:space-between;gap:var(--ui-gap-md);cursor:grab}.stats-window-header-actions-only{justify-content:end}.floating-window:active .floating-window-header,.stats-window:active .stats-window-header{cursor:grabbing}.floating-window-header h2,.stats-window-header h2{margin:0;color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase}.floating-window-hide,.stats-window-action{flex-shrink:0;padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border-radius:var(--ui-radius-md);font-size:var(--ui-control-font-size)}.mechanics-review-window-body{display:grid;gap:var(--ui-gap-md);max-height:min(74dvh,42rem);min-height:0;overflow:hidden auto;scrollbar-width:thin}.event-playlist-window-body{display:grid;gap:var(--ui-gap-sm);min-height:0}.touch-color-legend-body{display:grid;gap:var(--ui-gap-md);max-height:min(70dvh,38rem);overflow:auto;scrollbar-width:thin}.touch-color-legend-explainer{display:grid;gap:var(--ui-gap-xs);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);color:#c3d3df;font-size:.78rem;background:#ffffff0a}.touch-color-legend-group{display:grid;gap:var(--ui-gap-xs)}.touch-color-legend-heading{width:100%;min-height:1.45rem;margin:0;padding:.12rem .32rem;border-radius:var(--ui-radius-sm);color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.1em;text-align:left;text-transform:uppercase}.touch-color-legend-heading[data-active=true]{border-color:#8ec5ff6b;background:#21476b94;color:#f3f8fc}.touch-color-legend-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-xs)}.touch-color-legend-item{min-width:0;display:flex;align-items:center;gap:var(--ui-gap-xs);color:#e8f0f7;font-size:.76rem}.touch-color-legend-swatch{flex:0 0 auto;width:.78rem;height:.78rem;border:1px solid rgba(255,255,255,.35);border-radius:50%;box-shadow:0 0 0 1px #00000038}.event-playlist-toolbar{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm)}.event-playlist-filter{position:relative;min-width:0}.event-playlist-filter summary{display:inline-flex;align-items:center;min-height:var(--ui-control-height);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);background:#ffffff0a;color:var(--text);font-size:var(--ui-control-font-size);cursor:pointer;list-style:none}.event-playlist-filter summary::-webkit-details-marker{display:none}.event-playlist-filter-panel{position:absolute;z-index:5;top:calc(100% + .4rem);left:0;width:min(22rem,calc(100vw - 3rem));max-height:min(28rem,calc(100dvh - 10rem));overflow:auto;display:grid;gap:var(--ui-gap-md);padding:.85rem;border:1px solid rgba(255,255,255,.14);border-radius:var(--ui-radius-md);background:#090e16fa;box-shadow:0 16px 34px #00000057}.event-playlist-filter-actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem}.event-playlist-filter-group{display:grid;gap:.45rem}.event-playlist-filter-group h3{margin:0;color:#87afd4;font-size:.64rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase}.event-playlist-filter-option{min-width:0}.event-playlist-follow{flex-shrink:0}.event-playlist-list{max-height:min(31rem,calc(100dvh - 11rem));overflow:auto;display:grid;gap:.45rem;padding-right:.15rem;scrollbar-width:thin}.event-playlist-item{--event-color: #d1d9e0;appearance:none;width:100%;display:grid;grid-template-columns:3.4rem minmax(0,1fr);gap:.7rem;align-items:start;padding:.6rem .7rem;border:1px solid rgba(255,255,255,.09);border-left:.28rem solid var(--event-color);border-radius:var(--ui-radius-md);background:#ffffff09;color:var(--text);font:inherit;text-align:left;cursor:pointer}.event-playlist-item:hover,.event-playlist-item[data-active=true]{border-color:color-mix(in srgb,var(--event-color) 48%,rgba(255,255,255,.12));background:color-mix(in srgb,var(--event-color) 15%,rgba(255,255,255,.045))}.event-playlist-time{color:var(--muted);font-size:.72rem;font-variant-numeric:tabular-nums;line-height:1.35}.event-playlist-main{min-width:0;display:grid;gap:.15rem}.shot-visualization{display:grid;gap:var(--ui-gap-md);min-height:0}.shot-visualization-summary{color:var(--text);font-size:.78rem;font-weight:700;font-variant-numeric:tabular-nums}.shot-chart-canvas{width:100%;aspect-ratio:16 / 10;display:block;border:1px solid rgba(255,255,255,.1);border-radius:var(--ui-radius-md);background:#0f2b24}.shot-visualization-layout{display:grid;grid-template-columns:minmax(10rem,.78fr) minmax(15rem,1.22fr);gap:var(--ui-gap-md);min-height:0}.shot-list{display:grid;align-content:start;gap:.45rem;max-height:18rem;overflow:auto;padding-right:.15rem;scrollbar-width:thin}.shot-list-item{appearance:none;width:100%;display:grid;gap:.15rem;min-height:3.1rem;padding:.52rem .62rem;border:1px solid rgba(255,255,255,.09);border-left:.24rem solid #62d2a2;border-radius:var(--ui-radius-md);background:#ffffff09;color:var(--text);font:inherit;text-align:left;cursor:pointer}.shot-list-item[data-selected=true]{border-color:#f8fafcb8;background:#87afd429}.shot-list-item[data-active=true]{border-left-color:#e11d48}.shot-list-title{min-width:0;overflow:hidden;color:var(--text);font-size:.78rem;font-weight:800;text-overflow:ellipsis;white-space:nowrap}.shot-list-meta{color:var(--muted);font-size:.68rem;font-variant-numeric:tabular-nums;white-space:nowrap}.shot-demo-panel{display:grid;gap:var(--ui-gap-sm);min-width:0}.shot-demo-scene{width:100%;height:12rem;overflow:hidden;border:1px solid rgba(255,255,255,.1);border-radius:var(--ui-radius-md);background:#07111c}.shot-demo-scene canvas{width:100%;height:100%;display:block}.shot-details{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem;margin:0}.shot-details div{min-width:0;padding:.48rem .56rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:#ffffff09}.shot-details dt{color:var(--muted);font-size:.62rem;font-weight:700;text-transform:uppercase}.shot-details dd{min-width:0;margin:.14rem 0 0;overflow:hidden;color:var(--text);font-size:.76rem;font-variant-numeric:tabular-nums;text-overflow:ellipsis;white-space:nowrap}.shot-visualization-empty{margin:0;color:var(--muted);font-size:.78rem}.event-playlist-main strong{min-width:0;overflow-wrap:anywhere;font-size:.82rem;line-height:1.3}.event-playlist-main span{min-width:0;overflow-wrap:anywhere;color:var(--muted);font-size:.68rem;line-height:1.35}.mechanics-review-load-row{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:var(--ui-gap-sm);align-items:center}.mechanics-review-file{display:inline-grid;align-items:center;min-height:var(--ui-control-height);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);background:#ffffff0e;color:var(--text);cursor:pointer}.mechanics-review-file input{position:fixed;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap}.mechanics-review-url{min-width:0}.mechanics-review-status{min-height:1.2rem;color:var(--muted);font-size:.78rem}.mechanics-review-current{display:grid;gap:var(--ui-gap-sm);padding:.55rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:#ffffff09}.mechanics-review-index{color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase}.mechanics-review-current h3{margin:0;font-size:.96rem;line-height:1.2}.mechanics-review-fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-sm);margin:0}.mechanics-review-fields div{min-width:0}.mechanics-review-fields dt{color:var(--muted);font-size:.68rem;text-transform:uppercase}.mechanics-review-fields dd{margin:.1rem 0 0;overflow-wrap:anywhere}.mechanics-review-wide{grid-column:1 / -1}.mechanics-review-actions,.mechanics-review-decision-actions,.mechanics-review-list-header{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm)}.mechanics-review-actions button,.mechanics-review-decision-actions button{flex:1 1 0}#mechanics-review-confirm{border-color:#4caf7885}#mechanics-review-reject{border-color:#dc5f5f94}.mechanics-review-list-header{color:var(--muted);font-size:.72rem;font-weight:700;text-transform:uppercase}.mechanics-review-replays{display:grid;gap:var(--ui-gap-xs)}.replay-loading-window-body{display:grid;gap:var(--ui-gap-sm);max-height:min(72dvh,40rem);min-height:0}.replay-loading-summary{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm);color:var(--muted);font-size:.72rem;font-weight:700;text-transform:uppercase}.replay-loading-list{max-height:min(38rem,calc(100dvh - 9rem));overflow:auto;display:grid;gap:var(--ui-gap-xs);padding-right:.15rem;scrollbar-width:thin}.mechanics-review-replay-load{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.35rem var(--ui-gap-sm);min-width:0;padding:.5rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:#ffffff09}.mechanics-review-replay-load.loaded{border-color:#4caf786b}.mechanics-review-replay-load.error{border-color:#dc5f5f94}.mechanics-review-replay-load-main{display:grid;min-width:0;gap:.16rem}.mechanics-review-replay-load-title,.mechanics-review-replay-load-meta{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-replay-load-title{color:var(--text);font-size:.78rem;font-weight:700}.mechanics-review-replay-load-meta{color:var(--muted);font-size:.68rem}.mechanics-review-replay-load-status{max-width:11rem;overflow:hidden;color:var(--muted);font-size:.68rem;text-align:right;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-replay-load.loaded .mechanics-review-replay-load-status{color:#83d4a4}.mechanics-review-replay-load.error .mechanics-review-replay-load-status{color:#ff9b9b}.mechanics-review-replay-load-progress{grid-column:1 / -1;height:.25rem;overflow:hidden;border-radius:999px;background:#ffffff14}.mechanics-review-replay-load-progress span{display:block;width:0;height:100%;border-radius:inherit;background:#77a9ff;transition:width .14s ease}.mechanics-review-replay-load.loaded .mechanics-review-replay-load-progress span{background:#4caf78}.mechanics-review-replay-load.error .mechanics-review-replay-load-progress span{background:#dc5f5f}.mechanics-review-list{max-height:min(22rem,calc(100dvh - 27rem));display:grid;gap:var(--ui-gap-xs);overflow:auto;padding-right:.15rem;scrollbar-width:thin}.mechanics-review-item{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--ui-gap-sm);align-items:center;width:100%;min-height:2rem;text-align:left}.mechanics-review-item span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-item strong{color:var(--muted);font-size:.72rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-item[data-active=true]{border-color:#4b94ff6b;background:#4b94ff29}.viewport canvas{display:block;width:100%;height:100%}.replay-load-modal{position:fixed;inset:0;z-index:100;display:grid;place-items:center;padding:1.25rem;background:radial-gradient(circle at top,rgba(89,157,219,.18),transparent 30%),#040b12c2;-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px)}.replay-load-modal[hidden]{display:none}.replay-load-modal__dialog{width:min(32rem,100%);display:grid;gap:.75rem;padding:1.4rem 1.45rem;border-radius:1.35rem;border:1px solid rgba(255,255,255,.12);background:linear-gradient(180deg,#0b1724f5,#070f18f0);box-shadow:0 24px 70px #0006}.replay-load-modal__eyebrow{margin:0;font-size:.72rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase;color:#87afd4}.replay-load-modal__title,.replay-load-modal__status,.replay-load-modal__meta{margin:0}.replay-load-modal__title{font-size:clamp(1.45rem,4vw,2.1rem);line-height:1.1;color:#f3f8fc}.replay-load-modal__status{color:#e6f0f7;font-size:1rem}.replay-load-modal__phase-list{display:grid;gap:.52rem}.replay-load-modal__phase-row{display:grid;gap:.28rem}.replay-load-modal__phase-label{margin:0;font-size:.82rem;letter-spacing:.04em;color:#9eb4c6}.replay-load-modal__phase-row[data-state=active] .replay-load-modal__phase-label{color:#edf5fa}.replay-load-modal__phase-row[data-state=complete] .replay-load-modal__phase-label{color:#c5d9e7}.replay-load-modal__phase-bar{overflow:hidden;height:.58rem;border-radius:999px;background:#ffffff1a}.replay-load-modal__phase-fill{width:0%;height:100%;border-radius:inherit;background:linear-gradient(90deg,#4b94ff,#8ec5ff 55%,#f39a37);transition:width .14s ease}.replay-load-modal__phase-row[data-state=complete] .replay-load-modal__phase-fill{opacity:.95}.replay-load-modal__phase-fill[data-indeterminate=true]{width:100%!important;background:linear-gradient(90deg,#4b94ff40,#4b94ffcc 28%,#8ec5fff2,#f39a37cc 72%,#f39a3740);background-size:180% 100%;animation:replay-load-phase-indeterminate 1.1s linear infinite}@keyframes replay-load-phase-indeterminate{0%{background-position:0% 0%}to{background-position:180% 0%}}.replay-load-modal__meta{color:#9eb4c6;font-size:.92rem}.empty-state{position:absolute;left:50%;top:50%;z-index:10;display:grid;gap:.55rem;min-width:min(20rem,calc(100vw - 2rem));transform:translate(-50%,-50%);padding:.85rem .95rem;border-radius:1rem;border:1px solid rgba(169,201,226,.14);background:#040c12d1;color:#bfd2de;text-align:center;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}.empty-state[hidden]{display:none}.empty-state p{margin:0}.stats-panel{padding:1.15rem 1.15rem 1rem}.panel-heading{display:flex;justify-content:space-between;align-items:start;gap:1rem;margin-bottom:1rem}.player-stats-stack{display:grid;gap:.9rem}.player-team-stack{display:grid;gap:.85rem}.player-team-group{display:grid;gap:.7rem;padding:.75rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:linear-gradient(180deg,var(--team-soft),rgba(255,255,255,.025)),#ffffff08}.player-team-header{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-md);padding-bottom:.42rem;border-bottom:1px solid color-mix(in srgb,var(--team-accent) 36%,transparent)}.player-team-header h3{margin:0;color:#edf5fa;font-size:.76rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.player-team-header span{flex-shrink:0;color:color-mix(in srgb,var(--team-accent) 62%,#edf5fa);font-size:.68rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase}.player-stats-grid{display:flex;gap:.7rem;flex-wrap:wrap}.player-card{flex:1 1 13rem;min-width:12rem;padding:.85rem;border-radius:1rem;border:1px solid rgba(255,255,255,.08);background:#ffffff09}.player-card.team-blue{background:var(--blue-soft);border-color:#4b94ff42}.player-card.team-orange{background:var(--orange-soft);border-color:#f39a3747}.player-card.shared{background:linear-gradient(180deg,#ffffff0f,#ffffff06),#ffffff09;border-color:#ffffff1f}.player-card-header{display:flex;justify-content:space-between;align-items:center;gap:.4rem;margin-bottom:.45rem}.player-name{font-size:.85rem;font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stat-row{display:flex;justify-content:space-between;gap:.5rem;padding:.15rem 0;font-size:.8rem}.label,.detail-grid dt,.stat-row .label{color:#89a4ba}.stat-row .value,.detail-grid dd{font-variant-numeric:tabular-nums}.role-indicator,.depth-indicator{flex-shrink:0;padding:.18rem .45rem;border-radius:999px;font-size:.64rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase}.role-back,.depth-last{background:#ea55552e;color:#ff9b9b}.role-forward,.depth-upfield{background:#4ac6762e;color:#9ce5a8}.role-other,.depth-level{background:#8495a82e;color:#c0cbd6}.role-mid,.depth-mid{background:#f39a372e;color:#ffc680}.stat-module-section{display:grid;gap:.45rem}.stat-module-label{font-size:.72rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase;color:#6f889d}.sidebar{min-height:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));align-content:start;align-items:start;gap:1rem}.stat-window-empty{margin:0;color:#9eb4c6;font-size:.88rem}.stats-window-toolbar,.stats-window-scope-row,.stats-window-actions{display:flex;align-items:center;gap:var(--ui-gap-sm);flex-wrap:wrap}.stats-window-toolbar{justify-content:end}.stats-window-scope-select{min-width:min(100%,13rem)}.stats-window-add-button{width:var(--ui-control-height);min-width:var(--ui-control-height);padding:0;font-size:1rem;font-weight:800;line-height:1}.stats-window-add-button[aria-expanded=true]{border-color:var(--ui-border-hover);background:#ffffff1a}.stats-window-scope-select.team-blue,.stats-window-scope-select.team-orange,.stats-window-stat-target.team-blue,.stats-window-stat-target.team-orange{border-color:var(--team-accent);box-shadow:inset .22rem 0 0 var(--team-accent)}.stats-window-picker{display:grid;gap:var(--ui-gap-sm);padding:var(--ui-panel-padding);border-radius:var(--ui-radius-md);border:1px solid rgba(255,255,255,.08);background:#ffffff0a}.stats-window-picker[hidden]{display:none}.stats-window-picker-list{display:grid;gap:var(--ui-gap-xs);overflow:visible}.stats-window-picker-item{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.45rem;align-items:center;width:100%;padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);text-align:left}.stats-window-picker-item span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stats-window-picker-item strong{color:#87afd4;font-size:.62rem;letter-spacing:.08em;text-transform:uppercase}.stats-window-stat-list,.stats-window-entity-list,.stats-window-team-list{display:grid;gap:var(--ui-gap-sm)}.stats-window-team-group{display:grid;gap:var(--ui-gap-sm);padding:.48rem .5rem .55rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:linear-gradient(180deg,var(--team-soft),rgba(255,255,255,.025)),#ffffff08}.stats-window-team-header{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-md);padding-bottom:.34rem;border-bottom:1px solid color-mix(in srgb,var(--team-accent) 36%,transparent)}.stats-window-team-header h3{margin:0;color:#edf5fa;font-size:.76rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.stats-window-team-header span{flex-shrink:0;color:color-mix(in srgb,var(--team-accent) 62%,#edf5fa);font-size:.68rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase}.stats-window-entity{display:grid;gap:var(--ui-gap-xs);padding-left:.5rem;border-left:2px solid rgba(255,255,255,.12)}.stats-window-entity.team-blue,.stats-window-entity.team-orange{border-left-color:var(--team-accent);background:linear-gradient(90deg,var(--team-soft),transparent 70%)}.stats-window-entity-title{margin:0;color:#edf5fa;font-size:.82rem;font-weight:800}.stats-window-stat-row{display:grid;grid-template-columns:minmax(0,1fr) auto auto;gap:var(--ui-gap-sm);align-items:center;min-height:1.45rem;font-size:.8rem}.stats-window-stat-name{min-width:0;color:#9eb4c6;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stats-window-stat-target{max-width:7rem;margin-left:.35rem;padding:.16rem .3rem;border-radius:var(--ui-radius-sm);font-size:.7rem}.stats-window-stat-value{color:#edf5fa;font-variant-numeric:tabular-nums}.stats-window-stat-remove{padding:.18rem .36rem;border-radius:var(--ui-radius-sm);font-size:.7rem}.goal-label-list{display:grid;gap:var(--ui-gap-sm);min-width:min(26rem,72vw)}.goal-label-item{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--ui-gap-sm);align-items:center;padding:.56rem .62rem;border-left:2px solid rgba(255,255,255,.14);border-radius:var(--ui-radius-md);background:#ffffff09}.goal-label-item.team-blue,.goal-label-item.team-orange{border-left-color:var(--team-accent);background:linear-gradient(90deg,var(--team-soft),rgba(255,255,255,.03))}.goal-label-item header{min-width:0}.goal-label-item h3{margin:0;color:#edf5fa;font-size:.82rem;font-weight:800}.goal-label-item header span{display:block;margin-top:.12rem;color:#9eb4c6;font-size:.72rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.goal-label-tags{grid-column:1 / -1;display:flex;flex-wrap:wrap;gap:.32rem}.goal-label-tag{padding:.16rem .38rem;border-radius:var(--ui-radius-sm);background:#8ec5ff21;color:#cfe6ff;font-size:.68rem;font-weight:800}.goal-label-tag-empty{background:#8495a829;color:#c0cbd6}.goal-label-actions{justify-self:end;display:flex;gap:.28rem}.goal-label-actions button{min-height:1.8rem;padding:.2rem .48rem;font-size:.72rem}.goal-label-actions .goal-label-watch{border-color:#65d6ad5c;background:#65d6ad2e;color:#d7ffef}.stats-window:has(.kickoff-overview){width:min(34rem,calc(100vw - 1.6rem))}.kickoff-overview{display:grid;gap:var(--ui-gap-md);width:100%;min-width:0}.kickoff-overview-hero{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--ui-gap-md);align-items:start;padding-bottom:.52rem;border-bottom:1px solid rgba(255,255,255,.1)}.kickoff-overview-hero h3{margin:0;color:#edf5fa;font-size:.92rem;font-weight:800}.kickoff-overview-hero span{display:block;margin-top:.12rem;color:#9eb4c6;font-size:.72rem}.kickoff-overview-victor{max-width:9rem;padding:.2rem .46rem;border-radius:var(--ui-radius-sm);background:#8495a82e;color:#d8e5ee;font-size:.72rem;font-weight:800;text-align:center}.kickoff-overview-victor.team-blue,.kickoff-overview-victor.team-orange{background:var(--team-soft);color:color-mix(in srgb,var(--team-accent) 72%,#ffffff)}.kickoff-overview-summary{display:grid;grid-template-columns:1fr;gap:var(--ui-gap-sm)}.kickoff-metric{display:grid;gap:.12rem;min-width:0;padding:.46rem .52rem;border-radius:var(--ui-radius-md);border:1px solid rgba(255,255,255,.08);background:#ffffff09}.kickoff-metric span,.kickoff-detail-row span{color:#89a4ba;font-size:.7rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.kickoff-metric strong{min-width:0;color:#edf5fa;font-size:.78rem;overflow-wrap:anywhere}.kickoff-detail-grid{display:grid;gap:.18rem}.kickoff-detail-row{display:grid;grid-template-columns:minmax(7.5rem,1fr) auto;gap:var(--ui-gap-sm);align-items:baseline;min-height:1.38rem;font-size:.78rem}.kickoff-detail-row strong{color:#edf5fa;font-variant-numeric:tabular-nums}.kickoff-strategy-list{display:grid;grid-template-columns:1fr;gap:var(--ui-gap-sm)}.kickoff-strategy-team{display:grid;gap:.34rem;min-width:0;padding:.54rem .58rem;border-radius:var(--ui-radius-md);border:1px solid color-mix(in srgb,var(--team-accent) 26%,transparent);background:linear-gradient(180deg,var(--team-soft),rgba(255,255,255,.025)),#ffffff08}.kickoff-strategy-team h4{margin:0;color:color-mix(in srgb,var(--team-accent) 62%,#edf5fa);font-size:.72rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.kickoff-strategy-line{margin:0;color:#edf5fa;font-size:.78rem;line-height:1.35;overflow-wrap:anywhere}.kickoff-support-list{display:grid;gap:.22rem;margin:0;padding:0;list-style:none}.kickoff-support-list li{color:#afc4d4;font-size:.74rem;line-height:1.3;overflow-wrap:anywhere}@media(min-width:46rem){.kickoff-overview-summary{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:720px){.kickoff-overview-summary,.kickoff-detail-grid,.kickoff-strategy-list,.kickoff-overview-hero{grid-template-columns:1fr}.kickoff-overview-victor{justify-self:start}}.panel{padding:var(--ui-panel-padding);display:grid;gap:var(--ui-gap-md)}.panel>label,.panel>.detail-grid,.panel>.transport-row,.panel>.module-list{margin-top:0}.panel-copy{margin:0;font-size:.92rem;line-height:1.45}.transport-row{display:flex;gap:var(--ui-gap-sm)}.transport-row>*{flex:1 1 auto}.playback-rate-control{display:grid;gap:var(--ui-gap-xs)}.playback-rate-header{align-items:center;display:flex;justify-content:space-between}.playback-rate-header strong{font-variant-numeric:tabular-nums}.playback-rate-notches{color:var(--ui-muted);display:grid;font-size:.72rem;grid-template-columns:repeat(5,minmax(0,1fr));line-height:1.1;text-align:center}.playback-rate-notches span:first-child{text-align:left}.playback-rate-notches span:last-child{text-align:right}.recording-controls{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-sm)}.camera-presets{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-xs)}.camera-presets button{font-size:var(--ui-control-font-size)}.camera-presets button[data-active=true]{border-color:#8ec5ff6b;background:linear-gradient(180deg,#21476bf5,#0c1b2afa);color:#f3f8fc;box-shadow:inset 0 0 0 1px #8ec5ff1f}.camera-ball-cam{display:grid;gap:var(--ui-gap-xs)}.camera-ball-cam-modes{grid-template-columns:repeat(3,minmax(0,1fr))}.camera-settings-controls{display:grid;gap:var(--ui-gap-sm)}.camera-settings-controls[hidden]{display:none}.camera-setting-label{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-md);font-size:.8rem;color:#9fb3c4}.camera-setting-label strong{color:#e8f0f7;font-variant-numeric:tabular-nums}button,select,input[type=file],input[type=range]{border-radius:var(--ui-radius-md)}button,select,input[type=file]{min-height:var(--ui-control-height);border:1px solid var(--ui-border-subtle);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);background:var(--surface-strong);color:var(--text);font-size:var(--ui-control-font-size);line-height:var(--ui-control-line-height)}button{cursor:pointer}select{appearance:none;padding-right:1.35rem;background-image:linear-gradient(45deg,transparent 50%,var(--muted) 50%),linear-gradient(135deg,var(--muted) 50%,transparent 50%);background-position:calc(100% - .76rem) 50%,calc(100% - .52rem) 50%;background-repeat:no-repeat;background-size:.24rem .24rem}button:hover:not(:disabled),select:hover:not(:disabled){border-color:var(--ui-border-hover)}button:disabled,select:disabled,input:disabled{opacity:.55;cursor:not-allowed}input[type=range]{width:100%;margin-top:var(--ui-gap-xs);accent-color:var(--blue)}.metric-readout{font-size:.88rem;font-weight:700;font-variant-numeric:tabular-nums}.toggle{display:inline-flex;align-items:center;gap:.4rem;color:#bfd0dd}.detail-grid{margin:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.55rem .7rem}.detail-grid dt,.detail-grid dd{margin:0}.detail-grid dt{font-size:.68rem;margin-bottom:.12rem}.detail-grid dd{font-size:.84rem;color:var(--text);overflow-wrap:anywhere}.module-groups{display:grid;gap:var(--ui-gap-md)}.module-summary-group{display:grid;gap:var(--ui-gap-xs)}.module-summary-group h3{margin:0;color:#87afd4;font-size:.64rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase}.module-list{display:flex;flex-wrap:wrap;gap:.5rem}.mechanics-actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem;margin-bottom:.65rem}.mechanics-event-list{display:grid;grid-template-columns:repeat(var(--event-source-columns, 1),minmax(9.5rem,1fr));align-items:stretch}.module-settings{display:grid;gap:.75rem}.module-settings-card{display:grid;gap:.75rem;padding:.85rem .9rem;border-radius:1rem;border:1px solid rgba(255,255,255,.08);background:#ffffff09}.module-settings-subgroup{display:grid;gap:.65rem;padding-top:.15rem;border-top:1px solid rgba(255,255,255,.06)}.module-settings-options{display:grid;gap:.45rem}.module-settings-group-title{margin:0;color:#d7e5ef;font-size:.78rem;font-weight:800}.module-settings-header{display:flex;align-items:start;justify-content:space-between;gap:.8rem}.module-settings-header h3{margin:.1rem 0 0;font-size:.96rem}.module-settings-eyebrow{margin:0;font-size:.66rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase;color:#87afd4}.boost-pickup-filter-panel{display:grid;gap:.65rem}.boost-pickup-filter-summary{display:flex;justify-content:end}.boost-pickup-filter-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.75rem 1rem}.boost-pickup-filter-group{display:grid;align-content:start;gap:.35rem;min-width:0}.boost-pickup-filter-group[hidden]{display:none}.boost-pickup-filter-group-wide{grid-column:1 / -1}.boost-pickup-filter-options{display:flex;flex-wrap:wrap;gap:.35rem .8rem;min-width:0}.boost-pickup-filter-options .toggle{min-width:0}.module-summary-item{appearance:none;display:inline-flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm);min-height:var(--ui-control-height);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border-radius:var(--ui-radius-pill);border:1px solid var(--ui-border-subtle);background:#ffffff08;color:var(--muted);font:inherit;font-size:var(--ui-control-font-size);line-height:var(--ui-control-line-height);cursor:pointer;transition:border-color .14s ease,background-color .14s ease,color .14s ease}.module-summary-item:hover{border-color:var(--ui-border-hover);color:var(--text)}.module-summary-item strong{font-size:.62rem;letter-spacing:.08em;text-transform:uppercase}.module-summary-item[data-active=true]{border-color:#4b94ff38;background:#4b94ff14;color:#dceafb}@media(max-width:1180px){.sidebar{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:860px){.shell{padding:0}.sidebar{grid-template-columns:1fr}.panel-heading{display:grid}.detail-grid{grid-template-columns:1fr 1fr}.viewport-panel{min-height:100dvh}}@media(max-width:560px){.detail-grid{grid-template-columns:1fr}.transport-row{flex-direction:column}.floating-window,.stats-window{left:.55rem;right:.55rem;width:auto}}@media(max-width:720px){.viewport-panel:has(.floating-window:not([hidden])) .viewport{inset:0 0 52dvh}.floating-window{position:fixed;inset:auto 0 0;width:100%;max-width:none;height:52dvh;max-height:52dvh;overflow:auto;border-width:1px 0 0 0;border-radius:1rem 1rem 0 0;transform:none;z-index:30}.floating-window .floating-window-header{cursor:default}}.missed-event-body{display:flex;flex-direction:column;gap:.5rem;padding:.6rem .7rem;max-height:50vh;font-size:.8rem}.missed-event-controls{display:flex;align-items:center;gap:.4rem}.missed-event-controls select{flex:1 1 auto}.missed-event-list{list-style:none;margin:0;padding:0;overflow-y:auto;display:flex;flex-direction:column;gap:.25rem}.missed-event-list li{display:flex;align-items:center;justify-content:space-between;gap:.4rem;padding:.2rem .3rem;border-radius:.3rem;background:#1c272ee6}.missed-event-status{margin:0;min-height:1rem;color:#9fadb7}:root{color-scheme:dark;font-family:IBM Plex Sans,Avenir Next,sans-serif;font-size:13px;--surface: rgba(10, 16, 20, .86);--surface-strong: rgba(14, 22, 27, .96);--border: rgba(218, 226, 232, .14);--text: #f2f6f8;--muted: #9fadb7;--blue: #58a6ff;--orange: #f39a37;--green: #65d6ad;--ui-border-subtle: rgba(255, 255, 255, .1);--ui-border-hover: rgba(255, 255, 255, .2);--ui-radius-md: .5rem;--ui-radius-lg: .72rem;background:radial-gradient(circle at 8% 0%,rgba(88,166,255,.16),transparent 28rem),radial-gradient(circle at 95% 12%,rgba(243,154,55,.12),transparent 24rem),linear-gradient(180deg,#080d10,#11181d);color:var(--text)}*,*:before,*:after{box-sizing:border-box}html,body,#app{min-height:100%}body{margin:0}button,select,input{font:inherit}.stats-report{width:min(1380px,calc(100vw - 2rem));margin:0 auto;padding:1rem 0 2rem}.stats-report-header{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:1rem;align-items:end;padding:1rem 0 .8rem}.stats-report-title h1{margin:0;font-size:clamp(1.55rem,2.6vw,2.7rem);line-height:1;letter-spacing:0}.stats-report-title p{max-width:62rem;margin:.55rem 0 0;color:var(--muted);font-size:.94rem;line-height:1.45}.stats-report-actions{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:.5rem}.stats-report-link,.stats-report-file-label,.stats-report-tabs button,.stats-report-jump-nav a{display:inline-flex;align-items:center;justify-content:center;min-height:2.15rem;padding:.48rem .72rem;border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);background:#10181dd1;color:var(--text);text-decoration:none;cursor:pointer}.stats-report-link:hover,.stats-report-file-label:hover,.stats-report-tabs button:hover,.stats-report-jump-nav a:hover{border-color:var(--ui-border-hover);background:#1c272ef2}.stats-report-file-label input{display:none}.stats-report-status{margin:.25rem 0 1rem;color:#c9d6dd}.stats-report-empty{display:grid;min-height:48dvh;place-items:center;border:1px dashed rgba(255,255,255,.2);border-radius:var(--ui-radius-lg);color:var(--muted);text-align:center}.stats-report-tabs{position:sticky;top:0;z-index:4;display:flex;gap:.45rem;overflow:auto;padding:.65rem 0;background:#080d10d1;-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px)}.stats-report-tabs button{flex:0 0 auto;color:#dce8ee}.stats-report-tabs button[data-active=true]{border-color:#65d6ad85;background:#65d6ad24;color:#effff9}.stats-report-page{display:grid;gap:1rem}.stats-report-page-intro{max-width:78rem;padding-top:.35rem}.stats-report-page-intro h2{margin:0;font-size:1.12rem;letter-spacing:0}.stats-report-page-intro p,.stats-report-note,.stats-report-chart-card p{margin:.35rem 0 0;color:var(--muted);line-height:1.45}.stats-report-summary,.stats-report-metric-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:.75rem}.stats-report-summary-card,.stats-report-section,.stats-report-chart-card{border:1px solid var(--border);border-radius:var(--ui-radius-lg);background:var(--surface);box-shadow:0 18px 44px #0003}.stats-report-summary-card{min-width:0;padding:.8rem}.stats-report-summary-card span{display:block;overflow:hidden;color:var(--muted);font-size:.72rem;font-weight:800;letter-spacing:.1em;text-overflow:ellipsis;text-transform:uppercase;white-space:nowrap}.stats-report-summary-card strong{display:block;overflow-wrap:anywhere;margin-top:.35rem;font-size:1.18rem}.stats-report-summary-card small{display:block;margin-top:.28rem;color:var(--muted)}.stats-report-charts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.75rem}.stats-report-chart-card{min-width:0;padding:.8rem}.stats-report-chart-card h3{margin:0 0 .75rem;font-size:.92rem;letter-spacing:0}.stats-report-bar-chart{display:grid;gap:.5rem}.stats-report-bar-row{display:grid;grid-template-columns:minmax(5.5rem,10rem) minmax(8rem,1fr) minmax(3rem,auto);gap:.55rem;align-items:center;min-height:1.35rem}.stats-report-bar-label{overflow:hidden;color:#dce8ee;text-overflow:ellipsis;white-space:nowrap}.stats-report-bar-track{position:relative;height:.72rem;overflow:hidden;border-radius:999px;background:#ffffff14}.stats-report-bar-track:before{content:"";position:absolute;inset:0 auto 0 0;width:var(--bar-width);border-radius:inherit;background:var(--bar-color)}.stats-report-pie-chart{display:grid;grid-template-columns:8.5rem minmax(0,1fr);gap:1rem;align-items:center}.stats-report-pie{width:8.5rem;aspect-ratio:1;border:1px solid rgba(255,255,255,.16);border-radius:50%}.stats-report-pie-legend{display:grid;gap:.45rem}.stats-report-pie-legend div{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.5rem;align-items:baseline}.stats-report-pie-legend span:before,.stats-report-stacked-legend span:before{content:"";display:inline-block;width:.58rem;height:.58rem;margin-right:.3rem;border-radius:50%;background:var(--legend-color)}.stats-report-pie-legend span,.stats-report-stacked-legend span{overflow:hidden;color:#dce8ee;text-overflow:ellipsis;white-space:nowrap}.stats-report-stacked-chart{display:grid;gap:.82rem}.stats-report-stacked-row{display:grid;gap:.38rem}.stats-report-stacked-row>strong{overflow:hidden;color:#e5edf1;font-weight:700;text-overflow:ellipsis;white-space:nowrap}.stats-report-stacked-track{display:flex;height:.82rem;overflow:hidden;border-radius:999px;background:#ffffff14}.stats-report-stacked-track span{flex:0 0 var(--segment-width);min-width:0;background:var(--segment-color)}.stats-report-stacked-legend{display:flex;flex-wrap:wrap;gap:.42rem .72rem;color:var(--muted);font-size:.82rem}.stats-report-goal-list{display:grid;gap:1rem}.stats-report-goal-card{overflow:hidden;border:1px solid var(--border);border-left:3px solid rgba(255,255,255,.16);border-radius:var(--ui-radius-lg);background:var(--surface);box-shadow:0 18px 44px #0003}.stats-report-goal-card[data-team=blue]{border-left-color:var(--blue)}.stats-report-goal-card[data-team=orange]{border-left-color:var(--orange)}.stats-report-goal-card>header{display:flex;justify-content:space-between;gap:1rem;align-items:center;padding:.85rem .9rem;border-bottom:1px solid var(--border);background:#ffffff05}.stats-report-goal-heading{min-width:0}.stats-report-goal-card h2,.stats-report-goal-subsection h3{margin:0;letter-spacing:0}.stats-report-goal-card h2{font-size:1rem}.stats-report-goal-heading span{display:block;margin-top:.14rem;overflow:hidden;color:var(--muted);text-overflow:ellipsis;white-space:nowrap}.stats-report-goal-watch{flex:0 0 auto;padding:.34rem .58rem;border:1px solid rgba(101,214,173,.34);border-radius:var(--ui-radius-md);background:#65d6ad24;color:#d7ffef;cursor:pointer;font-size:.82rem;font-weight:800;text-decoration:none}.stats-report-goal-watch:hover{border-color:#65d6ad85;background:#65d6ad38}.stats-report-goal-tags{display:flex;flex-wrap:wrap;gap:.42rem;padding:.7rem .9rem 0}.stats-report-goal-tag{padding:.2rem .48rem;border:1px solid rgba(88,166,255,.24);border-radius:var(--ui-radius-md);background:#58a6ff24;color:#d8ecff;font-size:.78rem;font-weight:800}.stats-report-goal-tag-empty{border-color:#9fadb733;background:#9fadb71f;color:#c8d2d9}.stats-report-detail-list{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:.7rem .9rem;margin:0;padding:.85rem .9rem}.stats-report-detail-item{min-width:0}.stats-report-detail-list dt{color:var(--muted);font-size:.72rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.stats-report-detail-list dd{overflow-wrap:anywhere;margin:.22rem 0 0;color:#edf5fa;font-weight:700}.stats-report-goal-subsection{display:grid;gap:.5rem;padding:0 .9rem .9rem}.stats-report-goal-subsection h3{color:#dce8ee;font-size:.88rem}.stats-report-jump-nav{display:flex;flex-wrap:wrap;gap:.45rem}.stats-report-grid{display:grid;gap:1rem}.stats-report-section{overflow:hidden}.stats-report-section header{display:flex;justify-content:space-between;gap:1rem;align-items:center;padding:.85rem .9rem;border-bottom:1px solid var(--border);background:#ffffff05}.stats-report-section h2{margin:0;font-size:1rem;letter-spacing:0}.stats-report-section header span{color:var(--muted)}.stats-report-table-wrap{overflow:auto}.stats-report-table{width:100%;border-collapse:collapse;font-variant-numeric:tabular-nums}.stats-report-table th,.stats-report-table td{padding:.48rem .62rem;border-bottom:1px solid rgba(255,255,255,.07);text-align:right;white-space:nowrap}.stats-report-table th:first-child,.stats-report-table td:first-child{position:sticky;left:0;z-index:1;max-width:20rem;background:var(--surface-strong);text-align:left;white-space:normal}.stats-report-table th{color:#b7c6cf;font-size:.72rem;text-transform:uppercase}@media(max-width:960px){.stats-report-header{grid-template-columns:1fr}.stats-report-actions{justify-content:flex-start}.stats-report-summary,.stats-report-metric-grid,.stats-report-charts{grid-template-columns:1fr}.stats-report-detail-list{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:620px){.stats-report{width:min(100vw - 1rem,1380px)}.stats-report-bar-row,.stats-report-pie-chart{grid-template-columns:1fr}.stats-report-pie{width:min(11rem,54vw)}.stats-report-goal-card>header{display:grid}.stats-report-detail-list{grid-template-columns:1fr}}.replay-review-document,#app.replay-review-root,.replay-review-root{height:auto;min-height:100%;overflow:visible}body.replay-review-document{overflow-y:auto}.replay-review-shell{min-height:100dvh}.replay-review-toolbar{position:fixed;top:.75rem;right:.75rem;z-index:1000;display:flex;align-items:center;gap:.4rem;max-width:min(34rem,calc(100vw - 1.5rem));padding:.35rem;border:1px solid rgba(255,255,255,.14);border-radius:.5rem;background:#080d10c7;color:#f2f6f8;-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px);box-shadow:0 14px 34px #00000042}.replay-review-status{overflow:hidden;max-width:14rem;padding:0 .35rem;color:#c9d6dd;font-size:.78rem;text-overflow:ellipsis;white-space:nowrap}.replay-review-toolbar button,.replay-review-file{display:inline-flex;align-items:center;justify-content:center;min-height:2rem;padding:.42rem .62rem;border:1px solid rgba(255,255,255,.12);border-radius:.4rem;background:#10181dd6;color:#f2f6f8;cursor:pointer;font:inherit;text-decoration:none}.replay-review-toolbar button:hover,.replay-review-file:hover{border-color:#ffffff38;background:#1c272ef2}.replay-review-toolbar button[data-active=true]{border-color:#65d6ad8c;background:#65d6ad29;color:#effff9}.replay-review-file input,.replay-review-pane[hidden]{display:none}.replay-review-empty{display:grid;min-height:100dvh;place-items:center;padding:4rem 1rem;color:#9fadb7;text-align:center}@media(max-width:720px){.replay-review-toolbar{left:.5rem;right:.5rem}.replay-review-status{flex:1 1 auto;max-width:none}} +:root{color-scheme:dark;font-family:IBM Plex Sans,Avenir Next,sans-serif;font-size:13px;--surface: rgba(8, 20, 30, .82);--surface-strong: rgba(7, 16, 24, .94);--surface-soft: rgba(12, 28, 40, .72);--border: rgba(167, 199, 222, .14);--text: #edf5fa;--muted: #9eb4c6;--blue: #4b94ff;--blue-soft: rgba(75, 148, 255, .18);--orange: #f39a37;--orange-soft: rgba(243, 154, 55, .18);--ui-gap-xs: .22rem;--ui-gap-sm: .34rem;--ui-gap-md: .5rem;--ui-panel-padding: .52rem;--ui-control-font-size: .72rem;--ui-control-line-height: 1.15;--ui-control-padding-block: .22rem;--ui-control-padding-inline: .38rem;--ui-control-height: 1.55rem;--ui-radius-sm: .36rem;--ui-radius-md: .5rem;--ui-radius-lg: .72rem;--ui-radius-pill: 999px;--ui-border-subtle: rgba(255, 255, 255, .1);--ui-border-hover: rgba(255, 255, 255, .18);--ui-overlay-bg: rgba(4, 12, 18, .82);--ui-overlay-bg-strong: rgba(4, 12, 18, .9);background:radial-gradient(circle at top left,rgba(73,112,158,.28),transparent 32%),radial-gradient(circle at top right,rgba(243,154,55,.12),transparent 24%),linear-gradient(180deg,#071018,#0b1721);color:var(--text)}html,body,#app{width:100%;height:100%;overflow:hidden}.shell{min-height:100dvh;height:100dvh;padding:0;display:block}.workspace{height:100%;display:block;min-height:0}.panel h2,.stats-panel h2{margin:0}.panel-copy{color:#bdd0de}.viewport-panel,.panel,.stats-panel{position:relative;border:1px solid var(--border);border-radius:1.4rem;background:var(--surface);box-shadow:0 22px 56px #0000003d;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}.viewport-panel{width:100%;height:100%;min-height:100dvh;overflow:hidden;border:0;border-radius:0;background:#061019;box-shadow:none}.viewport{position:absolute;inset:0}.top-chrome{position:absolute;top:.8rem;left:.8rem;z-index:20}.launcher-toggle{width:2.65rem;min-width:0;aspect-ratio:1;display:grid;place-items:center;padding:0;border-color:transparent;border-radius:var(--ui-radius-md);background:#050e16ad;box-shadow:0 12px 30px #0000004d;-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px)}.launcher-toggle:hover,.launcher-toggle[aria-expanded=true]{border-color:#ffffff29;background:#081824d1}.launcher-toggle-bars,.launcher-toggle-bars:before,.launcher-toggle-bars:after{display:block;width:1.18rem;height:.12rem;border-radius:var(--ui-radius-pill);background:#edf5fa}.launcher-toggle-bars{position:relative}.launcher-toggle-bars:before,.launcher-toggle-bars:after{content:"";position:absolute;left:0}.launcher-toggle-bars:before{top:-.38rem}.launcher-toggle-bars:after{top:.38rem}.launcher-menu{position:absolute;top:calc(100% + .55rem);left:0;width:min(22rem,calc(100vw - 1.6rem));max-height:calc(100dvh - 7.5rem);overflow:auto;display:grid;gap:var(--ui-gap-md);padding:var(--ui-panel-padding);border:1px solid rgba(255,255,255,.12);border-radius:var(--ui-radius-lg);background:var(--ui-overlay-bg-strong);box-shadow:0 18px 54px #0000005c;-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px)}.launcher-menu[hidden]{display:none}.launcher-section{display:grid;gap:var(--ui-gap-xs)}.launcher-section h2{margin:0;color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase}.launcher-section button{width:100%;text-align:left}.hidden-file-input,.visually-hidden{position:fixed;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap}.team-blue{--team-accent: var(--blue);--team-soft: var(--blue-soft)}.team-orange{--team-accent: var(--orange);--team-soft: var(--orange-soft)}.floating-window-layer,.stats-window-layer{position:absolute;inset:0;z-index:12;pointer-events:none}.floating-window,.stats-window,.scoreboard-window{position:absolute;left:clamp(.8rem,var(--window-x, 1rem),calc(100vw - 18rem));top:clamp(.8rem,var(--window-y, 1rem),calc(100dvh - 12rem));width:min(26rem,calc(100vw - 1.6rem));overflow:visible;display:grid;gap:var(--ui-gap-md);padding:var(--ui-panel-padding);border:1px solid rgba(255,255,255,.12);border-radius:var(--ui-radius-lg);background:var(--ui-overlay-bg);box-shadow:0 16px 44px #00000052;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);pointer-events:auto;-webkit-user-select:none;user-select:none}.floating-window[hidden],.stats-window[hidden],.scoreboard-window[hidden]{display:none}.scoreboard-window{left:50%;top:.7rem;width:auto;min-width:4.4rem;transform:translate(-50%);gap:var(--ui-gap-sm);padding:.34rem .62rem;border-radius:999px}.scoreboard-window-body{display:grid;gap:.42rem}.scoreboard-scoreline{display:grid;grid-template-columns:minmax(1.2rem,auto) auto minmax(1.2rem,auto);align-items:center;justify-content:center;gap:.3rem;min-width:0;font-variant-numeric:tabular-nums}.scoreboard-goal-value{color:var(--team-accent);font-size:1rem;font-weight:850;line-height:1;text-align:center}.scoreboard-divider{color:var(--muted);font-size:1rem;font-weight:800;line-height:1}.scoreboard-empty{margin:0;color:var(--muted);font-size:.74rem;text-align:center}@media(max-width:900px){.scoreboard-window{top:3.25rem}}@media(max-width:640px){.scoreboard-window{min-width:4rem;padding:.32rem .56rem}.scoreboard-scoreline{gap:.24rem}.scoreboard-goal-value{font-size:.92rem}}.floating-window-camera{width:min(26rem,calc(100vw - 1.6rem))}.floating-window-recording{--window-x: calc(100vw - 27rem) ;width:min(26rem,calc(100vw - 1.6rem))}.floating-window-playback{--window-x: calc(100vw - 23rem) ;width:min(21rem,calc(100vw - 1.6rem))}.floating-window-mechanics{width:auto;min-width:min(18rem,calc(100vw - 1.6rem));max-width:min(42rem,calc(100vw - 1.6rem))}.mechanics-timeline-window-body{display:grid;gap:var(--ui-gap-sm);max-height:min(72dvh,42rem);overflow:auto}.floating-window-event-playlist{width:min(27rem,calc(100vw - 1.6rem))}.floating-window-mechanics-review{width:min(30rem,calc(100vw - 1.6rem))}.floating-window-replay-loading{width:min(32rem,calc(100vw - 1.6rem))}.floating-window-boost-pickups{width:min(34rem,calc(100vw - 1.6rem))}.floating-window-touch-controls,.floating-window-touch-legend{width:min(24rem,calc(100vw - 1.6rem))}.floating-window-shot-visualization{width:min(38rem,calc(100vw - 1.6rem))}.floating-window-header,.stats-window-header{display:flex;align-items:start;justify-content:space-between;gap:var(--ui-gap-md);cursor:grab}.stats-window-header-actions-only{justify-content:end}.floating-window:active .floating-window-header,.stats-window:active .stats-window-header{cursor:grabbing}.floating-window-header h2,.stats-window-header h2{margin:0;color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase}.floating-window-hide,.stats-window-action{flex-shrink:0;padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border-radius:var(--ui-radius-md);font-size:var(--ui-control-font-size)}.mechanics-review-window-body{display:grid;gap:var(--ui-gap-md);max-height:min(74dvh,42rem);min-height:0;overflow:hidden auto;scrollbar-width:thin}.event-playlist-window-body{display:grid;gap:var(--ui-gap-sm);min-height:0}.touch-color-legend-body{display:grid;gap:var(--ui-gap-md);max-height:min(70dvh,38rem);overflow:auto;scrollbar-width:thin}.touch-color-legend-explainer{display:grid;gap:var(--ui-gap-xs);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);color:#c3d3df;font-size:.78rem;background:#ffffff0a}.touch-color-legend-group{display:grid;gap:var(--ui-gap-xs)}.touch-color-legend-heading{width:100%;min-height:1.45rem;margin:0;padding:.12rem .32rem;border-radius:var(--ui-radius-sm);color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.1em;text-align:left;text-transform:uppercase}.touch-color-legend-heading[data-active=true]{border-color:#8ec5ff6b;background:#21476b94;color:#f3f8fc}.touch-color-legend-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-xs)}.touch-color-legend-item{min-width:0;display:flex;align-items:center;gap:var(--ui-gap-xs);color:#e8f0f7;font-size:.76rem}.touch-color-legend-swatch{flex:0 0 auto;width:.78rem;height:.78rem;border:1px solid rgba(255,255,255,.35);border-radius:50%;box-shadow:0 0 0 1px #00000038}.event-playlist-toolbar{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm)}.event-playlist-filter{position:relative;min-width:0}.event-playlist-filter summary{display:inline-flex;align-items:center;min-height:var(--ui-control-height);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);background:#ffffff0a;color:var(--text);font-size:var(--ui-control-font-size);cursor:pointer;list-style:none}.event-playlist-filter summary::-webkit-details-marker{display:none}.event-playlist-filter-panel{position:absolute;z-index:5;top:calc(100% + .4rem);left:0;width:min(22rem,calc(100vw - 3rem));max-height:min(28rem,calc(100dvh - 10rem));overflow:auto;display:grid;gap:var(--ui-gap-md);padding:.85rem;border:1px solid rgba(255,255,255,.14);border-radius:var(--ui-radius-md);background:#090e16fa;box-shadow:0 16px 34px #00000057}.event-playlist-filter-actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem}.event-playlist-filter-group{display:grid;gap:.45rem}.event-playlist-filter-group h3{margin:0;color:#87afd4;font-size:.64rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase}.event-playlist-filter-option{min-width:0}.event-playlist-follow{flex-shrink:0}.event-playlist-list{max-height:min(31rem,calc(100dvh - 11rem));overflow:auto;display:grid;gap:.45rem;padding-right:.15rem;scrollbar-width:thin}.event-playlist-item{--event-color: #d1d9e0;appearance:none;width:100%;display:grid;grid-template-columns:3.4rem minmax(0,1fr);gap:.7rem;align-items:start;padding:.6rem .7rem;border:1px solid rgba(255,255,255,.09);border-left:.28rem solid var(--event-color);border-radius:var(--ui-radius-md);background:#ffffff09;color:var(--text);font:inherit;text-align:left;cursor:pointer}.event-playlist-item:hover,.event-playlist-item[data-active=true]{border-color:color-mix(in srgb,var(--event-color) 48%,rgba(255,255,255,.12));background:color-mix(in srgb,var(--event-color) 15%,rgba(255,255,255,.045))}.event-playlist-time{color:var(--muted);font-size:.72rem;font-variant-numeric:tabular-nums;line-height:1.35}.event-playlist-main{min-width:0;display:grid;gap:.15rem}.shot-visualization{display:grid;gap:var(--ui-gap-md);min-height:0}.shot-visualization-summary{color:var(--text);font-size:.78rem;font-weight:700;font-variant-numeric:tabular-nums}.shot-chart-canvas{width:100%;aspect-ratio:16 / 10;display:block;border:1px solid rgba(255,255,255,.1);border-radius:var(--ui-radius-md);background:#0f2b24}.shot-visualization-layout{display:grid;grid-template-columns:minmax(10rem,.78fr) minmax(15rem,1.22fr);gap:var(--ui-gap-md);min-height:0}.shot-list{display:grid;align-content:start;gap:.45rem;max-height:18rem;overflow:auto;padding-right:.15rem;scrollbar-width:thin}.shot-list-item{appearance:none;width:100%;display:grid;gap:.15rem;min-height:3.1rem;padding:.52rem .62rem;border:1px solid rgba(255,255,255,.09);border-left:.24rem solid #62d2a2;border-radius:var(--ui-radius-md);background:#ffffff09;color:var(--text);font:inherit;text-align:left;cursor:pointer}.shot-list-item[data-selected=true]{border-color:#f8fafcb8;background:#87afd429}.shot-list-item[data-active=true]{border-left-color:#e11d48}.shot-list-title{min-width:0;overflow:hidden;color:var(--text);font-size:.78rem;font-weight:800;text-overflow:ellipsis;white-space:nowrap}.shot-list-meta{color:var(--muted);font-size:.68rem;font-variant-numeric:tabular-nums;white-space:nowrap}.shot-demo-panel{display:grid;gap:var(--ui-gap-sm);min-width:0}.shot-demo-scene{width:100%;height:12rem;overflow:hidden;border:1px solid rgba(255,255,255,.1);border-radius:var(--ui-radius-md);background:#07111c}.shot-demo-scene canvas{width:100%;height:100%;display:block}.shot-details{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem;margin:0}.shot-details div{min-width:0;padding:.48rem .56rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:#ffffff09}.shot-details dt{color:var(--muted);font-size:.62rem;font-weight:700;text-transform:uppercase}.shot-details dd{min-width:0;margin:.14rem 0 0;overflow:hidden;color:var(--text);font-size:.76rem;font-variant-numeric:tabular-nums;text-overflow:ellipsis;white-space:nowrap}.shot-visualization-empty{margin:0;color:var(--muted);font-size:.78rem}.event-playlist-main strong{min-width:0;overflow-wrap:anywhere;font-size:.82rem;line-height:1.3}.event-playlist-main span{min-width:0;overflow-wrap:anywhere;color:var(--muted);font-size:.68rem;line-height:1.35}.mechanics-review-load-row{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:var(--ui-gap-sm);align-items:center}.mechanics-review-file{display:inline-grid;align-items:center;min-height:var(--ui-control-height);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);background:#ffffff0e;color:var(--text);cursor:pointer}.mechanics-review-file input{position:fixed;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap}.mechanics-review-url{min-width:0}.mechanics-review-status{min-height:1.2rem;color:var(--muted);font-size:.78rem}.mechanics-review-current{display:grid;gap:var(--ui-gap-sm);padding:.55rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:#ffffff09}.mechanics-review-index{color:#87afd4;font-size:.68rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase}.mechanics-review-current h3{margin:0;font-size:.96rem;line-height:1.2}.mechanics-review-fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-sm);margin:0}.mechanics-review-fields div{min-width:0}.mechanics-review-fields dt{color:var(--muted);font-size:.68rem;text-transform:uppercase}.mechanics-review-fields dd{margin:.1rem 0 0;overflow-wrap:anywhere}.mechanics-review-wide{grid-column:1 / -1}.mechanics-review-actions,.mechanics-review-decision-actions,.mechanics-review-list-header{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm)}.mechanics-review-actions button,.mechanics-review-decision-actions button{flex:1 1 0}#mechanics-review-confirm{border-color:#4caf7885}#mechanics-review-reject{border-color:#dc5f5f94}.mechanics-review-list-header{color:var(--muted);font-size:.72rem;font-weight:700;text-transform:uppercase}.mechanics-review-replays{display:grid;gap:var(--ui-gap-xs)}.replay-loading-window-body{display:grid;gap:var(--ui-gap-sm);max-height:min(72dvh,40rem);min-height:0}.replay-loading-summary{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm);color:var(--muted);font-size:.72rem;font-weight:700;text-transform:uppercase}.replay-loading-list{max-height:min(38rem,calc(100dvh - 9rem));overflow:auto;display:grid;gap:var(--ui-gap-xs);padding-right:.15rem;scrollbar-width:thin}.mechanics-review-replay-load{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.35rem var(--ui-gap-sm);min-width:0;padding:.5rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:#ffffff09}.mechanics-review-replay-load.loaded{border-color:#4caf786b}.mechanics-review-replay-load.error{border-color:#dc5f5f94}.mechanics-review-replay-load-main{display:grid;min-width:0;gap:.16rem}.mechanics-review-replay-load-title,.mechanics-review-replay-load-meta{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-replay-load-title{color:var(--text);font-size:.78rem;font-weight:700}.mechanics-review-replay-load-meta{color:var(--muted);font-size:.68rem}.mechanics-review-replay-load-status{max-width:11rem;overflow:hidden;color:var(--muted);font-size:.68rem;text-align:right;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-replay-load.loaded .mechanics-review-replay-load-status{color:#83d4a4}.mechanics-review-replay-load.error .mechanics-review-replay-load-status{color:#ff9b9b}.mechanics-review-replay-load-progress{grid-column:1 / -1;height:.25rem;overflow:hidden;border-radius:999px;background:#ffffff14}.mechanics-review-replay-load-progress span{display:block;width:0;height:100%;border-radius:inherit;background:#77a9ff;transition:width .14s ease}.mechanics-review-replay-load.loaded .mechanics-review-replay-load-progress span{background:#4caf78}.mechanics-review-replay-load.error .mechanics-review-replay-load-progress span{background:#dc5f5f}.mechanics-review-list{max-height:min(22rem,calc(100dvh - 27rem));display:grid;gap:var(--ui-gap-xs);overflow:auto;padding-right:.15rem;scrollbar-width:thin}.mechanics-review-item{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--ui-gap-sm);align-items:center;width:100%;min-height:2rem;text-align:left}.mechanics-review-item span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-item strong{color:var(--muted);font-size:.72rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mechanics-review-item[data-active=true]{border-color:#4b94ff6b;background:#4b94ff29}.viewport canvas{display:block;width:100%;height:100%}.replay-load-modal{position:fixed;inset:0;z-index:100;display:grid;place-items:center;padding:1.25rem;background:radial-gradient(circle at top,rgba(89,157,219,.18),transparent 30%),#040b12c2;-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px)}.replay-load-modal[hidden]{display:none}.replay-load-modal__dialog{width:min(32rem,100%);display:grid;gap:.75rem;padding:1.4rem 1.45rem;border-radius:1.35rem;border:1px solid rgba(255,255,255,.12);background:linear-gradient(180deg,#0b1724f5,#070f18f0);box-shadow:0 24px 70px #0006}.replay-load-modal__eyebrow{margin:0;font-size:.72rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase;color:#87afd4}.replay-load-modal__title,.replay-load-modal__status,.replay-load-modal__meta{margin:0}.replay-load-modal__title{font-size:clamp(1.45rem,4vw,2.1rem);line-height:1.1;color:#f3f8fc}.replay-load-modal__status{color:#e6f0f7;font-size:1rem}.replay-load-modal__phase-list{display:grid;gap:.52rem}.replay-load-modal__phase-row{display:grid;gap:.28rem}.replay-load-modal__phase-label{margin:0;font-size:.82rem;letter-spacing:.04em;color:#9eb4c6}.replay-load-modal__phase-row[data-state=active] .replay-load-modal__phase-label{color:#edf5fa}.replay-load-modal__phase-row[data-state=complete] .replay-load-modal__phase-label{color:#c5d9e7}.replay-load-modal__phase-bar{overflow:hidden;height:.58rem;border-radius:999px;background:#ffffff1a}.replay-load-modal__phase-fill{width:0%;height:100%;border-radius:inherit;background:linear-gradient(90deg,#4b94ff,#8ec5ff 55%,#f39a37);transition:width .14s ease}.replay-load-modal__phase-row[data-state=complete] .replay-load-modal__phase-fill{opacity:.95}.replay-load-modal__phase-fill[data-indeterminate=true]{width:100%!important;background:linear-gradient(90deg,#4b94ff40,#4b94ffcc 28%,#8ec5fff2,#f39a37cc 72%,#f39a3740);background-size:180% 100%;animation:replay-load-phase-indeterminate 1.1s linear infinite}@keyframes replay-load-phase-indeterminate{0%{background-position:0% 0%}to{background-position:180% 0%}}.replay-load-modal__meta{color:#9eb4c6;font-size:.92rem}.empty-state{position:absolute;left:50%;top:50%;z-index:10;display:grid;gap:.55rem;min-width:min(20rem,calc(100vw - 2rem));transform:translate(-50%,-50%);padding:.85rem .95rem;border-radius:1rem;border:1px solid rgba(169,201,226,.14);background:#040c12d1;color:#bfd2de;text-align:center;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}.empty-state[hidden]{display:none}.empty-state p{margin:0}.stats-panel{padding:1.15rem 1.15rem 1rem}.panel-heading{display:flex;justify-content:space-between;align-items:start;gap:1rem;margin-bottom:1rem}.player-stats-stack{display:grid;gap:.9rem}.player-team-stack{display:grid;gap:.85rem}.player-team-group{display:grid;gap:.7rem;padding:.75rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:linear-gradient(180deg,var(--team-soft),rgba(255,255,255,.025)),#ffffff08}.player-team-header{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-md);padding-bottom:.42rem;border-bottom:1px solid color-mix(in srgb,var(--team-accent) 36%,transparent)}.player-team-header h3{margin:0;color:#edf5fa;font-size:.76rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.player-team-header span{flex-shrink:0;color:color-mix(in srgb,var(--team-accent) 62%,#edf5fa);font-size:.68rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase}.player-stats-grid{display:flex;gap:.7rem;flex-wrap:wrap}.player-card{flex:1 1 13rem;min-width:12rem;padding:.85rem;border-radius:1rem;border:1px solid rgba(255,255,255,.08);background:#ffffff09}.player-card.team-blue{background:var(--blue-soft);border-color:#4b94ff42}.player-card.team-orange{background:var(--orange-soft);border-color:#f39a3747}.player-card.shared{background:linear-gradient(180deg,#ffffff0f,#ffffff06),#ffffff09;border-color:#ffffff1f}.player-card-header{display:flex;justify-content:space-between;align-items:center;gap:.4rem;margin-bottom:.45rem}.player-name{font-size:.85rem;font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stat-row{display:flex;justify-content:space-between;gap:.5rem;padding:.15rem 0;font-size:.8rem}.label,.detail-grid dt,.stat-row .label{color:#89a4ba}.stat-row .value,.detail-grid dd{font-variant-numeric:tabular-nums}.role-indicator,.depth-indicator{flex-shrink:0;padding:.18rem .45rem;border-radius:999px;font-size:.64rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase}.role-back,.depth-last{background:#ea55552e;color:#ff9b9b}.role-forward,.depth-upfield{background:#4ac6762e;color:#9ce5a8}.role-other,.depth-level{background:#8495a82e;color:#c0cbd6}.role-mid,.depth-mid{background:#f39a372e;color:#ffc680}.stat-module-section{display:grid;gap:.45rem}.stat-module-label{font-size:.72rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase;color:#6f889d}.sidebar{min-height:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));align-content:start;align-items:start;gap:1rem}.stat-window-empty{margin:0;color:#9eb4c6;font-size:.88rem}.stats-window-toolbar,.stats-window-scope-row,.stats-window-actions{display:flex;align-items:center;gap:var(--ui-gap-sm);flex-wrap:wrap}.stats-window-toolbar{justify-content:end}.stats-window-scope-select{min-width:min(100%,13rem)}.stats-window-add-button{width:var(--ui-control-height);min-width:var(--ui-control-height);padding:0;font-size:1rem;font-weight:800;line-height:1}.stats-window-add-button[aria-expanded=true]{border-color:var(--ui-border-hover);background:#ffffff1a}.stats-window-scope-select.team-blue,.stats-window-scope-select.team-orange,.stats-window-stat-target.team-blue,.stats-window-stat-target.team-orange{border-color:var(--team-accent);box-shadow:inset .22rem 0 0 var(--team-accent)}.stats-window-picker{display:grid;gap:var(--ui-gap-sm);padding:var(--ui-panel-padding);border-radius:var(--ui-radius-md);border:1px solid rgba(255,255,255,.08);background:#ffffff0a}.stats-window-picker[hidden]{display:none}.stats-window-picker-list{display:grid;gap:var(--ui-gap-xs);overflow:visible}.stats-window-picker-item{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.45rem;align-items:center;width:100%;padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);text-align:left}.stats-window-picker-item span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stats-window-picker-item strong{color:#87afd4;font-size:.62rem;letter-spacing:.08em;text-transform:uppercase}.stats-window-stat-list,.stats-window-entity-list,.stats-window-team-list{display:grid;gap:var(--ui-gap-sm)}.stats-window-team-group{display:grid;gap:var(--ui-gap-sm);padding:.48rem .5rem .55rem;border:1px solid rgba(255,255,255,.08);border-radius:var(--ui-radius-md);background:linear-gradient(180deg,var(--team-soft),rgba(255,255,255,.025)),#ffffff08}.stats-window-team-header{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-md);padding-bottom:.34rem;border-bottom:1px solid color-mix(in srgb,var(--team-accent) 36%,transparent)}.stats-window-team-header h3{margin:0;color:#edf5fa;font-size:.76rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.stats-window-team-header span{flex-shrink:0;color:color-mix(in srgb,var(--team-accent) 62%,#edf5fa);font-size:.68rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase}.stats-window-entity{display:grid;gap:var(--ui-gap-xs);padding-left:.5rem;border-left:2px solid rgba(255,255,255,.12)}.stats-window-entity.team-blue,.stats-window-entity.team-orange{border-left-color:var(--team-accent);background:linear-gradient(90deg,var(--team-soft),transparent 70%)}.stats-window-entity-title{margin:0;color:#edf5fa;font-size:.82rem;font-weight:800}.stats-window-stat-row{display:grid;grid-template-columns:minmax(0,1fr) auto auto;gap:var(--ui-gap-sm);align-items:center;min-height:1.45rem;font-size:.8rem}.stats-window-stat-name{min-width:0;color:#9eb4c6;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stats-window-stat-target{max-width:7rem;margin-left:.35rem;padding:.16rem .3rem;border-radius:var(--ui-radius-sm);font-size:.7rem}.stats-window-stat-value{color:#edf5fa;font-variant-numeric:tabular-nums}.stats-window-stat-remove{padding:.18rem .36rem;border-radius:var(--ui-radius-sm);font-size:.7rem}.goal-label-list{display:grid;gap:var(--ui-gap-sm);min-width:min(26rem,72vw)}.goal-label-item{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--ui-gap-sm);align-items:center;padding:.56rem .62rem;border-left:2px solid rgba(255,255,255,.14);border-radius:var(--ui-radius-md);background:#ffffff09}.goal-label-item.team-blue,.goal-label-item.team-orange{border-left-color:var(--team-accent);background:linear-gradient(90deg,var(--team-soft),rgba(255,255,255,.03))}.goal-label-item header{min-width:0}.goal-label-item h3{margin:0;color:#edf5fa;font-size:.82rem;font-weight:800}.goal-label-item header span{display:block;margin-top:.12rem;color:#9eb4c6;font-size:.72rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.goal-label-tags{grid-column:1 / -1;display:flex;flex-wrap:wrap;gap:.32rem}.goal-label-tag{padding:.16rem .38rem;border-radius:var(--ui-radius-sm);background:#8ec5ff21;color:#cfe6ff;font-size:.68rem;font-weight:800}.goal-label-tag-empty{background:#8495a829;color:#c0cbd6}.goal-label-actions{justify-self:end;display:flex;gap:.28rem}.goal-label-actions button{min-height:1.8rem;padding:.2rem .48rem;font-size:.72rem}.goal-label-actions .goal-label-watch{border-color:#65d6ad5c;background:#65d6ad2e;color:#d7ffef}.stats-window:has(.kickoff-overview){width:min(34rem,calc(100vw - 1.6rem))}.kickoff-overview{display:grid;gap:var(--ui-gap-md);width:100%;min-width:0}.kickoff-overview-hero{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--ui-gap-md);align-items:start;padding-bottom:.52rem;border-bottom:1px solid rgba(255,255,255,.1)}.kickoff-overview-hero h3{margin:0;color:#edf5fa;font-size:.92rem;font-weight:800}.kickoff-overview-hero span{display:block;margin-top:.12rem;color:#9eb4c6;font-size:.72rem}.kickoff-overview-victor{max-width:9rem;padding:.2rem .46rem;border-radius:var(--ui-radius-sm);background:#8495a82e;color:#d8e5ee;font-size:.72rem;font-weight:800;text-align:center}.kickoff-overview-victor.team-blue,.kickoff-overview-victor.team-orange{background:var(--team-soft);color:color-mix(in srgb,var(--team-accent) 72%,#ffffff)}.kickoff-overview-summary{display:grid;grid-template-columns:1fr;gap:var(--ui-gap-sm)}.kickoff-metric{display:grid;gap:.12rem;min-width:0;padding:.46rem .52rem;border-radius:var(--ui-radius-md);border:1px solid rgba(255,255,255,.08);background:#ffffff09}.kickoff-metric span,.kickoff-detail-row span{color:#89a4ba;font-size:.7rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.kickoff-metric strong{min-width:0;color:#edf5fa;font-size:.78rem;overflow-wrap:anywhere}.kickoff-detail-grid{display:grid;gap:.18rem}.kickoff-detail-row{display:grid;grid-template-columns:minmax(7.5rem,1fr) auto;gap:var(--ui-gap-sm);align-items:baseline;min-height:1.38rem;font-size:.78rem}.kickoff-detail-row strong{color:#edf5fa;font-variant-numeric:tabular-nums}.kickoff-strategy-list{display:grid;grid-template-columns:1fr;gap:var(--ui-gap-sm)}.kickoff-strategy-team{display:grid;gap:.34rem;min-width:0;padding:.54rem .58rem;border-radius:var(--ui-radius-md);border:1px solid color-mix(in srgb,var(--team-accent) 26%,transparent);background:linear-gradient(180deg,var(--team-soft),rgba(255,255,255,.025)),#ffffff08}.kickoff-strategy-team h4{margin:0;color:color-mix(in srgb,var(--team-accent) 62%,#edf5fa);font-size:.72rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.kickoff-strategy-line{margin:0;color:#edf5fa;font-size:.78rem;line-height:1.35;overflow-wrap:anywhere}.kickoff-support-list{display:grid;gap:.22rem;margin:0;padding:0;list-style:none}.kickoff-support-list li{color:#afc4d4;font-size:.74rem;line-height:1.3;overflow-wrap:anywhere}@media(min-width:46rem){.kickoff-overview-summary{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:720px){.kickoff-overview-summary,.kickoff-detail-grid,.kickoff-strategy-list,.kickoff-overview-hero{grid-template-columns:1fr}.kickoff-overview-victor{justify-self:start}}.panel{padding:var(--ui-panel-padding);display:grid;gap:var(--ui-gap-md)}.panel>label,.panel>.detail-grid,.panel>.transport-row,.panel>.module-list{margin-top:0}.panel-copy{margin:0;font-size:.92rem;line-height:1.45}.transport-row{display:flex;gap:var(--ui-gap-sm)}.transport-row>*{flex:1 1 auto}.playback-rate-control{display:grid;gap:var(--ui-gap-xs)}.playback-rate-header{align-items:center;display:flex;justify-content:space-between}.playback-rate-header strong{font-variant-numeric:tabular-nums}.playback-rate-notches{color:var(--ui-muted);display:grid;font-size:.72rem;grid-template-columns:repeat(5,minmax(0,1fr));line-height:1.1;text-align:center}.playback-rate-notches span:first-child{text-align:left}.playback-rate-notches span:last-child{text-align:right}.recording-controls{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-sm)}.camera-presets{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--ui-gap-xs)}.camera-presets button{font-size:var(--ui-control-font-size)}.camera-presets button[data-active=true]{border-color:#8ec5ff6b;background:linear-gradient(180deg,#21476bf5,#0c1b2afa);color:#f3f8fc;box-shadow:inset 0 0 0 1px #8ec5ff1f}.camera-ball-cam{display:grid;gap:var(--ui-gap-xs)}.camera-ball-cam-modes{grid-template-columns:repeat(3,minmax(0,1fr))}.camera-settings-controls{display:grid;gap:var(--ui-gap-sm)}.camera-settings-controls[hidden]{display:none}.camera-setting-label{display:flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-md);font-size:.8rem;color:#9fb3c4}.camera-setting-label strong{color:#e8f0f7;font-variant-numeric:tabular-nums}button,select,input[type=file],input[type=range]{border-radius:var(--ui-radius-md)}button,select,input[type=file]{min-height:var(--ui-control-height);border:1px solid var(--ui-border-subtle);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);background:var(--surface-strong);color:var(--text);font-size:var(--ui-control-font-size);line-height:var(--ui-control-line-height)}button{cursor:pointer}select{appearance:none;padding-right:1.35rem;background-image:linear-gradient(45deg,transparent 50%,var(--muted) 50%),linear-gradient(135deg,var(--muted) 50%,transparent 50%);background-position:calc(100% - .76rem) 50%,calc(100% - .52rem) 50%;background-repeat:no-repeat;background-size:.24rem .24rem}button:hover:not(:disabled),select:hover:not(:disabled){border-color:var(--ui-border-hover)}button:disabled,select:disabled,input:disabled{opacity:.55;cursor:not-allowed}input[type=range]{width:100%;margin-top:var(--ui-gap-xs);accent-color:var(--blue)}.metric-readout{font-size:.88rem;font-weight:700;font-variant-numeric:tabular-nums}.toggle{display:inline-flex;align-items:center;gap:.4rem;color:#bfd0dd}.detail-grid{margin:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.55rem .7rem}.detail-grid dt,.detail-grid dd{margin:0}.detail-grid dt{font-size:.68rem;margin-bottom:.12rem}.detail-grid dd{font-size:.84rem;color:var(--text);overflow-wrap:anywhere}.module-groups{display:grid;gap:var(--ui-gap-md)}.module-summary-group{display:grid;gap:var(--ui-gap-xs)}.module-summary-group h3{margin:0;color:#87afd4;font-size:.64rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase}.module-list{display:flex;flex-wrap:wrap;gap:.5rem}.mechanics-actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem;margin-bottom:.65rem}.mechanics-event-list{display:grid;grid-template-columns:repeat(var(--event-source-columns, 1),minmax(9.5rem,1fr));align-items:stretch}.module-settings{display:grid;gap:.75rem}.module-settings-card{display:grid;gap:.75rem;padding:.85rem .9rem;border-radius:1rem;border:1px solid rgba(255,255,255,.08);background:#ffffff09}.module-settings-subgroup{display:grid;gap:.65rem;padding-top:.15rem;border-top:1px solid rgba(255,255,255,.06)}.module-settings-options{display:grid;gap:.45rem}.module-settings-group-title{margin:0;color:#d7e5ef;font-size:.78rem;font-weight:800}.module-settings-header{display:flex;align-items:start;justify-content:space-between;gap:.8rem}.module-settings-header h3{margin:.1rem 0 0;font-size:.96rem}.module-settings-eyebrow{margin:0;font-size:.66rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase;color:#87afd4}.boost-pickup-filter-panel{display:grid;gap:.65rem}.boost-pickup-filter-summary{display:flex;justify-content:end}.boost-pickup-filter-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.75rem 1rem}.boost-pickup-filter-group{display:grid;align-content:start;gap:.35rem;min-width:0}.boost-pickup-filter-group[hidden]{display:none}.boost-pickup-filter-group-wide{grid-column:1 / -1}.boost-pickup-filter-options{display:flex;flex-wrap:wrap;gap:.35rem .8rem;min-width:0}.boost-pickup-filter-options .toggle{min-width:0}.module-summary-item{appearance:none;display:inline-flex;align-items:center;justify-content:space-between;gap:var(--ui-gap-sm);min-height:var(--ui-control-height);padding:var(--ui-control-padding-block) var(--ui-control-padding-inline);border-radius:var(--ui-radius-pill);border:1px solid var(--ui-border-subtle);background:#ffffff08;color:var(--muted);font:inherit;font-size:var(--ui-control-font-size);line-height:var(--ui-control-line-height);cursor:pointer;transition:border-color .14s ease,background-color .14s ease,color .14s ease}.module-summary-item:hover{border-color:var(--ui-border-hover);color:var(--text)}.module-summary-item strong{font-size:.62rem;letter-spacing:.08em;text-transform:uppercase}.module-summary-item[data-active=true]{border-color:#4b94ff38;background:#4b94ff14;color:#dceafb}@media(max-width:1180px){.sidebar{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:860px){.shell{padding:0}.sidebar{grid-template-columns:1fr}.panel-heading{display:grid}.detail-grid{grid-template-columns:1fr 1fr}.viewport-panel{min-height:100dvh}}@media(max-width:560px){.detail-grid{grid-template-columns:1fr}.transport-row{flex-direction:column}.floating-window,.stats-window{left:.55rem;right:.55rem;width:auto}}@media(max-width:720px){.viewport-panel:has(.floating-window:not([hidden])) .viewport{inset:0 0 52dvh}.floating-window{position:fixed;inset:auto 0 0;width:100%;max-width:none;height:52dvh;max-height:52dvh;overflow:auto;border-width:1px 0 0 0;border-radius:1rem 1rem 0 0;transform:none;z-index:30}.floating-window .floating-window-header{cursor:default}}.missed-event-body{display:flex;flex-direction:column;gap:.5rem;padding:.6rem .7rem;max-height:50vh;font-size:.8rem}.missed-event-controls{display:flex;align-items:center;gap:.4rem}.missed-event-controls select{flex:1 1 auto}.missed-event-list{list-style:none;margin:0;padding:0;overflow-y:auto;display:flex;flex-direction:column;gap:.25rem}.missed-event-list li{display:flex;align-items:center;justify-content:space-between;gap:.4rem;padding:.2rem .3rem;border-radius:.3rem;background:#1c272ee6}.missed-event-status{margin:0;min-height:1rem;color:#9fadb7}.training-pack-shots{list-style:none;margin:.4rem 0 0;padding:0;overflow-y:auto;max-height:12rem;display:flex;flex-direction:column;gap:.25rem;font-size:.8rem}.training-pack-shots li{display:flex;align-items:center;justify-content:space-between;gap:.4rem;padding:.2rem .3rem;border-radius:.3rem;background:#1c272ee6}.training-pack-status{margin:.4rem 0 0;min-height:1rem;font-size:.8rem;color:#9fadb7}:root{color-scheme:dark;font-family:IBM Plex Sans,Avenir Next,sans-serif;font-size:13px;--surface: rgba(10, 16, 20, .86);--surface-strong: rgba(14, 22, 27, .96);--border: rgba(218, 226, 232, .14);--text: #f2f6f8;--muted: #9fadb7;--blue: #58a6ff;--orange: #f39a37;--green: #65d6ad;--ui-border-subtle: rgba(255, 255, 255, .1);--ui-border-hover: rgba(255, 255, 255, .2);--ui-radius-md: .5rem;--ui-radius-lg: .72rem;background:radial-gradient(circle at 8% 0%,rgba(88,166,255,.16),transparent 28rem),radial-gradient(circle at 95% 12%,rgba(243,154,55,.12),transparent 24rem),linear-gradient(180deg,#080d10,#11181d);color:var(--text)}*,*:before,*:after{box-sizing:border-box}html,body,#app{min-height:100%}body{margin:0}button,select,input{font:inherit}.stats-report{width:min(1380px,calc(100vw - 2rem));margin:0 auto;padding:1rem 0 2rem}.stats-report-header{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:1rem;align-items:end;padding:1rem 0 .8rem}.stats-report-title h1{margin:0;font-size:clamp(1.55rem,2.6vw,2.7rem);line-height:1;letter-spacing:0}.stats-report-title p{max-width:62rem;margin:.55rem 0 0;color:var(--muted);font-size:.94rem;line-height:1.45}.stats-report-actions{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:.5rem}.stats-report-link,.stats-report-file-label,.stats-report-tabs button,.stats-report-jump-nav a{display:inline-flex;align-items:center;justify-content:center;min-height:2.15rem;padding:.48rem .72rem;border:1px solid var(--ui-border-subtle);border-radius:var(--ui-radius-md);background:#10181dd1;color:var(--text);text-decoration:none;cursor:pointer}.stats-report-link:hover,.stats-report-file-label:hover,.stats-report-tabs button:hover,.stats-report-jump-nav a:hover{border-color:var(--ui-border-hover);background:#1c272ef2}.stats-report-file-label input{display:none}.stats-report-status{margin:.25rem 0 1rem;color:#c9d6dd}.stats-report-empty{display:grid;min-height:48dvh;place-items:center;border:1px dashed rgba(255,255,255,.2);border-radius:var(--ui-radius-lg);color:var(--muted);text-align:center}.stats-report-tabs{position:sticky;top:0;z-index:4;display:flex;gap:.45rem;overflow:auto;padding:.65rem 0;background:#080d10d1;-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px)}.stats-report-tabs button{flex:0 0 auto;color:#dce8ee}.stats-report-tabs button[data-active=true]{border-color:#65d6ad85;background:#65d6ad24;color:#effff9}.stats-report-page{display:grid;gap:1rem}.stats-report-page-intro{max-width:78rem;padding-top:.35rem}.stats-report-page-intro h2{margin:0;font-size:1.12rem;letter-spacing:0}.stats-report-page-intro p,.stats-report-note,.stats-report-chart-card p{margin:.35rem 0 0;color:var(--muted);line-height:1.45}.stats-report-summary,.stats-report-metric-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:.75rem}.stats-report-summary-card,.stats-report-section,.stats-report-chart-card{border:1px solid var(--border);border-radius:var(--ui-radius-lg);background:var(--surface);box-shadow:0 18px 44px #0003}.stats-report-summary-card{min-width:0;padding:.8rem}.stats-report-summary-card span{display:block;overflow:hidden;color:var(--muted);font-size:.72rem;font-weight:800;letter-spacing:.1em;text-overflow:ellipsis;text-transform:uppercase;white-space:nowrap}.stats-report-summary-card strong{display:block;overflow-wrap:anywhere;margin-top:.35rem;font-size:1.18rem}.stats-report-summary-card small{display:block;margin-top:.28rem;color:var(--muted)}.stats-report-charts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.75rem}.stats-report-chart-card{min-width:0;padding:.8rem}.stats-report-chart-card h3{margin:0 0 .75rem;font-size:.92rem;letter-spacing:0}.stats-report-bar-chart{display:grid;gap:.5rem}.stats-report-bar-row{display:grid;grid-template-columns:minmax(5.5rem,10rem) minmax(8rem,1fr) minmax(3rem,auto);gap:.55rem;align-items:center;min-height:1.35rem}.stats-report-bar-label{overflow:hidden;color:#dce8ee;text-overflow:ellipsis;white-space:nowrap}.stats-report-bar-track{position:relative;height:.72rem;overflow:hidden;border-radius:999px;background:#ffffff14}.stats-report-bar-track:before{content:"";position:absolute;inset:0 auto 0 0;width:var(--bar-width);border-radius:inherit;background:var(--bar-color)}.stats-report-pie-chart{display:grid;grid-template-columns:8.5rem minmax(0,1fr);gap:1rem;align-items:center}.stats-report-pie{width:8.5rem;aspect-ratio:1;border:1px solid rgba(255,255,255,.16);border-radius:50%}.stats-report-pie-legend{display:grid;gap:.45rem}.stats-report-pie-legend div{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.5rem;align-items:baseline}.stats-report-pie-legend span:before,.stats-report-stacked-legend span:before{content:"";display:inline-block;width:.58rem;height:.58rem;margin-right:.3rem;border-radius:50%;background:var(--legend-color)}.stats-report-pie-legend span,.stats-report-stacked-legend span{overflow:hidden;color:#dce8ee;text-overflow:ellipsis;white-space:nowrap}.stats-report-stacked-chart{display:grid;gap:.82rem}.stats-report-stacked-row{display:grid;gap:.38rem}.stats-report-stacked-row>strong{overflow:hidden;color:#e5edf1;font-weight:700;text-overflow:ellipsis;white-space:nowrap}.stats-report-stacked-track{display:flex;height:.82rem;overflow:hidden;border-radius:999px;background:#ffffff14}.stats-report-stacked-track span{flex:0 0 var(--segment-width);min-width:0;background:var(--segment-color)}.stats-report-stacked-legend{display:flex;flex-wrap:wrap;gap:.42rem .72rem;color:var(--muted);font-size:.82rem}.stats-report-goal-list{display:grid;gap:1rem}.stats-report-goal-card{overflow:hidden;border:1px solid var(--border);border-left:3px solid rgba(255,255,255,.16);border-radius:var(--ui-radius-lg);background:var(--surface);box-shadow:0 18px 44px #0003}.stats-report-goal-card[data-team=blue]{border-left-color:var(--blue)}.stats-report-goal-card[data-team=orange]{border-left-color:var(--orange)}.stats-report-goal-card>header{display:flex;justify-content:space-between;gap:1rem;align-items:center;padding:.85rem .9rem;border-bottom:1px solid var(--border);background:#ffffff05}.stats-report-goal-heading{min-width:0}.stats-report-goal-card h2,.stats-report-goal-subsection h3{margin:0;letter-spacing:0}.stats-report-goal-card h2{font-size:1rem}.stats-report-goal-heading span{display:block;margin-top:.14rem;overflow:hidden;color:var(--muted);text-overflow:ellipsis;white-space:nowrap}.stats-report-goal-watch{flex:0 0 auto;padding:.34rem .58rem;border:1px solid rgba(101,214,173,.34);border-radius:var(--ui-radius-md);background:#65d6ad24;color:#d7ffef;cursor:pointer;font-size:.82rem;font-weight:800;text-decoration:none}.stats-report-goal-watch:hover{border-color:#65d6ad85;background:#65d6ad38}.stats-report-goal-tags{display:flex;flex-wrap:wrap;gap:.42rem;padding:.7rem .9rem 0}.stats-report-goal-tag{padding:.2rem .48rem;border:1px solid rgba(88,166,255,.24);border-radius:var(--ui-radius-md);background:#58a6ff24;color:#d8ecff;font-size:.78rem;font-weight:800}.stats-report-goal-tag-empty{border-color:#9fadb733;background:#9fadb71f;color:#c8d2d9}.stats-report-detail-list{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:.7rem .9rem;margin:0;padding:.85rem .9rem}.stats-report-detail-item{min-width:0}.stats-report-detail-list dt{color:var(--muted);font-size:.72rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.stats-report-detail-list dd{overflow-wrap:anywhere;margin:.22rem 0 0;color:#edf5fa;font-weight:700}.stats-report-goal-subsection{display:grid;gap:.5rem;padding:0 .9rem .9rem}.stats-report-goal-subsection h3{color:#dce8ee;font-size:.88rem}.stats-report-jump-nav{display:flex;flex-wrap:wrap;gap:.45rem}.stats-report-grid{display:grid;gap:1rem}.stats-report-section{overflow:hidden}.stats-report-section header{display:flex;justify-content:space-between;gap:1rem;align-items:center;padding:.85rem .9rem;border-bottom:1px solid var(--border);background:#ffffff05}.stats-report-section h2{margin:0;font-size:1rem;letter-spacing:0}.stats-report-section header span{color:var(--muted)}.stats-report-table-wrap{overflow:auto}.stats-report-table{width:100%;border-collapse:collapse;font-variant-numeric:tabular-nums}.stats-report-table th,.stats-report-table td{padding:.48rem .62rem;border-bottom:1px solid rgba(255,255,255,.07);text-align:right;white-space:nowrap}.stats-report-table th:first-child,.stats-report-table td:first-child{position:sticky;left:0;z-index:1;max-width:20rem;background:var(--surface-strong);text-align:left;white-space:normal}.stats-report-table th{color:#b7c6cf;font-size:.72rem;text-transform:uppercase}@media(max-width:960px){.stats-report-header{grid-template-columns:1fr}.stats-report-actions{justify-content:flex-start}.stats-report-summary,.stats-report-metric-grid,.stats-report-charts{grid-template-columns:1fr}.stats-report-detail-list{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:620px){.stats-report{width:min(100vw - 1rem,1380px)}.stats-report-bar-row,.stats-report-pie-chart{grid-template-columns:1fr}.stats-report-pie{width:min(11rem,54vw)}.stats-report-goal-card>header{display:grid}.stats-report-detail-list{grid-template-columns:1fr}}.replay-review-document,#app.replay-review-root,.replay-review-root{height:auto;min-height:100%;overflow:visible}body.replay-review-document{overflow-y:auto}.replay-review-shell{min-height:100dvh}.replay-review-toolbar{position:fixed;top:.75rem;right:.75rem;z-index:1000;display:flex;align-items:center;gap:.4rem;max-width:min(34rem,calc(100vw - 1.5rem));padding:.35rem;border:1px solid rgba(255,255,255,.14);border-radius:.5rem;background:#080d10c7;color:#f2f6f8;-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px);box-shadow:0 14px 34px #00000042}.replay-review-status{overflow:hidden;max-width:14rem;padding:0 .35rem;color:#c9d6dd;font-size:.78rem;text-overflow:ellipsis;white-space:nowrap}.replay-review-toolbar button,.replay-review-file{display:inline-flex;align-items:center;justify-content:center;min-height:2rem;padding:.42rem .62rem;border:1px solid rgba(255,255,255,.12);border-radius:.4rem;background:#10181dd6;color:#f2f6f8;cursor:pointer;font:inherit;text-decoration:none}.replay-review-toolbar button:hover,.replay-review-file:hover{border-color:#ffffff38;background:#1c272ef2}.replay-review-toolbar button[data-active=true]{border-color:#65d6ad8c;background:#65d6ad29;color:#effff9}.replay-review-file input,.replay-review-pane[hidden]{display:none}.replay-review-empty{display:grid;min-height:100dvh;place-items:center;padding:4rem 1rem;color:#9fadb7;text-align:center}@media(max-width:720px){.replay-review-toolbar{left:.5rem;right:.5rem}.replay-review-status{flex:1 1 auto;max-width:none}} diff --git a/crates/rocket-sense-server/static/subtr-actor/stats/assets/index-B06RRC2i.js b/crates/rocket-sense-server/static/subtr-actor/stats/assets/index-N5lUKPt0.js similarity index 74% rename from crates/rocket-sense-server/static/subtr-actor/stats/assets/index-B06RRC2i.js rename to crates/rocket-sense-server/static/subtr-actor/stats/assets/index-N5lUKPt0.js index 5ec87c40..8535b5ec 100644 --- a/crates/rocket-sense-server/static/subtr-actor/stats/assets/index-B06RRC2i.js +++ b/crates/rocket-sense-server/static/subtr-actor/stats/assets/index-N5lUKPt0.js @@ -1,8 +1,8 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const a of s)if(a.type==="childList")for(const r of a.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&i(r)}).observe(document,{childList:!0,subtree:!0});function t(s){const a={};return s.integrity&&(a.integrity=s.integrity),s.referrerPolicy&&(a.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?a.credentials="include":s.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function i(s){if(s.ep)return;s.ep=!0;const a=t(s);fetch(s.href,a)}})();function Bh(n,e){if(n.frames.length===0)return 0;let t=0,i=n.frames.length-1;for(;t<=i;){const s=Math.floor((t+i)/2),a=n.frames[s]?.time??0;if(ae)i=s-1;else return s}return Math.max(0,t-1)}class eS{_listeners=new Map;on(e,t){let i=this._listeners.get(e);return i||(i=new Set,this._listeners.set(e,i)),i.add(t),this}once(e,t){const i=(...s)=>{this.off(e,i),t(...s)};return this.on(e,i)}off(e,t){const i=this._listeners.get(e);return i?(t?i.delete(t):i.clear(),i.size===0&&this._listeners.delete(e),this):this}removeListener(e,t){return this.off(e,t)}removeAllListeners(e){return e?this._listeners.delete(e):this._listeners.clear(),this}emit(e,...t){const i=this._listeners.get(e);if(!i||i.size===0)return!1;for(const s of[...i])s(...t);return!0}}function Bf(n){return n?{x:n.x,y:n.z,z:n.y}:null}function CC(n){return n?{x:n.x,y:n.z,z:n.y,w:-n.w}:null}function AC(n){return n*100/255}const Ny={Octane:{length:118.0074,width:84.19941,height:36.15907,offsetX:13.87566,offsetZ:20.75499},Dominus:{length:127.9268,width:83.27995,height:31.3,offsetX:9,offsetZ:15.75},Plank:{length:128.8198,width:84.67036,height:29.3944,offsetX:9.00857,offsetZ:12.0942},Breakout:{length:131.4924,width:80.521,height:30.3,offsetX:12.5,offsetZ:11.75},Hybrid:{length:127.0192,width:82.18787,height:34.15907,offsetX:13.87566,offsetZ:20.75499},Merc:{length:120.72,width:76.71,height:41.66,offsetX:11.37566,offsetZ:21.504988}},RC={21:{name:"Backfire",hitbox:"Octane"},22:{name:"Breakout",hitbox:"Breakout"},23:{name:"Octane",hitbox:"Octane"},24:{name:"Paladin",hitbox:"Plank"},25:{name:"Road Hog",hitbox:"Octane"},26:{name:"Gizmo",hitbox:"Octane"},28:{name:"X-Devil",hitbox:"Hybrid"},29:{name:"Hotshot",hitbox:"Dominus"},30:{name:"Merc",hitbox:"Merc"},31:{name:"Venom",hitbox:"Hybrid"},402:{name:"Takumi",hitbox:"Octane"},403:{name:"Dominus",hitbox:"Dominus"},404:{name:"Scarab",hitbox:"Octane"},523:{name:"Zippy",hitbox:"Octane"},597:{name:"DeLorean Time Machine",hitbox:"Dominus"},600:{name:"Ripper",hitbox:"Dominus"},607:{name:"Grog",hitbox:"Octane"},1018:{name:"Dominus GT",hitbox:"Dominus"},1159:{name:"X-Devil Mk2",hitbox:"Hybrid"},1171:{name:"Masamune",hitbox:"Dominus"},1172:{name:"Marauder",hitbox:"Octane"},1286:{name:"Aftershock",hitbox:"Dominus"},1295:{name:"Takumi RX-T",hitbox:"Octane"},1300:{name:"Road Hog XL",hitbox:"Octane"},1317:{name:"Esper",hitbox:"Hybrid"},1416:{name:"Breakout Type-S",hitbox:"Breakout"},1475:{name:"Proteus",hitbox:"Octane"},1478:{name:"Triton",hitbox:"Octane"},1533:{name:"Vulcan",hitbox:"Octane"},1568:{name:"Octane ZSR",hitbox:"Octane"},1603:{name:"Twin Mill III",hitbox:"Plank"},1623:{name:"Bone Shaker",hitbox:"Octane"},1624:{name:"Endo",hitbox:"Hybrid"},1675:{name:"Ice Charger",hitbox:"Dominus"},1689:{name:"Nemesis",hitbox:"Dominus"},1691:{name:"Mantis",hitbox:"Plank"},1856:{name:"Jager 619",hitbox:"Hybrid"},1883:{name:"Imperator DT5",hitbox:"Dominus"},1894:{name:"Samurai",hitbox:"Breakout"},1919:{name:"Centio",hitbox:"Plank"},1932:{name:"Animus GP",hitbox:"Breakout"},2070:{name:"Werewolf",hitbox:"Dominus"},2268:{name:"Fast & Furious Dodge Charger",hitbox:"Dominus"},2269:{name:"Fast & Furious Nissan Skyline",hitbox:"Hybrid"},2665:{name:"The Dark Knight's Tumbler",hitbox:"Octane"},2666:{name:"Batmobile (1989)",hitbox:"Dominus"},2853:{name:"Twinzer",hitbox:"Octane"},2919:{name:"Jurassic Jeep Wrangler",hitbox:"Octane"},2949:{name:"Fast 4WD",hitbox:"Octane"},2950:{name:"MR11",hitbox:"Dominus"},2951:{name:"Gazella GT",hitbox:"Dominus"},3031:{name:"Cyclone",hitbox:"Breakout"},3155:{name:"Maverick",hitbox:"Dominus"},3156:{name:"Maverick G1",hitbox:"Dominus"},3157:{name:"Maverick GXT",hitbox:"Dominus"},3265:{name:"McLaren 570S",hitbox:"Dominus"},3311:{name:"Komodo",hitbox:"Breakout"},3426:{name:"Diestro",hitbox:"Dominus"},3451:{name:"Nimbus",hitbox:"Hybrid"},3582:{name:"Insidio",hitbox:"Hybrid"},3594:{name:"Artemis G1",hitbox:"Plank"},3614:{name:"Artemis",hitbox:"Plank"},3622:{name:"Artemis GXT",hitbox:"Plank"},3702:{name:"Tygris",hitbox:"Hybrid"},3875:{name:"Guardian GXT",hitbox:"Dominus"},3879:{name:"Guardian",hitbox:"Dominus"},3880:{name:"Guardian G1",hitbox:"Dominus"},4014:{name:"K.I.T.T.",hitbox:"Dominus"},4155:{name:"Ecto-1",hitbox:"Dominus"},4268:{name:"Sentinel",hitbox:"Plank"},4284:{name:"Fennec",hitbox:"Octane"},4318:{name:"Mudcat",hitbox:"Octane"},4319:{name:"Mudcat G1",hitbox:"Octane"},4320:{name:"Mudcat GXT",hitbox:"Octane"},4367:{name:"Chikara GXT",hitbox:"Dominus"},4472:{name:"Chikara",hitbox:"Dominus"},4473:{name:"Chikara G1",hitbox:"Dominus"},4745:{name:"Ronin GXT",hitbox:"Dominus"},4770:{name:"Dominus",hitbox:"Dominus"},4780:{name:"Battle Bus",hitbox:"Merc"},4781:{name:"Peregrine TT",hitbox:"Dominus"},4782:{name:"Psyclops",hitbox:"Body_Tritip_Handling"},4861:{name:"Ronin",hitbox:"Dominus"},4864:{name:"Ronin G1",hitbox:"Dominus"},4906:{name:"Harbinger",hitbox:"Octane"},5020:{name:"Outlaw",hitbox:"Octane"},5039:{name:"Harbinger GXT",hitbox:"Octane"},5188:{name:"Scarab",hitbox:"Octane"},5265:{name:"Formula 1 2021",hitbox:"Plank"},5361:{name:"Dingo",hitbox:"Octane"},5470:{name:"R3MX",hitbox:"Hybrid"},5488:{name:"R3MX GXT",hitbox:"Hybrid"},5547:{name:"007's Aston Martin DB5",hitbox:"Octane"},5709:{name:"NASCAR Ford Mustang",hitbox:"Dominus"},5713:{name:"Ford F-150 RLE",hitbox:"Octane"},5773:{name:"NASCAR Toyota Camry",hitbox:"Dominus"},5823:{name:"NASCAR Chevrolet Camaro",hitbox:"Dominus"},5837:{name:"Outlaw GXT",hitbox:"Octane"},5858:{name:"Tyranno",hitbox:"Dominus"},5879:{name:"Fast & Furious Pontiac Fiero",hitbox:"Hybrid"},5951:{name:"Jackal",hitbox:"Octane"},5964:{name:"Lamborghini Huracan STO",hitbox:"Dominus"},5979:{name:"Tyranno GXT",hitbox:"Dominus"},6122:{name:"Masamune",hitbox:"Dominus"},6243:{name:"Nexus",hitbox:"Breakout"},6244:{name:"BMW M240i",hitbox:"Dominus"},6247:{name:"McLaren 765LT",hitbox:"Dominus"},6260:{name:"007's Aston Martin Valhalla",hitbox:"Dominus"},6489:{name:"Nexus SC",hitbox:"Breakout"},6836:{name:"Ford Mustang Shelby GT350R RLE",hitbox:"Dominus"},6939:{name:"Ford Mustang Mach-E RLE",hitbox:"Octane"},7012:{name:"Tesla Cybertruck",hitbox:"Hybrid"},7052:{name:"Formula 1 2022",hitbox:"Plank"},7211:{name:"Mamba",hitbox:"Dominus"},7336:{name:"Nomad",hitbox:"Merc"},7337:{name:"NASCAR Next Gen Chevrolet Camaro",hitbox:"Dominus"},7338:{name:"NASCAR Next Gen Ford Mustang",hitbox:"Dominus"},7341:{name:"NASCAR Next Gen Toyota Camry",hitbox:"Dominus"},7343:{name:"007's Aston Martin DBS",hitbox:"Dominus"},7415:{name:"Batmobile (2022)",hitbox:"Dominus"},7477:{name:"Nomad GXT",hitbox:"Merc"},7512:{name:"Lamborghini Countach LPI 800-4",hitbox:"Dominus"},7532:{name:"Maestro",hitbox:"Dominus"},7593:{name:"Nissan Z Performance",hitbox:"Dominus"},7651:{name:"Redline",hitbox:"Breakout"},7696:{name:"Whiplash",hitbox:"Breakout"},7772:{name:"Ferrari 296 GTB",hitbox:"Dominus"},7815:{name:"Ford Bronco Raptor RLE",hitbox:"Merc"},7890:{name:"Fuse",hitbox:"Breakout"},7901:{name:"Fast & Furious Mazda RX-7",hitbox:"Breakout"},7947:{name:"Honda Civic Type R",hitbox:"Octane"},7948:{name:"Honda Civic Type R-LE",hitbox:"Octane"},7979:{name:"Stampede",hitbox:"Merc"},8006:{name:"Mako",hitbox:"Breakout"},8360:{name:"Emperor",hitbox:"Breakout"},8361:{name:"Emperor II",hitbox:"Breakout"},8383:{name:"Xentari",hitbox:"Octane"},8454:{name:"Admiral",hitbox:"Dominus"},8524:{name:"Bugatti Centodieci",hitbox:"Plank"},8565:{name:"Emperor II: Frozen",hitbox:"Breakout"},8566:{name:"Emperor II: Scorched",hitbox:"Breakout"},8669:{name:"Ace",hitbox:"Breakout"},8806:{name:"Volkswagen Golf GTI",hitbox:"Octane"},8807:{name:"Volkswagen Golf GTI RLE",hitbox:"Octane"},9053:{name:"Fast & Furious Dodge Charger SRT Hellcat",hitbox:"Dominus"},9084:{name:"Nissan Silvia",hitbox:"Hybrid"},9085:{name:"Nissan Silvia RLE",hitbox:"Hybrid"},9088:{name:"Porsche 911 Turbo",hitbox:"Dominus"},9089:{name:"Porsche 911 Turbo RLE",hitbox:"Dominus"},9140:{name:"Bumblebee",hitbox:"Dominus"},9357:{name:"Diesel",hitbox:"Breakout"},9388:{name:"Lightning McQueen",hitbox:"Dominus"},9427:{name:"Primo",hitbox:"Hybrid"},9894:{name:"Scorpion",hitbox:"Dominus"},10044:{name:"Beskar",hitbox:"Hybrid"},10094:{name:"Ford Mustang GTD",hitbox:"Dominus"},10440:{name:"Nissan Fairlady Z",hitbox:"Dominus"},10441:{name:"Nissan Fairlady Z RLE",hitbox:"Dominus"},10689:{name:"Behemoth",hitbox:"Merc"},10694:{name:"Lockjaw",hitbox:"Dominus"},10697:{name:"The Incredibile",hitbox:"Breakout"},10698:{name:"1966 Cadillac DeVille",hitbox:"Breakout"},10805:{name:"Nissan Skyline GT-R (R32)",hitbox:"Hybrid"},10817:{name:"Quadra Turbo-R",hitbox:"Breakout"},10822:{name:"McLaren Senna",hitbox:"Breakout"},10896:{name:"BMW 1 Series",hitbox:"Octane"},10897:{name:"BMW 1 Series RLE",hitbox:"Octane"},10900:{name:"Shokunin",hitbox:"Octane"},10901:{name:"Shokunin GXT",hitbox:"Octane"},11016:{name:"Porsche 911 GT3 RS",hitbox:"Dominus"},11038:{name:"Revolver",hitbox:"Breakout"},11095:{name:"Dodge Charger Daytona Scat Pack",hitbox:"Dominus"},11098:{name:"Turtle Van",hitbox:"Merc"},11138:{name:"Void Burn",hitbox:"Hybrid"},11141:{name:"Lamborghini Urus SE",hitbox:"Hybrid"},11314:{name:"Jeep Wrangler Rubicon",hitbox:"Merc"},11315:{name:"Ford Mustang Shelby GT500",hitbox:"Dominus"},11336:{name:"Dominus: Neon",hitbox:"Dominus"},11379:{name:"Ram 1500 RHO",hitbox:"Hybrid"},11394:{name:"Azura",hitbox:"Breakout"},11505:{name:"Breakout X",hitbox:"Breakout"},11534:{name:"BMW M3 (E30)",hitbox:"Dominus"},11603:{name:"Fennec ZR-F",hitbox:"Octane"},11677:{name:"Chevrolet Corvette ZR1",hitbox:"Breakout"},11736:{name:"Recoil AV",hitbox:"Merc"},11800:{name:"Megastar",hitbox:"Breakout"},11905:{name:"The Mystery Machine",hitbox:"Merc"},11932:{name:"Hearse",hitbox:"Hybrid"},11933:{name:"Porsche 918 Spyder",hitbox:"Breakout"},11941:{name:"Mercedes-AMG GT 63 S",hitbox:"Dominus"},11949:{name:"Pontiac Firebird",hitbox:"Breakout"},11950:{name:"Chevrolet Astro",hitbox:"Merc"},12142:{name:"Homer's Car",hitbox:"Dominus"},12173:{name:"Ferrari F40",hitbox:"Breakout"}},PC=RC;function tS(n){const e=PC[String(n)];return e?{name:e.name,hitboxType:e.hitbox}:null}function IC(n){if(!n)return null;const e={fov:n.fov,height:n.height,angle:n.angle,distance:n.distance,stiffness:n.stiffness,swivelSpeed:n.swivel_speed};return n.transition_speed!=null&&(e.transitionSpeed=n.transition_speed),e}const LC=2200,kC=!0,DC=!1,OC=.15,FC=10,NC=.1,UC=10,BC=.1,zC=.15,HC=10;function el(n,e){if(n.length===0)return null;let t=0,i=n.length-1;if(e<=n[0].time)return n[0];if(e>=n[i].time)return n[i];for(;t>1;n[s].time<=e?t=s:i=s-1}return n[t]}class VC{position={x:0,y:0,z:0};rotation={x:0,y:0,z:0,w:1};velocity={x:0,y:0,z:0};angularVelocity={x:0,y:0,z:0};sleeping=!1;visible=!0}class GC{constructor(e,t,i){this.isBig=e,this.position=t,this.events=i}isAvailable=!0}class $C extends eS{constructor(e,t,i,s,a,r=null){super(),this.id=e,this.name=t,this.team=i,this.carName=s,this.hitboxType=a,this.cameraSettings=r}position={x:0,y:0,z:0};rotation={x:0,y:0,z:0,w:1};velocity={x:0,y:0,z:0};angularVelocity={x:0,y:0,z:0};sleeping=!1;steer=0;boost=0;isBoosting=!1;isSupersonic=!1;isKickoffReset=!1;isVisible=!0;isBallCam=!0}class nS extends eS{constructor(e,t={}){super(),this.raw=e,this.options=t,this._compile()}duration=0;playerList=[];frameTimes=[];rawStartTime=0;ball=new VC;players=new Map;boostPads=new Map;_currentTime=0;_ballTimeline=[];_playerTimelines={};_ballFlags=[];_playerFlags={};_playerCameraEvents={};_teams={};_timelineCompaction=null;_compile(){const e=this.raw.frame_data,t=this.raw.meta,i=e.metadata_frames,s=i[0]?.time??0;this.rawStartTime=s;const a=l=>Math.max(0,l-s);this.duration=i.length?a(i[i.length-1].time):0,this.frameTimes=i.map(l=>a(l.time));const r=new Map;t.team_zero.forEach(l=>r.set(this._idKey(l.remote_id),{info:l,team:0})),t.team_one.forEach(l=>r.set(this._idKey(l.remote_id),{info:l,team:1})),e.ball_data.frames.forEach((l,c)=>{if(l==="Empty"||!("Data"in l))return;const u=this._rbToKeyframe(l.Data.rigid_body,a(i[c]?.time??s),c);u&&this._ballTimeline.push(u)}),e.players.forEach(([l,c])=>{const u=this._idKey(l),d=r.get(u);let h=d?.info.name??null,f=d?.team??0;if(!h){for(const S of c.frames)if(S!=="Empty"&&"Data"in S&&S.Data.player_name){h=S.Data.player_name,S.Data.is_team_0!=null&&(f=S.Data.is_team_0?0:1);break}}h||(h=`Player_${u}`);const p=d?.info,g=p?.car_body_id!=null?tS(p.car_body_id):null,_=p?.car_body_name??g?.name??"Octane",m=p?.car_hitbox_family??g?.hitboxType??"Octane",v=[],y=[];c.frames.forEach((S,x)=>{const M=a(i[x]?.time??s);if(S==="Empty"||!("Data"in S))return;const C=this._rbToKeyframe(S.Data.rigid_body,M,x);C&&v.push(C);const w=S.Data.input?.steer;y.push({time:M,boost:AC(S.Data.boost_amount??0),isBoosting:!!S.Data.boost_active,present:!0,steer:w==null?0:Math.max(-1,Math.min(1,(w-128)/128))})});const b=IC(p?.camera_settings);this._playerTimelines[h]=v,this._playerFlags[h]=y,this._teams[h]=f,this.playerList.push({id:u,name:h,team:f,carName:_,hitboxType:m,cameraSettings:b}),this.players.set(h,new $C(u,h,f,_,m,b))});const o=new Map;this.playerList.forEach(l=>o.set(l.id,l.name));for(const[l,c]of this.raw.player_camera_events??[]){const u=o.get(this._idKey(l));u&&(this._playerCameraEvents[u]=c.map(d=>({time:a(i[d.frame]?.time??s),ballCam:d.ball_cam_active})))}this._preprocessMotionTimelines(),this._compileBoostPads(),this.seek(0)}_timelineProcessingOptions(){return{motionSmoothing:this.options.motionSmoothing??kC,smoothingBlendFactor:this.options.smoothingBlendFactor??OC,smoothingAnchorInterval:this.options.smoothingAnchorInterval??FC,timelineCompaction:this.options.timelineCompaction??DC,disableFrameFiltering:this.options.disableFrameFiltering??!1}}_preprocessMotionTimelines(){const e=this._timelineProcessingOptions();e.motionSmoothing&&this._applyVelocityBasedPositionCorrection(e),e.timelineCompaction&&this._applyTimelineCompaction(),e.disableFrameFiltering||this._filterInconsistentFrames()}_applyTimelineCompaction(){const e=this._buildTimelineCompaction();!e||e.gaps.length===0&&e.prematchEndTime===null||(this._timelineCompaction=e,this._ballTimeline=this._compactTimeline(this._ballTimeline,e),Object.entries(this._playerTimelines).forEach(([t,i])=>{this._playerTimelines[t]=this._compactTimeline(i,e)}),Object.entries(this._playerFlags).forEach(([t,i])=>{this._playerFlags[t]=this._compactTimeline(i,e)}),this.frameTimes=this.frameTimes.map(t=>this._compactTime(t,e)),this.duration=e.compactedDuration)}_buildTimelineCompaction(){if(this.frameTimes.length===0)return null;const e=this._detectPostGoalTimeGaps(),t=this._detectFirstKickoffGoTime(),i=t==null?null:tl(t,e),a=e.reduce((r,o)=>r+o.duration,0)+(i??0);return a<=0?null:{gaps:e,prematchEndTime:i,removedDuration:a,compactedDuration:Math.max(0,this.duration-a)}}_detectPostGoalTimeGaps(){const e=[];for(const t of this.raw.goal_events??[]){const i=t.frame;if(!Number.isInteger(i)||i<0||i>=this.frameTimes.length)continue;const s=this.frameTimes[i];for(let a=i+1;a10)break;const l=o-r;if(l>.3){e.push({beforeFrame:a-1,afterFrame:a,beforeTime:r,afterTime:o,duration:l});break}}}return e}_detectFirstKickoffGoTime(){const e=this.raw.frame_data.metadata_frames;let t=!1;for(let s=0;s0&&(t=!0),t&&a===0)return this.frameTimes[s]??null}const i=e.findIndex(s=>s.replicated_game_state_name===54);return i===-1?null:this.frameTimes[i]??null}_compactTimeline(e,t){const i=this._remapReplayGaps(e,t.gaps);return t.prematchEndTime===null?i:this._remapPrematch(i,t.prematchEndTime)}_remapReplayGaps(e,t){if(t.length===0)return e;const i=[];t.forEach((a,r)=>{const o=e.find(l=>l.time>=a.afterTime);o&&i.push({...o,time:tl(a.afterTime,t.slice(0,r+1))})});const s=e.filter(a=>!zy(a.time,t)).map(a=>({...a,time:tl(a.time,t)}));for(const a of i){if(s.some(o=>Math.abs(o.time-a.time)<.001))continue;let r=s.findIndex(o=>o.time>a.time);r===-1&&(r=s.length),s.splice(r,0,a)}return s}_remapPrematch(e,t){let i=null;for(const a of e)if(a.timea.time>=t).map(a=>({...a,time:a.time-t}));return i&&(s.length===0||s[0].time>.001)&&s.unshift({...i,time:0}),s}_compactTime(e,t){const i=tl(e,t.gaps);return t.prematchEndTime===null?i:Math.max(0,i-t.prematchEndTime)}_applyVelocityBasedPositionCorrection(e){const t=i=>{if(i.length<3)return;let s=0;for(;s=i.length-1)return;let a={...i[s].position};for(let r=s+1;rNC){a={...l.position};continue}if(By(a,l.position)>UC){a={...l.position};continue}const u={x:(o.velocity.x+l.velocity.x)/2,y:(o.velocity.y+l.velocity.y)/2,z:(o.velocity.z+l.velocity.z)/2},d={x:a.x+u.x*c,y:a.y+u.y*c,z:a.z+u.z*c},h=(r-s)%e.smoothingAnchorInterval===0?.5:e.smoothingBlendFactor;a={x:d.x*(1-h)+l.position.x*h,y:d.y*(1-h)+l.position.y*h,z:d.z*(1-h)+l.position.z*h},l.position={...a}}};t(this._ballTimeline),Object.values(this._playerTimelines).forEach(t)}_filterInconsistentFrames(){this._ballTimeline=this._filterInconsistentTimeline(this._ballTimeline),Object.entries(this._playerTimelines).forEach(([e,t])=>{this._playerTimelines[e]=this._filterInconsistentTimeline(t)})}_filterInconsistentTimeline(e){if(e.length<2)return e;const t=[e[0]];let i=0;for(let s=1;s.001){const u=o*c,d=By(r.position,a.position),h=Math.abs(d-u)/u;if(Number.isFinite(h)&&h>zC)continue}}t.push(a),i=s}return t}_compileBoostPads(){const e=new Map;(this.raw.boost_pad_events??[]).forEach(t=>{const i=t.kind==="Available"?!0:t.kind&&typeof t.kind=="object"&&"PickedUp"in t.kind?!1:null;if(i===null)return;const s=Math.max(0,t.time-this.rawStartTime);if(this._timelineCompaction&&this._isRemovedByTimelineCompaction(s))return;const a=this._timelineCompaction?this._compactTime(s,this._timelineCompaction):s,r=e.get(t.pad_id);r?r.push({time:a,available:i}):e.set(t.pad_id,[{time:a,available:i}])}),(this.raw.boost_pads??[]).forEach(t=>{const i=(t.pad_id?e.get(t.pad_id):void 0)??[];i.sort((s,a)=>s.time-a.time),this.boostPads.set(t.index,new GC(t.size==="Big",t.position,i))})}_rbToKeyframe(e,t,i){const s=Bf(e.location);return s?{time:t,frame:i,position:s,rotation:CC(e.rotation),velocity:Bf(e.linear_velocity)??{x:0,y:0,z:0},angularVelocity:Bf(e.angular_velocity),sleeping:!!e.sleeping}:null}_isRemovedByTimelineCompaction(e){const t=this._timelineCompaction;if(!t)return!1;if(zy(e,t.gaps))return!0;const i=tl(e,t.gaps);return t.prematchEndTime!==null&&i=LC}const r=el(this._playerFlags[i]??[],e);r&&(s.boost=r.boost,s.isBoosting=r.isBoosting,s.steer=r.steer);const o=el(this._playerCameraEvents[i]??[],e);o&&o.ballCam!=null&&(s.isBallCam=o.ballCam);const l=this._playerTimelines[i]??[];s.isVisible=l.length>0&&e>=l[0].time-.001&&e<=l[l.length-1].time+1}for(const i of this.boostPads.values()){if(i.events.length===0)continue;const s=el(i.events,e);i.isAvailable=s&&s.time<=e?s.available:!0}}frameIndexAt(e){const t=this.frameTimes;if(t.length===0||e<=t[0])return 0;let i=0,s=t.length-1;if(e>=t[s])return s;for(;i>1;t[a]<=e?i=a:s=a-1}return i}getBall(){return this.ball}getPlayer(e){return this.players.get(e)}getPlayerById(e){for(const t of this.players.values())if(t.id===e)return t}getAllPlayers(){return Array.from(this.players.values())}getPlayerTeams(){return{...this._teams}}getGameTimeMap(){return[]}getCountdownEvents(){return[]}getPlayerStatsTimelines(){return{}}getGameEventTimeline(){return[]}getAdvancedStats(){return null}getEvents(){return[]}getEventsInRange(){return[]}getTextOverlaysAt(){return[]}getGamePhaseAt(){return null}}function Uy(n){return Math.sqrt(n.x*n.x+n.y*n.y+n.z*n.z)}function By(n,e){const t=e.x-n.x,i=e.y-n.y,s=e.z-n.z;return Math.sqrt(t*t+i*i+s*s)}function tl(n,e){let t=0;for(const i of e){if(n=i.afterTime){t+=i.duration;continue}return i.beforeTime-t}return n-t}function zy(n,e){return e.some(t=>n>t.beforeTime&&n>8&255]+Cn[n>>16&255]+Cn[n>>24&255]+"-"+Cn[e&255]+Cn[e>>8&255]+"-"+Cn[e>>16&15|64]+Cn[e>>24&255]+"-"+Cn[t&63|128]+Cn[t>>8&255]+"-"+Cn[t>>16&255]+Cn[t>>24&255]+Cn[i&255]+Cn[i>>8&255]+Cn[i>>16&255]+Cn[i>>24&255]).toLowerCase()}function Je(n,e,t){return Math.max(e,Math.min(t,n))}function Sg(n,e){return(n%e+e)%e}function EA(n,e,t,i,s){return i+(n-e)*(s-i)/(t-e)}function CA(n,e,t){return n!==e?(t-n)/(e-n):0}function Wl(n,e,t){return(1-t)*n+t*e}function AA(n,e,t,i){return Wl(n,e,1-Math.exp(-t*i))}function RA(n,e=1){return e-Math.abs(Sg(n,e*2)-e)}function PA(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*(3-2*n))}function IA(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*n*(n*(n*6-15)+10))}function LA(n,e){return n+Math.floor(Math.random()*(e-n+1))}function kA(n,e){return n+Math.random()*(e-n)}function DA(n){return n*(.5-Math.random())}function OA(n){n!==void 0&&(Hy=n);let e=Hy+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function FA(n){return n*dr}function NA(n){return n*Oo}function UA(n){return(n&n-1)===0&&n!==0}function BA(n){return Math.pow(2,Math.ceil(Math.log(n)/Math.LN2))}function zA(n){return Math.pow(2,Math.floor(Math.log(n)/Math.LN2))}function HA(n,e,t,i,s){const a=Math.cos,r=Math.sin,o=a(t/2),l=r(t/2),c=a((e+i)/2),u=r((e+i)/2),d=a((e-i)/2),h=r((e-i)/2),f=a((i-e)/2),p=r((i-e)/2);switch(s){case"XYX":n.set(o*u,l*d,l*h,o*c);break;case"YZY":n.set(l*h,o*u,l*d,o*c);break;case"ZXZ":n.set(l*d,l*h,o*u,o*c);break;case"XZX":n.set(o*u,l*p,l*f,o*c);break;case"YXY":n.set(l*f,o*u,l*p,o*c);break;case"ZYZ":n.set(l*p,l*f,o*u,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+s)}}function $n(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return n/4294967295;case Uint16Array:return n/65535;case Uint8Array:return n/255;case Int32Array:return Math.max(n/2147483647,-1);case Int16Array:return Math.max(n/32767,-1);case Int8Array:return Math.max(n/127,-1);default:throw new Error("Invalid component type.")}}function dt(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return Math.round(n*4294967295);case Uint16Array:return Math.round(n*65535);case Uint8Array:return Math.round(n*255);case Int32Array:return Math.round(n*2147483647);case Int16Array:return Math.round(n*32767);case Int8Array:return Math.round(n*127);default:throw new Error("Invalid component type.")}}const bt={DEG2RAD:dr,RAD2DEG:Oo,generateUUID:bi,clamp:Je,euclideanModulo:Sg,mapLinear:EA,inverseLerp:CA,lerp:Wl,damp:AA,pingpong:RA,smoothstep:PA,smootherstep:IA,randInt:LA,randFloat:kA,randFloatSpread:DA,seededRandom:OA,degToRad:FA,radToDeg:NA,isPowerOfTwo:UA,ceilPowerOfTwo:BA,floorPowerOfTwo:zA,setQuaternionFromProperEuler:HA,normalize:dt,denormalize:$n};class ne{constructor(e=0,t=0){ne.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,i=this.y,s=e.elements;return this.x=s[0]*t+s[3]*i+s[6],this.y=s[1]*t+s[4]*i+s[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Je(this.x,e.x,t.x),this.y=Je(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Je(this.x,e,t),this.y=Je(this.y,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Je(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Je(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),s=Math.sin(t),a=this.x-e.x,r=this.y-e.y;return this.x=a*i-r*s+e.x,this.y=a*s+r*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class ht{constructor(e=0,t=0,i=0,s=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=s}static slerpFlat(e,t,i,s,a,r,o){let l=i[s+0],c=i[s+1],u=i[s+2],d=i[s+3];const h=a[r+0],f=a[r+1],p=a[r+2],g=a[r+3];if(o===0){e[t+0]=l,e[t+1]=c,e[t+2]=u,e[t+3]=d;return}if(o===1){e[t+0]=h,e[t+1]=f,e[t+2]=p,e[t+3]=g;return}if(d!==g||l!==h||c!==f||u!==p){let _=1-o;const m=l*h+c*f+u*p+d*g,v=m>=0?1:-1,y=1-m*m;if(y>Number.EPSILON){const S=Math.sqrt(y),x=Math.atan2(S,m*v);_=Math.sin(_*x)/S,o=Math.sin(o*x)/S}const b=o*v;if(l=l*_+h*b,c=c*_+f*b,u=u*_+p*b,d=d*_+g*b,_===1-o){const S=1/Math.sqrt(l*l+c*c+u*u+d*d);l*=S,c*=S,u*=S,d*=S}}e[t]=l,e[t+1]=c,e[t+2]=u,e[t+3]=d}static multiplyQuaternionsFlat(e,t,i,s,a,r){const o=i[s],l=i[s+1],c=i[s+2],u=i[s+3],d=a[r],h=a[r+1],f=a[r+2],p=a[r+3];return e[t]=o*p+u*d+l*f-c*h,e[t+1]=l*p+u*h+c*d-o*f,e[t+2]=c*p+u*f+o*h-l*d,e[t+3]=u*p-o*d-l*h-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,i,s){return this._x=e,this._y=t,this._z=i,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const i=e._x,s=e._y,a=e._z,r=e._order,o=Math.cos,l=Math.sin,c=o(i/2),u=o(s/2),d=o(a/2),h=l(i/2),f=l(s/2),p=l(a/2);switch(r){case"XYZ":this._x=h*u*d+c*f*p,this._y=c*f*d-h*u*p,this._z=c*u*p+h*f*d,this._w=c*u*d-h*f*p;break;case"YXZ":this._x=h*u*d+c*f*p,this._y=c*f*d-h*u*p,this._z=c*u*p-h*f*d,this._w=c*u*d+h*f*p;break;case"ZXY":this._x=h*u*d-c*f*p,this._y=c*f*d+h*u*p,this._z=c*u*p+h*f*d,this._w=c*u*d-h*f*p;break;case"ZYX":this._x=h*u*d-c*f*p,this._y=c*f*d+h*u*p,this._z=c*u*p-h*f*d,this._w=c*u*d+h*f*p;break;case"YZX":this._x=h*u*d+c*f*p,this._y=c*f*d+h*u*p,this._z=c*u*p-h*f*d,this._w=c*u*d-h*f*p;break;case"XZY":this._x=h*u*d-c*f*p,this._y=c*f*d-h*u*p,this._z=c*u*p+h*f*d,this._w=c*u*d+h*f*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+r)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const i=t/2,s=Math.sin(i);return this._x=e.x*s,this._y=e.y*s,this._z=e.z*s,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],s=t[4],a=t[8],r=t[1],o=t[5],l=t[9],c=t[2],u=t[6],d=t[10],h=i+o+d;if(h>0){const f=.5/Math.sqrt(h+1);this._w=.25/f,this._x=(u-l)*f,this._y=(a-c)*f,this._z=(r-s)*f}else if(i>o&&i>d){const f=2*Math.sqrt(1+i-o-d);this._w=(u-l)/f,this._x=.25*f,this._y=(s+r)/f,this._z=(a+c)/f}else if(o>d){const f=2*Math.sqrt(1+o-i-d);this._w=(a-c)/f,this._x=(s+r)/f,this._y=.25*f,this._z=(l+u)/f}else{const f=2*Math.sqrt(1+d-i-o);this._w=(r-s)/f,this._x=(a+c)/f,this._y=(l+u)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<1e-8?(i=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Je(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(i===0)return this;const s=Math.min(1,t/i);return this.slerp(e,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const i=e._x,s=e._y,a=e._z,r=e._w,o=t._x,l=t._y,c=t._z,u=t._w;return this._x=i*u+r*o+s*c-a*l,this._y=s*u+r*l+a*o-i*c,this._z=a*u+r*c+i*l-s*o,this._w=r*u-i*o-s*l-a*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const i=this._x,s=this._y,a=this._z,r=this._w;let o=r*e._w+i*e._x+s*e._y+a*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=r,this._x=i,this._y=s,this._z=a,this;const l=1-o*o;if(l<=Number.EPSILON){const f=1-t;return this._w=f*r+t*this._w,this._x=f*i+t*this._x,this._y=f*s+t*this._y,this._z=f*a+t*this._z,this.normalize(),this}const c=Math.sqrt(l),u=Math.atan2(c,o),d=Math.sin((1-t)*u)/c,h=Math.sin(t*u)/c;return this._w=r*d+this._w*h,this._x=i*d+this._x*h,this._y=s*d+this._y*h,this._z=a*d+this._z*h,this._onChangeCallback(),this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),s=Math.sqrt(1-i),a=Math.sqrt(i);return this.set(s*Math.sin(e),s*Math.cos(e),a*Math.sin(t),a*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class T{constructor(e=0,t=0,i=0){T.prototype.isVector3=!0,this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Vy.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Vy.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,s=this.z,a=e.elements;return this.x=a[0]*t+a[3]*i+a[6]*s,this.y=a[1]*t+a[4]*i+a[7]*s,this.z=a[2]*t+a[5]*i+a[8]*s,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,s=this.z,a=e.elements,r=1/(a[3]*t+a[7]*i+a[11]*s+a[15]);return this.x=(a[0]*t+a[4]*i+a[8]*s+a[12])*r,this.y=(a[1]*t+a[5]*i+a[9]*s+a[13])*r,this.z=(a[2]*t+a[6]*i+a[10]*s+a[14])*r,this}applyQuaternion(e){const t=this.x,i=this.y,s=this.z,a=e.x,r=e.y,o=e.z,l=e.w,c=2*(r*s-o*i),u=2*(o*t-a*s),d=2*(a*i-r*t);return this.x=t+l*c+r*d-o*u,this.y=i+l*u+o*c-a*d,this.z=s+l*d+a*u-r*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,i=this.y,s=this.z,a=e.elements;return this.x=a[0]*t+a[4]*i+a[8]*s,this.y=a[1]*t+a[5]*i+a[9]*s,this.z=a[2]*t+a[6]*i+a[10]*s,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Je(this.x,e.x,t.x),this.y=Je(this.y,e.y,t.y),this.z=Je(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Je(this.x,e,t),this.y=Je(this.y,e,t),this.z=Je(this.z,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Je(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const i=e.x,s=e.y,a=e.z,r=t.x,o=t.y,l=t.z;return this.x=s*l-a*o,this.y=a*r-i*l,this.z=i*o-s*r,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return zf.copy(this).projectOnVector(e),this.sub(zf)}reflect(e){return this.sub(zf.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Je(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,s=this.z-e.z;return t*t+i*i+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){const s=Math.sin(t)*e;return this.x=s*Math.sin(i),this.y=Math.cos(t)*e,this.z=s*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),s=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=s,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(e),this.y=t,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const zf=new T,Vy=new ht;class at{constructor(e,t,i,s,a,r,o,l,c){at.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,s,a,r,o,l,c)}set(e,t,i,s,a,r,o,l,c){const u=this.elements;return u[0]=e,u[1]=s,u[2]=o,u[3]=t,u[4]=a,u[5]=l,u[6]=i,u[7]=r,u[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,s=t.elements,a=this.elements,r=i[0],o=i[3],l=i[6],c=i[1],u=i[4],d=i[7],h=i[2],f=i[5],p=i[8],g=s[0],_=s[3],m=s[6],v=s[1],y=s[4],b=s[7],S=s[2],x=s[5],M=s[8];return a[0]=r*g+o*v+l*S,a[3]=r*_+o*y+l*x,a[6]=r*m+o*b+l*M,a[1]=c*g+u*v+d*S,a[4]=c*_+u*y+d*x,a[7]=c*m+u*b+d*M,a[2]=h*g+f*v+p*S,a[5]=h*_+f*y+p*x,a[8]=h*m+f*b+p*M,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[1],s=e[2],a=e[3],r=e[4],o=e[5],l=e[6],c=e[7],u=e[8];return t*r*u-t*o*c-i*a*u+i*o*l+s*a*c-s*r*l}invert(){const e=this.elements,t=e[0],i=e[1],s=e[2],a=e[3],r=e[4],o=e[5],l=e[6],c=e[7],u=e[8],d=u*r-o*c,h=o*l-u*a,f=c*a-r*l,p=t*d+i*h+s*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);const g=1/p;return e[0]=d*g,e[1]=(s*c-u*i)*g,e[2]=(o*i-s*r)*g,e[3]=h*g,e[4]=(u*t-s*l)*g,e[5]=(s*a-o*t)*g,e[6]=f*g,e[7]=(i*l-c*t)*g,e[8]=(r*t-i*a)*g,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,s,a,r,o){const l=Math.cos(a),c=Math.sin(a);return this.set(i*l,i*c,-i*(l*r+c*o)+r+e,-s*c,s*l,-s*(-c*r+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(Hf.makeScale(e,t)),this}rotate(e){return this.premultiply(Hf.makeRotation(-e)),this}translate(e,t){return this.premultiply(Hf.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,i=e.elements;for(let s=0;s<9;s++)if(t[s]!==i[s])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const Hf=new at;function $S(n){for(let e=n.length-1;e>=0;--e)if(n[e]>=65535)return!0;return!1}const VA={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function ro(n,e){return new VA[n](e)}function rc(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}function WS(){const n=rc("canvas");return n.style.display="block",n}const Gy={};function oc(n){n in Gy||(Gy[n]=!0,console.warn(n))}function GA(n,e,t){return new Promise(function(i,s){function a(){switch(n.clientWaitSync(e,n.SYNC_FLUSH_COMMANDS_BIT,0)){case n.WAIT_FAILED:s();break;case n.TIMEOUT_EXPIRED:setTimeout(a,t);break;default:i()}}setTimeout(a,t)})}const $y=new at().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Wy=new at().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function $A(){const n={enabled:!0,workingColorSpace:wn,spaces:{},convert:function(s,a,r){return this.enabled===!1||a===r||!a||!r||(this.spaces[a].transfer===It&&(s.r=Gs(s.r),s.g=Gs(s.g),s.b=Gs(s.b)),this.spaces[a].primaries!==this.spaces[r].primaries&&(s.applyMatrix3(this.spaces[a].toXYZ),s.applyMatrix3(this.spaces[r].fromXYZ)),this.spaces[r].transfer===It&&(s.r=fo(s.r),s.g=fo(s.g),s.b=fo(s.b))),s},workingToColorSpace:function(s,a){return this.convert(s,this.workingColorSpace,a)},colorSpaceToWorking:function(s,a){return this.convert(s,a,this.workingColorSpace)},getPrimaries:function(s){return this.spaces[s].primaries},getTransfer:function(s){return s===Bs?sc:this.spaces[s].transfer},getToneMappingMode:function(s){return this.spaces[s].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(s,a=this.workingColorSpace){return s.fromArray(this.spaces[a].luminanceCoefficients)},define:function(s){Object.assign(this.spaces,s)},_getMatrix:function(s,a,r){return s.copy(this.spaces[a].toXYZ).multiply(this.spaces[r].fromXYZ)},_getDrawingBufferColorSpace:function(s){return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(s=this.workingColorSpace){return this.spaces[s].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(s,a){return oc("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),n.workingToColorSpace(s,a)},toWorkingColorSpace:function(s,a){return oc("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),n.colorSpaceToWorking(s,a)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],i=[.3127,.329];return n.define({[wn]:{primaries:e,whitePoint:i,transfer:sc,toXYZ:$y,fromXYZ:Wy,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:yt},outputColorSpaceConfig:{drawingBufferColorSpace:yt}},[yt]:{primaries:e,whitePoint:i,transfer:It,toXYZ:$y,fromXYZ:Wy,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:yt}}}),n}const rt=$A();function Gs(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function fo(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}let Ar;class XS{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{Ar===void 0&&(Ar=rc("canvas")),Ar.width=e.width,Ar.height=e.height;const s=Ar.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),i=Ar}return i.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=rc("canvas");t.width=e.width,t.height=e.height;const i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const s=i.getImageData(0,0,e.width,e.height),a=s.data;for(let r=0;r1),this.pmremVersion=0}get width(){return this.source.getSize(Gf).x}get height(){return this.source.getSize(Gf).y}get depth(){return this.source.getSize(Gf).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const i=e[t];if(i===void 0){console.warn(`THREE.Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){console.warn(`THREE.Texture.setValues(): property '${t}' does not exist.`);continue}s&&i&&s.isVector2&&i.isVector2||s&&i&&s.isVector3&&i.isVector3||s&&i&&s.isMatrix3&&i.isMatrix3?s.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),t||(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==Hh)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case xs:e.x=e.x-Math.floor(e.x);break;case Wn:e.x=e.x<0?0:1;break;case Ao:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case xs:e.y=e.y-Math.floor(e.y);break;case Wn:e.y=e.y<0?0:1;break;case Ao:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}zt.DEFAULT_IMAGE=null;zt.DEFAULT_MAPPING=Hh;zt.DEFAULT_ANISOTROPY=1;class Ye{constructor(e=0,t=0,i=0,s=1){Ye.prototype.isVector4=!0,this.x=e,this.y=t,this.z=i,this.w=s}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,s=this.z,a=this.w,r=e.elements;return this.x=r[0]*t+r[4]*i+r[8]*s+r[12]*a,this.y=r[1]*t+r[5]*i+r[9]*s+r[13]*a,this.z=r[2]*t+r[6]*i+r[10]*s+r[14]*a,this.w=r[3]*t+r[7]*i+r[11]*s+r[15]*a,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,i,s,a;const l=e.elements,c=l[0],u=l[4],d=l[8],h=l[1],f=l[5],p=l[9],g=l[2],_=l[6],m=l[10];if(Math.abs(u-h)<.01&&Math.abs(d-g)<.01&&Math.abs(p-_)<.01){if(Math.abs(u+h)<.1&&Math.abs(d+g)<.1&&Math.abs(p+_)<.1&&Math.abs(c+f+m-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const y=(c+1)/2,b=(f+1)/2,S=(m+1)/2,x=(u+h)/4,M=(d+g)/4,C=(p+_)/4;return y>b&&y>S?y<.01?(i=0,s=.707106781,a=.707106781):(i=Math.sqrt(y),s=x/i,a=M/i):b>S?b<.01?(i=.707106781,s=0,a=.707106781):(s=Math.sqrt(b),i=x/s,a=C/s):S<.01?(i=.707106781,s=.707106781,a=0):(a=Math.sqrt(S),i=M/a,s=C/a),this.set(i,s,a,t),this}let v=Math.sqrt((_-p)*(_-p)+(d-g)*(d-g)+(h-u)*(h-u));return Math.abs(v)<.001&&(v=1),this.x=(_-p)/v,this.y=(d-g)/v,this.z=(h-u)/v,this.w=Math.acos((c+f+m-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Je(this.x,e.x,t.x),this.y=Je(this.y,e.y,t.y),this.z=Je(this.z,e.z,t.z),this.w=Je(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Je(this.x,e,t),this.y=Je(this.y,e,t),this.z=Je(this.z,e,t),this.w=Je(this.w,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Je(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class Tg extends Ts{constructor(e=1,t=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Gt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},i),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=i.depth,this.scissor=new Ye(0,0,e,t),this.scissorTest=!1,this.viewport=new Ye(0,0,e,t);const s={width:e,height:t,depth:i.depth},a=new zt(s);this.textures=[];const r=i.count;for(let o=0;o1;this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,i=e.textures.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Ni),Ni.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(nl),Nc.subVectors(this.max,nl),Rr.subVectors(e.a,nl),Pr.subVectors(e.b,nl),Ir.subVectors(e.c,nl),js.subVectors(Pr,Rr),Zs.subVectors(Ir,Pr),Ma.subVectors(Rr,Ir);let t=[0,-js.z,js.y,0,-Zs.z,Zs.y,0,-Ma.z,Ma.y,js.z,0,-js.x,Zs.z,0,-Zs.x,Ma.z,0,-Ma.x,-js.y,js.x,0,-Zs.y,Zs.x,0,-Ma.y,Ma.x,0];return!$f(t,Rr,Pr,Ir,Nc)||(t=[1,0,0,0,1,0,0,0,1],!$f(t,Rr,Pr,Ir,Nc))?!1:(Uc.crossVectors(js,Zs),t=[Uc.x,Uc.y,Uc.z],$f(t,Rr,Pr,Ir,Nc))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Ni).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Ni).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Es[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Es[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Es[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Es[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Es[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Es[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Es[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Es[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Es),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const Es=[new T,new T,new T,new T,new T,new T,new T,new T],Ni=new T,Fc=new bn,Rr=new T,Pr=new T,Ir=new T,js=new T,Zs=new T,Ma=new T,nl=new T,Nc=new T,Uc=new T,Ea=new T;function $f(n,e,t,i,s){for(let a=0,r=n.length-3;a<=r;a+=3){Ea.fromArray(n,a);const o=s.x*Math.abs(Ea.x)+s.y*Math.abs(Ea.y)+s.z*Math.abs(Ea.z),l=e.dot(Ea),c=t.dot(Ea),u=i.dot(Ea);if(Math.max(-Math.max(l,c,u),Math.min(l,c,u))>o)return!1}return!0}const YA=new bn,il=new T,Wf=new T;class xn{constructor(e=new T,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const i=this.center;t!==void 0?i.copy(t):YA.setFromPoints(e).getCenter(i);let s=0;for(let a=0,r=e.length;athis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;il.subVectors(e,this.center);const t=il.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),s=(i-this.radius)*.5;this.center.addScaledVector(il,s/i),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(Wf.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(il.copy(e.center).add(Wf)),this.expandByPoint(il.copy(e.center).sub(Wf))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}const Cs=new T,Xf=new T,Bc=new T,Js=new T,Kf=new T,zc=new T,qf=new T;class Sr{constructor(e=new T,t=new T(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Cs)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Cs.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Cs.copy(this.origin).addScaledVector(this.direction,t),Cs.distanceToSquared(e))}distanceSqToSegment(e,t,i,s){Xf.copy(e).add(t).multiplyScalar(.5),Bc.copy(t).sub(e).normalize(),Js.copy(this.origin).sub(Xf);const a=e.distanceTo(t)*.5,r=-this.direction.dot(Bc),o=Js.dot(this.direction),l=-Js.dot(Bc),c=Js.lengthSq(),u=Math.abs(1-r*r);let d,h,f,p;if(u>0)if(d=r*l-o,h=r*o-l,p=a*u,d>=0)if(h>=-p)if(h<=p){const g=1/u;d*=g,h*=g,f=d*(d+r*h+2*o)+h*(r*d+h+2*l)+c}else h=a,d=Math.max(0,-(r*h+o)),f=-d*d+h*(h+2*l)+c;else h=-a,d=Math.max(0,-(r*h+o)),f=-d*d+h*(h+2*l)+c;else h<=-p?(d=Math.max(0,-(-r*a+o)),h=d>0?-a:Math.min(Math.max(-a,-l),a),f=-d*d+h*(h+2*l)+c):h<=p?(d=0,h=Math.min(Math.max(-a,-l),a),f=h*(h+2*l)+c):(d=Math.max(0,-(r*a+o)),h=d>0?a:Math.min(Math.max(-a,-l),a),f=-d*d+h*(h+2*l)+c);else h=r>0?-a:a,d=Math.max(0,-(r*h+o)),f=-d*d+h*(h+2*l)+c;return i&&i.copy(this.origin).addScaledVector(this.direction,d),s&&s.copy(Xf).addScaledVector(Bc,h),f}intersectSphere(e,t){Cs.subVectors(e.center,this.origin);const i=Cs.dot(this.direction),s=Cs.dot(Cs)-i*i,a=e.radius*e.radius;if(s>a)return null;const r=Math.sqrt(a-s),o=i-r,l=i+r;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,s,a,r,o,l;const c=1/this.direction.x,u=1/this.direction.y,d=1/this.direction.z,h=this.origin;return c>=0?(i=(e.min.x-h.x)*c,s=(e.max.x-h.x)*c):(i=(e.max.x-h.x)*c,s=(e.min.x-h.x)*c),u>=0?(a=(e.min.y-h.y)*u,r=(e.max.y-h.y)*u):(a=(e.max.y-h.y)*u,r=(e.min.y-h.y)*u),i>r||a>s||((a>i||isNaN(i))&&(i=a),(r=0?(o=(e.min.z-h.z)*d,l=(e.max.z-h.z)*d):(o=(e.max.z-h.z)*d,l=(e.min.z-h.z)*d),i>l||o>s)||((o>i||i!==i)&&(i=o),(l=0?i:s,t)}intersectsBox(e){return this.intersectBox(e,Cs)!==null}intersectTriangle(e,t,i,s,a){Kf.subVectors(t,e),zc.subVectors(i,e),qf.crossVectors(Kf,zc);let r=this.direction.dot(qf),o;if(r>0){if(s)return null;o=1}else if(r<0)o=-1,r=-r;else return null;Js.subVectors(this.origin,e);const l=o*this.direction.dot(zc.crossVectors(Js,zc));if(l<0)return null;const c=o*this.direction.dot(Kf.cross(Js));if(c<0||l+c>r)return null;const u=-o*Js.dot(qf);return u<0?null:this.at(u/r,a)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Ee{constructor(e,t,i,s,a,r,o,l,c,u,d,h,f,p,g,_){Ee.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,i,s,a,r,o,l,c,u,d,h,f,p,g,_)}set(e,t,i,s,a,r,o,l,c,u,d,h,f,p,g,_){const m=this.elements;return m[0]=e,m[4]=t,m[8]=i,m[12]=s,m[1]=a,m[5]=r,m[9]=o,m[13]=l,m[2]=c,m[6]=u,m[10]=d,m[14]=h,m[3]=f,m[7]=p,m[11]=g,m[15]=_,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Ee().fromArray(this.elements)}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(e){const t=this.elements,i=e.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,i){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(e,t,i){return this.set(e.x,t.x,i.x,0,e.y,t.y,i.y,0,e.z,t.z,i.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,i=e.elements,s=1/Lr.setFromMatrixColumn(e,0).length(),a=1/Lr.setFromMatrixColumn(e,1).length(),r=1/Lr.setFromMatrixColumn(e,2).length();return t[0]=i[0]*s,t[1]=i[1]*s,t[2]=i[2]*s,t[3]=0,t[4]=i[4]*a,t[5]=i[5]*a,t[6]=i[6]*a,t[7]=0,t[8]=i[8]*r,t[9]=i[9]*r,t[10]=i[10]*r,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,i=e.x,s=e.y,a=e.z,r=Math.cos(i),o=Math.sin(i),l=Math.cos(s),c=Math.sin(s),u=Math.cos(a),d=Math.sin(a);if(e.order==="XYZ"){const h=r*u,f=r*d,p=o*u,g=o*d;t[0]=l*u,t[4]=-l*d,t[8]=c,t[1]=f+p*c,t[5]=h-g*c,t[9]=-o*l,t[2]=g-h*c,t[6]=p+f*c,t[10]=r*l}else if(e.order==="YXZ"){const h=l*u,f=l*d,p=c*u,g=c*d;t[0]=h+g*o,t[4]=p*o-f,t[8]=r*c,t[1]=r*d,t[5]=r*u,t[9]=-o,t[2]=f*o-p,t[6]=g+h*o,t[10]=r*l}else if(e.order==="ZXY"){const h=l*u,f=l*d,p=c*u,g=c*d;t[0]=h-g*o,t[4]=-r*d,t[8]=p+f*o,t[1]=f+p*o,t[5]=r*u,t[9]=g-h*o,t[2]=-r*c,t[6]=o,t[10]=r*l}else if(e.order==="ZYX"){const h=r*u,f=r*d,p=o*u,g=o*d;t[0]=l*u,t[4]=p*c-f,t[8]=h*c+g,t[1]=l*d,t[5]=g*c+h,t[9]=f*c-p,t[2]=-c,t[6]=o*l,t[10]=r*l}else if(e.order==="YZX"){const h=r*l,f=r*c,p=o*l,g=o*c;t[0]=l*u,t[4]=g-h*d,t[8]=p*d+f,t[1]=d,t[5]=r*u,t[9]=-o*u,t[2]=-c*u,t[6]=f*d+p,t[10]=h-g*d}else if(e.order==="XZY"){const h=r*l,f=r*c,p=o*l,g=o*c;t[0]=l*u,t[4]=-d,t[8]=c*u,t[1]=h*d+g,t[5]=r*u,t[9]=f*d-p,t[2]=p*d-f,t[6]=o*u,t[10]=g*d+h}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(jA,e,ZA)}lookAt(e,t,i){const s=this.elements;return fi.subVectors(e,t),fi.lengthSq()===0&&(fi.z=1),fi.normalize(),Qs.crossVectors(i,fi),Qs.lengthSq()===0&&(Math.abs(i.z)===1?fi.x+=1e-4:fi.z+=1e-4,fi.normalize(),Qs.crossVectors(i,fi)),Qs.normalize(),Hc.crossVectors(fi,Qs),s[0]=Qs.x,s[4]=Hc.x,s[8]=fi.x,s[1]=Qs.y,s[5]=Hc.y,s[9]=fi.y,s[2]=Qs.z,s[6]=Hc.z,s[10]=fi.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,s=t.elements,a=this.elements,r=i[0],o=i[4],l=i[8],c=i[12],u=i[1],d=i[5],h=i[9],f=i[13],p=i[2],g=i[6],_=i[10],m=i[14],v=i[3],y=i[7],b=i[11],S=i[15],x=s[0],M=s[4],C=s[8],w=s[12],E=s[1],R=s[5],L=s[9],O=s[13],D=s[2],U=s[6],F=s[10],W=s[14],H=s[3],ie=s[7],le=s[11],me=s[15];return a[0]=r*x+o*E+l*D+c*H,a[4]=r*M+o*R+l*U+c*ie,a[8]=r*C+o*L+l*F+c*le,a[12]=r*w+o*O+l*W+c*me,a[1]=u*x+d*E+h*D+f*H,a[5]=u*M+d*R+h*U+f*ie,a[9]=u*C+d*L+h*F+f*le,a[13]=u*w+d*O+h*W+f*me,a[2]=p*x+g*E+_*D+m*H,a[6]=p*M+g*R+_*U+m*ie,a[10]=p*C+g*L+_*F+m*le,a[14]=p*w+g*O+_*W+m*me,a[3]=v*x+y*E+b*D+S*H,a[7]=v*M+y*R+b*U+S*ie,a[11]=v*C+y*L+b*F+S*le,a[15]=v*w+y*O+b*W+S*me,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[4],s=e[8],a=e[12],r=e[1],o=e[5],l=e[9],c=e[13],u=e[2],d=e[6],h=e[10],f=e[14],p=e[3],g=e[7],_=e[11],m=e[15];return p*(+a*l*d-s*c*d-a*o*h+i*c*h+s*o*f-i*l*f)+g*(+t*l*f-t*c*h+a*r*h-s*r*f+s*c*u-a*l*u)+_*(+t*c*d-t*o*f-a*r*d+i*r*f+a*o*u-i*c*u)+m*(-s*o*u-t*l*d+t*o*h+s*r*d-i*r*h+i*l*u)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,i){const s=this.elements;return e.isVector3?(s[12]=e.x,s[13]=e.y,s[14]=e.z):(s[12]=e,s[13]=t,s[14]=i),this}invert(){const e=this.elements,t=e[0],i=e[1],s=e[2],a=e[3],r=e[4],o=e[5],l=e[6],c=e[7],u=e[8],d=e[9],h=e[10],f=e[11],p=e[12],g=e[13],_=e[14],m=e[15],v=d*_*c-g*h*c+g*l*f-o*_*f-d*l*m+o*h*m,y=p*h*c-u*_*c-p*l*f+r*_*f+u*l*m-r*h*m,b=u*g*c-p*d*c+p*o*f-r*g*f-u*o*m+r*d*m,S=p*d*l-u*g*l-p*o*h+r*g*h+u*o*_-r*d*_,x=t*v+i*y+s*b+a*S;if(x===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const M=1/x;return e[0]=v*M,e[1]=(g*h*a-d*_*a-g*s*f+i*_*f+d*s*m-i*h*m)*M,e[2]=(o*_*a-g*l*a+g*s*c-i*_*c-o*s*m+i*l*m)*M,e[3]=(d*l*a-o*h*a-d*s*c+i*h*c+o*s*f-i*l*f)*M,e[4]=y*M,e[5]=(u*_*a-p*h*a+p*s*f-t*_*f-u*s*m+t*h*m)*M,e[6]=(p*l*a-r*_*a-p*s*c+t*_*c+r*s*m-t*l*m)*M,e[7]=(r*h*a-u*l*a+u*s*c-t*h*c-r*s*f+t*l*f)*M,e[8]=b*M,e[9]=(p*d*a-u*g*a-p*i*f+t*g*f+u*i*m-t*d*m)*M,e[10]=(r*g*a-p*o*a+p*i*c-t*g*c-r*i*m+t*o*m)*M,e[11]=(u*o*a-r*d*a-u*i*c+t*d*c+r*i*f-t*o*f)*M,e[12]=S*M,e[13]=(u*g*s-p*d*s+p*i*h-t*g*h-u*i*_+t*d*_)*M,e[14]=(p*o*s-r*g*s-p*i*l+t*g*l+r*i*_-t*o*_)*M,e[15]=(r*d*s-u*o*s+u*i*l-t*d*l-r*i*h+t*o*h)*M,this}scale(e){const t=this.elements,i=e.x,s=e.y,a=e.z;return t[0]*=i,t[4]*=s,t[8]*=a,t[1]*=i,t[5]*=s,t[9]*=a,t[2]*=i,t[6]*=s,t[10]*=a,t[3]*=i,t[7]*=s,t[11]*=a,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],s=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,s))}makeTranslation(e,t,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const i=Math.cos(t),s=Math.sin(t),a=1-i,r=e.x,o=e.y,l=e.z,c=a*r,u=a*o;return this.set(c*r+i,c*o-s*l,c*l+s*o,0,c*o+s*l,u*o+i,u*l-s*r,0,c*l-s*o,u*l+s*r,a*l*l+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,s,a,r){return this.set(1,i,a,0,e,1,r,0,t,s,1,0,0,0,0,1),this}compose(e,t,i){const s=this.elements,a=t._x,r=t._y,o=t._z,l=t._w,c=a+a,u=r+r,d=o+o,h=a*c,f=a*u,p=a*d,g=r*u,_=r*d,m=o*d,v=l*c,y=l*u,b=l*d,S=i.x,x=i.y,M=i.z;return s[0]=(1-(g+m))*S,s[1]=(f+b)*S,s[2]=(p-y)*S,s[3]=0,s[4]=(f-b)*x,s[5]=(1-(h+m))*x,s[6]=(_+v)*x,s[7]=0,s[8]=(p+y)*M,s[9]=(_-v)*M,s[10]=(1-(h+g))*M,s[11]=0,s[12]=e.x,s[13]=e.y,s[14]=e.z,s[15]=1,this}decompose(e,t,i){const s=this.elements;let a=Lr.set(s[0],s[1],s[2]).length();const r=Lr.set(s[4],s[5],s[6]).length(),o=Lr.set(s[8],s[9],s[10]).length();this.determinant()<0&&(a=-a),e.x=s[12],e.y=s[13],e.z=s[14],Ui.copy(this);const c=1/a,u=1/r,d=1/o;return Ui.elements[0]*=c,Ui.elements[1]*=c,Ui.elements[2]*=c,Ui.elements[4]*=u,Ui.elements[5]*=u,Ui.elements[6]*=u,Ui.elements[8]*=d,Ui.elements[9]*=d,Ui.elements[10]*=d,t.setFromRotationMatrix(Ui),i.x=a,i.y=r,i.z=o,this}makePerspective(e,t,i,s,a,r,o=yi,l=!1){const c=this.elements,u=2*a/(t-e),d=2*a/(i-s),h=(t+e)/(t-e),f=(i+s)/(i-s);let p,g;if(l)p=a/(r-a),g=r*a/(r-a);else if(o===yi)p=-(r+a)/(r-a),g=-2*r*a/(r-a);else if(o===Do)p=-r/(r-a),g=-r*a/(r-a);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return c[0]=u,c[4]=0,c[8]=h,c[12]=0,c[1]=0,c[5]=d,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=g,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,i,s,a,r,o=yi,l=!1){const c=this.elements,u=2/(t-e),d=2/(i-s),h=-(t+e)/(t-e),f=-(i+s)/(i-s);let p,g;if(l)p=1/(r-a),g=r/(r-a);else if(o===yi)p=-2/(r-a),g=-(r+a)/(r-a);else if(o===Do)p=-1/(r-a),g=-a/(r-a);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return c[0]=u,c[4]=0,c[8]=0,c[12]=h,c[1]=0,c[5]=d,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=p,c[14]=g,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const t=this.elements,i=e.elements;for(let s=0;s<16;s++)if(t[s]!==i[s])return!1;return!0}fromArray(e,t=0){for(let i=0;i<16;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],e}}const Lr=new T,Ui=new Ee,jA=new T(0,0,0),ZA=new T(1,1,1),Qs=new T,Hc=new T,fi=new T,Xy=new Ee,Ky=new ht;class rn{constructor(e=0,t=0,i=0,s=rn.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=s}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,i,s=this._order){return this._x=e,this._y=t,this._z=i,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,i=!0){const s=e.elements,a=s[0],r=s[4],o=s[8],l=s[1],c=s[5],u=s[9],d=s[2],h=s[6],f=s[10];switch(t){case"XYZ":this._y=Math.asin(Je(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,f),this._z=Math.atan2(-r,a)):(this._x=Math.atan2(h,c),this._z=0);break;case"YXZ":this._x=Math.asin(-Je(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-d,a),this._z=0);break;case"ZXY":this._x=Math.asin(Je(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-d,f),this._z=Math.atan2(-r,c)):(this._y=0,this._z=Math.atan2(l,a));break;case"ZYX":this._y=Math.asin(-Je(d,-1,1)),Math.abs(d)<.9999999?(this._x=Math.atan2(h,f),this._z=Math.atan2(l,a)):(this._x=0,this._z=Math.atan2(-r,c));break;case"YZX":this._z=Math.asin(Je(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-u,c),this._y=Math.atan2(-d,a)):(this._x=0,this._y=Math.atan2(o,f));break;case"XZY":this._z=Math.asin(-Je(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(h,c),this._y=Math.atan2(o,a)):(this._x=Math.atan2(-u,f),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,i===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return Xy.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Xy,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Ky.setFromEuler(this),this.setFromQuaternion(Ky,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}rn.DEFAULT_ORDER="XYZ";class Jh{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let i=0;i0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(s.matrixAutoUpdate=!1),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),s.instanceInfo=this._instanceInfo.map(o=>({...o})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(e),s.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(s.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(s.boundingBox=this.boundingBox.toJSON()));function a(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=a(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const l=o.shapes;if(Array.isArray(l))for(let c=0,u=l.length;c0){s.children=[];for(let o=0;o0){s.animations=[];for(let o=0;o0&&(i.geometries=o),l.length>0&&(i.materials=l),c.length>0&&(i.textures=c),u.length>0&&(i.images=u),d.length>0&&(i.shapes=d),h.length>0&&(i.skeletons=h),f.length>0&&(i.animations=f),p.length>0&&(i.nodes=p)}return i.object=s,i;function r(o){const l=[];for(const c in o){const u=o[c];delete u.metadata,l.push(u)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let i=0;i0?s.multiplyScalar(1/Math.sqrt(a)):s.set(0,0,0)}static getBarycoord(e,t,i,s,a){Bi.subVectors(s,t),Rs.subVectors(i,t),jf.subVectors(e,t);const r=Bi.dot(Bi),o=Bi.dot(Rs),l=Bi.dot(jf),c=Rs.dot(Rs),u=Rs.dot(jf),d=r*c-o*o;if(d===0)return a.set(0,0,0),null;const h=1/d,f=(c*l-o*u)*h,p=(r*u-o*l)*h;return a.set(1-f-p,p,f)}static containsPoint(e,t,i,s){return this.getBarycoord(e,t,i,s,Ps)===null?!1:Ps.x>=0&&Ps.y>=0&&Ps.x+Ps.y<=1}static getInterpolation(e,t,i,s,a,r,o,l){return this.getBarycoord(e,t,i,s,Ps)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(a,Ps.x),l.addScaledVector(r,Ps.y),l.addScaledVector(o,Ps.z),l)}static getInterpolatedAttribute(e,t,i,s,a,r){return ep.setScalar(0),tp.setScalar(0),np.setScalar(0),ep.fromBufferAttribute(e,t),tp.fromBufferAttribute(e,i),np.fromBufferAttribute(e,s),r.setScalar(0),r.addScaledVector(ep,a.x),r.addScaledVector(tp,a.y),r.addScaledVector(np,a.z),r}static isFrontFacing(e,t,i,s){return Bi.subVectors(i,t),Rs.subVectors(e,t),Bi.cross(Rs).dot(s)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,s){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[s]),this}setFromAttributeAndIndices(e,t,i,s){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,s),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Bi.subVectors(this.c,this.b),Rs.subVectors(this.a,this.b),Bi.cross(Rs).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return ii.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return ii.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,s,a){return ii.getInterpolation(e,this.a,this.b,this.c,t,i,s,a)}containsPoint(e){return ii.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return ii.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,s=this.b,a=this.c;let r,o;Or.subVectors(s,i),Fr.subVectors(a,i),Zf.subVectors(e,i);const l=Or.dot(Zf),c=Fr.dot(Zf);if(l<=0&&c<=0)return t.copy(i);Jf.subVectors(e,s);const u=Or.dot(Jf),d=Fr.dot(Jf);if(u>=0&&d<=u)return t.copy(s);const h=l*d-u*c;if(h<=0&&l>=0&&u<=0)return r=l/(l-u),t.copy(i).addScaledVector(Or,r);Qf.subVectors(e,a);const f=Or.dot(Qf),p=Fr.dot(Qf);if(p>=0&&f<=p)return t.copy(a);const g=f*c-l*p;if(g<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(i).addScaledVector(Fr,o);const _=u*p-f*d;if(_<=0&&d-u>=0&&f-p>=0)return Qy.subVectors(a,s),o=(d-u)/(d-u+(f-p)),t.copy(s).addScaledVector(Qy,o);const m=1/(_+g+h);return r=g*m,o=h*m,t.copy(i).addScaledVector(Or,r).addScaledVector(Fr,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const KS={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},ea={h:0,s:0,l:0},Gc={h:0,s:0,l:0};function ip(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*6*(2/3-t):n}class de{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){const s=e;s&&s.isColor?this.copy(s):typeof s=="number"?this.setHex(s):typeof s=="string"&&this.setStyle(s)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=yt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,rt.colorSpaceToWorking(this,t),this}setRGB(e,t,i,s=rt.workingColorSpace){return this.r=e,this.g=t,this.b=i,rt.colorSpaceToWorking(this,s),this}setHSL(e,t,i,s=rt.workingColorSpace){if(e=Sg(e,1),t=Je(t,0,1),i=Je(i,0,1),t===0)this.r=this.g=this.b=i;else{const a=i<=.5?i*(1+t):i+t-i*t,r=2*i-a;this.r=ip(r,a,e+1/3),this.g=ip(r,a,e),this.b=ip(r,a,e-1/3)}return rt.colorSpaceToWorking(this,s),this}setStyle(e,t=yt){function i(a){a!==void 0&&parseFloat(a)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(e)){let a;const r=s[1],o=s[2];switch(r){case"rgb":case"rgba":if(a=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setRGB(Math.min(255,parseInt(a[1],10))/255,Math.min(255,parseInt(a[2],10))/255,Math.min(255,parseInt(a[3],10))/255,t);if(a=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setRGB(Math.min(100,parseInt(a[1],10))/100,Math.min(100,parseInt(a[2],10))/100,Math.min(100,parseInt(a[3],10))/100,t);break;case"hsl":case"hsla":if(a=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setHSL(parseFloat(a[1])/360,parseFloat(a[2])/100,parseFloat(a[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(e)){const a=s[1],r=a.length;if(r===3)return this.setRGB(parseInt(a.charAt(0),16)/15,parseInt(a.charAt(1),16)/15,parseInt(a.charAt(2),16)/15,t);if(r===6)return this.setHex(parseInt(a,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=yt){const i=KS[e.toLowerCase()];return i!==void 0?this.setHex(i,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Gs(e.r),this.g=Gs(e.g),this.b=Gs(e.b),this}copyLinearToSRGB(e){return this.r=fo(e.r),this.g=fo(e.g),this.b=fo(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=yt){return rt.workingToColorSpace(An.copy(this),e),Math.round(Je(An.r*255,0,255))*65536+Math.round(Je(An.g*255,0,255))*256+Math.round(Je(An.b*255,0,255))}getHexString(e=yt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=rt.workingColorSpace){rt.workingToColorSpace(An.copy(this),t);const i=An.r,s=An.g,a=An.b,r=Math.max(i,s,a),o=Math.min(i,s,a);let l,c;const u=(o+r)/2;if(o===r)l=0,c=0;else{const d=r-o;switch(c=u<=.5?d/(r+o):d/(2-r-o),r){case i:l=(s-a)/d+(s0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const i=e[t];if(i===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(i):s&&s.isVector3&&i&&i.isVector3?s.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==ur&&(i.blending=this.blending),this.side!==bs&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==ec&&(i.blendSrc=this.blendSrc),this.blendDst!==tc&&(i.blendDst=this.blendDst),this.blendEquation!==Us&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==fr&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==Km&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Xa&&(i.stencilFail=this.stencilFail),this.stencilZFail!==Xa&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==Xa&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function s(a){const r=[];for(const o in a){const l=a[o];delete l.metadata,r.push(l)}return r}if(t){const a=s(e.textures),r=s(e.images);a.length>0&&(i.textures=a),r.length>0&&(i.images=r)}return i}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let i=null;if(t!==null){const s=t.length;i=new Array(s);for(let a=0;a!==s;++a)i[a]=t[a].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class je extends en{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new de(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new rn,this.combine=xc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const zs=iR();function iR(){const n=new ArrayBuffer(4),e=new Float32Array(n),t=new Uint32Array(n),i=new Uint32Array(512),s=new Uint32Array(512);for(let l=0;l<256;++l){const c=l-127;c<-27?(i[l]=0,i[l|256]=32768,s[l]=24,s[l|256]=24):c<-14?(i[l]=1024>>-c-14,i[l|256]=1024>>-c-14|32768,s[l]=-c-1,s[l|256]=-c-1):c<=15?(i[l]=c+15<<10,i[l|256]=c+15<<10|32768,s[l]=13,s[l|256]=13):c<128?(i[l]=31744,i[l|256]=64512,s[l]=24,s[l|256]=24):(i[l]=31744,i[l|256]=64512,s[l]=13,s[l|256]=13)}const a=new Uint32Array(2048),r=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,u=0;for(;(c&8388608)===0;)c<<=1,u-=8388608;c&=-8388609,u+=947912704,a[l]=c|u}for(let l=1024;l<2048;++l)a[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)r[l]=l<<23;r[31]=1199570944,r[32]=2147483648;for(let l=33;l<63;++l)r[l]=2147483648+(l-32<<23);r[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:e,uint32View:t,baseTable:i,shiftTable:s,mantissaTable:a,exponentTable:r,offsetTable:o}}function Qn(n){Math.abs(n)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),n=Je(n,-65504,65504),zs.floatView[0]=n;const e=zs.uint32View[0],t=e>>23&511;return zs.baseTable[t]+((e&8388607)>>zs.shiftTable[t])}function Cl(n){const e=n>>10;return zs.uint32View[0]=zs.mantissaTable[zs.offsetTable[e]+(n&1023)]+zs.exponentTable[e],zs.floatView[0]}class Al{static toHalfFloat(e){return Qn(e)}static fromHalfFloat(e){return Cl(e)}}const sn=new T,$c=new ne;let sR=0;class ot{constructor(e,t,i=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:sR++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=ac,this.updateRanges=[],this.gpuType=Mn,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,i){e*=this.itemSize,i*=t.itemSize;for(let s=0,a=this.itemSize;st.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new bn);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new T(-1/0,-1/0,-1/0),new T(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,s=t.length;i0&&(e.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const l in i){const c=i[l];e.data.attributes[l]=c.toJSON(e.data)}const s={};let a=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],u=[];for(let d=0,h=c.length;d0&&(s[l]=u,a=!0)}a&&(e.data.morphAttributes=s,e.data.morphTargetsRelative=this.morphTargetsRelative);const r=this.groups;r.length>0&&(e.data.groups=JSON.parse(JSON.stringify(r)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const i=e.index;i!==null&&this.setIndex(i.clone());const s=e.attributes;for(const c in s){const u=s[c];this.setAttribute(c,u.clone(t))}const a=e.morphAttributes;for(const c in a){const u=[],d=a[c];for(let h=0,f=d.length;h0){const s=t[i[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,r=s.length;a(e.far-e.near)**2))&&(e0.copy(a).invert(),Ca.copy(e.ray).applyMatrix4(e0),!(i.boundingBox!==null&&Ca.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,Ca)))}_computeIntersections(e,t,i){let s;const a=this.geometry,r=this.material,o=a.index,l=a.attributes.position,c=a.attributes.uv,u=a.attributes.uv1,d=a.attributes.normal,h=a.groups,f=a.drawRange;if(o!==null)if(Array.isArray(r))for(let p=0,g=h.length;pt.far?null:{distance:c,point:jc.clone(),object:n}}function Zc(n,e,t,i,s,a,r,o,l,c){n.getVertexPosition(o,Xc),n.getVertexPosition(l,Kc),n.getVertexPosition(c,qc);const u=hR(n,e,t,i,Xc,Kc,qc,n0);if(u){const d=new T;ii.getBarycoord(n0,Xc,Kc,qc,d),s&&(u.uv=ii.getInterpolatedAttribute(s,o,l,c,d,new ne)),a&&(u.uv1=ii.getInterpolatedAttribute(a,o,l,c,d,new ne)),r&&(u.normal=ii.getInterpolatedAttribute(r,o,l,c,d,new T),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));const h={a:o,b:l,c,normal:new T,materialIndex:0};ii.getNormal(Xc,Kc,qc,h.normal),u.face=h,u.barycoord=d}return u}class ki extends $e{constructor(e=1,t=1,i=1,s=1,a=1,r=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:s,heightSegments:a,depthSegments:r};const o=this;s=Math.floor(s),a=Math.floor(a),r=Math.floor(r);const l=[],c=[],u=[],d=[];let h=0,f=0;p("z","y","x",-1,-1,i,t,e,r,a,0),p("z","y","x",1,-1,i,t,-e,r,a,1),p("x","z","y",1,1,e,i,t,s,r,2),p("x","z","y",1,-1,e,i,-t,s,r,3),p("x","y","z",1,-1,e,t,i,s,a,4),p("x","y","z",-1,-1,e,t,-i,s,a,5),this.setIndex(l),this.setAttribute("position",new Ce(c,3)),this.setAttribute("normal",new Ce(u,3)),this.setAttribute("uv",new Ce(d,2));function p(g,_,m,v,y,b,S,x,M,C,w){const E=b/M,R=S/C,L=b/2,O=S/2,D=x/2,U=M+1,F=C+1;let W=0,H=0;const ie=new T;for(let le=0;le0?1:-1,u.push(ie.x,ie.y,ie.z),d.push(Le/M),d.push(1-le/C),W+=1}}for(let le=0;le{for(const a of s)if(a.type==="childList")for(const r of a.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&i(r)}).observe(document,{childList:!0,subtree:!0});function t(s){const a={};return s.integrity&&(a.integrity=s.integrity),s.referrerPolicy&&(a.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?a.credentials="include":s.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function i(s){if(s.ep)return;s.ep=!0;const a=t(s);fetch(s.href,a)}})();function Wh(n,e){if(n.frames.length===0)return 0;let t=0,i=n.frames.length-1;for(;t<=i;){const s=Math.floor((t+i)/2),a=n.frames[s]?.time??0;if(ae)i=s-1;else return s}return Math.max(0,t-1)}class cS{_listeners=new Map;on(e,t){let i=this._listeners.get(e);return i||(i=new Set,this._listeners.set(e,i)),i.add(t),this}once(e,t){const i=(...s)=>{this.off(e,i),t(...s)};return this.on(e,i)}off(e,t){const i=this._listeners.get(e);return i?(t?i.delete(t):i.clear(),i.size===0&&this._listeners.delete(e),this):this}removeListener(e,t){return this.off(e,t)}removeAllListeners(e){return e?this._listeners.delete(e):this._listeners.clear(),this}emit(e,...t){const i=this._listeners.get(e);if(!i||i.size===0)return!1;for(const s of[...i])s(...t);return!0}}function Wf(n){return n?{x:n.x,y:n.z,z:n.y}:null}function UC(n){return n?{x:n.x,y:n.z,z:n.y,w:-n.w}:null}function BC(n){return n*100/255}const $y={Octane:{length:118.0074,width:84.19941,height:36.15907,offsetX:13.87566,offsetZ:20.75499},Dominus:{length:127.9268,width:83.27995,height:31.3,offsetX:9,offsetZ:15.75},Plank:{length:128.8198,width:84.67036,height:29.3944,offsetX:9.00857,offsetZ:12.0942},Breakout:{length:131.4924,width:80.521,height:30.3,offsetX:12.5,offsetZ:11.75},Hybrid:{length:127.0192,width:82.18787,height:34.15907,offsetX:13.87566,offsetZ:20.75499},Merc:{length:120.72,width:76.71,height:41.66,offsetX:11.37566,offsetZ:21.504988}},zC={21:{name:"Backfire",hitbox:"Octane"},22:{name:"Breakout",hitbox:"Breakout"},23:{name:"Octane",hitbox:"Octane"},24:{name:"Paladin",hitbox:"Plank"},25:{name:"Road Hog",hitbox:"Octane"},26:{name:"Gizmo",hitbox:"Octane"},28:{name:"X-Devil",hitbox:"Hybrid"},29:{name:"Hotshot",hitbox:"Dominus"},30:{name:"Merc",hitbox:"Merc"},31:{name:"Venom",hitbox:"Hybrid"},402:{name:"Takumi",hitbox:"Octane"},403:{name:"Dominus",hitbox:"Dominus"},404:{name:"Scarab",hitbox:"Octane"},523:{name:"Zippy",hitbox:"Octane"},597:{name:"DeLorean Time Machine",hitbox:"Dominus"},600:{name:"Ripper",hitbox:"Dominus"},607:{name:"Grog",hitbox:"Octane"},1018:{name:"Dominus GT",hitbox:"Dominus"},1159:{name:"X-Devil Mk2",hitbox:"Hybrid"},1171:{name:"Masamune",hitbox:"Dominus"},1172:{name:"Marauder",hitbox:"Octane"},1286:{name:"Aftershock",hitbox:"Dominus"},1295:{name:"Takumi RX-T",hitbox:"Octane"},1300:{name:"Road Hog XL",hitbox:"Octane"},1317:{name:"Esper",hitbox:"Hybrid"},1416:{name:"Breakout Type-S",hitbox:"Breakout"},1475:{name:"Proteus",hitbox:"Octane"},1478:{name:"Triton",hitbox:"Octane"},1533:{name:"Vulcan",hitbox:"Octane"},1568:{name:"Octane ZSR",hitbox:"Octane"},1603:{name:"Twin Mill III",hitbox:"Plank"},1623:{name:"Bone Shaker",hitbox:"Octane"},1624:{name:"Endo",hitbox:"Hybrid"},1675:{name:"Ice Charger",hitbox:"Dominus"},1689:{name:"Nemesis",hitbox:"Dominus"},1691:{name:"Mantis",hitbox:"Plank"},1856:{name:"Jager 619",hitbox:"Hybrid"},1883:{name:"Imperator DT5",hitbox:"Dominus"},1894:{name:"Samurai",hitbox:"Breakout"},1919:{name:"Centio",hitbox:"Plank"},1932:{name:"Animus GP",hitbox:"Breakout"},2070:{name:"Werewolf",hitbox:"Dominus"},2268:{name:"Fast & Furious Dodge Charger",hitbox:"Dominus"},2269:{name:"Fast & Furious Nissan Skyline",hitbox:"Hybrid"},2665:{name:"The Dark Knight's Tumbler",hitbox:"Octane"},2666:{name:"Batmobile (1989)",hitbox:"Dominus"},2853:{name:"Twinzer",hitbox:"Octane"},2919:{name:"Jurassic Jeep Wrangler",hitbox:"Octane"},2949:{name:"Fast 4WD",hitbox:"Octane"},2950:{name:"MR11",hitbox:"Dominus"},2951:{name:"Gazella GT",hitbox:"Dominus"},3031:{name:"Cyclone",hitbox:"Breakout"},3155:{name:"Maverick",hitbox:"Dominus"},3156:{name:"Maverick G1",hitbox:"Dominus"},3157:{name:"Maverick GXT",hitbox:"Dominus"},3265:{name:"McLaren 570S",hitbox:"Dominus"},3311:{name:"Komodo",hitbox:"Breakout"},3426:{name:"Diestro",hitbox:"Dominus"},3451:{name:"Nimbus",hitbox:"Hybrid"},3582:{name:"Insidio",hitbox:"Hybrid"},3594:{name:"Artemis G1",hitbox:"Plank"},3614:{name:"Artemis",hitbox:"Plank"},3622:{name:"Artemis GXT",hitbox:"Plank"},3702:{name:"Tygris",hitbox:"Hybrid"},3875:{name:"Guardian GXT",hitbox:"Dominus"},3879:{name:"Guardian",hitbox:"Dominus"},3880:{name:"Guardian G1",hitbox:"Dominus"},4014:{name:"K.I.T.T.",hitbox:"Dominus"},4155:{name:"Ecto-1",hitbox:"Dominus"},4268:{name:"Sentinel",hitbox:"Plank"},4284:{name:"Fennec",hitbox:"Octane"},4318:{name:"Mudcat",hitbox:"Octane"},4319:{name:"Mudcat G1",hitbox:"Octane"},4320:{name:"Mudcat GXT",hitbox:"Octane"},4367:{name:"Chikara GXT",hitbox:"Dominus"},4472:{name:"Chikara",hitbox:"Dominus"},4473:{name:"Chikara G1",hitbox:"Dominus"},4745:{name:"Ronin GXT",hitbox:"Dominus"},4770:{name:"Dominus",hitbox:"Dominus"},4780:{name:"Battle Bus",hitbox:"Merc"},4781:{name:"Peregrine TT",hitbox:"Dominus"},4782:{name:"Psyclops",hitbox:"Body_Tritip_Handling"},4861:{name:"Ronin",hitbox:"Dominus"},4864:{name:"Ronin G1",hitbox:"Dominus"},4906:{name:"Harbinger",hitbox:"Octane"},5020:{name:"Outlaw",hitbox:"Octane"},5039:{name:"Harbinger GXT",hitbox:"Octane"},5188:{name:"Scarab",hitbox:"Octane"},5265:{name:"Formula 1 2021",hitbox:"Plank"},5361:{name:"Dingo",hitbox:"Octane"},5470:{name:"R3MX",hitbox:"Hybrid"},5488:{name:"R3MX GXT",hitbox:"Hybrid"},5547:{name:"007's Aston Martin DB5",hitbox:"Octane"},5709:{name:"NASCAR Ford Mustang",hitbox:"Dominus"},5713:{name:"Ford F-150 RLE",hitbox:"Octane"},5773:{name:"NASCAR Toyota Camry",hitbox:"Dominus"},5823:{name:"NASCAR Chevrolet Camaro",hitbox:"Dominus"},5837:{name:"Outlaw GXT",hitbox:"Octane"},5858:{name:"Tyranno",hitbox:"Dominus"},5879:{name:"Fast & Furious Pontiac Fiero",hitbox:"Hybrid"},5951:{name:"Jackal",hitbox:"Octane"},5964:{name:"Lamborghini Huracan STO",hitbox:"Dominus"},5979:{name:"Tyranno GXT",hitbox:"Dominus"},6122:{name:"Masamune",hitbox:"Dominus"},6243:{name:"Nexus",hitbox:"Breakout"},6244:{name:"BMW M240i",hitbox:"Dominus"},6247:{name:"McLaren 765LT",hitbox:"Dominus"},6260:{name:"007's Aston Martin Valhalla",hitbox:"Dominus"},6489:{name:"Nexus SC",hitbox:"Breakout"},6836:{name:"Ford Mustang Shelby GT350R RLE",hitbox:"Dominus"},6939:{name:"Ford Mustang Mach-E RLE",hitbox:"Octane"},7012:{name:"Tesla Cybertruck",hitbox:"Hybrid"},7052:{name:"Formula 1 2022",hitbox:"Plank"},7211:{name:"Mamba",hitbox:"Dominus"},7336:{name:"Nomad",hitbox:"Merc"},7337:{name:"NASCAR Next Gen Chevrolet Camaro",hitbox:"Dominus"},7338:{name:"NASCAR Next Gen Ford Mustang",hitbox:"Dominus"},7341:{name:"NASCAR Next Gen Toyota Camry",hitbox:"Dominus"},7343:{name:"007's Aston Martin DBS",hitbox:"Dominus"},7415:{name:"Batmobile (2022)",hitbox:"Dominus"},7477:{name:"Nomad GXT",hitbox:"Merc"},7512:{name:"Lamborghini Countach LPI 800-4",hitbox:"Dominus"},7532:{name:"Maestro",hitbox:"Dominus"},7593:{name:"Nissan Z Performance",hitbox:"Dominus"},7651:{name:"Redline",hitbox:"Breakout"},7696:{name:"Whiplash",hitbox:"Breakout"},7772:{name:"Ferrari 296 GTB",hitbox:"Dominus"},7815:{name:"Ford Bronco Raptor RLE",hitbox:"Merc"},7890:{name:"Fuse",hitbox:"Breakout"},7901:{name:"Fast & Furious Mazda RX-7",hitbox:"Breakout"},7947:{name:"Honda Civic Type R",hitbox:"Octane"},7948:{name:"Honda Civic Type R-LE",hitbox:"Octane"},7979:{name:"Stampede",hitbox:"Merc"},8006:{name:"Mako",hitbox:"Breakout"},8360:{name:"Emperor",hitbox:"Breakout"},8361:{name:"Emperor II",hitbox:"Breakout"},8383:{name:"Xentari",hitbox:"Octane"},8454:{name:"Admiral",hitbox:"Dominus"},8524:{name:"Bugatti Centodieci",hitbox:"Plank"},8565:{name:"Emperor II: Frozen",hitbox:"Breakout"},8566:{name:"Emperor II: Scorched",hitbox:"Breakout"},8669:{name:"Ace",hitbox:"Breakout"},8806:{name:"Volkswagen Golf GTI",hitbox:"Octane"},8807:{name:"Volkswagen Golf GTI RLE",hitbox:"Octane"},9053:{name:"Fast & Furious Dodge Charger SRT Hellcat",hitbox:"Dominus"},9084:{name:"Nissan Silvia",hitbox:"Hybrid"},9085:{name:"Nissan Silvia RLE",hitbox:"Hybrid"},9088:{name:"Porsche 911 Turbo",hitbox:"Dominus"},9089:{name:"Porsche 911 Turbo RLE",hitbox:"Dominus"},9140:{name:"Bumblebee",hitbox:"Dominus"},9357:{name:"Diesel",hitbox:"Breakout"},9388:{name:"Lightning McQueen",hitbox:"Dominus"},9427:{name:"Primo",hitbox:"Hybrid"},9894:{name:"Scorpion",hitbox:"Dominus"},10044:{name:"Beskar",hitbox:"Hybrid"},10094:{name:"Ford Mustang GTD",hitbox:"Dominus"},10440:{name:"Nissan Fairlady Z",hitbox:"Dominus"},10441:{name:"Nissan Fairlady Z RLE",hitbox:"Dominus"},10689:{name:"Behemoth",hitbox:"Merc"},10694:{name:"Lockjaw",hitbox:"Dominus"},10697:{name:"The Incredibile",hitbox:"Breakout"},10698:{name:"1966 Cadillac DeVille",hitbox:"Breakout"},10805:{name:"Nissan Skyline GT-R (R32)",hitbox:"Hybrid"},10817:{name:"Quadra Turbo-R",hitbox:"Breakout"},10822:{name:"McLaren Senna",hitbox:"Breakout"},10896:{name:"BMW 1 Series",hitbox:"Octane"},10897:{name:"BMW 1 Series RLE",hitbox:"Octane"},10900:{name:"Shokunin",hitbox:"Octane"},10901:{name:"Shokunin GXT",hitbox:"Octane"},11016:{name:"Porsche 911 GT3 RS",hitbox:"Dominus"},11038:{name:"Revolver",hitbox:"Breakout"},11095:{name:"Dodge Charger Daytona Scat Pack",hitbox:"Dominus"},11098:{name:"Turtle Van",hitbox:"Merc"},11138:{name:"Void Burn",hitbox:"Hybrid"},11141:{name:"Lamborghini Urus SE",hitbox:"Hybrid"},11314:{name:"Jeep Wrangler Rubicon",hitbox:"Merc"},11315:{name:"Ford Mustang Shelby GT500",hitbox:"Dominus"},11336:{name:"Dominus: Neon",hitbox:"Dominus"},11379:{name:"Ram 1500 RHO",hitbox:"Hybrid"},11394:{name:"Azura",hitbox:"Breakout"},11505:{name:"Breakout X",hitbox:"Breakout"},11534:{name:"BMW M3 (E30)",hitbox:"Dominus"},11603:{name:"Fennec ZR-F",hitbox:"Octane"},11677:{name:"Chevrolet Corvette ZR1",hitbox:"Breakout"},11736:{name:"Recoil AV",hitbox:"Merc"},11800:{name:"Megastar",hitbox:"Breakout"},11905:{name:"The Mystery Machine",hitbox:"Merc"},11932:{name:"Hearse",hitbox:"Hybrid"},11933:{name:"Porsche 918 Spyder",hitbox:"Breakout"},11941:{name:"Mercedes-AMG GT 63 S",hitbox:"Dominus"},11949:{name:"Pontiac Firebird",hitbox:"Breakout"},11950:{name:"Chevrolet Astro",hitbox:"Merc"},12142:{name:"Homer's Car",hitbox:"Dominus"},12173:{name:"Ferrari F40",hitbox:"Breakout"}},HC=zC;function uS(n){const e=HC[String(n)];return e?{name:e.name,hitboxType:e.hitbox}:null}function VC(n){if(!n)return null;const e={fov:n.fov,height:n.height,angle:n.angle,distance:n.distance,stiffness:n.stiffness,swivelSpeed:n.swivel_speed};return n.transition_speed!=null&&(e.transitionSpeed=n.transition_speed),e}const GC=2200,$C=!0,WC=!1,XC=.15,KC=10,qC=.1,YC=10,jC=.1,ZC=.15,JC=10;function il(n,e){if(n.length===0)return null;let t=0,i=n.length-1;if(e<=n[0].time)return n[0];if(e>=n[i].time)return n[i];for(;t>1;n[s].time<=e?t=s:i=s-1}return n[t]}class QC{position={x:0,y:0,z:0};rotation={x:0,y:0,z:0,w:1};velocity={x:0,y:0,z:0};angularVelocity={x:0,y:0,z:0};sleeping=!1;visible=!0}class eA{constructor(e,t,i){this.isBig=e,this.position=t,this.events=i}isAvailable=!0}class tA extends cS{constructor(e,t,i,s,a,r=null){super(),this.id=e,this.name=t,this.team=i,this.carName=s,this.hitboxType=a,this.cameraSettings=r}position={x:0,y:0,z:0};rotation={x:0,y:0,z:0,w:1};velocity={x:0,y:0,z:0};angularVelocity={x:0,y:0,z:0};sleeping=!1;steer=0;boost=0;isBoosting=!1;isSupersonic=!1;isKickoffReset=!1;isVisible=!0;isBallCam=!0}class dS extends cS{constructor(e,t={}){super(),this.raw=e,this.options=t,this._compile()}duration=0;playerList=[];frameTimes=[];rawStartTime=0;ball=new QC;players=new Map;boostPads=new Map;_currentTime=0;_ballTimeline=[];_playerTimelines={};_ballFlags=[];_playerFlags={};_playerCameraEvents={};_teams={};_timelineCompaction=null;_compile(){const e=this.raw.frame_data,t=this.raw.meta,i=e.metadata_frames,s=i[0]?.time??0;this.rawStartTime=s;const a=l=>Math.max(0,l-s);this.duration=i.length?a(i[i.length-1].time):0,this.frameTimes=i.map(l=>a(l.time));const r=new Map;t.team_zero.forEach(l=>r.set(this._idKey(l.remote_id),{info:l,team:0})),t.team_one.forEach(l=>r.set(this._idKey(l.remote_id),{info:l,team:1})),e.ball_data.frames.forEach((l,c)=>{if(l==="Empty"||!("Data"in l))return;const u=this._rbToKeyframe(l.Data.rigid_body,a(i[c]?.time??s),c);u&&this._ballTimeline.push(u)}),e.players.forEach(([l,c])=>{const u=this._idKey(l),d=r.get(u);let h=d?.info.name??null,f=d?.team??0;if(!h){for(const S of c.frames)if(S!=="Empty"&&"Data"in S&&S.Data.player_name){h=S.Data.player_name,S.Data.is_team_0!=null&&(f=S.Data.is_team_0?0:1);break}}h||(h=`Player_${u}`);const p=d?.info,g=p?.car_body_id!=null?uS(p.car_body_id):null,_=p?.car_body_name??g?.name??"Octane",m=p?.car_hitbox_family??g?.hitboxType??"Octane",v=[],y=[];c.frames.forEach((S,x)=>{const M=a(i[x]?.time??s);if(S==="Empty"||!("Data"in S))return;const C=this._rbToKeyframe(S.Data.rigid_body,M,x);C&&v.push(C);const w=S.Data.input?.steer;y.push({time:M,boost:BC(S.Data.boost_amount??0),isBoosting:!!S.Data.boost_active,present:!0,steer:w==null?0:Math.max(-1,Math.min(1,(w-128)/128))})});const b=VC(p?.camera_settings);this._playerTimelines[h]=v,this._playerFlags[h]=y,this._teams[h]=f,this.playerList.push({id:u,name:h,team:f,carName:_,hitboxType:m,cameraSettings:b}),this.players.set(h,new tA(u,h,f,_,m,b))});const o=new Map;this.playerList.forEach(l=>o.set(l.id,l.name));for(const[l,c]of this.raw.player_camera_events??[]){const u=o.get(this._idKey(l));u&&(this._playerCameraEvents[u]=c.map(d=>({time:a(i[d.frame]?.time??s),ballCam:d.ball_cam_active})))}this._preprocessMotionTimelines(),this._compileBoostPads(),this.seek(0)}_timelineProcessingOptions(){return{motionSmoothing:this.options.motionSmoothing??$C,smoothingBlendFactor:this.options.smoothingBlendFactor??XC,smoothingAnchorInterval:this.options.smoothingAnchorInterval??KC,timelineCompaction:this.options.timelineCompaction??WC,disableFrameFiltering:this.options.disableFrameFiltering??!1}}_preprocessMotionTimelines(){const e=this._timelineProcessingOptions();e.motionSmoothing&&this._applyVelocityBasedPositionCorrection(e),e.timelineCompaction&&this._applyTimelineCompaction(),e.disableFrameFiltering||this._filterInconsistentFrames()}_applyTimelineCompaction(){const e=this._buildTimelineCompaction();!e||e.gaps.length===0&&e.prematchEndTime===null||(this._timelineCompaction=e,this._ballTimeline=this._compactTimeline(this._ballTimeline,e),Object.entries(this._playerTimelines).forEach(([t,i])=>{this._playerTimelines[t]=this._compactTimeline(i,e)}),Object.entries(this._playerFlags).forEach(([t,i])=>{this._playerFlags[t]=this._compactTimeline(i,e)}),this.frameTimes=this.frameTimes.map(t=>this._compactTime(t,e)),this.duration=e.compactedDuration)}_buildTimelineCompaction(){if(this.frameTimes.length===0)return null;const e=this._detectPostGoalTimeGaps(),t=this._detectFirstKickoffGoTime(),i=t==null?null:sl(t,e),a=e.reduce((r,o)=>r+o.duration,0)+(i??0);return a<=0?null:{gaps:e,prematchEndTime:i,removedDuration:a,compactedDuration:Math.max(0,this.duration-a)}}_detectPostGoalTimeGaps(){const e=[];for(const t of this.raw.goal_events??[]){const i=t.frame;if(!Number.isInteger(i)||i<0||i>=this.frameTimes.length)continue;const s=this.frameTimes[i];for(let a=i+1;a10)break;const l=o-r;if(l>.3){e.push({beforeFrame:a-1,afterFrame:a,beforeTime:r,afterTime:o,duration:l});break}}}return e}_detectFirstKickoffGoTime(){const e=this.raw.frame_data.metadata_frames;let t=!1;for(let s=0;s0&&(t=!0),t&&a===0)return this.frameTimes[s]??null}const i=e.findIndex(s=>s.replicated_game_state_name===54);return i===-1?null:this.frameTimes[i]??null}_compactTimeline(e,t){const i=this._remapReplayGaps(e,t.gaps);return t.prematchEndTime===null?i:this._remapPrematch(i,t.prematchEndTime)}_remapReplayGaps(e,t){if(t.length===0)return e;const i=[];t.forEach((a,r)=>{const o=e.find(l=>l.time>=a.afterTime);o&&i.push({...o,time:sl(a.afterTime,t.slice(0,r+1))})});const s=e.filter(a=>!Ky(a.time,t)).map(a=>({...a,time:sl(a.time,t)}));for(const a of i){if(s.some(o=>Math.abs(o.time-a.time)<.001))continue;let r=s.findIndex(o=>o.time>a.time);r===-1&&(r=s.length),s.splice(r,0,a)}return s}_remapPrematch(e,t){let i=null;for(const a of e)if(a.timea.time>=t).map(a=>({...a,time:a.time-t}));return i&&(s.length===0||s[0].time>.001)&&s.unshift({...i,time:0}),s}_compactTime(e,t){const i=sl(e,t.gaps);return t.prematchEndTime===null?i:Math.max(0,i-t.prematchEndTime)}_applyVelocityBasedPositionCorrection(e){const t=i=>{if(i.length<3)return;let s=0;for(;s=i.length-1)return;let a={...i[s].position};for(let r=s+1;rqC){a={...l.position};continue}if(Xy(a,l.position)>YC){a={...l.position};continue}const u={x:(o.velocity.x+l.velocity.x)/2,y:(o.velocity.y+l.velocity.y)/2,z:(o.velocity.z+l.velocity.z)/2},d={x:a.x+u.x*c,y:a.y+u.y*c,z:a.z+u.z*c},h=(r-s)%e.smoothingAnchorInterval===0?.5:e.smoothingBlendFactor;a={x:d.x*(1-h)+l.position.x*h,y:d.y*(1-h)+l.position.y*h,z:d.z*(1-h)+l.position.z*h},l.position={...a}}};t(this._ballTimeline),Object.values(this._playerTimelines).forEach(t)}_filterInconsistentFrames(){this._ballTimeline=this._filterInconsistentTimeline(this._ballTimeline),Object.entries(this._playerTimelines).forEach(([e,t])=>{this._playerTimelines[e]=this._filterInconsistentTimeline(t)})}_filterInconsistentTimeline(e){if(e.length<2)return e;const t=[e[0]];let i=0;for(let s=1;s.001){const u=o*c,d=Xy(r.position,a.position),h=Math.abs(d-u)/u;if(Number.isFinite(h)&&h>ZC)continue}}t.push(a),i=s}return t}_compileBoostPads(){const e=new Map;(this.raw.boost_pad_events??[]).forEach(t=>{const i=t.kind==="Available"?!0:t.kind&&typeof t.kind=="object"&&"PickedUp"in t.kind?!1:null;if(i===null)return;const s=Math.max(0,t.time-this.rawStartTime);if(this._timelineCompaction&&this._isRemovedByTimelineCompaction(s))return;const a=this._timelineCompaction?this._compactTime(s,this._timelineCompaction):s,r=e.get(t.pad_id);r?r.push({time:a,available:i}):e.set(t.pad_id,[{time:a,available:i}])}),(this.raw.boost_pads??[]).forEach(t=>{const i=(t.pad_id?e.get(t.pad_id):void 0)??[];i.sort((s,a)=>s.time-a.time),this.boostPads.set(t.index,new eA(t.size==="Big",t.position,i))})}_rbToKeyframe(e,t,i){const s=Wf(e.location);return s?{time:t,frame:i,position:s,rotation:UC(e.rotation),velocity:Wf(e.linear_velocity)??{x:0,y:0,z:0},angularVelocity:Wf(e.angular_velocity),sleeping:!!e.sleeping}:null}_isRemovedByTimelineCompaction(e){const t=this._timelineCompaction;if(!t)return!1;if(Ky(e,t.gaps))return!0;const i=sl(e,t.gaps);return t.prematchEndTime!==null&&i=GC}const r=il(this._playerFlags[i]??[],e);r&&(s.boost=r.boost,s.isBoosting=r.isBoosting,s.steer=r.steer);const o=il(this._playerCameraEvents[i]??[],e);o&&o.ballCam!=null&&(s.isBallCam=o.ballCam);const l=this._playerTimelines[i]??[];s.isVisible=l.length>0&&e>=l[0].time-.001&&e<=l[l.length-1].time+1}for(const i of this.boostPads.values()){if(i.events.length===0)continue;const s=il(i.events,e);i.isAvailable=s&&s.time<=e?s.available:!0}}frameIndexAt(e){const t=this.frameTimes;if(t.length===0||e<=t[0])return 0;let i=0,s=t.length-1;if(e>=t[s])return s;for(;i>1;t[a]<=e?i=a:s=a-1}return i}getBall(){return this.ball}getPlayer(e){return this.players.get(e)}getPlayerById(e){for(const t of this.players.values())if(t.id===e)return t}getAllPlayers(){return Array.from(this.players.values())}getPlayerTeams(){return{...this._teams}}getGameTimeMap(){return[]}getCountdownEvents(){return[]}getPlayerStatsTimelines(){return{}}getGameEventTimeline(){return[]}getAdvancedStats(){return null}getEvents(){return[]}getEventsInRange(){return[]}getTextOverlaysAt(){return[]}getGamePhaseAt(){return null}}function Wy(n){return Math.sqrt(n.x*n.x+n.y*n.y+n.z*n.z)}function Xy(n,e){const t=e.x-n.x,i=e.y-n.y,s=e.z-n.z;return Math.sqrt(t*t+i*i+s*s)}function sl(n,e){let t=0;for(const i of e){if(n=i.afterTime){t+=i.duration;continue}return i.beforeTime-t}return n-t}function Ky(n,e){return e.some(t=>n>t.beforeTime&&n>8&255]+Cn[n>>16&255]+Cn[n>>24&255]+"-"+Cn[e&255]+Cn[e>>8&255]+"-"+Cn[e>>16&15|64]+Cn[e>>24&255]+"-"+Cn[t&63|128]+Cn[t>>8&255]+"-"+Cn[t>>16&255]+Cn[t>>24&255]+Cn[i&255]+Cn[i>>8&255]+Cn[i>>16&255]+Cn[i>>24&255]).toLowerCase()}function Je(n,e,t){return Math.max(e,Math.min(t,n))}function Pg(n,e){return(n%e+e)%e}function NA(n,e,t,i,s){return i+(n-e)*(s-i)/(t-e)}function UA(n,e,t){return n!==e?(t-n)/(e-n):0}function ql(n,e,t){return(1-t)*n+t*e}function BA(n,e,t,i){return ql(n,e,1-Math.exp(-t*i))}function zA(n,e=1){return e-Math.abs(Pg(n,e*2)-e)}function HA(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*(3-2*n))}function VA(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*n*(n*(n*6-15)+10))}function GA(n,e){return n+Math.floor(Math.random()*(e-n+1))}function $A(n,e){return n+Math.random()*(e-n)}function WA(n){return n*(.5-Math.random())}function XA(n){n!==void 0&&(qy=n);let e=qy+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function KA(n){return n*hr}function qA(n){return n*Uo}function YA(n){return(n&n-1)===0&&n!==0}function jA(n){return Math.pow(2,Math.ceil(Math.log(n)/Math.LN2))}function ZA(n){return Math.pow(2,Math.floor(Math.log(n)/Math.LN2))}function JA(n,e,t,i,s){const a=Math.cos,r=Math.sin,o=a(t/2),l=r(t/2),c=a((e+i)/2),u=r((e+i)/2),d=a((e-i)/2),h=r((e-i)/2),f=a((i-e)/2),p=r((i-e)/2);switch(s){case"XYX":n.set(o*u,l*d,l*h,o*c);break;case"YZY":n.set(l*h,o*u,l*d,o*c);break;case"ZXZ":n.set(l*d,l*h,o*u,o*c);break;case"XZX":n.set(o*u,l*p,l*f,o*c);break;case"YXY":n.set(l*f,o*u,l*p,o*c);break;case"ZYZ":n.set(l*p,l*f,o*u,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+s)}}function $n(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return n/4294967295;case Uint16Array:return n/65535;case Uint8Array:return n/255;case Int32Array:return Math.max(n/2147483647,-1);case Int16Array:return Math.max(n/32767,-1);case Int8Array:return Math.max(n/127,-1);default:throw new Error("Invalid component type.")}}function dt(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return Math.round(n*4294967295);case Uint16Array:return Math.round(n*65535);case Uint8Array:return Math.round(n*255);case Int32Array:return Math.round(n*2147483647);case Int16Array:return Math.round(n*32767);case Int8Array:return Math.round(n*127);default:throw new Error("Invalid component type.")}}const bt={DEG2RAD:hr,RAD2DEG:Uo,generateUUID:bi,clamp:Je,euclideanModulo:Pg,mapLinear:NA,inverseLerp:UA,lerp:ql,damp:BA,pingpong:zA,smoothstep:HA,smootherstep:VA,randInt:GA,randFloat:$A,randFloatSpread:WA,seededRandom:XA,degToRad:KA,radToDeg:qA,isPowerOfTwo:YA,ceilPowerOfTwo:jA,floorPowerOfTwo:ZA,setQuaternionFromProperEuler:JA,normalize:dt,denormalize:$n};class ne{constructor(e=0,t=0){ne.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,i=this.y,s=e.elements;return this.x=s[0]*t+s[3]*i+s[6],this.y=s[1]*t+s[4]*i+s[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Je(this.x,e.x,t.x),this.y=Je(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Je(this.x,e,t),this.y=Je(this.y,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Je(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Je(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),s=Math.sin(t),a=this.x-e.x,r=this.y-e.y;return this.x=a*i-r*s+e.x,this.y=a*s+r*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class ht{constructor(e=0,t=0,i=0,s=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=s}static slerpFlat(e,t,i,s,a,r,o){let l=i[s+0],c=i[s+1],u=i[s+2],d=i[s+3];const h=a[r+0],f=a[r+1],p=a[r+2],g=a[r+3];if(o===0){e[t+0]=l,e[t+1]=c,e[t+2]=u,e[t+3]=d;return}if(o===1){e[t+0]=h,e[t+1]=f,e[t+2]=p,e[t+3]=g;return}if(d!==g||l!==h||c!==f||u!==p){let _=1-o;const m=l*h+c*f+u*p+d*g,v=m>=0?1:-1,y=1-m*m;if(y>Number.EPSILON){const S=Math.sqrt(y),x=Math.atan2(S,m*v);_=Math.sin(_*x)/S,o=Math.sin(o*x)/S}const b=o*v;if(l=l*_+h*b,c=c*_+f*b,u=u*_+p*b,d=d*_+g*b,_===1-o){const S=1/Math.sqrt(l*l+c*c+u*u+d*d);l*=S,c*=S,u*=S,d*=S}}e[t]=l,e[t+1]=c,e[t+2]=u,e[t+3]=d}static multiplyQuaternionsFlat(e,t,i,s,a,r){const o=i[s],l=i[s+1],c=i[s+2],u=i[s+3],d=a[r],h=a[r+1],f=a[r+2],p=a[r+3];return e[t]=o*p+u*d+l*f-c*h,e[t+1]=l*p+u*h+c*d-o*f,e[t+2]=c*p+u*f+o*h-l*d,e[t+3]=u*p-o*d-l*h-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,i,s){return this._x=e,this._y=t,this._z=i,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const i=e._x,s=e._y,a=e._z,r=e._order,o=Math.cos,l=Math.sin,c=o(i/2),u=o(s/2),d=o(a/2),h=l(i/2),f=l(s/2),p=l(a/2);switch(r){case"XYZ":this._x=h*u*d+c*f*p,this._y=c*f*d-h*u*p,this._z=c*u*p+h*f*d,this._w=c*u*d-h*f*p;break;case"YXZ":this._x=h*u*d+c*f*p,this._y=c*f*d-h*u*p,this._z=c*u*p-h*f*d,this._w=c*u*d+h*f*p;break;case"ZXY":this._x=h*u*d-c*f*p,this._y=c*f*d+h*u*p,this._z=c*u*p+h*f*d,this._w=c*u*d-h*f*p;break;case"ZYX":this._x=h*u*d-c*f*p,this._y=c*f*d+h*u*p,this._z=c*u*p-h*f*d,this._w=c*u*d+h*f*p;break;case"YZX":this._x=h*u*d+c*f*p,this._y=c*f*d+h*u*p,this._z=c*u*p-h*f*d,this._w=c*u*d-h*f*p;break;case"XZY":this._x=h*u*d-c*f*p,this._y=c*f*d-h*u*p,this._z=c*u*p+h*f*d,this._w=c*u*d+h*f*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+r)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const i=t/2,s=Math.sin(i);return this._x=e.x*s,this._y=e.y*s,this._z=e.z*s,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],s=t[4],a=t[8],r=t[1],o=t[5],l=t[9],c=t[2],u=t[6],d=t[10],h=i+o+d;if(h>0){const f=.5/Math.sqrt(h+1);this._w=.25/f,this._x=(u-l)*f,this._y=(a-c)*f,this._z=(r-s)*f}else if(i>o&&i>d){const f=2*Math.sqrt(1+i-o-d);this._w=(u-l)/f,this._x=.25*f,this._y=(s+r)/f,this._z=(a+c)/f}else if(o>d){const f=2*Math.sqrt(1+o-i-d);this._w=(a-c)/f,this._x=(s+r)/f,this._y=.25*f,this._z=(l+u)/f}else{const f=2*Math.sqrt(1+d-i-o);this._w=(r-s)/f,this._x=(a+c)/f,this._y=(l+u)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<1e-8?(i=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Je(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(i===0)return this;const s=Math.min(1,t/i);return this.slerp(e,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const i=e._x,s=e._y,a=e._z,r=e._w,o=t._x,l=t._y,c=t._z,u=t._w;return this._x=i*u+r*o+s*c-a*l,this._y=s*u+r*l+a*o-i*c,this._z=a*u+r*c+i*l-s*o,this._w=r*u-i*o-s*l-a*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const i=this._x,s=this._y,a=this._z,r=this._w;let o=r*e._w+i*e._x+s*e._y+a*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=r,this._x=i,this._y=s,this._z=a,this;const l=1-o*o;if(l<=Number.EPSILON){const f=1-t;return this._w=f*r+t*this._w,this._x=f*i+t*this._x,this._y=f*s+t*this._y,this._z=f*a+t*this._z,this.normalize(),this}const c=Math.sqrt(l),u=Math.atan2(c,o),d=Math.sin((1-t)*u)/c,h=Math.sin(t*u)/c;return this._w=r*d+this._w*h,this._x=i*d+this._x*h,this._y=s*d+this._y*h,this._z=a*d+this._z*h,this._onChangeCallback(),this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),s=Math.sqrt(1-i),a=Math.sqrt(i);return this.set(s*Math.sin(e),s*Math.cos(e),a*Math.sin(t),a*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class T{constructor(e=0,t=0,i=0){T.prototype.isVector3=!0,this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Yy.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Yy.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,s=this.z,a=e.elements;return this.x=a[0]*t+a[3]*i+a[6]*s,this.y=a[1]*t+a[4]*i+a[7]*s,this.z=a[2]*t+a[5]*i+a[8]*s,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,s=this.z,a=e.elements,r=1/(a[3]*t+a[7]*i+a[11]*s+a[15]);return this.x=(a[0]*t+a[4]*i+a[8]*s+a[12])*r,this.y=(a[1]*t+a[5]*i+a[9]*s+a[13])*r,this.z=(a[2]*t+a[6]*i+a[10]*s+a[14])*r,this}applyQuaternion(e){const t=this.x,i=this.y,s=this.z,a=e.x,r=e.y,o=e.z,l=e.w,c=2*(r*s-o*i),u=2*(o*t-a*s),d=2*(a*i-r*t);return this.x=t+l*c+r*d-o*u,this.y=i+l*u+o*c-a*d,this.z=s+l*d+a*u-r*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,i=this.y,s=this.z,a=e.elements;return this.x=a[0]*t+a[4]*i+a[8]*s,this.y=a[1]*t+a[5]*i+a[9]*s,this.z=a[2]*t+a[6]*i+a[10]*s,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Je(this.x,e.x,t.x),this.y=Je(this.y,e.y,t.y),this.z=Je(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Je(this.x,e,t),this.y=Je(this.y,e,t),this.z=Je(this.z,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Je(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const i=e.x,s=e.y,a=e.z,r=t.x,o=t.y,l=t.z;return this.x=s*l-a*o,this.y=a*r-i*l,this.z=i*o-s*r,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return Xf.copy(this).projectOnVector(e),this.sub(Xf)}reflect(e){return this.sub(Xf.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Je(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,s=this.z-e.z;return t*t+i*i+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){const s=Math.sin(t)*e;return this.x=s*Math.sin(i),this.y=Math.cos(t)*e,this.z=s*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),s=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=s,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(e),this.y=t,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Xf=new T,Yy=new ht;class rt{constructor(e,t,i,s,a,r,o,l,c){rt.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,s,a,r,o,l,c)}set(e,t,i,s,a,r,o,l,c){const u=this.elements;return u[0]=e,u[1]=s,u[2]=o,u[3]=t,u[4]=a,u[5]=l,u[6]=i,u[7]=r,u[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,s=t.elements,a=this.elements,r=i[0],o=i[3],l=i[6],c=i[1],u=i[4],d=i[7],h=i[2],f=i[5],p=i[8],g=s[0],_=s[3],m=s[6],v=s[1],y=s[4],b=s[7],S=s[2],x=s[5],M=s[8];return a[0]=r*g+o*v+l*S,a[3]=r*_+o*y+l*x,a[6]=r*m+o*b+l*M,a[1]=c*g+u*v+d*S,a[4]=c*_+u*y+d*x,a[7]=c*m+u*b+d*M,a[2]=h*g+f*v+p*S,a[5]=h*_+f*y+p*x,a[8]=h*m+f*b+p*M,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[1],s=e[2],a=e[3],r=e[4],o=e[5],l=e[6],c=e[7],u=e[8];return t*r*u-t*o*c-i*a*u+i*o*l+s*a*c-s*r*l}invert(){const e=this.elements,t=e[0],i=e[1],s=e[2],a=e[3],r=e[4],o=e[5],l=e[6],c=e[7],u=e[8],d=u*r-o*c,h=o*l-u*a,f=c*a-r*l,p=t*d+i*h+s*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);const g=1/p;return e[0]=d*g,e[1]=(s*c-u*i)*g,e[2]=(o*i-s*r)*g,e[3]=h*g,e[4]=(u*t-s*l)*g,e[5]=(s*a-o*t)*g,e[6]=f*g,e[7]=(i*l-c*t)*g,e[8]=(r*t-i*a)*g,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,s,a,r,o){const l=Math.cos(a),c=Math.sin(a);return this.set(i*l,i*c,-i*(l*r+c*o)+r+e,-s*c,s*l,-s*(-c*r+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(Kf.makeScale(e,t)),this}rotate(e){return this.premultiply(Kf.makeRotation(-e)),this}translate(e,t){return this.premultiply(Kf.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,i=e.elements;for(let s=0;s<9;s++)if(t[s]!==i[s])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const Kf=new rt;function QS(n){for(let e=n.length-1;e>=0;--e)if(n[e]>=65535)return!0;return!1}const QA={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function lo(n,e){return new QA[n](e)}function uc(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}function eT(){const n=uc("canvas");return n.style.display="block",n}const jy={};function dc(n){n in jy||(jy[n]=!0,console.warn(n))}function eR(n,e,t){return new Promise(function(i,s){function a(){switch(n.clientWaitSync(e,n.SYNC_FLUSH_COMMANDS_BIT,0)){case n.WAIT_FAILED:s();break;case n.TIMEOUT_EXPIRED:setTimeout(a,t);break;default:i()}}setTimeout(a,t)})}const Zy=new rt().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Jy=new rt().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function tR(){const n={enabled:!0,workingColorSpace:wn,spaces:{},convert:function(s,a,r){return this.enabled===!1||a===r||!a||!r||(this.spaces[a].transfer===It&&(s.r=Gs(s.r),s.g=Gs(s.g),s.b=Gs(s.b)),this.spaces[a].primaries!==this.spaces[r].primaries&&(s.applyMatrix3(this.spaces[a].toXYZ),s.applyMatrix3(this.spaces[r].fromXYZ)),this.spaces[r].transfer===It&&(s.r=mo(s.r),s.g=mo(s.g),s.b=mo(s.b))),s},workingToColorSpace:function(s,a){return this.convert(s,this.workingColorSpace,a)},colorSpaceToWorking:function(s,a){return this.convert(s,a,this.workingColorSpace)},getPrimaries:function(s){return this.spaces[s].primaries},getTransfer:function(s){return s===Bs?lc:this.spaces[s].transfer},getToneMappingMode:function(s){return this.spaces[s].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(s,a=this.workingColorSpace){return s.fromArray(this.spaces[a].luminanceCoefficients)},define:function(s){Object.assign(this.spaces,s)},_getMatrix:function(s,a,r){return s.copy(this.spaces[a].toXYZ).multiply(this.spaces[r].fromXYZ)},_getDrawingBufferColorSpace:function(s){return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(s=this.workingColorSpace){return this.spaces[s].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(s,a){return dc("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),n.workingToColorSpace(s,a)},toWorkingColorSpace:function(s,a){return dc("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),n.colorSpaceToWorking(s,a)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],i=[.3127,.329];return n.define({[wn]:{primaries:e,whitePoint:i,transfer:lc,toXYZ:Zy,fromXYZ:Jy,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:yt},outputColorSpaceConfig:{drawingBufferColorSpace:yt}},[yt]:{primaries:e,whitePoint:i,transfer:It,toXYZ:Zy,fromXYZ:Jy,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:yt}}}),n}const ot=tR();function Gs(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function mo(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}let Rr;class tT{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{Rr===void 0&&(Rr=uc("canvas")),Rr.width=e.width,Rr.height=e.height;const s=Rr.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),i=Rr}return i.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=uc("canvas");t.width=e.width,t.height=e.height;const i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const s=i.getImageData(0,0,e.width,e.height),a=s.data;for(let r=0;r1),this.pmremVersion=0}get width(){return this.source.getSize(Yf).x}get height(){return this.source.getSize(Yf).y}get depth(){return this.source.getSize(Yf).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const i=e[t];if(i===void 0){console.warn(`THREE.Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){console.warn(`THREE.Texture.setValues(): property '${t}' does not exist.`);continue}s&&i&&s.isVector2&&i.isVector2||s&&i&&s.isVector3&&i.isVector3||s&&i&&s.isMatrix3&&i.isMatrix3?s.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),t||(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==Kh)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case xs:e.x=e.x-Math.floor(e.x);break;case Wn:e.x=e.x<0?0:1;break;case Io:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case xs:e.y=e.y-Math.floor(e.y);break;case Wn:e.y=e.y<0?0:1;break;case Io:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}zt.DEFAULT_IMAGE=null;zt.DEFAULT_MAPPING=Kh;zt.DEFAULT_ANISOTROPY=1;class Ye{constructor(e=0,t=0,i=0,s=1){Ye.prototype.isVector4=!0,this.x=e,this.y=t,this.z=i,this.w=s}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,s=this.z,a=this.w,r=e.elements;return this.x=r[0]*t+r[4]*i+r[8]*s+r[12]*a,this.y=r[1]*t+r[5]*i+r[9]*s+r[13]*a,this.z=r[2]*t+r[6]*i+r[10]*s+r[14]*a,this.w=r[3]*t+r[7]*i+r[11]*s+r[15]*a,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,i,s,a;const l=e.elements,c=l[0],u=l[4],d=l[8],h=l[1],f=l[5],p=l[9],g=l[2],_=l[6],m=l[10];if(Math.abs(u-h)<.01&&Math.abs(d-g)<.01&&Math.abs(p-_)<.01){if(Math.abs(u+h)<.1&&Math.abs(d+g)<.1&&Math.abs(p+_)<.1&&Math.abs(c+f+m-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const y=(c+1)/2,b=(f+1)/2,S=(m+1)/2,x=(u+h)/4,M=(d+g)/4,C=(p+_)/4;return y>b&&y>S?y<.01?(i=0,s=.707106781,a=.707106781):(i=Math.sqrt(y),s=x/i,a=M/i):b>S?b<.01?(i=.707106781,s=0,a=.707106781):(s=Math.sqrt(b),i=x/s,a=C/s):S<.01?(i=.707106781,s=.707106781,a=0):(a=Math.sqrt(S),i=M/a,s=C/a),this.set(i,s,a,t),this}let v=Math.sqrt((_-p)*(_-p)+(d-g)*(d-g)+(h-u)*(h-u));return Math.abs(v)<.001&&(v=1),this.x=(_-p)/v,this.y=(d-g)/v,this.z=(h-u)/v,this.w=Math.acos((c+f+m-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Je(this.x,e.x,t.x),this.y=Je(this.y,e.y,t.y),this.z=Je(this.z,e.z,t.z),this.w=Je(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Je(this.x,e,t),this.y=Je(this.y,e,t),this.z=Je(this.z,e,t),this.w=Je(this.w,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Je(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class Ig extends Ts{constructor(e=1,t=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Gt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},i),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=i.depth,this.scissor=new Ye(0,0,e,t),this.scissorTest=!1,this.viewport=new Ye(0,0,e,t);const s={width:e,height:t,depth:i.depth},a=new zt(s);this.textures=[];const r=i.count;for(let o=0;o1;this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,i=e.textures.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Ui),Ui.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(al),Hc.subVectors(this.max,al),Pr.subVectors(e.a,al),Ir.subVectors(e.b,al),Lr.subVectors(e.c,al),js.subVectors(Ir,Pr),Zs.subVectors(Lr,Ir),Ea.subVectors(Pr,Lr);let t=[0,-js.z,js.y,0,-Zs.z,Zs.y,0,-Ea.z,Ea.y,js.z,0,-js.x,Zs.z,0,-Zs.x,Ea.z,0,-Ea.x,-js.y,js.x,0,-Zs.y,Zs.x,0,-Ea.y,Ea.x,0];return!jf(t,Pr,Ir,Lr,Hc)||(t=[1,0,0,0,1,0,0,0,1],!jf(t,Pr,Ir,Lr,Hc))?!1:(Vc.crossVectors(js,Zs),t=[Vc.x,Vc.y,Vc.z],jf(t,Pr,Ir,Lr,Hc))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Ui).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Ui).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Es[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Es[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Es[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Es[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Es[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Es[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Es[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Es[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Es),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const Es=[new T,new T,new T,new T,new T,new T,new T,new T],Ui=new T,zc=new bn,Pr=new T,Ir=new T,Lr=new T,js=new T,Zs=new T,Ea=new T,al=new T,Hc=new T,Vc=new T,Ca=new T;function jf(n,e,t,i,s){for(let a=0,r=n.length-3;a<=r;a+=3){Ca.fromArray(n,a);const o=s.x*Math.abs(Ca.x)+s.y*Math.abs(Ca.y)+s.z*Math.abs(Ca.z),l=e.dot(Ca),c=t.dot(Ca),u=i.dot(Ca);if(Math.max(-Math.max(l,c,u),Math.min(l,c,u))>o)return!1}return!0}const rR=new bn,rl=new T,Zf=new T;class xn{constructor(e=new T,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const i=this.center;t!==void 0?i.copy(t):rR.setFromPoints(e).getCenter(i);let s=0;for(let a=0,r=e.length;athis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;rl.subVectors(e,this.center);const t=rl.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),s=(i-this.radius)*.5;this.center.addScaledVector(rl,s/i),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(Zf.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(rl.copy(e.center).add(Zf)),this.expandByPoint(rl.copy(e.center).sub(Zf))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}const Cs=new T,Jf=new T,Gc=new T,Js=new T,Qf=new T,$c=new T,ep=new T;class Tr{constructor(e=new T,t=new T(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Cs)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Cs.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Cs.copy(this.origin).addScaledVector(this.direction,t),Cs.distanceToSquared(e))}distanceSqToSegment(e,t,i,s){Jf.copy(e).add(t).multiplyScalar(.5),Gc.copy(t).sub(e).normalize(),Js.copy(this.origin).sub(Jf);const a=e.distanceTo(t)*.5,r=-this.direction.dot(Gc),o=Js.dot(this.direction),l=-Js.dot(Gc),c=Js.lengthSq(),u=Math.abs(1-r*r);let d,h,f,p;if(u>0)if(d=r*l-o,h=r*o-l,p=a*u,d>=0)if(h>=-p)if(h<=p){const g=1/u;d*=g,h*=g,f=d*(d+r*h+2*o)+h*(r*d+h+2*l)+c}else h=a,d=Math.max(0,-(r*h+o)),f=-d*d+h*(h+2*l)+c;else h=-a,d=Math.max(0,-(r*h+o)),f=-d*d+h*(h+2*l)+c;else h<=-p?(d=Math.max(0,-(-r*a+o)),h=d>0?-a:Math.min(Math.max(-a,-l),a),f=-d*d+h*(h+2*l)+c):h<=p?(d=0,h=Math.min(Math.max(-a,-l),a),f=h*(h+2*l)+c):(d=Math.max(0,-(r*a+o)),h=d>0?a:Math.min(Math.max(-a,-l),a),f=-d*d+h*(h+2*l)+c);else h=r>0?-a:a,d=Math.max(0,-(r*h+o)),f=-d*d+h*(h+2*l)+c;return i&&i.copy(this.origin).addScaledVector(this.direction,d),s&&s.copy(Jf).addScaledVector(Gc,h),f}intersectSphere(e,t){Cs.subVectors(e.center,this.origin);const i=Cs.dot(this.direction),s=Cs.dot(Cs)-i*i,a=e.radius*e.radius;if(s>a)return null;const r=Math.sqrt(a-s),o=i-r,l=i+r;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,s,a,r,o,l;const c=1/this.direction.x,u=1/this.direction.y,d=1/this.direction.z,h=this.origin;return c>=0?(i=(e.min.x-h.x)*c,s=(e.max.x-h.x)*c):(i=(e.max.x-h.x)*c,s=(e.min.x-h.x)*c),u>=0?(a=(e.min.y-h.y)*u,r=(e.max.y-h.y)*u):(a=(e.max.y-h.y)*u,r=(e.min.y-h.y)*u),i>r||a>s||((a>i||isNaN(i))&&(i=a),(r=0?(o=(e.min.z-h.z)*d,l=(e.max.z-h.z)*d):(o=(e.max.z-h.z)*d,l=(e.min.z-h.z)*d),i>l||o>s)||((o>i||i!==i)&&(i=o),(l=0?i:s,t)}intersectsBox(e){return this.intersectBox(e,Cs)!==null}intersectTriangle(e,t,i,s,a){Qf.subVectors(t,e),$c.subVectors(i,e),ep.crossVectors(Qf,$c);let r=this.direction.dot(ep),o;if(r>0){if(s)return null;o=1}else if(r<0)o=-1,r=-r;else return null;Js.subVectors(this.origin,e);const l=o*this.direction.dot($c.crossVectors(Js,$c));if(l<0)return null;const c=o*this.direction.dot(Qf.cross(Js));if(c<0||l+c>r)return null;const u=-o*Js.dot(ep);return u<0?null:this.at(u/r,a)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Ee{constructor(e,t,i,s,a,r,o,l,c,u,d,h,f,p,g,_){Ee.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,i,s,a,r,o,l,c,u,d,h,f,p,g,_)}set(e,t,i,s,a,r,o,l,c,u,d,h,f,p,g,_){const m=this.elements;return m[0]=e,m[4]=t,m[8]=i,m[12]=s,m[1]=a,m[5]=r,m[9]=o,m[13]=l,m[2]=c,m[6]=u,m[10]=d,m[14]=h,m[3]=f,m[7]=p,m[11]=g,m[15]=_,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Ee().fromArray(this.elements)}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(e){const t=this.elements,i=e.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,i){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(e,t,i){return this.set(e.x,t.x,i.x,0,e.y,t.y,i.y,0,e.z,t.z,i.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,i=e.elements,s=1/kr.setFromMatrixColumn(e,0).length(),a=1/kr.setFromMatrixColumn(e,1).length(),r=1/kr.setFromMatrixColumn(e,2).length();return t[0]=i[0]*s,t[1]=i[1]*s,t[2]=i[2]*s,t[3]=0,t[4]=i[4]*a,t[5]=i[5]*a,t[6]=i[6]*a,t[7]=0,t[8]=i[8]*r,t[9]=i[9]*r,t[10]=i[10]*r,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,i=e.x,s=e.y,a=e.z,r=Math.cos(i),o=Math.sin(i),l=Math.cos(s),c=Math.sin(s),u=Math.cos(a),d=Math.sin(a);if(e.order==="XYZ"){const h=r*u,f=r*d,p=o*u,g=o*d;t[0]=l*u,t[4]=-l*d,t[8]=c,t[1]=f+p*c,t[5]=h-g*c,t[9]=-o*l,t[2]=g-h*c,t[6]=p+f*c,t[10]=r*l}else if(e.order==="YXZ"){const h=l*u,f=l*d,p=c*u,g=c*d;t[0]=h+g*o,t[4]=p*o-f,t[8]=r*c,t[1]=r*d,t[5]=r*u,t[9]=-o,t[2]=f*o-p,t[6]=g+h*o,t[10]=r*l}else if(e.order==="ZXY"){const h=l*u,f=l*d,p=c*u,g=c*d;t[0]=h-g*o,t[4]=-r*d,t[8]=p+f*o,t[1]=f+p*o,t[5]=r*u,t[9]=g-h*o,t[2]=-r*c,t[6]=o,t[10]=r*l}else if(e.order==="ZYX"){const h=r*u,f=r*d,p=o*u,g=o*d;t[0]=l*u,t[4]=p*c-f,t[8]=h*c+g,t[1]=l*d,t[5]=g*c+h,t[9]=f*c-p,t[2]=-c,t[6]=o*l,t[10]=r*l}else if(e.order==="YZX"){const h=r*l,f=r*c,p=o*l,g=o*c;t[0]=l*u,t[4]=g-h*d,t[8]=p*d+f,t[1]=d,t[5]=r*u,t[9]=-o*u,t[2]=-c*u,t[6]=f*d+p,t[10]=h-g*d}else if(e.order==="XZY"){const h=r*l,f=r*c,p=o*l,g=o*c;t[0]=l*u,t[4]=-d,t[8]=c*u,t[1]=h*d+g,t[5]=r*u,t[9]=f*d-p,t[2]=p*d-f,t[6]=o*u,t[10]=g*d+h}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(oR,e,lR)}lookAt(e,t,i){const s=this.elements;return fi.subVectors(e,t),fi.lengthSq()===0&&(fi.z=1),fi.normalize(),Qs.crossVectors(i,fi),Qs.lengthSq()===0&&(Math.abs(i.z)===1?fi.x+=1e-4:fi.z+=1e-4,fi.normalize(),Qs.crossVectors(i,fi)),Qs.normalize(),Wc.crossVectors(fi,Qs),s[0]=Qs.x,s[4]=Wc.x,s[8]=fi.x,s[1]=Qs.y,s[5]=Wc.y,s[9]=fi.y,s[2]=Qs.z,s[6]=Wc.z,s[10]=fi.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,s=t.elements,a=this.elements,r=i[0],o=i[4],l=i[8],c=i[12],u=i[1],d=i[5],h=i[9],f=i[13],p=i[2],g=i[6],_=i[10],m=i[14],v=i[3],y=i[7],b=i[11],S=i[15],x=s[0],M=s[4],C=s[8],w=s[12],E=s[1],R=s[5],L=s[9],O=s[13],D=s[2],U=s[6],F=s[10],W=s[14],H=s[3],ie=s[7],le=s[11],me=s[15];return a[0]=r*x+o*E+l*D+c*H,a[4]=r*M+o*R+l*U+c*ie,a[8]=r*C+o*L+l*F+c*le,a[12]=r*w+o*O+l*W+c*me,a[1]=u*x+d*E+h*D+f*H,a[5]=u*M+d*R+h*U+f*ie,a[9]=u*C+d*L+h*F+f*le,a[13]=u*w+d*O+h*W+f*me,a[2]=p*x+g*E+_*D+m*H,a[6]=p*M+g*R+_*U+m*ie,a[10]=p*C+g*L+_*F+m*le,a[14]=p*w+g*O+_*W+m*me,a[3]=v*x+y*E+b*D+S*H,a[7]=v*M+y*R+b*U+S*ie,a[11]=v*C+y*L+b*F+S*le,a[15]=v*w+y*O+b*W+S*me,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[4],s=e[8],a=e[12],r=e[1],o=e[5],l=e[9],c=e[13],u=e[2],d=e[6],h=e[10],f=e[14],p=e[3],g=e[7],_=e[11],m=e[15];return p*(+a*l*d-s*c*d-a*o*h+i*c*h+s*o*f-i*l*f)+g*(+t*l*f-t*c*h+a*r*h-s*r*f+s*c*u-a*l*u)+_*(+t*c*d-t*o*f-a*r*d+i*r*f+a*o*u-i*c*u)+m*(-s*o*u-t*l*d+t*o*h+s*r*d-i*r*h+i*l*u)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,i){const s=this.elements;return e.isVector3?(s[12]=e.x,s[13]=e.y,s[14]=e.z):(s[12]=e,s[13]=t,s[14]=i),this}invert(){const e=this.elements,t=e[0],i=e[1],s=e[2],a=e[3],r=e[4],o=e[5],l=e[6],c=e[7],u=e[8],d=e[9],h=e[10],f=e[11],p=e[12],g=e[13],_=e[14],m=e[15],v=d*_*c-g*h*c+g*l*f-o*_*f-d*l*m+o*h*m,y=p*h*c-u*_*c-p*l*f+r*_*f+u*l*m-r*h*m,b=u*g*c-p*d*c+p*o*f-r*g*f-u*o*m+r*d*m,S=p*d*l-u*g*l-p*o*h+r*g*h+u*o*_-r*d*_,x=t*v+i*y+s*b+a*S;if(x===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const M=1/x;return e[0]=v*M,e[1]=(g*h*a-d*_*a-g*s*f+i*_*f+d*s*m-i*h*m)*M,e[2]=(o*_*a-g*l*a+g*s*c-i*_*c-o*s*m+i*l*m)*M,e[3]=(d*l*a-o*h*a-d*s*c+i*h*c+o*s*f-i*l*f)*M,e[4]=y*M,e[5]=(u*_*a-p*h*a+p*s*f-t*_*f-u*s*m+t*h*m)*M,e[6]=(p*l*a-r*_*a-p*s*c+t*_*c+r*s*m-t*l*m)*M,e[7]=(r*h*a-u*l*a+u*s*c-t*h*c-r*s*f+t*l*f)*M,e[8]=b*M,e[9]=(p*d*a-u*g*a-p*i*f+t*g*f+u*i*m-t*d*m)*M,e[10]=(r*g*a-p*o*a+p*i*c-t*g*c-r*i*m+t*o*m)*M,e[11]=(u*o*a-r*d*a-u*i*c+t*d*c+r*i*f-t*o*f)*M,e[12]=S*M,e[13]=(u*g*s-p*d*s+p*i*h-t*g*h-u*i*_+t*d*_)*M,e[14]=(p*o*s-r*g*s-p*i*l+t*g*l+r*i*_-t*o*_)*M,e[15]=(r*d*s-u*o*s+u*i*l-t*d*l-r*i*h+t*o*h)*M,this}scale(e){const t=this.elements,i=e.x,s=e.y,a=e.z;return t[0]*=i,t[4]*=s,t[8]*=a,t[1]*=i,t[5]*=s,t[9]*=a,t[2]*=i,t[6]*=s,t[10]*=a,t[3]*=i,t[7]*=s,t[11]*=a,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],s=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,s))}makeTranslation(e,t,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const i=Math.cos(t),s=Math.sin(t),a=1-i,r=e.x,o=e.y,l=e.z,c=a*r,u=a*o;return this.set(c*r+i,c*o-s*l,c*l+s*o,0,c*o+s*l,u*o+i,u*l-s*r,0,c*l-s*o,u*l+s*r,a*l*l+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,s,a,r){return this.set(1,i,a,0,e,1,r,0,t,s,1,0,0,0,0,1),this}compose(e,t,i){const s=this.elements,a=t._x,r=t._y,o=t._z,l=t._w,c=a+a,u=r+r,d=o+o,h=a*c,f=a*u,p=a*d,g=r*u,_=r*d,m=o*d,v=l*c,y=l*u,b=l*d,S=i.x,x=i.y,M=i.z;return s[0]=(1-(g+m))*S,s[1]=(f+b)*S,s[2]=(p-y)*S,s[3]=0,s[4]=(f-b)*x,s[5]=(1-(h+m))*x,s[6]=(_+v)*x,s[7]=0,s[8]=(p+y)*M,s[9]=(_-v)*M,s[10]=(1-(h+g))*M,s[11]=0,s[12]=e.x,s[13]=e.y,s[14]=e.z,s[15]=1,this}decompose(e,t,i){const s=this.elements;let a=kr.set(s[0],s[1],s[2]).length();const r=kr.set(s[4],s[5],s[6]).length(),o=kr.set(s[8],s[9],s[10]).length();this.determinant()<0&&(a=-a),e.x=s[12],e.y=s[13],e.z=s[14],Bi.copy(this);const c=1/a,u=1/r,d=1/o;return Bi.elements[0]*=c,Bi.elements[1]*=c,Bi.elements[2]*=c,Bi.elements[4]*=u,Bi.elements[5]*=u,Bi.elements[6]*=u,Bi.elements[8]*=d,Bi.elements[9]*=d,Bi.elements[10]*=d,t.setFromRotationMatrix(Bi),i.x=a,i.y=r,i.z=o,this}makePerspective(e,t,i,s,a,r,o=yi,l=!1){const c=this.elements,u=2*a/(t-e),d=2*a/(i-s),h=(t+e)/(t-e),f=(i+s)/(i-s);let p,g;if(l)p=a/(r-a),g=r*a/(r-a);else if(o===yi)p=-(r+a)/(r-a),g=-2*r*a/(r-a);else if(o===No)p=-r/(r-a),g=-r*a/(r-a);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return c[0]=u,c[4]=0,c[8]=h,c[12]=0,c[1]=0,c[5]=d,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=g,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,i,s,a,r,o=yi,l=!1){const c=this.elements,u=2/(t-e),d=2/(i-s),h=-(t+e)/(t-e),f=-(i+s)/(i-s);let p,g;if(l)p=1/(r-a),g=r/(r-a);else if(o===yi)p=-2/(r-a),g=-(r+a)/(r-a);else if(o===No)p=-1/(r-a),g=-a/(r-a);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return c[0]=u,c[4]=0,c[8]=0,c[12]=h,c[1]=0,c[5]=d,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=p,c[14]=g,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const t=this.elements,i=e.elements;for(let s=0;s<16;s++)if(t[s]!==i[s])return!1;return!0}fromArray(e,t=0){for(let i=0;i<16;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],e}}const kr=new T,Bi=new Ee,oR=new T(0,0,0),lR=new T(1,1,1),Qs=new T,Wc=new T,fi=new T,Qy=new Ee,e0=new ht;class rn{constructor(e=0,t=0,i=0,s=rn.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=s}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,i,s=this._order){return this._x=e,this._y=t,this._z=i,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,i=!0){const s=e.elements,a=s[0],r=s[4],o=s[8],l=s[1],c=s[5],u=s[9],d=s[2],h=s[6],f=s[10];switch(t){case"XYZ":this._y=Math.asin(Je(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,f),this._z=Math.atan2(-r,a)):(this._x=Math.atan2(h,c),this._z=0);break;case"YXZ":this._x=Math.asin(-Je(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-d,a),this._z=0);break;case"ZXY":this._x=Math.asin(Je(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-d,f),this._z=Math.atan2(-r,c)):(this._y=0,this._z=Math.atan2(l,a));break;case"ZYX":this._y=Math.asin(-Je(d,-1,1)),Math.abs(d)<.9999999?(this._x=Math.atan2(h,f),this._z=Math.atan2(l,a)):(this._x=0,this._z=Math.atan2(-r,c));break;case"YZX":this._z=Math.asin(Je(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-u,c),this._y=Math.atan2(-d,a)):(this._x=0,this._y=Math.atan2(o,f));break;case"XZY":this._z=Math.asin(-Je(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(h,c),this._y=Math.atan2(o,a)):(this._x=Math.atan2(-u,f),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,i===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return Qy.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Qy,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return e0.setFromEuler(this),this.setFromQuaternion(e0,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}rn.DEFAULT_ORDER="XYZ";class af{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let i=0;i0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(s.matrixAutoUpdate=!1),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),s.instanceInfo=this._instanceInfo.map(o=>({...o})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(e),s.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(s.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(s.boundingBox=this.boundingBox.toJSON()));function a(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=a(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const l=o.shapes;if(Array.isArray(l))for(let c=0,u=l.length;c0){s.children=[];for(let o=0;o0){s.animations=[];for(let o=0;o0&&(i.geometries=o),l.length>0&&(i.materials=l),c.length>0&&(i.textures=c),u.length>0&&(i.images=u),d.length>0&&(i.shapes=d),h.length>0&&(i.skeletons=h),f.length>0&&(i.animations=f),p.length>0&&(i.nodes=p)}return i.object=s,i;function r(o){const l=[];for(const c in o){const u=o[c];delete u.metadata,l.push(u)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let i=0;i0?s.multiplyScalar(1/Math.sqrt(a)):s.set(0,0,0)}static getBarycoord(e,t,i,s,a){zi.subVectors(s,t),Rs.subVectors(i,t),np.subVectors(e,t);const r=zi.dot(zi),o=zi.dot(Rs),l=zi.dot(np),c=Rs.dot(Rs),u=Rs.dot(np),d=r*c-o*o;if(d===0)return a.set(0,0,0),null;const h=1/d,f=(c*l-o*u)*h,p=(r*u-o*l)*h;return a.set(1-f-p,p,f)}static containsPoint(e,t,i,s){return this.getBarycoord(e,t,i,s,Ps)===null?!1:Ps.x>=0&&Ps.y>=0&&Ps.x+Ps.y<=1}static getInterpolation(e,t,i,s,a,r,o,l){return this.getBarycoord(e,t,i,s,Ps)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(a,Ps.x),l.addScaledVector(r,Ps.y),l.addScaledVector(o,Ps.z),l)}static getInterpolatedAttribute(e,t,i,s,a,r){return rp.setScalar(0),op.setScalar(0),lp.setScalar(0),rp.fromBufferAttribute(e,t),op.fromBufferAttribute(e,i),lp.fromBufferAttribute(e,s),r.setScalar(0),r.addScaledVector(rp,a.x),r.addScaledVector(op,a.y),r.addScaledVector(lp,a.z),r}static isFrontFacing(e,t,i,s){return zi.subVectors(i,t),Rs.subVectors(e,t),zi.cross(Rs).dot(s)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,s){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[s]),this}setFromAttributeAndIndices(e,t,i,s){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,s),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return zi.subVectors(this.c,this.b),Rs.subVectors(this.a,this.b),zi.cross(Rs).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return ii.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return ii.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,s,a){return ii.getInterpolation(e,this.a,this.b,this.c,t,i,s,a)}containsPoint(e){return ii.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return ii.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,s=this.b,a=this.c;let r,o;Fr.subVectors(s,i),Nr.subVectors(a,i),ip.subVectors(e,i);const l=Fr.dot(ip),c=Nr.dot(ip);if(l<=0&&c<=0)return t.copy(i);sp.subVectors(e,s);const u=Fr.dot(sp),d=Nr.dot(sp);if(u>=0&&d<=u)return t.copy(s);const h=l*d-u*c;if(h<=0&&l>=0&&u<=0)return r=l/(l-u),t.copy(i).addScaledVector(Fr,r);ap.subVectors(e,a);const f=Fr.dot(ap),p=Nr.dot(ap);if(p>=0&&f<=p)return t.copy(a);const g=f*c-l*p;if(g<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(i).addScaledVector(Nr,o);const _=u*p-f*d;if(_<=0&&d-u>=0&&f-p>=0)return r0.subVectors(a,s),o=(d-u)/(d-u+(f-p)),t.copy(s).addScaledVector(r0,o);const m=1/(_+g+h);return r=g*m,o=h*m,t.copy(i).addScaledVector(Fr,r).addScaledVector(Nr,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const nT={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},ea={h:0,s:0,l:0},Kc={h:0,s:0,l:0};function cp(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*6*(2/3-t):n}class de{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){const s=e;s&&s.isColor?this.copy(s):typeof s=="number"?this.setHex(s):typeof s=="string"&&this.setStyle(s)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=yt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,ot.colorSpaceToWorking(this,t),this}setRGB(e,t,i,s=ot.workingColorSpace){return this.r=e,this.g=t,this.b=i,ot.colorSpaceToWorking(this,s),this}setHSL(e,t,i,s=ot.workingColorSpace){if(e=Pg(e,1),t=Je(t,0,1),i=Je(i,0,1),t===0)this.r=this.g=this.b=i;else{const a=i<=.5?i*(1+t):i+t-i*t,r=2*i-a;this.r=cp(r,a,e+1/3),this.g=cp(r,a,e),this.b=cp(r,a,e-1/3)}return ot.colorSpaceToWorking(this,s),this}setStyle(e,t=yt){function i(a){a!==void 0&&parseFloat(a)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(e)){let a;const r=s[1],o=s[2];switch(r){case"rgb":case"rgba":if(a=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setRGB(Math.min(255,parseInt(a[1],10))/255,Math.min(255,parseInt(a[2],10))/255,Math.min(255,parseInt(a[3],10))/255,t);if(a=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setRGB(Math.min(100,parseInt(a[1],10))/100,Math.min(100,parseInt(a[2],10))/100,Math.min(100,parseInt(a[3],10))/100,t);break;case"hsl":case"hsla":if(a=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setHSL(parseFloat(a[1])/360,parseFloat(a[2])/100,parseFloat(a[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(e)){const a=s[1],r=a.length;if(r===3)return this.setRGB(parseInt(a.charAt(0),16)/15,parseInt(a.charAt(1),16)/15,parseInt(a.charAt(2),16)/15,t);if(r===6)return this.setHex(parseInt(a,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=yt){const i=nT[e.toLowerCase()];return i!==void 0?this.setHex(i,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Gs(e.r),this.g=Gs(e.g),this.b=Gs(e.b),this}copyLinearToSRGB(e){return this.r=mo(e.r),this.g=mo(e.g),this.b=mo(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=yt){return ot.workingToColorSpace(An.copy(this),e),Math.round(Je(An.r*255,0,255))*65536+Math.round(Je(An.g*255,0,255))*256+Math.round(Je(An.b*255,0,255))}getHexString(e=yt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=ot.workingColorSpace){ot.workingToColorSpace(An.copy(this),t);const i=An.r,s=An.g,a=An.b,r=Math.max(i,s,a),o=Math.min(i,s,a);let l,c;const u=(o+r)/2;if(o===r)l=0,c=0;else{const d=r-o;switch(c=u<=.5?d/(r+o):d/(2-r-o),r){case i:l=(s-a)/d+(s0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const i=e[t];if(i===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(i):s&&s.isVector3&&i&&i.isVector3?s.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==dr&&(i.blending=this.blending),this.side!==bs&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==sc&&(i.blendSrc=this.blendSrc),this.blendDst!==ac&&(i.blendDst=this.blendDst),this.blendEquation!==Us&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==pr&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==e_&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Ka&&(i.stencilFail=this.stencilFail),this.stencilZFail!==Ka&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==Ka&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function s(a){const r=[];for(const o in a){const l=a[o];delete l.metadata,r.push(l)}return r}if(t){const a=s(e.textures),r=s(e.images);a.length>0&&(i.textures=a),r.length>0&&(i.images=r)}return i}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let i=null;if(t!==null){const s=t.length;i=new Array(s);for(let a=0;a!==s;++a)i[a]=t[a].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class je extends en{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new de(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new rn,this.combine=Mc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const zs=pR();function pR(){const n=new ArrayBuffer(4),e=new Float32Array(n),t=new Uint32Array(n),i=new Uint32Array(512),s=new Uint32Array(512);for(let l=0;l<256;++l){const c=l-127;c<-27?(i[l]=0,i[l|256]=32768,s[l]=24,s[l|256]=24):c<-14?(i[l]=1024>>-c-14,i[l|256]=1024>>-c-14|32768,s[l]=-c-1,s[l|256]=-c-1):c<=15?(i[l]=c+15<<10,i[l|256]=c+15<<10|32768,s[l]=13,s[l|256]=13):c<128?(i[l]=31744,i[l|256]=64512,s[l]=24,s[l|256]=24):(i[l]=31744,i[l|256]=64512,s[l]=13,s[l|256]=13)}const a=new Uint32Array(2048),r=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,u=0;for(;(c&8388608)===0;)c<<=1,u-=8388608;c&=-8388609,u+=947912704,a[l]=c|u}for(let l=1024;l<2048;++l)a[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)r[l]=l<<23;r[31]=1199570944,r[32]=2147483648;for(let l=33;l<63;++l)r[l]=2147483648+(l-32<<23);r[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:e,uint32View:t,baseTable:i,shiftTable:s,mantissaTable:a,exponentTable:r,offsetTable:o}}function Qn(n){Math.abs(n)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),n=Je(n,-65504,65504),zs.floatView[0]=n;const e=zs.uint32View[0],t=e>>23&511;return zs.baseTable[t]+((e&8388607)>>zs.shiftTable[t])}function Pl(n){const e=n>>10;return zs.uint32View[0]=zs.mantissaTable[zs.offsetTable[e]+(n&1023)]+zs.exponentTable[e],zs.floatView[0]}class Il{static toHalfFloat(e){return Qn(e)}static fromHalfFloat(e){return Pl(e)}}const sn=new T,qc=new ne;let mR=0;class lt{constructor(e,t,i=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:mR++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=cc,this.updateRanges=[],this.gpuType=Mn,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,i){e*=this.itemSize,i*=t.itemSize;for(let s=0,a=this.itemSize;st.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new bn);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new T(-1/0,-1/0,-1/0),new T(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,s=t.length;i0&&(e.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const l in i){const c=i[l];e.data.attributes[l]=c.toJSON(e.data)}const s={};let a=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],u=[];for(let d=0,h=c.length;d0&&(s[l]=u,a=!0)}a&&(e.data.morphAttributes=s,e.data.morphTargetsRelative=this.morphTargetsRelative);const r=this.groups;r.length>0&&(e.data.groups=JSON.parse(JSON.stringify(r)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const i=e.index;i!==null&&this.setIndex(i.clone());const s=e.attributes;for(const c in s){const u=s[c];this.setAttribute(c,u.clone(t))}const a=e.morphAttributes;for(const c in a){const u=[],d=a[c];for(let h=0,f=d.length;h0){const s=t[i[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,r=s.length;a(e.far-e.near)**2))&&(o0.copy(a).invert(),Aa.copy(e.ray).applyMatrix4(o0),!(i.boundingBox!==null&&Aa.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,Aa)))}_computeIntersections(e,t,i){let s;const a=this.geometry,r=this.material,o=a.index,l=a.attributes.position,c=a.attributes.uv,u=a.attributes.uv1,d=a.attributes.normal,h=a.groups,f=a.drawRange;if(o!==null)if(Array.isArray(r))for(let p=0,g=h.length;pt.far?null:{distance:c,point:eu.clone(),object:n}}function tu(n,e,t,i,s,a,r,o,l,c){n.getVertexPosition(o,jc),n.getVertexPosition(l,Zc),n.getVertexPosition(c,Jc);const u=SR(n,e,t,i,jc,Zc,Jc,c0);if(u){const d=new T;ii.getBarycoord(c0,jc,Zc,Jc,d),s&&(u.uv=ii.getInterpolatedAttribute(s,o,l,c,d,new ne)),a&&(u.uv1=ii.getInterpolatedAttribute(a,o,l,c,d,new ne)),r&&(u.normal=ii.getInterpolatedAttribute(r,o,l,c,d,new T),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));const h={a:o,b:l,c,normal:new T,materialIndex:0};ii.getNormal(jc,Zc,Jc,h.normal),u.face=h,u.barycoord=d}return u}class Di extends $e{constructor(e=1,t=1,i=1,s=1,a=1,r=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:s,heightSegments:a,depthSegments:r};const o=this;s=Math.floor(s),a=Math.floor(a),r=Math.floor(r);const l=[],c=[],u=[],d=[];let h=0,f=0;p("z","y","x",-1,-1,i,t,e,r,a,0),p("z","y","x",1,-1,i,t,-e,r,a,1),p("x","z","y",1,1,e,i,t,s,r,2),p("x","z","y",1,-1,e,i,-t,s,r,3),p("x","y","z",1,-1,e,t,i,s,a,4),p("x","y","z",-1,-1,e,t,-i,s,a,5),this.setIndex(l),this.setAttribute("position",new Ce(c,3)),this.setAttribute("normal",new Ce(u,3)),this.setAttribute("uv",new Ce(d,2));function p(g,_,m,v,y,b,S,x,M,C,w){const E=b/M,R=S/C,L=b/2,O=S/2,D=x/2,U=M+1,F=C+1;let W=0,H=0;const ie=new T;for(let le=0;le0?1:-1,u.push(ie.x,ie.y,ie.z),d.push(Le/M),d.push(1-le/C),W+=1}}for(let le=0;le0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const i={};for(const s in this.extensions)this.extensions[s]===!0&&(i[s]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}}class ef extends et{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Ee,this.projectionMatrix=new Ee,this.projectionMatrixInverse=new Ee,this.coordinateSystem=yi,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const ta=new T,i0=new ne,s0=new ne;class Qt extends ef{constructor(e=50,t=1,i=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=i,this.far=s,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=Oo*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(dr*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Oo*2*Math.atan(Math.tan(dr*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,i){ta.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(ta.x,ta.y).multiplyScalar(-e/ta.z),ta.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(ta.x,ta.y).multiplyScalar(-e/ta.z)}getViewSize(e,t){return this.getViewBounds(e,i0,s0),t.subVectors(s0,i0)}setViewOffset(e,t,i,s,a,r){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=s,this.view.width=a,this.view.height=r,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(dr*.5*this.fov)/this.zoom,i=2*t,s=this.aspect*i,a=-.5*s;const r=this.view;if(this.view!==null&&this.view.enabled){const l=r.fullWidth,c=r.fullHeight;a+=r.offsetX*s/l,t-=r.offsetY*i/c,s*=r.width/l,i*=r.height/c}const o=this.filmOffset;o!==0&&(a+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(a,a+s,t,t-i,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const Ur=-90,Br=1;class jS extends et{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new Qt(Ur,Br,e,t);s.layers=this.layers,this.add(s);const a=new Qt(Ur,Br,e,t);a.layers=this.layers,this.add(a);const r=new Qt(Ur,Br,e,t);r.layers=this.layers,this.add(r);const o=new Qt(Ur,Br,e,t);o.layers=this.layers,this.add(o);const l=new Qt(Ur,Br,e,t);l.layers=this.layers,this.add(l);const c=new Qt(Ur,Br,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[i,s,a,r,o,l]=t;for(const c of t)this.remove(c);if(e===yi)i.up.set(0,1,0),i.lookAt(1,0,0),s.up.set(0,1,0),s.lookAt(-1,0,0),a.up.set(0,0,-1),a.lookAt(0,1,0),r.up.set(0,0,1),r.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===Do)i.up.set(0,-1,0),i.lookAt(-1,0,0),s.up.set(0,-1,0),s.lookAt(1,0,0),a.up.set(0,0,1),a.lookAt(0,1,0),r.up.set(0,0,-1),r.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:s}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[a,r,o,l,c,u]=this.children,d=e.getRenderTarget(),h=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const g=i.texture.generateMipmaps;i.texture.generateMipmaps=!1,e.setRenderTarget(i,0,s),e.render(t,a),e.setRenderTarget(i,1,s),e.render(t,r),e.setRenderTarget(i,2,s),e.render(t,o),e.setRenderTarget(i,3,s),e.render(t,l),e.setRenderTarget(i,4,s),e.render(t,c),i.texture.generateMipmaps=g,e.setRenderTarget(i,5,s),e.render(t,u),e.setRenderTarget(d,h,f),e.xr.enabled=p,i.texture.needsPMREMUpdate=!0}}class Sc extends zt{constructor(e=[],t=Xs,i,s,a,r,o,l,c,u){super(e,t,i,s,a,r,o,l,c,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class ZS extends ws{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const i={width:e,height:e,depth:1},s=[i,i,i,i,i,i];this.texture=new Sc(s),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const i={uniforms:{tEquirect:{value:null}},vertexShader:` +}`;class ri extends en{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=MR,this.fragmentShader=ER,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=Bo(e.uniforms),this.uniformsGroups=TR(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const s in this.uniforms){const r=this.uniforms[s].value;r&&r.isTexture?t.uniforms[s]={type:"t",value:r.toJSON(e).uuid}:r&&r.isColor?t.uniforms[s]={type:"c",value:r.getHex()}:r&&r.isVector2?t.uniforms[s]={type:"v2",value:r.toArray()}:r&&r.isVector3?t.uniforms[s]={type:"v3",value:r.toArray()}:r&&r.isVector4?t.uniforms[s]={type:"v4",value:r.toArray()}:r&&r.isMatrix3?t.uniforms[s]={type:"m3",value:r.toArray()}:r&&r.isMatrix4?t.uniforms[s]={type:"m4",value:r.toArray()}:t.uniforms[s]={value:r}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const i={};for(const s in this.extensions)this.extensions[s]===!0&&(i[s]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}}class of extends et{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Ee,this.projectionMatrix=new Ee,this.projectionMatrixInverse=new Ee,this.coordinateSystem=yi,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const ta=new T,u0=new ne,d0=new ne;class Qt extends of{constructor(e=50,t=1,i=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=i,this.far=s,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=Uo*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(hr*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Uo*2*Math.atan(Math.tan(hr*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,i){ta.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(ta.x,ta.y).multiplyScalar(-e/ta.z),ta.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(ta.x,ta.y).multiplyScalar(-e/ta.z)}getViewSize(e,t){return this.getViewBounds(e,u0,d0),t.subVectors(d0,u0)}setViewOffset(e,t,i,s,a,r){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=s,this.view.width=a,this.view.height=r,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(hr*.5*this.fov)/this.zoom,i=2*t,s=this.aspect*i,a=-.5*s;const r=this.view;if(this.view!==null&&this.view.enabled){const l=r.fullWidth,c=r.fullHeight;a+=r.offsetX*s/l,t-=r.offsetY*i/c,s*=r.width/l,i*=r.height/c}const o=this.filmOffset;o!==0&&(a+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(a,a+s,t,t-i,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const Br=-90,zr=1;class aT extends et{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new Qt(Br,zr,e,t);s.layers=this.layers,this.add(s);const a=new Qt(Br,zr,e,t);a.layers=this.layers,this.add(a);const r=new Qt(Br,zr,e,t);r.layers=this.layers,this.add(r);const o=new Qt(Br,zr,e,t);o.layers=this.layers,this.add(o);const l=new Qt(Br,zr,e,t);l.layers=this.layers,this.add(l);const c=new Qt(Br,zr,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[i,s,a,r,o,l]=t;for(const c of t)this.remove(c);if(e===yi)i.up.set(0,1,0),i.lookAt(1,0,0),s.up.set(0,1,0),s.lookAt(-1,0,0),a.up.set(0,0,-1),a.lookAt(0,1,0),r.up.set(0,0,1),r.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===No)i.up.set(0,-1,0),i.lookAt(-1,0,0),s.up.set(0,-1,0),s.lookAt(1,0,0),a.up.set(0,0,1),a.lookAt(0,1,0),r.up.set(0,0,-1),r.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:s}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[a,r,o,l,c,u]=this.children,d=e.getRenderTarget(),h=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const g=i.texture.generateMipmaps;i.texture.generateMipmaps=!1,e.setRenderTarget(i,0,s),e.render(t,a),e.setRenderTarget(i,1,s),e.render(t,r),e.setRenderTarget(i,2,s),e.render(t,o),e.setRenderTarget(i,3,s),e.render(t,l),e.setRenderTarget(i,4,s),e.render(t,c),i.texture.generateMipmaps=g,e.setRenderTarget(i,5,s),e.render(t,u),e.setRenderTarget(d,h,f),e.xr.enabled=p,i.texture.needsPMREMUpdate=!0}}class Cc extends zt{constructor(e=[],t=Xs,i,s,a,r,o,l,c,u){super(e,t,i,s,a,r,o,l,c,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class rT extends ws{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const i={width:e,height:e,depth:1},s=[i,i,i,i,i,i];this.texture=new Cc(s),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const i={uniforms:{tEquirect:{value:null}},vertexShader:` varying vec3 vWorldDirection; @@ -37,9 +37,9 @@ gl_FragColor = texture2D( tEquirect, sampleUV ); } - `},s=new ki(5,5,5),a=new ri({name:"CubemapFromEquirect",uniforms:Fo(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:dn,blending:Hs});a.uniforms.tEquirect.value=t;const r=new Se(s,a),o=t.minFilter;return t.minFilter===Ii&&(t.minFilter=Gt),new jS(1,10,this).update(e,r),t.minFilter=o,r.geometry.dispose(),r.material.dispose(),this}clear(e,t=!0,i=!0,s=!0){const a=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,i,s);e.setRenderTarget(a)}}class Et extends et{constructor(){super(),this.isGroup=!0,this.type="Group"}}const _R={type:"move"};class cd{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Et,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Et,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new T,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new T),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Et,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new T,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new T),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const i of e.hand.values())this._getHandJoint(t,i)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,i){let s=null,a=null,r=null;const o=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){r=!0;for(const g of e.hand.values()){const _=t.getJointPose(g,i),m=this._getHandJoint(c,g);_!==null&&(m.matrix.fromArray(_.transform.matrix),m.matrix.decompose(m.position,m.rotation,m.scale),m.matrixWorldNeedsUpdate=!0,m.jointRadius=_.radius),m.visible=_!==null}const u=c.joints["index-finger-tip"],d=c.joints["thumb-tip"],h=u.position.distanceTo(d.position),f=.02,p=.005;c.inputState.pinching&&h>f+p?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&h<=f-p&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(a=t.getPose(e.gripSpace,i),a!==null&&(l.matrix.fromArray(a.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,a.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(a.linearVelocity)):l.hasLinearVelocity=!1,a.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(a.angularVelocity)):l.hasAngularVelocity=!1));o!==null&&(s=t.getPose(e.targetRaySpace,i),s===null&&a!==null&&(s=a),s!==null&&(o.matrix.fromArray(s.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,s.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(s.linearVelocity)):o.hasLinearVelocity=!1,s.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(s.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(_R)))}return o!==null&&(o.visible=s!==null),l!==null&&(l.visible=a!==null),c!==null&&(c.visible=r!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const i=new Et;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}class tf{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new de(e),this.density=t}clone(){return new tf(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class nf{constructor(e,t=1,i=1e3){this.isFog=!0,this.name="",this.color=new de(e),this.near=t,this.far=i}clone(){return new nf(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class Tc extends et{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new rn,this.environmentIntensity=1,this.environmentRotation=new rn,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class Mc{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=ac,this.updateRanges=[],this.version=0,this.uuid=bi()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,i){e*=this.stride,i*=t.stride;for(let s=0,a=this.stride;se.far||t.push({distance:l,point:rl.clone(),uv:ii.getInterpolation(rl,Jc,ll,Qc,a0,rp,r0,new ne),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}}function eu(n,e,t,i,s,a){Gr.subVectors(n,t).addScalar(.5).multiply(i),s!==void 0?(ol.x=a*Gr.x-s*Gr.y,ol.y=s*Gr.x+a*Gr.y):ol.copy(Gr),n.copy(e),n.x+=ol.x,n.y+=ol.y,n.applyMatrix4(JS)}const tu=new T,o0=new T;class QS extends et{constructor(){super(),this.isLOD=!0,this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);const t=e.levels;for(let i=0,s=t.length;i0){let i,s;for(i=1,s=t.length;i0){tu.setFromMatrixPosition(this.matrixWorld);const s=e.ray.origin.distanceTo(tu);this.getObjectForDistance(s).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){tu.setFromMatrixPosition(e.matrixWorld),o0.setFromMatrixPosition(this.matrixWorld);const i=tu.distanceTo(o0)/e.zoom;t[0].object.visible=!0;let s,a;for(s=1,a=t.length;s=r)t[s-1].object.visible=!1,t[s].object.visible=!0;else break}for(this._currentLevel=s-1;s1?null:t.copy(e.start).addScaledVector(i,a)}intersectsLine(e){const t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const i=t||xR.getNormalMatrix(e),s=this.coplanarPoint(cp).applyMatrix4(e),a=this.normal.applyMatrix3(i).normalize();return this.constant=-s.dot(a),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Aa=new xn,wR=new ne(.5,.5),su=new T;class $o{constructor(e=new Ns,t=new Ns,i=new Ns,s=new Ns,a=new Ns,r=new Ns){this.planes=[e,t,i,s,a,r]}set(e,t,i,s,a,r){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(i),o[3].copy(s),o[4].copy(a),o[5].copy(r),this}copy(e){const t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=yi,i=!1){const s=this.planes,a=e.elements,r=a[0],o=a[1],l=a[2],c=a[3],u=a[4],d=a[5],h=a[6],f=a[7],p=a[8],g=a[9],_=a[10],m=a[11],v=a[12],y=a[13],b=a[14],S=a[15];if(s[0].setComponents(c-r,f-u,m-p,S-v).normalize(),s[1].setComponents(c+r,f+u,m+p,S+v).normalize(),s[2].setComponents(c+o,f+d,m+g,S+y).normalize(),s[3].setComponents(c-o,f-d,m-g,S-y).normalize(),i)s[4].setComponents(l,h,_,b).normalize(),s[5].setComponents(c-l,f-h,m-_,S-b).normalize();else if(s[4].setComponents(c-l,f-h,m-_,S-b).normalize(),t===yi)s[5].setComponents(c+l,f+h,m+_,S+b).normalize();else if(t===Do)s[5].setComponents(l,h,_,b).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Aa.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Aa.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Aa)}intersectsSprite(e){Aa.center.set(0,0,0);const t=wR.distanceTo(e.center);return Aa.radius=.7071067811865476+t,Aa.applyMatrix4(e.matrixWorld),this.intersectsSphere(Aa)}intersectsSphere(e){const t=this.planes,i=e.center,s=-e.radius;for(let a=0;a<6;a++)if(t[a].distanceToPoint(i)0?e.max.x:e.min.x,su.y=s.normal.y>0?e.max.y:e.min.y,su.z=s.normal.z>0?e.max.z:e.min.z,s.distanceToPoint(su)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}const as=new Ee,rs=new $o;class lf{constructor(){this.coordinateSystem=yi}intersectsObject(e,t){if(!t.isArrayCamera||t.cameras.length===0)return!1;for(let i=0;i=a.length&&a.push({start:-1,count:-1,z:-1,index:-1});const o=a[this.index];r.push(o),this.index++,o.start=e,o.count=t,o.z=i,o.index=s}reset(){this.list.length=0,this.index=0}}const Yn=new Ee,ER=new de(1,1,1),_0=new $o,CR=new lf,au=new bn,Ra=new xn,dl=new T,g0=new T,AR=new T,dp=new MR,Rn=new Se,ru=[];function RR(n,e,t=0){const i=e.itemSize;if(n.isInterleavedBufferAttribute||n.array.constructor!==e.array.constructor){const s=n.count;for(let a=0;a65535?new Uint32Array(s):new Uint16Array(s);t.setIndex(new ot(a,1))}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;if(!!e.getIndex()!=!!t.getIndex())throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');for(const i in t.attributes){if(!e.hasAttribute(i))throw new Error(`THREE.BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`);const s=e.getAttribute(i),a=t.getAttribute(i);if(s.itemSize!==a.itemSize||s.normalized!==a.normalized)throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}validateInstanceId(e){const t=this._instanceInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid instanceId ${e}. Instance is either out of range or has been deleted.`)}validateGeometryId(e){const t=this._geometryInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`)}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new bn);const e=this.boundingBox,t=this._instanceInfo;e.makeEmpty();for(let i=0,s=t.length;i=this.maxInstanceCount&&this._availableInstanceIds.length===0)throw new Error("THREE.BatchedMesh: Maximum item count reached.");const i={visible:!0,active:!0,geometryIndex:e};let s=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(up),s=this._availableInstanceIds.shift(),this._instanceInfo[s]=i):(s=this._instanceInfo.length,this._instanceInfo.push(i));const a=this._matricesTexture;Yn.identity().toArray(a.image.data,s*16),a.needsUpdate=!0;const r=this._colorsTexture;return r&&(ER.toArray(r.image.data,s*4),r.needsUpdate=!0),this._visibilityChanged=!0,s}addGeometry(e,t=-1,i=-1){this._initializeGeometry(e),this._validateGeometry(e);const s={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},a=this._geometryInfo;s.vertexStart=this._nextVertexStart,s.reservedVertexCount=t===-1?e.getAttribute("position").count:t;const r=e.getIndex();if(r!==null&&(s.indexStart=this._nextIndexStart,s.reservedIndexCount=i===-1?r.count:i),s.indexStart!==-1&&s.indexStart+s.reservedIndexCount>this._maxIndexCount||s.vertexStart+s.reservedVertexCount>this._maxVertexCount)throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");let l;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(up),l=this._availableGeometryIds.shift(),a[l]=s):(l=this._geometryCount,this._geometryCount++,a.push(s)),this.setGeometryAt(l,e),this._nextIndexStart=s.indexStart+s.reservedIndexCount,this._nextVertexStart=s.vertexStart+s.reservedVertexCount,l}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,s=i.getIndex()!==null,a=i.getIndex(),r=t.getIndex(),o=this._geometryInfo[e];if(s&&r.count>o.reservedIndexCount||t.attributes.position.count>o.reservedVertexCount)throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");const l=o.vertexStart,c=o.reservedVertexCount;o.vertexCount=t.getAttribute("position").count;for(const u in i.attributes){const d=t.getAttribute(u),h=i.getAttribute(u);RR(d,h,l);const f=d.itemSize;for(let p=d.count,g=c;p=t.length||t[e].active===!1)return this;const i=this._instanceInfo;for(let s=0,a=i.length;so).sort((r,o)=>i[r].vertexStart-i[o].vertexStart),a=this.geometry;for(let r=0,o=i.length;r=this._geometryCount)return null;const i=this.geometry,s=this._geometryInfo[e];if(s.boundingBox===null){const a=new bn,r=i.index,o=i.attributes.position;for(let l=s.start,c=s.start+s.count;l=this._geometryCount)return null;const i=this.geometry,s=this._geometryInfo[e];if(s.boundingSphere===null){const a=new xn;this.getBoundingBoxAt(e,au),au.getCenter(a.center);const r=i.index,o=i.attributes.position;let l=0;for(let c=s.start,u=s.start+s.count;co.active);if(Math.max(...i.map(o=>o.vertexStart+o.reservedVertexCount))>e)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${t}. Cannot shrink further.`);if(this.geometry.index&&Math.max(...i.map(l=>l.indexStart+l.reservedIndexCount))>t)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${t}. Cannot shrink further.`);const a=this.geometry;a.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new $e,this._initializeGeometry(a));const r=this.geometry;a.index&&Pa(a.index.array,r.index.array);for(const o in a.attributes)Pa(a.attributes[o].array,r.attributes[o].array)}raycast(e,t){const i=this._instanceInfo,s=this._geometryInfo,a=this.matrixWorld,r=this.geometry;Rn.material=this.material,Rn.geometry.index=r.index,Rn.geometry.attributes=r.attributes,Rn.geometry.boundingBox===null&&(Rn.geometry.boundingBox=new bn),Rn.geometry.boundingSphere===null&&(Rn.geometry.boundingSphere=new xn);for(let o=0,l=i.length;o({...t,boundingBox:t.boundingBox!==null?t.boundingBox.clone():null,boundingSphere:t.boundingSphere!==null?t.boundingSphere.clone():null})),this._instanceInfo=e._instanceInfo.map(t=>({...t})),this._availableInstanceIds=e._availableInstanceIds.slice(),this._availableGeometryIds=e._availableGeometryIds.slice(),this._nextIndexStart=e._nextIndexStart,this._nextVertexStart=e._nextVertexStart,this._geometryCount=e._geometryCount,this._maxInstanceCount=e._maxInstanceCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._indirectTexture=e._indirectTexture.clone(),this._indirectTexture.image.data=this._indirectTexture.image.data.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),this._colorsTexture!==null&&(this._colorsTexture=e._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,this._colorsTexture!==null&&(this._colorsTexture.dispose(),this._colorsTexture=null)}onBeforeRender(e,t,i,s,a){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const r=s.getIndex(),o=r===null?1:r.array.BYTES_PER_ELEMENT,l=this._instanceInfo,c=this._multiDrawStarts,u=this._multiDrawCounts,d=this._geometryInfo,h=this.perObjectFrustumCulled,f=this._indirectTexture,p=f.image.data,g=i.isArrayCamera?CR:_0;h&&!i.isArrayCamera&&(Yn.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse).multiply(this.matrixWorld),_0.setFromProjectionMatrix(Yn,i.coordinateSystem,i.reversedDepth));let _=0;if(this.sortObjects){Yn.copy(this.matrixWorld).invert(),dl.setFromMatrixPosition(i.matrixWorld).applyMatrix4(Yn),g0.set(0,0,-1).transformDirection(i.matrixWorld).transformDirection(Yn);for(let y=0,b=l.length;y0){const s=t[i[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,r=s.length;ai)return;hp.applyMatrix4(n.matrixWorld);const c=e.ray.origin.distanceTo(hp);if(!(ce.far))return{distance:c,point:v0.clone().applyMatrix4(n.matrixWorld),index:r,face:null,faceIndex:null,barycoord:null,object:n}}const b0=new T,x0=new T;class Fn extends On{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,i=[];for(let s=0,a=t.count;s0){const s=t[i[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,r=s.length;as.far)return;a.push({distance:c,distanceToRay:Math.sqrt(o),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:r})}}class tT extends zt{constructor(e,t,i,s,a=Gt,r=Gt,o,l,c){super(e,t,i,s,a,r,o,l,c),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;const u=this;function d(){u.needsUpdate=!0,u._requestVideoFrameCallbackId=e.requestVideoFrameCallback(d)}"requestVideoFrameCallback"in e&&(this._requestVideoFrameCallbackId=e.requestVideoFrameCallback(d))}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;"requestVideoFrameCallback"in e===!1&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),super.dispose()}}class PR extends tT{constructor(e,t,i,s,a,r,o,l){super({},e,t,i,s,a,r,o,l),this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(e){this.image=e,this.needsUpdate=!0}}class IR extends zt{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=hn,this.minFilter=hn,this.generateMipmaps=!1,this.needsUpdate=!0}}class cf extends zt{constructor(e,t,i,s,a,r,o,l,c,u,d,h){super(null,r,o,l,c,u,s,a,d,h),this.isCompressedTexture=!0,this.image={width:t,height:i},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class LR extends cf{constructor(e,t,i,s,a,r){super(e,t,i,a,r),this.isCompressedArrayTexture=!0,this.image.depth=s,this.wrapR=Wn,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class kR extends cf{constructor(e,t,i){super(void 0,e[0].width,e[0].height,t,i,Xs),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class Ec extends zt{constructor(e,t,i,s,a,r,o,l,c){super(e,t,i,s,a,r,o,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Cg extends zt{constructor(e,t,i=Ks,s,a,r,o=hn,l=hn,c,u=Io,d=1){if(u!==Io&&u!==Lo)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const h={width:e,height:t,depth:d};super(h,s,a,r,o,l,u,i,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new da(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class Ag extends zt{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class uf extends $e{constructor(e=1,t=1,i=4,s=8,a=1){super(),this.type="CapsuleGeometry",this.parameters={radius:e,height:t,capSegments:i,radialSegments:s,heightSegments:a},t=Math.max(0,t),i=Math.max(1,Math.floor(i)),s=Math.max(3,Math.floor(s)),a=Math.max(1,Math.floor(a));const r=[],o=[],l=[],c=[],u=t/2,d=Math.PI/2*e,h=t,f=2*d+h,p=i*2+a,g=s+1,_=new T,m=new T;for(let v=0;v<=p;v++){let y=0,b=0,S=0,x=0;if(v<=i){const w=v/i,E=w*Math.PI/2;b=-u-e*Math.cos(E),S=e*Math.sin(E),x=-e*Math.cos(E),y=w*d}else if(v<=i+a){const w=(v-i)/a;b=-u+w*t,S=e,x=0,y=d+w*h}else{const w=(v-i-a)/i,E=w*Math.PI/2;b=u+e*Math.sin(E),S=e*Math.cos(E),x=e*Math.sin(E),y=d+h+w*d}const M=Math.max(0,Math.min(1,y/f));let C=0;v===0?C=.5/s:v===p&&(C=-.5/s);for(let w=0;w<=s;w++){const E=w/s,R=E*Math.PI*2,L=Math.sin(R),O=Math.cos(R);m.x=-S*O,m.y=b,m.z=S*L,o.push(m.x,m.y,m.z),_.set(-S*O,x,S*L),_.normalize(),l.push(_.x,_.y,_.z),c.push(E+C,M)}if(v>0){const w=(v-1)*g;for(let E=0;E0&&y(!0),t>0&&y(!1)),this.setIndex(u),this.setAttribute("position",new Ce(d,3)),this.setAttribute("normal",new Ce(h,3)),this.setAttribute("uv",new Ce(f,2));function v(){const b=new T,S=new T;let x=0;const M=(t-e)/i;for(let C=0;C<=a;C++){const w=[],E=C/a,R=E*(t-e)+e;for(let L=0;L<=s;L++){const O=L/s,D=O*l+o,U=Math.sin(D),F=Math.cos(D);S.x=R*U,S.y=-E*i+_,S.z=R*F,d.push(S.x,S.y,S.z),b.set(U,M,F).normalize(),h.push(b.x,b.y,b.z),f.push(O,1-E),w.push(p++)}g.push(w)}for(let C=0;C0||w!==0)&&(u.push(E,R,O),x+=3),(t>0||w!==a-1)&&(u.push(R,L,O),x+=3)}c.addGroup(m,x,0),m+=x}function y(b){const S=p,x=new ne,M=new T;let C=0;const w=b===!0?e:t,E=b===!0?1:-1;for(let L=1;L<=s;L++)d.push(0,_*E,0),h.push(0,E,0),f.push(.5,.5),p++;const R=p;for(let L=0;L<=s;L++){const D=L/s*l+o,U=Math.cos(D),F=Math.sin(D);M.x=w*F,M.y=_*E,M.z=w*U,d.push(M.x,M.y,M.z),h.push(0,E,0),x.x=U*.5+.5,x.y=F*.5*E+.5,f.push(x.x,x.y),p++}for(let L=0;L.9&&M<.1&&(y<.2&&(r[v+0]+=1),b<.2&&(r[v+2]+=1),S<.2&&(r[v+4]+=1))}}function h(v){a.push(v.x,v.y,v.z)}function f(v,y){const b=v*3;y.x=e[b+0],y.y=e[b+1],y.z=e[b+2]}function p(){const v=new T,y=new T,b=new T,S=new T,x=new ne,M=new ne,C=new ne;for(let w=0,E=0;w0)l=s-1;else{l=s;break}if(s=l,i[s]===r)return s/(a-1);const u=i[s],h=i[s+1]-u,f=(r-u)/h;return(s+f)/(a-1)}getTangent(e,t){let s=e-1e-4,a=e+1e-4;s<0&&(s=0),a>1&&(a=1);const r=this.getPoint(s),o=this.getPoint(a),l=t||(r.isVector2?new ne:new T);return l.copy(o).sub(r).normalize(),l}getTangentAt(e,t){const i=this.getUtoTmapping(e);return this.getTangent(i,t)}computeFrenetFrames(e,t=!1){const i=new T,s=[],a=[],r=[],o=new T,l=new Ee;for(let f=0;f<=e;f++){const p=f/e;s[f]=this.getTangentAt(p,new T)}a[0]=new T,r[0]=new T;let c=Number.MAX_VALUE;const u=Math.abs(s[0].x),d=Math.abs(s[0].y),h=Math.abs(s[0].z);u<=c&&(c=u,i.set(1,0,0)),d<=c&&(c=d,i.set(0,1,0)),h<=c&&i.set(0,0,1),o.crossVectors(s[0],i).normalize(),a[0].crossVectors(s[0],o),r[0].crossVectors(s[0],a[0]);for(let f=1;f<=e;f++){if(a[f]=a[f-1].clone(),r[f]=r[f-1].clone(),o.crossVectors(s[f-1],s[f]),o.length()>Number.EPSILON){o.normalize();const p=Math.acos(Je(s[f-1].dot(s[f]),-1,1));a[f].applyMatrix4(l.makeRotationAxis(o,p))}r[f].crossVectors(s[f],a[f])}if(t===!0){let f=Math.acos(Je(a[0].dot(a[e]),-1,1));f/=e,s[0].dot(o.crossVectors(a[0],a[e]))>0&&(f=-f);for(let p=1;p<=e;p++)a[p].applyMatrix4(l.makeRotationAxis(s[p],f*p)),r[p].crossVectors(s[p],a[p])}return{tangents:s,normals:a,binormals:r}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class ff extends Oi{constructor(e=0,t=0,i=1,s=1,a=0,r=Math.PI*2,o=!1,l=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=i,this.yRadius=s,this.aStartAngle=a,this.aEndAngle=r,this.aClockwise=o,this.aRotation=l}getPoint(e,t=new ne){const i=t,s=Math.PI*2;let a=this.aEndAngle-this.aStartAngle;const r=Math.abs(a)s;)a-=s;a0?0:(Math.floor(Math.abs(o)/a)+1)*a:l===0&&o===a-1&&(o=a-2,l=1);let c,u;this.closed||o>0?c=s[(o-1)%a]:(pu.subVectors(s[0],s[1]).add(s[0]),c=pu);const d=s[o%a],h=s[(o+1)%a];if(this.closed||o+2s.length-2?s.length-1:r+1],d=s[r>s.length-3?s.length-1:r+2];return i.set(T0(o,l.x,c.x,u.x,d.x),T0(o,l.y,c.y,u.y,d.y)),i}copy(e){super.copy(e),this.points=[];for(let t=0,i=e.points.length;t=i){const r=s[a]-i,o=this.curves[a],l=o.getLength(),c=l===0?0:1-r/l;return o.getPointAt(c,t)}a++}return null}getLength(){const e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const e=[];let t=0;for(let i=0,s=this.curves.length;i1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,i=e.curves.length;t0){const d=c.getPoint(0);d.equals(this.currentPoint)||this.lineTo(d.x,d.y)}this.curves.push(c);const u=c.getPoint(1);return this.currentPoint.copy(u),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class $s extends vh{constructor(e){super(e),this.uuid=bi(),this.type="Shape",this.holes=[]}getPointsHoles(e){const t=[];for(let i=0,s=this.holes.length;i80*t){o=1/0,l=1/0;let u=-1/0,d=-1/0;for(let h=t;hu&&(u=f),p>d&&(d=p)}c=Math.max(u-o,d-l),c=c!==0?32767/c:0}return lc(a,r,t,o,l,c,0),r}function rT(n,e,t,i,s){let a;if(s===iP(n,e,t,i)>0)for(let r=e;r=e;r-=i)a=M0(r/i|0,n[r],n[r+1],a);return a&&Uo(a,a.next)&&(uc(a),a=a.next),a}function yr(n,e){if(!n)return n;e||(e=n);let t=n,i;do if(i=!1,!t.steiner&&(Uo(t,t.next)||qt(t.prev,t,t.next)===0)){if(uc(t),t=e=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==e);return e}function lc(n,e,t,i,s,a,r){if(!n)return;!r&&a&&ZR(n,i,s,a);let o=n;for(;n.prev!==n.next;){const l=n.prev,c=n.next;if(a?GR(n,i,s,a):VR(n)){e.push(l.i,n.i,c.i),uc(n),n=c.next,o=c.next;continue}if(n=c,n===o){r?r===1?(n=$R(yr(n),e),lc(n,e,t,i,s,a,2)):r===2&&WR(n,e,t,i,s,a):lc(yr(n),e,t,i,s,a,1);break}}}function VR(n){const e=n.prev,t=n,i=n.next;if(qt(e,t,i)>=0)return!1;const s=e.x,a=t.x,r=i.x,o=e.y,l=t.y,c=i.y,u=Math.min(s,a,r),d=Math.min(o,l,c),h=Math.max(s,a,r),f=Math.max(o,l,c);let p=i.next;for(;p!==e;){if(p.x>=u&&p.x<=h&&p.y>=d&&p.y<=f&&Rl(s,o,a,l,r,c,p.x,p.y)&&qt(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function GR(n,e,t,i){const s=n.prev,a=n,r=n.next;if(qt(s,a,r)>=0)return!1;const o=s.x,l=a.x,c=r.x,u=s.y,d=a.y,h=r.y,f=Math.min(o,l,c),p=Math.min(u,d,h),g=Math.max(o,l,c),_=Math.max(u,d,h),m=jm(f,p,e,t,i),v=jm(g,_,e,t,i);let y=n.prevZ,b=n.nextZ;for(;y&&y.z>=m&&b&&b.z<=v;){if(y.x>=f&&y.x<=g&&y.y>=p&&y.y<=_&&y!==s&&y!==r&&Rl(o,u,l,d,c,h,y.x,y.y)&&qt(y.prev,y,y.next)>=0||(y=y.prevZ,b.x>=f&&b.x<=g&&b.y>=p&&b.y<=_&&b!==s&&b!==r&&Rl(o,u,l,d,c,h,b.x,b.y)&&qt(b.prev,b,b.next)>=0))return!1;b=b.nextZ}for(;y&&y.z>=m;){if(y.x>=f&&y.x<=g&&y.y>=p&&y.y<=_&&y!==s&&y!==r&&Rl(o,u,l,d,c,h,y.x,y.y)&&qt(y.prev,y,y.next)>=0)return!1;y=y.prevZ}for(;b&&b.z<=v;){if(b.x>=f&&b.x<=g&&b.y>=p&&b.y<=_&&b!==s&&b!==r&&Rl(o,u,l,d,c,h,b.x,b.y)&&qt(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function $R(n,e){let t=n;do{const i=t.prev,s=t.next.next;!Uo(i,s)&&lT(i,t,t.next,s)&&cc(i,s)&&cc(s,i)&&(e.push(i.i,t.i,s.i),uc(t),uc(t.next),t=n=s),t=t.next}while(t!==n);return yr(t)}function WR(n,e,t,i,s,a){let r=n;do{let o=r.next.next;for(;o!==r.prev;){if(r.i!==o.i&&eP(r,o)){let l=cT(r,o);r=yr(r,r.next),l=yr(l,l.next),lc(r,e,t,i,s,a,0),lc(l,e,t,i,s,a,0);return}o=o.next}r=r.next}while(r!==n)}function XR(n,e,t,i){const s=[];for(let a=0,r=e.length;a=t.next.y&&t.next.y!==t.y){const d=t.x+(s-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(d<=i&&d>a&&(a=d,r=t.x=t.x&&t.x>=l&&i!==t.x&&oT(sr.x||t.x===r.x&&jR(r,t)))&&(r=t,u=d)}t=t.next}while(t!==o);return r}function jR(n,e){return qt(n.prev,n,e.prev)<0&&qt(e.next,n,n.next)<0}function ZR(n,e,t,i){let s=n;do s.z===0&&(s.z=jm(s.x,s.y,e,t,i)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next;while(s!==n);s.prevZ.nextZ=null,s.prevZ=null,JR(s)}function JR(n){let e,t=1;do{let i=n,s;n=null;let a=null;for(e=0;i;){e++;let r=i,o=0;for(let c=0;c0||l>0&&r;)o!==0&&(l===0||!r||i.z<=r.z)?(s=i,i=i.nextZ,o--):(s=r,r=r.nextZ,l--),a?a.nextZ=s:n=s,s.prevZ=a,a=s;i=r}a.nextZ=null,t*=2}while(e>1);return n}function jm(n,e,t,i,s){return n=(n-t)*s|0,e=(e-i)*s|0,n=(n|n<<8)&16711935,n=(n|n<<4)&252645135,n=(n|n<<2)&858993459,n=(n|n<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,n|e<<1}function QR(n){let e=n,t=n;do(e.x=(n-r)*(a-o)&&(n-r)*(i-o)>=(t-r)*(e-o)&&(t-r)*(a-o)>=(s-r)*(i-o)}function Rl(n,e,t,i,s,a,r,o){return!(n===r&&e===o)&&oT(n,e,t,i,s,a,r,o)}function eP(n,e){return n.next.i!==e.i&&n.prev.i!==e.i&&!tP(n,e)&&(cc(n,e)&&cc(e,n)&&nP(n,e)&&(qt(n.prev,n,e.prev)||qt(n,e.prev,e))||Uo(n,e)&&qt(n.prev,n,n.next)>0&&qt(e.prev,e,e.next)>0)}function qt(n,e,t){return(e.y-n.y)*(t.x-e.x)-(e.x-n.x)*(t.y-e.y)}function Uo(n,e){return n.x===e.x&&n.y===e.y}function lT(n,e,t,i){const s=_u(qt(n,e,t)),a=_u(qt(n,e,i)),r=_u(qt(t,i,n)),o=_u(qt(t,i,e));return!!(s!==a&&r!==o||s===0&&mu(n,t,e)||a===0&&mu(n,i,e)||r===0&&mu(t,n,i)||o===0&&mu(t,e,i))}function mu(n,e,t){return e.x<=Math.max(n.x,t.x)&&e.x>=Math.min(n.x,t.x)&&e.y<=Math.max(n.y,t.y)&&e.y>=Math.min(n.y,t.y)}function _u(n){return n>0?1:n<0?-1:0}function tP(n,e){let t=n;do{if(t.i!==n.i&&t.next.i!==n.i&&t.i!==e.i&&t.next.i!==e.i&&lT(t,t.next,n,e))return!0;t=t.next}while(t!==n);return!1}function cc(n,e){return qt(n.prev,n,n.next)<0?qt(n,e,n.next)>=0&&qt(n,n.prev,e)>=0:qt(n,e,n.prev)<0||qt(n,n.next,e)<0}function nP(n,e){let t=n,i=!1;const s=(n.x+e.x)/2,a=(n.y+e.y)/2;do t.y>a!=t.next.y>a&&t.next.y!==t.y&&s<(t.next.x-t.x)*(a-t.y)/(t.next.y-t.y)+t.x&&(i=!i),t=t.next;while(t!==n);return i}function cT(n,e){const t=Zm(n.i,n.x,n.y),i=Zm(e.i,e.x,e.y),s=n.next,a=e.prev;return n.next=e,e.prev=n,t.next=s,s.prev=t,i.next=t,t.prev=i,a.next=i,i.prev=a,i}function M0(n,e,t,i){const s=Zm(n,e,t);return i?(s.next=i.next,s.prev=i,i.next.prev=s,i.next=s):(s.prev=s,s.next=s),s}function uc(n){n.next.prev=n.prev,n.prev.next=n.next,n.prevZ&&(n.prevZ.nextZ=n.nextZ),n.nextZ&&(n.nextZ.prevZ=n.prevZ)}function Zm(n,e,t){return{i:n,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function iP(n,e,t,i){let s=0;for(let a=e,r=t-i;a2&&n[e-1].equals(n[0])&&n.pop()}function C0(n,e){for(let t=0;tNumber.EPSILON){const J=Math.sqrt(A),ce=Math.sqrt(st*st+I*I),ee=j.x-We/J,Ve=j.y+ye/J,ve=Y.x-I/ce,Be=Y.y+st/ce,ze=((ve-ee)*I-(Be-Ve)*st)/(ye*I-We*st);Q=ee+ye*ze-G.x,ge=Ve+We*ze-G.y;const he=Q*Q+ge*ge;if(he<=2)return new ne(Q,ge);ue=Math.sqrt(he/2)}else{let J=!1;ye>Number.EPSILON?st>Number.EPSILON&&(J=!0):ye<-Number.EPSILON?st<-Number.EPSILON&&(J=!0):Math.sign(We)===Math.sign(I)&&(J=!0),J?(Q=-We,ge=ye,ue=Math.sqrt(A)):(Q=ye,ge=We,ue=Math.sqrt(A/2))}return new ne(Q/ue,ge/ue)}const ie=[];for(let G=0,j=U.length,Y=j-1,Q=G+1;G=0;G--){const j=G/_,Y=f*Math.cos(j*Math.PI/2),Q=p*Math.sin(j*Math.PI/2)+g;for(let ge=0,ue=U.length;ge=0;){const Q=Y;let ge=Y-1;ge<0&&(ge=G.length-1);for(let ue=0,ye=u+_*2;ue0)&&f.push(y,b,x),(m!==i-1||l0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class ir extends en{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new de(16777215),this.specular=new de(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new de(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ba,this.normalScale=new ne(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new rn,this.combine=xc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class hT extends en{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new de(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new de(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ba,this.normalScale=new ne(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class fT extends en{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ba,this.normalScale=new ne(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class xf extends en{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new de(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new de(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ba,this.normalScale=new ne(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new rn,this.combine=xc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Ng extends en{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=DS,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class Ug extends en{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class pT extends en{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new de(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ba,this.normalScale=new ne(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}class mT extends Pt{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}function sr(n,e){return!n||n.constructor===e?n:typeof e.BYTES_PER_ELEMENT=="number"?new e(n):Array.prototype.slice.call(n)}function _T(n){return ArrayBuffer.isView(n)&&!(n instanceof DataView)}function gT(n){function e(s,a){return n[s]-n[a]}const t=n.length,i=new Array(t);for(let s=0;s!==t;++s)i[s]=s;return i.sort(e),i}function Jm(n,e,t){const i=n.length,s=new n.constructor(i);for(let a=0,r=0;r!==i;++a){const o=t[a]*e;for(let l=0;l!==e;++l)s[r++]=n[o+l]}return s}function Bg(n,e,t,i){let s=1,a=n[0];for(;a!==void 0&&a[i]===void 0;)a=n[s++];if(a===void 0)return;let r=a[i];if(r!==void 0)if(Array.isArray(r))do r=a[i],r!==void 0&&(e.push(a.time),t.push(...r)),a=n[s++];while(a!==void 0);else if(r.toArray!==void 0)do r=a[i],r!==void 0&&(e.push(a.time),r.toArray(t,t.length)),a=n[s++];while(a!==void 0);else do r=a[i],r!==void 0&&(e.push(a.time),t.push(r)),a=n[s++];while(a!==void 0)}function lP(n,e,t,i,s=30){const a=n.clone();a.name=e;const r=[];for(let l=0;l=i)){d.push(c.times[f]);for(let g=0;ga.tracks[l].times[0]&&(o=a.tracks[l].times[0]);for(let l=0;l=o.times[p]){const m=p*d+u,v=m+d-u;g=o.values.slice(m,v)}else{const m=o.createInterpolant(),v=u,y=d-u;m.evaluate(a),g=m.resultBuffer.slice(v,y)}l==="quaternion"&&new ht().fromArray(g).normalize().conjugate().toArray(g);const _=c.times.length;for(let m=0;m<_;++m){const v=m*f+h;if(l==="quaternion")ht.multiplyQuaternionsFlat(c.values,v,g,0,c.values,v);else{const y=f-h*2;for(let b=0;b=a)){const o=t[1];e=a)break t}r=i,i=0;break n}break e}for(;i>>1;et;)--r;if(++r,a!==0||r!==s){a>=r&&(r=Math.max(r,1),a=r-1);const o=this.getValueSize();this.times=i.slice(a,r),this.values=this.values.slice(a*o,r*o)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const i=this.times,s=this.values,a=i.length;a===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let r=null;for(let o=0;o!==a;o++){const l=i[o];if(typeof l=="number"&&isNaN(l)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,o,l),e=!1;break}if(r!==null&&r>l){console.error("THREE.KeyframeTrack: Out of order keys.",this,o,l,r),e=!1;break}r=l}if(s!==void 0&&_T(s))for(let o=0,l=s.length;o!==l;++o){const c=s[o];if(isNaN(c)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,o,c),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),i=this.getValueSize(),s=this.getInterpolation()===ld,a=e.length-1;let r=1;for(let o=1;o0){e[r]=e[a];for(let o=a*i,l=r*i,c=0;c!==i;++c)t[l+c]=t[o+c];++r}return r!==e.length?(this.times=e.slice(0,r),this.values=t.slice(0,r*i)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),i=this.constructor,s=new i(this.name,e,t);return s.createInterpolant=this.createInterpolant,s}}Fi.prototype.ValueTypeName="";Fi.prototype.TimeBufferType=Float32Array;Fi.prototype.ValueBufferType=Float32Array;Fi.prototype.DefaultInterpolation=mr;class Tr extends Fi{constructor(e,t,i){super(e,t,i)}}Tr.prototype.ValueTypeName="bool";Tr.prototype.ValueBufferType=Array;Tr.prototype.DefaultInterpolation=ko;Tr.prototype.InterpolantFactoryMethodLinear=void 0;Tr.prototype.InterpolantFactoryMethodSmooth=void 0;class Hg extends Fi{constructor(e,t,i,s){super(e,t,i,s)}}Hg.prototype.ValueTypeName="color";class ga extends Fi{constructor(e,t,i,s){super(e,t,i,s)}}ga.prototype.ValueTypeName="number";class bT extends Xo{constructor(e,t,i,s){super(e,t,i,s)}interpolate_(e,t,i,s){const a=this.resultBuffer,r=this.sampleValues,o=this.valueSize,l=(i-t)/(s-t);let c=e*o;for(let u=c+o;c!==u;c+=4)ht.slerpFlat(a,0,r,c-o,r,c,l);return a}}class Ss extends Fi{constructor(e,t,i,s){super(e,t,i,s)}InterpolantFactoryMethodLinear(e){return new bT(this.times,this.values,this.getValueSize(),e)}}Ss.prototype.ValueTypeName="quaternion";Ss.prototype.InterpolantFactoryMethodSmooth=void 0;class Mr extends Fi{constructor(e,t,i){super(e,t,i)}}Mr.prototype.ValueTypeName="string";Mr.prototype.ValueBufferType=Array;Mr.prototype.DefaultInterpolation=ko;Mr.prototype.InterpolantFactoryMethodLinear=void 0;Mr.prototype.InterpolantFactoryMethodSmooth=void 0;class qs extends Fi{constructor(e,t,i,s){super(e,t,i,s)}}qs.prototype.ValueTypeName="vector";class ya{constructor(e="",t=-1,i=[],s=Yh){this.name=e,this.tracks=i,this.duration=t,this.blendMode=s,this.uuid=bi(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){const t=[],i=e.tracks,s=1/(e.fps||1);for(let r=0,o=i.length;r!==o;++r)t.push(hP(i[r]).scale(s));const a=new this(e.name,e.duration,t,e.blendMode);return a.uuid=e.uuid,a.userData=JSON.parse(e.userData||"{}"),a}static toJSON(e){const t=[],i=e.tracks,s={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let a=0,r=i.length;a!==r;++a)t.push(Fi.toJSON(i[a]));return s}static CreateFromMorphTargetSequence(e,t,i,s){const a=t.length,r=[];for(let o=0;o1){const d=u[1];let h=s[d];h||(s[d]=h=[]),h.push(c)}}const r=[];for(const o in s)r.push(this.CreateFromMorphTargetSequence(o,s[o],t,i));return r}static parseAnimation(e,t){if(console.warn("THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const i=function(d,h,f,p,g){if(f.length!==0){const _=[],m=[];Bg(f,_,m,p),_.length!==0&&g.push(new d(h,_,m))}},s=[],a=e.name||"default",r=e.fps||30,o=e.blendMode;let l=e.length||-1;const c=e.hierarchy||[];for(let d=0;d{t&&t(a),this.manager.itemEnd(e)},0),a;if(Is[e]!==void 0){Is[e].push({onLoad:t,onProgress:i,onError:s});return}Is[e]=[],Is[e].push({onLoad:t,onProgress:i,onError:s});const r=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,l=this.responseType;fetch(r).then(c=>{if(c.status===200||c.status===0){if(c.status===0&&console.warn("THREE.FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||c.body===void 0||c.body.getReader===void 0)return c;const u=Is[e],d=c.body.getReader(),h=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),f=h?parseInt(h):0,p=f!==0;let g=0;const _=new ReadableStream({start(m){v();function v(){d.read().then(({done:y,value:b})=>{if(y)m.close();else{g+=b.byteLength;const S=new ProgressEvent("progress",{lengthComputable:p,loaded:g,total:f});for(let x=0,M=u.length;x{m.error(y)})}}});return new Response(_)}else throw new fP(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`,c)}).then(c=>{switch(l){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then(u=>new DOMParser().parseFromString(u,o));case"json":return c.json();default:if(o==="")return c.text();{const d=/charset="?([^;"\s]*)"?/i.exec(o),h=d&&d[1]?d[1].toLowerCase():void 0,f=new TextDecoder(h);return c.arrayBuffer().then(p=>f.decode(p))}}}).then(c=>{_s.add(`file:${e}`,c);const u=Is[e];delete Is[e];for(let d=0,h=u.length;d{const u=Is[e];if(u===void 0)throw this.manager.itemError(e),c;delete Is[e];for(let d=0,h=u.length;d{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}class pP extends ln{constructor(e){super(e)}load(e,t,i,s){const a=this,r=new Kn(this.manager);r.setPath(this.path),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,function(o){try{t(a.parse(JSON.parse(o)))}catch(l){s?s(l):console.error(l),a.manager.itemError(e)}},i,s)}parse(e){const t=[];for(let i=0;i0:s.vertexColors=e.vertexColors),e.uniforms!==void 0)for(const a in e.uniforms){const r=e.uniforms[a];switch(s.uniforms[a]={},r.type){case"t":s.uniforms[a].value=i(r.value);break;case"c":s.uniforms[a].value=new de().setHex(r.value);break;case"v2":s.uniforms[a].value=new ne().fromArray(r.value);break;case"v3":s.uniforms[a].value=new T().fromArray(r.value);break;case"v4":s.uniforms[a].value=new Ye().fromArray(r.value);break;case"m3":s.uniforms[a].value=new at().fromArray(r.value);break;case"m4":s.uniforms[a].value=new Ee().fromArray(r.value);break;default:s.uniforms[a].value=r.value}}if(e.defines!==void 0&&(s.defines=e.defines),e.vertexShader!==void 0&&(s.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(s.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(s.glslVersion=e.glslVersion),e.extensions!==void 0)for(const a in e.extensions)s.extensions[a]=e.extensions[a];if(e.lights!==void 0&&(s.lights=e.lights),e.clipping!==void 0&&(s.clipping=e.clipping),e.size!==void 0&&(s.size=e.size),e.sizeAttenuation!==void 0&&(s.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(s.map=i(e.map)),e.matcap!==void 0&&(s.matcap=i(e.matcap)),e.alphaMap!==void 0&&(s.alphaMap=i(e.alphaMap)),e.bumpMap!==void 0&&(s.bumpMap=i(e.bumpMap)),e.bumpScale!==void 0&&(s.bumpScale=e.bumpScale),e.normalMap!==void 0&&(s.normalMap=i(e.normalMap)),e.normalMapType!==void 0&&(s.normalMapType=e.normalMapType),e.normalScale!==void 0){let a=e.normalScale;Array.isArray(a)===!1&&(a=[a,a]),s.normalScale=new ne().fromArray(a)}return e.displacementMap!==void 0&&(s.displacementMap=i(e.displacementMap)),e.displacementScale!==void 0&&(s.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(s.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(s.roughnessMap=i(e.roughnessMap)),e.metalnessMap!==void 0&&(s.metalnessMap=i(e.metalnessMap)),e.emissiveMap!==void 0&&(s.emissiveMap=i(e.emissiveMap)),e.emissiveIntensity!==void 0&&(s.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(s.specularMap=i(e.specularMap)),e.specularIntensityMap!==void 0&&(s.specularIntensityMap=i(e.specularIntensityMap)),e.specularColorMap!==void 0&&(s.specularColorMap=i(e.specularColorMap)),e.envMap!==void 0&&(s.envMap=i(e.envMap)),e.envMapRotation!==void 0&&s.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(s.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(s.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(s.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(s.lightMap=i(e.lightMap)),e.lightMapIntensity!==void 0&&(s.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(s.aoMap=i(e.aoMap)),e.aoMapIntensity!==void 0&&(s.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(s.gradientMap=i(e.gradientMap)),e.clearcoatMap!==void 0&&(s.clearcoatMap=i(e.clearcoatMap)),e.clearcoatRoughnessMap!==void 0&&(s.clearcoatRoughnessMap=i(e.clearcoatRoughnessMap)),e.clearcoatNormalMap!==void 0&&(s.clearcoatNormalMap=i(e.clearcoatNormalMap)),e.clearcoatNormalScale!==void 0&&(s.clearcoatNormalScale=new ne().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(s.iridescenceMap=i(e.iridescenceMap)),e.iridescenceThicknessMap!==void 0&&(s.iridescenceThicknessMap=i(e.iridescenceThicknessMap)),e.transmissionMap!==void 0&&(s.transmissionMap=i(e.transmissionMap)),e.thicknessMap!==void 0&&(s.thicknessMap=i(e.thicknessMap)),e.anisotropyMap!==void 0&&(s.anisotropyMap=i(e.anisotropyMap)),e.sheenColorMap!==void 0&&(s.sheenColorMap=i(e.sheenColorMap)),e.sheenRoughnessMap!==void 0&&(s.sheenRoughnessMap=i(e.sheenRoughnessMap)),s}setTextures(e){return this.textures=e,this}createMaterialFromType(e){return Tf.createMaterialFromType(e)}static createMaterialFromType(e){const t={ShadowMaterial:uT,SpriteMaterial:sf,RawShaderMaterial:dT,ShaderMaterial:ri,PointsMaterial:ha,MeshPhysicalMaterial:li,MeshStandardMaterial:kn,MeshPhongMaterial:ir,MeshToonMaterial:hT,MeshNormalMaterial:fT,MeshLambertMaterial:xf,MeshDepthMaterial:Ng,MeshDistanceMaterial:Ug,MeshBasicMaterial:je,MeshMatcapMaterial:pT,LineDashedMaterial:mT,LineBasicMaterial:Pt,Material:en};return new t[e]}}class Ws{static extractUrlBase(e){const t=e.lastIndexOf("/");return t===-1?"./":e.slice(0,t+1)}static resolveURL(e,t){return typeof e!="string"||e===""?"":(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}}class CT extends $e{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){const e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}}class AT extends ln{constructor(e){super(e)}load(e,t,i,s){const a=this,r=new Kn(a.manager);r.setPath(a.path),r.setRequestHeader(a.requestHeader),r.setWithCredentials(a.withCredentials),r.load(e,function(o){try{t(a.parse(JSON.parse(o)))}catch(l){s?s(l):console.error(l),a.manager.itemError(e)}},i,s)}parse(e){const t={},i={};function s(f,p){if(t[p]!==void 0)return t[p];const _=f.interleavedBuffers[p],m=a(f,_.buffer),v=ro(_.type,m),y=new Mc(v,_.stride);return y.uuid=_.uuid,t[p]=y,y}function a(f,p){if(i[p]!==void 0)return i[p];const _=f.arrayBuffers[p],m=new Uint32Array(_).buffer;return i[p]=m,m}const r=e.isInstancedBufferGeometry?new CT:new $e,o=e.data.index;if(o!==void 0){const f=ro(o.type,o.array);r.setIndex(new ot(f,1))}const l=e.data.attributes;for(const f in l){const p=l[f];let g;if(p.isInterleavedBufferAttribute){const _=s(e.data,p.data);g=new _a(_,p.itemSize,p.offset,p.normalized)}else{const _=ro(p.type,p.array),m=p.isInstancedBufferAttribute?_r:ot;g=new m(_,p.itemSize,p.normalized)}p.name!==void 0&&(g.name=p.name),p.usage!==void 0&&g.setUsage(p.usage),r.setAttribute(f,g)}const c=e.data.morphAttributes;if(c)for(const f in c){const p=c[f],g=[];for(let _=0,m=p.length;_0){const l=new Vg(t);a=new dc(l),a.setCrossOrigin(this.crossOrigin);for(let c=0,u=e.length;c0){s=new dc(this.manager),s.setCrossOrigin(this.crossOrigin);for(let r=0,o=e.length;r{let _=null,m=null;return g.boundingBox!==void 0&&(_=new bn().fromJSON(g.boundingBox)),g.boundingSphere!==void 0&&(m=new xn().fromJSON(g.boundingSphere)),{...g,boundingBox:_,boundingSphere:m}}),r._instanceInfo=e.instanceInfo,r._availableInstanceIds=e._availableInstanceIds,r._availableGeometryIds=e._availableGeometryIds,r._nextIndexStart=e.nextIndexStart,r._nextVertexStart=e.nextVertexStart,r._geometryCount=e.geometryCount,r._maxInstanceCount=e.maxInstanceCount,r._maxVertexCount=e.maxVertexCount,r._maxIndexCount=e.maxIndexCount,r._geometryInitialized=e.geometryInitialized,r._matricesTexture=c(e.matricesTexture.uuid),r._indirectTexture=c(e.indirectTexture.uuid),e.colorsTexture!==void 0&&(r._colorsTexture=c(e.colorsTexture.uuid)),e.boundingSphere!==void 0&&(r.boundingSphere=new xn().fromJSON(e.boundingSphere)),e.boundingBox!==void 0&&(r.boundingBox=new bn().fromJSON(e.boundingBox));break;case"LOD":r=new QS;break;case"Line":r=new On(o(e.geometry),l(e.material));break;case"LineLoop":r=new Eg(o(e.geometry),l(e.material));break;case"LineSegments":r=new Fn(o(e.geometry),l(e.material));break;case"PointCloud":case"Points":r=new hr(o(e.geometry),l(e.material));break;case"Sprite":r=new af(l(e.material));break;case"Group":r=new Et;break;case"Bone":r=new No;break;default:r=new et}if(r.uuid=e.uuid,e.name!==void 0&&(r.name=e.name),e.matrix!==void 0?(r.matrix.fromArray(e.matrix),e.matrixAutoUpdate!==void 0&&(r.matrixAutoUpdate=e.matrixAutoUpdate),r.matrixAutoUpdate&&r.matrix.decompose(r.position,r.quaternion,r.scale)):(e.position!==void 0&&r.position.fromArray(e.position),e.rotation!==void 0&&r.rotation.fromArray(e.rotation),e.quaternion!==void 0&&r.quaternion.fromArray(e.quaternion),e.scale!==void 0&&r.scale.fromArray(e.scale)),e.up!==void 0&&r.up.fromArray(e.up),e.castShadow!==void 0&&(r.castShadow=e.castShadow),e.receiveShadow!==void 0&&(r.receiveShadow=e.receiveShadow),e.shadow&&(e.shadow.intensity!==void 0&&(r.shadow.intensity=e.shadow.intensity),e.shadow.bias!==void 0&&(r.shadow.bias=e.shadow.bias),e.shadow.normalBias!==void 0&&(r.shadow.normalBias=e.shadow.normalBias),e.shadow.radius!==void 0&&(r.shadow.radius=e.shadow.radius),e.shadow.mapSize!==void 0&&r.shadow.mapSize.fromArray(e.shadow.mapSize),e.shadow.camera!==void 0&&(r.shadow.camera=this.parseObject(e.shadow.camera))),e.visible!==void 0&&(r.visible=e.visible),e.frustumCulled!==void 0&&(r.frustumCulled=e.frustumCulled),e.renderOrder!==void 0&&(r.renderOrder=e.renderOrder),e.userData!==void 0&&(r.userData=e.userData),e.layers!==void 0&&(r.layers.mask=e.layers),e.children!==void 0){const h=e.children;for(let f=0;f"u"&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,i,s){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const a=this,r=_s.get(`image-bitmap:${e}`);if(r!==void 0){if(a.manager.itemStart(e),r.then){r.then(c=>{if(vp.has(r)===!0)s&&s(vp.get(r)),a.manager.itemError(e),a.manager.itemEnd(e);else return t&&t(c),a.manager.itemEnd(e),c});return}return setTimeout(function(){t&&t(r),a.manager.itemEnd(e)},0),r}const o={};o.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",o.headers=this.requestHeader,o.signal=typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;const l=fetch(e,o).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign(a.options,{colorSpaceConversion:"none"}))}).then(function(c){return _s.add(`image-bitmap:${e}`,c),t&&t(c),a.manager.itemEnd(e),c}).catch(function(c){s&&s(c),vp.set(l,c),_s.remove(`image-bitmap:${e}`),a.manager.itemError(e),a.manager.itemEnd(e)});_s.add(`image-bitmap:${e}`,l),a.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}let gu;class $g{static getContext(){return gu===void 0&&(gu=new(window.AudioContext||window.webkitAudioContext)),gu}static setContext(e){gu=e}}class wP extends ln{constructor(e){super(e)}load(e,t,i,s){const a=this,r=new Kn(this.manager);r.setResponseType("arraybuffer"),r.setPath(this.path),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,function(l){try{const c=l.slice(0);$g.getContext().decodeAudioData(c,function(d){t(d)}).catch(o)}catch(c){o(c)}},i,s);function o(l){s?s(l):console.error(l),a.manager.itemError(e)}}}const O0=new Ee,F0=new Ee,Ia=new Ee;class SP{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new Qt,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Qt,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){const t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,Ia.copy(e.projectionMatrix);const s=t.eyeSep/2,a=s*t.near/t.focus,r=t.near*Math.tan(dr*t.fov*.5)/t.zoom;let o,l;F0.elements[12]=-s,O0.elements[12]=s,o=-r*t.aspect+a,l=r*t.aspect+a,Ia.elements[0]=2*t.near/(l-o),Ia.elements[8]=(l+o)/(l-o),this.cameraL.projectionMatrix.copy(Ia),o=-r*t.aspect-a,l=r*t.aspect-a,Ia.elements[0]=2*t.near/(l-o),Ia.elements[8]=(l+o)/(l-o),this.cameraR.projectionMatrix.copy(Ia)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(F0),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(O0)}}class PT extends Qt{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class Wg{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}const La=new T,bp=new ht,TP=new T,ka=new T,Da=new T;class MP extends et{constructor(){super(),this.type="AudioListener",this.context=$g.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new Wg}getInput(){return this.gain}removeFilter(){return this.filter!==null&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return this.filter!==null?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e);const t=this.context.listener;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(La,bp,TP),ka.set(0,0,-1).applyQuaternion(bp),Da.set(0,1,0).applyQuaternion(bp),t.positionX){const i=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(La.x,i),t.positionY.linearRampToValueAtTime(La.y,i),t.positionZ.linearRampToValueAtTime(La.z,i),t.forwardX.linearRampToValueAtTime(ka.x,i),t.forwardY.linearRampToValueAtTime(ka.y,i),t.forwardZ.linearRampToValueAtTime(ka.z,i),t.upX.linearRampToValueAtTime(Da.x,i),t.upY.linearRampToValueAtTime(Da.y,i),t.upZ.linearRampToValueAtTime(Da.z,i)}else t.setPosition(La.x,La.y,La.z),t.setOrientation(ka.x,ka.y,ka.z,Da.x,Da.y,Da.z)}}class IT extends et{constructor(e){super(),this.type="Audio",this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType="buffer",this.autoplay&&this.play(),this}play(e=0){if(this.isPlaying===!0){console.warn("THREE.Audio: Audio is already playing.");return}if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}this._startedAt=this.context.currentTime+e;const t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.isPlaying===!0&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this}stop(e=0){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this._progress=0,this.source!==null&&(this.source.stop(this.context.currentTime+e),this.source.onended=null),this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(i,s,this._addIndex*t,1,t);for(let l=t,c=t+t;l!==c;++l)if(i[l]!==i[l+t]){o.setValue(i,s);break}}saveOriginalState(){const e=this.binding,t=this.buffer,i=this.valueSize,s=i*this._origIndex;e.getValue(t,s);for(let a=i,r=s;a!==r;++a)t[a]=t[s+a%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let i=e;i=.5)for(let r=0;r!==a;++r)e[t+r]=e[i+r]}_slerp(e,t,i,s){ht.slerpFlat(e,t,e,t,e,i,s)}_slerpAdditive(e,t,i,s,a){const r=this._workIndex*a;ht.multiplyQuaternionsFlat(e,r,e,t,e,i),ht.slerpFlat(e,t,e,t,e,r,s)}_lerp(e,t,i,s,a){const r=1-s;for(let o=0;o!==a;++o){const l=t+o;e[l]=e[l]*r+e[i+o]*s}}_lerpAdditive(e,t,i,s,a){for(let r=0;r!==a;++r){const o=t+r;e[o]=e[o]+e[i+r]*s}}}const Xg="\\[\\]\\.:\\/",RP=new RegExp("["+Xg+"]","g"),Kg="[^"+Xg+"]",PP="[^"+Xg.replace("\\.","")+"]",IP=/((?:WC+[\/:])*)/.source.replace("WC",Kg),LP=/(WCOD+)?/.source.replace("WCOD",PP),kP=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Kg),DP=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Kg),OP=new RegExp("^"+IP+LP+kP+DP+"$"),FP=["material","materials","bones","map"];class NP{constructor(e,t,i){const s=i||vt.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,s)}getValue(e,t){this.bind();const i=this._targetGroup.nCachedObjects_,s=this._bindings[i];s!==void 0&&s.getValue(e,t)}setValue(e,t){const i=this._bindings;for(let s=this._targetGroup.nCachedObjects_,a=i.length;s!==a;++s)i[s].setValue(e,t)}bind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].bind()}unbind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].unbind()}}class vt{constructor(e,t,i){this.path=t,this.parsedPath=i||vt.parseTrackName(t),this.node=vt.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,i){return e&&e.isAnimationObjectGroup?new vt.Composite(e,t,i):new vt(e,t,i)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(RP,"")}static parseTrackName(e){const t=OP.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const i={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},s=i.nodeName&&i.nodeName.lastIndexOf(".");if(s!==void 0&&s!==-1){const a=i.nodeName.substring(s+1);FP.indexOf(a)!==-1&&(i.nodeName=i.nodeName.substring(0,s),i.objectName=a)}if(i.propertyName===null||i.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return i}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){const i=e.skeleton.getBoneByName(t);if(i!==void 0)return i}if(e.children){const i=function(a){for(let r=0;r=a){const d=a++,h=e[d];t[h.uuid]=u,e[u]=h,t[c]=d,e[d]=l;for(let f=0,p=s;f!==p;++f){const g=i[f],_=g[d],m=g[u];g[u]=_,g[d]=m}}}this.nCachedObjects_=a}uncache(){const e=this._objects,t=this._indicesByUUID,i=this._bindings,s=i.length;let a=this.nCachedObjects_,r=e.length;for(let o=0,l=arguments.length;o!==l;++o){const c=arguments[o],u=c.uuid,d=t[u];if(d!==void 0)if(delete t[u],d0&&(t[f.uuid]=d),e[d]=f,e.pop();for(let p=0,g=s;p!==g;++p){const _=i[p];_[d]=_[h],_.pop()}}}this.nCachedObjects_=a}subscribe_(e,t){const i=this._bindingsIndicesByPath;let s=i[e];const a=this._bindings;if(s!==void 0)return a[s];const r=this._paths,o=this._parsedPaths,l=this._objects,c=l.length,u=this.nCachedObjects_,d=new Array(c);s=a.length,i[e]=s,r.push(e),o.push(t),a.push(d);for(let h=u,f=l.length;h!==f;++h){const p=l[h];d[h]=new vt(p,e,t)}return d}unsubscribe_(e){const t=this._bindingsIndicesByPath,i=t[e];if(i!==void 0){const s=this._paths,a=this._parsedPaths,r=this._bindings,o=r.length-1,l=r[o],c=e[o];t[c]=i,r[i]=l,r.pop(),a[i]=a[o],a.pop(),s[i]=s[o],s.pop()}}}class kT{constructor(e,t,i=null,s=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=i,this.blendMode=s;const a=t.tracks,r=a.length,o=new Array(r),l={endingStart:tr,endingEnd:tr};for(let c=0;c!==r;++c){const u=a[c].createInterpolant(null);o[c]=u,u.settings=l}this._interpolantSettings=l,this._interpolants=o,this._propertyBindings=new Array(r),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=IS,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,i=!1){if(e.fadeOut(t),this.fadeIn(t),i===!0){const s=this._clip.duration,a=e._clip.duration,r=a/s,o=s/a;e.warp(1,r,t),this.warp(o,1,t)}return this}crossFadeTo(e,t,i=!1){return e.crossFadeFrom(this,t,i)}stopFading(){const e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,i){const s=this._mixer,a=s.time,r=this.timeScale;let o=this._timeScaleInterpolant;o===null&&(o=s._lendControlInterpolant(),this._timeScaleInterpolant=o);const l=o.parameterPositions,c=o.sampleValues;return l[0]=a,l[1]=a+i,c[0]=e/r,c[1]=t/r,this}stopWarping(){const e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,i,s){if(!this.enabled){this._updateWeight(e);return}const a=this._startTime;if(a!==null){const l=(e-a)*i;l<0||i===0?t=0:(this._startTime=null,t=i*l)}t*=this._updateTimeScale(e);const r=this._updateTime(t),o=this._updateWeight(e);if(o>0){const l=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case bg:for(let u=0,d=l.length;u!==d;++u)l[u].evaluate(r),c[u].accumulateAdditive(o);break;case Yh:default:for(let u=0,d=l.length;u!==d;++u)l[u].evaluate(r),c[u].accumulate(s,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const i=this._weightInterpolant;if(i!==null){const s=i.evaluate(e)[0];t*=s,e>i.parameterPositions[1]&&(this.stopFading(),s===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const i=this._timeScaleInterpolant;if(i!==null){const s=i.evaluate(e)[0];t*=s,e>i.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,i=this.loop;let s=this.time+e,a=this._loopCount;const r=i===LS;if(e===0)return a===-1?s:r&&(a&1)===1?t-s:s;if(i===ph){a===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(s>=t)s=t;else if(s<0)s=0;else{this.time=s;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(a===-1&&(e>=0?(a=0,this._setEndings(!0,this.repetitions===0,r)):this._setEndings(this.repetitions===0,!0,r)),s>=t||s<0){const o=Math.floor(s/t);s-=t*o,a+=Math.abs(o);const l=this.repetitions-a;if(l<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,s=e>0?t:0,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(l===1){const c=e<0;this._setEndings(c,!c,r)}else this._setEndings(!1,!1,r);this._loopCount=a,this.time=s,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this.time=s;if(r&&(a&1)===1)return t-s}return s}_setEndings(e,t,i){const s=this._interpolantSettings;i?(s.endingStart=nr,s.endingEnd=nr):(e?s.endingStart=this.zeroSlopeAtStart?nr:tr:s.endingStart=ic,t?s.endingEnd=this.zeroSlopeAtEnd?nr:tr:s.endingEnd=ic)}_scheduleFading(e,t,i){const s=this._mixer,a=s.time;let r=this._weightInterpolant;r===null&&(r=s._lendControlInterpolant(),this._weightInterpolant=r);const o=r.parameterPositions,l=r.sampleValues;return o[0]=a,l[0]=t,o[1]=a+e,l[1]=i,this}}const BP=new Float32Array(1);class DT extends Ts{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const i=e._localRoot||this._root,s=e._clip.tracks,a=s.length,r=e._propertyBindings,o=e._interpolants,l=i.uuid,c=this._bindingsByRootAndName;let u=c[l];u===void 0&&(u={},c[l]=u);for(let d=0;d!==a;++d){const h=s[d],f=h.name;let p=u[f];if(p!==void 0)++p.referenceCount,r[d]=p;else{if(p=r[d],p!==void 0){p._cacheIndex===null&&(++p.referenceCount,this._addInactiveBinding(p,l,f));continue}const g=t&&t._propertyBindings[d].binding.parsedPath;p=new LT(vt.create(i,f,g),h.ValueTypeName,h.getValueSize()),++p.referenceCount,this._addInactiveBinding(p,l,f),r[d]=p}o[d].resultBuffer=p.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){const i=(e._localRoot||this._root).uuid,s=e._clip.uuid,a=this._actionsByClip[s];this._bindAction(e,a&&a.knownActions[0]),this._addInactiveAction(e,s,i)}const t=e._propertyBindings;for(let i=0,s=t.length;i!==s;++i){const a=t[i];a.useCount++===0&&(this._lendBinding(a),a.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let i=0,s=t.length;i!==s;++i){const a=t[i];--a.useCount===0&&(a.restoreOriginalState(),this._takeBackBinding(a))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return t!==null&&t=0;--i)e[i].stop();return this}update(e){e*=this.timeScale;const t=this._actions,i=this._nActiveActions,s=this.time+=e,a=Math.sign(e),r=this._accuIndex^=1;for(let c=0;c!==i;++c)t[c]._update(s,e,a,r);const o=this._bindings,l=this._nActiveBindings;for(let c=0;c!==l;++c)o[c].apply(r);return this}setTime(e){this.time=0;for(let t=0;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,z0).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const H0=new T,yu=new T,Xr=new T,Kr=new T,xp=new T,jP=new T,ZP=new T;class JP{constructor(e=new T,t=new T){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){H0.subVectors(e,this.start),yu.subVectors(this.end,this.start);const i=yu.dot(yu);let a=yu.dot(H0)/i;return t&&(a=Je(a,0,1)),a}closestPointToPoint(e,t,i){const s=this.closestPointToPointParameter(e,t);return this.delta(i).multiplyScalar(s).add(this.start)}distanceSqToLine3(e,t=jP,i=ZP){const s=10000000000000001e-32;let a,r;const o=this.start,l=e.start,c=this.end,u=e.end;Xr.subVectors(c,o),Kr.subVectors(u,l),xp.subVectors(o,l);const d=Xr.dot(Xr),h=Kr.dot(Kr),f=Kr.dot(xp);if(d<=s&&h<=s)return t.copy(o),i.copy(l),t.sub(i),t.dot(t);if(d<=s)a=0,r=f/h,r=Je(r,0,1);else{const p=Xr.dot(xp);if(h<=s)r=0,a=Je(-p/d,0,1);else{const g=Xr.dot(Kr),_=d*h-g*g;_!==0?a=Je((g*f-p*h)/_,0,1):a=0,r=(g*a+f)/h,r<0?(r=0,a=Je(-p/d,0,1)):r>1&&(r=1,a=Je((g-p)/d,0,1))}}return t.copy(o).add(Xr.multiplyScalar(a)),i.copy(l).add(Kr.multiplyScalar(r)),t.sub(i),t.dot(t)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}const V0=new T;class QP extends et{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const i=new $e,s=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let r=0,o=1,l=32;r1)for(let d=0;d.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{K0.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(K0,t)}}setLength(e,t=e*.2,i=t*.2){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(i,t,i),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class dI extends Fn{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],i=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],s=new $e;s.setAttribute("position",new Ce(t,3)),s.setAttribute("color",new Ce(i,3));const a=new Pt({vertexColors:!0,toneMapped:!1});super(s,a),this.type="AxesHelper"}setColors(e,t,i){const s=new de,a=this.geometry.attributes.color.array;return s.set(e),s.toArray(a,0),s.toArray(a,3),s.set(t),s.toArray(a,6),s.toArray(a,9),s.set(i),s.toArray(a,12),s.toArray(a,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class hI{constructor(){this.type="ShapePath",this.color=new de,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new vh,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,i,s){return this.currentPath.quadraticCurveTo(e,t,i,s),this}bezierCurveTo(e,t,i,s,a,r){return this.currentPath.bezierCurveTo(e,t,i,s,a,r),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(m){const v=[];for(let y=0,b=m.length;yNumber.EPSILON){if(E<0&&(M=v[x],w=-w,C=v[S],E=-E),m.yC.y)continue;if(m.y===M.y){if(m.x===M.x)return!0}else{const R=E*(m.x-M.x)-w*(m.y-M.y);if(R===0)return!0;if(R<0)continue;b=!b}}else{if(m.y!==M.y)continue;if(C.x<=m.x&&m.x<=M.x||M.x<=m.x&&m.x<=C.x)return!0}}return b}const s=Li.isClockWise,a=this.subPaths;if(a.length===0)return[];let r,o,l;const c=[];if(a.length===1)return o=a[0],l=new $s,l.curves=o.curves,c.push(l),c;let u=!s(a[0].getPoints());u=e?!u:u;const d=[],h=[];let f=[],p=0,g;h[p]=void 0,f[p]=[];for(let m=0,v=a.length;m1){let m=!1,v=0;for(let y=0,b=h.length;y0&&m===!1&&(f=d)}let _;for(let m=0,v=h.length;me?(n.repeat.x=1,n.repeat.y=t/e,n.offset.x=0,n.offset.y=(1-n.repeat.y)/2):(n.repeat.x=e/t,n.repeat.y=1,n.offset.x=(1-n.repeat.x)/2,n.offset.y=0),n}function pI(n,e){const t=n.image&&n.image.width?n.image.width/n.image.height:1;return t>e?(n.repeat.x=e/t,n.repeat.y=1,n.offset.x=(1-n.repeat.x)/2,n.offset.y=0):(n.repeat.x=1,n.repeat.y=t/e,n.offset.x=0,n.offset.y=(1-n.repeat.y)/2),n}function mI(n){return n.repeat.x=1,n.repeat.y=1,n.offset.x=0,n.offset.y=0,n}function t_(n,e,t,i){const s=_I(i);switch(t){case gg:return n*e;case Xh:return n*e/s.components*s.byteLength;case wc:return n*e/s.components*s.byteLength;case vg:return n*e*2/s.components*s.byteLength;case Kh:return n*e*2/s.components*s.byteLength;case yg:return n*e*3/s.components*s.byteLength;case Xn:return n*e*4/s.components*s.byteLength;case qh:return n*e*4/s.components*s.byteLength;case Hl:case Vl:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case Gl:case $l:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case Hd:case Gd:return Math.max(n,16)*Math.max(e,8)/4;case zd:case Vd:return Math.max(n,8)*Math.max(e,8)/2;case $d:case Wd:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case Xd:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case Kd:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case qd:return Math.floor((n+4)/5)*Math.floor((e+3)/4)*16;case Yd:return Math.floor((n+4)/5)*Math.floor((e+4)/5)*16;case jd:return Math.floor((n+5)/6)*Math.floor((e+4)/5)*16;case Zd:return Math.floor((n+5)/6)*Math.floor((e+5)/6)*16;case Jd:return Math.floor((n+7)/8)*Math.floor((e+4)/5)*16;case Qd:return Math.floor((n+7)/8)*Math.floor((e+5)/6)*16;case eh:return Math.floor((n+7)/8)*Math.floor((e+7)/8)*16;case th:return Math.floor((n+9)/10)*Math.floor((e+4)/5)*16;case nh:return Math.floor((n+9)/10)*Math.floor((e+5)/6)*16;case ih:return Math.floor((n+9)/10)*Math.floor((e+7)/8)*16;case sh:return Math.floor((n+9)/10)*Math.floor((e+9)/10)*16;case ah:return Math.floor((n+11)/12)*Math.floor((e+9)/10)*16;case rh:return Math.floor((n+11)/12)*Math.floor((e+11)/12)*16;case oh:case lh:case ch:return Math.ceil(n/4)*Math.ceil(e/4)*16;case uh:case dh:return Math.ceil(n/4)*Math.ceil(e/4)*8;case hh:case fh:return Math.ceil(n/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function _I(n){switch(n){case ns:case fg:return{byteLength:1,components:1};case Ro:case pg:case ms:return{byteLength:2,components:1};case $h:case Wh:return{byteLength:2,components:4};case Ks:case Gh:case Mn:return{byteLength:4,components:1};case mg:case _g:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${n}.`)}class gI{static contain(e,t){return fI(e,t)}static cover(e,t){return pI(e,t)}static fill(e){return mI(e)}static getByteLength(e,t,i,s){return t_(e,t,i,s)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:zh}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=zh);function NT(){let n=null,e=!1,t=null,i=null;function s(a,r){t(a,r),i=n.requestAnimationFrame(s)}return{start:function(){e!==!0&&t!==null&&(i=n.requestAnimationFrame(s),e=!0)},stop:function(){n.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(a){t=a},setContext:function(a){n=a}}}function yI(n){const e=new WeakMap;function t(o,l){const c=o.array,u=o.usage,d=c.byteLength,h=n.createBuffer();n.bindBuffer(l,h),n.bufferData(l,c,u),o.onUploadCallback();let f;if(c instanceof Float32Array)f=n.FLOAT;else if(typeof Float16Array<"u"&&c instanceof Float16Array)f=n.HALF_FLOAT;else if(c instanceof Uint16Array)o.isFloat16BufferAttribute?f=n.HALF_FLOAT:f=n.UNSIGNED_SHORT;else if(c instanceof Int16Array)f=n.SHORT;else if(c instanceof Uint32Array)f=n.UNSIGNED_INT;else if(c instanceof Int32Array)f=n.INT;else if(c instanceof Int8Array)f=n.BYTE;else if(c instanceof Uint8Array)f=n.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)f=n.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:h,type:f,bytesPerElement:c.BYTES_PER_ELEMENT,version:o.version,size:d}}function i(o,l,c){const u=l.array,d=l.updateRanges;if(n.bindBuffer(c,o),d.length===0)n.bufferSubData(c,0,u);else{d.sort((f,p)=>f.start-p.start);let h=0;for(let f=1;ff+p?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&h<=f-p&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(a=t.getPose(e.gripSpace,i),a!==null&&(l.matrix.fromArray(a.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,a.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(a.linearVelocity)):l.hasLinearVelocity=!1,a.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(a.angularVelocity)):l.hasAngularVelocity=!1));o!==null&&(s=t.getPose(e.targetRaySpace,i),s===null&&a!==null&&(s=a),s!==null&&(o.matrix.fromArray(s.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,s.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(s.linearVelocity)):o.hasLinearVelocity=!1,s.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(s.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(CR)))}return o!==null&&(o.visible=s!==null),l!==null&&(l.visible=a!==null),c!==null&&(c.visible=r!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const i=new Et;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}class lf{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new de(e),this.density=t}clone(){return new lf(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class cf{constructor(e,t=1,i=1e3){this.isFog=!0,this.name="",this.color=new de(e),this.near=t,this.far=i}clone(){return new cf(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class Ac extends et{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new rn,this.environmentIntensity=1,this.environmentRotation=new rn,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class Rc{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=cc,this.updateRanges=[],this.version=0,this.uuid=bi()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,i){e*=this.stride,i*=t.stride;for(let s=0,a=this.stride;se.far||t.push({distance:l,point:cl.clone(),uv:ii.getInterpolation(cl,nu,dl,iu,h0,hp,f0,new ne),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}}function su(n,e,t,i,s,a){$r.subVectors(n,t).addScalar(.5).multiply(i),s!==void 0?(ul.x=a*$r.x-s*$r.y,ul.y=s*$r.x+a*$r.y):ul.copy($r),n.copy(e),n.x+=ul.x,n.y+=ul.y,n.applyMatrix4(oT)}const au=new T,p0=new T;class lT extends et{constructor(){super(),this.isLOD=!0,this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);const t=e.levels;for(let i=0,s=t.length;i0){let i,s;for(i=1,s=t.length;i0){au.setFromMatrixPosition(this.matrixWorld);const s=e.ray.origin.distanceTo(au);this.getObjectForDistance(s).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){au.setFromMatrixPosition(e.matrixWorld),p0.setFromMatrixPosition(this.matrixWorld);const i=au.distanceTo(p0)/e.zoom;t[0].object.visible=!0;let s,a;for(s=1,a=t.length;s=r)t[s-1].object.visible=!1,t[s].object.visible=!0;else break}for(this._currentLevel=s-1;s1?null:t.copy(e.start).addScaledVector(i,a)}intersectsLine(e){const t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const i=t||LR.getNormalMatrix(e),s=this.coplanarPoint(mp).applyMatrix4(e),a=this.normal.applyMatrix3(i).normalize();return this.constant=-s.dot(a),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Ra=new xn,kR=new ne(.5,.5),lu=new T;class Ko{constructor(e=new Ns,t=new Ns,i=new Ns,s=new Ns,a=new Ns,r=new Ns){this.planes=[e,t,i,s,a,r]}set(e,t,i,s,a,r){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(i),o[3].copy(s),o[4].copy(a),o[5].copy(r),this}copy(e){const t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=yi,i=!1){const s=this.planes,a=e.elements,r=a[0],o=a[1],l=a[2],c=a[3],u=a[4],d=a[5],h=a[6],f=a[7],p=a[8],g=a[9],_=a[10],m=a[11],v=a[12],y=a[13],b=a[14],S=a[15];if(s[0].setComponents(c-r,f-u,m-p,S-v).normalize(),s[1].setComponents(c+r,f+u,m+p,S+v).normalize(),s[2].setComponents(c+o,f+d,m+g,S+y).normalize(),s[3].setComponents(c-o,f-d,m-g,S-y).normalize(),i)s[4].setComponents(l,h,_,b).normalize(),s[5].setComponents(c-l,f-h,m-_,S-b).normalize();else if(s[4].setComponents(c-l,f-h,m-_,S-b).normalize(),t===yi)s[5].setComponents(c+l,f+h,m+_,S+b).normalize();else if(t===No)s[5].setComponents(l,h,_,b).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Ra.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Ra.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Ra)}intersectsSprite(e){Ra.center.set(0,0,0);const t=kR.distanceTo(e.center);return Ra.radius=.7071067811865476+t,Ra.applyMatrix4(e.matrixWorld),this.intersectsSphere(Ra)}intersectsSphere(e){const t=this.planes,i=e.center,s=-e.radius;for(let a=0;a<6;a++)if(t[a].distanceToPoint(i)0?e.max.x:e.min.x,lu.y=s.normal.y>0?e.max.y:e.min.y,lu.z=s.normal.z>0?e.max.z:e.min.z,s.distanceToPoint(lu)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}const rs=new Ee,os=new Ko;class pf{constructor(){this.coordinateSystem=yi}intersectsObject(e,t){if(!t.isArrayCamera||t.cameras.length===0)return!1;for(let i=0;i=a.length&&a.push({start:-1,count:-1,z:-1,index:-1});const o=a[this.index];r.push(o),this.index++,o.start=e,o.count=t,o.z=i,o.index=s}reset(){this.list.length=0,this.index=0}}const Yn=new Ee,NR=new de(1,1,1),S0=new Ko,UR=new pf,cu=new bn,Pa=new xn,pl=new T,T0=new T,BR=new T,gp=new FR,Rn=new Se,uu=[];function zR(n,e,t=0){const i=e.itemSize;if(n.isInterleavedBufferAttribute||n.array.constructor!==e.array.constructor){const s=n.count;for(let a=0;a65535?new Uint32Array(s):new Uint16Array(s);t.setIndex(new lt(a,1))}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;if(!!e.getIndex()!=!!t.getIndex())throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');for(const i in t.attributes){if(!e.hasAttribute(i))throw new Error(`THREE.BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`);const s=e.getAttribute(i),a=t.getAttribute(i);if(s.itemSize!==a.itemSize||s.normalized!==a.normalized)throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}validateInstanceId(e){const t=this._instanceInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid instanceId ${e}. Instance is either out of range or has been deleted.`)}validateGeometryId(e){const t=this._geometryInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`)}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new bn);const e=this.boundingBox,t=this._instanceInfo;e.makeEmpty();for(let i=0,s=t.length;i=this.maxInstanceCount&&this._availableInstanceIds.length===0)throw new Error("THREE.BatchedMesh: Maximum item count reached.");const i={visible:!0,active:!0,geometryIndex:e};let s=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(_p),s=this._availableInstanceIds.shift(),this._instanceInfo[s]=i):(s=this._instanceInfo.length,this._instanceInfo.push(i));const a=this._matricesTexture;Yn.identity().toArray(a.image.data,s*16),a.needsUpdate=!0;const r=this._colorsTexture;return r&&(NR.toArray(r.image.data,s*4),r.needsUpdate=!0),this._visibilityChanged=!0,s}addGeometry(e,t=-1,i=-1){this._initializeGeometry(e),this._validateGeometry(e);const s={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},a=this._geometryInfo;s.vertexStart=this._nextVertexStart,s.reservedVertexCount=t===-1?e.getAttribute("position").count:t;const r=e.getIndex();if(r!==null&&(s.indexStart=this._nextIndexStart,s.reservedIndexCount=i===-1?r.count:i),s.indexStart!==-1&&s.indexStart+s.reservedIndexCount>this._maxIndexCount||s.vertexStart+s.reservedVertexCount>this._maxVertexCount)throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");let l;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(_p),l=this._availableGeometryIds.shift(),a[l]=s):(l=this._geometryCount,this._geometryCount++,a.push(s)),this.setGeometryAt(l,e),this._nextIndexStart=s.indexStart+s.reservedIndexCount,this._nextVertexStart=s.vertexStart+s.reservedVertexCount,l}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,s=i.getIndex()!==null,a=i.getIndex(),r=t.getIndex(),o=this._geometryInfo[e];if(s&&r.count>o.reservedIndexCount||t.attributes.position.count>o.reservedVertexCount)throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");const l=o.vertexStart,c=o.reservedVertexCount;o.vertexCount=t.getAttribute("position").count;for(const u in i.attributes){const d=t.getAttribute(u),h=i.getAttribute(u);zR(d,h,l);const f=d.itemSize;for(let p=d.count,g=c;p=t.length||t[e].active===!1)return this;const i=this._instanceInfo;for(let s=0,a=i.length;so).sort((r,o)=>i[r].vertexStart-i[o].vertexStart),a=this.geometry;for(let r=0,o=i.length;r=this._geometryCount)return null;const i=this.geometry,s=this._geometryInfo[e];if(s.boundingBox===null){const a=new bn,r=i.index,o=i.attributes.position;for(let l=s.start,c=s.start+s.count;l=this._geometryCount)return null;const i=this.geometry,s=this._geometryInfo[e];if(s.boundingSphere===null){const a=new xn;this.getBoundingBoxAt(e,cu),cu.getCenter(a.center);const r=i.index,o=i.attributes.position;let l=0;for(let c=s.start,u=s.start+s.count;co.active);if(Math.max(...i.map(o=>o.vertexStart+o.reservedVertexCount))>e)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${t}. Cannot shrink further.`);if(this.geometry.index&&Math.max(...i.map(l=>l.indexStart+l.reservedIndexCount))>t)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${t}. Cannot shrink further.`);const a=this.geometry;a.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new $e,this._initializeGeometry(a));const r=this.geometry;a.index&&Ia(a.index.array,r.index.array);for(const o in a.attributes)Ia(a.attributes[o].array,r.attributes[o].array)}raycast(e,t){const i=this._instanceInfo,s=this._geometryInfo,a=this.matrixWorld,r=this.geometry;Rn.material=this.material,Rn.geometry.index=r.index,Rn.geometry.attributes=r.attributes,Rn.geometry.boundingBox===null&&(Rn.geometry.boundingBox=new bn),Rn.geometry.boundingSphere===null&&(Rn.geometry.boundingSphere=new xn);for(let o=0,l=i.length;o({...t,boundingBox:t.boundingBox!==null?t.boundingBox.clone():null,boundingSphere:t.boundingSphere!==null?t.boundingSphere.clone():null})),this._instanceInfo=e._instanceInfo.map(t=>({...t})),this._availableInstanceIds=e._availableInstanceIds.slice(),this._availableGeometryIds=e._availableGeometryIds.slice(),this._nextIndexStart=e._nextIndexStart,this._nextVertexStart=e._nextVertexStart,this._geometryCount=e._geometryCount,this._maxInstanceCount=e._maxInstanceCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._indirectTexture=e._indirectTexture.clone(),this._indirectTexture.image.data=this._indirectTexture.image.data.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),this._colorsTexture!==null&&(this._colorsTexture=e._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,this._colorsTexture!==null&&(this._colorsTexture.dispose(),this._colorsTexture=null)}onBeforeRender(e,t,i,s,a){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const r=s.getIndex(),o=r===null?1:r.array.BYTES_PER_ELEMENT,l=this._instanceInfo,c=this._multiDrawStarts,u=this._multiDrawCounts,d=this._geometryInfo,h=this.perObjectFrustumCulled,f=this._indirectTexture,p=f.image.data,g=i.isArrayCamera?UR:S0;h&&!i.isArrayCamera&&(Yn.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse).multiply(this.matrixWorld),S0.setFromProjectionMatrix(Yn,i.coordinateSystem,i.reversedDepth));let _=0;if(this.sortObjects){Yn.copy(this.matrixWorld).invert(),pl.setFromMatrixPosition(i.matrixWorld).applyMatrix4(Yn),T0.set(0,0,-1).transformDirection(i.matrixWorld).transformDirection(Yn);for(let y=0,b=l.length;y0){const s=t[i[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,r=s.length;ai)return;yp.applyMatrix4(n.matrixWorld);const c=e.ray.origin.distanceTo(yp);if(!(ce.far))return{distance:c,point:E0.clone().applyMatrix4(n.matrixWorld),index:r,face:null,faceIndex:null,barycoord:null,object:n}}const C0=new T,A0=new T;class Fn extends On{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,i=[];for(let s=0,a=t.count;s0){const s=t[i[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,r=s.length;as.far)return;a.push({distance:c,distanceToRay:Math.sqrt(o),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:r})}}class uT extends zt{constructor(e,t,i,s,a=Gt,r=Gt,o,l,c){super(e,t,i,s,a,r,o,l,c),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;const u=this;function d(){u.needsUpdate=!0,u._requestVideoFrameCallbackId=e.requestVideoFrameCallback(d)}"requestVideoFrameCallback"in e&&(this._requestVideoFrameCallbackId=e.requestVideoFrameCallback(d))}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;"requestVideoFrameCallback"in e===!1&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),super.dispose()}}class HR extends uT{constructor(e,t,i,s,a,r,o,l){super({},e,t,i,s,a,r,o,l),this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(e){this.image=e,this.needsUpdate=!0}}class VR extends zt{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=hn,this.minFilter=hn,this.generateMipmaps=!1,this.needsUpdate=!0}}class mf extends zt{constructor(e,t,i,s,a,r,o,l,c,u,d,h){super(null,r,o,l,c,u,s,a,d,h),this.isCompressedTexture=!0,this.image={width:t,height:i},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class GR extends mf{constructor(e,t,i,s,a,r){super(e,t,i,a,r),this.isCompressedArrayTexture=!0,this.image.depth=s,this.wrapR=Wn,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class $R extends mf{constructor(e,t,i){super(void 0,e[0].width,e[0].height,t,i,Xs),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class Pc extends zt{constructor(e,t,i,s,a,r,o,l,c){super(e,t,i,s,a,r,o,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Dg extends zt{constructor(e,t,i=Ks,s,a,r,o=hn,l=hn,c,u=Do,d=1){if(u!==Do&&u!==Oo)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const h={width:e,height:t,depth:d};super(h,s,a,r,o,l,u,i,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new ha(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class Og extends zt{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class _f extends $e{constructor(e=1,t=1,i=4,s=8,a=1){super(),this.type="CapsuleGeometry",this.parameters={radius:e,height:t,capSegments:i,radialSegments:s,heightSegments:a},t=Math.max(0,t),i=Math.max(1,Math.floor(i)),s=Math.max(3,Math.floor(s)),a=Math.max(1,Math.floor(a));const r=[],o=[],l=[],c=[],u=t/2,d=Math.PI/2*e,h=t,f=2*d+h,p=i*2+a,g=s+1,_=new T,m=new T;for(let v=0;v<=p;v++){let y=0,b=0,S=0,x=0;if(v<=i){const w=v/i,E=w*Math.PI/2;b=-u-e*Math.cos(E),S=e*Math.sin(E),x=-e*Math.cos(E),y=w*d}else if(v<=i+a){const w=(v-i)/a;b=-u+w*t,S=e,x=0,y=d+w*h}else{const w=(v-i-a)/i,E=w*Math.PI/2;b=u+e*Math.sin(E),S=e*Math.cos(E),x=e*Math.sin(E),y=d+h+w*d}const M=Math.max(0,Math.min(1,y/f));let C=0;v===0?C=.5/s:v===p&&(C=-.5/s);for(let w=0;w<=s;w++){const E=w/s,R=E*Math.PI*2,L=Math.sin(R),O=Math.cos(R);m.x=-S*O,m.y=b,m.z=S*L,o.push(m.x,m.y,m.z),_.set(-S*O,x,S*L),_.normalize(),l.push(_.x,_.y,_.z),c.push(E+C,M)}if(v>0){const w=(v-1)*g;for(let E=0;E0&&y(!0),t>0&&y(!1)),this.setIndex(u),this.setAttribute("position",new Ce(d,3)),this.setAttribute("normal",new Ce(h,3)),this.setAttribute("uv",new Ce(f,2));function v(){const b=new T,S=new T;let x=0;const M=(t-e)/i;for(let C=0;C<=a;C++){const w=[],E=C/a,R=E*(t-e)+e;for(let L=0;L<=s;L++){const O=L/s,D=O*l+o,U=Math.sin(D),F=Math.cos(D);S.x=R*U,S.y=-E*i+_,S.z=R*F,d.push(S.x,S.y,S.z),b.set(U,M,F).normalize(),h.push(b.x,b.y,b.z),f.push(O,1-E),w.push(p++)}g.push(w)}for(let C=0;C0||w!==0)&&(u.push(E,R,O),x+=3),(t>0||w!==a-1)&&(u.push(R,L,O),x+=3)}c.addGroup(m,x,0),m+=x}function y(b){const S=p,x=new ne,M=new T;let C=0;const w=b===!0?e:t,E=b===!0?1:-1;for(let L=1;L<=s;L++)d.push(0,_*E,0),h.push(0,E,0),f.push(.5,.5),p++;const R=p;for(let L=0;L<=s;L++){const D=L/s*l+o,U=Math.cos(D),F=Math.sin(D);M.x=w*F,M.y=_*E,M.z=w*U,d.push(M.x,M.y,M.z),h.push(0,E,0),x.x=U*.5+.5,x.y=F*.5*E+.5,f.push(x.x,x.y),p++}for(let L=0;L.9&&M<.1&&(y<.2&&(r[v+0]+=1),b<.2&&(r[v+2]+=1),S<.2&&(r[v+4]+=1))}}function h(v){a.push(v.x,v.y,v.z)}function f(v,y){const b=v*3;y.x=e[b+0],y.y=e[b+1],y.z=e[b+2]}function p(){const v=new T,y=new T,b=new T,S=new T,x=new ne,M=new ne,C=new ne;for(let w=0,E=0;w0)l=s-1;else{l=s;break}if(s=l,i[s]===r)return s/(a-1);const u=i[s],h=i[s+1]-u,f=(r-u)/h;return(s+f)/(a-1)}getTangent(e,t){let s=e-1e-4,a=e+1e-4;s<0&&(s=0),a>1&&(a=1);const r=this.getPoint(s),o=this.getPoint(a),l=t||(r.isVector2?new ne:new T);return l.copy(o).sub(r).normalize(),l}getTangentAt(e,t){const i=this.getUtoTmapping(e);return this.getTangent(i,t)}computeFrenetFrames(e,t=!1){const i=new T,s=[],a=[],r=[],o=new T,l=new Ee;for(let f=0;f<=e;f++){const p=f/e;s[f]=this.getTangentAt(p,new T)}a[0]=new T,r[0]=new T;let c=Number.MAX_VALUE;const u=Math.abs(s[0].x),d=Math.abs(s[0].y),h=Math.abs(s[0].z);u<=c&&(c=u,i.set(1,0,0)),d<=c&&(c=d,i.set(0,1,0)),h<=c&&i.set(0,0,1),o.crossVectors(s[0],i).normalize(),a[0].crossVectors(s[0],o),r[0].crossVectors(s[0],a[0]);for(let f=1;f<=e;f++){if(a[f]=a[f-1].clone(),r[f]=r[f-1].clone(),o.crossVectors(s[f-1],s[f]),o.length()>Number.EPSILON){o.normalize();const p=Math.acos(Je(s[f-1].dot(s[f]),-1,1));a[f].applyMatrix4(l.makeRotationAxis(o,p))}r[f].crossVectors(s[f],a[f])}if(t===!0){let f=Math.acos(Je(a[0].dot(a[e]),-1,1));f/=e,s[0].dot(o.crossVectors(a[0],a[e]))>0&&(f=-f);for(let p=1;p<=e;p++)a[p].applyMatrix4(l.makeRotationAxis(s[p],f*p)),r[p].crossVectors(s[p],a[p])}return{tangents:s,normals:a,binormals:r}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class vf extends Fi{constructor(e=0,t=0,i=1,s=1,a=0,r=Math.PI*2,o=!1,l=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=i,this.yRadius=s,this.aStartAngle=a,this.aEndAngle=r,this.aClockwise=o,this.aRotation=l}getPoint(e,t=new ne){const i=t,s=Math.PI*2;let a=this.aEndAngle-this.aStartAngle;const r=Math.abs(a)s;)a-=s;a0?0:(Math.floor(Math.abs(o)/a)+1)*a:l===0&&o===a-1&&(o=a-2,l=1);let c,u;this.closed||o>0?c=s[(o-1)%a]:(yu.subVectors(s[0],s[1]).add(s[0]),c=yu);const d=s[o%a],h=s[(o+1)%a];if(this.closed||o+2s.length-2?s.length-1:r+1],d=s[r>s.length-3?s.length-1:r+2];return i.set(I0(o,l.x,c.x,u.x,d.x),I0(o,l.y,c.y,u.y,d.y)),i}copy(e){super.copy(e),this.points=[];for(let t=0,i=e.points.length;t=i){const r=s[a]-i,o=this.curves[a],l=o.getLength(),c=l===0?0:1-r/l;return o.getPointAt(c,t)}a++}return null}getLength(){const e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const e=[];let t=0;for(let i=0,s=this.curves.length;i1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,i=e.curves.length;t0){const d=c.getPoint(0);d.equals(this.currentPoint)||this.lineTo(d.x,d.y)}this.curves.push(c);const u=c.getPoint(1);return this.currentPoint.copy(u),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class $s extends Mh{constructor(e){super(e),this.uuid=bi(),this.type="Shape",this.holes=[]}getPointsHoles(e){const t=[];for(let i=0,s=this.holes.length;i80*t){o=1/0,l=1/0;let u=-1/0,d=-1/0;for(let h=t;hu&&(u=f),p>d&&(d=p)}c=Math.max(u-o,d-l),c=c!==0?32767/c:0}return hc(a,r,t,o,l,c,0),r}function mT(n,e,t,i,s){let a;if(s===pP(n,e,t,i)>0)for(let r=e;r=e;r-=i)a=L0(r/i|0,n[r],n[r+1],a);return a&&Ho(a,a.next)&&(pc(a),a=a.next),a}function vr(n,e){if(!n)return n;e||(e=n);let t=n,i;do if(i=!1,!t.steiner&&(Ho(t,t.next)||qt(t.prev,t,t.next)===0)){if(pc(t),t=e=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==e);return e}function hc(n,e,t,i,s,a,r){if(!n)return;!r&&a&&lP(n,i,s,a);let o=n;for(;n.prev!==n.next;){const l=n.prev,c=n.next;if(a?eP(n,i,s,a):QR(n)){e.push(l.i,n.i,c.i),pc(n),n=c.next,o=c.next;continue}if(n=c,n===o){r?r===1?(n=tP(vr(n),e),hc(n,e,t,i,s,a,2)):r===2&&nP(n,e,t,i,s,a):hc(vr(n),e,t,i,s,a,1);break}}}function QR(n){const e=n.prev,t=n,i=n.next;if(qt(e,t,i)>=0)return!1;const s=e.x,a=t.x,r=i.x,o=e.y,l=t.y,c=i.y,u=Math.min(s,a,r),d=Math.min(o,l,c),h=Math.max(s,a,r),f=Math.max(o,l,c);let p=i.next;for(;p!==e;){if(p.x>=u&&p.x<=h&&p.y>=d&&p.y<=f&&Ll(s,o,a,l,r,c,p.x,p.y)&&qt(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function eP(n,e,t,i){const s=n.prev,a=n,r=n.next;if(qt(s,a,r)>=0)return!1;const o=s.x,l=a.x,c=r.x,u=s.y,d=a.y,h=r.y,f=Math.min(o,l,c),p=Math.min(u,d,h),g=Math.max(o,l,c),_=Math.max(u,d,h),m=i_(f,p,e,t,i),v=i_(g,_,e,t,i);let y=n.prevZ,b=n.nextZ;for(;y&&y.z>=m&&b&&b.z<=v;){if(y.x>=f&&y.x<=g&&y.y>=p&&y.y<=_&&y!==s&&y!==r&&Ll(o,u,l,d,c,h,y.x,y.y)&&qt(y.prev,y,y.next)>=0||(y=y.prevZ,b.x>=f&&b.x<=g&&b.y>=p&&b.y<=_&&b!==s&&b!==r&&Ll(o,u,l,d,c,h,b.x,b.y)&&qt(b.prev,b,b.next)>=0))return!1;b=b.nextZ}for(;y&&y.z>=m;){if(y.x>=f&&y.x<=g&&y.y>=p&&y.y<=_&&y!==s&&y!==r&&Ll(o,u,l,d,c,h,y.x,y.y)&&qt(y.prev,y,y.next)>=0)return!1;y=y.prevZ}for(;b&&b.z<=v;){if(b.x>=f&&b.x<=g&&b.y>=p&&b.y<=_&&b!==s&&b!==r&&Ll(o,u,l,d,c,h,b.x,b.y)&&qt(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function tP(n,e){let t=n;do{const i=t.prev,s=t.next.next;!Ho(i,s)&&gT(i,t,t.next,s)&&fc(i,s)&&fc(s,i)&&(e.push(i.i,t.i,s.i),pc(t),pc(t.next),t=n=s),t=t.next}while(t!==n);return vr(t)}function nP(n,e,t,i,s,a){let r=n;do{let o=r.next.next;for(;o!==r.prev;){if(r.i!==o.i&&dP(r,o)){let l=yT(r,o);r=vr(r,r.next),l=vr(l,l.next),hc(r,e,t,i,s,a,0),hc(l,e,t,i,s,a,0);return}o=o.next}r=r.next}while(r!==n)}function iP(n,e,t,i){const s=[];for(let a=0,r=e.length;a=t.next.y&&t.next.y!==t.y){const d=t.x+(s-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(d<=i&&d>a&&(a=d,r=t.x=t.x&&t.x>=l&&i!==t.x&&_T(sr.x||t.x===r.x&&oP(r,t)))&&(r=t,u=d)}t=t.next}while(t!==o);return r}function oP(n,e){return qt(n.prev,n,e.prev)<0&&qt(e.next,n,n.next)<0}function lP(n,e,t,i){let s=n;do s.z===0&&(s.z=i_(s.x,s.y,e,t,i)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next;while(s!==n);s.prevZ.nextZ=null,s.prevZ=null,cP(s)}function cP(n){let e,t=1;do{let i=n,s;n=null;let a=null;for(e=0;i;){e++;let r=i,o=0;for(let c=0;c0||l>0&&r;)o!==0&&(l===0||!r||i.z<=r.z)?(s=i,i=i.nextZ,o--):(s=r,r=r.nextZ,l--),a?a.nextZ=s:n=s,s.prevZ=a,a=s;i=r}a.nextZ=null,t*=2}while(e>1);return n}function i_(n,e,t,i,s){return n=(n-t)*s|0,e=(e-i)*s|0,n=(n|n<<8)&16711935,n=(n|n<<4)&252645135,n=(n|n<<2)&858993459,n=(n|n<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,n|e<<1}function uP(n){let e=n,t=n;do(e.x=(n-r)*(a-o)&&(n-r)*(i-o)>=(t-r)*(e-o)&&(t-r)*(a-o)>=(s-r)*(i-o)}function Ll(n,e,t,i,s,a,r,o){return!(n===r&&e===o)&&_T(n,e,t,i,s,a,r,o)}function dP(n,e){return n.next.i!==e.i&&n.prev.i!==e.i&&!hP(n,e)&&(fc(n,e)&&fc(e,n)&&fP(n,e)&&(qt(n.prev,n,e.prev)||qt(n,e.prev,e))||Ho(n,e)&&qt(n.prev,n,n.next)>0&&qt(e.prev,e,e.next)>0)}function qt(n,e,t){return(e.y-n.y)*(t.x-e.x)-(e.x-n.x)*(t.y-e.y)}function Ho(n,e){return n.x===e.x&&n.y===e.y}function gT(n,e,t,i){const s=bu(qt(n,e,t)),a=bu(qt(n,e,i)),r=bu(qt(t,i,n)),o=bu(qt(t,i,e));return!!(s!==a&&r!==o||s===0&&vu(n,t,e)||a===0&&vu(n,i,e)||r===0&&vu(t,n,i)||o===0&&vu(t,e,i))}function vu(n,e,t){return e.x<=Math.max(n.x,t.x)&&e.x>=Math.min(n.x,t.x)&&e.y<=Math.max(n.y,t.y)&&e.y>=Math.min(n.y,t.y)}function bu(n){return n>0?1:n<0?-1:0}function hP(n,e){let t=n;do{if(t.i!==n.i&&t.next.i!==n.i&&t.i!==e.i&&t.next.i!==e.i&&gT(t,t.next,n,e))return!0;t=t.next}while(t!==n);return!1}function fc(n,e){return qt(n.prev,n,n.next)<0?qt(n,e,n.next)>=0&&qt(n,n.prev,e)>=0:qt(n,e,n.prev)<0||qt(n,n.next,e)<0}function fP(n,e){let t=n,i=!1;const s=(n.x+e.x)/2,a=(n.y+e.y)/2;do t.y>a!=t.next.y>a&&t.next.y!==t.y&&s<(t.next.x-t.x)*(a-t.y)/(t.next.y-t.y)+t.x&&(i=!i),t=t.next;while(t!==n);return i}function yT(n,e){const t=s_(n.i,n.x,n.y),i=s_(e.i,e.x,e.y),s=n.next,a=e.prev;return n.next=e,e.prev=n,t.next=s,s.prev=t,i.next=t,t.prev=i,a.next=i,i.prev=a,i}function L0(n,e,t,i){const s=s_(n,e,t);return i?(s.next=i.next,s.prev=i,i.next.prev=s,i.next=s):(s.prev=s,s.next=s),s}function pc(n){n.next.prev=n.prev,n.prev.next=n.next,n.prevZ&&(n.prevZ.nextZ=n.nextZ),n.nextZ&&(n.nextZ.prevZ=n.prevZ)}function s_(n,e,t){return{i:n,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function pP(n,e,t,i){let s=0;for(let a=e,r=t-i;a2&&n[e-1].equals(n[0])&&n.pop()}function D0(n,e){for(let t=0;tNumber.EPSILON){const J=Math.sqrt(A),ce=Math.sqrt(st*st+I*I),ee=j.x-We/J,Ve=j.y+ye/J,ve=Y.x-I/ce,Be=Y.y+st/ce,ze=((ve-ee)*I-(Be-Ve)*st)/(ye*I-We*st);Q=ee+ye*ze-G.x,ge=Ve+We*ze-G.y;const he=Q*Q+ge*ge;if(he<=2)return new ne(Q,ge);ue=Math.sqrt(he/2)}else{let J=!1;ye>Number.EPSILON?st>Number.EPSILON&&(J=!0):ye<-Number.EPSILON?st<-Number.EPSILON&&(J=!0):Math.sign(We)===Math.sign(I)&&(J=!0),J?(Q=-We,ge=ye,ue=Math.sqrt(A)):(Q=ye,ge=We,ue=Math.sqrt(A/2))}return new ne(Q/ue,ge/ue)}const ie=[];for(let G=0,j=U.length,Y=j-1,Q=G+1;G=0;G--){const j=G/_,Y=f*Math.cos(j*Math.PI/2),Q=p*Math.sin(j*Math.PI/2)+g;for(let ge=0,ue=U.length;ge=0;){const Q=Y;let ge=Y-1;ge<0&&(ge=G.length-1);for(let ue=0,ye=u+_*2;ue0)&&f.push(y,b,x),(m!==i-1||l0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class sr extends en{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new de(16777215),this.specular=new de(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new de(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=xa,this.normalScale=new ne(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new rn,this.combine=Mc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class xT extends en{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new de(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new de(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=xa,this.normalScale=new ne(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class wT extends en{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=xa,this.normalScale=new ne(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class Cf extends en{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new de(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new de(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=xa,this.normalScale=new ne(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new rn,this.combine=Mc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class $g extends en{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=GS,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class Wg extends en{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class ST extends en{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new de(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=xa,this.normalScale=new ne(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}class TT extends Pt{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}function ar(n,e){return!n||n.constructor===e?n:typeof e.BYTES_PER_ELEMENT=="number"?new e(n):Array.prototype.slice.call(n)}function MT(n){return ArrayBuffer.isView(n)&&!(n instanceof DataView)}function ET(n){function e(s,a){return n[s]-n[a]}const t=n.length,i=new Array(t);for(let s=0;s!==t;++s)i[s]=s;return i.sort(e),i}function a_(n,e,t){const i=n.length,s=new n.constructor(i);for(let a=0,r=0;r!==i;++a){const o=t[a]*e;for(let l=0;l!==e;++l)s[r++]=n[o+l]}return s}function Xg(n,e,t,i){let s=1,a=n[0];for(;a!==void 0&&a[i]===void 0;)a=n[s++];if(a===void 0)return;let r=a[i];if(r!==void 0)if(Array.isArray(r))do r=a[i],r!==void 0&&(e.push(a.time),t.push(...r)),a=n[s++];while(a!==void 0);else if(r.toArray!==void 0)do r=a[i],r!==void 0&&(e.push(a.time),r.toArray(t,t.length)),a=n[s++];while(a!==void 0);else do r=a[i],r!==void 0&&(e.push(a.time),t.push(r)),a=n[s++];while(a!==void 0)}function vP(n,e,t,i,s=30){const a=n.clone();a.name=e;const r=[];for(let l=0;l=i)){d.push(c.times[f]);for(let g=0;ga.tracks[l].times[0]&&(o=a.tracks[l].times[0]);for(let l=0;l=o.times[p]){const m=p*d+u,v=m+d-u;g=o.values.slice(m,v)}else{const m=o.createInterpolant(),v=u,y=d-u;m.evaluate(a),g=m.resultBuffer.slice(v,y)}l==="quaternion"&&new ht().fromArray(g).normalize().conjugate().toArray(g);const _=c.times.length;for(let m=0;m<_;++m){const v=m*f+h;if(l==="quaternion")ht.multiplyQuaternionsFlat(c.values,v,g,0,c.values,v);else{const y=f-h*2;for(let b=0;b=a)){const o=t[1];e=a)break t}r=i,i=0;break n}break e}for(;i>>1;et;)--r;if(++r,a!==0||r!==s){a>=r&&(r=Math.max(r,1),a=r-1);const o=this.getValueSize();this.times=i.slice(a,r),this.values=this.values.slice(a*o,r*o)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const i=this.times,s=this.values,a=i.length;a===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let r=null;for(let o=0;o!==a;o++){const l=i[o];if(typeof l=="number"&&isNaN(l)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,o,l),e=!1;break}if(r!==null&&r>l){console.error("THREE.KeyframeTrack: Out of order keys.",this,o,l,r),e=!1;break}r=l}if(s!==void 0&&MT(s))for(let o=0,l=s.length;o!==l;++o){const c=s[o];if(isNaN(c)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,o,c),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),i=this.getValueSize(),s=this.getInterpolation()===hd,a=e.length-1;let r=1;for(let o=1;o0){e[r]=e[a];for(let o=a*i,l=r*i,c=0;c!==i;++c)t[l+c]=t[o+c];++r}return r!==e.length?(this.times=e.slice(0,r),this.values=t.slice(0,r*i)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),i=this.constructor,s=new i(this.name,e,t);return s.createInterpolant=this.createInterpolant,s}}Ni.prototype.ValueTypeName="";Ni.prototype.TimeBufferType=Float32Array;Ni.prototype.ValueBufferType=Float32Array;Ni.prototype.DefaultInterpolation=_r;class Mr extends Ni{constructor(e,t,i){super(e,t,i)}}Mr.prototype.ValueTypeName="bool";Mr.prototype.ValueBufferType=Array;Mr.prototype.DefaultInterpolation=Fo;Mr.prototype.InterpolantFactoryMethodLinear=void 0;Mr.prototype.InterpolantFactoryMethodSmooth=void 0;class qg extends Ni{constructor(e,t,i,s){super(e,t,i,s)}}qg.prototype.ValueTypeName="color";class ya extends Ni{constructor(e,t,i,s){super(e,t,i,s)}}ya.prototype.ValueTypeName="number";class RT extends Yo{constructor(e,t,i,s){super(e,t,i,s)}interpolate_(e,t,i,s){const a=this.resultBuffer,r=this.sampleValues,o=this.valueSize,l=(i-t)/(s-t);let c=e*o;for(let u=c+o;c!==u;c+=4)ht.slerpFlat(a,0,r,c-o,r,c,l);return a}}class Ss extends Ni{constructor(e,t,i,s){super(e,t,i,s)}InterpolantFactoryMethodLinear(e){return new RT(this.times,this.values,this.getValueSize(),e)}}Ss.prototype.ValueTypeName="quaternion";Ss.prototype.InterpolantFactoryMethodSmooth=void 0;class Er extends Ni{constructor(e,t,i){super(e,t,i)}}Er.prototype.ValueTypeName="string";Er.prototype.ValueBufferType=Array;Er.prototype.DefaultInterpolation=Fo;Er.prototype.InterpolantFactoryMethodLinear=void 0;Er.prototype.InterpolantFactoryMethodSmooth=void 0;class qs extends Ni{constructor(e,t,i,s){super(e,t,i,s)}}qs.prototype.ValueTypeName="vector";class va{constructor(e="",t=-1,i=[],s=tf){this.name=e,this.tracks=i,this.duration=t,this.blendMode=s,this.uuid=bi(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){const t=[],i=e.tracks,s=1/(e.fps||1);for(let r=0,o=i.length;r!==o;++r)t.push(SP(i[r]).scale(s));const a=new this(e.name,e.duration,t,e.blendMode);return a.uuid=e.uuid,a.userData=JSON.parse(e.userData||"{}"),a}static toJSON(e){const t=[],i=e.tracks,s={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let a=0,r=i.length;a!==r;++a)t.push(Ni.toJSON(i[a]));return s}static CreateFromMorphTargetSequence(e,t,i,s){const a=t.length,r=[];for(let o=0;o1){const d=u[1];let h=s[d];h||(s[d]=h=[]),h.push(c)}}const r=[];for(const o in s)r.push(this.CreateFromMorphTargetSequence(o,s[o],t,i));return r}static parseAnimation(e,t){if(console.warn("THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const i=function(d,h,f,p,g){if(f.length!==0){const _=[],m=[];Xg(f,_,m,p),_.length!==0&&g.push(new d(h,_,m))}},s=[],a=e.name||"default",r=e.fps||30,o=e.blendMode;let l=e.length||-1;const c=e.hierarchy||[];for(let d=0;d{t&&t(a),this.manager.itemEnd(e)},0),a;if(Is[e]!==void 0){Is[e].push({onLoad:t,onProgress:i,onError:s});return}Is[e]=[],Is[e].push({onLoad:t,onProgress:i,onError:s});const r=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,l=this.responseType;fetch(r).then(c=>{if(c.status===200||c.status===0){if(c.status===0&&console.warn("THREE.FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||c.body===void 0||c.body.getReader===void 0)return c;const u=Is[e],d=c.body.getReader(),h=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),f=h?parseInt(h):0,p=f!==0;let g=0;const _=new ReadableStream({start(m){v();function v(){d.read().then(({done:y,value:b})=>{if(y)m.close();else{g+=b.byteLength;const S=new ProgressEvent("progress",{lengthComputable:p,loaded:g,total:f});for(let x=0,M=u.length;x{m.error(y)})}}});return new Response(_)}else throw new TP(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`,c)}).then(c=>{switch(l){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then(u=>new DOMParser().parseFromString(u,o));case"json":return c.json();default:if(o==="")return c.text();{const d=/charset="?([^;"\s]*)"?/i.exec(o),h=d&&d[1]?d[1].toLowerCase():void 0,f=new TextDecoder(h);return c.arrayBuffer().then(p=>f.decode(p))}}}).then(c=>{_s.add(`file:${e}`,c);const u=Is[e];delete Is[e];for(let d=0,h=u.length;d{const u=Is[e];if(u===void 0)throw this.manager.itemError(e),c;delete Is[e];for(let d=0,h=u.length;d{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}class MP extends ln{constructor(e){super(e)}load(e,t,i,s){const a=this,r=new Kn(this.manager);r.setPath(this.path),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,function(o){try{t(a.parse(JSON.parse(o)))}catch(l){s?s(l):console.error(l),a.manager.itemError(e)}},i,s)}parse(e){const t=[];for(let i=0;i0:s.vertexColors=e.vertexColors),e.uniforms!==void 0)for(const a in e.uniforms){const r=e.uniforms[a];switch(s.uniforms[a]={},r.type){case"t":s.uniforms[a].value=i(r.value);break;case"c":s.uniforms[a].value=new de().setHex(r.value);break;case"v2":s.uniforms[a].value=new ne().fromArray(r.value);break;case"v3":s.uniforms[a].value=new T().fromArray(r.value);break;case"v4":s.uniforms[a].value=new Ye().fromArray(r.value);break;case"m3":s.uniforms[a].value=new rt().fromArray(r.value);break;case"m4":s.uniforms[a].value=new Ee().fromArray(r.value);break;default:s.uniforms[a].value=r.value}}if(e.defines!==void 0&&(s.defines=e.defines),e.vertexShader!==void 0&&(s.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(s.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(s.glslVersion=e.glslVersion),e.extensions!==void 0)for(const a in e.extensions)s.extensions[a]=e.extensions[a];if(e.lights!==void 0&&(s.lights=e.lights),e.clipping!==void 0&&(s.clipping=e.clipping),e.size!==void 0&&(s.size=e.size),e.sizeAttenuation!==void 0&&(s.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(s.map=i(e.map)),e.matcap!==void 0&&(s.matcap=i(e.matcap)),e.alphaMap!==void 0&&(s.alphaMap=i(e.alphaMap)),e.bumpMap!==void 0&&(s.bumpMap=i(e.bumpMap)),e.bumpScale!==void 0&&(s.bumpScale=e.bumpScale),e.normalMap!==void 0&&(s.normalMap=i(e.normalMap)),e.normalMapType!==void 0&&(s.normalMapType=e.normalMapType),e.normalScale!==void 0){let a=e.normalScale;Array.isArray(a)===!1&&(a=[a,a]),s.normalScale=new ne().fromArray(a)}return e.displacementMap!==void 0&&(s.displacementMap=i(e.displacementMap)),e.displacementScale!==void 0&&(s.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(s.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(s.roughnessMap=i(e.roughnessMap)),e.metalnessMap!==void 0&&(s.metalnessMap=i(e.metalnessMap)),e.emissiveMap!==void 0&&(s.emissiveMap=i(e.emissiveMap)),e.emissiveIntensity!==void 0&&(s.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(s.specularMap=i(e.specularMap)),e.specularIntensityMap!==void 0&&(s.specularIntensityMap=i(e.specularIntensityMap)),e.specularColorMap!==void 0&&(s.specularColorMap=i(e.specularColorMap)),e.envMap!==void 0&&(s.envMap=i(e.envMap)),e.envMapRotation!==void 0&&s.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(s.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(s.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(s.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(s.lightMap=i(e.lightMap)),e.lightMapIntensity!==void 0&&(s.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(s.aoMap=i(e.aoMap)),e.aoMapIntensity!==void 0&&(s.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(s.gradientMap=i(e.gradientMap)),e.clearcoatMap!==void 0&&(s.clearcoatMap=i(e.clearcoatMap)),e.clearcoatRoughnessMap!==void 0&&(s.clearcoatRoughnessMap=i(e.clearcoatRoughnessMap)),e.clearcoatNormalMap!==void 0&&(s.clearcoatNormalMap=i(e.clearcoatNormalMap)),e.clearcoatNormalScale!==void 0&&(s.clearcoatNormalScale=new ne().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(s.iridescenceMap=i(e.iridescenceMap)),e.iridescenceThicknessMap!==void 0&&(s.iridescenceThicknessMap=i(e.iridescenceThicknessMap)),e.transmissionMap!==void 0&&(s.transmissionMap=i(e.transmissionMap)),e.thicknessMap!==void 0&&(s.thicknessMap=i(e.thicknessMap)),e.anisotropyMap!==void 0&&(s.anisotropyMap=i(e.anisotropyMap)),e.sheenColorMap!==void 0&&(s.sheenColorMap=i(e.sheenColorMap)),e.sheenRoughnessMap!==void 0&&(s.sheenRoughnessMap=i(e.sheenRoughnessMap)),s}setTextures(e){return this.textures=e,this}createMaterialFromType(e){return Pf.createMaterialFromType(e)}static createMaterialFromType(e){const t={ShadowMaterial:vT,SpriteMaterial:uf,RawShaderMaterial:bT,ShaderMaterial:ri,PointsMaterial:fa,MeshPhysicalMaterial:li,MeshStandardMaterial:kn,MeshPhongMaterial:sr,MeshToonMaterial:xT,MeshNormalMaterial:wT,MeshLambertMaterial:Cf,MeshDepthMaterial:$g,MeshDistanceMaterial:Wg,MeshBasicMaterial:je,MeshMatcapMaterial:ST,LineDashedMaterial:TT,LineBasicMaterial:Pt,Material:en};return new t[e]}}class Ws{static extractUrlBase(e){const t=e.lastIndexOf("/");return t===-1?"./":e.slice(0,t+1)}static resolveURL(e,t){return typeof e!="string"||e===""?"":(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}}class FT extends $e{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){const e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}}class NT extends ln{constructor(e){super(e)}load(e,t,i,s){const a=this,r=new Kn(a.manager);r.setPath(a.path),r.setRequestHeader(a.requestHeader),r.setWithCredentials(a.withCredentials),r.load(e,function(o){try{t(a.parse(JSON.parse(o)))}catch(l){s?s(l):console.error(l),a.manager.itemError(e)}},i,s)}parse(e){const t={},i={};function s(f,p){if(t[p]!==void 0)return t[p];const _=f.interleavedBuffers[p],m=a(f,_.buffer),v=lo(_.type,m),y=new Rc(v,_.stride);return y.uuid=_.uuid,t[p]=y,y}function a(f,p){if(i[p]!==void 0)return i[p];const _=f.arrayBuffers[p],m=new Uint32Array(_).buffer;return i[p]=m,m}const r=e.isInstancedBufferGeometry?new FT:new $e,o=e.data.index;if(o!==void 0){const f=lo(o.type,o.array);r.setIndex(new lt(f,1))}const l=e.data.attributes;for(const f in l){const p=l[f];let g;if(p.isInterleavedBufferAttribute){const _=s(e.data,p.data);g=new ga(_,p.itemSize,p.offset,p.normalized)}else{const _=lo(p.type,p.array),m=p.isInstancedBufferAttribute?gr:lt;g=new m(_,p.itemSize,p.normalized)}p.name!==void 0&&(g.name=p.name),p.usage!==void 0&&g.setUsage(p.usage),r.setAttribute(f,g)}const c=e.data.morphAttributes;if(c)for(const f in c){const p=c[f],g=[];for(let _=0,m=p.length;_0){const l=new Yg(t);a=new mc(l),a.setCrossOrigin(this.crossOrigin);for(let c=0,u=e.length;c0){s=new mc(this.manager),s.setCrossOrigin(this.crossOrigin);for(let r=0,o=e.length;r{let _=null,m=null;return g.boundingBox!==void 0&&(_=new bn().fromJSON(g.boundingBox)),g.boundingSphere!==void 0&&(m=new xn().fromJSON(g.boundingSphere)),{...g,boundingBox:_,boundingSphere:m}}),r._instanceInfo=e.instanceInfo,r._availableInstanceIds=e._availableInstanceIds,r._availableGeometryIds=e._availableGeometryIds,r._nextIndexStart=e.nextIndexStart,r._nextVertexStart=e.nextVertexStart,r._geometryCount=e.geometryCount,r._maxInstanceCount=e.maxInstanceCount,r._maxVertexCount=e.maxVertexCount,r._maxIndexCount=e.maxIndexCount,r._geometryInitialized=e.geometryInitialized,r._matricesTexture=c(e.matricesTexture.uuid),r._indirectTexture=c(e.indirectTexture.uuid),e.colorsTexture!==void 0&&(r._colorsTexture=c(e.colorsTexture.uuid)),e.boundingSphere!==void 0&&(r.boundingSphere=new xn().fromJSON(e.boundingSphere)),e.boundingBox!==void 0&&(r.boundingBox=new bn().fromJSON(e.boundingBox));break;case"LOD":r=new lT;break;case"Line":r=new On(o(e.geometry),l(e.material));break;case"LineLoop":r=new kg(o(e.geometry),l(e.material));break;case"LineSegments":r=new Fn(o(e.geometry),l(e.material));break;case"PointCloud":case"Points":r=new fr(o(e.geometry),l(e.material));break;case"Sprite":r=new df(l(e.material));break;case"Group":r=new Et;break;case"Bone":r=new zo;break;default:r=new et}if(r.uuid=e.uuid,e.name!==void 0&&(r.name=e.name),e.matrix!==void 0?(r.matrix.fromArray(e.matrix),e.matrixAutoUpdate!==void 0&&(r.matrixAutoUpdate=e.matrixAutoUpdate),r.matrixAutoUpdate&&r.matrix.decompose(r.position,r.quaternion,r.scale)):(e.position!==void 0&&r.position.fromArray(e.position),e.rotation!==void 0&&r.rotation.fromArray(e.rotation),e.quaternion!==void 0&&r.quaternion.fromArray(e.quaternion),e.scale!==void 0&&r.scale.fromArray(e.scale)),e.up!==void 0&&r.up.fromArray(e.up),e.castShadow!==void 0&&(r.castShadow=e.castShadow),e.receiveShadow!==void 0&&(r.receiveShadow=e.receiveShadow),e.shadow&&(e.shadow.intensity!==void 0&&(r.shadow.intensity=e.shadow.intensity),e.shadow.bias!==void 0&&(r.shadow.bias=e.shadow.bias),e.shadow.normalBias!==void 0&&(r.shadow.normalBias=e.shadow.normalBias),e.shadow.radius!==void 0&&(r.shadow.radius=e.shadow.radius),e.shadow.mapSize!==void 0&&r.shadow.mapSize.fromArray(e.shadow.mapSize),e.shadow.camera!==void 0&&(r.shadow.camera=this.parseObject(e.shadow.camera))),e.visible!==void 0&&(r.visible=e.visible),e.frustumCulled!==void 0&&(r.frustumCulled=e.frustumCulled),e.renderOrder!==void 0&&(r.renderOrder=e.renderOrder),e.userData!==void 0&&(r.userData=e.userData),e.layers!==void 0&&(r.layers.mask=e.layers),e.children!==void 0){const h=e.children;for(let f=0;f"u"&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,i,s){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const a=this,r=_s.get(`image-bitmap:${e}`);if(r!==void 0){if(a.manager.itemStart(e),r.then){r.then(c=>{if(Mp.has(r)===!0)s&&s(Mp.get(r)),a.manager.itemError(e),a.manager.itemEnd(e);else return t&&t(c),a.manager.itemEnd(e),c});return}return setTimeout(function(){t&&t(r),a.manager.itemEnd(e)},0),r}const o={};o.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",o.headers=this.requestHeader,o.signal=typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;const l=fetch(e,o).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign(a.options,{colorSpaceConversion:"none"}))}).then(function(c){return _s.add(`image-bitmap:${e}`,c),t&&t(c),a.manager.itemEnd(e),c}).catch(function(c){s&&s(c),Mp.set(l,c),_s.remove(`image-bitmap:${e}`),a.manager.itemError(e),a.manager.itemEnd(e)});_s.add(`image-bitmap:${e}`,l),a.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}let xu;class Zg{static getContext(){return xu===void 0&&(xu=new(window.AudioContext||window.webkitAudioContext)),xu}static setContext(e){xu=e}}class kP extends ln{constructor(e){super(e)}load(e,t,i,s){const a=this,r=new Kn(this.manager);r.setResponseType("arraybuffer"),r.setPath(this.path),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,function(l){try{const c=l.slice(0);Zg.getContext().decodeAudioData(c,function(d){t(d)}).catch(o)}catch(c){o(c)}},i,s);function o(l){s?s(l):console.error(l),a.manager.itemError(e)}}}const V0=new Ee,G0=new Ee,La=new Ee;class DP{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new Qt,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Qt,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){const t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,La.copy(e.projectionMatrix);const s=t.eyeSep/2,a=s*t.near/t.focus,r=t.near*Math.tan(hr*t.fov*.5)/t.zoom;let o,l;G0.elements[12]=-s,V0.elements[12]=s,o=-r*t.aspect+a,l=r*t.aspect+a,La.elements[0]=2*t.near/(l-o),La.elements[8]=(l+o)/(l-o),this.cameraL.projectionMatrix.copy(La),o=-r*t.aspect-a,l=r*t.aspect-a,La.elements[0]=2*t.near/(l-o),La.elements[8]=(l+o)/(l-o),this.cameraR.projectionMatrix.copy(La)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(G0),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(V0)}}class BT extends Qt{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class Jg{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}const ka=new T,Ep=new ht,OP=new T,Da=new T,Oa=new T;class FP extends et{constructor(){super(),this.type="AudioListener",this.context=Zg.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new Jg}getInput(){return this.gain}removeFilter(){return this.filter!==null&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return this.filter!==null?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e);const t=this.context.listener;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(ka,Ep,OP),Da.set(0,0,-1).applyQuaternion(Ep),Oa.set(0,1,0).applyQuaternion(Ep),t.positionX){const i=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(ka.x,i),t.positionY.linearRampToValueAtTime(ka.y,i),t.positionZ.linearRampToValueAtTime(ka.z,i),t.forwardX.linearRampToValueAtTime(Da.x,i),t.forwardY.linearRampToValueAtTime(Da.y,i),t.forwardZ.linearRampToValueAtTime(Da.z,i),t.upX.linearRampToValueAtTime(Oa.x,i),t.upY.linearRampToValueAtTime(Oa.y,i),t.upZ.linearRampToValueAtTime(Oa.z,i)}else t.setPosition(ka.x,ka.y,ka.z),t.setOrientation(Da.x,Da.y,Da.z,Oa.x,Oa.y,Oa.z)}}class zT extends et{constructor(e){super(),this.type="Audio",this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType="buffer",this.autoplay&&this.play(),this}play(e=0){if(this.isPlaying===!0){console.warn("THREE.Audio: Audio is already playing.");return}if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}this._startedAt=this.context.currentTime+e;const t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.isPlaying===!0&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this}stop(e=0){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this._progress=0,this.source!==null&&(this.source.stop(this.context.currentTime+e),this.source.onended=null),this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(i,s,this._addIndex*t,1,t);for(let l=t,c=t+t;l!==c;++l)if(i[l]!==i[l+t]){o.setValue(i,s);break}}saveOriginalState(){const e=this.binding,t=this.buffer,i=this.valueSize,s=i*this._origIndex;e.getValue(t,s);for(let a=i,r=s;a!==r;++a)t[a]=t[s+a%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let i=e;i=.5)for(let r=0;r!==a;++r)e[t+r]=e[i+r]}_slerp(e,t,i,s){ht.slerpFlat(e,t,e,t,e,i,s)}_slerpAdditive(e,t,i,s,a){const r=this._workIndex*a;ht.multiplyQuaternionsFlat(e,r,e,t,e,i),ht.slerpFlat(e,t,e,t,e,r,s)}_lerp(e,t,i,s,a){const r=1-s;for(let o=0;o!==a;++o){const l=t+o;e[l]=e[l]*r+e[i+o]*s}}_lerpAdditive(e,t,i,s,a){for(let r=0;r!==a;++r){const o=t+r;e[o]=e[o]+e[i+r]*s}}}const Qg="\\[\\]\\.:\\/",zP=new RegExp("["+Qg+"]","g"),ey="[^"+Qg+"]",HP="[^"+Qg.replace("\\.","")+"]",VP=/((?:WC+[\/:])*)/.source.replace("WC",ey),GP=/(WCOD+)?/.source.replace("WCOD",HP),$P=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",ey),WP=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",ey),XP=new RegExp("^"+VP+GP+$P+WP+"$"),KP=["material","materials","bones","map"];class qP{constructor(e,t,i){const s=i||vt.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,s)}getValue(e,t){this.bind();const i=this._targetGroup.nCachedObjects_,s=this._bindings[i];s!==void 0&&s.getValue(e,t)}setValue(e,t){const i=this._bindings;for(let s=this._targetGroup.nCachedObjects_,a=i.length;s!==a;++s)i[s].setValue(e,t)}bind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].bind()}unbind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].unbind()}}class vt{constructor(e,t,i){this.path=t,this.parsedPath=i||vt.parseTrackName(t),this.node=vt.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,i){return e&&e.isAnimationObjectGroup?new vt.Composite(e,t,i):new vt(e,t,i)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(zP,"")}static parseTrackName(e){const t=XP.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const i={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},s=i.nodeName&&i.nodeName.lastIndexOf(".");if(s!==void 0&&s!==-1){const a=i.nodeName.substring(s+1);KP.indexOf(a)!==-1&&(i.nodeName=i.nodeName.substring(0,s),i.objectName=a)}if(i.propertyName===null||i.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return i}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){const i=e.skeleton.getBoneByName(t);if(i!==void 0)return i}if(e.children){const i=function(a){for(let r=0;r=a){const d=a++,h=e[d];t[h.uuid]=u,e[u]=h,t[c]=d,e[d]=l;for(let f=0,p=s;f!==p;++f){const g=i[f],_=g[d],m=g[u];g[u]=_,g[d]=m}}}this.nCachedObjects_=a}uncache(){const e=this._objects,t=this._indicesByUUID,i=this._bindings,s=i.length;let a=this.nCachedObjects_,r=e.length;for(let o=0,l=arguments.length;o!==l;++o){const c=arguments[o],u=c.uuid,d=t[u];if(d!==void 0)if(delete t[u],d0&&(t[f.uuid]=d),e[d]=f,e.pop();for(let p=0,g=s;p!==g;++p){const _=i[p];_[d]=_[h],_.pop()}}}this.nCachedObjects_=a}subscribe_(e,t){const i=this._bindingsIndicesByPath;let s=i[e];const a=this._bindings;if(s!==void 0)return a[s];const r=this._paths,o=this._parsedPaths,l=this._objects,c=l.length,u=this.nCachedObjects_,d=new Array(c);s=a.length,i[e]=s,r.push(e),o.push(t),a.push(d);for(let h=u,f=l.length;h!==f;++h){const p=l[h];d[h]=new vt(p,e,t)}return d}unsubscribe_(e){const t=this._bindingsIndicesByPath,i=t[e];if(i!==void 0){const s=this._paths,a=this._parsedPaths,r=this._bindings,o=r.length-1,l=r[o],c=e[o];t[c]=i,r[i]=l,r.pop(),a[i]=a[o],a.pop(),s[i]=s[o],s.pop()}}}class VT{constructor(e,t,i=null,s=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=i,this.blendMode=s;const a=t.tracks,r=a.length,o=new Array(r),l={endingStart:nr,endingEnd:nr};for(let c=0;c!==r;++c){const u=a[c].createInterpolant(null);o[c]=u,u.settings=l}this._interpolantSettings=l,this._interpolants=o,this._propertyBindings=new Array(r),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=zS,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,i=!1){if(e.fadeOut(t),this.fadeIn(t),i===!0){const s=this._clip.duration,a=e._clip.duration,r=a/s,o=s/a;e.warp(1,r,t),this.warp(o,1,t)}return this}crossFadeTo(e,t,i=!1){return e.crossFadeFrom(this,t,i)}stopFading(){const e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,i){const s=this._mixer,a=s.time,r=this.timeScale;let o=this._timeScaleInterpolant;o===null&&(o=s._lendControlInterpolant(),this._timeScaleInterpolant=o);const l=o.parameterPositions,c=o.sampleValues;return l[0]=a,l[1]=a+i,c[0]=e/r,c[1]=t/r,this}stopWarping(){const e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,i,s){if(!this.enabled){this._updateWeight(e);return}const a=this._startTime;if(a!==null){const l=(e-a)*i;l<0||i===0?t=0:(this._startTime=null,t=i*l)}t*=this._updateTimeScale(e);const r=this._updateTime(t),o=this._updateWeight(e);if(o>0){const l=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case Cg:for(let u=0,d=l.length;u!==d;++u)l[u].evaluate(r),c[u].accumulateAdditive(o);break;case tf:default:for(let u=0,d=l.length;u!==d;++u)l[u].evaluate(r),c[u].accumulate(s,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const i=this._weightInterpolant;if(i!==null){const s=i.evaluate(e)[0];t*=s,e>i.parameterPositions[1]&&(this.stopFading(),s===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const i=this._timeScaleInterpolant;if(i!==null){const s=i.evaluate(e)[0];t*=s,e>i.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,i=this.loop;let s=this.time+e,a=this._loopCount;const r=i===HS;if(e===0)return a===-1?s:r&&(a&1)===1?t-s:s;if(i===bh){a===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(s>=t)s=t;else if(s<0)s=0;else{this.time=s;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(a===-1&&(e>=0?(a=0,this._setEndings(!0,this.repetitions===0,r)):this._setEndings(this.repetitions===0,!0,r)),s>=t||s<0){const o=Math.floor(s/t);s-=t*o,a+=Math.abs(o);const l=this.repetitions-a;if(l<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,s=e>0?t:0,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(l===1){const c=e<0;this._setEndings(c,!c,r)}else this._setEndings(!1,!1,r);this._loopCount=a,this.time=s,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this.time=s;if(r&&(a&1)===1)return t-s}return s}_setEndings(e,t,i){const s=this._interpolantSettings;i?(s.endingStart=ir,s.endingEnd=ir):(e?s.endingStart=this.zeroSlopeAtStart?ir:nr:s.endingStart=oc,t?s.endingEnd=this.zeroSlopeAtEnd?ir:nr:s.endingEnd=oc)}_scheduleFading(e,t,i){const s=this._mixer,a=s.time;let r=this._weightInterpolant;r===null&&(r=s._lendControlInterpolant(),this._weightInterpolant=r);const o=r.parameterPositions,l=r.sampleValues;return o[0]=a,l[0]=t,o[1]=a+e,l[1]=i,this}}const jP=new Float32Array(1);class GT extends Ts{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const i=e._localRoot||this._root,s=e._clip.tracks,a=s.length,r=e._propertyBindings,o=e._interpolants,l=i.uuid,c=this._bindingsByRootAndName;let u=c[l];u===void 0&&(u={},c[l]=u);for(let d=0;d!==a;++d){const h=s[d],f=h.name;let p=u[f];if(p!==void 0)++p.referenceCount,r[d]=p;else{if(p=r[d],p!==void 0){p._cacheIndex===null&&(++p.referenceCount,this._addInactiveBinding(p,l,f));continue}const g=t&&t._propertyBindings[d].binding.parsedPath;p=new HT(vt.create(i,f,g),h.ValueTypeName,h.getValueSize()),++p.referenceCount,this._addInactiveBinding(p,l,f),r[d]=p}o[d].resultBuffer=p.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){const i=(e._localRoot||this._root).uuid,s=e._clip.uuid,a=this._actionsByClip[s];this._bindAction(e,a&&a.knownActions[0]),this._addInactiveAction(e,s,i)}const t=e._propertyBindings;for(let i=0,s=t.length;i!==s;++i){const a=t[i];a.useCount++===0&&(this._lendBinding(a),a.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let i=0,s=t.length;i!==s;++i){const a=t[i];--a.useCount===0&&(a.restoreOriginalState(),this._takeBackBinding(a))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return t!==null&&t=0;--i)e[i].stop();return this}update(e){e*=this.timeScale;const t=this._actions,i=this._nActiveActions,s=this.time+=e,a=Math.sign(e),r=this._accuIndex^=1;for(let c=0;c!==i;++c)t[c]._update(s,e,a,r);const o=this._bindings,l=this._nActiveBindings;for(let c=0;c!==l;++c)o[c].apply(r);return this}setTime(e){this.time=0;for(let t=0;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,K0).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const q0=new T,wu=new T,Kr=new T,qr=new T,Cp=new T,oI=new T,lI=new T;class cI{constructor(e=new T,t=new T){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){q0.subVectors(e,this.start),wu.subVectors(this.end,this.start);const i=wu.dot(wu);let a=wu.dot(q0)/i;return t&&(a=Je(a,0,1)),a}closestPointToPoint(e,t,i){const s=this.closestPointToPointParameter(e,t);return this.delta(i).multiplyScalar(s).add(this.start)}distanceSqToLine3(e,t=oI,i=lI){const s=10000000000000001e-32;let a,r;const o=this.start,l=e.start,c=this.end,u=e.end;Kr.subVectors(c,o),qr.subVectors(u,l),Cp.subVectors(o,l);const d=Kr.dot(Kr),h=qr.dot(qr),f=qr.dot(Cp);if(d<=s&&h<=s)return t.copy(o),i.copy(l),t.sub(i),t.dot(t);if(d<=s)a=0,r=f/h,r=Je(r,0,1);else{const p=Kr.dot(Cp);if(h<=s)r=0,a=Je(-p/d,0,1);else{const g=Kr.dot(qr),_=d*h-g*g;_!==0?a=Je((g*f-p*h)/_,0,1):a=0,r=(g*a+f)/h,r<0?(r=0,a=Je(-p/d,0,1)):r>1&&(r=1,a=Je((g-p)/d,0,1))}}return t.copy(o).add(Kr.multiplyScalar(a)),i.copy(l).add(qr.multiplyScalar(r)),t.sub(i),t.dot(t)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}const Y0=new T;class uI extends et{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const i=new $e,s=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let r=0,o=1,l=32;r1)for(let d=0;d.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{ev.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(ev,t)}}setLength(e,t=e*.2,i=t*.2){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(i,t,i),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class wI extends Fn{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],i=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],s=new $e;s.setAttribute("position",new Ce(t,3)),s.setAttribute("color",new Ce(i,3));const a=new Pt({vertexColors:!0,toneMapped:!1});super(s,a),this.type="AxesHelper"}setColors(e,t,i){const s=new de,a=this.geometry.attributes.color.array;return s.set(e),s.toArray(a,0),s.toArray(a,3),s.set(t),s.toArray(a,6),s.toArray(a,9),s.set(i),s.toArray(a,12),s.toArray(a,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class SI{constructor(){this.type="ShapePath",this.color=new de,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new Mh,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,i,s){return this.currentPath.quadraticCurveTo(e,t,i,s),this}bezierCurveTo(e,t,i,s,a,r){return this.currentPath.bezierCurveTo(e,t,i,s,a,r),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(m){const v=[];for(let y=0,b=m.length;yNumber.EPSILON){if(E<0&&(M=v[x],w=-w,C=v[S],E=-E),m.yC.y)continue;if(m.y===M.y){if(m.x===M.x)return!0}else{const R=E*(m.x-M.x)-w*(m.y-M.y);if(R===0)return!0;if(R<0)continue;b=!b}}else{if(m.y!==M.y)continue;if(C.x<=m.x&&m.x<=M.x||M.x<=m.x&&m.x<=C.x)return!0}}return b}const s=ki.isClockWise,a=this.subPaths;if(a.length===0)return[];let r,o,l;const c=[];if(a.length===1)return o=a[0],l=new $s,l.curves=o.curves,c.push(l),c;let u=!s(a[0].getPoints());u=e?!u:u;const d=[],h=[];let f=[],p=0,g;h[p]=void 0,f[p]=[];for(let m=0,v=a.length;m1){let m=!1,v=0;for(let y=0,b=h.length;y0&&m===!1&&(f=d)}let _;for(let m=0,v=h.length;me?(n.repeat.x=1,n.repeat.y=t/e,n.offset.x=0,n.offset.y=(1-n.repeat.y)/2):(n.repeat.x=e/t,n.repeat.y=1,n.offset.x=(1-n.repeat.x)/2,n.offset.y=0),n}function MI(n,e){const t=n.image&&n.image.width?n.image.width/n.image.height:1;return t>e?(n.repeat.x=e/t,n.repeat.y=1,n.offset.x=(1-n.repeat.x)/2,n.offset.y=0):(n.repeat.x=1,n.repeat.y=t/e,n.offset.x=0,n.offset.y=(1-n.repeat.y)/2),n}function EI(n){return n.repeat.x=1,n.repeat.y=1,n.offset.x=0,n.offset.y=0,n}function l_(n,e,t,i){const s=CI(i);switch(t){case Tg:return n*e;case Jh:return n*e/s.components*s.byteLength;case Ec:return n*e/s.components*s.byteLength;case Eg:return n*e*2/s.components*s.byteLength;case Qh:return n*e*2/s.components*s.byteLength;case Mg:return n*e*3/s.components*s.byteLength;case Xn:return n*e*4/s.components*s.byteLength;case ef:return n*e*4/s.components*s.byteLength;case $l:case Wl:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case Xl:case Kl:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case Kd:case Yd:return Math.max(n,16)*Math.max(e,8)/4;case Xd:case qd:return Math.max(n,8)*Math.max(e,8)/2;case jd:case Zd:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case Jd:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case Qd:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case eh:return Math.floor((n+4)/5)*Math.floor((e+3)/4)*16;case th:return Math.floor((n+4)/5)*Math.floor((e+4)/5)*16;case nh:return Math.floor((n+5)/6)*Math.floor((e+4)/5)*16;case ih:return Math.floor((n+5)/6)*Math.floor((e+5)/6)*16;case sh:return Math.floor((n+7)/8)*Math.floor((e+4)/5)*16;case ah:return Math.floor((n+7)/8)*Math.floor((e+5)/6)*16;case rh:return Math.floor((n+7)/8)*Math.floor((e+7)/8)*16;case oh:return Math.floor((n+9)/10)*Math.floor((e+4)/5)*16;case lh:return Math.floor((n+9)/10)*Math.floor((e+5)/6)*16;case ch:return Math.floor((n+9)/10)*Math.floor((e+7)/8)*16;case uh:return Math.floor((n+9)/10)*Math.floor((e+9)/10)*16;case dh:return Math.floor((n+11)/12)*Math.floor((e+9)/10)*16;case hh:return Math.floor((n+11)/12)*Math.floor((e+11)/12)*16;case fh:case ph:case mh:return Math.ceil(n/4)*Math.ceil(e/4)*16;case _h:case gh:return Math.ceil(n/4)*Math.ceil(e/4)*8;case yh:case vh:return Math.ceil(n/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function CI(n){switch(n){case is:case bg:return{byteLength:1,components:1};case Lo:case xg:case ms:return{byteLength:2,components:1};case jh:case Zh:return{byteLength:2,components:4};case Ks:case Yh:case Mn:return{byteLength:4,components:1};case wg:case Sg:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${n}.`)}class AI{static contain(e,t){return TI(e,t)}static cover(e,t){return MI(e,t)}static fill(e){return EI(e)}static getByteLength(e,t,i,s){return l_(e,t,i,s)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:Xh}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=Xh);function XT(){let n=null,e=!1,t=null,i=null;function s(a,r){t(a,r),i=n.requestAnimationFrame(s)}return{start:function(){e!==!0&&t!==null&&(i=n.requestAnimationFrame(s),e=!0)},stop:function(){n.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(a){t=a},setContext:function(a){n=a}}}function RI(n){const e=new WeakMap;function t(o,l){const c=o.array,u=o.usage,d=c.byteLength,h=n.createBuffer();n.bindBuffer(l,h),n.bufferData(l,c,u),o.onUploadCallback();let f;if(c instanceof Float32Array)f=n.FLOAT;else if(typeof Float16Array<"u"&&c instanceof Float16Array)f=n.HALF_FLOAT;else if(c instanceof Uint16Array)o.isFloat16BufferAttribute?f=n.HALF_FLOAT:f=n.UNSIGNED_SHORT;else if(c instanceof Int16Array)f=n.SHORT;else if(c instanceof Uint32Array)f=n.UNSIGNED_INT;else if(c instanceof Int32Array)f=n.INT;else if(c instanceof Int8Array)f=n.BYTE;else if(c instanceof Uint8Array)f=n.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)f=n.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:h,type:f,bytesPerElement:c.BYTES_PER_ELEMENT,version:o.version,size:d}}function i(o,l,c){const u=l.array,d=l.updateRanges;if(n.bindBuffer(c,o),d.length===0)n.bufferSubData(c,0,u);else{d.sort((f,p)=>f.start-p.start);let h=0;for(let f=1;f 0 +#endif`,WI=`#if NUM_CLIPPING_PLANES > 0 vec4 plane; #ifdef ALPHA_TO_COVERAGE float distanceToPlane, distanceGradient; @@ -289,26 +289,26 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve if ( clipped ) discard; #endif #endif -#endif`,OI=`#if NUM_CLIPPING_PLANES > 0 +#endif`,XI=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; -#endif`,FI=`#if NUM_CLIPPING_PLANES > 0 +#endif`,KI=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; -#endif`,NI=`#if NUM_CLIPPING_PLANES > 0 +#endif`,qI=`#if NUM_CLIPPING_PLANES > 0 vClipPosition = - mvPosition.xyz; -#endif`,UI=`#if defined( USE_COLOR_ALPHA ) +#endif`,YI=`#if defined( USE_COLOR_ALPHA ) diffuseColor *= vColor; #elif defined( USE_COLOR ) diffuseColor.rgb *= vColor; -#endif`,BI=`#if defined( USE_COLOR_ALPHA ) +#endif`,jI=`#if defined( USE_COLOR_ALPHA ) varying vec4 vColor; #elif defined( USE_COLOR ) varying vec3 vColor; -#endif`,zI=`#if defined( USE_COLOR_ALPHA ) +#endif`,ZI=`#if defined( USE_COLOR_ALPHA ) varying vec4 vColor; #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) varying vec3 vColor; -#endif`,HI=`#if defined( USE_COLOR_ALPHA ) +#endif`,JI=`#if defined( USE_COLOR_ALPHA ) vColor = vec4( 1.0 ); #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) vColor = vec3( 1.0 ); @@ -322,7 +322,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve #ifdef USE_BATCHING_COLOR vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); vColor.xyz *= batchingColor.xyz; -#endif`,VI=`#define PI 3.141592653589793 +#endif`,QI=`#define PI 3.141592653589793 #define PI2 6.283185307179586 #define PI_HALF 1.5707963267948966 #define RECIPROCAL_PI 0.3183098861837907 @@ -396,7 +396,7 @@ vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); -} // validated`,GI=`#ifdef ENVMAP_TYPE_CUBE_UV +} // validated`,eL=`#ifdef ENVMAP_TYPE_CUBE_UV #define cubeUV_minMipLevel 4.0 #define cubeUV_minTileSize 16.0 float getFace( vec3 direction ) { @@ -489,7 +489,7 @@ float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { return vec4( mix( color0, color1, mipF ), 1.0 ); } } -#endif`,$I=`vec3 transformedNormal = objectNormal; +#endif`,tL=`vec3 transformedNormal = objectNormal; #ifdef USE_TANGENT vec3 transformedTangent = objectTangent; #endif @@ -518,21 +518,21 @@ transformedNormal = normalMatrix * transformedNormal; #ifdef FLIP_SIDED transformedTangent = - transformedTangent; #endif -#endif`,WI=`#ifdef USE_DISPLACEMENTMAP +#endif`,nL=`#ifdef USE_DISPLACEMENTMAP uniform sampler2D displacementMap; uniform float displacementScale; uniform float displacementBias; -#endif`,XI=`#ifdef USE_DISPLACEMENTMAP +#endif`,iL=`#ifdef USE_DISPLACEMENTMAP transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); -#endif`,KI=`#ifdef USE_EMISSIVEMAP +#endif`,sL=`#ifdef USE_EMISSIVEMAP vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE emissiveColor = sRGBTransferEOTF( emissiveColor ); #endif totalEmissiveRadiance *= emissiveColor.rgb; -#endif`,qI=`#ifdef USE_EMISSIVEMAP +#endif`,aL=`#ifdef USE_EMISSIVEMAP uniform sampler2D emissiveMap; -#endif`,YI="gl_FragColor = linearToOutputTexel( gl_FragColor );",jI=`vec4 LinearTransferOETF( in vec4 value ) { +#endif`,rL="gl_FragColor = linearToOutputTexel( gl_FragColor );",oL=`vec4 LinearTransferOETF( in vec4 value ) { return value; } vec4 sRGBTransferEOTF( in vec4 value ) { @@ -540,7 +540,7 @@ vec4 sRGBTransferEOTF( in vec4 value ) { } vec4 sRGBTransferOETF( in vec4 value ) { return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); -}`,ZI=`#ifdef USE_ENVMAP +}`,lL=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vec3 cameraToFrag; if ( isOrthographic ) { @@ -569,7 +569,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { #elif defined( ENVMAP_BLENDING_ADD ) outgoingLight += envColor.xyz * specularStrength * reflectivity; #endif -#endif`,JI=`#ifdef USE_ENVMAP +#endif`,cL=`#ifdef USE_ENVMAP uniform float envMapIntensity; uniform float flipEnvMap; uniform mat3 envMapRotation; @@ -579,7 +579,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { uniform sampler2D envMap; #endif -#endif`,QI=`#ifdef USE_ENVMAP +#endif`,uL=`#ifdef USE_ENVMAP uniform float reflectivity; #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS @@ -590,7 +590,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { #else varying vec3 vReflect; #endif -#endif`,eL=`#ifdef USE_ENVMAP +#endif`,dL=`#ifdef USE_ENVMAP #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif @@ -601,7 +601,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { varying vec3 vReflect; uniform float refractionRatio; #endif -#endif`,tL=`#ifdef USE_ENVMAP +#endif`,hL=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vWorldPosition = worldPosition.xyz; #else @@ -618,18 +618,18 @@ vec4 sRGBTransferOETF( in vec4 value ) { vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); #endif #endif -#endif`,nL=`#ifdef USE_FOG +#endif`,fL=`#ifdef USE_FOG vFogDepth = - mvPosition.z; -#endif`,iL=`#ifdef USE_FOG +#endif`,pL=`#ifdef USE_FOG varying float vFogDepth; -#endif`,sL=`#ifdef USE_FOG +#endif`,mL=`#ifdef USE_FOG #ifdef FOG_EXP2 float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); #else float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); #endif gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); -#endif`,aL=`#ifdef USE_FOG +#endif`,_L=`#ifdef USE_FOG uniform vec3 fogColor; varying float vFogDepth; #ifdef FOG_EXP2 @@ -638,7 +638,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { uniform float fogNear; uniform float fogFar; #endif -#endif`,rL=`#ifdef USE_GRADIENTMAP +#endif`,gL=`#ifdef USE_GRADIENTMAP uniform sampler2D gradientMap; #endif vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { @@ -650,12 +650,12 @@ vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { vec2 fw = fwidth( coord ) * 0.5; return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); #endif -}`,oL=`#ifdef USE_LIGHTMAP +}`,yL=`#ifdef USE_LIGHTMAP uniform sampler2D lightMap; uniform float lightMapIntensity; -#endif`,lL=`LambertMaterial material; +#endif`,vL=`LambertMaterial material; material.diffuseColor = diffuseColor.rgb; -material.specularStrength = specularStrength;`,cL=`varying vec3 vViewPosition; +material.specularStrength = specularStrength;`,bL=`varying vec3 vViewPosition; struct LambertMaterial { vec3 diffuseColor; float specularStrength; @@ -669,7 +669,7 @@ void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometr reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Lambert -#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,uL=`uniform bool receiveShadow; +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,xL=`uniform bool receiveShadow; uniform vec3 ambientLightColor; #if defined( USE_LIGHT_PROBES ) uniform vec3 lightProbe[ 9 ]; @@ -785,7 +785,7 @@ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosi vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); return irradiance; } -#endif`,dL=`#ifdef USE_ENVMAP +#endif`,wL=`#ifdef USE_ENVMAP vec3 getIBLIrradiance( const in vec3 normal ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); @@ -818,8 +818,8 @@ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosi #endif } #endif -#endif`,hL=`ToonMaterial material; -material.diffuseColor = diffuseColor.rgb;`,fL=`varying vec3 vViewPosition; +#endif`,SL=`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,TL=`varying vec3 vViewPosition; struct ToonMaterial { vec3 diffuseColor; }; @@ -831,11 +831,11 @@ void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPo reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Toon -#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,pL=`BlinnPhongMaterial material; +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,ML=`BlinnPhongMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularColor = specular; material.specularShininess = shininess; -material.specularStrength = specularStrength;`,mL=`varying vec3 vViewPosition; +material.specularStrength = specularStrength;`,EL=`varying vec3 vViewPosition; struct BlinnPhongMaterial { vec3 diffuseColor; vec3 specularColor; @@ -852,7 +852,7 @@ void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geom reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_BlinnPhong -#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,_L=`PhysicalMaterial material; +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,CL=`PhysicalMaterial material; material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); @@ -938,7 +938,7 @@ material.roughness = min( material.roughness, 1.0 ); material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; -#endif`,gL=`struct PhysicalMaterial { +#endif`,AL=`struct PhysicalMaterial { vec3 diffuseColor; float roughness; vec3 specularColor; @@ -1239,7 +1239,7 @@ void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradia #define RE_IndirectSpecular RE_IndirectSpecular_Physical float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); -}`,yL=` +}`,RL=` vec3 geometryPosition = - vViewPosition; vec3 geometryNormal = normal; vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); @@ -1354,7 +1354,7 @@ IncidentLight directLight; #if defined( RE_IndirectSpecular ) vec3 radiance = vec3( 0.0 ); vec3 clearcoatRadiance = vec3( 0.0 ); -#endif`,vL=`#if defined( RE_IndirectDiffuse ) +#endif`,PL=`#if defined( RE_IndirectDiffuse ) #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; @@ -1373,32 +1373,32 @@ IncidentLight directLight; #ifdef USE_CLEARCOAT clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); #endif -#endif`,bL=`#if defined( RE_IndirectDiffuse ) +#endif`,IL=`#if defined( RE_IndirectDiffuse ) RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); #endif #if defined( RE_IndirectSpecular ) RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); -#endif`,xL=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) +#endif`,LL=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; -#endif`,wL=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) +#endif`,kL=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) uniform float logDepthBufFC; varying float vFragDepth; varying float vIsPerspective; -#endif`,SL=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER +#endif`,DL=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER varying float vFragDepth; varying float vIsPerspective; -#endif`,TL=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER +#endif`,OL=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER vFragDepth = 1.0 + gl_Position.w; vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); -#endif`,ML=`#ifdef USE_MAP +#endif`,FL=`#ifdef USE_MAP vec4 sampledDiffuseColor = texture2D( map, vMapUv ); #ifdef DECODE_VIDEO_TEXTURE sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); #endif diffuseColor *= sampledDiffuseColor; -#endif`,EL=`#ifdef USE_MAP +#endif`,NL=`#ifdef USE_MAP uniform sampler2D map; -#endif`,CL=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) +#endif`,UL=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) #if defined( USE_POINTS_UV ) vec2 uv = vUv; #else @@ -1410,7 +1410,7 @@ IncidentLight directLight; #endif #ifdef USE_ALPHAMAP diffuseColor.a *= texture2D( alphaMap, uv ).g; -#endif`,AL=`#if defined( USE_POINTS_UV ) +#endif`,BL=`#if defined( USE_POINTS_UV ) varying vec2 vUv; #else #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) @@ -1422,19 +1422,19 @@ IncidentLight directLight; #endif #ifdef USE_ALPHAMAP uniform sampler2D alphaMap; -#endif`,RL=`float metalnessFactor = metalness; +#endif`,zL=`float metalnessFactor = metalness; #ifdef USE_METALNESSMAP vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); metalnessFactor *= texelMetalness.b; -#endif`,PL=`#ifdef USE_METALNESSMAP +#endif`,HL=`#ifdef USE_METALNESSMAP uniform sampler2D metalnessMap; -#endif`,IL=`#ifdef USE_INSTANCING_MORPH +#endif`,VL=`#ifdef USE_INSTANCING_MORPH float morphTargetInfluences[ MORPHTARGETS_COUNT ]; float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; } -#endif`,LL=`#if defined( USE_MORPHCOLORS ) +#endif`,GL=`#if defined( USE_MORPHCOLORS ) vColor *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { #if defined( USE_COLOR_ALPHA ) @@ -1443,12 +1443,12 @@ IncidentLight directLight; if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; #endif } -#endif`,kL=`#ifdef USE_MORPHNORMALS +#endif`,$L=`#ifdef USE_MORPHNORMALS objectNormal *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; } -#endif`,DL=`#ifdef USE_MORPHTARGETS +#endif`,WL=`#ifdef USE_MORPHTARGETS #ifndef USE_INSTANCING_MORPH uniform float morphTargetBaseInfluence; uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; @@ -1462,12 +1462,12 @@ IncidentLight directLight; ivec3 morphUV = ivec3( x, y, morphTargetIndex ); return texelFetch( morphTargetsTexture, morphUV, 0 ); } -#endif`,OL=`#ifdef USE_MORPHTARGETS +#endif`,XL=`#ifdef USE_MORPHTARGETS transformed *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; } -#endif`,FL=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#endif`,KL=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; #ifdef FLAT_SHADED vec3 fdx = dFdx( vViewPosition ); vec3 fdy = dFdy( vViewPosition ); @@ -1508,7 +1508,7 @@ IncidentLight directLight; tbn2[1] *= faceDirection; #endif #endif -vec3 nonPerturbedNormal = normal;`,NL=`#ifdef USE_NORMALMAP_OBJECTSPACE +vec3 nonPerturbedNormal = normal;`,qL=`#ifdef USE_NORMALMAP_OBJECTSPACE normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; #ifdef FLIP_SIDED normal = - normal; @@ -1523,25 +1523,25 @@ vec3 nonPerturbedNormal = normal;`,NL=`#ifdef USE_NORMALMAP_OBJECTSPACE normal = normalize( tbn * mapN ); #elif defined( USE_BUMPMAP ) normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); -#endif`,UL=`#ifndef FLAT_SHADED +#endif`,YL=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif -#endif`,BL=`#ifndef FLAT_SHADED +#endif`,jL=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif -#endif`,zL=`#ifndef FLAT_SHADED +#endif`,ZL=`#ifndef FLAT_SHADED vNormal = normalize( transformedNormal ); #ifdef USE_TANGENT vTangent = normalize( transformedTangent ); vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); #endif -#endif`,HL=`#ifdef USE_NORMALMAP +#endif`,JL=`#ifdef USE_NORMALMAP uniform sampler2D normalMap; uniform vec2 normalScale; #endif @@ -1563,13 +1563,13 @@ vec3 nonPerturbedNormal = normal;`,NL=`#ifdef USE_NORMALMAP_OBJECTSPACE float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); return mat3( T * scale, B * scale, N ); } -#endif`,VL=`#ifdef USE_CLEARCOAT +#endif`,QL=`#ifdef USE_CLEARCOAT vec3 clearcoatNormal = nonPerturbedNormal; -#endif`,GL=`#ifdef USE_CLEARCOAT_NORMALMAP +#endif`,e2=`#ifdef USE_CLEARCOAT_NORMALMAP vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; clearcoatMapN.xy *= clearcoatNormalScale; clearcoatNormal = normalize( tbn2 * clearcoatMapN ); -#endif`,$L=`#ifdef USE_CLEARCOATMAP +#endif`,t2=`#ifdef USE_CLEARCOATMAP uniform sampler2D clearcoatMap; #endif #ifdef USE_CLEARCOAT_NORMALMAP @@ -1578,18 +1578,18 @@ vec3 nonPerturbedNormal = normal;`,NL=`#ifdef USE_NORMALMAP_OBJECTSPACE #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform sampler2D clearcoatRoughnessMap; -#endif`,WL=`#ifdef USE_IRIDESCENCEMAP +#endif`,n2=`#ifdef USE_IRIDESCENCEMAP uniform sampler2D iridescenceMap; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform sampler2D iridescenceThicknessMap; -#endif`,XL=`#ifdef OPAQUE +#endif`,i2=`#ifdef OPAQUE diffuseColor.a = 1.0; #endif #ifdef USE_TRANSMISSION diffuseColor.a *= material.transmissionAlpha; #endif -gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,KL=`vec3 packNormalToRGB( const in vec3 normal ) { +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,s2=`vec3 packNormalToRGB( const in vec3 normal ) { return normalize( normal ) * 0.5 + 0.5; } vec3 unpackRGBToNormal( const in vec3 rgb ) { @@ -1658,9 +1658,9 @@ float viewZToPerspectiveDepth( const in float viewZ, const in float near, const } float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { return ( near * far ) / ( ( far - near ) * depth - far ); -}`,qL=`#ifdef PREMULTIPLIED_ALPHA +}`,a2=`#ifdef PREMULTIPLIED_ALPHA gl_FragColor.rgb *= gl_FragColor.a; -#endif`,YL=`vec4 mvPosition = vec4( transformed, 1.0 ); +#endif`,r2=`vec4 mvPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING mvPosition = batchingMatrix * mvPosition; #endif @@ -1668,22 +1668,22 @@ float perspectiveDepthToViewZ( const in float depth, const in float near, const mvPosition = instanceMatrix * mvPosition; #endif mvPosition = modelViewMatrix * mvPosition; -gl_Position = projectionMatrix * mvPosition;`,jL=`#ifdef DITHERING +gl_Position = projectionMatrix * mvPosition;`,o2=`#ifdef DITHERING gl_FragColor.rgb = dithering( gl_FragColor.rgb ); -#endif`,ZL=`#ifdef DITHERING +#endif`,l2=`#ifdef DITHERING vec3 dithering( vec3 color ) { float grid_position = rand( gl_FragCoord.xy ); vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); return color + dither_shift_RGB; } -#endif`,JL=`float roughnessFactor = roughness; +#endif`,c2=`float roughnessFactor = roughness; #ifdef USE_ROUGHNESSMAP vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); roughnessFactor *= texelRoughness.g; -#endif`,QL=`#ifdef USE_ROUGHNESSMAP +#endif`,u2=`#ifdef USE_ROUGHNESSMAP uniform sampler2D roughnessMap; -#endif`,e2=`#if NUM_SPOT_LIGHT_COORDS > 0 +#endif`,d2=`#if NUM_SPOT_LIGHT_COORDS > 0 varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #if NUM_SPOT_LIGHT_MAPS > 0 @@ -1878,7 +1878,7 @@ gl_Position = projectionMatrix * mvPosition;`,jL=`#ifdef DITHERING } return mix( 1.0, shadow, shadowIntensity ); } -#endif`,t2=`#if NUM_SPOT_LIGHT_COORDS > 0 +#endif`,h2=`#if NUM_SPOT_LIGHT_COORDS > 0 uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif @@ -1919,7 +1919,7 @@ gl_Position = projectionMatrix * mvPosition;`,jL=`#ifdef DITHERING }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif -#endif`,n2=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) +#endif`,f2=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); vec4 shadowWorldPosition; #endif @@ -1951,7 +1951,7 @@ gl_Position = projectionMatrix * mvPosition;`,jL=`#ifdef DITHERING vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end -#endif`,i2=`float getShadowMask() { +#endif`,p2=`float getShadowMask() { float shadow = 1.0; #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 @@ -1983,12 +1983,12 @@ gl_Position = projectionMatrix * mvPosition;`,jL=`#ifdef DITHERING #endif #endif return shadow; -}`,s2=`#ifdef USE_SKINNING +}`,m2=`#ifdef USE_SKINNING mat4 boneMatX = getBoneMatrix( skinIndex.x ); mat4 boneMatY = getBoneMatrix( skinIndex.y ); mat4 boneMatZ = getBoneMatrix( skinIndex.z ); mat4 boneMatW = getBoneMatrix( skinIndex.w ); -#endif`,a2=`#ifdef USE_SKINNING +#endif`,_2=`#ifdef USE_SKINNING uniform mat4 bindMatrix; uniform mat4 bindMatrixInverse; uniform highp sampler2D boneTexture; @@ -2003,7 +2003,7 @@ gl_Position = projectionMatrix * mvPosition;`,jL=`#ifdef DITHERING vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); return mat4( v1, v2, v3, v4 ); } -#endif`,r2=`#ifdef USE_SKINNING +#endif`,g2=`#ifdef USE_SKINNING vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); vec4 skinned = vec4( 0.0 ); skinned += boneMatX * skinVertex * skinWeight.x; @@ -2011,7 +2011,7 @@ gl_Position = projectionMatrix * mvPosition;`,jL=`#ifdef DITHERING skinned += boneMatZ * skinVertex * skinWeight.z; skinned += boneMatW * skinVertex * skinWeight.w; transformed = ( bindMatrixInverse * skinned ).xyz; -#endif`,o2=`#ifdef USE_SKINNING +#endif`,y2=`#ifdef USE_SKINNING mat4 skinMatrix = mat4( 0.0 ); skinMatrix += skinWeight.x * boneMatX; skinMatrix += skinWeight.y * boneMatY; @@ -2022,17 +2022,17 @@ gl_Position = projectionMatrix * mvPosition;`,jL=`#ifdef DITHERING #ifdef USE_TANGENT objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; #endif -#endif`,l2=`float specularStrength; +#endif`,v2=`float specularStrength; #ifdef USE_SPECULARMAP vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); specularStrength = texelSpecular.r; #else specularStrength = 1.0; -#endif`,c2=`#ifdef USE_SPECULARMAP +#endif`,b2=`#ifdef USE_SPECULARMAP uniform sampler2D specularMap; -#endif`,u2=`#if defined( TONE_MAPPING ) +#endif`,x2=`#if defined( TONE_MAPPING ) gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); -#endif`,d2=`#ifndef saturate +#endif`,w2=`#ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif uniform float toneMappingExposure; @@ -2129,7 +2129,7 @@ vec3 NeutralToneMapping( vec3 color ) { float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); return mix( color, vec3( newPeak ), g ); } -vec3 CustomToneMapping( vec3 color ) { return color; }`,h2=`#ifdef USE_TRANSMISSION +vec3 CustomToneMapping( vec3 color ) { return color; }`,S2=`#ifdef USE_TRANSMISSION material.transmission = transmission; material.transmissionAlpha = 1.0; material.thickness = thickness; @@ -2150,7 +2150,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,h2=`#ifdef USE_TRANSMISS material.attenuationColor, material.attenuationDistance ); material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); -#endif`,f2=`#ifdef USE_TRANSMISSION +#endif`,T2=`#ifdef USE_TRANSMISSION uniform float transmission; uniform float thickness; uniform float attenuationDistance; @@ -2276,7 +2276,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,h2=`#ifdef USE_TRANSMISS float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); } -#endif`,p2=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) +#endif`,M2=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP @@ -2346,7 +2346,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,h2=`#ifdef USE_TRANSMISS #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; -#endif`,m2=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) +#endif`,E2=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP @@ -2440,7 +2440,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,h2=`#ifdef USE_TRANSMISS #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; -#endif`,_2=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) +#endif`,C2=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) vUv = vec3( uv, 1 ).xy; #endif #ifdef USE_MAP @@ -2511,7 +2511,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,h2=`#ifdef USE_TRANSMISS #endif #ifdef USE_THICKNESSMAP vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; -#endif`,g2=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 +#endif`,A2=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 vec4 worldPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING worldPosition = batchingMatrix * worldPosition; @@ -2520,12 +2520,12 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,h2=`#ifdef USE_TRANSMISS worldPosition = instanceMatrix * worldPosition; #endif worldPosition = modelMatrix * worldPosition; -#endif`;const y2=`varying vec2 vUv; +#endif`;const R2=`varying vec2 vUv; uniform mat3 uvTransform; void main() { vUv = ( uvTransform * vec3( uv, 1 ) ).xy; gl_Position = vec4( position.xy, 1.0, 1.0 ); -}`,v2=`uniform sampler2D t2D; +}`,P2=`uniform sampler2D t2D; uniform float backgroundIntensity; varying vec2 vUv; void main() { @@ -2537,14 +2537,14 @@ void main() { gl_FragColor = texColor; #include #include -}`,b2=`varying vec3 vWorldDirection; +}`,I2=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; -}`,x2=`#ifdef ENVMAP_TYPE_CUBE +}`,L2=`#ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #elif defined( ENVMAP_TYPE_CUBE_UV ) uniform sampler2D envMap; @@ -2567,14 +2567,14 @@ void main() { gl_FragColor = texColor; #include #include -}`,w2=`varying vec3 vWorldDirection; +}`,k2=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; -}`,S2=`uniform samplerCube tCube; +}`,D2=`uniform samplerCube tCube; uniform float tFlip; uniform float opacity; varying vec3 vWorldDirection; @@ -2584,7 +2584,7 @@ void main() { gl_FragColor.a *= opacity; #include #include -}`,T2=`#include +}`,O2=`#include #include #include #include @@ -2611,7 +2611,7 @@ void main() { #include #include vHighPrecisionZW = gl_Position.zw; -}`,M2=`#if DEPTH_PACKING == 3200 +}`,F2=`#if DEPTH_PACKING == 3200 uniform float opacity; #endif #include @@ -2649,7 +2649,7 @@ void main() { #elif DEPTH_PACKING == 3203 gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); #endif -}`,E2=`#define DISTANCE +}`,N2=`#define DISTANCE varying vec3 vWorldPosition; #include #include @@ -2676,7 +2676,7 @@ void main() { #include #include vWorldPosition = worldPosition.xyz; -}`,C2=`#define DISTANCE +}`,U2=`#define DISTANCE uniform vec3 referencePosition; uniform float nearDistance; uniform float farDistance; @@ -2700,13 +2700,13 @@ void main () { dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); dist = saturate( dist ); gl_FragColor = packDepthToRGBA( dist ); -}`,A2=`varying vec3 vWorldDirection; +}`,B2=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include -}`,R2=`uniform sampler2D tEquirect; +}`,z2=`uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { @@ -2715,7 +2715,7 @@ void main() { gl_FragColor = texture2D( tEquirect, sampleUV ); #include #include -}`,P2=`uniform float scale; +}`,H2=`uniform float scale; attribute float lineDistance; varying float vLineDistance; #include @@ -2737,7 +2737,7 @@ void main() { #include #include #include -}`,I2=`uniform vec3 diffuse; +}`,V2=`uniform vec3 diffuse; uniform float opacity; uniform float dashSize; uniform float totalSize; @@ -2765,7 +2765,7 @@ void main() { #include #include #include -}`,L2=`#include +}`,G2=`#include #include #include #include @@ -2797,7 +2797,7 @@ void main() { #include #include #include -}`,k2=`uniform vec3 diffuse; +}`,$2=`uniform vec3 diffuse; uniform float opacity; #ifndef FLAT_SHADED varying vec3 vNormal; @@ -2845,7 +2845,7 @@ void main() { #include #include #include -}`,D2=`#define LAMBERT +}`,W2=`#define LAMBERT varying vec3 vViewPosition; #include #include @@ -2884,7 +2884,7 @@ void main() { #include #include #include -}`,O2=`#define LAMBERT +}`,X2=`#define LAMBERT uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; @@ -2941,7 +2941,7 @@ void main() { #include #include #include -}`,F2=`#define MATCAP +}`,K2=`#define MATCAP varying vec3 vViewPosition; #include #include @@ -2975,7 +2975,7 @@ void main() { #include #include vViewPosition = - mvPosition.xyz; -}`,N2=`#define MATCAP +}`,q2=`#define MATCAP uniform vec3 diffuse; uniform float opacity; uniform sampler2D matcap; @@ -3021,7 +3021,7 @@ void main() { #include #include #include -}`,U2=`#define NORMAL +}`,Y2=`#define NORMAL #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif @@ -3054,7 +3054,7 @@ void main() { #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) vViewPosition = - mvPosition.xyz; #endif -}`,B2=`#define NORMAL +}`,j2=`#define NORMAL uniform float opacity; #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; @@ -3076,7 +3076,7 @@ void main() { #ifdef OPAQUE gl_FragColor.a = 1.0; #endif -}`,z2=`#define PHONG +}`,Z2=`#define PHONG varying vec3 vViewPosition; #include #include @@ -3115,7 +3115,7 @@ void main() { #include #include #include -}`,H2=`#define PHONG +}`,J2=`#define PHONG uniform vec3 diffuse; uniform vec3 emissive; uniform vec3 specular; @@ -3174,7 +3174,7 @@ void main() { #include #include #include -}`,V2=`#define STANDARD +}`,Q2=`#define STANDARD varying vec3 vViewPosition; #ifdef USE_TRANSMISSION varying vec3 vWorldPosition; @@ -3217,7 +3217,7 @@ void main() { #ifdef USE_TRANSMISSION vWorldPosition = worldPosition.xyz; #endif -}`,G2=`#define STANDARD +}`,ek=`#define STANDARD #ifdef PHYSICAL #define IOR #define USE_SPECULAR @@ -3342,7 +3342,7 @@ void main() { #include #include #include -}`,$2=`#define TOON +}`,tk=`#define TOON varying vec3 vViewPosition; #include #include @@ -3379,7 +3379,7 @@ void main() { #include #include #include -}`,W2=`#define TOON +}`,nk=`#define TOON uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; @@ -3432,7 +3432,7 @@ void main() { #include #include #include -}`,X2=`uniform float size; +}`,ik=`uniform float size; uniform float scale; #include #include @@ -3463,7 +3463,7 @@ void main() { #include #include #include -}`,K2=`uniform vec3 diffuse; +}`,sk=`uniform vec3 diffuse; uniform float opacity; #include #include @@ -3488,7 +3488,7 @@ void main() { #include #include #include -}`,q2=`#include +}`,ak=`#include #include #include #include @@ -3511,7 +3511,7 @@ void main() { #include #include #include -}`,Y2=`uniform vec3 color; +}`,rk=`uniform vec3 color; uniform float opacity; #include #include @@ -3527,7 +3527,7 @@ void main() { #include #include #include -}`,j2=`uniform float rotation; +}`,ok=`uniform float rotation; uniform vec2 center; #include #include @@ -3551,7 +3551,7 @@ void main() { #include #include #include -}`,Z2=`uniform vec3 diffuse; +}`,lk=`uniform vec3 diffuse; uniform float opacity; #include #include @@ -3576,7 +3576,7 @@ void main() { #include #include #include -}`,_t={alphahash_fragment:vI,alphahash_pars_fragment:bI,alphamap_fragment:xI,alphamap_pars_fragment:wI,alphatest_fragment:SI,alphatest_pars_fragment:TI,aomap_fragment:MI,aomap_pars_fragment:EI,batching_pars_vertex:CI,batching_vertex:AI,begin_vertex:RI,beginnormal_vertex:PI,bsdfs:II,iridescence_fragment:LI,bumpmap_pars_fragment:kI,clipping_planes_fragment:DI,clipping_planes_pars_fragment:OI,clipping_planes_pars_vertex:FI,clipping_planes_vertex:NI,color_fragment:UI,color_pars_fragment:BI,color_pars_vertex:zI,color_vertex:HI,common:VI,cube_uv_reflection_fragment:GI,defaultnormal_vertex:$I,displacementmap_pars_vertex:WI,displacementmap_vertex:XI,emissivemap_fragment:KI,emissivemap_pars_fragment:qI,colorspace_fragment:YI,colorspace_pars_fragment:jI,envmap_fragment:ZI,envmap_common_pars_fragment:JI,envmap_pars_fragment:QI,envmap_pars_vertex:eL,envmap_physical_pars_fragment:dL,envmap_vertex:tL,fog_vertex:nL,fog_pars_vertex:iL,fog_fragment:sL,fog_pars_fragment:aL,gradientmap_pars_fragment:rL,lightmap_pars_fragment:oL,lights_lambert_fragment:lL,lights_lambert_pars_fragment:cL,lights_pars_begin:uL,lights_toon_fragment:hL,lights_toon_pars_fragment:fL,lights_phong_fragment:pL,lights_phong_pars_fragment:mL,lights_physical_fragment:_L,lights_physical_pars_fragment:gL,lights_fragment_begin:yL,lights_fragment_maps:vL,lights_fragment_end:bL,logdepthbuf_fragment:xL,logdepthbuf_pars_fragment:wL,logdepthbuf_pars_vertex:SL,logdepthbuf_vertex:TL,map_fragment:ML,map_pars_fragment:EL,map_particle_fragment:CL,map_particle_pars_fragment:AL,metalnessmap_fragment:RL,metalnessmap_pars_fragment:PL,morphinstance_vertex:IL,morphcolor_vertex:LL,morphnormal_vertex:kL,morphtarget_pars_vertex:DL,morphtarget_vertex:OL,normal_fragment_begin:FL,normal_fragment_maps:NL,normal_pars_fragment:UL,normal_pars_vertex:BL,normal_vertex:zL,normalmap_pars_fragment:HL,clearcoat_normal_fragment_begin:VL,clearcoat_normal_fragment_maps:GL,clearcoat_pars_fragment:$L,iridescence_pars_fragment:WL,opaque_fragment:XL,packing:KL,premultiplied_alpha_fragment:qL,project_vertex:YL,dithering_fragment:jL,dithering_pars_fragment:ZL,roughnessmap_fragment:JL,roughnessmap_pars_fragment:QL,shadowmap_pars_fragment:e2,shadowmap_pars_vertex:t2,shadowmap_vertex:n2,shadowmask_pars_fragment:i2,skinbase_vertex:s2,skinning_pars_vertex:a2,skinning_vertex:r2,skinnormal_vertex:o2,specularmap_fragment:l2,specularmap_pars_fragment:c2,tonemapping_fragment:u2,tonemapping_pars_fragment:d2,transmission_fragment:h2,transmission_pars_fragment:f2,uv_pars_fragment:p2,uv_pars_vertex:m2,uv_vertex:_2,worldpos_vertex:g2,background_vert:y2,background_frag:v2,backgroundCube_vert:b2,backgroundCube_frag:x2,cube_vert:w2,cube_frag:S2,depth_vert:T2,depth_frag:M2,distanceRGBA_vert:E2,distanceRGBA_frag:C2,equirect_vert:A2,equirect_frag:R2,linedashed_vert:P2,linedashed_frag:I2,meshbasic_vert:L2,meshbasic_frag:k2,meshlambert_vert:D2,meshlambert_frag:O2,meshmatcap_vert:F2,meshmatcap_frag:N2,meshnormal_vert:U2,meshnormal_frag:B2,meshphong_vert:z2,meshphong_frag:H2,meshphysical_vert:V2,meshphysical_frag:G2,meshtoon_vert:$2,meshtoon_frag:W2,points_vert:X2,points_frag:K2,shadow_vert:q2,shadow_frag:Y2,sprite_vert:j2,sprite_frag:Z2},Me={common:{diffuse:{value:new de(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new at},alphaMap:{value:null},alphaMapTransform:{value:new at},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new at}},envmap:{envMap:{value:null},envMapRotation:{value:new at},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new at}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new at}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new at},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new at},normalScale:{value:new ne(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new at},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new at}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new at}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new at}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new de(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new de(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new at},alphaTest:{value:0},uvTransform:{value:new at}},sprite:{diffuse:{value:new de(16777215)},opacity:{value:1},center:{value:new ne(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new at},alphaMap:{value:null},alphaMapTransform:{value:new at},alphaTest:{value:0}}},Zi={basic:{uniforms:Hn([Me.common,Me.specularmap,Me.envmap,Me.aomap,Me.lightmap,Me.fog]),vertexShader:_t.meshbasic_vert,fragmentShader:_t.meshbasic_frag},lambert:{uniforms:Hn([Me.common,Me.specularmap,Me.envmap,Me.aomap,Me.lightmap,Me.emissivemap,Me.bumpmap,Me.normalmap,Me.displacementmap,Me.fog,Me.lights,{emissive:{value:new de(0)}}]),vertexShader:_t.meshlambert_vert,fragmentShader:_t.meshlambert_frag},phong:{uniforms:Hn([Me.common,Me.specularmap,Me.envmap,Me.aomap,Me.lightmap,Me.emissivemap,Me.bumpmap,Me.normalmap,Me.displacementmap,Me.fog,Me.lights,{emissive:{value:new de(0)},specular:{value:new de(1118481)},shininess:{value:30}}]),vertexShader:_t.meshphong_vert,fragmentShader:_t.meshphong_frag},standard:{uniforms:Hn([Me.common,Me.envmap,Me.aomap,Me.lightmap,Me.emissivemap,Me.bumpmap,Me.normalmap,Me.displacementmap,Me.roughnessmap,Me.metalnessmap,Me.fog,Me.lights,{emissive:{value:new de(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:_t.meshphysical_vert,fragmentShader:_t.meshphysical_frag},toon:{uniforms:Hn([Me.common,Me.aomap,Me.lightmap,Me.emissivemap,Me.bumpmap,Me.normalmap,Me.displacementmap,Me.gradientmap,Me.fog,Me.lights,{emissive:{value:new de(0)}}]),vertexShader:_t.meshtoon_vert,fragmentShader:_t.meshtoon_frag},matcap:{uniforms:Hn([Me.common,Me.bumpmap,Me.normalmap,Me.displacementmap,Me.fog,{matcap:{value:null}}]),vertexShader:_t.meshmatcap_vert,fragmentShader:_t.meshmatcap_frag},points:{uniforms:Hn([Me.points,Me.fog]),vertexShader:_t.points_vert,fragmentShader:_t.points_frag},dashed:{uniforms:Hn([Me.common,Me.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:_t.linedashed_vert,fragmentShader:_t.linedashed_frag},depth:{uniforms:Hn([Me.common,Me.displacementmap]),vertexShader:_t.depth_vert,fragmentShader:_t.depth_frag},normal:{uniforms:Hn([Me.common,Me.bumpmap,Me.normalmap,Me.displacementmap,{opacity:{value:1}}]),vertexShader:_t.meshnormal_vert,fragmentShader:_t.meshnormal_frag},sprite:{uniforms:Hn([Me.sprite,Me.fog]),vertexShader:_t.sprite_vert,fragmentShader:_t.sprite_frag},background:{uniforms:{uvTransform:{value:new at},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:_t.background_vert,fragmentShader:_t.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new at}},vertexShader:_t.backgroundCube_vert,fragmentShader:_t.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:_t.cube_vert,fragmentShader:_t.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:_t.equirect_vert,fragmentShader:_t.equirect_frag},distanceRGBA:{uniforms:Hn([Me.common,Me.displacementmap,{referencePosition:{value:new T},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:_t.distanceRGBA_vert,fragmentShader:_t.distanceRGBA_frag},shadow:{uniforms:Hn([Me.lights,Me.fog,{color:{value:new de(0)},opacity:{value:1}}]),vertexShader:_t.shadow_vert,fragmentShader:_t.shadow_frag}};Zi.physical={uniforms:Hn([Zi.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new at},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new at},clearcoatNormalScale:{value:new ne(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new at},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new at},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new at},sheen:{value:0},sheenColor:{value:new de(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new at},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new at},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new at},transmissionSamplerSize:{value:new ne},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new at},attenuationDistance:{value:0},attenuationColor:{value:new de(0)},specularColor:{value:new de(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new at},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new at},anisotropyVector:{value:new ne},anisotropyMap:{value:null},anisotropyMapTransform:{value:new at}}]),vertexShader:_t.meshphysical_vert,fragmentShader:_t.meshphysical_frag};const Tu={r:0,b:0,g:0},Na=new rn,J2=new Ee;function Q2(n,e,t,i,s,a,r){const o=new de(0);let l=a===!0?0:1,c,u,d=null,h=0,f=null;function p(y){let b=y.isScene===!0?y.background:null;return b&&b.isTexture&&(b=(y.backgroundBlurriness>0?t:e).get(b)),b}function g(y){let b=!1;const S=p(y);S===null?m(o,l):S&&S.isColor&&(m(S,1),b=!0);const x=n.xr.getEnvironmentBlendMode();x==="additive"?i.buffers.color.setClear(0,0,0,1,r):x==="alpha-blend"&&i.buffers.color.setClear(0,0,0,0,r),(n.autoClear||b)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),n.clear(n.autoClearColor,n.autoClearDepth,n.autoClearStencil))}function _(y,b){const S=p(b);S&&(S.isCubeTexture||S.mapping===Vo)?(u===void 0&&(u=new Se(new ki(1,1,1),new ri({name:"BackgroundCubeMaterial",uniforms:Fo(Zi.backgroundCube.uniforms),vertexShader:Zi.backgroundCube.vertexShader,fragmentShader:Zi.backgroundCube.fragmentShader,side:dn,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(x,M,C){this.matrixWorld.copyPosition(C.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),s.update(u)),Na.copy(b.backgroundRotation),Na.x*=-1,Na.y*=-1,Na.z*=-1,S.isCubeTexture&&S.isRenderTargetTexture===!1&&(Na.y*=-1,Na.z*=-1),u.material.uniforms.envMap.value=S,u.material.uniforms.flipEnvMap.value=S.isCubeTexture&&S.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=b.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(J2.makeRotationFromEuler(Na)),u.material.toneMapped=rt.getTransfer(S.colorSpace)!==It,(d!==S||h!==S.version||f!==n.toneMapping)&&(u.material.needsUpdate=!0,d=S,h=S.version,f=n.toneMapping),u.layers.enableAll(),y.unshift(u,u.geometry,u.material,0,0,null)):S&&S.isTexture&&(c===void 0&&(c=new Se(new Nn(2,2),new ri({name:"BackgroundMaterial",uniforms:Fo(Zi.background.uniforms),vertexShader:Zi.background.vertexShader,fragmentShader:Zi.background.fragmentShader,side:bs,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),s.update(c)),c.material.uniforms.t2D.value=S,c.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,c.material.toneMapped=rt.getTransfer(S.colorSpace)!==It,S.matrixAutoUpdate===!0&&S.updateMatrix(),c.material.uniforms.uvTransform.value.copy(S.matrix),(d!==S||h!==S.version||f!==n.toneMapping)&&(c.material.needsUpdate=!0,d=S,h=S.version,f=n.toneMapping),c.layers.enableAll(),y.unshift(c,c.geometry,c.material,0,0,null))}function m(y,b){y.getRGB(Tu,qS(n)),i.buffers.color.setClear(Tu.r,Tu.g,Tu.b,b,r)}function v(){u!==void 0&&(u.geometry.dispose(),u.material.dispose(),u=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return o},setClearColor:function(y,b=1){o.set(y),l=b,m(o,l)},getClearAlpha:function(){return l},setClearAlpha:function(y){l=y,m(o,l)},render:g,addToRenderList:_,dispose:v}}function ek(n,e){const t=n.getParameter(n.MAX_VERTEX_ATTRIBS),i={},s=h(null);let a=s,r=!1;function o(E,R,L,O,D){let U=!1;const F=d(O,L,R);a!==F&&(a=F,c(a.object)),U=f(E,O,L,D),U&&p(E,O,L,D),D!==null&&e.update(D,n.ELEMENT_ARRAY_BUFFER),(U||r)&&(r=!1,b(E,R,L,O),D!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e.get(D).buffer))}function l(){return n.createVertexArray()}function c(E){return n.bindVertexArray(E)}function u(E){return n.deleteVertexArray(E)}function d(E,R,L){const O=L.wireframe===!0;let D=i[E.id];D===void 0&&(D={},i[E.id]=D);let U=D[R.id];U===void 0&&(U={},D[R.id]=U);let F=U[O];return F===void 0&&(F=h(l()),U[O]=F),F}function h(E){const R=[],L=[],O=[];for(let D=0;D=0){const le=D[H];let me=U[H];if(me===void 0&&(H==="instanceMatrix"&&E.instanceMatrix&&(me=E.instanceMatrix),H==="instanceColor"&&E.instanceColor&&(me=E.instanceColor)),le===void 0||le.attribute!==me||me&&le.data!==me.data)return!0;F++}return a.attributesNum!==F||a.index!==O}function p(E,R,L,O){const D={},U=R.attributes;let F=0;const W=L.getAttributes();for(const H in W)if(W[H].location>=0){let le=U[H];le===void 0&&(H==="instanceMatrix"&&E.instanceMatrix&&(le=E.instanceMatrix),H==="instanceColor"&&E.instanceColor&&(le=E.instanceColor));const me={};me.attribute=le,le&&le.data&&(me.data=le.data),D[H]=me,F++}a.attributes=D,a.attributesNum=F,a.index=O}function g(){const E=a.newAttributes;for(let R=0,L=E.length;R=0){let ie=D[W];if(ie===void 0&&(W==="instanceMatrix"&&E.instanceMatrix&&(ie=E.instanceMatrix),W==="instanceColor"&&E.instanceColor&&(ie=E.instanceColor)),ie!==void 0){const le=ie.normalized,me=ie.itemSize,Le=e.get(ie);if(Le===void 0)continue;const De=Le.buffer,Ke=Le.type,Oe=Le.bytesPerElement,Z=Ke===n.INT||Ke===n.UNSIGNED_INT||ie.gpuType===Gh;if(ie.isInterleavedBufferAttribute){const ae=ie.data,Te=ae.stride,X=ie.offset;if(ae.isInstancedInterleavedBuffer){for(let se=0;se0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision>0)return"highp";M="mediump"}return M==="mediump"&&n.getShaderPrecisionFormat(n.VERTEX_SHADER,n.MEDIUM_FLOAT).precision>0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=t.precision!==void 0?t.precision:"highp";const u=l(c);u!==c&&(console.warn("THREE.WebGLRenderer:",c,"not supported, using",u,"instead."),c=u);const d=t.logarithmicDepthBuffer===!0,h=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),f=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),p=n.getParameter(n.MAX_VERTEX_TEXTURE_IMAGE_UNITS),g=n.getParameter(n.MAX_TEXTURE_SIZE),_=n.getParameter(n.MAX_CUBE_MAP_TEXTURE_SIZE),m=n.getParameter(n.MAX_VERTEX_ATTRIBS),v=n.getParameter(n.MAX_VERTEX_UNIFORM_VECTORS),y=n.getParameter(n.MAX_VARYING_VECTORS),b=n.getParameter(n.MAX_FRAGMENT_UNIFORM_VECTORS),S=p>0,x=n.getParameter(n.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:l,textureFormatReadable:r,textureTypeReadable:o,precision:c,logarithmicDepthBuffer:d,reversedDepthBuffer:h,maxTextures:f,maxVertexTextures:p,maxTextureSize:g,maxCubemapSize:_,maxAttributes:m,maxVertexUniforms:v,maxVaryings:y,maxFragmentUniforms:b,vertexTextures:S,maxSamples:x}}function ik(n){const e=this;let t=null,i=0,s=!1,a=!1;const r=new Ns,o=new at,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(d,h){const f=d.length!==0||h||i!==0||s;return s=h,i=d.length,f},this.beginShadows=function(){a=!0,u(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(d,h){t=u(d,h,0)},this.setState=function(d,h,f){const p=d.clippingPlanes,g=d.clipIntersection,_=d.clipShadows,m=n.get(d);if(!s||p===null||p.length===0||a&&!_)a?u(null):c();else{const v=a?0:i,y=v*4;let b=m.clippingState||null;l.value=b,b=u(p,h,y,f);for(let S=0;S!==y;++S)b[S]=t[S];m.clippingState=b,this.numIntersection=g?this.numPlanes:0,this.numPlanes+=v}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function u(d,h,f,p){const g=d!==null?d.length:0;let _=null;if(g!==0){if(_=l.value,p!==!0||_===null){const m=f+g*4,v=h.matrixWorldInverse;o.getNormalMatrix(v),(_===null||_.length0){const c=new ZS(l.height);return c.fromEquirectangularTexture(n,r),e.set(r,c),r.addEventListener("dispose",s),t(c.texture,r.mapping)}else return null}}return r}function s(r){const o=r.target;o.removeEventListener("dispose",s);const l=e.get(o);l!==void 0&&(e.delete(o),l.dispose())}function a(){e=new WeakMap}return{get:i,dispose:a}}const oo=4,q0=[.125,.215,.35,.446,.526,.582],Ya=20,Tp=new Rc,Y0=new de;let Mp=null,Ep=0,Cp=0,Ap=!1;const Ka=(1+Math.sqrt(5))/2,qr=1/Ka,j0=[new T(-Ka,qr,0),new T(Ka,qr,0),new T(-qr,0,Ka),new T(qr,0,Ka),new T(0,Ka,-qr),new T(0,Ka,qr),new T(-1,1,-1),new T(1,1,-1),new T(-1,1,1),new T(1,1,1)],ak=new T;class bh{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,i=.1,s=100,a={}){const{size:r=256,position:o=ak}=a;Mp=this._renderer.getRenderTarget(),Ep=this._renderer.getActiveCubeFace(),Cp=this._renderer.getActiveMipmapLevel(),Ap=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(r);const l=this._allocateTargets();return l.depthBuffer=!0,this._sceneToCubeUV(e,i,s,l,o),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Q0(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=J0(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?S:0,S,S),d.setRenderTarget(s),m&&d.render(_,l),d.render(e,l)}_.geometry.dispose(),_.material.dispose(),d.toneMapping=f,d.autoClear=h,e.background=v}_textureToCubeUV(e,t){const i=this._renderer,s=e.mapping===Xs||e.mapping===ma;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=Q0()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=J0());const a=s?this._cubemapMaterial:this._equirectMaterial,r=new Se(this._lodPlanes[0],a),o=a.uniforms;o.envMap.value=e;const l=this._cubeSize;Mu(t,0,0,3*l,2*l),i.setRenderTarget(t),i.render(r,Tp)}_applyPMREM(e){const t=this._renderer,i=t.autoClear;t.autoClear=!1;const s=this._lodPlanes.length;for(let a=1;aYa&&console.warn(`sigmaRadians, ${a}, is too large and will clip, as it requested ${_} samples when the maximum is set to ${Ya}`);const m=[];let v=0;for(let M=0;My-oo?s-y+oo:0),x=4*(this._cubeSize-b);Mu(t,S,x,3*b,2*b),l.setRenderTarget(t),l.render(d,Tp)}}function rk(n){const e=[],t=[],i=[];let s=n;const a=n-oo+1+q0.length;for(let r=0;rn-oo?l=q0[r-n+oo-1]:r===0&&(l=0),i.push(l);const c=1/(o-2),u=-c,d=1+c,h=[u,u,d,u,d,d,u,u,d,d,u,d],f=6,p=6,g=3,_=2,m=1,v=new Float32Array(g*p*f),y=new Float32Array(_*p*f),b=new Float32Array(m*p*f);for(let x=0;x2?0:-1,w=[M,C,0,M+2/3,C,0,M+2/3,C+1,0,M,C,0,M+2/3,C+1,0,M,C+1,0];v.set(w,g*p*x),y.set(h,_*p*x);const E=[x,x,x,x,x,x];b.set(E,m*p*x)}const S=new $e;S.setAttribute("position",new ot(v,g)),S.setAttribute("uv",new ot(y,_)),S.setAttribute("faceIndex",new ot(b,m)),e.push(S),s>oo&&s--}return{lodPlanes:e,sizeLods:t,sigmas:i}}function Z0(n,e,t){const i=new ws(n,e,t);return i.texture.mapping=Vo,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function Mu(n,e,t,i,s){n.viewport.set(e,t,i,s),n.scissor.set(e,t,i,s)}function ok(n,e,t){const i=new Float32Array(Ya),s=new T(0,1,0);return new ri({name:"SphericalGaussianBlur",defines:{n:Ya,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:s}},vertexShader:Zg(),fragmentShader:` +}`,_t={alphahash_fragment:PI,alphahash_pars_fragment:II,alphamap_fragment:LI,alphamap_pars_fragment:kI,alphatest_fragment:DI,alphatest_pars_fragment:OI,aomap_fragment:FI,aomap_pars_fragment:NI,batching_pars_vertex:UI,batching_vertex:BI,begin_vertex:zI,beginnormal_vertex:HI,bsdfs:VI,iridescence_fragment:GI,bumpmap_pars_fragment:$I,clipping_planes_fragment:WI,clipping_planes_pars_fragment:XI,clipping_planes_pars_vertex:KI,clipping_planes_vertex:qI,color_fragment:YI,color_pars_fragment:jI,color_pars_vertex:ZI,color_vertex:JI,common:QI,cube_uv_reflection_fragment:eL,defaultnormal_vertex:tL,displacementmap_pars_vertex:nL,displacementmap_vertex:iL,emissivemap_fragment:sL,emissivemap_pars_fragment:aL,colorspace_fragment:rL,colorspace_pars_fragment:oL,envmap_fragment:lL,envmap_common_pars_fragment:cL,envmap_pars_fragment:uL,envmap_pars_vertex:dL,envmap_physical_pars_fragment:wL,envmap_vertex:hL,fog_vertex:fL,fog_pars_vertex:pL,fog_fragment:mL,fog_pars_fragment:_L,gradientmap_pars_fragment:gL,lightmap_pars_fragment:yL,lights_lambert_fragment:vL,lights_lambert_pars_fragment:bL,lights_pars_begin:xL,lights_toon_fragment:SL,lights_toon_pars_fragment:TL,lights_phong_fragment:ML,lights_phong_pars_fragment:EL,lights_physical_fragment:CL,lights_physical_pars_fragment:AL,lights_fragment_begin:RL,lights_fragment_maps:PL,lights_fragment_end:IL,logdepthbuf_fragment:LL,logdepthbuf_pars_fragment:kL,logdepthbuf_pars_vertex:DL,logdepthbuf_vertex:OL,map_fragment:FL,map_pars_fragment:NL,map_particle_fragment:UL,map_particle_pars_fragment:BL,metalnessmap_fragment:zL,metalnessmap_pars_fragment:HL,morphinstance_vertex:VL,morphcolor_vertex:GL,morphnormal_vertex:$L,morphtarget_pars_vertex:WL,morphtarget_vertex:XL,normal_fragment_begin:KL,normal_fragment_maps:qL,normal_pars_fragment:YL,normal_pars_vertex:jL,normal_vertex:ZL,normalmap_pars_fragment:JL,clearcoat_normal_fragment_begin:QL,clearcoat_normal_fragment_maps:e2,clearcoat_pars_fragment:t2,iridescence_pars_fragment:n2,opaque_fragment:i2,packing:s2,premultiplied_alpha_fragment:a2,project_vertex:r2,dithering_fragment:o2,dithering_pars_fragment:l2,roughnessmap_fragment:c2,roughnessmap_pars_fragment:u2,shadowmap_pars_fragment:d2,shadowmap_pars_vertex:h2,shadowmap_vertex:f2,shadowmask_pars_fragment:p2,skinbase_vertex:m2,skinning_pars_vertex:_2,skinning_vertex:g2,skinnormal_vertex:y2,specularmap_fragment:v2,specularmap_pars_fragment:b2,tonemapping_fragment:x2,tonemapping_pars_fragment:w2,transmission_fragment:S2,transmission_pars_fragment:T2,uv_pars_fragment:M2,uv_pars_vertex:E2,uv_vertex:C2,worldpos_vertex:A2,background_vert:R2,background_frag:P2,backgroundCube_vert:I2,backgroundCube_frag:L2,cube_vert:k2,cube_frag:D2,depth_vert:O2,depth_frag:F2,distanceRGBA_vert:N2,distanceRGBA_frag:U2,equirect_vert:B2,equirect_frag:z2,linedashed_vert:H2,linedashed_frag:V2,meshbasic_vert:G2,meshbasic_frag:$2,meshlambert_vert:W2,meshlambert_frag:X2,meshmatcap_vert:K2,meshmatcap_frag:q2,meshnormal_vert:Y2,meshnormal_frag:j2,meshphong_vert:Z2,meshphong_frag:J2,meshphysical_vert:Q2,meshphysical_frag:ek,meshtoon_vert:tk,meshtoon_frag:nk,points_vert:ik,points_frag:sk,shadow_vert:ak,shadow_frag:rk,sprite_vert:ok,sprite_frag:lk},Me={common:{diffuse:{value:new de(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new rt},alphaMap:{value:null},alphaMapTransform:{value:new rt},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new rt}},envmap:{envMap:{value:null},envMapRotation:{value:new rt},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new rt}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new rt}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new rt},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new rt},normalScale:{value:new ne(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new rt},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new rt}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new rt}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new rt}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new de(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new de(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new rt},alphaTest:{value:0},uvTransform:{value:new rt}},sprite:{diffuse:{value:new de(16777215)},opacity:{value:1},center:{value:new ne(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new rt},alphaMap:{value:null},alphaMapTransform:{value:new rt},alphaTest:{value:0}}},Ji={basic:{uniforms:Hn([Me.common,Me.specularmap,Me.envmap,Me.aomap,Me.lightmap,Me.fog]),vertexShader:_t.meshbasic_vert,fragmentShader:_t.meshbasic_frag},lambert:{uniforms:Hn([Me.common,Me.specularmap,Me.envmap,Me.aomap,Me.lightmap,Me.emissivemap,Me.bumpmap,Me.normalmap,Me.displacementmap,Me.fog,Me.lights,{emissive:{value:new de(0)}}]),vertexShader:_t.meshlambert_vert,fragmentShader:_t.meshlambert_frag},phong:{uniforms:Hn([Me.common,Me.specularmap,Me.envmap,Me.aomap,Me.lightmap,Me.emissivemap,Me.bumpmap,Me.normalmap,Me.displacementmap,Me.fog,Me.lights,{emissive:{value:new de(0)},specular:{value:new de(1118481)},shininess:{value:30}}]),vertexShader:_t.meshphong_vert,fragmentShader:_t.meshphong_frag},standard:{uniforms:Hn([Me.common,Me.envmap,Me.aomap,Me.lightmap,Me.emissivemap,Me.bumpmap,Me.normalmap,Me.displacementmap,Me.roughnessmap,Me.metalnessmap,Me.fog,Me.lights,{emissive:{value:new de(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:_t.meshphysical_vert,fragmentShader:_t.meshphysical_frag},toon:{uniforms:Hn([Me.common,Me.aomap,Me.lightmap,Me.emissivemap,Me.bumpmap,Me.normalmap,Me.displacementmap,Me.gradientmap,Me.fog,Me.lights,{emissive:{value:new de(0)}}]),vertexShader:_t.meshtoon_vert,fragmentShader:_t.meshtoon_frag},matcap:{uniforms:Hn([Me.common,Me.bumpmap,Me.normalmap,Me.displacementmap,Me.fog,{matcap:{value:null}}]),vertexShader:_t.meshmatcap_vert,fragmentShader:_t.meshmatcap_frag},points:{uniforms:Hn([Me.points,Me.fog]),vertexShader:_t.points_vert,fragmentShader:_t.points_frag},dashed:{uniforms:Hn([Me.common,Me.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:_t.linedashed_vert,fragmentShader:_t.linedashed_frag},depth:{uniforms:Hn([Me.common,Me.displacementmap]),vertexShader:_t.depth_vert,fragmentShader:_t.depth_frag},normal:{uniforms:Hn([Me.common,Me.bumpmap,Me.normalmap,Me.displacementmap,{opacity:{value:1}}]),vertexShader:_t.meshnormal_vert,fragmentShader:_t.meshnormal_frag},sprite:{uniforms:Hn([Me.sprite,Me.fog]),vertexShader:_t.sprite_vert,fragmentShader:_t.sprite_frag},background:{uniforms:{uvTransform:{value:new rt},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:_t.background_vert,fragmentShader:_t.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new rt}},vertexShader:_t.backgroundCube_vert,fragmentShader:_t.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:_t.cube_vert,fragmentShader:_t.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:_t.equirect_vert,fragmentShader:_t.equirect_frag},distanceRGBA:{uniforms:Hn([Me.common,Me.displacementmap,{referencePosition:{value:new T},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:_t.distanceRGBA_vert,fragmentShader:_t.distanceRGBA_frag},shadow:{uniforms:Hn([Me.lights,Me.fog,{color:{value:new de(0)},opacity:{value:1}}]),vertexShader:_t.shadow_vert,fragmentShader:_t.shadow_frag}};Ji.physical={uniforms:Hn([Ji.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new rt},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new rt},clearcoatNormalScale:{value:new ne(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new rt},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new rt},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new rt},sheen:{value:0},sheenColor:{value:new de(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new rt},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new rt},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new rt},transmissionSamplerSize:{value:new ne},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new rt},attenuationDistance:{value:0},attenuationColor:{value:new de(0)},specularColor:{value:new de(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new rt},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new rt},anisotropyVector:{value:new ne},anisotropyMap:{value:null},anisotropyMapTransform:{value:new rt}}]),vertexShader:_t.meshphysical_vert,fragmentShader:_t.meshphysical_frag};const Au={r:0,b:0,g:0},Ua=new rn,ck=new Ee;function uk(n,e,t,i,s,a,r){const o=new de(0);let l=a===!0?0:1,c,u,d=null,h=0,f=null;function p(y){let b=y.isScene===!0?y.background:null;return b&&b.isTexture&&(b=(y.backgroundBlurriness>0?t:e).get(b)),b}function g(y){let b=!1;const S=p(y);S===null?m(o,l):S&&S.isColor&&(m(S,1),b=!0);const x=n.xr.getEnvironmentBlendMode();x==="additive"?i.buffers.color.setClear(0,0,0,1,r):x==="alpha-blend"&&i.buffers.color.setClear(0,0,0,0,r),(n.autoClear||b)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),n.clear(n.autoClearColor,n.autoClearDepth,n.autoClearStencil))}function _(y,b){const S=p(b);S&&(S.isCubeTexture||S.mapping===Wo)?(u===void 0&&(u=new Se(new Di(1,1,1),new ri({name:"BackgroundCubeMaterial",uniforms:Bo(Ji.backgroundCube.uniforms),vertexShader:Ji.backgroundCube.vertexShader,fragmentShader:Ji.backgroundCube.fragmentShader,side:dn,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(x,M,C){this.matrixWorld.copyPosition(C.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),s.update(u)),Ua.copy(b.backgroundRotation),Ua.x*=-1,Ua.y*=-1,Ua.z*=-1,S.isCubeTexture&&S.isRenderTargetTexture===!1&&(Ua.y*=-1,Ua.z*=-1),u.material.uniforms.envMap.value=S,u.material.uniforms.flipEnvMap.value=S.isCubeTexture&&S.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=b.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(ck.makeRotationFromEuler(Ua)),u.material.toneMapped=ot.getTransfer(S.colorSpace)!==It,(d!==S||h!==S.version||f!==n.toneMapping)&&(u.material.needsUpdate=!0,d=S,h=S.version,f=n.toneMapping),u.layers.enableAll(),y.unshift(u,u.geometry,u.material,0,0,null)):S&&S.isTexture&&(c===void 0&&(c=new Se(new Nn(2,2),new ri({name:"BackgroundMaterial",uniforms:Bo(Ji.background.uniforms),vertexShader:Ji.background.vertexShader,fragmentShader:Ji.background.fragmentShader,side:bs,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),s.update(c)),c.material.uniforms.t2D.value=S,c.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,c.material.toneMapped=ot.getTransfer(S.colorSpace)!==It,S.matrixAutoUpdate===!0&&S.updateMatrix(),c.material.uniforms.uvTransform.value.copy(S.matrix),(d!==S||h!==S.version||f!==n.toneMapping)&&(c.material.needsUpdate=!0,d=S,h=S.version,f=n.toneMapping),c.layers.enableAll(),y.unshift(c,c.geometry,c.material,0,0,null))}function m(y,b){y.getRGB(Au,iT(n)),i.buffers.color.setClear(Au.r,Au.g,Au.b,b,r)}function v(){u!==void 0&&(u.geometry.dispose(),u.material.dispose(),u=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return o},setClearColor:function(y,b=1){o.set(y),l=b,m(o,l)},getClearAlpha:function(){return l},setClearAlpha:function(y){l=y,m(o,l)},render:g,addToRenderList:_,dispose:v}}function dk(n,e){const t=n.getParameter(n.MAX_VERTEX_ATTRIBS),i={},s=h(null);let a=s,r=!1;function o(E,R,L,O,D){let U=!1;const F=d(O,L,R);a!==F&&(a=F,c(a.object)),U=f(E,O,L,D),U&&p(E,O,L,D),D!==null&&e.update(D,n.ELEMENT_ARRAY_BUFFER),(U||r)&&(r=!1,b(E,R,L,O),D!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e.get(D).buffer))}function l(){return n.createVertexArray()}function c(E){return n.bindVertexArray(E)}function u(E){return n.deleteVertexArray(E)}function d(E,R,L){const O=L.wireframe===!0;let D=i[E.id];D===void 0&&(D={},i[E.id]=D);let U=D[R.id];U===void 0&&(U={},D[R.id]=U);let F=U[O];return F===void 0&&(F=h(l()),U[O]=F),F}function h(E){const R=[],L=[],O=[];for(let D=0;D=0){const le=D[H];let me=U[H];if(me===void 0&&(H==="instanceMatrix"&&E.instanceMatrix&&(me=E.instanceMatrix),H==="instanceColor"&&E.instanceColor&&(me=E.instanceColor)),le===void 0||le.attribute!==me||me&&le.data!==me.data)return!0;F++}return a.attributesNum!==F||a.index!==O}function p(E,R,L,O){const D={},U=R.attributes;let F=0;const W=L.getAttributes();for(const H in W)if(W[H].location>=0){let le=U[H];le===void 0&&(H==="instanceMatrix"&&E.instanceMatrix&&(le=E.instanceMatrix),H==="instanceColor"&&E.instanceColor&&(le=E.instanceColor));const me={};me.attribute=le,le&&le.data&&(me.data=le.data),D[H]=me,F++}a.attributes=D,a.attributesNum=F,a.index=O}function g(){const E=a.newAttributes;for(let R=0,L=E.length;R=0){let ie=D[W];if(ie===void 0&&(W==="instanceMatrix"&&E.instanceMatrix&&(ie=E.instanceMatrix),W==="instanceColor"&&E.instanceColor&&(ie=E.instanceColor)),ie!==void 0){const le=ie.normalized,me=ie.itemSize,Le=e.get(ie);if(Le===void 0)continue;const De=Le.buffer,Ke=Le.type,Oe=Le.bytesPerElement,Z=Ke===n.INT||Ke===n.UNSIGNED_INT||ie.gpuType===Yh;if(ie.isInterleavedBufferAttribute){const re=ie.data,Te=re.stride,X=ie.offset;if(re.isInstancedInterleavedBuffer){for(let se=0;se0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision>0)return"highp";M="mediump"}return M==="mediump"&&n.getShaderPrecisionFormat(n.VERTEX_SHADER,n.MEDIUM_FLOAT).precision>0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=t.precision!==void 0?t.precision:"highp";const u=l(c);u!==c&&(console.warn("THREE.WebGLRenderer:",c,"not supported, using",u,"instead."),c=u);const d=t.logarithmicDepthBuffer===!0,h=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),f=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),p=n.getParameter(n.MAX_VERTEX_TEXTURE_IMAGE_UNITS),g=n.getParameter(n.MAX_TEXTURE_SIZE),_=n.getParameter(n.MAX_CUBE_MAP_TEXTURE_SIZE),m=n.getParameter(n.MAX_VERTEX_ATTRIBS),v=n.getParameter(n.MAX_VERTEX_UNIFORM_VECTORS),y=n.getParameter(n.MAX_VARYING_VECTORS),b=n.getParameter(n.MAX_FRAGMENT_UNIFORM_VECTORS),S=p>0,x=n.getParameter(n.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:l,textureFormatReadable:r,textureTypeReadable:o,precision:c,logarithmicDepthBuffer:d,reversedDepthBuffer:h,maxTextures:f,maxVertexTextures:p,maxTextureSize:g,maxCubemapSize:_,maxAttributes:m,maxVertexUniforms:v,maxVaryings:y,maxFragmentUniforms:b,vertexTextures:S,maxSamples:x}}function pk(n){const e=this;let t=null,i=0,s=!1,a=!1;const r=new Ns,o=new rt,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(d,h){const f=d.length!==0||h||i!==0||s;return s=h,i=d.length,f},this.beginShadows=function(){a=!0,u(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(d,h){t=u(d,h,0)},this.setState=function(d,h,f){const p=d.clippingPlanes,g=d.clipIntersection,_=d.clipShadows,m=n.get(d);if(!s||p===null||p.length===0||a&&!_)a?u(null):c();else{const v=a?0:i,y=v*4;let b=m.clippingState||null;l.value=b,b=u(p,h,y,f);for(let S=0;S!==y;++S)b[S]=t[S];m.clippingState=b,this.numIntersection=g?this.numPlanes:0,this.numPlanes+=v}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function u(d,h,f,p){const g=d!==null?d.length:0;let _=null;if(g!==0){if(_=l.value,p!==!0||_===null){const m=f+g*4,v=h.matrixWorldInverse;o.getNormalMatrix(v),(_===null||_.length0){const c=new rT(l.height);return c.fromEquirectangularTexture(n,r),e.set(r,c),r.addEventListener("dispose",s),t(c.texture,r.mapping)}else return null}}return r}function s(r){const o=r.target;o.removeEventListener("dispose",s);const l=e.get(o);l!==void 0&&(e.delete(o),l.dispose())}function a(){e=new WeakMap}return{get:i,dispose:a}}const co=4,tv=[.125,.215,.35,.446,.526,.582],ja=20,Pp=new kc,nv=new de;let Ip=null,Lp=0,kp=0,Dp=!1;const qa=(1+Math.sqrt(5))/2,Yr=1/qa,iv=[new T(-qa,Yr,0),new T(qa,Yr,0),new T(-Yr,0,qa),new T(Yr,0,qa),new T(0,qa,-Yr),new T(0,qa,Yr),new T(-1,1,-1),new T(1,1,-1),new T(-1,1,1),new T(1,1,1)],_k=new T;class Eh{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,i=.1,s=100,a={}){const{size:r=256,position:o=_k}=a;Ip=this._renderer.getRenderTarget(),Lp=this._renderer.getActiveCubeFace(),kp=this._renderer.getActiveMipmapLevel(),Dp=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(r);const l=this._allocateTargets();return l.depthBuffer=!0,this._sceneToCubeUV(e,i,s,l,o),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=rv(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=av(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?S:0,S,S),d.setRenderTarget(s),m&&d.render(_,l),d.render(e,l)}_.geometry.dispose(),_.material.dispose(),d.toneMapping=f,d.autoClear=h,e.background=v}_textureToCubeUV(e,t){const i=this._renderer,s=e.mapping===Xs||e.mapping===_a;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=rv()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=av());const a=s?this._cubemapMaterial:this._equirectMaterial,r=new Se(this._lodPlanes[0],a),o=a.uniforms;o.envMap.value=e;const l=this._cubeSize;Ru(t,0,0,3*l,2*l),i.setRenderTarget(t),i.render(r,Pp)}_applyPMREM(e){const t=this._renderer,i=t.autoClear;t.autoClear=!1;const s=this._lodPlanes.length;for(let a=1;aja&&console.warn(`sigmaRadians, ${a}, is too large and will clip, as it requested ${_} samples when the maximum is set to ${ja}`);const m=[];let v=0;for(let M=0;My-co?s-y+co:0),x=4*(this._cubeSize-b);Ru(t,S,x,3*b,2*b),l.setRenderTarget(t),l.render(d,Pp)}}function gk(n){const e=[],t=[],i=[];let s=n;const a=n-co+1+tv.length;for(let r=0;rn-co?l=tv[r-n+co-1]:r===0&&(l=0),i.push(l);const c=1/(o-2),u=-c,d=1+c,h=[u,u,d,u,d,d,u,u,d,d,u,d],f=6,p=6,g=3,_=2,m=1,v=new Float32Array(g*p*f),y=new Float32Array(_*p*f),b=new Float32Array(m*p*f);for(let x=0;x2?0:-1,w=[M,C,0,M+2/3,C,0,M+2/3,C+1,0,M,C,0,M+2/3,C+1,0,M,C+1,0];v.set(w,g*p*x),y.set(h,_*p*x);const E=[x,x,x,x,x,x];b.set(E,m*p*x)}const S=new $e;S.setAttribute("position",new lt(v,g)),S.setAttribute("uv",new lt(y,_)),S.setAttribute("faceIndex",new lt(b,m)),e.push(S),s>co&&s--}return{lodPlanes:e,sizeLods:t,sigmas:i}}function sv(n,e,t){const i=new ws(n,e,t);return i.texture.mapping=Wo,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function Ru(n,e,t,i,s){n.viewport.set(e,t,i,s),n.scissor.set(e,t,i,s)}function yk(n,e,t){const i=new Float32Array(ja),s=new T(0,1,0);return new ri({name:"SphericalGaussianBlur",defines:{n:ja,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:s}},vertexShader:sy(),fragmentShader:` precision mediump float; precision mediump int; @@ -3636,7 +3636,7 @@ void main() { } } - `,blending:Hs,depthTest:!1,depthWrite:!1})}function J0(){return new ri({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Zg(),fragmentShader:` + `,blending:Hs,depthTest:!1,depthWrite:!1})}function av(){return new ri({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:sy(),fragmentShader:` precision mediump float; precision mediump int; @@ -3655,7 +3655,7 @@ void main() { gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); } - `,blending:Hs,depthTest:!1,depthWrite:!1})}function Q0(){return new ri({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Zg(),fragmentShader:` + `,blending:Hs,depthTest:!1,depthWrite:!1})}function rv(){return new ri({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:sy(),fragmentShader:` precision mediump float; precision mediump int; @@ -3671,7 +3671,7 @@ void main() { gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); } - `,blending:Hs,depthTest:!1,depthWrite:!1})}function Zg(){return` + `,blending:Hs,depthTest:!1,depthWrite:!1})}function sy(){return` precision mediump float; precision mediump int; @@ -3726,17 +3726,17 @@ void main() { gl_Position = vec4( position, 1.0 ); } - `}function lk(n){let e=new WeakMap,t=null;function i(o){if(o&&o.isTexture){const l=o.mapping,c=l===pr||l===nc,u=l===Xs||l===ma;if(c||u){let d=e.get(o);const h=d!==void 0?d.texture.pmremVersion:0;if(o.isRenderTargetTexture&&o.pmremVersion!==h)return t===null&&(t=new bh(n)),d=c?t.fromEquirectangular(o,d):t.fromCubemap(o,d),d.texture.pmremVersion=o.pmremVersion,e.set(o,d),d.texture;if(d!==void 0)return d.texture;{const f=o.image;return c&&f&&f.height>0||u&&f&&s(f)?(t===null&&(t=new bh(n)),d=c?t.fromEquirectangular(o):t.fromCubemap(o),d.texture.pmremVersion=o.pmremVersion,e.set(o,d),o.addEventListener("dispose",a),d.texture):null}}}return o}function s(o){let l=0;const c=6;for(let u=0;ue.maxTextureSize&&(S=Math.ceil(b/e.maxTextureSize),b=e.maxTextureSize);const x=new Float32Array(b*S*4*d),M=new jh(x,b,S,d);M.type=Mn,M.needsUpdate=!0;const C=y*4;for(let E=0;E0)return n;const s=e*t;let a=tv[s];if(a===void 0&&(a=new Float32Array(s),tv[s]=a),e!==0){i.toArray(a,0);for(let r=1,o=0;r!==e;++r)o+=t,n[r].toArray(a,o)}return a}function fn(n,e){if(n.length!==e.length)return!1;for(let t=0,i=n.length;t0||u&&f&&s(f)?(t===null&&(t=new Eh(n)),d=c?t.fromEquirectangular(o):t.fromCubemap(o),d.texture.pmremVersion=o.pmremVersion,e.set(o,d),o.addEventListener("dispose",a),d.texture):null}}}return o}function s(o){let l=0;const c=6;for(let u=0;ue.maxTextureSize&&(S=Math.ceil(b/e.maxTextureSize),b=e.maxTextureSize);const x=new Float32Array(b*S*4*d),M=new nf(x,b,S,d);M.type=Mn,M.needsUpdate=!0;const C=y*4;for(let E=0;E0)return n;const s=e*t;let a=lv[s];if(a===void 0&&(a=new Float32Array(s),lv[s]=a),e!==0){i.toArray(a,0);for(let r=1,o=0;r!==e;++r)o+=t,n[r].toArray(a,o)}return a}function fn(n,e){if(n.length!==e.length)return!1;for(let t=0,i=n.length;t":" "} ${o}: ${t[r]}`)}return i.join(` -`)}const lv=new at;function lD(n){rt._getMatrix(lv,rt.workingColorSpace,n);const e=`mat3( ${lv.elements.map(t=>t.toFixed(4))} )`;switch(rt.getTransfer(n)){case sc:return[e,"LinearTransferOETF"];case It:return[e,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",n),[e,"LinearTransferOETF"]}}function cv(n,e,t){const i=n.getShaderParameter(e,n.COMPILE_STATUS),a=(n.getShaderInfoLog(e)||"").trim();if(i&&a==="")return"";const r=/ERROR: 0:(\d+)/.exec(a);if(r){const o=parseInt(r[1]);return t.toUpperCase()+` +`)}const mv=new rt;function vD(n){ot._getMatrix(mv,ot.workingColorSpace,n);const e=`mat3( ${mv.elements.map(t=>t.toFixed(4))} )`;switch(ot.getTransfer(n)){case lc:return[e,"LinearTransferOETF"];case It:return[e,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",n),[e,"LinearTransferOETF"]}}function _v(n,e,t){const i=n.getShaderParameter(e,n.COMPILE_STATUS),a=(n.getShaderInfoLog(e)||"").trim();if(i&&a==="")return"";const r=/ERROR: 0:(\d+)/.exec(a);if(r){const o=parseInt(r[1]);return t.toUpperCase()+` `+a+` -`+oD(n.getShaderSource(e),o)}else return a}function cD(n,e){const t=lD(e);return[`vec4 ${n}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(` -`)}function uD(n,e){let t;switch(e){case TS:t="Linear";break;case MS:t="Reinhard";break;case ES:t="Cineon";break;case hg:t="ACESFilmic";break;case AS:t="AgX";break;case RS:t="Neutral";break;case CS:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+n+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const Eu=new T;function dD(){rt.getLuminanceCoefficients(Eu);const n=Eu.x.toFixed(4),e=Eu.y.toFixed(4),t=Eu.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${n}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(` -`)}function hD(n){return[n.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",n.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Pl).join(` -`)}function fD(n){const e=[];for(const t in n){const i=n[t];i!==!1&&e.push("#define "+t+" "+i)}return e.join(` -`)}function pD(n,e){const t={},i=n.getProgramParameter(e,n.ACTIVE_ATTRIBUTES);for(let s=0;s/gm;function n_(n){return n.replace(mD,gD)}const _D=new Map;function gD(n,e){let t=_t[e];if(t===void 0){const i=_D.get(e);if(i!==void 0)t=_t[i],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,i);else throw new Error("Can not resolve #include <"+e+">")}return n_(t)}const yD=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function hv(n){return n.replace(yD,vD)}function vD(n,e,t,i){let s="";for(let a=parseInt(e);a/gm;function c_(n){return n.replace(ED,AD)}const CD=new Map;function AD(n,e){let t=_t[e];if(t===void 0){const i=CD.get(e);if(i!==void 0)t=_t[i],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,i);else throw new Error("Can not resolve #include <"+e+">")}return c_(t)}const RD=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function vv(n){return n.replace(RD,PD)}function PD(n,e,t,i){let s="";for(let a=parseInt(e);a0&&(_+=` -`),m=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p].filter(Pl).join(` +`),m=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p].filter(kl).join(` `),m.length>0&&(m+=` -`)):(_=[fv(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+u:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` -`].filter(Pl).join(` -`),m=[fv(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+u:"",t.envMap?"#define "+d:"",h?"#define CUBEUV_TEXEL_WIDTH "+h.texelWidth:"",h?"#define CUBEUV_TEXEL_HEIGHT "+h.texelHeight:"",h?"#define CUBEUV_MAX_MIP "+h.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==Vs?"#define TONE_MAPPING":"",t.toneMapping!==Vs?_t.tonemapping_pars_fragment:"",t.toneMapping!==Vs?uD("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",_t.colorspace_pars_fragment,cD("linearToOutputTexel",t.outputColorSpace),dD(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` -`].filter(Pl).join(` -`)),r=n_(r),r=uv(r,t),r=dv(r,t),o=n_(o),o=uv(o,t),o=dv(o,t),r=hv(r),o=hv(o),t.isRawShaderMaterial!==!0&&(v=`#version 300 es +`)):(_=[bv(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+u:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` +`].filter(kl).join(` +`),m=[bv(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+u:"",t.envMap?"#define "+d:"",h?"#define CUBEUV_TEXEL_WIDTH "+h.texelWidth:"",h?"#define CUBEUV_TEXEL_HEIGHT "+h.texelHeight:"",h?"#define CUBEUV_MAX_MIP "+h.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==Vs?"#define TONE_MAPPING":"",t.toneMapping!==Vs?_t.tonemapping_pars_fragment:"",t.toneMapping!==Vs?xD("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",_t.colorspace_pars_fragment,bD("linearToOutputTexel",t.outputColorSpace),wD(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` +`].filter(kl).join(` +`)),r=c_(r),r=gv(r,t),r=yv(r,t),o=c_(o),o=gv(o,t),o=yv(o,t),r=vv(r),o=vv(o),t.isRawShaderMaterial!==!0&&(v=`#version 300 es `,_=[f,"#define attribute in","#define varying out","#define texture2D texture"].join(` `)+` -`+_,m=["#define varying in",t.glslVersion===qm?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===qm?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` +`+_,m=["#define varying in",t.glslVersion===t_?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===t_?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` `)+` -`+m);const y=v+_+r,b=v+m+o,S=ov(s,s.VERTEX_SHADER,y),x=ov(s,s.FRAGMENT_SHADER,b);s.attachShader(g,S),s.attachShader(g,x),t.index0AttributeName!==void 0?s.bindAttribLocation(g,0,t.index0AttributeName):t.morphTargets===!0&&s.bindAttribLocation(g,0,"position"),s.linkProgram(g);function M(R){if(n.debug.checkShaderErrors){const L=s.getProgramInfoLog(g)||"",O=s.getShaderInfoLog(S)||"",D=s.getShaderInfoLog(x)||"",U=L.trim(),F=O.trim(),W=D.trim();let H=!0,ie=!0;if(s.getProgramParameter(g,s.LINK_STATUS)===!1)if(H=!1,typeof n.debug.onShaderError=="function")n.debug.onShaderError(s,g,S,x);else{const le=cv(s,S,"vertex"),me=cv(s,x,"fragment");console.error("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(g,s.VALIDATE_STATUS)+` +`+m);const y=v+_+r,b=v+m+o,S=pv(s,s.VERTEX_SHADER,y),x=pv(s,s.FRAGMENT_SHADER,b);s.attachShader(g,S),s.attachShader(g,x),t.index0AttributeName!==void 0?s.bindAttribLocation(g,0,t.index0AttributeName):t.morphTargets===!0&&s.bindAttribLocation(g,0,"position"),s.linkProgram(g);function M(R){if(n.debug.checkShaderErrors){const L=s.getProgramInfoLog(g)||"",O=s.getShaderInfoLog(S)||"",D=s.getShaderInfoLog(x)||"",U=L.trim(),F=O.trim(),W=D.trim();let H=!0,ie=!0;if(s.getProgramParameter(g,s.LINK_STATUS)===!1)if(H=!1,typeof n.debug.onShaderError=="function")n.debug.onShaderError(s,g,S,x);else{const le=_v(s,S,"vertex"),me=_v(s,x,"fragment");console.error("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(g,s.VALIDATE_STATUS)+` Material Name: `+R.name+` Material Type: `+R.type+` Program Info Log: `+U+` `+le+` -`+me)}else U!==""?console.warn("THREE.WebGLProgram: Program Info Log:",U):(F===""||W==="")&&(ie=!1);ie&&(R.diagnostics={runnable:H,programLog:U,vertexShader:{log:F,prefix:_},fragmentShader:{log:W,prefix:m}})}s.deleteShader(S),s.deleteShader(x),C=new ud(s,g),w=pD(s,g)}let C;this.getUniforms=function(){return C===void 0&&M(this),C};let w;this.getAttributes=function(){return w===void 0&&M(this),w};let E=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=s.getProgramParameter(g,aD)),E},this.destroy=function(){i.releaseStatesOfProgram(this),s.deleteProgram(g),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=rD++,this.cacheKey=e,this.usedTimes=1,this.program=g,this.vertexShader=S,this.fragmentShader=x,this}let ED=0;class CD{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,i=e.fragmentShader,s=this._getShaderStage(t),a=this._getShaderStage(i),r=this._getShaderCacheForMaterial(e);return r.has(s)===!1&&(r.add(s),s.usedTimes++),r.has(a)===!1&&(r.add(a),a.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return i===void 0&&(i=new AD(e),t.set(e,i)),i}}class AD{constructor(e){this.id=ED++,this.code=e,this.usedTimes=0}}function RD(n,e,t,i,s,a,r){const o=new Jh,l=new CD,c=new Set,u=[],d=s.logarithmicDepthBuffer,h=s.vertexTextures;let f=s.precision;const p={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function g(w){return c.add(w),w===0?"uv":`uv${w}`}function _(w,E,R,L,O){const D=L.fog,U=O.geometry,F=w.isMeshStandardMaterial?L.environment:null,W=(w.isMeshStandardMaterial?t:e).get(w.envMap||F),H=W&&W.mapping===Vo?W.image.height:null,ie=p[w.type];w.precision!==null&&(f=s.getMaxPrecision(w.precision),f!==w.precision&&console.warn("THREE.WebGLProgram.getParameters:",w.precision,"not supported, using",f,"instead."));const le=U.morphAttributes.position||U.morphAttributes.normal||U.morphAttributes.color,me=le!==void 0?le.length:0;let Le=0;U.morphAttributes.position!==void 0&&(Le=1),U.morphAttributes.normal!==void 0&&(Le=2),U.morphAttributes.color!==void 0&&(Le=3);let De,Ke,Oe,Z;if(ie){const At=Zi[ie];De=At.vertexShader,Ke=At.fragmentShader}else De=w.vertexShader,Ke=w.fragmentShader,l.update(w),Oe=l.getVertexShaderID(w),Z=l.getFragmentShaderID(w);const ae=n.getRenderTarget(),Te=n.state.buffers.depth.getReversed(),X=O.isInstancedMesh===!0,se=O.isBatchedMesh===!0,we=!!w.map,Re=!!w.matcap,k=!!W,G=!!w.aoMap,j=!!w.lightMap,Y=!!w.bumpMap,Q=!!w.normalMap,ge=!!w.displacementMap,ue=!!w.emissiveMap,ye=!!w.metalnessMap,We=!!w.roughnessMap,st=w.anisotropy>0,I=w.clearcoat>0,A=w.dispersion>0,V=w.iridescence>0,J=w.sheen>0,ce=w.transmission>0,ee=st&&!!w.anisotropyMap,Ve=I&&!!w.clearcoatMap,ve=I&&!!w.clearcoatNormalMap,Be=I&&!!w.clearcoatRoughnessMap,ze=V&&!!w.iridescenceMap,he=V&&!!w.iridescenceThicknessMap,Ie=J&&!!w.sheenColorMap,Qe=J&&!!w.sheenRoughnessMap,Ge=!!w.specularMap,Ae=!!w.specularColorMap,ft=!!w.specularIntensityMap,N=ce&&!!w.transmissionMap,_e=ce&&!!w.thicknessMap,xe=!!w.gradientMap,Ne=!!w.alphaMap,fe=w.alphaTest>0,oe=!!w.alphaHash,He=!!w.extensions;let ct=Vs;w.toneMapped&&(ae===null||ae.isXRRenderTarget===!0)&&(ct=n.toneMapping);const Ot={shaderID:ie,shaderType:w.type,shaderName:w.name,vertexShader:De,fragmentShader:Ke,defines:w.defines,customVertexShaderID:Oe,customFragmentShaderID:Z,isRawShaderMaterial:w.isRawShaderMaterial===!0,glslVersion:w.glslVersion,precision:f,batching:se,batchingColor:se&&O._colorsTexture!==null,instancing:X,instancingColor:X&&O.instanceColor!==null,instancingMorph:X&&O.morphTexture!==null,supportsVertexTextures:h,outputColorSpace:ae===null?n.outputColorSpace:ae.isXRRenderTarget===!0?ae.texture.colorSpace:wn,alphaToCoverage:!!w.alphaToCoverage,map:we,matcap:Re,envMap:k,envMapMode:k&&W.mapping,envMapCubeUVHeight:H,aoMap:G,lightMap:j,bumpMap:Y,normalMap:Q,displacementMap:h&&ge,emissiveMap:ue,normalMapObjectSpace:Q&&w.normalMapType===FS,normalMapTangentSpace:Q&&w.normalMapType===ba,metalnessMap:ye,roughnessMap:We,anisotropy:st,anisotropyMap:ee,clearcoat:I,clearcoatMap:Ve,clearcoatNormalMap:ve,clearcoatRoughnessMap:Be,dispersion:A,iridescence:V,iridescenceMap:ze,iridescenceThicknessMap:he,sheen:J,sheenColorMap:Ie,sheenRoughnessMap:Qe,specularMap:Ge,specularColorMap:Ae,specularIntensityMap:ft,transmission:ce,transmissionMap:N,thicknessMap:_e,gradientMap:xe,opaque:w.transparent===!1&&w.blending===ur&&w.alphaToCoverage===!1,alphaMap:Ne,alphaTest:fe,alphaHash:oe,combine:w.combine,mapUv:we&&g(w.map.channel),aoMapUv:G&&g(w.aoMap.channel),lightMapUv:j&&g(w.lightMap.channel),bumpMapUv:Y&&g(w.bumpMap.channel),normalMapUv:Q&&g(w.normalMap.channel),displacementMapUv:ge&&g(w.displacementMap.channel),emissiveMapUv:ue&&g(w.emissiveMap.channel),metalnessMapUv:ye&&g(w.metalnessMap.channel),roughnessMapUv:We&&g(w.roughnessMap.channel),anisotropyMapUv:ee&&g(w.anisotropyMap.channel),clearcoatMapUv:Ve&&g(w.clearcoatMap.channel),clearcoatNormalMapUv:ve&&g(w.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Be&&g(w.clearcoatRoughnessMap.channel),iridescenceMapUv:ze&&g(w.iridescenceMap.channel),iridescenceThicknessMapUv:he&&g(w.iridescenceThicknessMap.channel),sheenColorMapUv:Ie&&g(w.sheenColorMap.channel),sheenRoughnessMapUv:Qe&&g(w.sheenRoughnessMap.channel),specularMapUv:Ge&&g(w.specularMap.channel),specularColorMapUv:Ae&&g(w.specularColorMap.channel),specularIntensityMapUv:ft&&g(w.specularIntensityMap.channel),transmissionMapUv:N&&g(w.transmissionMap.channel),thicknessMapUv:_e&&g(w.thicknessMap.channel),alphaMapUv:Ne&&g(w.alphaMap.channel),vertexTangents:!!U.attributes.tangent&&(Q||st),vertexColors:w.vertexColors,vertexAlphas:w.vertexColors===!0&&!!U.attributes.color&&U.attributes.color.itemSize===4,pointsUvs:O.isPoints===!0&&!!U.attributes.uv&&(we||Ne),fog:!!D,useFog:w.fog===!0,fogExp2:!!D&&D.isFogExp2,flatShading:w.flatShading===!0&&w.wireframe===!1,sizeAttenuation:w.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:Te,skinning:O.isSkinnedMesh===!0,morphTargets:U.morphAttributes.position!==void 0,morphNormals:U.morphAttributes.normal!==void 0,morphColors:U.morphAttributes.color!==void 0,morphTargetsCount:me,morphTextureStride:Le,numDirLights:E.directional.length,numPointLights:E.point.length,numSpotLights:E.spot.length,numSpotLightMaps:E.spotLightMap.length,numRectAreaLights:E.rectArea.length,numHemiLights:E.hemi.length,numDirLightShadows:E.directionalShadowMap.length,numPointLightShadows:E.pointShadowMap.length,numSpotLightShadows:E.spotShadowMap.length,numSpotLightShadowsWithMaps:E.numSpotLightShadowsWithMaps,numLightProbes:E.numLightProbes,numClippingPlanes:r.numPlanes,numClipIntersection:r.numIntersection,dithering:w.dithering,shadowMapEnabled:n.shadowMap.enabled&&R.length>0,shadowMapType:n.shadowMap.type,toneMapping:ct,decodeVideoTexture:we&&w.map.isVideoTexture===!0&&rt.getTransfer(w.map.colorSpace)===It,decodeVideoTextureEmissive:ue&&w.emissiveMap.isVideoTexture===!0&&rt.getTransfer(w.emissiveMap.colorSpace)===It,premultipliedAlpha:w.premultipliedAlpha,doubleSided:w.side===ut,flipSided:w.side===dn,useDepthPacking:w.depthPacking>=0,depthPacking:w.depthPacking||0,index0AttributeName:w.index0AttributeName,extensionClipCullDistance:He&&w.extensions.clipCullDistance===!0&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(He&&w.extensions.multiDraw===!0||se)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:w.customProgramCacheKey()};return Ot.vertexUv1s=c.has(1),Ot.vertexUv2s=c.has(2),Ot.vertexUv3s=c.has(3),c.clear(),Ot}function m(w){const E=[];if(w.shaderID?E.push(w.shaderID):(E.push(w.customVertexShaderID),E.push(w.customFragmentShaderID)),w.defines!==void 0)for(const R in w.defines)E.push(R),E.push(w.defines[R]);return w.isRawShaderMaterial===!1&&(v(E,w),y(E,w),E.push(n.outputColorSpace)),E.push(w.customProgramCacheKey),E.join()}function v(w,E){w.push(E.precision),w.push(E.outputColorSpace),w.push(E.envMapMode),w.push(E.envMapCubeUVHeight),w.push(E.mapUv),w.push(E.alphaMapUv),w.push(E.lightMapUv),w.push(E.aoMapUv),w.push(E.bumpMapUv),w.push(E.normalMapUv),w.push(E.displacementMapUv),w.push(E.emissiveMapUv),w.push(E.metalnessMapUv),w.push(E.roughnessMapUv),w.push(E.anisotropyMapUv),w.push(E.clearcoatMapUv),w.push(E.clearcoatNormalMapUv),w.push(E.clearcoatRoughnessMapUv),w.push(E.iridescenceMapUv),w.push(E.iridescenceThicknessMapUv),w.push(E.sheenColorMapUv),w.push(E.sheenRoughnessMapUv),w.push(E.specularMapUv),w.push(E.specularColorMapUv),w.push(E.specularIntensityMapUv),w.push(E.transmissionMapUv),w.push(E.thicknessMapUv),w.push(E.combine),w.push(E.fogExp2),w.push(E.sizeAttenuation),w.push(E.morphTargetsCount),w.push(E.morphAttributeCount),w.push(E.numDirLights),w.push(E.numPointLights),w.push(E.numSpotLights),w.push(E.numSpotLightMaps),w.push(E.numHemiLights),w.push(E.numRectAreaLights),w.push(E.numDirLightShadows),w.push(E.numPointLightShadows),w.push(E.numSpotLightShadows),w.push(E.numSpotLightShadowsWithMaps),w.push(E.numLightProbes),w.push(E.shadowMapType),w.push(E.toneMapping),w.push(E.numClippingPlanes),w.push(E.numClipIntersection),w.push(E.depthPacking)}function y(w,E){o.disableAll(),E.supportsVertexTextures&&o.enable(0),E.instancing&&o.enable(1),E.instancingColor&&o.enable(2),E.instancingMorph&&o.enable(3),E.matcap&&o.enable(4),E.envMap&&o.enable(5),E.normalMapObjectSpace&&o.enable(6),E.normalMapTangentSpace&&o.enable(7),E.clearcoat&&o.enable(8),E.iridescence&&o.enable(9),E.alphaTest&&o.enable(10),E.vertexColors&&o.enable(11),E.vertexAlphas&&o.enable(12),E.vertexUv1s&&o.enable(13),E.vertexUv2s&&o.enable(14),E.vertexUv3s&&o.enable(15),E.vertexTangents&&o.enable(16),E.anisotropy&&o.enable(17),E.alphaHash&&o.enable(18),E.batching&&o.enable(19),E.dispersion&&o.enable(20),E.batchingColor&&o.enable(21),E.gradientMap&&o.enable(22),w.push(o.mask),o.disableAll(),E.fog&&o.enable(0),E.useFog&&o.enable(1),E.flatShading&&o.enable(2),E.logarithmicDepthBuffer&&o.enable(3),E.reversedDepthBuffer&&o.enable(4),E.skinning&&o.enable(5),E.morphTargets&&o.enable(6),E.morphNormals&&o.enable(7),E.morphColors&&o.enable(8),E.premultipliedAlpha&&o.enable(9),E.shadowMapEnabled&&o.enable(10),E.doubleSided&&o.enable(11),E.flipSided&&o.enable(12),E.useDepthPacking&&o.enable(13),E.dithering&&o.enable(14),E.transmission&&o.enable(15),E.sheen&&o.enable(16),E.opaque&&o.enable(17),E.pointsUvs&&o.enable(18),E.decodeVideoTexture&&o.enable(19),E.decodeVideoTextureEmissive&&o.enable(20),E.alphaToCoverage&&o.enable(21),w.push(o.mask)}function b(w){const E=p[w.type];let R;if(E){const L=Zi[E];R=YS.clone(L.uniforms)}else R=w.uniforms;return R}function S(w,E){let R;for(let L=0,O=u.length;L0?i.push(m):f.transparent===!0?s.push(m):t.push(m)}function l(d,h,f,p,g,_){const m=r(d,h,f,p,g,_);f.transmission>0?i.unshift(m):f.transparent===!0?s.unshift(m):t.unshift(m)}function c(d,h){t.length>1&&t.sort(d||ID),i.length>1&&i.sort(h||pv),s.length>1&&s.sort(h||pv)}function u(){for(let d=e,h=n.length;d=a.length?(r=new mv,a.push(r)):r=a[s],r}function t(){n=new WeakMap}return{get:e,dispose:t}}function kD(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new T,color:new de};break;case"SpotLight":t={position:new T,direction:new T,color:new de,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new T,color:new de,distance:0,decay:0};break;case"HemisphereLight":t={direction:new T,skyColor:new de,groundColor:new de};break;case"RectAreaLight":t={color:new de,position:new T,halfWidth:new T,halfHeight:new T};break}return n[e.id]=t,t}}}function DD(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ne};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ne};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ne,shadowCameraNear:1,shadowCameraFar:1e3};break}return n[e.id]=t,t}}}let OD=0;function FD(n,e){return(e.castShadow?2:0)-(n.castShadow?2:0)+(e.map?1:0)-(n.map?1:0)}function ND(n){const e=new kD,t=DD(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)i.probe.push(new T);const s=new T,a=new Ee,r=new Ee;function o(c){let u=0,d=0,h=0;for(let w=0;w<9;w++)i.probe[w].set(0,0,0);let f=0,p=0,g=0,_=0,m=0,v=0,y=0,b=0,S=0,x=0,M=0;c.sort(FD);for(let w=0,E=c.length;w0&&(n.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Me.LTC_FLOAT_1,i.rectAreaLTC2=Me.LTC_FLOAT_2):(i.rectAreaLTC1=Me.LTC_HALF_1,i.rectAreaLTC2=Me.LTC_HALF_2)),i.ambient[0]=u,i.ambient[1]=d,i.ambient[2]=h;const C=i.hash;(C.directionalLength!==f||C.pointLength!==p||C.spotLength!==g||C.rectAreaLength!==_||C.hemiLength!==m||C.numDirectionalShadows!==v||C.numPointShadows!==y||C.numSpotShadows!==b||C.numSpotMaps!==S||C.numLightProbes!==M)&&(i.directional.length=f,i.spot.length=g,i.rectArea.length=_,i.point.length=p,i.hemi.length=m,i.directionalShadow.length=v,i.directionalShadowMap.length=v,i.pointShadow.length=y,i.pointShadowMap.length=y,i.spotShadow.length=b,i.spotShadowMap.length=b,i.directionalShadowMatrix.length=v,i.pointShadowMatrix.length=y,i.spotLightMatrix.length=b+S-x,i.spotLightMap.length=S,i.numSpotLightShadowsWithMaps=x,i.numLightProbes=M,C.directionalLength=f,C.pointLength=p,C.spotLength=g,C.rectAreaLength=_,C.hemiLength=m,C.numDirectionalShadows=v,C.numPointShadows=y,C.numSpotShadows=b,C.numSpotMaps=S,C.numLightProbes=M,i.version=OD++)}function l(c,u){let d=0,h=0,f=0,p=0,g=0;const _=u.matrixWorldInverse;for(let m=0,v=c.length;m=r.length?(o=new _v(n),r.push(o)):o=r[a],o}function i(){e=new WeakMap}return{get:t,dispose:i}}const BD=`void main() { +`+me)}else U!==""?console.warn("THREE.WebGLProgram: Program Info Log:",U):(F===""||W==="")&&(ie=!1);ie&&(R.diagnostics={runnable:H,programLog:U,vertexShader:{log:F,prefix:_},fragmentShader:{log:W,prefix:m}})}s.deleteShader(S),s.deleteShader(x),C=new pd(s,g),w=MD(s,g)}let C;this.getUniforms=function(){return C===void 0&&M(this),C};let w;this.getAttributes=function(){return w===void 0&&M(this),w};let E=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=s.getProgramParameter(g,_D)),E},this.destroy=function(){i.releaseStatesOfProgram(this),s.deleteProgram(g),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=gD++,this.cacheKey=e,this.usedTimes=1,this.program=g,this.vertexShader=S,this.fragmentShader=x,this}let ND=0;class UD{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,i=e.fragmentShader,s=this._getShaderStage(t),a=this._getShaderStage(i),r=this._getShaderCacheForMaterial(e);return r.has(s)===!1&&(r.add(s),s.usedTimes++),r.has(a)===!1&&(r.add(a),a.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return i===void 0&&(i=new BD(e),t.set(e,i)),i}}class BD{constructor(e){this.id=ND++,this.code=e,this.usedTimes=0}}function zD(n,e,t,i,s,a,r){const o=new af,l=new UD,c=new Set,u=[],d=s.logarithmicDepthBuffer,h=s.vertexTextures;let f=s.precision;const p={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function g(w){return c.add(w),w===0?"uv":`uv${w}`}function _(w,E,R,L,O){const D=L.fog,U=O.geometry,F=w.isMeshStandardMaterial?L.environment:null,W=(w.isMeshStandardMaterial?t:e).get(w.envMap||F),H=W&&W.mapping===Wo?W.image.height:null,ie=p[w.type];w.precision!==null&&(f=s.getMaxPrecision(w.precision),f!==w.precision&&console.warn("THREE.WebGLProgram.getParameters:",w.precision,"not supported, using",f,"instead."));const le=U.morphAttributes.position||U.morphAttributes.normal||U.morphAttributes.color,me=le!==void 0?le.length:0;let Le=0;U.morphAttributes.position!==void 0&&(Le=1),U.morphAttributes.normal!==void 0&&(Le=2),U.morphAttributes.color!==void 0&&(Le=3);let De,Ke,Oe,Z;if(ie){const At=Ji[ie];De=At.vertexShader,Ke=At.fragmentShader}else De=w.vertexShader,Ke=w.fragmentShader,l.update(w),Oe=l.getVertexShaderID(w),Z=l.getFragmentShaderID(w);const re=n.getRenderTarget(),Te=n.state.buffers.depth.getReversed(),X=O.isInstancedMesh===!0,se=O.isBatchedMesh===!0,we=!!w.map,Re=!!w.matcap,k=!!W,G=!!w.aoMap,j=!!w.lightMap,Y=!!w.bumpMap,Q=!!w.normalMap,ge=!!w.displacementMap,ue=!!w.emissiveMap,ye=!!w.metalnessMap,We=!!w.roughnessMap,st=w.anisotropy>0,I=w.clearcoat>0,A=w.dispersion>0,V=w.iridescence>0,J=w.sheen>0,ce=w.transmission>0,ee=st&&!!w.anisotropyMap,Ve=I&&!!w.clearcoatMap,ve=I&&!!w.clearcoatNormalMap,Be=I&&!!w.clearcoatRoughnessMap,ze=V&&!!w.iridescenceMap,he=V&&!!w.iridescenceThicknessMap,Ie=J&&!!w.sheenColorMap,Qe=J&&!!w.sheenRoughnessMap,Ge=!!w.specularMap,Ae=!!w.specularColorMap,ft=!!w.specularIntensityMap,N=ce&&!!w.transmissionMap,_e=ce&&!!w.thicknessMap,xe=!!w.gradientMap,Ne=!!w.alphaMap,fe=w.alphaTest>0,oe=!!w.alphaHash,He=!!w.extensions;let ct=Vs;w.toneMapped&&(re===null||re.isXRRenderTarget===!0)&&(ct=n.toneMapping);const Ot={shaderID:ie,shaderType:w.type,shaderName:w.name,vertexShader:De,fragmentShader:Ke,defines:w.defines,customVertexShaderID:Oe,customFragmentShaderID:Z,isRawShaderMaterial:w.isRawShaderMaterial===!0,glslVersion:w.glslVersion,precision:f,batching:se,batchingColor:se&&O._colorsTexture!==null,instancing:X,instancingColor:X&&O.instanceColor!==null,instancingMorph:X&&O.morphTexture!==null,supportsVertexTextures:h,outputColorSpace:re===null?n.outputColorSpace:re.isXRRenderTarget===!0?re.texture.colorSpace:wn,alphaToCoverage:!!w.alphaToCoverage,map:we,matcap:Re,envMap:k,envMapMode:k&&W.mapping,envMapCubeUVHeight:H,aoMap:G,lightMap:j,bumpMap:Y,normalMap:Q,displacementMap:h&&ge,emissiveMap:ue,normalMapObjectSpace:Q&&w.normalMapType===WS,normalMapTangentSpace:Q&&w.normalMapType===xa,metalnessMap:ye,roughnessMap:We,anisotropy:st,anisotropyMap:ee,clearcoat:I,clearcoatMap:Ve,clearcoatNormalMap:ve,clearcoatRoughnessMap:Be,dispersion:A,iridescence:V,iridescenceMap:ze,iridescenceThicknessMap:he,sheen:J,sheenColorMap:Ie,sheenRoughnessMap:Qe,specularMap:Ge,specularColorMap:Ae,specularIntensityMap:ft,transmission:ce,transmissionMap:N,thicknessMap:_e,gradientMap:xe,opaque:w.transparent===!1&&w.blending===dr&&w.alphaToCoverage===!1,alphaMap:Ne,alphaTest:fe,alphaHash:oe,combine:w.combine,mapUv:we&&g(w.map.channel),aoMapUv:G&&g(w.aoMap.channel),lightMapUv:j&&g(w.lightMap.channel),bumpMapUv:Y&&g(w.bumpMap.channel),normalMapUv:Q&&g(w.normalMap.channel),displacementMapUv:ge&&g(w.displacementMap.channel),emissiveMapUv:ue&&g(w.emissiveMap.channel),metalnessMapUv:ye&&g(w.metalnessMap.channel),roughnessMapUv:We&&g(w.roughnessMap.channel),anisotropyMapUv:ee&&g(w.anisotropyMap.channel),clearcoatMapUv:Ve&&g(w.clearcoatMap.channel),clearcoatNormalMapUv:ve&&g(w.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Be&&g(w.clearcoatRoughnessMap.channel),iridescenceMapUv:ze&&g(w.iridescenceMap.channel),iridescenceThicknessMapUv:he&&g(w.iridescenceThicknessMap.channel),sheenColorMapUv:Ie&&g(w.sheenColorMap.channel),sheenRoughnessMapUv:Qe&&g(w.sheenRoughnessMap.channel),specularMapUv:Ge&&g(w.specularMap.channel),specularColorMapUv:Ae&&g(w.specularColorMap.channel),specularIntensityMapUv:ft&&g(w.specularIntensityMap.channel),transmissionMapUv:N&&g(w.transmissionMap.channel),thicknessMapUv:_e&&g(w.thicknessMap.channel),alphaMapUv:Ne&&g(w.alphaMap.channel),vertexTangents:!!U.attributes.tangent&&(Q||st),vertexColors:w.vertexColors,vertexAlphas:w.vertexColors===!0&&!!U.attributes.color&&U.attributes.color.itemSize===4,pointsUvs:O.isPoints===!0&&!!U.attributes.uv&&(we||Ne),fog:!!D,useFog:w.fog===!0,fogExp2:!!D&&D.isFogExp2,flatShading:w.flatShading===!0&&w.wireframe===!1,sizeAttenuation:w.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:Te,skinning:O.isSkinnedMesh===!0,morphTargets:U.morphAttributes.position!==void 0,morphNormals:U.morphAttributes.normal!==void 0,morphColors:U.morphAttributes.color!==void 0,morphTargetsCount:me,morphTextureStride:Le,numDirLights:E.directional.length,numPointLights:E.point.length,numSpotLights:E.spot.length,numSpotLightMaps:E.spotLightMap.length,numRectAreaLights:E.rectArea.length,numHemiLights:E.hemi.length,numDirLightShadows:E.directionalShadowMap.length,numPointLightShadows:E.pointShadowMap.length,numSpotLightShadows:E.spotShadowMap.length,numSpotLightShadowsWithMaps:E.numSpotLightShadowsWithMaps,numLightProbes:E.numLightProbes,numClippingPlanes:r.numPlanes,numClipIntersection:r.numIntersection,dithering:w.dithering,shadowMapEnabled:n.shadowMap.enabled&&R.length>0,shadowMapType:n.shadowMap.type,toneMapping:ct,decodeVideoTexture:we&&w.map.isVideoTexture===!0&&ot.getTransfer(w.map.colorSpace)===It,decodeVideoTextureEmissive:ue&&w.emissiveMap.isVideoTexture===!0&&ot.getTransfer(w.emissiveMap.colorSpace)===It,premultipliedAlpha:w.premultipliedAlpha,doubleSided:w.side===ut,flipSided:w.side===dn,useDepthPacking:w.depthPacking>=0,depthPacking:w.depthPacking||0,index0AttributeName:w.index0AttributeName,extensionClipCullDistance:He&&w.extensions.clipCullDistance===!0&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(He&&w.extensions.multiDraw===!0||se)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:w.customProgramCacheKey()};return Ot.vertexUv1s=c.has(1),Ot.vertexUv2s=c.has(2),Ot.vertexUv3s=c.has(3),c.clear(),Ot}function m(w){const E=[];if(w.shaderID?E.push(w.shaderID):(E.push(w.customVertexShaderID),E.push(w.customFragmentShaderID)),w.defines!==void 0)for(const R in w.defines)E.push(R),E.push(w.defines[R]);return w.isRawShaderMaterial===!1&&(v(E,w),y(E,w),E.push(n.outputColorSpace)),E.push(w.customProgramCacheKey),E.join()}function v(w,E){w.push(E.precision),w.push(E.outputColorSpace),w.push(E.envMapMode),w.push(E.envMapCubeUVHeight),w.push(E.mapUv),w.push(E.alphaMapUv),w.push(E.lightMapUv),w.push(E.aoMapUv),w.push(E.bumpMapUv),w.push(E.normalMapUv),w.push(E.displacementMapUv),w.push(E.emissiveMapUv),w.push(E.metalnessMapUv),w.push(E.roughnessMapUv),w.push(E.anisotropyMapUv),w.push(E.clearcoatMapUv),w.push(E.clearcoatNormalMapUv),w.push(E.clearcoatRoughnessMapUv),w.push(E.iridescenceMapUv),w.push(E.iridescenceThicknessMapUv),w.push(E.sheenColorMapUv),w.push(E.sheenRoughnessMapUv),w.push(E.specularMapUv),w.push(E.specularColorMapUv),w.push(E.specularIntensityMapUv),w.push(E.transmissionMapUv),w.push(E.thicknessMapUv),w.push(E.combine),w.push(E.fogExp2),w.push(E.sizeAttenuation),w.push(E.morphTargetsCount),w.push(E.morphAttributeCount),w.push(E.numDirLights),w.push(E.numPointLights),w.push(E.numSpotLights),w.push(E.numSpotLightMaps),w.push(E.numHemiLights),w.push(E.numRectAreaLights),w.push(E.numDirLightShadows),w.push(E.numPointLightShadows),w.push(E.numSpotLightShadows),w.push(E.numSpotLightShadowsWithMaps),w.push(E.numLightProbes),w.push(E.shadowMapType),w.push(E.toneMapping),w.push(E.numClippingPlanes),w.push(E.numClipIntersection),w.push(E.depthPacking)}function y(w,E){o.disableAll(),E.supportsVertexTextures&&o.enable(0),E.instancing&&o.enable(1),E.instancingColor&&o.enable(2),E.instancingMorph&&o.enable(3),E.matcap&&o.enable(4),E.envMap&&o.enable(5),E.normalMapObjectSpace&&o.enable(6),E.normalMapTangentSpace&&o.enable(7),E.clearcoat&&o.enable(8),E.iridescence&&o.enable(9),E.alphaTest&&o.enable(10),E.vertexColors&&o.enable(11),E.vertexAlphas&&o.enable(12),E.vertexUv1s&&o.enable(13),E.vertexUv2s&&o.enable(14),E.vertexUv3s&&o.enable(15),E.vertexTangents&&o.enable(16),E.anisotropy&&o.enable(17),E.alphaHash&&o.enable(18),E.batching&&o.enable(19),E.dispersion&&o.enable(20),E.batchingColor&&o.enable(21),E.gradientMap&&o.enable(22),w.push(o.mask),o.disableAll(),E.fog&&o.enable(0),E.useFog&&o.enable(1),E.flatShading&&o.enable(2),E.logarithmicDepthBuffer&&o.enable(3),E.reversedDepthBuffer&&o.enable(4),E.skinning&&o.enable(5),E.morphTargets&&o.enable(6),E.morphNormals&&o.enable(7),E.morphColors&&o.enable(8),E.premultipliedAlpha&&o.enable(9),E.shadowMapEnabled&&o.enable(10),E.doubleSided&&o.enable(11),E.flipSided&&o.enable(12),E.useDepthPacking&&o.enable(13),E.dithering&&o.enable(14),E.transmission&&o.enable(15),E.sheen&&o.enable(16),E.opaque&&o.enable(17),E.pointsUvs&&o.enable(18),E.decodeVideoTexture&&o.enable(19),E.decodeVideoTextureEmissive&&o.enable(20),E.alphaToCoverage&&o.enable(21),w.push(o.mask)}function b(w){const E=p[w.type];let R;if(E){const L=Ji[E];R=sT.clone(L.uniforms)}else R=w.uniforms;return R}function S(w,E){let R;for(let L=0,O=u.length;L0?i.push(m):f.transparent===!0?s.push(m):t.push(m)}function l(d,h,f,p,g,_){const m=r(d,h,f,p,g,_);f.transmission>0?i.unshift(m):f.transparent===!0?s.unshift(m):t.unshift(m)}function c(d,h){t.length>1&&t.sort(d||VD),i.length>1&&i.sort(h||xv),s.length>1&&s.sort(h||xv)}function u(){for(let d=e,h=n.length;d=a.length?(r=new wv,a.push(r)):r=a[s],r}function t(){n=new WeakMap}return{get:e,dispose:t}}function $D(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new T,color:new de};break;case"SpotLight":t={position:new T,direction:new T,color:new de,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new T,color:new de,distance:0,decay:0};break;case"HemisphereLight":t={direction:new T,skyColor:new de,groundColor:new de};break;case"RectAreaLight":t={color:new de,position:new T,halfWidth:new T,halfHeight:new T};break}return n[e.id]=t,t}}}function WD(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ne};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ne};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ne,shadowCameraNear:1,shadowCameraFar:1e3};break}return n[e.id]=t,t}}}let XD=0;function KD(n,e){return(e.castShadow?2:0)-(n.castShadow?2:0)+(e.map?1:0)-(n.map?1:0)}function qD(n){const e=new $D,t=WD(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)i.probe.push(new T);const s=new T,a=new Ee,r=new Ee;function o(c){let u=0,d=0,h=0;for(let w=0;w<9;w++)i.probe[w].set(0,0,0);let f=0,p=0,g=0,_=0,m=0,v=0,y=0,b=0,S=0,x=0,M=0;c.sort(KD);for(let w=0,E=c.length;w0&&(n.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Me.LTC_FLOAT_1,i.rectAreaLTC2=Me.LTC_FLOAT_2):(i.rectAreaLTC1=Me.LTC_HALF_1,i.rectAreaLTC2=Me.LTC_HALF_2)),i.ambient[0]=u,i.ambient[1]=d,i.ambient[2]=h;const C=i.hash;(C.directionalLength!==f||C.pointLength!==p||C.spotLength!==g||C.rectAreaLength!==_||C.hemiLength!==m||C.numDirectionalShadows!==v||C.numPointShadows!==y||C.numSpotShadows!==b||C.numSpotMaps!==S||C.numLightProbes!==M)&&(i.directional.length=f,i.spot.length=g,i.rectArea.length=_,i.point.length=p,i.hemi.length=m,i.directionalShadow.length=v,i.directionalShadowMap.length=v,i.pointShadow.length=y,i.pointShadowMap.length=y,i.spotShadow.length=b,i.spotShadowMap.length=b,i.directionalShadowMatrix.length=v,i.pointShadowMatrix.length=y,i.spotLightMatrix.length=b+S-x,i.spotLightMap.length=S,i.numSpotLightShadowsWithMaps=x,i.numLightProbes=M,C.directionalLength=f,C.pointLength=p,C.spotLength=g,C.rectAreaLength=_,C.hemiLength=m,C.numDirectionalShadows=v,C.numPointShadows=y,C.numSpotShadows=b,C.numSpotMaps=S,C.numLightProbes=M,i.version=XD++)}function l(c,u){let d=0,h=0,f=0,p=0,g=0;const _=u.matrixWorldInverse;for(let m=0,v=c.length;m=r.length?(o=new Sv(n),r.push(o)):o=r[a],o}function i(){e=new WeakMap}return{get:t,dispose:i}}const jD=`void main() { gl_Position = vec4( position, 1.0 ); -}`,zD=`uniform sampler2D shadow_pass; +}`,ZD=`uniform sampler2D shadow_pass; uniform vec2 resolution; uniform float radius; #include @@ -3805,12 +3805,12 @@ void main() { squared_mean = squared_mean / samples; float std_dev = sqrt( squared_mean - mean * mean ); gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); -}`;function HD(n,e,t){let i=new $o;const s=new ne,a=new ne,r=new Ye,o=new Ng({depthPacking:OS}),l=new Ug,c={},u=t.maxTextureSize,d={[bs]:dn,[dn]:bs,[ut]:ut},h=new ri({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new ne},radius:{value:4}},vertexShader:BD,fragmentShader:zD}),f=h.clone();f.defines.HORIZONTAL_PASS=1;const p=new $e;p.setAttribute("position",new ot(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const g=new Se(p,h),_=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=cg;let m=this.type;this.render=function(x,M,C){if(_.enabled===!1||_.autoUpdate===!1&&_.needsUpdate===!1||x.length===0)return;const w=n.getRenderTarget(),E=n.getActiveCubeFace(),R=n.getActiveMipmapLevel(),L=n.state;L.setBlending(Hs),L.buffers.depth.getReversed()===!0?L.buffers.color.setClear(0,0,0,0):L.buffers.color.setClear(1,1,1,1),L.buffers.depth.setTest(!0),L.setScissorTest(!1);const O=m!==hs&&this.type===hs,D=m===hs&&this.type!==hs;for(let U=0,F=x.length;Uu||s.y>u)&&(s.x>u&&(a.x=Math.floor(u/ie.x),s.x=a.x*ie.x,H.mapSize.x=a.x),s.y>u&&(a.y=Math.floor(u/ie.y),s.y=a.y*ie.y,H.mapSize.y=a.y)),H.map===null||O===!0||D===!0){const me=this.type!==hs?{minFilter:hn,magFilter:hn}:{};H.map!==null&&H.map.dispose(),H.map=new ws(s.x,s.y,me),H.map.texture.name=W.name+".shadowMap",H.camera.updateProjectionMatrix()}n.setRenderTarget(H.map),n.clear();const le=H.getViewportCount();for(let me=0;me0||M.map&&M.alphaTest>0||M.alphaToCoverage===!0){const L=E.uuid,O=M.uuid;let D=c[L];D===void 0&&(D={},c[L]=D);let U=D[O];U===void 0&&(U=E.clone(),D[O]=U,M.addEventListener("dispose",S)),E=U}if(E.visible=M.visible,E.wireframe=M.wireframe,w===hs?E.side=M.shadowSide!==null?M.shadowSide:M.side:E.side=M.shadowSide!==null?M.shadowSide:d[M.side],E.alphaMap=M.alphaMap,E.alphaTest=M.alphaToCoverage===!0?.5:M.alphaTest,E.map=M.map,E.clipShadows=M.clipShadows,E.clippingPlanes=M.clippingPlanes,E.clipIntersection=M.clipIntersection,E.displacementMap=M.displacementMap,E.displacementScale=M.displacementScale,E.displacementBias=M.displacementBias,E.wireframeLinewidth=M.wireframeLinewidth,E.linewidth=M.linewidth,C.isPointLight===!0&&E.isMeshDistanceMaterial===!0){const L=n.properties.get(E);L.light=C}return E}function b(x,M,C,w,E){if(x.visible===!1)return;if(x.layers.test(M.layers)&&(x.isMesh||x.isLine||x.isPoints)&&(x.castShadow||x.receiveShadow&&E===hs)&&(!x.frustumCulled||i.intersectsObject(x))){x.modelViewMatrix.multiplyMatrices(C.matrixWorldInverse,x.matrixWorld);const O=e.update(x),D=x.material;if(Array.isArray(D)){const U=O.groups;for(let F=0,W=U.length;F=1):H.indexOf("OpenGL ES")!==-1&&(W=parseFloat(/^OpenGL ES (\d)/.exec(H)[1]),F=W>=2);let ie=null,le={};const me=n.getParameter(n.SCISSOR_BOX),Le=n.getParameter(n.VIEWPORT),De=new Ye().fromArray(me),Ke=new Ye().fromArray(Le);function Oe(N,_e,xe,Ne){const fe=new Uint8Array(4),oe=n.createTexture();n.bindTexture(N,oe),n.texParameteri(N,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(N,n.TEXTURE_MAG_FILTER,n.NEAREST);for(let He=0;He"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new ne,u=new WeakMap;let d;const h=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function p(I,A){return f?new OffscreenCanvas(I,A):rc("canvas")}function g(I,A,V){let J=1;const ce=st(I);if((ce.width>V||ce.height>V)&&(J=V/Math.max(ce.width,ce.height)),J<1)if(typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&I instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&I instanceof ImageBitmap||typeof VideoFrame<"u"&&I instanceof VideoFrame){const ee=Math.floor(J*ce.width),Ve=Math.floor(J*ce.height);d===void 0&&(d=p(ee,Ve));const ve=A?p(ee,Ve):d;return ve.width=ee,ve.height=Ve,ve.getContext("2d").drawImage(I,0,0,ee,Ve),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+ce.width+"x"+ce.height+") to ("+ee+"x"+Ve+")."),ve}else return"data"in I&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+ce.width+"x"+ce.height+")."),I;return I}function _(I){return I.generateMipmaps}function m(I){n.generateMipmap(I)}function v(I){return I.isWebGLCubeRenderTarget?n.TEXTURE_CUBE_MAP:I.isWebGL3DRenderTarget?n.TEXTURE_3D:I.isWebGLArrayRenderTarget||I.isCompressedArrayTexture?n.TEXTURE_2D_ARRAY:n.TEXTURE_2D}function y(I,A,V,J,ce=!1){if(I!==null){if(n[I]!==void 0)return n[I];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+I+"'")}let ee=A;if(A===n.RED&&(V===n.FLOAT&&(ee=n.R32F),V===n.HALF_FLOAT&&(ee=n.R16F),V===n.UNSIGNED_BYTE&&(ee=n.R8)),A===n.RED_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.R8UI),V===n.UNSIGNED_SHORT&&(ee=n.R16UI),V===n.UNSIGNED_INT&&(ee=n.R32UI),V===n.BYTE&&(ee=n.R8I),V===n.SHORT&&(ee=n.R16I),V===n.INT&&(ee=n.R32I)),A===n.RG&&(V===n.FLOAT&&(ee=n.RG32F),V===n.HALF_FLOAT&&(ee=n.RG16F),V===n.UNSIGNED_BYTE&&(ee=n.RG8)),A===n.RG_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.RG8UI),V===n.UNSIGNED_SHORT&&(ee=n.RG16UI),V===n.UNSIGNED_INT&&(ee=n.RG32UI),V===n.BYTE&&(ee=n.RG8I),V===n.SHORT&&(ee=n.RG16I),V===n.INT&&(ee=n.RG32I)),A===n.RGB_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.RGB8UI),V===n.UNSIGNED_SHORT&&(ee=n.RGB16UI),V===n.UNSIGNED_INT&&(ee=n.RGB32UI),V===n.BYTE&&(ee=n.RGB8I),V===n.SHORT&&(ee=n.RGB16I),V===n.INT&&(ee=n.RGB32I)),A===n.RGBA_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.RGBA8UI),V===n.UNSIGNED_SHORT&&(ee=n.RGBA16UI),V===n.UNSIGNED_INT&&(ee=n.RGBA32UI),V===n.BYTE&&(ee=n.RGBA8I),V===n.SHORT&&(ee=n.RGBA16I),V===n.INT&&(ee=n.RGBA32I)),A===n.RGB&&(V===n.UNSIGNED_INT_5_9_9_9_REV&&(ee=n.RGB9_E5),V===n.UNSIGNED_INT_10F_11F_11F_REV&&(ee=n.R11F_G11F_B10F)),A===n.RGBA){const Ve=ce?sc:rt.getTransfer(J);V===n.FLOAT&&(ee=n.RGBA32F),V===n.HALF_FLOAT&&(ee=n.RGBA16F),V===n.UNSIGNED_BYTE&&(ee=Ve===It?n.SRGB8_ALPHA8:n.RGBA8),V===n.UNSIGNED_SHORT_4_4_4_4&&(ee=n.RGBA4),V===n.UNSIGNED_SHORT_5_5_5_1&&(ee=n.RGB5_A1)}return(ee===n.R16F||ee===n.R32F||ee===n.RG16F||ee===n.RG32F||ee===n.RGBA16F||ee===n.RGBA32F)&&e.get("EXT_color_buffer_float"),ee}function b(I,A){let V;return I?A===null||A===Ks||A===Po?V=n.DEPTH24_STENCIL8:A===Mn?V=n.DEPTH32F_STENCIL8:A===Ro&&(V=n.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):A===null||A===Ks||A===Po?V=n.DEPTH_COMPONENT24:A===Mn?V=n.DEPTH_COMPONENT32F:A===Ro&&(V=n.DEPTH_COMPONENT16),V}function S(I,A){return _(I)===!0||I.isFramebufferTexture&&I.minFilter!==hn&&I.minFilter!==Gt?Math.log2(Math.max(A.width,A.height))+1:I.mipmaps!==void 0&&I.mipmaps.length>0?I.mipmaps.length:I.isCompressedTexture&&Array.isArray(I.image)?A.mipmaps.length:1}function x(I){const A=I.target;A.removeEventListener("dispose",x),C(A),A.isVideoTexture&&u.delete(A)}function M(I){const A=I.target;A.removeEventListener("dispose",M),E(A)}function C(I){const A=i.get(I);if(A.__webglInit===void 0)return;const V=I.source,J=h.get(V);if(J){const ce=J[A.__cacheKey];ce.usedTimes--,ce.usedTimes===0&&w(I),Object.keys(J).length===0&&h.delete(V)}i.remove(I)}function w(I){const A=i.get(I);n.deleteTexture(A.__webglTexture);const V=I.source,J=h.get(V);delete J[A.__cacheKey],r.memory.textures--}function E(I){const A=i.get(I);if(I.depthTexture&&(I.depthTexture.dispose(),i.remove(I.depthTexture)),I.isWebGLCubeRenderTarget)for(let J=0;J<6;J++){if(Array.isArray(A.__webglFramebuffer[J]))for(let ce=0;ce=s.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+I+" texture units while this GPU supports only "+s.maxTextures),R+=1,I}function D(I){const A=[];return A.push(I.wrapS),A.push(I.wrapT),A.push(I.wrapR||0),A.push(I.magFilter),A.push(I.minFilter),A.push(I.anisotropy),A.push(I.internalFormat),A.push(I.format),A.push(I.type),A.push(I.generateMipmaps),A.push(I.premultiplyAlpha),A.push(I.flipY),A.push(I.unpackAlignment),A.push(I.colorSpace),A.join()}function U(I,A){const V=i.get(I);if(I.isVideoTexture&&ye(I),I.isRenderTargetTexture===!1&&I.isExternalTexture!==!0&&I.version>0&&V.__version!==I.version){const J=I.image;if(J===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(J.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{Z(V,I,A);return}}else I.isExternalTexture&&(V.__webglTexture=I.sourceTexture?I.sourceTexture:null);t.bindTexture(n.TEXTURE_2D,V.__webglTexture,n.TEXTURE0+A)}function F(I,A){const V=i.get(I);if(I.isRenderTargetTexture===!1&&I.version>0&&V.__version!==I.version){Z(V,I,A);return}t.bindTexture(n.TEXTURE_2D_ARRAY,V.__webglTexture,n.TEXTURE0+A)}function W(I,A){const V=i.get(I);if(I.isRenderTargetTexture===!1&&I.version>0&&V.__version!==I.version){Z(V,I,A);return}t.bindTexture(n.TEXTURE_3D,V.__webglTexture,n.TEXTURE0+A)}function H(I,A){const V=i.get(I);if(I.version>0&&V.__version!==I.version){ae(V,I,A);return}t.bindTexture(n.TEXTURE_CUBE_MAP,V.__webglTexture,n.TEXTURE0+A)}const ie={[xs]:n.REPEAT,[Wn]:n.CLAMP_TO_EDGE,[Ao]:n.MIRRORED_REPEAT},le={[hn]:n.NEAREST,[Vh]:n.NEAREST_MIPMAP_NEAREST,[er]:n.NEAREST_MIPMAP_LINEAR,[Gt]:n.LINEAR,[ho]:n.LINEAR_MIPMAP_NEAREST,[Ii]:n.LINEAR_MIPMAP_LINEAR},me={[NS]:n.NEVER,[GS]:n.ALWAYS,[US]:n.LESS,[wg]:n.LEQUAL,[BS]:n.EQUAL,[VS]:n.GEQUAL,[zS]:n.GREATER,[HS]:n.NOTEQUAL};function Le(I,A){if(A.type===Mn&&e.has("OES_texture_float_linear")===!1&&(A.magFilter===Gt||A.magFilter===ho||A.magFilter===er||A.magFilter===Ii||A.minFilter===Gt||A.minFilter===ho||A.minFilter===er||A.minFilter===Ii)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),n.texParameteri(I,n.TEXTURE_WRAP_S,ie[A.wrapS]),n.texParameteri(I,n.TEXTURE_WRAP_T,ie[A.wrapT]),(I===n.TEXTURE_3D||I===n.TEXTURE_2D_ARRAY)&&n.texParameteri(I,n.TEXTURE_WRAP_R,ie[A.wrapR]),n.texParameteri(I,n.TEXTURE_MAG_FILTER,le[A.magFilter]),n.texParameteri(I,n.TEXTURE_MIN_FILTER,le[A.minFilter]),A.compareFunction&&(n.texParameteri(I,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(I,n.TEXTURE_COMPARE_FUNC,me[A.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(A.magFilter===hn||A.minFilter!==er&&A.minFilter!==Ii||A.type===Mn&&e.has("OES_texture_float_linear")===!1)return;if(A.anisotropy>1||i.get(A).__currentAnisotropy){const V=e.get("EXT_texture_filter_anisotropic");n.texParameterf(I,V.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(A.anisotropy,s.getMaxAnisotropy())),i.get(A).__currentAnisotropy=A.anisotropy}}}function De(I,A){let V=!1;I.__webglInit===void 0&&(I.__webglInit=!0,A.addEventListener("dispose",x));const J=A.source;let ce=h.get(J);ce===void 0&&(ce={},h.set(J,ce));const ee=D(A);if(ee!==I.__cacheKey){ce[ee]===void 0&&(ce[ee]={texture:n.createTexture(),usedTimes:0},r.memory.textures++,V=!0),ce[ee].usedTimes++;const Ve=ce[I.__cacheKey];Ve!==void 0&&(ce[I.__cacheKey].usedTimes--,Ve.usedTimes===0&&w(A)),I.__cacheKey=ee,I.__webglTexture=ce[ee].texture}return V}function Ke(I,A,V){return Math.floor(Math.floor(I/V)/A)}function Oe(I,A,V,J){const ee=I.updateRanges;if(ee.length===0)t.texSubImage2D(n.TEXTURE_2D,0,0,0,A.width,A.height,V,J,A.data);else{ee.sort((he,Ie)=>he.start-Ie.start);let Ve=0;for(let he=1;he0){N&&_e&&t.texStorage2D(n.TEXTURE_2D,Ne,Ge,ft[0].width,ft[0].height);for(let fe=0,oe=ft.length;fe0){const He=t_(Ae.width,Ae.height,A.format,A.type);for(const ct of A.layerUpdates){const Ot=Ae.data.subarray(ct*He/Ae.data.BYTES_PER_ELEMENT,(ct+1)*He/Ae.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,fe,0,0,ct,Ae.width,Ae.height,1,Ie,Ot)}A.clearLayerUpdates()}else t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,fe,0,0,0,Ae.width,Ae.height,he.depth,Ie,Ae.data)}else t.compressedTexImage3D(n.TEXTURE_2D_ARRAY,fe,Ge,Ae.width,Ae.height,he.depth,0,Ae.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else N?xe&&t.texSubImage3D(n.TEXTURE_2D_ARRAY,fe,0,0,0,Ae.width,Ae.height,he.depth,Ie,Qe,Ae.data):t.texImage3D(n.TEXTURE_2D_ARRAY,fe,Ge,Ae.width,Ae.height,he.depth,0,Ie,Qe,Ae.data)}else{N&&_e&&t.texStorage2D(n.TEXTURE_2D,Ne,Ge,ft[0].width,ft[0].height);for(let fe=0,oe=ft.length;fe0){const fe=t_(he.width,he.height,A.format,A.type);for(const oe of A.layerUpdates){const He=he.data.subarray(oe*fe/he.data.BYTES_PER_ELEMENT,(oe+1)*fe/he.data.BYTES_PER_ELEMENT);t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,oe,he.width,he.height,1,Ie,Qe,He)}A.clearLayerUpdates()}else t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,he.width,he.height,he.depth,Ie,Qe,he.data)}else t.texImage3D(n.TEXTURE_2D_ARRAY,0,Ge,he.width,he.height,he.depth,0,Ie,Qe,he.data);else if(A.isData3DTexture)N?(_e&&t.texStorage3D(n.TEXTURE_3D,Ne,Ge,he.width,he.height,he.depth),xe&&t.texSubImage3D(n.TEXTURE_3D,0,0,0,0,he.width,he.height,he.depth,Ie,Qe,he.data)):t.texImage3D(n.TEXTURE_3D,0,Ge,he.width,he.height,he.depth,0,Ie,Qe,he.data);else if(A.isFramebufferTexture){if(_e)if(N)t.texStorage2D(n.TEXTURE_2D,Ne,Ge,he.width,he.height);else{let fe=he.width,oe=he.height;for(let He=0;He>=1,oe>>=1}}else if(ft.length>0){if(N&&_e){const fe=st(ft[0]);t.texStorage2D(n.TEXTURE_2D,Ne,Ge,fe.width,fe.height)}for(let fe=0,oe=ft.length;fe0&&Ne++;const oe=st(Ie[0]);t.texStorage2D(n.TEXTURE_CUBE_MAP,Ne,ft,oe.width,oe.height)}for(let oe=0;oe<6;oe++)if(he){N?xe&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+oe,0,0,0,Ie[oe].width,Ie[oe].height,Ge,Ae,Ie[oe].data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+oe,0,ft,Ie[oe].width,Ie[oe].height,0,Ge,Ae,Ie[oe].data);for(let He=0;He>ee),Qe=Math.max(1,A.height>>ee);ce===n.TEXTURE_3D||ce===n.TEXTURE_2D_ARRAY?t.texImage3D(ce,ee,Be,Ie,Qe,A.depth,0,Ve,ve,null):t.texImage2D(ce,ee,Be,Ie,Qe,0,Ve,ve,null)}t.bindFramebuffer(n.FRAMEBUFFER,I),ue(A)?o.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,J,ce,he.__webglTexture,0,ge(A)):(ce===n.TEXTURE_2D||ce>=n.TEXTURE_CUBE_MAP_POSITIVE_X&&ce<=n.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&n.framebufferTexture2D(n.FRAMEBUFFER,J,ce,he.__webglTexture,ee),t.bindFramebuffer(n.FRAMEBUFFER,null)}function X(I,A,V){if(n.bindRenderbuffer(n.RENDERBUFFER,I),A.depthBuffer){const J=A.depthTexture,ce=J&&J.isDepthTexture?J.type:null,ee=b(A.stencilBuffer,ce),Ve=A.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ve=ge(A);ue(A)?o.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,ve,ee,A.width,A.height):V?n.renderbufferStorageMultisample(n.RENDERBUFFER,ve,ee,A.width,A.height):n.renderbufferStorage(n.RENDERBUFFER,ee,A.width,A.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,Ve,n.RENDERBUFFER,I)}else{const J=A.textures;for(let ce=0;ce{delete A.__boundDepthTexture,delete A.__depthDisposeCallback,J.removeEventListener("dispose",ce)};J.addEventListener("dispose",ce),A.__depthDisposeCallback=ce}A.__boundDepthTexture=J}if(I.depthTexture&&!A.__autoAllocateDepthBuffer){if(V)throw new Error("target.depthTexture not supported in Cube render targets");const J=I.texture.mipmaps;J&&J.length>0?se(A.__webglFramebuffer[0],I):se(A.__webglFramebuffer,I)}else if(V){A.__webglDepthbuffer=[];for(let J=0;J<6;J++)if(t.bindFramebuffer(n.FRAMEBUFFER,A.__webglFramebuffer[J]),A.__webglDepthbuffer[J]===void 0)A.__webglDepthbuffer[J]=n.createRenderbuffer(),X(A.__webglDepthbuffer[J],I,!1);else{const ce=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ee=A.__webglDepthbuffer[J];n.bindRenderbuffer(n.RENDERBUFFER,ee),n.framebufferRenderbuffer(n.FRAMEBUFFER,ce,n.RENDERBUFFER,ee)}}else{const J=I.texture.mipmaps;if(J&&J.length>0?t.bindFramebuffer(n.FRAMEBUFFER,A.__webglFramebuffer[0]):t.bindFramebuffer(n.FRAMEBUFFER,A.__webglFramebuffer),A.__webglDepthbuffer===void 0)A.__webglDepthbuffer=n.createRenderbuffer(),X(A.__webglDepthbuffer,I,!1);else{const ce=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ee=A.__webglDepthbuffer;n.bindRenderbuffer(n.RENDERBUFFER,ee),n.framebufferRenderbuffer(n.FRAMEBUFFER,ce,n.RENDERBUFFER,ee)}}t.bindFramebuffer(n.FRAMEBUFFER,null)}function Re(I,A,V){const J=i.get(I);A!==void 0&&Te(J.__webglFramebuffer,I,I.texture,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,0),V!==void 0&&we(I)}function k(I){const A=I.texture,V=i.get(I),J=i.get(A);I.addEventListener("dispose",M);const ce=I.textures,ee=I.isWebGLCubeRenderTarget===!0,Ve=ce.length>1;if(Ve||(J.__webglTexture===void 0&&(J.__webglTexture=n.createTexture()),J.__version=A.version,r.memory.textures++),ee){V.__webglFramebuffer=[];for(let ve=0;ve<6;ve++)if(A.mipmaps&&A.mipmaps.length>0){V.__webglFramebuffer[ve]=[];for(let Be=0;Be0){V.__webglFramebuffer=[];for(let ve=0;ve0&&ue(I)===!1){V.__webglMultisampledFramebuffer=n.createFramebuffer(),V.__webglColorRenderbuffer=[],t.bindFramebuffer(n.FRAMEBUFFER,V.__webglMultisampledFramebuffer);for(let ve=0;ve0)for(let Be=0;Be0)for(let Be=0;Be0){if(ue(I)===!1){const A=I.textures,V=I.width,J=I.height;let ce=n.COLOR_BUFFER_BIT;const ee=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,Ve=i.get(I),ve=A.length>1;if(ve)for(let ze=0;ze0?t.bindFramebuffer(n.DRAW_FRAMEBUFFER,Ve.__webglFramebuffer[0]):t.bindFramebuffer(n.DRAW_FRAMEBUFFER,Ve.__webglFramebuffer);for(let ze=0;ze0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&A.__useRenderToTexture!==!1}function ye(I){const A=r.render.frame;u.get(I)!==A&&(u.set(I,A),I.update())}function We(I,A){const V=I.colorSpace,J=I.format,ce=I.type;return I.isCompressedTexture===!0||I.isVideoTexture===!0||V!==wn&&V!==Bs&&(rt.getTransfer(V)===It?(J!==Xn||ce!==ns)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",V)),A}function st(I){return typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement?(c.width=I.naturalWidth||I.width,c.height=I.naturalHeight||I.height):typeof VideoFrame<"u"&&I instanceof VideoFrame?(c.width=I.displayWidth,c.height=I.displayHeight):(c.width=I.width,c.height=I.height),c}this.allocateTextureUnit=O,this.resetTextureUnits=L,this.setTexture2D=U,this.setTexture2DArray=F,this.setTexture3D=W,this.setTextureCube=H,this.rebindTextures=Re,this.setupRenderTarget=k,this.updateRenderTargetMipmap=G,this.updateMultisampleRenderTarget=Q,this.setupDepthRenderbuffer=we,this.setupFrameBufferTexture=Te,this.useMultisampledRTT=ue}function VT(n,e){function t(i,s=Bs){let a;const r=rt.getTransfer(s);if(i===ns)return n.UNSIGNED_BYTE;if(i===$h)return n.UNSIGNED_SHORT_4_4_4_4;if(i===Wh)return n.UNSIGNED_SHORT_5_5_5_1;if(i===mg)return n.UNSIGNED_INT_5_9_9_9_REV;if(i===_g)return n.UNSIGNED_INT_10F_11F_11F_REV;if(i===fg)return n.BYTE;if(i===pg)return n.SHORT;if(i===Ro)return n.UNSIGNED_SHORT;if(i===Gh)return n.INT;if(i===Ks)return n.UNSIGNED_INT;if(i===Mn)return n.FLOAT;if(i===ms)return n.HALF_FLOAT;if(i===gg)return n.ALPHA;if(i===yg)return n.RGB;if(i===Xn)return n.RGBA;if(i===Io)return n.DEPTH_COMPONENT;if(i===Lo)return n.DEPTH_STENCIL;if(i===Xh)return n.RED;if(i===wc)return n.RED_INTEGER;if(i===vg)return n.RG;if(i===Kh)return n.RG_INTEGER;if(i===qh)return n.RGBA_INTEGER;if(i===Hl||i===Vl||i===Gl||i===$l)if(r===It)if(a=e.get("WEBGL_compressed_texture_s3tc_srgb"),a!==null){if(i===Hl)return a.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===Vl)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===Gl)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===$l)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(a=e.get("WEBGL_compressed_texture_s3tc"),a!==null){if(i===Hl)return a.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===Vl)return a.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===Gl)return a.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===$l)return a.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===zd||i===Hd||i===Vd||i===Gd)if(a=e.get("WEBGL_compressed_texture_pvrtc"),a!==null){if(i===zd)return a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===Hd)return a.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===Vd)return a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===Gd)return a.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===$d||i===Wd||i===Xd)if(a=e.get("WEBGL_compressed_texture_etc"),a!==null){if(i===$d||i===Wd)return r===It?a.COMPRESSED_SRGB8_ETC2:a.COMPRESSED_RGB8_ETC2;if(i===Xd)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:a.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(i===Kd||i===qd||i===Yd||i===jd||i===Zd||i===Jd||i===Qd||i===eh||i===th||i===nh||i===ih||i===sh||i===ah||i===rh)if(a=e.get("WEBGL_compressed_texture_astc"),a!==null){if(i===Kd)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:a.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===qd)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:a.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===Yd)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:a.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===jd)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:a.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===Zd)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:a.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===Jd)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:a.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===Qd)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:a.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===eh)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:a.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===th)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:a.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===nh)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:a.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===ih)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:a.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===sh)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:a.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===ah)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:a.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===rh)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:a.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===oh||i===lh||i===ch)if(a=e.get("EXT_texture_compression_bptc"),a!==null){if(i===oh)return r===It?a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:a.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===lh)return a.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===ch)return a.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===uh||i===dh||i===hh||i===fh)if(a=e.get("EXT_texture_compression_rgtc"),a!==null){if(i===uh)return a.COMPRESSED_RED_RGTC1_EXT;if(i===dh)return a.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===hh)return a.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===fh)return a.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===Po?n.UNSIGNED_INT_24_8:n[i]!==void 0?n[i]:null}return{convert:t}}const WD=` +}`;function JD(n,e,t){let i=new Ko;const s=new ne,a=new ne,r=new Ye,o=new $g({depthPacking:$S}),l=new Wg,c={},u=t.maxTextureSize,d={[bs]:dn,[dn]:bs,[ut]:ut},h=new ri({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new ne},radius:{value:4}},vertexShader:jD,fragmentShader:ZD}),f=h.clone();f.defines.HORIZONTAL_PASS=1;const p=new $e;p.setAttribute("position",new lt(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const g=new Se(p,h),_=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=_g;let m=this.type;this.render=function(x,M,C){if(_.enabled===!1||_.autoUpdate===!1&&_.needsUpdate===!1||x.length===0)return;const w=n.getRenderTarget(),E=n.getActiveCubeFace(),R=n.getActiveMipmapLevel(),L=n.state;L.setBlending(Hs),L.buffers.depth.getReversed()===!0?L.buffers.color.setClear(0,0,0,0):L.buffers.color.setClear(1,1,1,1),L.buffers.depth.setTest(!0),L.setScissorTest(!1);const O=m!==hs&&this.type===hs,D=m===hs&&this.type!==hs;for(let U=0,F=x.length;Uu||s.y>u)&&(s.x>u&&(a.x=Math.floor(u/ie.x),s.x=a.x*ie.x,H.mapSize.x=a.x),s.y>u&&(a.y=Math.floor(u/ie.y),s.y=a.y*ie.y,H.mapSize.y=a.y)),H.map===null||O===!0||D===!0){const me=this.type!==hs?{minFilter:hn,magFilter:hn}:{};H.map!==null&&H.map.dispose(),H.map=new ws(s.x,s.y,me),H.map.texture.name=W.name+".shadowMap",H.camera.updateProjectionMatrix()}n.setRenderTarget(H.map),n.clear();const le=H.getViewportCount();for(let me=0;me0||M.map&&M.alphaTest>0||M.alphaToCoverage===!0){const L=E.uuid,O=M.uuid;let D=c[L];D===void 0&&(D={},c[L]=D);let U=D[O];U===void 0&&(U=E.clone(),D[O]=U,M.addEventListener("dispose",S)),E=U}if(E.visible=M.visible,E.wireframe=M.wireframe,w===hs?E.side=M.shadowSide!==null?M.shadowSide:M.side:E.side=M.shadowSide!==null?M.shadowSide:d[M.side],E.alphaMap=M.alphaMap,E.alphaTest=M.alphaToCoverage===!0?.5:M.alphaTest,E.map=M.map,E.clipShadows=M.clipShadows,E.clippingPlanes=M.clippingPlanes,E.clipIntersection=M.clipIntersection,E.displacementMap=M.displacementMap,E.displacementScale=M.displacementScale,E.displacementBias=M.displacementBias,E.wireframeLinewidth=M.wireframeLinewidth,E.linewidth=M.linewidth,C.isPointLight===!0&&E.isMeshDistanceMaterial===!0){const L=n.properties.get(E);L.light=C}return E}function b(x,M,C,w,E){if(x.visible===!1)return;if(x.layers.test(M.layers)&&(x.isMesh||x.isLine||x.isPoints)&&(x.castShadow||x.receiveShadow&&E===hs)&&(!x.frustumCulled||i.intersectsObject(x))){x.modelViewMatrix.multiplyMatrices(C.matrixWorldInverse,x.matrixWorld);const O=e.update(x),D=x.material;if(Array.isArray(D)){const U=O.groups;for(let F=0,W=U.length;F=1):H.indexOf("OpenGL ES")!==-1&&(W=parseFloat(/^OpenGL ES (\d)/.exec(H)[1]),F=W>=2);let ie=null,le={};const me=n.getParameter(n.SCISSOR_BOX),Le=n.getParameter(n.VIEWPORT),De=new Ye().fromArray(me),Ke=new Ye().fromArray(Le);function Oe(N,_e,xe,Ne){const fe=new Uint8Array(4),oe=n.createTexture();n.bindTexture(N,oe),n.texParameteri(N,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(N,n.TEXTURE_MAG_FILTER,n.NEAREST);for(let He=0;He"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new ne,u=new WeakMap;let d;const h=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function p(I,A){return f?new OffscreenCanvas(I,A):uc("canvas")}function g(I,A,V){let J=1;const ce=st(I);if((ce.width>V||ce.height>V)&&(J=V/Math.max(ce.width,ce.height)),J<1)if(typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&I instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&I instanceof ImageBitmap||typeof VideoFrame<"u"&&I instanceof VideoFrame){const ee=Math.floor(J*ce.width),Ve=Math.floor(J*ce.height);d===void 0&&(d=p(ee,Ve));const ve=A?p(ee,Ve):d;return ve.width=ee,ve.height=Ve,ve.getContext("2d").drawImage(I,0,0,ee,Ve),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+ce.width+"x"+ce.height+") to ("+ee+"x"+Ve+")."),ve}else return"data"in I&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+ce.width+"x"+ce.height+")."),I;return I}function _(I){return I.generateMipmaps}function m(I){n.generateMipmap(I)}function v(I){return I.isWebGLCubeRenderTarget?n.TEXTURE_CUBE_MAP:I.isWebGL3DRenderTarget?n.TEXTURE_3D:I.isWebGLArrayRenderTarget||I.isCompressedArrayTexture?n.TEXTURE_2D_ARRAY:n.TEXTURE_2D}function y(I,A,V,J,ce=!1){if(I!==null){if(n[I]!==void 0)return n[I];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+I+"'")}let ee=A;if(A===n.RED&&(V===n.FLOAT&&(ee=n.R32F),V===n.HALF_FLOAT&&(ee=n.R16F),V===n.UNSIGNED_BYTE&&(ee=n.R8)),A===n.RED_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.R8UI),V===n.UNSIGNED_SHORT&&(ee=n.R16UI),V===n.UNSIGNED_INT&&(ee=n.R32UI),V===n.BYTE&&(ee=n.R8I),V===n.SHORT&&(ee=n.R16I),V===n.INT&&(ee=n.R32I)),A===n.RG&&(V===n.FLOAT&&(ee=n.RG32F),V===n.HALF_FLOAT&&(ee=n.RG16F),V===n.UNSIGNED_BYTE&&(ee=n.RG8)),A===n.RG_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.RG8UI),V===n.UNSIGNED_SHORT&&(ee=n.RG16UI),V===n.UNSIGNED_INT&&(ee=n.RG32UI),V===n.BYTE&&(ee=n.RG8I),V===n.SHORT&&(ee=n.RG16I),V===n.INT&&(ee=n.RG32I)),A===n.RGB_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.RGB8UI),V===n.UNSIGNED_SHORT&&(ee=n.RGB16UI),V===n.UNSIGNED_INT&&(ee=n.RGB32UI),V===n.BYTE&&(ee=n.RGB8I),V===n.SHORT&&(ee=n.RGB16I),V===n.INT&&(ee=n.RGB32I)),A===n.RGBA_INTEGER&&(V===n.UNSIGNED_BYTE&&(ee=n.RGBA8UI),V===n.UNSIGNED_SHORT&&(ee=n.RGBA16UI),V===n.UNSIGNED_INT&&(ee=n.RGBA32UI),V===n.BYTE&&(ee=n.RGBA8I),V===n.SHORT&&(ee=n.RGBA16I),V===n.INT&&(ee=n.RGBA32I)),A===n.RGB&&(V===n.UNSIGNED_INT_5_9_9_9_REV&&(ee=n.RGB9_E5),V===n.UNSIGNED_INT_10F_11F_11F_REV&&(ee=n.R11F_G11F_B10F)),A===n.RGBA){const Ve=ce?lc:ot.getTransfer(J);V===n.FLOAT&&(ee=n.RGBA32F),V===n.HALF_FLOAT&&(ee=n.RGBA16F),V===n.UNSIGNED_BYTE&&(ee=Ve===It?n.SRGB8_ALPHA8:n.RGBA8),V===n.UNSIGNED_SHORT_4_4_4_4&&(ee=n.RGBA4),V===n.UNSIGNED_SHORT_5_5_5_1&&(ee=n.RGB5_A1)}return(ee===n.R16F||ee===n.R32F||ee===n.RG16F||ee===n.RG32F||ee===n.RGBA16F||ee===n.RGBA32F)&&e.get("EXT_color_buffer_float"),ee}function b(I,A){let V;return I?A===null||A===Ks||A===ko?V=n.DEPTH24_STENCIL8:A===Mn?V=n.DEPTH32F_STENCIL8:A===Lo&&(V=n.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):A===null||A===Ks||A===ko?V=n.DEPTH_COMPONENT24:A===Mn?V=n.DEPTH_COMPONENT32F:A===Lo&&(V=n.DEPTH_COMPONENT16),V}function S(I,A){return _(I)===!0||I.isFramebufferTexture&&I.minFilter!==hn&&I.minFilter!==Gt?Math.log2(Math.max(A.width,A.height))+1:I.mipmaps!==void 0&&I.mipmaps.length>0?I.mipmaps.length:I.isCompressedTexture&&Array.isArray(I.image)?A.mipmaps.length:1}function x(I){const A=I.target;A.removeEventListener("dispose",x),C(A),A.isVideoTexture&&u.delete(A)}function M(I){const A=I.target;A.removeEventListener("dispose",M),E(A)}function C(I){const A=i.get(I);if(A.__webglInit===void 0)return;const V=I.source,J=h.get(V);if(J){const ce=J[A.__cacheKey];ce.usedTimes--,ce.usedTimes===0&&w(I),Object.keys(J).length===0&&h.delete(V)}i.remove(I)}function w(I){const A=i.get(I);n.deleteTexture(A.__webglTexture);const V=I.source,J=h.get(V);delete J[A.__cacheKey],r.memory.textures--}function E(I){const A=i.get(I);if(I.depthTexture&&(I.depthTexture.dispose(),i.remove(I.depthTexture)),I.isWebGLCubeRenderTarget)for(let J=0;J<6;J++){if(Array.isArray(A.__webglFramebuffer[J]))for(let ce=0;ce=s.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+I+" texture units while this GPU supports only "+s.maxTextures),R+=1,I}function D(I){const A=[];return A.push(I.wrapS),A.push(I.wrapT),A.push(I.wrapR||0),A.push(I.magFilter),A.push(I.minFilter),A.push(I.anisotropy),A.push(I.internalFormat),A.push(I.format),A.push(I.type),A.push(I.generateMipmaps),A.push(I.premultiplyAlpha),A.push(I.flipY),A.push(I.unpackAlignment),A.push(I.colorSpace),A.join()}function U(I,A){const V=i.get(I);if(I.isVideoTexture&&ye(I),I.isRenderTargetTexture===!1&&I.isExternalTexture!==!0&&I.version>0&&V.__version!==I.version){const J=I.image;if(J===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(J.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{Z(V,I,A);return}}else I.isExternalTexture&&(V.__webglTexture=I.sourceTexture?I.sourceTexture:null);t.bindTexture(n.TEXTURE_2D,V.__webglTexture,n.TEXTURE0+A)}function F(I,A){const V=i.get(I);if(I.isRenderTargetTexture===!1&&I.version>0&&V.__version!==I.version){Z(V,I,A);return}t.bindTexture(n.TEXTURE_2D_ARRAY,V.__webglTexture,n.TEXTURE0+A)}function W(I,A){const V=i.get(I);if(I.isRenderTargetTexture===!1&&I.version>0&&V.__version!==I.version){Z(V,I,A);return}t.bindTexture(n.TEXTURE_3D,V.__webglTexture,n.TEXTURE0+A)}function H(I,A){const V=i.get(I);if(I.version>0&&V.__version!==I.version){re(V,I,A);return}t.bindTexture(n.TEXTURE_CUBE_MAP,V.__webglTexture,n.TEXTURE0+A)}const ie={[xs]:n.REPEAT,[Wn]:n.CLAMP_TO_EDGE,[Io]:n.MIRRORED_REPEAT},le={[hn]:n.NEAREST,[qh]:n.NEAREST_MIPMAP_NEAREST,[tr]:n.NEAREST_MIPMAP_LINEAR,[Gt]:n.LINEAR,[po]:n.LINEAR_MIPMAP_NEAREST,[Li]:n.LINEAR_MIPMAP_LINEAR},me={[XS]:n.NEVER,[JS]:n.ALWAYS,[KS]:n.LESS,[Rg]:n.LEQUAL,[qS]:n.EQUAL,[ZS]:n.GEQUAL,[YS]:n.GREATER,[jS]:n.NOTEQUAL};function Le(I,A){if(A.type===Mn&&e.has("OES_texture_float_linear")===!1&&(A.magFilter===Gt||A.magFilter===po||A.magFilter===tr||A.magFilter===Li||A.minFilter===Gt||A.minFilter===po||A.minFilter===tr||A.minFilter===Li)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),n.texParameteri(I,n.TEXTURE_WRAP_S,ie[A.wrapS]),n.texParameteri(I,n.TEXTURE_WRAP_T,ie[A.wrapT]),(I===n.TEXTURE_3D||I===n.TEXTURE_2D_ARRAY)&&n.texParameteri(I,n.TEXTURE_WRAP_R,ie[A.wrapR]),n.texParameteri(I,n.TEXTURE_MAG_FILTER,le[A.magFilter]),n.texParameteri(I,n.TEXTURE_MIN_FILTER,le[A.minFilter]),A.compareFunction&&(n.texParameteri(I,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(I,n.TEXTURE_COMPARE_FUNC,me[A.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(A.magFilter===hn||A.minFilter!==tr&&A.minFilter!==Li||A.type===Mn&&e.has("OES_texture_float_linear")===!1)return;if(A.anisotropy>1||i.get(A).__currentAnisotropy){const V=e.get("EXT_texture_filter_anisotropic");n.texParameterf(I,V.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(A.anisotropy,s.getMaxAnisotropy())),i.get(A).__currentAnisotropy=A.anisotropy}}}function De(I,A){let V=!1;I.__webglInit===void 0&&(I.__webglInit=!0,A.addEventListener("dispose",x));const J=A.source;let ce=h.get(J);ce===void 0&&(ce={},h.set(J,ce));const ee=D(A);if(ee!==I.__cacheKey){ce[ee]===void 0&&(ce[ee]={texture:n.createTexture(),usedTimes:0},r.memory.textures++,V=!0),ce[ee].usedTimes++;const Ve=ce[I.__cacheKey];Ve!==void 0&&(ce[I.__cacheKey].usedTimes--,Ve.usedTimes===0&&w(A)),I.__cacheKey=ee,I.__webglTexture=ce[ee].texture}return V}function Ke(I,A,V){return Math.floor(Math.floor(I/V)/A)}function Oe(I,A,V,J){const ee=I.updateRanges;if(ee.length===0)t.texSubImage2D(n.TEXTURE_2D,0,0,0,A.width,A.height,V,J,A.data);else{ee.sort((he,Ie)=>he.start-Ie.start);let Ve=0;for(let he=1;he0){N&&_e&&t.texStorage2D(n.TEXTURE_2D,Ne,Ge,ft[0].width,ft[0].height);for(let fe=0,oe=ft.length;fe0){const He=l_(Ae.width,Ae.height,A.format,A.type);for(const ct of A.layerUpdates){const Ot=Ae.data.subarray(ct*He/Ae.data.BYTES_PER_ELEMENT,(ct+1)*He/Ae.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,fe,0,0,ct,Ae.width,Ae.height,1,Ie,Ot)}A.clearLayerUpdates()}else t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,fe,0,0,0,Ae.width,Ae.height,he.depth,Ie,Ae.data)}else t.compressedTexImage3D(n.TEXTURE_2D_ARRAY,fe,Ge,Ae.width,Ae.height,he.depth,0,Ae.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else N?xe&&t.texSubImage3D(n.TEXTURE_2D_ARRAY,fe,0,0,0,Ae.width,Ae.height,he.depth,Ie,Qe,Ae.data):t.texImage3D(n.TEXTURE_2D_ARRAY,fe,Ge,Ae.width,Ae.height,he.depth,0,Ie,Qe,Ae.data)}else{N&&_e&&t.texStorage2D(n.TEXTURE_2D,Ne,Ge,ft[0].width,ft[0].height);for(let fe=0,oe=ft.length;fe0){const fe=l_(he.width,he.height,A.format,A.type);for(const oe of A.layerUpdates){const He=he.data.subarray(oe*fe/he.data.BYTES_PER_ELEMENT,(oe+1)*fe/he.data.BYTES_PER_ELEMENT);t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,oe,he.width,he.height,1,Ie,Qe,He)}A.clearLayerUpdates()}else t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,he.width,he.height,he.depth,Ie,Qe,he.data)}else t.texImage3D(n.TEXTURE_2D_ARRAY,0,Ge,he.width,he.height,he.depth,0,Ie,Qe,he.data);else if(A.isData3DTexture)N?(_e&&t.texStorage3D(n.TEXTURE_3D,Ne,Ge,he.width,he.height,he.depth),xe&&t.texSubImage3D(n.TEXTURE_3D,0,0,0,0,he.width,he.height,he.depth,Ie,Qe,he.data)):t.texImage3D(n.TEXTURE_3D,0,Ge,he.width,he.height,he.depth,0,Ie,Qe,he.data);else if(A.isFramebufferTexture){if(_e)if(N)t.texStorage2D(n.TEXTURE_2D,Ne,Ge,he.width,he.height);else{let fe=he.width,oe=he.height;for(let He=0;He>=1,oe>>=1}}else if(ft.length>0){if(N&&_e){const fe=st(ft[0]);t.texStorage2D(n.TEXTURE_2D,Ne,Ge,fe.width,fe.height)}for(let fe=0,oe=ft.length;fe0&&Ne++;const oe=st(Ie[0]);t.texStorage2D(n.TEXTURE_CUBE_MAP,Ne,ft,oe.width,oe.height)}for(let oe=0;oe<6;oe++)if(he){N?xe&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+oe,0,0,0,Ie[oe].width,Ie[oe].height,Ge,Ae,Ie[oe].data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+oe,0,ft,Ie[oe].width,Ie[oe].height,0,Ge,Ae,Ie[oe].data);for(let He=0;He>ee),Qe=Math.max(1,A.height>>ee);ce===n.TEXTURE_3D||ce===n.TEXTURE_2D_ARRAY?t.texImage3D(ce,ee,Be,Ie,Qe,A.depth,0,Ve,ve,null):t.texImage2D(ce,ee,Be,Ie,Qe,0,Ve,ve,null)}t.bindFramebuffer(n.FRAMEBUFFER,I),ue(A)?o.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,J,ce,he.__webglTexture,0,ge(A)):(ce===n.TEXTURE_2D||ce>=n.TEXTURE_CUBE_MAP_POSITIVE_X&&ce<=n.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&n.framebufferTexture2D(n.FRAMEBUFFER,J,ce,he.__webglTexture,ee),t.bindFramebuffer(n.FRAMEBUFFER,null)}function X(I,A,V){if(n.bindRenderbuffer(n.RENDERBUFFER,I),A.depthBuffer){const J=A.depthTexture,ce=J&&J.isDepthTexture?J.type:null,ee=b(A.stencilBuffer,ce),Ve=A.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ve=ge(A);ue(A)?o.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,ve,ee,A.width,A.height):V?n.renderbufferStorageMultisample(n.RENDERBUFFER,ve,ee,A.width,A.height):n.renderbufferStorage(n.RENDERBUFFER,ee,A.width,A.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,Ve,n.RENDERBUFFER,I)}else{const J=A.textures;for(let ce=0;ce{delete A.__boundDepthTexture,delete A.__depthDisposeCallback,J.removeEventListener("dispose",ce)};J.addEventListener("dispose",ce),A.__depthDisposeCallback=ce}A.__boundDepthTexture=J}if(I.depthTexture&&!A.__autoAllocateDepthBuffer){if(V)throw new Error("target.depthTexture not supported in Cube render targets");const J=I.texture.mipmaps;J&&J.length>0?se(A.__webglFramebuffer[0],I):se(A.__webglFramebuffer,I)}else if(V){A.__webglDepthbuffer=[];for(let J=0;J<6;J++)if(t.bindFramebuffer(n.FRAMEBUFFER,A.__webglFramebuffer[J]),A.__webglDepthbuffer[J]===void 0)A.__webglDepthbuffer[J]=n.createRenderbuffer(),X(A.__webglDepthbuffer[J],I,!1);else{const ce=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ee=A.__webglDepthbuffer[J];n.bindRenderbuffer(n.RENDERBUFFER,ee),n.framebufferRenderbuffer(n.FRAMEBUFFER,ce,n.RENDERBUFFER,ee)}}else{const J=I.texture.mipmaps;if(J&&J.length>0?t.bindFramebuffer(n.FRAMEBUFFER,A.__webglFramebuffer[0]):t.bindFramebuffer(n.FRAMEBUFFER,A.__webglFramebuffer),A.__webglDepthbuffer===void 0)A.__webglDepthbuffer=n.createRenderbuffer(),X(A.__webglDepthbuffer,I,!1);else{const ce=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ee=A.__webglDepthbuffer;n.bindRenderbuffer(n.RENDERBUFFER,ee),n.framebufferRenderbuffer(n.FRAMEBUFFER,ce,n.RENDERBUFFER,ee)}}t.bindFramebuffer(n.FRAMEBUFFER,null)}function Re(I,A,V){const J=i.get(I);A!==void 0&&Te(J.__webglFramebuffer,I,I.texture,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,0),V!==void 0&&we(I)}function k(I){const A=I.texture,V=i.get(I),J=i.get(A);I.addEventListener("dispose",M);const ce=I.textures,ee=I.isWebGLCubeRenderTarget===!0,Ve=ce.length>1;if(Ve||(J.__webglTexture===void 0&&(J.__webglTexture=n.createTexture()),J.__version=A.version,r.memory.textures++),ee){V.__webglFramebuffer=[];for(let ve=0;ve<6;ve++)if(A.mipmaps&&A.mipmaps.length>0){V.__webglFramebuffer[ve]=[];for(let Be=0;Be0){V.__webglFramebuffer=[];for(let ve=0;ve0&&ue(I)===!1){V.__webglMultisampledFramebuffer=n.createFramebuffer(),V.__webglColorRenderbuffer=[],t.bindFramebuffer(n.FRAMEBUFFER,V.__webglMultisampledFramebuffer);for(let ve=0;ve0)for(let Be=0;Be0)for(let Be=0;Be0){if(ue(I)===!1){const A=I.textures,V=I.width,J=I.height;let ce=n.COLOR_BUFFER_BIT;const ee=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,Ve=i.get(I),ve=A.length>1;if(ve)for(let ze=0;ze0?t.bindFramebuffer(n.DRAW_FRAMEBUFFER,Ve.__webglFramebuffer[0]):t.bindFramebuffer(n.DRAW_FRAMEBUFFER,Ve.__webglFramebuffer);for(let ze=0;ze0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&A.__useRenderToTexture!==!1}function ye(I){const A=r.render.frame;u.get(I)!==A&&(u.set(I,A),I.update())}function We(I,A){const V=I.colorSpace,J=I.format,ce=I.type;return I.isCompressedTexture===!0||I.isVideoTexture===!0||V!==wn&&V!==Bs&&(ot.getTransfer(V)===It?(J!==Xn||ce!==is)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",V)),A}function st(I){return typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement?(c.width=I.naturalWidth||I.width,c.height=I.naturalHeight||I.height):typeof VideoFrame<"u"&&I instanceof VideoFrame?(c.width=I.displayWidth,c.height=I.displayHeight):(c.width=I.width,c.height=I.height),c}this.allocateTextureUnit=O,this.resetTextureUnits=L,this.setTexture2D=U,this.setTexture2DArray=F,this.setTexture3D=W,this.setTextureCube=H,this.rebindTextures=Re,this.setupRenderTarget=k,this.updateRenderTargetMipmap=G,this.updateMultisampleRenderTarget=Q,this.setupDepthRenderbuffer=we,this.setupFrameBufferTexture=Te,this.useMultisampledRTT=ue}function ZT(n,e){function t(i,s=Bs){let a;const r=ot.getTransfer(s);if(i===is)return n.UNSIGNED_BYTE;if(i===jh)return n.UNSIGNED_SHORT_4_4_4_4;if(i===Zh)return n.UNSIGNED_SHORT_5_5_5_1;if(i===wg)return n.UNSIGNED_INT_5_9_9_9_REV;if(i===Sg)return n.UNSIGNED_INT_10F_11F_11F_REV;if(i===bg)return n.BYTE;if(i===xg)return n.SHORT;if(i===Lo)return n.UNSIGNED_SHORT;if(i===Yh)return n.INT;if(i===Ks)return n.UNSIGNED_INT;if(i===Mn)return n.FLOAT;if(i===ms)return n.HALF_FLOAT;if(i===Tg)return n.ALPHA;if(i===Mg)return n.RGB;if(i===Xn)return n.RGBA;if(i===Do)return n.DEPTH_COMPONENT;if(i===Oo)return n.DEPTH_STENCIL;if(i===Jh)return n.RED;if(i===Ec)return n.RED_INTEGER;if(i===Eg)return n.RG;if(i===Qh)return n.RG_INTEGER;if(i===ef)return n.RGBA_INTEGER;if(i===$l||i===Wl||i===Xl||i===Kl)if(r===It)if(a=e.get("WEBGL_compressed_texture_s3tc_srgb"),a!==null){if(i===$l)return a.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===Wl)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===Xl)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===Kl)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(a=e.get("WEBGL_compressed_texture_s3tc"),a!==null){if(i===$l)return a.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===Wl)return a.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===Xl)return a.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===Kl)return a.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===Xd||i===Kd||i===qd||i===Yd)if(a=e.get("WEBGL_compressed_texture_pvrtc"),a!==null){if(i===Xd)return a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===Kd)return a.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===qd)return a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===Yd)return a.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===jd||i===Zd||i===Jd)if(a=e.get("WEBGL_compressed_texture_etc"),a!==null){if(i===jd||i===Zd)return r===It?a.COMPRESSED_SRGB8_ETC2:a.COMPRESSED_RGB8_ETC2;if(i===Jd)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:a.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(i===Qd||i===eh||i===th||i===nh||i===ih||i===sh||i===ah||i===rh||i===oh||i===lh||i===ch||i===uh||i===dh||i===hh)if(a=e.get("WEBGL_compressed_texture_astc"),a!==null){if(i===Qd)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:a.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===eh)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:a.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===th)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:a.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===nh)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:a.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===ih)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:a.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===sh)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:a.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===ah)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:a.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===rh)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:a.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===oh)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:a.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===lh)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:a.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===ch)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:a.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===uh)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:a.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===dh)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:a.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===hh)return r===It?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:a.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===fh||i===ph||i===mh)if(a=e.get("EXT_texture_compression_bptc"),a!==null){if(i===fh)return r===It?a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:a.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===ph)return a.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===mh)return a.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===_h||i===gh||i===yh||i===vh)if(a=e.get("EXT_texture_compression_rgtc"),a!==null){if(i===_h)return a.COMPRESSED_RED_RGTC1_EXT;if(i===gh)return a.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===yh)return a.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===vh)return a.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===ko?n.UNSIGNED_INT_24_8:n[i]!==void 0?n[i]:null}return{convert:t}}const nO=` void main() { gl_Position = vec4( position, 1.0 ); -}`,XD=` +}`,iO=` uniform sampler2DArray depthColor; uniform float depthWidth; uniform float depthHeight; @@ -3829,16 +3829,16 @@ void main() { } -}`;class KD{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const i=new Ag(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,i=new ri({vertexShader:WD,fragmentShader:XD,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Se(new Nn(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class qD extends Ts{constructor(e,t){super();const i=this;let s=null,a=1,r=null,o="local-floor",l=1,c=null,u=null,d=null,h=null,f=null,p=null;const g=typeof XRWebGLBinding<"u",_=new KD,m={},v=t.getContextAttributes();let y=null,b=null;const S=[],x=[],M=new ne;let C=null;const w=new Qt;w.viewport=new Ye;const E=new Qt;E.viewport=new Ye;const R=[w,E],L=new PT;let O=null,D=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Z){let ae=S[Z];return ae===void 0&&(ae=new cd,S[Z]=ae),ae.getTargetRaySpace()},this.getControllerGrip=function(Z){let ae=S[Z];return ae===void 0&&(ae=new cd,S[Z]=ae),ae.getGripSpace()},this.getHand=function(Z){let ae=S[Z];return ae===void 0&&(ae=new cd,S[Z]=ae),ae.getHandSpace()};function U(Z){const ae=x.indexOf(Z.inputSource);if(ae===-1)return;const Te=S[ae];Te!==void 0&&(Te.update(Z.inputSource,Z.frame,c||r),Te.dispatchEvent({type:Z.type,data:Z.inputSource}))}function F(){s.removeEventListener("select",U),s.removeEventListener("selectstart",U),s.removeEventListener("selectend",U),s.removeEventListener("squeeze",U),s.removeEventListener("squeezestart",U),s.removeEventListener("squeezeend",U),s.removeEventListener("end",F),s.removeEventListener("inputsourceschange",W);for(let Z=0;Z=0&&(x[X]=null,S[X].disconnect(Te))}for(let ae=0;ae=x.length){x.push(Te),X=we;break}else if(x[we]===null){x[we]=Te,X=we;break}if(X===-1)break}const se=S[X];se&&se.connect(Te)}}const H=new T,ie=new T;function le(Z,ae,Te){H.setFromMatrixPosition(ae.matrixWorld),ie.setFromMatrixPosition(Te.matrixWorld);const X=H.distanceTo(ie),se=ae.projectionMatrix.elements,we=Te.projectionMatrix.elements,Re=se[14]/(se[10]-1),k=se[14]/(se[10]+1),G=(se[9]+1)/se[5],j=(se[9]-1)/se[5],Y=(se[8]-1)/se[0],Q=(we[8]+1)/we[0],ge=Re*Y,ue=Re*Q,ye=X/(-Y+Q),We=ye*-Y;if(ae.matrixWorld.decompose(Z.position,Z.quaternion,Z.scale),Z.translateX(We),Z.translateZ(ye),Z.matrixWorld.compose(Z.position,Z.quaternion,Z.scale),Z.matrixWorldInverse.copy(Z.matrixWorld).invert(),se[10]===-1)Z.projectionMatrix.copy(ae.projectionMatrix),Z.projectionMatrixInverse.copy(ae.projectionMatrixInverse);else{const st=Re+ye,I=k+ye,A=ge-We,V=ue+(X-We),J=G*k/I*st,ce=j*k/I*st;Z.projectionMatrix.makePerspective(A,V,J,ce,st,I),Z.projectionMatrixInverse.copy(Z.projectionMatrix).invert()}}function me(Z,ae){ae===null?Z.matrixWorld.copy(Z.matrix):Z.matrixWorld.multiplyMatrices(ae.matrixWorld,Z.matrix),Z.matrixWorldInverse.copy(Z.matrixWorld).invert()}this.updateCamera=function(Z){if(s===null)return;let ae=Z.near,Te=Z.far;_.texture!==null&&(_.depthNear>0&&(ae=_.depthNear),_.depthFar>0&&(Te=_.depthFar)),L.near=E.near=w.near=ae,L.far=E.far=w.far=Te,(O!==L.near||D!==L.far)&&(s.updateRenderState({depthNear:L.near,depthFar:L.far}),O=L.near,D=L.far),L.layers.mask=Z.layers.mask|6,w.layers.mask=L.layers.mask&3,E.layers.mask=L.layers.mask&5;const X=Z.parent,se=L.cameras;me(L,X);for(let we=0;we0&&(_.alphaTest.value=m.alphaTest);const v=e.get(m),y=v.envMap,b=v.envMapRotation;y&&(_.envMap.value=y,Ua.copy(b),Ua.x*=-1,Ua.y*=-1,Ua.z*=-1,y.isCubeTexture&&y.isRenderTargetTexture===!1&&(Ua.y*=-1,Ua.z*=-1),_.envMapRotation.value.setFromMatrix4(YD.makeRotationFromEuler(Ua)),_.flipEnvMap.value=y.isCubeTexture&&y.isRenderTargetTexture===!1?-1:1,_.reflectivity.value=m.reflectivity,_.ior.value=m.ior,_.refractionRatio.value=m.refractionRatio),m.lightMap&&(_.lightMap.value=m.lightMap,_.lightMapIntensity.value=m.lightMapIntensity,t(m.lightMap,_.lightMapTransform)),m.aoMap&&(_.aoMap.value=m.aoMap,_.aoMapIntensity.value=m.aoMapIntensity,t(m.aoMap,_.aoMapTransform))}function r(_,m){_.diffuse.value.copy(m.color),_.opacity.value=m.opacity,m.map&&(_.map.value=m.map,t(m.map,_.mapTransform))}function o(_,m){_.dashSize.value=m.dashSize,_.totalSize.value=m.dashSize+m.gapSize,_.scale.value=m.scale}function l(_,m,v,y){_.diffuse.value.copy(m.color),_.opacity.value=m.opacity,_.size.value=m.size*v,_.scale.value=y*.5,m.map&&(_.map.value=m.map,t(m.map,_.uvTransform)),m.alphaMap&&(_.alphaMap.value=m.alphaMap,t(m.alphaMap,_.alphaMapTransform)),m.alphaTest>0&&(_.alphaTest.value=m.alphaTest)}function c(_,m){_.diffuse.value.copy(m.color),_.opacity.value=m.opacity,_.rotation.value=m.rotation,m.map&&(_.map.value=m.map,t(m.map,_.mapTransform)),m.alphaMap&&(_.alphaMap.value=m.alphaMap,t(m.alphaMap,_.alphaMapTransform)),m.alphaTest>0&&(_.alphaTest.value=m.alphaTest)}function u(_,m){_.specular.value.copy(m.specular),_.shininess.value=Math.max(m.shininess,1e-4)}function d(_,m){m.gradientMap&&(_.gradientMap.value=m.gradientMap)}function h(_,m){_.metalness.value=m.metalness,m.metalnessMap&&(_.metalnessMap.value=m.metalnessMap,t(m.metalnessMap,_.metalnessMapTransform)),_.roughness.value=m.roughness,m.roughnessMap&&(_.roughnessMap.value=m.roughnessMap,t(m.roughnessMap,_.roughnessMapTransform)),m.envMap&&(_.envMapIntensity.value=m.envMapIntensity)}function f(_,m,v){_.ior.value=m.ior,m.sheen>0&&(_.sheenColor.value.copy(m.sheenColor).multiplyScalar(m.sheen),_.sheenRoughness.value=m.sheenRoughness,m.sheenColorMap&&(_.sheenColorMap.value=m.sheenColorMap,t(m.sheenColorMap,_.sheenColorMapTransform)),m.sheenRoughnessMap&&(_.sheenRoughnessMap.value=m.sheenRoughnessMap,t(m.sheenRoughnessMap,_.sheenRoughnessMapTransform))),m.clearcoat>0&&(_.clearcoat.value=m.clearcoat,_.clearcoatRoughness.value=m.clearcoatRoughness,m.clearcoatMap&&(_.clearcoatMap.value=m.clearcoatMap,t(m.clearcoatMap,_.clearcoatMapTransform)),m.clearcoatRoughnessMap&&(_.clearcoatRoughnessMap.value=m.clearcoatRoughnessMap,t(m.clearcoatRoughnessMap,_.clearcoatRoughnessMapTransform)),m.clearcoatNormalMap&&(_.clearcoatNormalMap.value=m.clearcoatNormalMap,t(m.clearcoatNormalMap,_.clearcoatNormalMapTransform),_.clearcoatNormalScale.value.copy(m.clearcoatNormalScale),m.side===dn&&_.clearcoatNormalScale.value.negate())),m.dispersion>0&&(_.dispersion.value=m.dispersion),m.iridescence>0&&(_.iridescence.value=m.iridescence,_.iridescenceIOR.value=m.iridescenceIOR,_.iridescenceThicknessMinimum.value=m.iridescenceThicknessRange[0],_.iridescenceThicknessMaximum.value=m.iridescenceThicknessRange[1],m.iridescenceMap&&(_.iridescenceMap.value=m.iridescenceMap,t(m.iridescenceMap,_.iridescenceMapTransform)),m.iridescenceThicknessMap&&(_.iridescenceThicknessMap.value=m.iridescenceThicknessMap,t(m.iridescenceThicknessMap,_.iridescenceThicknessMapTransform))),m.transmission>0&&(_.transmission.value=m.transmission,_.transmissionSamplerMap.value=v.texture,_.transmissionSamplerSize.value.set(v.width,v.height),m.transmissionMap&&(_.transmissionMap.value=m.transmissionMap,t(m.transmissionMap,_.transmissionMapTransform)),_.thickness.value=m.thickness,m.thicknessMap&&(_.thicknessMap.value=m.thicknessMap,t(m.thicknessMap,_.thicknessMapTransform)),_.attenuationDistance.value=m.attenuationDistance,_.attenuationColor.value.copy(m.attenuationColor)),m.anisotropy>0&&(_.anisotropyVector.value.set(m.anisotropy*Math.cos(m.anisotropyRotation),m.anisotropy*Math.sin(m.anisotropyRotation)),m.anisotropyMap&&(_.anisotropyMap.value=m.anisotropyMap,t(m.anisotropyMap,_.anisotropyMapTransform))),_.specularIntensity.value=m.specularIntensity,_.specularColor.value.copy(m.specularColor),m.specularColorMap&&(_.specularColorMap.value=m.specularColorMap,t(m.specularColorMap,_.specularColorMapTransform)),m.specularIntensityMap&&(_.specularIntensityMap.value=m.specularIntensityMap,t(m.specularIntensityMap,_.specularIntensityMapTransform))}function p(_,m){m.matcap&&(_.matcap.value=m.matcap)}function g(_,m){const v=e.get(m).light;_.referencePosition.value.setFromMatrixPosition(v.matrixWorld),_.nearDistance.value=v.shadow.camera.near,_.farDistance.value=v.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:s}}function ZD(n,e,t,i){let s={},a={},r=[];const o=n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS);function l(v,y){const b=y.program;i.uniformBlockBinding(v,b)}function c(v,y){let b=s[v.id];b===void 0&&(p(v),b=u(v),s[v.id]=b,v.addEventListener("dispose",_));const S=y.program;i.updateUBOMapping(v,S);const x=e.render.frame;a[v.id]!==x&&(h(v),a[v.id]=x)}function u(v){const y=d();v.__bindingPointIndex=y;const b=n.createBuffer(),S=v.__size,x=v.usage;return n.bindBuffer(n.UNIFORM_BUFFER,b),n.bufferData(n.UNIFORM_BUFFER,S,x),n.bindBuffer(n.UNIFORM_BUFFER,null),n.bindBufferBase(n.UNIFORM_BUFFER,y,b),b}function d(){for(let v=0;v0&&(b+=S-x),v.__size=b,v.__cache={},this}function g(v){const y={boundary:0,storage:0};return typeof v=="number"||typeof v=="boolean"?(y.boundary=4,y.storage=4):v.isVector2?(y.boundary=8,y.storage=8):v.isVector3||v.isColor?(y.boundary=16,y.storage=12):v.isVector4?(y.boundary=16,y.storage=16):v.isMatrix3?(y.boundary=48,y.storage=48):v.isMatrix4?(y.boundary=64,y.storage=64):v.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",v),y}function _(v){const y=v.target;y.removeEventListener("dispose",_);const b=r.indexOf(y.__bindingPointIndex);r.splice(b,1),n.deleteBuffer(s[y.id]),delete s[y.id],delete a[y.id]}function m(){for(const v in s)n.deleteBuffer(s[v]);r=[],s={},a={}}return{bind:l,update:c,dispose:m}}class Jg{constructor(e={}){const{canvas:t=WS(),context:i=null,depth:s=!0,stencil:a=!1,alpha:r=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:d=!1,reversedDepthBuffer:h=!1}=e;this.isWebGLRenderer=!0;let f;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=i.getContextAttributes().alpha}else f=r;const p=new Uint32Array(4),g=new Int32Array(4);let _=null,m=null;const v=[],y=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Vs,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const b=this;let S=!1;this._outputColorSpace=yt;let x=0,M=0,C=null,w=-1,E=null;const R=new Ye,L=new Ye;let O=null;const D=new de(0);let U=0,F=t.width,W=t.height,H=1,ie=null,le=null;const me=new Ye(0,0,F,W),Le=new Ye(0,0,F,W);let De=!1;const Ke=new $o;let Oe=!1,Z=!1;const ae=new Ee,Te=new T,X=new Ye,se={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let we=!1;function Re(){return C===null?H:1}let k=i;function G(P,B){return t.getContext(P,B)}try{const P={alpha:!0,depth:s,stencil:a,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:u,failIfMajorPerformanceCaveat:d};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${zh}`),t.addEventListener("webglcontextlost",xe,!1),t.addEventListener("webglcontextrestored",Ne,!1),t.addEventListener("webglcontextcreationerror",fe,!1),k===null){const B="webgl2";if(k=G(B,P),k===null)throw G(B)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(P){throw console.error("THREE.WebGLRenderer: "+P.message),P}let j,Y,Q,ge,ue,ye,We,st,I,A,V,J,ce,ee,Ve,ve,Be,ze,he,Ie,Qe,Ge,Ae,ft;function N(){j=new ck(k),j.init(),Ge=new VT(k,j),Y=new nk(k,j,e,Ge),Q=new GD(k,j),Y.reversedDepthBuffer&&h&&Q.buffers.depth.setReversed(!0),ge=new hk(k),ue=new PD,ye=new $D(k,j,Q,ue,Y,Ge,ge),We=new sk(b),st=new lk(b),I=new yI(k),Ae=new ek(k,I),A=new uk(k,I,ge,Ae),V=new pk(k,A,I,ge),he=new fk(k,Y,ye),ve=new ik(ue),J=new RD(b,We,st,j,Y,Ae,ve),ce=new jD(b,ue),ee=new LD,Ve=new UD(j),ze=new Q2(b,We,st,Q,V,f,l),Be=new HD(b,V,Y),ft=new ZD(k,ge,Y,Q),Ie=new tk(k,j,ge),Qe=new dk(k,j,ge),ge.programs=J.programs,b.capabilities=Y,b.extensions=j,b.properties=ue,b.renderLists=ee,b.shadowMap=Be,b.state=Q,b.info=ge}N();const _e=new qD(b,k);this.xr=_e,this.getContext=function(){return k},this.getContextAttributes=function(){return k.getContextAttributes()},this.forceContextLoss=function(){const P=j.get("WEBGL_lose_context");P&&P.loseContext()},this.forceContextRestore=function(){const P=j.get("WEBGL_lose_context");P&&P.restoreContext()},this.getPixelRatio=function(){return H},this.setPixelRatio=function(P){P!==void 0&&(H=P,this.setSize(F,W,!1))},this.getSize=function(P){return P.set(F,W)},this.setSize=function(P,B,K=!0){if(_e.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}F=P,W=B,t.width=Math.floor(P*H),t.height=Math.floor(B*H),K===!0&&(t.style.width=P+"px",t.style.height=B+"px"),this.setViewport(0,0,P,B)},this.getDrawingBufferSize=function(P){return P.set(F*H,W*H).floor()},this.setDrawingBufferSize=function(P,B,K){F=P,W=B,H=K,t.width=Math.floor(P*K),t.height=Math.floor(B*K),this.setViewport(0,0,P,B)},this.getCurrentViewport=function(P){return P.copy(R)},this.getViewport=function(P){return P.copy(me)},this.setViewport=function(P,B,K,q){P.isVector4?me.set(P.x,P.y,P.z,P.w):me.set(P,B,K,q),Q.viewport(R.copy(me).multiplyScalar(H).round())},this.getScissor=function(P){return P.copy(Le)},this.setScissor=function(P,B,K,q){P.isVector4?Le.set(P.x,P.y,P.z,P.w):Le.set(P,B,K,q),Q.scissor(L.copy(Le).multiplyScalar(H).round())},this.getScissorTest=function(){return De},this.setScissorTest=function(P){Q.setScissorTest(De=P)},this.setOpaqueSort=function(P){ie=P},this.setTransparentSort=function(P){le=P},this.getClearColor=function(P){return P.copy(ze.getClearColor())},this.setClearColor=function(){ze.setClearColor(...arguments)},this.getClearAlpha=function(){return ze.getClearAlpha()},this.setClearAlpha=function(){ze.setClearAlpha(...arguments)},this.clear=function(P=!0,B=!0,K=!0){let q=0;if(P){let z=!1;if(C!==null){const pe=C.texture.format;z=pe===qh||pe===Kh||pe===wc}if(z){const pe=C.texture.type,Pe=pe===ns||pe===Ks||pe===Ro||pe===Po||pe===$h||pe===Wh,Ue=ze.getClearColor(),Fe=ze.getClearAlpha(),Ze=Ue.r,tt=Ue.g,Xe=Ue.b;Pe?(p[0]=Ze,p[1]=tt,p[2]=Xe,p[3]=Fe,k.clearBufferuiv(k.COLOR,0,p)):(g[0]=Ze,g[1]=tt,g[2]=Xe,g[3]=Fe,k.clearBufferiv(k.COLOR,0,g))}else q|=k.COLOR_BUFFER_BIT}B&&(q|=k.DEPTH_BUFFER_BIT),K&&(q|=k.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),k.clear(q)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",xe,!1),t.removeEventListener("webglcontextrestored",Ne,!1),t.removeEventListener("webglcontextcreationerror",fe,!1),ze.dispose(),ee.dispose(),Ve.dispose(),ue.dispose(),We.dispose(),st.dispose(),V.dispose(),Ae.dispose(),ft.dispose(),J.dispose(),_e.dispose(),_e.removeEventListener("sessionstart",ss),_e.removeEventListener("sessionend",Iy),Sa.stop()};function xe(P){P.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),S=!0}function Ne(){console.log("THREE.WebGLRenderer: Context Restored."),S=!1;const P=ge.autoReset,B=Be.enabled,K=Be.autoUpdate,q=Be.needsUpdate,z=Be.type;N(),ge.autoReset=P,Be.enabled=B,Be.autoUpdate=K,Be.needsUpdate=q,Be.type=z}function fe(P){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",P.statusMessage)}function oe(P){const B=P.target;B.removeEventListener("dispose",oe),He(B)}function He(P){ct(P),ue.remove(P)}function ct(P){const B=ue.get(P).programs;B!==void 0&&(B.forEach(function(K){J.releaseProgram(K)}),P.isShaderMaterial&&J.releaseShaderCache(P))}this.renderBufferDirect=function(P,B,K,q,z,pe){B===null&&(B=se);const Pe=z.isMesh&&z.matrixWorld.determinant()<0,Ue=xC(P,B,K,q,z);Q.setMaterial(q,Pe);let Fe=K.index,Ze=1;if(q.wireframe===!0){if(Fe=A.getWireframeAttribute(K),Fe===void 0)return;Ze=2}const tt=K.drawRange,Xe=K.attributes.position;let St=tt.start*Ze,Lt=(tt.start+tt.count)*Ze;pe!==null&&(St=Math.max(St,pe.start*Ze),Lt=Math.min(Lt,(pe.start+pe.count)*Ze)),Fe!==null?(St=Math.max(St,0),Lt=Math.min(Lt,Fe.count)):Xe!=null&&(St=Math.max(St,0),Lt=Math.min(Lt,Xe.count));const Yt=Lt-St;if(Yt<0||Yt===1/0)return;Ae.setup(z,q,Ue,K,Fe);let Nt,Dt=Ie;if(Fe!==null&&(Nt=I.get(Fe),Dt=Qe,Dt.setIndex(Nt)),z.isMesh)q.wireframe===!0?(Q.setLineWidth(q.wireframeLinewidth*Re()),Dt.setMode(k.LINES)):Dt.setMode(k.TRIANGLES);else if(z.isLine){let qe=q.linewidth;qe===void 0&&(qe=1),Q.setLineWidth(qe*Re()),z.isLineSegments?Dt.setMode(k.LINES):z.isLineLoop?Dt.setMode(k.LINE_LOOP):Dt.setMode(k.LINE_STRIP)}else z.isPoints?Dt.setMode(k.POINTS):z.isSprite&&Dt.setMode(k.TRIANGLES);if(z.isBatchedMesh)if(z._multiDrawInstances!==null)oc("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),Dt.renderMultiDrawInstances(z._multiDrawStarts,z._multiDrawCounts,z._multiDrawCount,z._multiDrawInstances);else if(j.get("WEBGL_multi_draw"))Dt.renderMultiDraw(z._multiDrawStarts,z._multiDrawCounts,z._multiDrawCount);else{const qe=z._multiDrawStarts,$t=z._multiDrawCounts,Tt=z._multiDrawCount,di=Fe?I.get(Fe).bytesPerElement:1,Cr=ue.get(q).currentProgram.getUniforms();for(let hi=0;hi{function pe(){if(q.forEach(function(Pe){ue.get(Pe).currentProgram.isReady()&&q.delete(Pe)}),q.size===0){z(P);return}setTimeout(pe,10)}j.get("KHR_parallel_shader_compile")!==null?pe():setTimeout(pe,10)})};let At=null;function Ms(P){At&&At(P)}function ss(){Sa.stop()}function Iy(){Sa.start()}const Sa=new NT;Sa.setAnimationLoop(Ms),typeof self<"u"&&Sa.setContext(self),this.setAnimationLoop=function(P){At=P,_e.setAnimationLoop(P),P===null?Sa.stop():Sa.start()},_e.addEventListener("sessionstart",ss),_e.addEventListener("sessionend",Iy),this.render=function(P,B){if(B!==void 0&&B.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(S===!0)return;if(P.matrixWorldAutoUpdate===!0&&P.updateMatrixWorld(),B.parent===null&&B.matrixWorldAutoUpdate===!0&&B.updateMatrixWorld(),_e.enabled===!0&&_e.isPresenting===!0&&(_e.cameraAutoUpdate===!0&&_e.updateCamera(B),B=_e.getCamera()),P.isScene===!0&&P.onBeforeRender(b,P,B,C),m=Ve.get(P,y.length),m.init(B),y.push(m),ae.multiplyMatrices(B.projectionMatrix,B.matrixWorldInverse),Ke.setFromProjectionMatrix(ae,yi,B.reversedDepth),Z=this.localClippingEnabled,Oe=ve.init(this.clippingPlanes,Z),_=ee.get(P,v.length),_.init(),v.push(_),_e.enabled===!0&&_e.isPresenting===!0){const pe=b.xr.getDepthSensingMesh();pe!==null&&Nf(pe,B,-1/0,b.sortObjects)}Nf(P,B,0,b.sortObjects),_.finish(),b.sortObjects===!0&&_.sort(ie,le),we=_e.enabled===!1||_e.isPresenting===!1||_e.hasDepthSensing()===!1,we&&ze.addToRenderList(_,P),this.info.render.frame++,Oe===!0&&ve.beginShadows();const K=m.state.shadowsArray;Be.render(K,P,B),Oe===!0&&ve.endShadows(),this.info.autoReset===!0&&this.info.reset();const q=_.opaque,z=_.transmissive;if(m.setupLights(),B.isArrayCamera){const pe=B.cameras;if(z.length>0)for(let Pe=0,Ue=pe.length;Pe0&&ky(q,z,P,B),we&&ze.render(P),Ly(_,P,B);C!==null&&M===0&&(ye.updateMultisampleRenderTarget(C),ye.updateRenderTargetMipmap(C)),P.isScene===!0&&P.onAfterRender(b,P,B),Ae.resetDefaultState(),w=-1,E=null,y.pop(),y.length>0?(m=y[y.length-1],Oe===!0&&ve.setGlobalState(b.clippingPlanes,m.state.camera)):m=null,v.pop(),v.length>0?_=v[v.length-1]:_=null};function Nf(P,B,K,q){if(P.visible===!1)return;if(P.layers.test(B.layers)){if(P.isGroup)K=P.renderOrder;else if(P.isLOD)P.autoUpdate===!0&&P.update(B);else if(P.isLight)m.pushLight(P),P.castShadow&&m.pushShadow(P);else if(P.isSprite){if(!P.frustumCulled||Ke.intersectsSprite(P)){q&&X.setFromMatrixPosition(P.matrixWorld).applyMatrix4(ae);const Pe=V.update(P),Ue=P.material;Ue.visible&&_.push(P,Pe,Ue,K,X.z,null)}}else if((P.isMesh||P.isLine||P.isPoints)&&(!P.frustumCulled||Ke.intersectsObject(P))){const Pe=V.update(P),Ue=P.material;if(q&&(P.boundingSphere!==void 0?(P.boundingSphere===null&&P.computeBoundingSphere(),X.copy(P.boundingSphere.center)):(Pe.boundingSphere===null&&Pe.computeBoundingSphere(),X.copy(Pe.boundingSphere.center)),X.applyMatrix4(P.matrixWorld).applyMatrix4(ae)),Array.isArray(Ue)){const Fe=Pe.groups;for(let Ze=0,tt=Fe.length;Ze0&&Dc(z,B,K),pe.length>0&&Dc(pe,B,K),Pe.length>0&&Dc(Pe,B,K),Q.buffers.depth.setTest(!0),Q.buffers.depth.setMask(!0),Q.buffers.color.setMask(!0),Q.setPolygonOffset(!1)}function ky(P,B,K,q){if((K.isScene===!0?K.overrideMaterial:null)!==null)return;m.state.transmissionRenderTarget[q.id]===void 0&&(m.state.transmissionRenderTarget[q.id]=new ws(1,1,{generateMipmaps:!0,type:j.has("EXT_color_buffer_half_float")||j.has("EXT_color_buffer_float")?ms:ns,minFilter:Ii,samples:4,stencilBuffer:a,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:rt.workingColorSpace}));const pe=m.state.transmissionRenderTarget[q.id],Pe=q.viewport||R;pe.setSize(Pe.z*b.transmissionResolutionScale,Pe.w*b.transmissionResolutionScale);const Ue=b.getRenderTarget(),Fe=b.getActiveCubeFace(),Ze=b.getActiveMipmapLevel();b.setRenderTarget(pe),b.getClearColor(D),U=b.getClearAlpha(),U<1&&b.setClearColor(16777215,.5),b.clear(),we&&ze.render(K);const tt=b.toneMapping;b.toneMapping=Vs;const Xe=q.viewport;if(q.viewport!==void 0&&(q.viewport=void 0),m.setupLightsView(q),Oe===!0&&ve.setGlobalState(b.clippingPlanes,q),Dc(P,K,q),ye.updateMultisampleRenderTarget(pe),ye.updateRenderTargetMipmap(pe),j.has("WEBGL_multisampled_render_to_texture")===!1){let St=!1;for(let Lt=0,Yt=B.length;Lt0),Xe=!!K.morphAttributes.position,St=!!K.morphAttributes.normal,Lt=!!K.morphAttributes.color;let Yt=Vs;q.toneMapped&&(C===null||C.isXRRenderTarget===!0)&&(Yt=b.toneMapping);const Nt=K.morphAttributes.position||K.morphAttributes.normal||K.morphAttributes.color,Dt=Nt!==void 0?Nt.length:0,qe=ue.get(q),$t=m.state.lights;if(Oe===!0&&(Z===!0||P!==E)){const Bn=P===E&&q.id===w;ve.setState(q,P,Bn)}let Tt=!1;q.version===qe.__version?(qe.needsLights&&qe.lightsStateVersion!==$t.state.version||qe.outputColorSpace!==Ue||z.isBatchedMesh&&qe.batching===!1||!z.isBatchedMesh&&qe.batching===!0||z.isBatchedMesh&&qe.batchingColor===!0&&z.colorTexture===null||z.isBatchedMesh&&qe.batchingColor===!1&&z.colorTexture!==null||z.isInstancedMesh&&qe.instancing===!1||!z.isInstancedMesh&&qe.instancing===!0||z.isSkinnedMesh&&qe.skinning===!1||!z.isSkinnedMesh&&qe.skinning===!0||z.isInstancedMesh&&qe.instancingColor===!0&&z.instanceColor===null||z.isInstancedMesh&&qe.instancingColor===!1&&z.instanceColor!==null||z.isInstancedMesh&&qe.instancingMorph===!0&&z.morphTexture===null||z.isInstancedMesh&&qe.instancingMorph===!1&&z.morphTexture!==null||qe.envMap!==Fe||q.fog===!0&&qe.fog!==pe||qe.numClippingPlanes!==void 0&&(qe.numClippingPlanes!==ve.numPlanes||qe.numIntersection!==ve.numIntersection)||qe.vertexAlphas!==Ze||qe.vertexTangents!==tt||qe.morphTargets!==Xe||qe.morphNormals!==St||qe.morphColors!==Lt||qe.toneMapping!==Yt||qe.morphTargetsCount!==Dt)&&(Tt=!0):(Tt=!0,qe.__version=q.version);let di=qe.currentProgram;Tt===!0&&(di=Oc(q,B,z));let Cr=!1,hi=!1,Qo=!1;const Wt=di.getUniforms(),xi=qe.uniforms;if(Q.useProgram(di.program)&&(Cr=!0,hi=!0,Qo=!0),q.id!==w&&(w=q.id,hi=!0),Cr||E!==P){Q.buffers.depth.getReversed()&&P.reversedDepth!==!0&&(P._reversedDepth=!0,P.updateProjectionMatrix()),Wt.setValue(k,"projectionMatrix",P.projectionMatrix),Wt.setValue(k,"viewMatrix",P.matrixWorldInverse);const qn=Wt.map.cameraPosition;qn!==void 0&&qn.setValue(k,Te.setFromMatrixPosition(P.matrixWorld)),Y.logarithmicDepthBuffer&&Wt.setValue(k,"logDepthBufFC",2/(Math.log(P.far+1)/Math.LN2)),(q.isMeshPhongMaterial||q.isMeshToonMaterial||q.isMeshLambertMaterial||q.isMeshBasicMaterial||q.isMeshStandardMaterial||q.isShaderMaterial)&&Wt.setValue(k,"isOrthographic",P.isOrthographicCamera===!0),E!==P&&(E=P,hi=!0,Qo=!0)}if(z.isSkinnedMesh){Wt.setOptional(k,z,"bindMatrix"),Wt.setOptional(k,z,"bindMatrixInverse");const Bn=z.skeleton;Bn&&(Bn.boneTexture===null&&Bn.computeBoneTexture(),Wt.setValue(k,"boneTexture",Bn.boneTexture,ye))}z.isBatchedMesh&&(Wt.setOptional(k,z,"batchingTexture"),Wt.setValue(k,"batchingTexture",z._matricesTexture,ye),Wt.setOptional(k,z,"batchingIdTexture"),Wt.setValue(k,"batchingIdTexture",z._indirectTexture,ye),Wt.setOptional(k,z,"batchingColorTexture"),z._colorsTexture!==null&&Wt.setValue(k,"batchingColorTexture",z._colorsTexture,ye));const wi=K.morphAttributes;if((wi.position!==void 0||wi.normal!==void 0||wi.color!==void 0)&&he.update(z,K,di),(hi||qe.receiveShadow!==z.receiveShadow)&&(qe.receiveShadow=z.receiveShadow,Wt.setValue(k,"receiveShadow",z.receiveShadow)),q.isMeshGouraudMaterial&&q.envMap!==null&&(xi.envMap.value=Fe,xi.flipEnvMap.value=Fe.isCubeTexture&&Fe.isRenderTargetTexture===!1?-1:1),q.isMeshStandardMaterial&&q.envMap===null&&B.environment!==null&&(xi.envMapIntensity.value=B.environmentIntensity),hi&&(Wt.setValue(k,"toneMappingExposure",b.toneMappingExposure),qe.needsLights&&wC(xi,Qo),pe&&q.fog===!0&&ce.refreshFogUniforms(xi,pe),ce.refreshMaterialUniforms(xi,q,H,W,m.state.transmissionRenderTarget[P.id]),ud.upload(k,Oy(qe),xi,ye)),q.isShaderMaterial&&q.uniformsNeedUpdate===!0&&(ud.upload(k,Oy(qe),xi,ye),q.uniformsNeedUpdate=!1),q.isSpriteMaterial&&Wt.setValue(k,"center",z.center),Wt.setValue(k,"modelViewMatrix",z.modelViewMatrix),Wt.setValue(k,"normalMatrix",z.normalMatrix),Wt.setValue(k,"modelMatrix",z.matrixWorld),q.isShaderMaterial||q.isRawShaderMaterial){const Bn=q.uniformsGroups;for(let qn=0,Uf=Bn.length;qn0&&ye.useMultisampledRTT(P)===!1?z=ue.get(P).__webglMultisampledFramebuffer:Array.isArray(tt)?z=tt[K]:z=tt,R.copy(P.viewport),L.copy(P.scissor),O=P.scissorTest}else R.copy(me).multiplyScalar(H).floor(),L.copy(Le).multiplyScalar(H).floor(),O=De;if(K!==0&&(z=TC),Q.bindFramebuffer(k.FRAMEBUFFER,z)&&q&&Q.drawBuffers(P,z),Q.viewport(R),Q.scissor(L),Q.setScissorTest(O),pe){const Fe=ue.get(P.texture);k.framebufferTexture2D(k.FRAMEBUFFER,k.COLOR_ATTACHMENT0,k.TEXTURE_CUBE_MAP_POSITIVE_X+B,Fe.__webglTexture,K)}else if(Pe){const Fe=B;for(let Ze=0;Ze=0&&B<=P.width-q&&K>=0&&K<=P.height-z&&(P.textures.length>1&&k.readBuffer(k.COLOR_ATTACHMENT0+Ue),k.readPixels(B,K,q,z,Ge.convert(tt),Ge.convert(Xe),pe))}finally{const Ze=C!==null?ue.get(C).__webglFramebuffer:null;Q.bindFramebuffer(k.FRAMEBUFFER,Ze)}}},this.readRenderTargetPixelsAsync=async function(P,B,K,q,z,pe,Pe,Ue=0){if(!(P&&P.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Fe=ue.get(P).__webglFramebuffer;if(P.isWebGLCubeRenderTarget&&Pe!==void 0&&(Fe=Fe[Pe]),Fe)if(B>=0&&B<=P.width-q&&K>=0&&K<=P.height-z){Q.bindFramebuffer(k.FRAMEBUFFER,Fe);const Ze=P.textures[Ue],tt=Ze.format,Xe=Ze.type;if(!Y.textureFormatReadable(tt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Y.textureTypeReadable(Xe))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const St=k.createBuffer();k.bindBuffer(k.PIXEL_PACK_BUFFER,St),k.bufferData(k.PIXEL_PACK_BUFFER,pe.byteLength,k.STREAM_READ),P.textures.length>1&&k.readBuffer(k.COLOR_ATTACHMENT0+Ue),k.readPixels(B,K,q,z,Ge.convert(tt),Ge.convert(Xe),0);const Lt=C!==null?ue.get(C).__webglFramebuffer:null;Q.bindFramebuffer(k.FRAMEBUFFER,Lt);const Yt=k.fenceSync(k.SYNC_GPU_COMMANDS_COMPLETE,0);return k.flush(),await GA(k,Yt,4),k.bindBuffer(k.PIXEL_PACK_BUFFER,St),k.getBufferSubData(k.PIXEL_PACK_BUFFER,0,pe),k.deleteBuffer(St),k.deleteSync(Yt),pe}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(P,B=null,K=0){const q=Math.pow(2,-K),z=Math.floor(P.image.width*q),pe=Math.floor(P.image.height*q),Pe=B!==null?B.x:0,Ue=B!==null?B.y:0;ye.setTexture2D(P,0),k.copyTexSubImage2D(k.TEXTURE_2D,K,0,0,Pe,Ue,z,pe),Q.unbindTexture()};const MC=k.createFramebuffer(),EC=k.createFramebuffer();this.copyTextureToTexture=function(P,B,K=null,q=null,z=0,pe=null){pe===null&&(z!==0?(oc("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),pe=z,z=0):pe=0);let Pe,Ue,Fe,Ze,tt,Xe,St,Lt,Yt;const Nt=P.isCompressedTexture?P.mipmaps[pe]:P.image;if(K!==null)Pe=K.max.x-K.min.x,Ue=K.max.y-K.min.y,Fe=K.isBox3?K.max.z-K.min.z:1,Ze=K.min.x,tt=K.min.y,Xe=K.isBox3?K.min.z:0;else{const wi=Math.pow(2,-z);Pe=Math.floor(Nt.width*wi),Ue=Math.floor(Nt.height*wi),P.isDataArrayTexture?Fe=Nt.depth:P.isData3DTexture?Fe=Math.floor(Nt.depth*wi):Fe=1,Ze=0,tt=0,Xe=0}q!==null?(St=q.x,Lt=q.y,Yt=q.z):(St=0,Lt=0,Yt=0);const Dt=Ge.convert(B.format),qe=Ge.convert(B.type);let $t;B.isData3DTexture?(ye.setTexture3D(B,0),$t=k.TEXTURE_3D):B.isDataArrayTexture||B.isCompressedArrayTexture?(ye.setTexture2DArray(B,0),$t=k.TEXTURE_2D_ARRAY):(ye.setTexture2D(B,0),$t=k.TEXTURE_2D),k.pixelStorei(k.UNPACK_FLIP_Y_WEBGL,B.flipY),k.pixelStorei(k.UNPACK_PREMULTIPLY_ALPHA_WEBGL,B.premultiplyAlpha),k.pixelStorei(k.UNPACK_ALIGNMENT,B.unpackAlignment);const Tt=k.getParameter(k.UNPACK_ROW_LENGTH),di=k.getParameter(k.UNPACK_IMAGE_HEIGHT),Cr=k.getParameter(k.UNPACK_SKIP_PIXELS),hi=k.getParameter(k.UNPACK_SKIP_ROWS),Qo=k.getParameter(k.UNPACK_SKIP_IMAGES);k.pixelStorei(k.UNPACK_ROW_LENGTH,Nt.width),k.pixelStorei(k.UNPACK_IMAGE_HEIGHT,Nt.height),k.pixelStorei(k.UNPACK_SKIP_PIXELS,Ze),k.pixelStorei(k.UNPACK_SKIP_ROWS,tt),k.pixelStorei(k.UNPACK_SKIP_IMAGES,Xe);const Wt=P.isDataArrayTexture||P.isData3DTexture,xi=B.isDataArrayTexture||B.isData3DTexture;if(P.isDepthTexture){const wi=ue.get(P),Bn=ue.get(B),qn=ue.get(wi.__renderTarget),Uf=ue.get(Bn.__renderTarget);Q.bindFramebuffer(k.READ_FRAMEBUFFER,qn.__webglFramebuffer),Q.bindFramebuffer(k.DRAW_FRAMEBUFFER,Uf.__webglFramebuffer);for(let Ta=0;TaMath.PI&&(i-=jn),s<-Math.PI?s+=jn:s>Math.PI&&(s-=jn),i<=s?this._spherical.theta=Math.max(i,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(i+s)/2?Math.max(i,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let a=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const r=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),a=r!=this._spherical.radius}if(cn.setFromSpherical(this._spherical),cn.applyQuaternion(this._quatInverse),t.copy(this.target).add(cn),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let r=null;if(this.object.isPerspectiveCamera){const o=cn.length();r=this._clampDistance(o*this._scale);const l=o-r;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),a=!!l}else if(this.object.isOrthographicCamera){const o=new T(this._mouse.x,this._mouse.y,0);o.unproject(this.object);const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),a=l!==this.object.zoom;const c=new T(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(o),this.object.updateMatrixWorld(),r=cn.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;r!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(r).add(this.object.position):(Cu.origin.copy(this.object.position),Cu.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Cu.direction))Pp||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Pp||this._lastTargetPosition.distanceToSquared(this.target)>Pp?(this.dispatchEvent(gv),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?jn/60*this.autoRotateSpeed*e:jn/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){cn.setFromMatrixColumn(t,0),cn.multiplyScalar(-e),this._panOffset.add(cn)}_panUp(e,t){this.screenSpacePanning===!0?cn.setFromMatrixColumn(t,1):(cn.setFromMatrixColumn(t,0),cn.crossVectors(this.object.up,cn)),cn.multiplyScalar(e),this._panOffset.add(cn)}_pan(e,t){const i=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;cn.copy(s).sub(this.target);let a=cn.length();a*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*a/i.clientHeight,this.object.matrix),this._panUp(2*t*a/i.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/i.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/i.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const i=this.domElement.getBoundingClientRect(),s=e-i.left,a=t-i.top,r=i.width,o=i.height;this._mouse.x=s/r*2-1,this._mouse.y=-(a/o)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(jn*this._rotateDelta.x/t.clientHeight),this._rotateUp(jn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(jn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-jn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(jn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-jn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(i,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(i,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,s=e.pageY-t.y,a=Math.sqrt(i*i+s*s);this._dollyStart.set(0,a)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const i=this._getSecondPointerPosition(e),s=.5*(e.pageX+i.x),a=.5*(e.pageY+i.y);this._rotateEnd.set(s,a)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(jn*this._rotateDelta.x/t.clientHeight),this._rotateUp(jn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(i,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,s=e.pageY-t.y,a=Math.sqrt(i*i+s*s);this._dollyEnd.set(0,a),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const r=(e.pageX+t.x)*.5,o=(e.pageY+t.y)*.5;this._updateZoomParameters(r,o)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t(O=F.indexOf(` +}`;class sO{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const i=new Og(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,i=new ri({vertexShader:nO,fragmentShader:iO,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Se(new Nn(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class aO extends Ts{constructor(e,t){super();const i=this;let s=null,a=1,r=null,o="local-floor",l=1,c=null,u=null,d=null,h=null,f=null,p=null;const g=typeof XRWebGLBinding<"u",_=new sO,m={},v=t.getContextAttributes();let y=null,b=null;const S=[],x=[],M=new ne;let C=null;const w=new Qt;w.viewport=new Ye;const E=new Qt;E.viewport=new Ye;const R=[w,E],L=new BT;let O=null,D=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Z){let re=S[Z];return re===void 0&&(re=new fd,S[Z]=re),re.getTargetRaySpace()},this.getControllerGrip=function(Z){let re=S[Z];return re===void 0&&(re=new fd,S[Z]=re),re.getGripSpace()},this.getHand=function(Z){let re=S[Z];return re===void 0&&(re=new fd,S[Z]=re),re.getHandSpace()};function U(Z){const re=x.indexOf(Z.inputSource);if(re===-1)return;const Te=S[re];Te!==void 0&&(Te.update(Z.inputSource,Z.frame,c||r),Te.dispatchEvent({type:Z.type,data:Z.inputSource}))}function F(){s.removeEventListener("select",U),s.removeEventListener("selectstart",U),s.removeEventListener("selectend",U),s.removeEventListener("squeeze",U),s.removeEventListener("squeezestart",U),s.removeEventListener("squeezeend",U),s.removeEventListener("end",F),s.removeEventListener("inputsourceschange",W);for(let Z=0;Z=0&&(x[X]=null,S[X].disconnect(Te))}for(let re=0;re=x.length){x.push(Te),X=we;break}else if(x[we]===null){x[we]=Te,X=we;break}if(X===-1)break}const se=S[X];se&&se.connect(Te)}}const H=new T,ie=new T;function le(Z,re,Te){H.setFromMatrixPosition(re.matrixWorld),ie.setFromMatrixPosition(Te.matrixWorld);const X=H.distanceTo(ie),se=re.projectionMatrix.elements,we=Te.projectionMatrix.elements,Re=se[14]/(se[10]-1),k=se[14]/(se[10]+1),G=(se[9]+1)/se[5],j=(se[9]-1)/se[5],Y=(se[8]-1)/se[0],Q=(we[8]+1)/we[0],ge=Re*Y,ue=Re*Q,ye=X/(-Y+Q),We=ye*-Y;if(re.matrixWorld.decompose(Z.position,Z.quaternion,Z.scale),Z.translateX(We),Z.translateZ(ye),Z.matrixWorld.compose(Z.position,Z.quaternion,Z.scale),Z.matrixWorldInverse.copy(Z.matrixWorld).invert(),se[10]===-1)Z.projectionMatrix.copy(re.projectionMatrix),Z.projectionMatrixInverse.copy(re.projectionMatrixInverse);else{const st=Re+ye,I=k+ye,A=ge-We,V=ue+(X-We),J=G*k/I*st,ce=j*k/I*st;Z.projectionMatrix.makePerspective(A,V,J,ce,st,I),Z.projectionMatrixInverse.copy(Z.projectionMatrix).invert()}}function me(Z,re){re===null?Z.matrixWorld.copy(Z.matrix):Z.matrixWorld.multiplyMatrices(re.matrixWorld,Z.matrix),Z.matrixWorldInverse.copy(Z.matrixWorld).invert()}this.updateCamera=function(Z){if(s===null)return;let re=Z.near,Te=Z.far;_.texture!==null&&(_.depthNear>0&&(re=_.depthNear),_.depthFar>0&&(Te=_.depthFar)),L.near=E.near=w.near=re,L.far=E.far=w.far=Te,(O!==L.near||D!==L.far)&&(s.updateRenderState({depthNear:L.near,depthFar:L.far}),O=L.near,D=L.far),L.layers.mask=Z.layers.mask|6,w.layers.mask=L.layers.mask&3,E.layers.mask=L.layers.mask&5;const X=Z.parent,se=L.cameras;me(L,X);for(let we=0;we0&&(_.alphaTest.value=m.alphaTest);const v=e.get(m),y=v.envMap,b=v.envMapRotation;y&&(_.envMap.value=y,Ba.copy(b),Ba.x*=-1,Ba.y*=-1,Ba.z*=-1,y.isCubeTexture&&y.isRenderTargetTexture===!1&&(Ba.y*=-1,Ba.z*=-1),_.envMapRotation.value.setFromMatrix4(rO.makeRotationFromEuler(Ba)),_.flipEnvMap.value=y.isCubeTexture&&y.isRenderTargetTexture===!1?-1:1,_.reflectivity.value=m.reflectivity,_.ior.value=m.ior,_.refractionRatio.value=m.refractionRatio),m.lightMap&&(_.lightMap.value=m.lightMap,_.lightMapIntensity.value=m.lightMapIntensity,t(m.lightMap,_.lightMapTransform)),m.aoMap&&(_.aoMap.value=m.aoMap,_.aoMapIntensity.value=m.aoMapIntensity,t(m.aoMap,_.aoMapTransform))}function r(_,m){_.diffuse.value.copy(m.color),_.opacity.value=m.opacity,m.map&&(_.map.value=m.map,t(m.map,_.mapTransform))}function o(_,m){_.dashSize.value=m.dashSize,_.totalSize.value=m.dashSize+m.gapSize,_.scale.value=m.scale}function l(_,m,v,y){_.diffuse.value.copy(m.color),_.opacity.value=m.opacity,_.size.value=m.size*v,_.scale.value=y*.5,m.map&&(_.map.value=m.map,t(m.map,_.uvTransform)),m.alphaMap&&(_.alphaMap.value=m.alphaMap,t(m.alphaMap,_.alphaMapTransform)),m.alphaTest>0&&(_.alphaTest.value=m.alphaTest)}function c(_,m){_.diffuse.value.copy(m.color),_.opacity.value=m.opacity,_.rotation.value=m.rotation,m.map&&(_.map.value=m.map,t(m.map,_.mapTransform)),m.alphaMap&&(_.alphaMap.value=m.alphaMap,t(m.alphaMap,_.alphaMapTransform)),m.alphaTest>0&&(_.alphaTest.value=m.alphaTest)}function u(_,m){_.specular.value.copy(m.specular),_.shininess.value=Math.max(m.shininess,1e-4)}function d(_,m){m.gradientMap&&(_.gradientMap.value=m.gradientMap)}function h(_,m){_.metalness.value=m.metalness,m.metalnessMap&&(_.metalnessMap.value=m.metalnessMap,t(m.metalnessMap,_.metalnessMapTransform)),_.roughness.value=m.roughness,m.roughnessMap&&(_.roughnessMap.value=m.roughnessMap,t(m.roughnessMap,_.roughnessMapTransform)),m.envMap&&(_.envMapIntensity.value=m.envMapIntensity)}function f(_,m,v){_.ior.value=m.ior,m.sheen>0&&(_.sheenColor.value.copy(m.sheenColor).multiplyScalar(m.sheen),_.sheenRoughness.value=m.sheenRoughness,m.sheenColorMap&&(_.sheenColorMap.value=m.sheenColorMap,t(m.sheenColorMap,_.sheenColorMapTransform)),m.sheenRoughnessMap&&(_.sheenRoughnessMap.value=m.sheenRoughnessMap,t(m.sheenRoughnessMap,_.sheenRoughnessMapTransform))),m.clearcoat>0&&(_.clearcoat.value=m.clearcoat,_.clearcoatRoughness.value=m.clearcoatRoughness,m.clearcoatMap&&(_.clearcoatMap.value=m.clearcoatMap,t(m.clearcoatMap,_.clearcoatMapTransform)),m.clearcoatRoughnessMap&&(_.clearcoatRoughnessMap.value=m.clearcoatRoughnessMap,t(m.clearcoatRoughnessMap,_.clearcoatRoughnessMapTransform)),m.clearcoatNormalMap&&(_.clearcoatNormalMap.value=m.clearcoatNormalMap,t(m.clearcoatNormalMap,_.clearcoatNormalMapTransform),_.clearcoatNormalScale.value.copy(m.clearcoatNormalScale),m.side===dn&&_.clearcoatNormalScale.value.negate())),m.dispersion>0&&(_.dispersion.value=m.dispersion),m.iridescence>0&&(_.iridescence.value=m.iridescence,_.iridescenceIOR.value=m.iridescenceIOR,_.iridescenceThicknessMinimum.value=m.iridescenceThicknessRange[0],_.iridescenceThicknessMaximum.value=m.iridescenceThicknessRange[1],m.iridescenceMap&&(_.iridescenceMap.value=m.iridescenceMap,t(m.iridescenceMap,_.iridescenceMapTransform)),m.iridescenceThicknessMap&&(_.iridescenceThicknessMap.value=m.iridescenceThicknessMap,t(m.iridescenceThicknessMap,_.iridescenceThicknessMapTransform))),m.transmission>0&&(_.transmission.value=m.transmission,_.transmissionSamplerMap.value=v.texture,_.transmissionSamplerSize.value.set(v.width,v.height),m.transmissionMap&&(_.transmissionMap.value=m.transmissionMap,t(m.transmissionMap,_.transmissionMapTransform)),_.thickness.value=m.thickness,m.thicknessMap&&(_.thicknessMap.value=m.thicknessMap,t(m.thicknessMap,_.thicknessMapTransform)),_.attenuationDistance.value=m.attenuationDistance,_.attenuationColor.value.copy(m.attenuationColor)),m.anisotropy>0&&(_.anisotropyVector.value.set(m.anisotropy*Math.cos(m.anisotropyRotation),m.anisotropy*Math.sin(m.anisotropyRotation)),m.anisotropyMap&&(_.anisotropyMap.value=m.anisotropyMap,t(m.anisotropyMap,_.anisotropyMapTransform))),_.specularIntensity.value=m.specularIntensity,_.specularColor.value.copy(m.specularColor),m.specularColorMap&&(_.specularColorMap.value=m.specularColorMap,t(m.specularColorMap,_.specularColorMapTransform)),m.specularIntensityMap&&(_.specularIntensityMap.value=m.specularIntensityMap,t(m.specularIntensityMap,_.specularIntensityMapTransform))}function p(_,m){m.matcap&&(_.matcap.value=m.matcap)}function g(_,m){const v=e.get(m).light;_.referencePosition.value.setFromMatrixPosition(v.matrixWorld),_.nearDistance.value=v.shadow.camera.near,_.farDistance.value=v.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:s}}function lO(n,e,t,i){let s={},a={},r=[];const o=n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS);function l(v,y){const b=y.program;i.uniformBlockBinding(v,b)}function c(v,y){let b=s[v.id];b===void 0&&(p(v),b=u(v),s[v.id]=b,v.addEventListener("dispose",_));const S=y.program;i.updateUBOMapping(v,S);const x=e.render.frame;a[v.id]!==x&&(h(v),a[v.id]=x)}function u(v){const y=d();v.__bindingPointIndex=y;const b=n.createBuffer(),S=v.__size,x=v.usage;return n.bindBuffer(n.UNIFORM_BUFFER,b),n.bufferData(n.UNIFORM_BUFFER,S,x),n.bindBuffer(n.UNIFORM_BUFFER,null),n.bindBufferBase(n.UNIFORM_BUFFER,y,b),b}function d(){for(let v=0;v0&&(b+=S-x),v.__size=b,v.__cache={},this}function g(v){const y={boundary:0,storage:0};return typeof v=="number"||typeof v=="boolean"?(y.boundary=4,y.storage=4):v.isVector2?(y.boundary=8,y.storage=8):v.isVector3||v.isColor?(y.boundary=16,y.storage=12):v.isVector4?(y.boundary=16,y.storage=16):v.isMatrix3?(y.boundary=48,y.storage=48):v.isMatrix4?(y.boundary=64,y.storage=64):v.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",v),y}function _(v){const y=v.target;y.removeEventListener("dispose",_);const b=r.indexOf(y.__bindingPointIndex);r.splice(b,1),n.deleteBuffer(s[y.id]),delete s[y.id],delete a[y.id]}function m(){for(const v in s)n.deleteBuffer(s[v]);r=[],s={},a={}}return{bind:l,update:c,dispose:m}}class ay{constructor(e={}){const{canvas:t=eT(),context:i=null,depth:s=!0,stencil:a=!1,alpha:r=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:d=!1,reversedDepthBuffer:h=!1}=e;this.isWebGLRenderer=!0;let f;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=i.getContextAttributes().alpha}else f=r;const p=new Uint32Array(4),g=new Int32Array(4);let _=null,m=null;const v=[],y=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Vs,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const b=this;let S=!1;this._outputColorSpace=yt;let x=0,M=0,C=null,w=-1,E=null;const R=new Ye,L=new Ye;let O=null;const D=new de(0);let U=0,F=t.width,W=t.height,H=1,ie=null,le=null;const me=new Ye(0,0,F,W),Le=new Ye(0,0,F,W);let De=!1;const Ke=new Ko;let Oe=!1,Z=!1;const re=new Ee,Te=new T,X=new Ye,se={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let we=!1;function Re(){return C===null?H:1}let k=i;function G(P,B){return t.getContext(P,B)}try{const P={alpha:!0,depth:s,stencil:a,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:u,failIfMajorPerformanceCaveat:d};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${Xh}`),t.addEventListener("webglcontextlost",xe,!1),t.addEventListener("webglcontextrestored",Ne,!1),t.addEventListener("webglcontextcreationerror",fe,!1),k===null){const B="webgl2";if(k=G(B,P),k===null)throw G(B)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(P){throw console.error("THREE.WebGLRenderer: "+P.message),P}let j,Y,Q,ge,ue,ye,We,st,I,A,V,J,ce,ee,Ve,ve,Be,ze,he,Ie,Qe,Ge,Ae,ft;function N(){j=new bk(k),j.init(),Ge=new ZT(k,j),Y=new fk(k,j,e,Ge),Q=new eO(k,j),Y.reversedDepthBuffer&&h&&Q.buffers.depth.setReversed(!0),ge=new Sk(k),ue=new HD,ye=new tO(k,j,Q,ue,Y,Ge,ge),We=new mk(b),st=new vk(b),I=new RI(k),Ae=new dk(k,I),A=new xk(k,I,ge,Ae),V=new Mk(k,A,I,ge),he=new Tk(k,Y,ye),ve=new pk(ue),J=new zD(b,We,st,j,Y,Ae,ve),ce=new oO(b,ue),ee=new GD,Ve=new YD(j),ze=new uk(b,We,st,Q,V,f,l),Be=new JD(b,V,Y),ft=new lO(k,ge,Y,Q),Ie=new hk(k,j,ge),Qe=new wk(k,j,ge),ge.programs=J.programs,b.capabilities=Y,b.extensions=j,b.properties=ue,b.renderLists=ee,b.shadowMap=Be,b.state=Q,b.info=ge}N();const _e=new aO(b,k);this.xr=_e,this.getContext=function(){return k},this.getContextAttributes=function(){return k.getContextAttributes()},this.forceContextLoss=function(){const P=j.get("WEBGL_lose_context");P&&P.loseContext()},this.forceContextRestore=function(){const P=j.get("WEBGL_lose_context");P&&P.restoreContext()},this.getPixelRatio=function(){return H},this.setPixelRatio=function(P){P!==void 0&&(H=P,this.setSize(F,W,!1))},this.getSize=function(P){return P.set(F,W)},this.setSize=function(P,B,K=!0){if(_e.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}F=P,W=B,t.width=Math.floor(P*H),t.height=Math.floor(B*H),K===!0&&(t.style.width=P+"px",t.style.height=B+"px"),this.setViewport(0,0,P,B)},this.getDrawingBufferSize=function(P){return P.set(F*H,W*H).floor()},this.setDrawingBufferSize=function(P,B,K){F=P,W=B,H=K,t.width=Math.floor(P*K),t.height=Math.floor(B*K),this.setViewport(0,0,P,B)},this.getCurrentViewport=function(P){return P.copy(R)},this.getViewport=function(P){return P.copy(me)},this.setViewport=function(P,B,K,q){P.isVector4?me.set(P.x,P.y,P.z,P.w):me.set(P,B,K,q),Q.viewport(R.copy(me).multiplyScalar(H).round())},this.getScissor=function(P){return P.copy(Le)},this.setScissor=function(P,B,K,q){P.isVector4?Le.set(P.x,P.y,P.z,P.w):Le.set(P,B,K,q),Q.scissor(L.copy(Le).multiplyScalar(H).round())},this.getScissorTest=function(){return De},this.setScissorTest=function(P){Q.setScissorTest(De=P)},this.setOpaqueSort=function(P){ie=P},this.setTransparentSort=function(P){le=P},this.getClearColor=function(P){return P.copy(ze.getClearColor())},this.setClearColor=function(){ze.setClearColor(...arguments)},this.getClearAlpha=function(){return ze.getClearAlpha()},this.setClearAlpha=function(){ze.setClearAlpha(...arguments)},this.clear=function(P=!0,B=!0,K=!0){let q=0;if(P){let z=!1;if(C!==null){const pe=C.texture.format;z=pe===ef||pe===Qh||pe===Ec}if(z){const pe=C.texture.type,Pe=pe===is||pe===Ks||pe===Lo||pe===ko||pe===jh||pe===Zh,Ue=ze.getClearColor(),Fe=ze.getClearAlpha(),Ze=Ue.r,tt=Ue.g,Xe=Ue.b;Pe?(p[0]=Ze,p[1]=tt,p[2]=Xe,p[3]=Fe,k.clearBufferuiv(k.COLOR,0,p)):(g[0]=Ze,g[1]=tt,g[2]=Xe,g[3]=Fe,k.clearBufferiv(k.COLOR,0,g))}else q|=k.COLOR_BUFFER_BIT}B&&(q|=k.DEPTH_BUFFER_BIT),K&&(q|=k.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),k.clear(q)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",xe,!1),t.removeEventListener("webglcontextrestored",Ne,!1),t.removeEventListener("webglcontextcreationerror",fe,!1),ze.dispose(),ee.dispose(),Ve.dispose(),ue.dispose(),We.dispose(),st.dispose(),V.dispose(),Ae.dispose(),ft.dispose(),J.dispose(),_e.dispose(),_e.removeEventListener("sessionstart",as),_e.removeEventListener("sessionend",Uy),Ta.stop()};function xe(P){P.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),S=!0}function Ne(){console.log("THREE.WebGLRenderer: Context Restored."),S=!1;const P=ge.autoReset,B=Be.enabled,K=Be.autoUpdate,q=Be.needsUpdate,z=Be.type;N(),ge.autoReset=P,Be.enabled=B,Be.autoUpdate=K,Be.needsUpdate=q,Be.type=z}function fe(P){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",P.statusMessage)}function oe(P){const B=P.target;B.removeEventListener("dispose",oe),He(B)}function He(P){ct(P),ue.remove(P)}function ct(P){const B=ue.get(P).programs;B!==void 0&&(B.forEach(function(K){J.releaseProgram(K)}),P.isShaderMaterial&&J.releaseShaderCache(P))}this.renderBufferDirect=function(P,B,K,q,z,pe){B===null&&(B=se);const Pe=z.isMesh&&z.matrixWorld.determinant()<0,Ue=LC(P,B,K,q,z);Q.setMaterial(q,Pe);let Fe=K.index,Ze=1;if(q.wireframe===!0){if(Fe=A.getWireframeAttribute(K),Fe===void 0)return;Ze=2}const tt=K.drawRange,Xe=K.attributes.position;let St=tt.start*Ze,Lt=(tt.start+tt.count)*Ze;pe!==null&&(St=Math.max(St,pe.start*Ze),Lt=Math.min(Lt,(pe.start+pe.count)*Ze)),Fe!==null?(St=Math.max(St,0),Lt=Math.min(Lt,Fe.count)):Xe!=null&&(St=Math.max(St,0),Lt=Math.min(Lt,Xe.count));const Yt=Lt-St;if(Yt<0||Yt===1/0)return;Ae.setup(z,q,Ue,K,Fe);let Nt,Dt=Ie;if(Fe!==null&&(Nt=I.get(Fe),Dt=Qe,Dt.setIndex(Nt)),z.isMesh)q.wireframe===!0?(Q.setLineWidth(q.wireframeLinewidth*Re()),Dt.setMode(k.LINES)):Dt.setMode(k.TRIANGLES);else if(z.isLine){let qe=q.linewidth;qe===void 0&&(qe=1),Q.setLineWidth(qe*Re()),z.isLineSegments?Dt.setMode(k.LINES):z.isLineLoop?Dt.setMode(k.LINE_LOOP):Dt.setMode(k.LINE_STRIP)}else z.isPoints?Dt.setMode(k.POINTS):z.isSprite&&Dt.setMode(k.TRIANGLES);if(z.isBatchedMesh)if(z._multiDrawInstances!==null)dc("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),Dt.renderMultiDrawInstances(z._multiDrawStarts,z._multiDrawCounts,z._multiDrawCount,z._multiDrawInstances);else if(j.get("WEBGL_multi_draw"))Dt.renderMultiDraw(z._multiDrawStarts,z._multiDrawCounts,z._multiDrawCount);else{const qe=z._multiDrawStarts,$t=z._multiDrawCounts,Tt=z._multiDrawCount,di=Fe?I.get(Fe).bytesPerElement:1,Ar=ue.get(q).currentProgram.getUniforms();for(let hi=0;hi{function pe(){if(q.forEach(function(Pe){ue.get(Pe).currentProgram.isReady()&&q.delete(Pe)}),q.size===0){z(P);return}setTimeout(pe,10)}j.get("KHR_parallel_shader_compile")!==null?pe():setTimeout(pe,10)})};let At=null;function Ms(P){At&&At(P)}function as(){Ta.stop()}function Uy(){Ta.start()}const Ta=new XT;Ta.setAnimationLoop(Ms),typeof self<"u"&&Ta.setContext(self),this.setAnimationLoop=function(P){At=P,_e.setAnimationLoop(P),P===null?Ta.stop():Ta.start()},_e.addEventListener("sessionstart",as),_e.addEventListener("sessionend",Uy),this.render=function(P,B){if(B!==void 0&&B.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(S===!0)return;if(P.matrixWorldAutoUpdate===!0&&P.updateMatrixWorld(),B.parent===null&&B.matrixWorldAutoUpdate===!0&&B.updateMatrixWorld(),_e.enabled===!0&&_e.isPresenting===!0&&(_e.cameraAutoUpdate===!0&&_e.updateCamera(B),B=_e.getCamera()),P.isScene===!0&&P.onBeforeRender(b,P,B,C),m=Ve.get(P,y.length),m.init(B),y.push(m),re.multiplyMatrices(B.projectionMatrix,B.matrixWorldInverse),Ke.setFromProjectionMatrix(re,yi,B.reversedDepth),Z=this.localClippingEnabled,Oe=ve.init(this.clippingPlanes,Z),_=ee.get(P,v.length),_.init(),v.push(_),_e.enabled===!0&&_e.isPresenting===!0){const pe=b.xr.getDepthSensingMesh();pe!==null&&Gf(pe,B,-1/0,b.sortObjects)}Gf(P,B,0,b.sortObjects),_.finish(),b.sortObjects===!0&&_.sort(ie,le),we=_e.enabled===!1||_e.isPresenting===!1||_e.hasDepthSensing()===!1,we&&ze.addToRenderList(_,P),this.info.render.frame++,Oe===!0&&ve.beginShadows();const K=m.state.shadowsArray;Be.render(K,P,B),Oe===!0&&ve.endShadows(),this.info.autoReset===!0&&this.info.reset();const q=_.opaque,z=_.transmissive;if(m.setupLights(),B.isArrayCamera){const pe=B.cameras;if(z.length>0)for(let Pe=0,Ue=pe.length;Pe0&&zy(q,z,P,B),we&&ze.render(P),By(_,P,B);C!==null&&M===0&&(ye.updateMultisampleRenderTarget(C),ye.updateRenderTargetMipmap(C)),P.isScene===!0&&P.onAfterRender(b,P,B),Ae.resetDefaultState(),w=-1,E=null,y.pop(),y.length>0?(m=y[y.length-1],Oe===!0&&ve.setGlobalState(b.clippingPlanes,m.state.camera)):m=null,v.pop(),v.length>0?_=v[v.length-1]:_=null};function Gf(P,B,K,q){if(P.visible===!1)return;if(P.layers.test(B.layers)){if(P.isGroup)K=P.renderOrder;else if(P.isLOD)P.autoUpdate===!0&&P.update(B);else if(P.isLight)m.pushLight(P),P.castShadow&&m.pushShadow(P);else if(P.isSprite){if(!P.frustumCulled||Ke.intersectsSprite(P)){q&&X.setFromMatrixPosition(P.matrixWorld).applyMatrix4(re);const Pe=V.update(P),Ue=P.material;Ue.visible&&_.push(P,Pe,Ue,K,X.z,null)}}else if((P.isMesh||P.isLine||P.isPoints)&&(!P.frustumCulled||Ke.intersectsObject(P))){const Pe=V.update(P),Ue=P.material;if(q&&(P.boundingSphere!==void 0?(P.boundingSphere===null&&P.computeBoundingSphere(),X.copy(P.boundingSphere.center)):(Pe.boundingSphere===null&&Pe.computeBoundingSphere(),X.copy(Pe.boundingSphere.center)),X.applyMatrix4(P.matrixWorld).applyMatrix4(re)),Array.isArray(Ue)){const Fe=Pe.groups;for(let Ze=0,tt=Fe.length;Ze0&&Uc(z,B,K),pe.length>0&&Uc(pe,B,K),Pe.length>0&&Uc(Pe,B,K),Q.buffers.depth.setTest(!0),Q.buffers.depth.setMask(!0),Q.buffers.color.setMask(!0),Q.setPolygonOffset(!1)}function zy(P,B,K,q){if((K.isScene===!0?K.overrideMaterial:null)!==null)return;m.state.transmissionRenderTarget[q.id]===void 0&&(m.state.transmissionRenderTarget[q.id]=new ws(1,1,{generateMipmaps:!0,type:j.has("EXT_color_buffer_half_float")||j.has("EXT_color_buffer_float")?ms:is,minFilter:Li,samples:4,stencilBuffer:a,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:ot.workingColorSpace}));const pe=m.state.transmissionRenderTarget[q.id],Pe=q.viewport||R;pe.setSize(Pe.z*b.transmissionResolutionScale,Pe.w*b.transmissionResolutionScale);const Ue=b.getRenderTarget(),Fe=b.getActiveCubeFace(),Ze=b.getActiveMipmapLevel();b.setRenderTarget(pe),b.getClearColor(D),U=b.getClearAlpha(),U<1&&b.setClearColor(16777215,.5),b.clear(),we&&ze.render(K);const tt=b.toneMapping;b.toneMapping=Vs;const Xe=q.viewport;if(q.viewport!==void 0&&(q.viewport=void 0),m.setupLightsView(q),Oe===!0&&ve.setGlobalState(b.clippingPlanes,q),Uc(P,K,q),ye.updateMultisampleRenderTarget(pe),ye.updateRenderTargetMipmap(pe),j.has("WEBGL_multisampled_render_to_texture")===!1){let St=!1;for(let Lt=0,Yt=B.length;Lt0),Xe=!!K.morphAttributes.position,St=!!K.morphAttributes.normal,Lt=!!K.morphAttributes.color;let Yt=Vs;q.toneMapped&&(C===null||C.isXRRenderTarget===!0)&&(Yt=b.toneMapping);const Nt=K.morphAttributes.position||K.morphAttributes.normal||K.morphAttributes.color,Dt=Nt!==void 0?Nt.length:0,qe=ue.get(q),$t=m.state.lights;if(Oe===!0&&(Z===!0||P!==E)){const Bn=P===E&&q.id===w;ve.setState(q,P,Bn)}let Tt=!1;q.version===qe.__version?(qe.needsLights&&qe.lightsStateVersion!==$t.state.version||qe.outputColorSpace!==Ue||z.isBatchedMesh&&qe.batching===!1||!z.isBatchedMesh&&qe.batching===!0||z.isBatchedMesh&&qe.batchingColor===!0&&z.colorTexture===null||z.isBatchedMesh&&qe.batchingColor===!1&&z.colorTexture!==null||z.isInstancedMesh&&qe.instancing===!1||!z.isInstancedMesh&&qe.instancing===!0||z.isSkinnedMesh&&qe.skinning===!1||!z.isSkinnedMesh&&qe.skinning===!0||z.isInstancedMesh&&qe.instancingColor===!0&&z.instanceColor===null||z.isInstancedMesh&&qe.instancingColor===!1&&z.instanceColor!==null||z.isInstancedMesh&&qe.instancingMorph===!0&&z.morphTexture===null||z.isInstancedMesh&&qe.instancingMorph===!1&&z.morphTexture!==null||qe.envMap!==Fe||q.fog===!0&&qe.fog!==pe||qe.numClippingPlanes!==void 0&&(qe.numClippingPlanes!==ve.numPlanes||qe.numIntersection!==ve.numIntersection)||qe.vertexAlphas!==Ze||qe.vertexTangents!==tt||qe.morphTargets!==Xe||qe.morphNormals!==St||qe.morphColors!==Lt||qe.toneMapping!==Yt||qe.morphTargetsCount!==Dt)&&(Tt=!0):(Tt=!0,qe.__version=q.version);let di=qe.currentProgram;Tt===!0&&(di=Bc(q,B,z));let Ar=!1,hi=!1,nl=!1;const Wt=di.getUniforms(),xi=qe.uniforms;if(Q.useProgram(di.program)&&(Ar=!0,hi=!0,nl=!0),q.id!==w&&(w=q.id,hi=!0),Ar||E!==P){Q.buffers.depth.getReversed()&&P.reversedDepth!==!0&&(P._reversedDepth=!0,P.updateProjectionMatrix()),Wt.setValue(k,"projectionMatrix",P.projectionMatrix),Wt.setValue(k,"viewMatrix",P.matrixWorldInverse);const qn=Wt.map.cameraPosition;qn!==void 0&&qn.setValue(k,Te.setFromMatrixPosition(P.matrixWorld)),Y.logarithmicDepthBuffer&&Wt.setValue(k,"logDepthBufFC",2/(Math.log(P.far+1)/Math.LN2)),(q.isMeshPhongMaterial||q.isMeshToonMaterial||q.isMeshLambertMaterial||q.isMeshBasicMaterial||q.isMeshStandardMaterial||q.isShaderMaterial)&&Wt.setValue(k,"isOrthographic",P.isOrthographicCamera===!0),E!==P&&(E=P,hi=!0,nl=!0)}if(z.isSkinnedMesh){Wt.setOptional(k,z,"bindMatrix"),Wt.setOptional(k,z,"bindMatrixInverse");const Bn=z.skeleton;Bn&&(Bn.boneTexture===null&&Bn.computeBoneTexture(),Wt.setValue(k,"boneTexture",Bn.boneTexture,ye))}z.isBatchedMesh&&(Wt.setOptional(k,z,"batchingTexture"),Wt.setValue(k,"batchingTexture",z._matricesTexture,ye),Wt.setOptional(k,z,"batchingIdTexture"),Wt.setValue(k,"batchingIdTexture",z._indirectTexture,ye),Wt.setOptional(k,z,"batchingColorTexture"),z._colorsTexture!==null&&Wt.setValue(k,"batchingColorTexture",z._colorsTexture,ye));const wi=K.morphAttributes;if((wi.position!==void 0||wi.normal!==void 0||wi.color!==void 0)&&he.update(z,K,di),(hi||qe.receiveShadow!==z.receiveShadow)&&(qe.receiveShadow=z.receiveShadow,Wt.setValue(k,"receiveShadow",z.receiveShadow)),q.isMeshGouraudMaterial&&q.envMap!==null&&(xi.envMap.value=Fe,xi.flipEnvMap.value=Fe.isCubeTexture&&Fe.isRenderTargetTexture===!1?-1:1),q.isMeshStandardMaterial&&q.envMap===null&&B.environment!==null&&(xi.envMapIntensity.value=B.environmentIntensity),hi&&(Wt.setValue(k,"toneMappingExposure",b.toneMappingExposure),qe.needsLights&&kC(xi,nl),pe&&q.fog===!0&&ce.refreshFogUniforms(xi,pe),ce.refreshMaterialUniforms(xi,q,H,W,m.state.transmissionRenderTarget[P.id]),pd.upload(k,Vy(qe),xi,ye)),q.isShaderMaterial&&q.uniformsNeedUpdate===!0&&(pd.upload(k,Vy(qe),xi,ye),q.uniformsNeedUpdate=!1),q.isSpriteMaterial&&Wt.setValue(k,"center",z.center),Wt.setValue(k,"modelViewMatrix",z.modelViewMatrix),Wt.setValue(k,"normalMatrix",z.normalMatrix),Wt.setValue(k,"modelMatrix",z.matrixWorld),q.isShaderMaterial||q.isRawShaderMaterial){const Bn=q.uniformsGroups;for(let qn=0,$f=Bn.length;qn<$f;qn++){const Ma=Bn[qn];ft.update(Ma,di),ft.bind(Ma,di)}}return di}function kC(P,B){P.ambientLightColor.needsUpdate=B,P.lightProbe.needsUpdate=B,P.directionalLights.needsUpdate=B,P.directionalLightShadows.needsUpdate=B,P.pointLights.needsUpdate=B,P.pointLightShadows.needsUpdate=B,P.spotLights.needsUpdate=B,P.spotLightShadows.needsUpdate=B,P.rectAreaLights.needsUpdate=B,P.hemisphereLights.needsUpdate=B}function DC(P){return P.isMeshLambertMaterial||P.isMeshToonMaterial||P.isMeshPhongMaterial||P.isMeshStandardMaterial||P.isShadowMaterial||P.isShaderMaterial&&P.lights===!0}this.getActiveCubeFace=function(){return x},this.getActiveMipmapLevel=function(){return M},this.getRenderTarget=function(){return C},this.setRenderTargetTextures=function(P,B,K){const q=ue.get(P);q.__autoAllocateDepthBuffer=P.resolveDepthBuffer===!1,q.__autoAllocateDepthBuffer===!1&&(q.__useRenderToTexture=!1),ue.get(P.texture).__webglTexture=B,ue.get(P.depthTexture).__webglTexture=q.__autoAllocateDepthBuffer?void 0:K,q.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(P,B){const K=ue.get(P);K.__webglFramebuffer=B,K.__useDefaultFramebuffer=B===void 0};const OC=k.createFramebuffer();this.setRenderTarget=function(P,B=0,K=0){C=P,x=B,M=K;let q=!0,z=null,pe=!1,Pe=!1;if(P){const Fe=ue.get(P);if(Fe.__useDefaultFramebuffer!==void 0)Q.bindFramebuffer(k.FRAMEBUFFER,null),q=!1;else if(Fe.__webglFramebuffer===void 0)ye.setupRenderTarget(P);else if(Fe.__hasExternalTextures)ye.rebindTextures(P,ue.get(P.texture).__webglTexture,ue.get(P.depthTexture).__webglTexture);else if(P.depthBuffer){const Xe=P.depthTexture;if(Fe.__boundDepthTexture!==Xe){if(Xe!==null&&ue.has(Xe)&&(P.width!==Xe.image.width||P.height!==Xe.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");ye.setupDepthRenderbuffer(P)}}const Ze=P.texture;(Ze.isData3DTexture||Ze.isDataArrayTexture||Ze.isCompressedArrayTexture)&&(Pe=!0);const tt=ue.get(P).__webglFramebuffer;P.isWebGLCubeRenderTarget?(Array.isArray(tt[B])?z=tt[B][K]:z=tt[B],pe=!0):P.samples>0&&ye.useMultisampledRTT(P)===!1?z=ue.get(P).__webglMultisampledFramebuffer:Array.isArray(tt)?z=tt[K]:z=tt,R.copy(P.viewport),L.copy(P.scissor),O=P.scissorTest}else R.copy(me).multiplyScalar(H).floor(),L.copy(Le).multiplyScalar(H).floor(),O=De;if(K!==0&&(z=OC),Q.bindFramebuffer(k.FRAMEBUFFER,z)&&q&&Q.drawBuffers(P,z),Q.viewport(R),Q.scissor(L),Q.setScissorTest(O),pe){const Fe=ue.get(P.texture);k.framebufferTexture2D(k.FRAMEBUFFER,k.COLOR_ATTACHMENT0,k.TEXTURE_CUBE_MAP_POSITIVE_X+B,Fe.__webglTexture,K)}else if(Pe){const Fe=B;for(let Ze=0;Ze=0&&B<=P.width-q&&K>=0&&K<=P.height-z&&(P.textures.length>1&&k.readBuffer(k.COLOR_ATTACHMENT0+Ue),k.readPixels(B,K,q,z,Ge.convert(tt),Ge.convert(Xe),pe))}finally{const Ze=C!==null?ue.get(C).__webglFramebuffer:null;Q.bindFramebuffer(k.FRAMEBUFFER,Ze)}}},this.readRenderTargetPixelsAsync=async function(P,B,K,q,z,pe,Pe,Ue=0){if(!(P&&P.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Fe=ue.get(P).__webglFramebuffer;if(P.isWebGLCubeRenderTarget&&Pe!==void 0&&(Fe=Fe[Pe]),Fe)if(B>=0&&B<=P.width-q&&K>=0&&K<=P.height-z){Q.bindFramebuffer(k.FRAMEBUFFER,Fe);const Ze=P.textures[Ue],tt=Ze.format,Xe=Ze.type;if(!Y.textureFormatReadable(tt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Y.textureTypeReadable(Xe))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const St=k.createBuffer();k.bindBuffer(k.PIXEL_PACK_BUFFER,St),k.bufferData(k.PIXEL_PACK_BUFFER,pe.byteLength,k.STREAM_READ),P.textures.length>1&&k.readBuffer(k.COLOR_ATTACHMENT0+Ue),k.readPixels(B,K,q,z,Ge.convert(tt),Ge.convert(Xe),0);const Lt=C!==null?ue.get(C).__webglFramebuffer:null;Q.bindFramebuffer(k.FRAMEBUFFER,Lt);const Yt=k.fenceSync(k.SYNC_GPU_COMMANDS_COMPLETE,0);return k.flush(),await eR(k,Yt,4),k.bindBuffer(k.PIXEL_PACK_BUFFER,St),k.getBufferSubData(k.PIXEL_PACK_BUFFER,0,pe),k.deleteBuffer(St),k.deleteSync(Yt),pe}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(P,B=null,K=0){const q=Math.pow(2,-K),z=Math.floor(P.image.width*q),pe=Math.floor(P.image.height*q),Pe=B!==null?B.x:0,Ue=B!==null?B.y:0;ye.setTexture2D(P,0),k.copyTexSubImage2D(k.TEXTURE_2D,K,0,0,Pe,Ue,z,pe),Q.unbindTexture()};const FC=k.createFramebuffer(),NC=k.createFramebuffer();this.copyTextureToTexture=function(P,B,K=null,q=null,z=0,pe=null){pe===null&&(z!==0?(dc("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),pe=z,z=0):pe=0);let Pe,Ue,Fe,Ze,tt,Xe,St,Lt,Yt;const Nt=P.isCompressedTexture?P.mipmaps[pe]:P.image;if(K!==null)Pe=K.max.x-K.min.x,Ue=K.max.y-K.min.y,Fe=K.isBox3?K.max.z-K.min.z:1,Ze=K.min.x,tt=K.min.y,Xe=K.isBox3?K.min.z:0;else{const wi=Math.pow(2,-z);Pe=Math.floor(Nt.width*wi),Ue=Math.floor(Nt.height*wi),P.isDataArrayTexture?Fe=Nt.depth:P.isData3DTexture?Fe=Math.floor(Nt.depth*wi):Fe=1,Ze=0,tt=0,Xe=0}q!==null?(St=q.x,Lt=q.y,Yt=q.z):(St=0,Lt=0,Yt=0);const Dt=Ge.convert(B.format),qe=Ge.convert(B.type);let $t;B.isData3DTexture?(ye.setTexture3D(B,0),$t=k.TEXTURE_3D):B.isDataArrayTexture||B.isCompressedArrayTexture?(ye.setTexture2DArray(B,0),$t=k.TEXTURE_2D_ARRAY):(ye.setTexture2D(B,0),$t=k.TEXTURE_2D),k.pixelStorei(k.UNPACK_FLIP_Y_WEBGL,B.flipY),k.pixelStorei(k.UNPACK_PREMULTIPLY_ALPHA_WEBGL,B.premultiplyAlpha),k.pixelStorei(k.UNPACK_ALIGNMENT,B.unpackAlignment);const Tt=k.getParameter(k.UNPACK_ROW_LENGTH),di=k.getParameter(k.UNPACK_IMAGE_HEIGHT),Ar=k.getParameter(k.UNPACK_SKIP_PIXELS),hi=k.getParameter(k.UNPACK_SKIP_ROWS),nl=k.getParameter(k.UNPACK_SKIP_IMAGES);k.pixelStorei(k.UNPACK_ROW_LENGTH,Nt.width),k.pixelStorei(k.UNPACK_IMAGE_HEIGHT,Nt.height),k.pixelStorei(k.UNPACK_SKIP_PIXELS,Ze),k.pixelStorei(k.UNPACK_SKIP_ROWS,tt),k.pixelStorei(k.UNPACK_SKIP_IMAGES,Xe);const Wt=P.isDataArrayTexture||P.isData3DTexture,xi=B.isDataArrayTexture||B.isData3DTexture;if(P.isDepthTexture){const wi=ue.get(P),Bn=ue.get(B),qn=ue.get(wi.__renderTarget),$f=ue.get(Bn.__renderTarget);Q.bindFramebuffer(k.READ_FRAMEBUFFER,qn.__webglFramebuffer),Q.bindFramebuffer(k.DRAW_FRAMEBUFFER,$f.__webglFramebuffer);for(let Ma=0;MaMath.PI&&(i-=jn),s<-Math.PI?s+=jn:s>Math.PI&&(s-=jn),i<=s?this._spherical.theta=Math.max(i,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(i+s)/2?Math.max(i,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let a=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const r=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),a=r!=this._spherical.radius}if(cn.setFromSpherical(this._spherical),cn.applyQuaternion(this._quatInverse),t.copy(this.target).add(cn),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let r=null;if(this.object.isPerspectiveCamera){const o=cn.length();r=this._clampDistance(o*this._scale);const l=o-r;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),a=!!l}else if(this.object.isOrthographicCamera){const o=new T(this._mouse.x,this._mouse.y,0);o.unproject(this.object);const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),a=l!==this.object.zoom;const c=new T(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(o),this.object.updateMatrixWorld(),r=cn.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;r!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(r).add(this.object.position):(Iu.origin.copy(this.object.position),Iu.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Iu.direction))Fp||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Fp||this._lastTargetPosition.distanceToSquared(this.target)>Fp?(this.dispatchEvent(Tv),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?jn/60*this.autoRotateSpeed*e:jn/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){cn.setFromMatrixColumn(t,0),cn.multiplyScalar(-e),this._panOffset.add(cn)}_panUp(e,t){this.screenSpacePanning===!0?cn.setFromMatrixColumn(t,1):(cn.setFromMatrixColumn(t,0),cn.crossVectors(this.object.up,cn)),cn.multiplyScalar(e),this._panOffset.add(cn)}_pan(e,t){const i=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;cn.copy(s).sub(this.target);let a=cn.length();a*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*a/i.clientHeight,this.object.matrix),this._panUp(2*t*a/i.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/i.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/i.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const i=this.domElement.getBoundingClientRect(),s=e-i.left,a=t-i.top,r=i.width,o=i.height;this._mouse.x=s/r*2-1,this._mouse.y=-(a/o)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(jn*this._rotateDelta.x/t.clientHeight),this._rotateUp(jn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(jn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-jn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(jn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-jn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(i,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(i,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,s=e.pageY-t.y,a=Math.sqrt(i*i+s*s);this._dollyStart.set(0,a)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const i=this._getSecondPointerPosition(e),s=.5*(e.pageX+i.x),a=.5*(e.pageY+i.y);this._rotateEnd.set(s,a)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(jn*this._rotateDelta.x/t.clientHeight),this._rotateUp(jn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(i,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,s=e.pageY-t.y,a=Math.sqrt(i*i+s*s);this._dollyEnd.set(0,a),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const r=(e.pageX+t.x)*.5,o=(e.pageY+t.y)*.5;this._updateZoomParameters(r,o)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t(O=F.indexOf(` `))&&D=C.byteLength||!(U=d(C)))&&r(1,"no header found"),(F=U.match(w))||r(3,"bad initial token"),D.valid|=1,D.programtype=F[1],D.string+=U+` `;U=d(C),U!==!1;){if(D.string+=U+` `,U.charAt(0)==="#"){D.comments+=U+` -`;continue}if((F=U.match(E))&&(D.gamma=parseFloat(F[1])),(F=U.match(R))&&(D.exposure=parseFloat(F[1])),(F=U.match(L))&&(D.valid|=2,D.format=F[1]),(F=U.match(O))&&(D.valid|=4,D.height=parseInt(F[1],10),D.width=parseInt(F[2],10)),D.valid&2&&D.valid&4)break}return D.valid&2||r(3,"missing format specifier"),D.valid&4||r(3,"missing image size specifier"),D},f=function(C,w,E){const R=w;if(R<8||R>32767||C[0]!==2||C[1]!==2||C[2]&128)return new Uint8Array(C);R!==(C[2]<<8|C[3])&&r(3,"wrong scanline width");const L=new Uint8Array(4*w*E);L.length||r(4,"unable to allocate buffer space");let O=0,D=0;const U=4*R,F=new Uint8Array(4),W=new Uint8Array(U);let H=E;for(;H>0&&DC.byteLength&&r(1),F[0]=C[D++],F[1]=C[D++],F[2]=C[D++],F[3]=C[D++],(F[0]!=2||F[1]!=2||(F[2]<<8|F[3])!=R)&&r(3,"bad rgbe scanline format");let ie=0,le;for(;ie128;if(Le&&(le-=128),(le===0||ie+le>U)&&r(3,"bad scanline data"),Le){const De=C[D++];for(let Ke=0;Ke{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(const t of e)t.dispose()}}function Yr(n){return new xf({color:0,emissive:16777215,emissiveIntensity:n})}let $T=null;function mO(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof window<"u"&&window.location?.href?window.location.href:import.meta.url}function _O(){return"./"}function gO(n){return/^[a-z][a-z\d+\-.]*:/i.test(n)||n.startsWith("//")}function yO(n=$T){const e=n==null||n===""?_O():String(n);return new URL(e,mO()).href}function Ri(n,e=$T){const t=String(n);return gO(t)?t:new URL(t.replace(/^\/+/,""),yO(e)).href}class vO{constructor(e,t={}){if(this.container=typeof e=="string"?document.getElementById(e):e,this.assetBase=t.assetBase,!this.container){console.error("Invalid container passed to SceneManager");return}this.scene=new Tc,this.scene.background=new de(8900331);const i=this.container.clientWidth,s=this.container.clientHeight;this.camera=new Qt(75,i/s,10,5e4),this.camera.position.set(0,2e3,5e3),this.renderer=new Jg({antialias:!0,preserveDrawingBuffer:t.preserveDrawingBuffer===!0}),this.renderer.setSize(i,s),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=ug,this.renderer.toneMapping=hg,this.renderer.toneMappingExposure=1,this.renderer.outputColorSpace=yt,this.container.appendChild(this.renderer.domElement),window.addEventListener("resize",()=>this.onWindowResize())}initDefaultEnvironment(){if(!this._neutralEnvTexture){const e=new bh(this.renderer);this._neutralEnvTexture=e.fromScene(new pO,.04).texture,e.dispose()}if(this.scene.environment=this._neutralEnvTexture,!this._defaultLightsAdded){const e=new Ko(16777215,1.5);e.position.set(3e3,8e3,4e3),this.scene.add(e);const t=new Pc(16777215,.4);this.scene.add(t),this._defaultLightsAdded=!0}}applyEnvironment(e){return new Promise(t=>{const i=new fO,s=Ri(e.skyboxUrl,this.assetBase);i.load(s,a=>{this.scene.background&&this.scene.background.dispose&&this.scene.background.dispose(),a.mapping=pr,this.scene.background=a,this.scene.environment=a,this.currentEnvironmentId=e.id;const r=e.rotation??{};this._skyboxBaseRotation={x:bt.degToRad(r.x??0),y:bt.degToRad(r.y??0),z:bt.degToRad(r.z??0)},this._skyboxAnimatedY=0,this._skyboxAnimation=e.animation??null,this._applySkyboxRotation(),typeof e.exposure=="number"&&(this.renderer.toneMappingExposure=e.exposure),console.log(`[SceneManager] environment applied: ${e.id}`),t(!0)},void 0,a=>{console.error(`[SceneManager] Failed to load environment "${e.id}":`,a),t(!1)})})}_applySkyboxRotation(){const e=this._skyboxBaseRotation;if(!e)return;const t=e.y+(this._skyboxAnimatedY??0);this.scene.backgroundRotation&&this.scene.backgroundRotation.set(e.x,t,e.z),this.scene.environmentRotation&&this.scene.environmentRotation.set(e.x,t,e.z)}updateSkyboxAnimation(e){const t=this._skyboxAnimation;!t||!t.enabled||!e||(this._skyboxAnimatedY=(this._skyboxAnimatedY??0)+bt.degToRad(t.speed*e),this._applySkyboxRotation())}setDefaultBackground(){this.scene.background&&this.scene.background.dispose&&this.scene.background.dispose(),this.scene.background=new de(1710638),this.initDefaultEnvironment(),this.renderer.toneMappingExposure=1,this._skyboxAnimation=null,this._skyboxBaseRotation=null,this.currentEnvironmentId=null,console.log("[SceneManager] Using neutral default environment (no skybox)")}setExposure(e){this.renderer&&(this.renderer.toneMappingExposure=e)}onWindowResize(){if(!this.container||!this.renderer)return;const e=this.container.clientWidth,t=this.container.clientHeight;this.camera.aspect=e/t,this.camera.updateProjectionMatrix(),this.renderer.setSize(e,t)}render(){this.renderer&&this.renderer.render(this.scene,this.camera)}dispose(){this.renderer&&(this.renderer.dispose(),this.renderer.domElement&&this.renderer.domElement.parentNode&&this.renderer.domElement.parentNode.removeChild(this.renderer.domElement),this.renderer=null)}}function vv(n,e){if(e===kS)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),n;if(e===mh||e===xg){let t=n.getIndex();if(t===null){const r=[],o=n.getAttribute("position");if(o!==void 0){for(let l=0;l=2.0 are supported."));return}const c=new JO(a,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let u=0;u=0&&o[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}c.setExtensions(r),c.setPlugins(o),c.parse(i,s)}parseAsync(e,t){const i=this;return new Promise(function(s,a){i.parse(e,t,s,a)})}}function bO(){let n={};return{get:function(e){return n[e]},add:function(e,t){n[e]=t},remove:function(e){delete n[e]},removeAll:function(){n={}}}}const wt={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class xO{constructor(e){this.parser=e,this.name=wt.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let i=0,s=t.length;i=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,a.source,r)}}class OO{constructor(e){this.parser=e,this.name=wt.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,i=this.parser,s=i.json,a=s.textures[e];if(!a.extensions||!a.extensions[t])return null;const r=a.extensions[t],o=s.images[r.source];let l=i.textureLoader;if(o.uri){const c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,r.source,l)}}class FO{constructor(e){this.parser=e,this.name=wt.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,i=this.parser,s=i.json,a=s.textures[e];if(!a.extensions||!a.extensions[t])return null;const r=a.extensions[t],o=s.images[r.source];let l=i.textureLoader;if(o.uri){const c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,r.source,l)}}class NO{constructor(e){this.name=wt.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,i=t.bufferViews[e];if(i.extensions&&i.extensions[this.name]){const s=i.extensions[this.name],a=this.parser.getDependency("buffer",s.buffer),r=this.parser.options.meshoptDecoder;if(!r||!r.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return a.then(function(o){const l=s.byteOffset||0,c=s.byteLength||0,u=s.count,d=s.byteStride,h=new Uint8Array(o,l,c);return r.decodeGltfBufferAsync?r.decodeGltfBufferAsync(u,d,h,s.mode,s.filter).then(function(f){return f.buffer}):r.ready.then(function(){const f=new ArrayBuffer(u*d);return r.decodeGltfBuffer(new Uint8Array(f),u,d,h,s.mode,s.filter),f})})}else return null}}class UO{constructor(e){this.name=wt.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,i=t.nodes[e];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;const s=t.meshes[i.mesh];for(const c of s.primitives)if(c.mode!==Ci.TRIANGLES&&c.mode!==Ci.TRIANGLE_STRIP&&c.mode!==Ci.TRIANGLE_FAN&&c.mode!==void 0)return null;const r=i.extensions[this.name].attributes,o=[],l={};for(const c in r)o.push(this.parser.getDependency("accessor",r[c]).then(u=>(l[c]=u,l[c])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(c=>{const u=c.pop(),d=u.isGroup?u.children:[u],h=c[0].count,f=[];for(const p of d){const g=new Ee,_=new T,m=new ht,v=new T(1,1,1),y=new of(p.geometry,p.material,h);for(let b=0;b0||n.search(/^data\:image\/jpeg/)===0?"image/jpeg":n.search(/\.webp($|\?)/i)>0||n.search(/^data\:image\/webp/)===0?"image/webp":n.search(/\.ktx2($|\?)/i)>0||n.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const ZO=new Ee;class JO{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new bO,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let i=!1,s=-1,a=!1,r=-1;if(typeof navigator<"u"){const o=navigator.userAgent;i=/^((?!chrome|android).)*safari/i.test(o)===!0;const l=o.match(/Version\/(\d+)/);s=i&&l?parseInt(l[1],10):-1,a=o.indexOf("Firefox")>-1,r=a?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||i&&s<17||a&&r<98?this.textureLoader=new wf(this.options.manager):this.textureLoader=new RT(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Kn(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const i=this,s=this.json,a=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(r){return r._markDefs&&r._markDefs()}),Promise.all(this._invokeAll(function(r){return r.beforeRoot&&r.beforeRoot()})).then(function(){return Promise.all([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])}).then(function(r){const o={scene:r[0][s.scene||0],scenes:r[0],animations:r[1],cameras:r[2],asset:s.asset,parser:i,userData:{}};return Ba(a,o,s),fs(o,s),Promise.all(i._invokeAll(function(l){return l.afterRoot&&l.afterRoot(o)})).then(function(){for(const l of o.scenes)l.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let s=0,a=t.length;s{const l=this.associations.get(r);l!=null&&this.associations.set(o,l);for(const[c,u]of r.children.entries())a(u,o.children[c])};return a(i,s),s.name+="_instance_"+e.uses[t]++,s}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let i=0;i=2&&_.setY(w,x[M*l+1]),l>=3&&_.setZ(w,x[M*l+2]),l>=4&&_.setW(w,x[M*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}_.normalized=p}return _})}loadTexture(e){const t=this.json,i=this.options,a=t.textures[e].source,r=t.images[a];let o=this.textureLoader;if(r.uri){const l=i.manager.getHandler(r.uri);l!==null&&(o=l)}return this.loadTextureImage(e,a,o)}loadTextureImage(e,t,i){const s=this,a=this.json,r=a.textures[e],o=a.images[t],l=(o.uri||o.bufferView)+":"+r.sampler;if(this.textureCache[l])return this.textureCache[l];const c=this.loadImageSource(t,i).then(function(u){u.flipY=!1,u.name=r.name||o.name||"",u.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(u.name=o.uri);const h=(a.samplers||{})[r.sampler]||{};return u.magFilter=xv[h.magFilter]||Gt,u.minFilter=xv[h.minFilter]||Ii,u.wrapS=wv[h.wrapS]||xs,u.wrapT=wv[h.wrapT]||xs,u.generateMipmaps=!u.isCompressedTexture&&u.minFilter!==hn&&u.minFilter!==Gt,s.associations.set(u,{textures:e}),u}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){const i=this,s=this.json,a=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(d=>d.clone());const r=s.images[e],o=self.URL||self.webkitURL;let l=r.uri||"",c=!1;if(r.bufferView!==void 0)l=i.getDependency("bufferView",r.bufferView).then(function(d){c=!0;const h=new Blob([d],{type:r.mimeType});return l=o.createObjectURL(h),l});else if(r.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const u=Promise.resolve(l).then(function(d){return new Promise(function(h,f){let p=h;t.isImageBitmapLoader===!0&&(p=function(g){const _=new zt(g);_.needsUpdate=!0,h(_)}),t.load(Ws.resolveURL(d,a.path),p,void 0,f)})}).then(function(d){return c===!0&&o.revokeObjectURL(l),fs(d,r),d.userData.mimeType=r.mimeType||jO(r.uri),d}).catch(function(d){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),d});return this.sourceCache[e]=u,u}assignTexture(e,t,i,s){const a=this;return this.getDependency("texture",i.index).then(function(r){if(!r)return null;if(i.texCoord!==void 0&&i.texCoord>0&&(r=r.clone(),r.channel=i.texCoord),a.extensions[wt.KHR_TEXTURE_TRANSFORM]){const o=i.extensions!==void 0?i.extensions[wt.KHR_TEXTURE_TRANSFORM]:void 0;if(o){const l=a.associations.get(r);r=a.extensions[wt.KHR_TEXTURE_TRANSFORM].extendTexture(r,o),a.associations.set(r,l)}}return s!==void 0&&(r.colorSpace=s),e[t]=r,r})}assignFinalMaterial(e){const t=e.geometry;let i=e.material;const s=t.attributes.tangent===void 0,a=t.attributes.color!==void 0,r=t.attributes.normal===void 0;if(e.isPoints){const o="PointsMaterial:"+i.uuid;let l=this.cache.get(o);l||(l=new ha,en.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,l.sizeAttenuation=!1,this.cache.add(o,l)),i=l}else if(e.isLine){const o="LineBasicMaterial:"+i.uuid;let l=this.cache.get(o);l||(l=new Pt,en.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,this.cache.add(o,l)),i=l}if(s||a||r){let o="ClonedMaterial:"+i.uuid+":";s&&(o+="derivative-tangents:"),a&&(o+="vertex-colors:"),r&&(o+="flat-shading:");let l=this.cache.get(o);l||(l=i.clone(),a&&(l.vertexColors=!0),r&&(l.flatShading=!0),s&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(o,l),this.associations.set(l,this.associations.get(i))),i=l}e.material=i}getMaterialType(){return kn}loadMaterial(e){const t=this,i=this.json,s=this.extensions,a=i.materials[e];let r;const o={},l=a.extensions||{},c=[];if(l[wt.KHR_MATERIALS_UNLIT]){const d=s[wt.KHR_MATERIALS_UNLIT];r=d.getMaterialType(),c.push(d.extendParams(o,a,t))}else{const d=a.pbrMetallicRoughness||{};if(o.color=new de(1,1,1),o.opacity=1,Array.isArray(d.baseColorFactor)){const h=d.baseColorFactor;o.color.setRGB(h[0],h[1],h[2],wn),o.opacity=h[3]}d.baseColorTexture!==void 0&&c.push(t.assignTexture(o,"map",d.baseColorTexture,yt)),o.metalness=d.metallicFactor!==void 0?d.metallicFactor:1,o.roughness=d.roughnessFactor!==void 0?d.roughnessFactor:1,d.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,"metalnessMap",d.metallicRoughnessTexture)),c.push(t.assignTexture(o,"roughnessMap",d.metallicRoughnessTexture))),r=this._invokeOne(function(h){return h.getMaterialType&&h.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(h){return h.extendMaterialParams&&h.extendMaterialParams(e,o)})))}a.doubleSided===!0&&(o.side=ut);const u=a.alphaMode||Lp.OPAQUE;if(u===Lp.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,u===Lp.MASK&&(o.alphaTest=a.alphaCutoff!==void 0?a.alphaCutoff:.5)),a.normalTexture!==void 0&&r!==je&&(c.push(t.assignTexture(o,"normalMap",a.normalTexture)),o.normalScale=new ne(1,1),a.normalTexture.scale!==void 0)){const d=a.normalTexture.scale;o.normalScale.set(d,d)}if(a.occlusionTexture!==void 0&&r!==je&&(c.push(t.assignTexture(o,"aoMap",a.occlusionTexture)),a.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=a.occlusionTexture.strength)),a.emissiveFactor!==void 0&&r!==je){const d=a.emissiveFactor;o.emissive=new de().setRGB(d[0],d[1],d[2],wn)}return a.emissiveTexture!==void 0&&r!==je&&c.push(t.assignTexture(o,"emissiveMap",a.emissiveTexture,yt)),Promise.all(c).then(function(){const d=new r(o);return a.name&&(d.name=a.name),fs(d,a),t.associations.set(d,{materials:e}),a.extensions&&Ba(s,d,a),d})}createUniqueName(e){const t=vt.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,i=this.extensions,s=this.primitiveCache;function a(o){return i[wt.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(l){return Sv(l,o,t)})}const r=[];for(let o=0,l=e.length;o0&&qO(m,a),m.name=t.createUniqueName(a.name||"mesh_"+e),fs(m,a),_.extensions&&Ba(s,m,_),t.assignFinalMaterial(m),d.push(m)}for(let f=0,p=d.length;f1?u=new Et:c.length===1?u=c[0]:u=new et,u!==c[0])for(let d=0,h=c.length;d1){const d=s.associations.get(u);s.associations.set(u,{...d})}return s.associations.get(u).nodes=e,u}),this.nodeCache[e]}loadScene(e){const t=this.extensions,i=this.json.scenes[e],s=this,a=new Et;i.name&&(a.name=s.createUniqueName(i.name)),fs(a,i),i.extensions&&Ba(t,a,i);const r=i.nodes||[],o=[];for(let l=0,c=r.length;l{const d=new Map;for(const[h,f]of s.associations)(h instanceof en||h instanceof zt)&&d.set(h,f);return u.traverse(h=>{const f=s.associations.get(h);f!=null&&d.set(h,f)}),d};return s.associations=c(a),a})}_createAnimationTracks(e,t,i,s,a){const r=[],o=e.name?e.name:e.uuid,l=[];ia[a.path]===ia.weights?e.traverse(function(h){h.morphTargetInfluences&&l.push(h.name?h.name:h.uuid)}):l.push(o);let c;switch(ia[a.path]){case ia.weights:c=ga;break;case ia.rotation:c=Ss;break;case ia.translation:case ia.scale:c=qs;break;default:i.itemSize===1?c=ga:c=qs;break}const u=s.interpolation!==void 0?WO[s.interpolation]:mr,d=this._getArrayFromAccessor(i);for(let h=0,f=l.length;h{this.parse(r,t,s)},i,s)}parse(e,t,i=()=>{}){this.decodeDracoFile(e,t,null,null,yt,i).catch(i)}decodeDracoFile(e,t,i,s,a=wn,r=()=>{}){const o={attributeIDs:i||this.defaultAttributeIDs,attributeTypes:s||this.defaultAttributeTypes,useUniqueIDs:!!i,vertexColorSpace:a};return this.decodeGeometry(e,o).then(t).catch(r)}decodeGeometry(e,t){const i=JSON.stringify(t);if(Dp.has(e)){const l=Dp.get(e);if(l.key===i)return l.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let s;const a=this.workerNextTaskID++,r=e.byteLength,o=this._getWorker(a,r).then(l=>(s=l,new Promise((c,u)=>{s._callbacks[a]={resolve:c,reject:u},s.postMessage({type:"decode",id:a,taskConfig:t,buffer:e},[e])}))).then(l=>this._createGeometry(l.geometry));return o.catch(()=>!0).then(()=>{s&&a&&this._releaseTask(s,a)}),Dp.set(e,{key:i,promise:o}),o}_createGeometry(e){const t=new $e;e.index&&t.setIndex(new ot(e.index.array,1));for(let i=0;i{i.load(e,s,void 0,a)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(i=>{const s=i[0];e||(this.decoderConfig.wasmBinary=i[1]);const a=eF.toString(),r=["/* draco decoder */",s,"","/* worker */",a.substring(a.indexOf("{")+1,a.lastIndexOf("}"))].join(` -`);this.workerSourceURL=URL.createObjectURL(new Blob([r]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.lengtha._taskLoad?-1:1});const i=this.workerPool[this.workerPool.length-1];return i._taskCosts[e]=t,i._taskLoad+=t,i})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e{const d=u.draco,h=new d.Decoder;try{const f=t(d,h,new Int8Array(l),c),p=f.attributes.map(g=>g.array.buffer);f.index&&p.push(f.index.array.buffer),self.postMessage({type:"decode",id:o.id,geometry:f},p)}catch(f){console.error(f),self.postMessage({type:"error",id:o.id,error:f.message})}finally{d.destroy(h)}});break}};function t(r,o,l,c){const u=c.attributeIDs,d=c.attributeTypes;let h,f;const p=o.GetEncodedGeometryType(l);if(p===r.TRIANGULAR_MESH)h=new r.Mesh,f=o.DecodeArrayToMesh(l,l.byteLength,h);else if(p===r.POINT_CLOUD)h=new r.PointCloud,f=o.DecodeArrayToPointCloud(l,l.byteLength,h);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!f.ok()||h.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+f.error_msg());const g={index:null,attributes:[]};for(const _ in u){const m=self[d[_]];let v,y;if(c.useUniqueIDs)y=u[_],v=o.GetAttributeByUniqueId(h,y);else{if(y=o.GetAttributeId(h,r[u[_]]),y===-1)continue;v=o.GetAttribute(h,y)}const b=s(r,o,h,_,m,v);_==="color"&&(b.vertexColorSpace=c.vertexColorSpace),g.attributes.push(b)}return p===r.TRIANGULAR_MESH&&(g.index=i(r,o,h)),r.destroy(h),g}function i(r,o,l){const u=l.num_faces()*3,d=u*4,h=r._malloc(d);o.GetTrianglesUInt32Array(l,d,h);const f=new Uint32Array(r.HEAPF32.buffer,h,u).slice();return r._free(h),{array:f,itemSize:1}}function s(r,o,l,c,u,d){const h=d.num_components(),p=l.num_points()*h,g=p*u.BYTES_PER_ELEMENT,_=a(r,u),m=r._malloc(g);o.GetAttributeDataArrayForAllPoints(l,d,_,g,m);const v=new u(r.HEAPF32.buffer,m,p).slice();return r._free(m),{name:c,array:v,itemSize:h}}function a(r,o){switch(o){case Float32Array:return r.DT_FLOAT32;case Int8Array:return r.DT_INT8;case Int16Array:return r.DT_INT16;case Int32Array:return r.DT_INT32;case Uint8Array:return r.DT_UINT8;case Uint16Array:return r.DT_UINT16;case Uint32Array:return r.DT_UINT32}}}const tF=/^[og]\s*(.+)?/,nF=/^mtllib /,iF=/^usemtl /,sF=/^usemap /,Tv=/\s+/,Mv=new T,Op=new T,Ev=new T,Cv=new T,Ti=new T,Au=new de;function aF(){const n={objects:[],object:{},vertices:[],normals:[],colors:[],uvs:[],materials:{},materialLibraries:[],startObject:function(e,t){if(this.object&&this.object.fromDeclaration===!1){this.object.name=e,this.object.fromDeclaration=t!==!1;return}const i=this.object&&typeof this.object.currentMaterial=="function"?this.object.currentMaterial():void 0;if(this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0),this.object={name:e||"",fromDeclaration:t!==!1,geometry:{vertices:[],normals:[],colors:[],uvs:[],hasUVIndices:!1},materials:[],smooth:!0,startMaterial:function(s,a){const r=this._finalize(!1);r&&(r.inherited||r.groupCount<=0)&&this.materials.splice(r.index,1);const o={index:this.materials.length,name:s||"",mtllib:Array.isArray(a)&&a.length>0?a[a.length-1]:"",smooth:r!==void 0?r.smooth:this.smooth,groupStart:r!==void 0?r.groupEnd:0,groupEnd:-1,groupCount:-1,inherited:!1,clone:function(l){const c={index:typeof l=="number"?l:this.index,name:this.name,mtllib:this.mtllib,smooth:this.smooth,groupStart:0,groupEnd:-1,groupCount:-1,inherited:!1};return c.clone=this.clone.bind(c),c}};return this.materials.push(o),o},currentMaterial:function(){if(this.materials.length>0)return this.materials[this.materials.length-1]},_finalize:function(s){const a=this.currentMaterial();if(a&&a.groupEnd===-1&&(a.groupEnd=this.geometry.vertices.length/3,a.groupCount=a.groupEnd-a.groupStart,a.inherited=!1),s&&this.materials.length>1)for(let r=this.materials.length-1;r>=0;r--)this.materials[r].groupCount<=0&&this.materials.splice(r,1);return s&&this.materials.length===0&&this.materials.push({name:"",smooth:this.smooth}),a}},i&&i.name&&typeof i.clone=="function"){const s=i.clone(0);s.inherited=!0,this.object.materials.push(s)}this.objects.push(this.object)},finalize:function(){this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0)},parseVertexIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseNormalIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseUVIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/2)*2},addVertex:function(e,t,i){const s=this.vertices,a=this.object.geometry.vertices;a.push(s[e+0],s[e+1],s[e+2]),a.push(s[t+0],s[t+1],s[t+2]),a.push(s[i+0],s[i+1],s[i+2])},addVertexPoint:function(e){const t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addVertexLine:function(e){const t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addNormal:function(e,t,i){const s=this.normals,a=this.object.geometry.normals;a.push(s[e+0],s[e+1],s[e+2]),a.push(s[t+0],s[t+1],s[t+2]),a.push(s[i+0],s[i+1],s[i+2])},addFaceNormal:function(e,t,i){const s=this.vertices,a=this.object.geometry.normals;Mv.fromArray(s,e),Op.fromArray(s,t),Ev.fromArray(s,i),Ti.subVectors(Ev,Op),Cv.subVectors(Mv,Op),Ti.cross(Cv),Ti.normalize(),a.push(Ti.x,Ti.y,Ti.z),a.push(Ti.x,Ti.y,Ti.z),a.push(Ti.x,Ti.y,Ti.z)},addColor:function(e,t,i){const s=this.colors,a=this.object.geometry.colors;s[e]!==void 0&&a.push(s[e+0],s[e+1],s[e+2]),s[t]!==void 0&&a.push(s[t+0],s[t+1],s[t+2]),s[i]!==void 0&&a.push(s[i+0],s[i+1],s[i+2])},addUV:function(e,t,i){const s=this.uvs,a=this.object.geometry.uvs;a.push(s[e+0],s[e+1]),a.push(s[t+0],s[t+1]),a.push(s[i+0],s[i+1])},addDefaultUV:function(){const e=this.object.geometry.uvs;e.push(0,0),e.push(0,0),e.push(0,0)},addUVLine:function(e){const t=this.uvs;this.object.geometry.uvs.push(t[e+0],t[e+1])},addFace:function(e,t,i,s,a,r,o,l,c){const u=this.vertices.length;let d=this.parseVertexIndex(e,u),h=this.parseVertexIndex(t,u),f=this.parseVertexIndex(i,u);if(this.addVertex(d,h,f),this.addColor(d,h,f),o!==void 0&&o!==""){const p=this.normals.length;d=this.parseNormalIndex(o,p),h=this.parseNormalIndex(l,p),f=this.parseNormalIndex(c,p),this.addNormal(d,h,f)}else this.addFaceNormal(d,h,f);if(s!==void 0&&s!==""){const p=this.uvs.length;d=this.parseUVIndex(s,p),h=this.parseUVIndex(a,p),f=this.parseUVIndex(r,p),this.addUV(d,h,f),this.object.geometry.hasUVIndices=!0}else this.addDefaultUV()},addPointGeometry:function(e){this.object.geometry.type="Points";const t=this.vertices.length;for(let i=0,s=e.length;i32767||C[0]!==2||C[1]!==2||C[2]&128)return new Uint8Array(C);R!==(C[2]<<8|C[3])&&r(3,"wrong scanline width");const L=new Uint8Array(4*w*E);L.length||r(4,"unable to allocate buffer space");let O=0,D=0;const U=4*R,F=new Uint8Array(4),W=new Uint8Array(U);let H=E;for(;H>0&&DC.byteLength&&r(1),F[0]=C[D++],F[1]=C[D++],F[2]=C[D++],F[3]=C[D++],(F[0]!=2||F[1]!=2||(F[2]<<8|F[3])!=R)&&r(3,"bad rgbe scanline format");let ie=0,le;for(;ie128;if(Le&&(le-=128),(le===0||ie+le>U)&&r(3,"bad scanline data"),Le){const De=C[D++];for(let Ke=0;Ke{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(const t of e)t.dispose()}}function jr(n){return new Cf({color:0,emissive:16777215,emissiveIntensity:n})}let QT=null;function EO(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof window<"u"&&window.location?.href?window.location.href:import.meta.url}function CO(){return"./"}function AO(n){return/^[a-z][a-z\d+\-.]*:/i.test(n)||n.startsWith("//")}function RO(n=QT){const e=n==null||n===""?CO():String(n);return new URL(e,EO()).href}function Pi(n,e=QT){const t=String(n);return AO(t)?t:new URL(t.replace(/^\/+/,""),RO(e)).href}class PO{constructor(e,t={}){if(this.container=typeof e=="string"?document.getElementById(e):e,this.assetBase=t.assetBase,!this.container){console.error("Invalid container passed to SceneManager");return}this.scene=new Ac,this.scene.background=new de(8900331);const i=this.container.clientWidth,s=this.container.clientHeight;this.camera=new Qt(75,i/s,10,5e4),this.camera.position.set(0,2e3,5e3),this.renderer=new ay({antialias:!0,preserveDrawingBuffer:t.preserveDrawingBuffer===!0}),this.renderer.setSize(i,s),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=gg,this.renderer.toneMapping=vg,this.renderer.toneMappingExposure=1,this.renderer.outputColorSpace=yt,this.container.appendChild(this.renderer.domElement),window.addEventListener("resize",()=>this.onWindowResize())}initDefaultEnvironment(){if(!this._neutralEnvTexture){const e=new Eh(this.renderer);this._neutralEnvTexture=e.fromScene(new MO,.04).texture,e.dispose()}if(this.scene.environment=this._neutralEnvTexture,!this._defaultLightsAdded){const e=new jo(16777215,1.5);e.position.set(3e3,8e3,4e3),this.scene.add(e);const t=new Dc(16777215,.4);this.scene.add(t),this._defaultLightsAdded=!0}}applyEnvironment(e){return new Promise(t=>{const i=new TO,s=Pi(e.skyboxUrl,this.assetBase);i.load(s,a=>{this.scene.background&&this.scene.background.dispose&&this.scene.background.dispose(),a.mapping=mr,this.scene.background=a,this.scene.environment=a,this.currentEnvironmentId=e.id;const r=e.rotation??{};this._skyboxBaseRotation={x:bt.degToRad(r.x??0),y:bt.degToRad(r.y??0),z:bt.degToRad(r.z??0)},this._skyboxAnimatedY=0,this._skyboxAnimation=e.animation??null,this._applySkyboxRotation(),typeof e.exposure=="number"&&(this.renderer.toneMappingExposure=e.exposure),console.log(`[SceneManager] environment applied: ${e.id}`),t(!0)},void 0,a=>{console.error(`[SceneManager] Failed to load environment "${e.id}":`,a),t(!1)})})}_applySkyboxRotation(){const e=this._skyboxBaseRotation;if(!e)return;const t=e.y+(this._skyboxAnimatedY??0);this.scene.backgroundRotation&&this.scene.backgroundRotation.set(e.x,t,e.z),this.scene.environmentRotation&&this.scene.environmentRotation.set(e.x,t,e.z)}updateSkyboxAnimation(e){const t=this._skyboxAnimation;!t||!t.enabled||!e||(this._skyboxAnimatedY=(this._skyboxAnimatedY??0)+bt.degToRad(t.speed*e),this._applySkyboxRotation())}setDefaultBackground(){this.scene.background&&this.scene.background.dispose&&this.scene.background.dispose(),this.scene.background=new de(1710638),this.initDefaultEnvironment(),this.renderer.toneMappingExposure=1,this._skyboxAnimation=null,this._skyboxBaseRotation=null,this.currentEnvironmentId=null,console.log("[SceneManager] Using neutral default environment (no skybox)")}setExposure(e){this.renderer&&(this.renderer.toneMappingExposure=e)}onWindowResize(){if(!this.container||!this.renderer)return;const e=this.container.clientWidth,t=this.container.clientHeight;this.camera.aspect=e/t,this.camera.updateProjectionMatrix(),this.renderer.setSize(e,t)}render(){this.renderer&&this.renderer.render(this.scene,this.camera)}dispose(){this.renderer&&(this.renderer.dispose(),this.renderer.domElement&&this.renderer.domElement.parentNode&&this.renderer.domElement.parentNode.removeChild(this.renderer.domElement),this.renderer=null)}}function Ev(n,e){if(e===VS)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),n;if(e===xh||e===Ag){let t=n.getIndex();if(t===null){const r=[],o=n.getAttribute("position");if(o!==void 0){for(let l=0;l=2.0 are supported."));return}const c=new cF(a,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let u=0;u=0&&o[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}c.setExtensions(r),c.setPlugins(o),c.parse(i,s)}parseAsync(e,t){const i=this;return new Promise(function(s,a){i.parse(e,t,s,a)})}}function IO(){let n={};return{get:function(e){return n[e]},add:function(e,t){n[e]=t},remove:function(e){delete n[e]},removeAll:function(){n={}}}}const wt={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class LO{constructor(e){this.parser=e,this.name=wt.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let i=0,s=t.length;i=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,a.source,r)}}class XO{constructor(e){this.parser=e,this.name=wt.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,i=this.parser,s=i.json,a=s.textures[e];if(!a.extensions||!a.extensions[t])return null;const r=a.extensions[t],o=s.images[r.source];let l=i.textureLoader;if(o.uri){const c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,r.source,l)}}class KO{constructor(e){this.parser=e,this.name=wt.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,i=this.parser,s=i.json,a=s.textures[e];if(!a.extensions||!a.extensions[t])return null;const r=a.extensions[t],o=s.images[r.source];let l=i.textureLoader;if(o.uri){const c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,r.source,l)}}class qO{constructor(e){this.name=wt.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,i=t.bufferViews[e];if(i.extensions&&i.extensions[this.name]){const s=i.extensions[this.name],a=this.parser.getDependency("buffer",s.buffer),r=this.parser.options.meshoptDecoder;if(!r||!r.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return a.then(function(o){const l=s.byteOffset||0,c=s.byteLength||0,u=s.count,d=s.byteStride,h=new Uint8Array(o,l,c);return r.decodeGltfBufferAsync?r.decodeGltfBufferAsync(u,d,h,s.mode,s.filter).then(function(f){return f.buffer}):r.ready.then(function(){const f=new ArrayBuffer(u*d);return r.decodeGltfBuffer(new Uint8Array(f),u,d,h,s.mode,s.filter),f})})}else return null}}class YO{constructor(e){this.name=wt.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,i=t.nodes[e];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;const s=t.meshes[i.mesh];for(const c of s.primitives)if(c.mode!==Ci.TRIANGLES&&c.mode!==Ci.TRIANGLE_STRIP&&c.mode!==Ci.TRIANGLE_FAN&&c.mode!==void 0)return null;const r=i.extensions[this.name].attributes,o=[],l={};for(const c in r)o.push(this.parser.getDependency("accessor",r[c]).then(u=>(l[c]=u,l[c])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(c=>{const u=c.pop(),d=u.isGroup?u.children:[u],h=c[0].count,f=[];for(const p of d){const g=new Ee,_=new T,m=new ht,v=new T(1,1,1),y=new ff(p.geometry,p.material,h);for(let b=0;b0||n.search(/^data\:image\/jpeg/)===0?"image/jpeg":n.search(/\.webp($|\?)/i)>0||n.search(/^data\:image\/webp/)===0?"image/webp":n.search(/\.ktx2($|\?)/i)>0||n.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const lF=new Ee;class cF{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new IO,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let i=!1,s=-1,a=!1,r=-1;if(typeof navigator<"u"){const o=navigator.userAgent;i=/^((?!chrome|android).)*safari/i.test(o)===!0;const l=o.match(/Version\/(\d+)/);s=i&&l?parseInt(l[1],10):-1,a=o.indexOf("Firefox")>-1,r=a?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||i&&s<17||a&&r<98?this.textureLoader=new Af(this.options.manager):this.textureLoader=new UT(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Kn(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const i=this,s=this.json,a=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(r){return r._markDefs&&r._markDefs()}),Promise.all(this._invokeAll(function(r){return r.beforeRoot&&r.beforeRoot()})).then(function(){return Promise.all([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])}).then(function(r){const o={scene:r[0][s.scene||0],scenes:r[0],animations:r[1],cameras:r[2],asset:s.asset,parser:i,userData:{}};return za(a,o,s),fs(o,s),Promise.all(i._invokeAll(function(l){return l.afterRoot&&l.afterRoot(o)})).then(function(){for(const l of o.scenes)l.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let s=0,a=t.length;s{const l=this.associations.get(r);l!=null&&this.associations.set(o,l);for(const[c,u]of r.children.entries())a(u,o.children[c])};return a(i,s),s.name+="_instance_"+e.uses[t]++,s}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let i=0;i=2&&_.setY(w,x[M*l+1]),l>=3&&_.setZ(w,x[M*l+2]),l>=4&&_.setW(w,x[M*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}_.normalized=p}return _})}loadTexture(e){const t=this.json,i=this.options,a=t.textures[e].source,r=t.images[a];let o=this.textureLoader;if(r.uri){const l=i.manager.getHandler(r.uri);l!==null&&(o=l)}return this.loadTextureImage(e,a,o)}loadTextureImage(e,t,i){const s=this,a=this.json,r=a.textures[e],o=a.images[t],l=(o.uri||o.bufferView)+":"+r.sampler;if(this.textureCache[l])return this.textureCache[l];const c=this.loadImageSource(t,i).then(function(u){u.flipY=!1,u.name=r.name||o.name||"",u.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(u.name=o.uri);const h=(a.samplers||{})[r.sampler]||{};return u.magFilter=Av[h.magFilter]||Gt,u.minFilter=Av[h.minFilter]||Li,u.wrapS=Rv[h.wrapS]||xs,u.wrapT=Rv[h.wrapT]||xs,u.generateMipmaps=!u.isCompressedTexture&&u.minFilter!==hn&&u.minFilter!==Gt,s.associations.set(u,{textures:e}),u}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){const i=this,s=this.json,a=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(d=>d.clone());const r=s.images[e],o=self.URL||self.webkitURL;let l=r.uri||"",c=!1;if(r.bufferView!==void 0)l=i.getDependency("bufferView",r.bufferView).then(function(d){c=!0;const h=new Blob([d],{type:r.mimeType});return l=o.createObjectURL(h),l});else if(r.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const u=Promise.resolve(l).then(function(d){return new Promise(function(h,f){let p=h;t.isImageBitmapLoader===!0&&(p=function(g){const _=new zt(g);_.needsUpdate=!0,h(_)}),t.load(Ws.resolveURL(d,a.path),p,void 0,f)})}).then(function(d){return c===!0&&o.revokeObjectURL(l),fs(d,r),d.userData.mimeType=r.mimeType||oF(r.uri),d}).catch(function(d){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),d});return this.sourceCache[e]=u,u}assignTexture(e,t,i,s){const a=this;return this.getDependency("texture",i.index).then(function(r){if(!r)return null;if(i.texCoord!==void 0&&i.texCoord>0&&(r=r.clone(),r.channel=i.texCoord),a.extensions[wt.KHR_TEXTURE_TRANSFORM]){const o=i.extensions!==void 0?i.extensions[wt.KHR_TEXTURE_TRANSFORM]:void 0;if(o){const l=a.associations.get(r);r=a.extensions[wt.KHR_TEXTURE_TRANSFORM].extendTexture(r,o),a.associations.set(r,l)}}return s!==void 0&&(r.colorSpace=s),e[t]=r,r})}assignFinalMaterial(e){const t=e.geometry;let i=e.material;const s=t.attributes.tangent===void 0,a=t.attributes.color!==void 0,r=t.attributes.normal===void 0;if(e.isPoints){const o="PointsMaterial:"+i.uuid;let l=this.cache.get(o);l||(l=new fa,en.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,l.sizeAttenuation=!1,this.cache.add(o,l)),i=l}else if(e.isLine){const o="LineBasicMaterial:"+i.uuid;let l=this.cache.get(o);l||(l=new Pt,en.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,this.cache.add(o,l)),i=l}if(s||a||r){let o="ClonedMaterial:"+i.uuid+":";s&&(o+="derivative-tangents:"),a&&(o+="vertex-colors:"),r&&(o+="flat-shading:");let l=this.cache.get(o);l||(l=i.clone(),a&&(l.vertexColors=!0),r&&(l.flatShading=!0),s&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(o,l),this.associations.set(l,this.associations.get(i))),i=l}e.material=i}getMaterialType(){return kn}loadMaterial(e){const t=this,i=this.json,s=this.extensions,a=i.materials[e];let r;const o={},l=a.extensions||{},c=[];if(l[wt.KHR_MATERIALS_UNLIT]){const d=s[wt.KHR_MATERIALS_UNLIT];r=d.getMaterialType(),c.push(d.extendParams(o,a,t))}else{const d=a.pbrMetallicRoughness||{};if(o.color=new de(1,1,1),o.opacity=1,Array.isArray(d.baseColorFactor)){const h=d.baseColorFactor;o.color.setRGB(h[0],h[1],h[2],wn),o.opacity=h[3]}d.baseColorTexture!==void 0&&c.push(t.assignTexture(o,"map",d.baseColorTexture,yt)),o.metalness=d.metallicFactor!==void 0?d.metallicFactor:1,o.roughness=d.roughnessFactor!==void 0?d.roughnessFactor:1,d.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,"metalnessMap",d.metallicRoughnessTexture)),c.push(t.assignTexture(o,"roughnessMap",d.metallicRoughnessTexture))),r=this._invokeOne(function(h){return h.getMaterialType&&h.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(h){return h.extendMaterialParams&&h.extendMaterialParams(e,o)})))}a.doubleSided===!0&&(o.side=ut);const u=a.alphaMode||Up.OPAQUE;if(u===Up.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,u===Up.MASK&&(o.alphaTest=a.alphaCutoff!==void 0?a.alphaCutoff:.5)),a.normalTexture!==void 0&&r!==je&&(c.push(t.assignTexture(o,"normalMap",a.normalTexture)),o.normalScale=new ne(1,1),a.normalTexture.scale!==void 0)){const d=a.normalTexture.scale;o.normalScale.set(d,d)}if(a.occlusionTexture!==void 0&&r!==je&&(c.push(t.assignTexture(o,"aoMap",a.occlusionTexture)),a.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=a.occlusionTexture.strength)),a.emissiveFactor!==void 0&&r!==je){const d=a.emissiveFactor;o.emissive=new de().setRGB(d[0],d[1],d[2],wn)}return a.emissiveTexture!==void 0&&r!==je&&c.push(t.assignTexture(o,"emissiveMap",a.emissiveTexture,yt)),Promise.all(c).then(function(){const d=new r(o);return a.name&&(d.name=a.name),fs(d,a),t.associations.set(d,{materials:e}),a.extensions&&za(s,d,a),d})}createUniqueName(e){const t=vt.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,i=this.extensions,s=this.primitiveCache;function a(o){return i[wt.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(l){return Pv(l,o,t)})}const r=[];for(let o=0,l=e.length;o0&&aF(m,a),m.name=t.createUniqueName(a.name||"mesh_"+e),fs(m,a),_.extensions&&za(s,m,_),t.assignFinalMaterial(m),d.push(m)}for(let f=0,p=d.length;f1?u=new Et:c.length===1?u=c[0]:u=new et,u!==c[0])for(let d=0,h=c.length;d1){const d=s.associations.get(u);s.associations.set(u,{...d})}return s.associations.get(u).nodes=e,u}),this.nodeCache[e]}loadScene(e){const t=this.extensions,i=this.json.scenes[e],s=this,a=new Et;i.name&&(a.name=s.createUniqueName(i.name)),fs(a,i),i.extensions&&za(t,a,i);const r=i.nodes||[],o=[];for(let l=0,c=r.length;l{const d=new Map;for(const[h,f]of s.associations)(h instanceof en||h instanceof zt)&&d.set(h,f);return u.traverse(h=>{const f=s.associations.get(h);f!=null&&d.set(h,f)}),d};return s.associations=c(a),a})}_createAnimationTracks(e,t,i,s,a){const r=[],o=e.name?e.name:e.uuid,l=[];ia[a.path]===ia.weights?e.traverse(function(h){h.morphTargetInfluences&&l.push(h.name?h.name:h.uuid)}):l.push(o);let c;switch(ia[a.path]){case ia.weights:c=ya;break;case ia.rotation:c=Ss;break;case ia.translation:case ia.scale:c=qs;break;default:i.itemSize===1?c=ya:c=qs;break}const u=s.interpolation!==void 0?nF[s.interpolation]:_r,d=this._getArrayFromAccessor(i);for(let h=0,f=l.length;h{this.parse(r,t,s)},i,s)}parse(e,t,i=()=>{}){this.decodeDracoFile(e,t,null,null,yt,i).catch(i)}decodeDracoFile(e,t,i,s,a=wn,r=()=>{}){const o={attributeIDs:i||this.defaultAttributeIDs,attributeTypes:s||this.defaultAttributeTypes,useUniqueIDs:!!i,vertexColorSpace:a};return this.decodeGeometry(e,o).then(t).catch(r)}decodeGeometry(e,t){const i=JSON.stringify(t);if(zp.has(e)){const l=zp.get(e);if(l.key===i)return l.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let s;const a=this.workerNextTaskID++,r=e.byteLength,o=this._getWorker(a,r).then(l=>(s=l,new Promise((c,u)=>{s._callbacks[a]={resolve:c,reject:u},s.postMessage({type:"decode",id:a,taskConfig:t,buffer:e},[e])}))).then(l=>this._createGeometry(l.geometry));return o.catch(()=>!0).then(()=>{s&&a&&this._releaseTask(s,a)}),zp.set(e,{key:i,promise:o}),o}_createGeometry(e){const t=new $e;e.index&&t.setIndex(new lt(e.index.array,1));for(let i=0;i{i.load(e,s,void 0,a)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(i=>{const s=i[0];e||(this.decoderConfig.wasmBinary=i[1]);const a=dF.toString(),r=["/* draco decoder */",s,"","/* worker */",a.substring(a.indexOf("{")+1,a.lastIndexOf("}"))].join(` +`);this.workerSourceURL=URL.createObjectURL(new Blob([r]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.lengtha._taskLoad?-1:1});const i=this.workerPool[this.workerPool.length-1];return i._taskCosts[e]=t,i._taskLoad+=t,i})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e{const d=u.draco,h=new d.Decoder;try{const f=t(d,h,new Int8Array(l),c),p=f.attributes.map(g=>g.array.buffer);f.index&&p.push(f.index.array.buffer),self.postMessage({type:"decode",id:o.id,geometry:f},p)}catch(f){console.error(f),self.postMessage({type:"error",id:o.id,error:f.message})}finally{d.destroy(h)}});break}};function t(r,o,l,c){const u=c.attributeIDs,d=c.attributeTypes;let h,f;const p=o.GetEncodedGeometryType(l);if(p===r.TRIANGULAR_MESH)h=new r.Mesh,f=o.DecodeArrayToMesh(l,l.byteLength,h);else if(p===r.POINT_CLOUD)h=new r.PointCloud,f=o.DecodeArrayToPointCloud(l,l.byteLength,h);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!f.ok()||h.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+f.error_msg());const g={index:null,attributes:[]};for(const _ in u){const m=self[d[_]];let v,y;if(c.useUniqueIDs)y=u[_],v=o.GetAttributeByUniqueId(h,y);else{if(y=o.GetAttributeId(h,r[u[_]]),y===-1)continue;v=o.GetAttribute(h,y)}const b=s(r,o,h,_,m,v);_==="color"&&(b.vertexColorSpace=c.vertexColorSpace),g.attributes.push(b)}return p===r.TRIANGULAR_MESH&&(g.index=i(r,o,h)),r.destroy(h),g}function i(r,o,l){const u=l.num_faces()*3,d=u*4,h=r._malloc(d);o.GetTrianglesUInt32Array(l,d,h);const f=new Uint32Array(r.HEAPF32.buffer,h,u).slice();return r._free(h),{array:f,itemSize:1}}function s(r,o,l,c,u,d){const h=d.num_components(),p=l.num_points()*h,g=p*u.BYTES_PER_ELEMENT,_=a(r,u),m=r._malloc(g);o.GetAttributeDataArrayForAllPoints(l,d,_,g,m);const v=new u(r.HEAPF32.buffer,m,p).slice();return r._free(m),{name:c,array:v,itemSize:h}}function a(r,o){switch(o){case Float32Array:return r.DT_FLOAT32;case Int8Array:return r.DT_INT8;case Int16Array:return r.DT_INT16;case Int32Array:return r.DT_INT32;case Uint8Array:return r.DT_UINT8;case Uint16Array:return r.DT_UINT16;case Uint32Array:return r.DT_UINT32}}}const hF=/^[og]\s*(.+)?/,fF=/^mtllib /,pF=/^usemtl /,mF=/^usemap /,Iv=/\s+/,Lv=new T,Hp=new T,kv=new T,Dv=new T,Ti=new T,Lu=new de;function _F(){const n={objects:[],object:{},vertices:[],normals:[],colors:[],uvs:[],materials:{},materialLibraries:[],startObject:function(e,t){if(this.object&&this.object.fromDeclaration===!1){this.object.name=e,this.object.fromDeclaration=t!==!1;return}const i=this.object&&typeof this.object.currentMaterial=="function"?this.object.currentMaterial():void 0;if(this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0),this.object={name:e||"",fromDeclaration:t!==!1,geometry:{vertices:[],normals:[],colors:[],uvs:[],hasUVIndices:!1},materials:[],smooth:!0,startMaterial:function(s,a){const r=this._finalize(!1);r&&(r.inherited||r.groupCount<=0)&&this.materials.splice(r.index,1);const o={index:this.materials.length,name:s||"",mtllib:Array.isArray(a)&&a.length>0?a[a.length-1]:"",smooth:r!==void 0?r.smooth:this.smooth,groupStart:r!==void 0?r.groupEnd:0,groupEnd:-1,groupCount:-1,inherited:!1,clone:function(l){const c={index:typeof l=="number"?l:this.index,name:this.name,mtllib:this.mtllib,smooth:this.smooth,groupStart:0,groupEnd:-1,groupCount:-1,inherited:!1};return c.clone=this.clone.bind(c),c}};return this.materials.push(o),o},currentMaterial:function(){if(this.materials.length>0)return this.materials[this.materials.length-1]},_finalize:function(s){const a=this.currentMaterial();if(a&&a.groupEnd===-1&&(a.groupEnd=this.geometry.vertices.length/3,a.groupCount=a.groupEnd-a.groupStart,a.inherited=!1),s&&this.materials.length>1)for(let r=this.materials.length-1;r>=0;r--)this.materials[r].groupCount<=0&&this.materials.splice(r,1);return s&&this.materials.length===0&&this.materials.push({name:"",smooth:this.smooth}),a}},i&&i.name&&typeof i.clone=="function"){const s=i.clone(0);s.inherited=!0,this.object.materials.push(s)}this.objects.push(this.object)},finalize:function(){this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0)},parseVertexIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseNormalIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseUVIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/2)*2},addVertex:function(e,t,i){const s=this.vertices,a=this.object.geometry.vertices;a.push(s[e+0],s[e+1],s[e+2]),a.push(s[t+0],s[t+1],s[t+2]),a.push(s[i+0],s[i+1],s[i+2])},addVertexPoint:function(e){const t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addVertexLine:function(e){const t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addNormal:function(e,t,i){const s=this.normals,a=this.object.geometry.normals;a.push(s[e+0],s[e+1],s[e+2]),a.push(s[t+0],s[t+1],s[t+2]),a.push(s[i+0],s[i+1],s[i+2])},addFaceNormal:function(e,t,i){const s=this.vertices,a=this.object.geometry.normals;Lv.fromArray(s,e),Hp.fromArray(s,t),kv.fromArray(s,i),Ti.subVectors(kv,Hp),Dv.subVectors(Lv,Hp),Ti.cross(Dv),Ti.normalize(),a.push(Ti.x,Ti.y,Ti.z),a.push(Ti.x,Ti.y,Ti.z),a.push(Ti.x,Ti.y,Ti.z)},addColor:function(e,t,i){const s=this.colors,a=this.object.geometry.colors;s[e]!==void 0&&a.push(s[e+0],s[e+1],s[e+2]),s[t]!==void 0&&a.push(s[t+0],s[t+1],s[t+2]),s[i]!==void 0&&a.push(s[i+0],s[i+1],s[i+2])},addUV:function(e,t,i){const s=this.uvs,a=this.object.geometry.uvs;a.push(s[e+0],s[e+1]),a.push(s[t+0],s[t+1]),a.push(s[i+0],s[i+1])},addDefaultUV:function(){const e=this.object.geometry.uvs;e.push(0,0),e.push(0,0),e.push(0,0)},addUVLine:function(e){const t=this.uvs;this.object.geometry.uvs.push(t[e+0],t[e+1])},addFace:function(e,t,i,s,a,r,o,l,c){const u=this.vertices.length;let d=this.parseVertexIndex(e,u),h=this.parseVertexIndex(t,u),f=this.parseVertexIndex(i,u);if(this.addVertex(d,h,f),this.addColor(d,h,f),o!==void 0&&o!==""){const p=this.normals.length;d=this.parseNormalIndex(o,p),h=this.parseNormalIndex(l,p),f=this.parseNormalIndex(c,p),this.addNormal(d,h,f)}else this.addFaceNormal(d,h,f);if(s!==void 0&&s!==""){const p=this.uvs.length;d=this.parseUVIndex(s,p),h=this.parseUVIndex(a,p),f=this.parseUVIndex(r,p),this.addUV(d,h,f),this.object.geometry.hasUVIndices=!0}else this.addDefaultUV()},addPointGeometry:function(e){this.object.geometry.type="Points";const t=this.vertices.length;for(let i=0,s=e.length;i=7?(Au.setRGB(parseFloat(d[4]),parseFloat(d[5]),parseFloat(d[6]),yt),t.colors.push(Au.r,Au.g,Au.b)):t.colors.push(void 0,void 0,void 0);break;case"vn":t.normals.push(parseFloat(d[1]),parseFloat(d[2]),parseFloat(d[3]));break;case"vt":t.uvs.push(parseFloat(d[1]),parseFloat(d[2]));break}}else if(u==="f"){const h=c.slice(1).trim().split(Tv),f=[];for(let g=0,_=h.length;g<_;g++){const m=h[g];if(m.length>0){const v=m.split("/");f.push(v)}}const p=f[0];for(let g=1,_=f.length-1;g<_;g++){const m=f[g],v=f[g+1];t.addFace(p[0],m[0],v[0],p[1],m[1],v[1],p[2],m[2],v[2])}}else if(u==="l"){const d=c.substring(1).trim().split(" ");let h=[];const f=[];if(c.indexOf("/")===-1)h=d;else for(let p=0,g=d.length;p1){const h=s[1].trim().toLowerCase();t.object.smooth=h!=="0"&&h!=="off"}else t.object.smooth=!0;const d=t.object.currentMaterial();d&&(d.smooth=t.object.smooth)}else{if(c==="\0")continue;console.warn('THREE.OBJLoader: Unexpected line: "'+c+'"')}}t.finalize();const a=new Et;if(a.materialLibraries=[].concat(t.materialLibraries),!(t.objects.length===1&&t.objects[0].geometry.vertices.length===0)===!0)for(let o=0,l=t.objects.length;o0&&g.setAttribute("normal",new Ce(u.normals,3)),u.colors.length>0&&(p=!0,g.setAttribute("color",new Ce(u.colors,3))),u.hasUVIndices===!0&&g.setAttribute("uv",new Ce(u.uvs,2));const _=[];for(let v=0,y=d.length;v1){for(let v=0,y=d.length;v0){const o=new ha({size:1,sizeAttenuation:!1}),l=new $e;l.setAttribute("position",new Ce(t.vertices,3)),t.colors.length>0&&t.colors[0]!==void 0&&(l.setAttribute("color",new Ce(t.colors,3)),o.vertexColors=!0);const c=new hr(l,o);a.add(c)}return a}}const Fp=new Map;async function oF(n,e){const t=Ri("models/stadium/stadium.glb",e);let i=Fp.get(t);return i||(i=n.loadAsync(t).then(s=>{const a=s.scene;return lF(a),a}).catch(s=>{throw Fp.delete(t),s}),Fp.set(t,i)),i}function lF(n){const e=["Sol_Trait_T0","Sol_Trait_T1","Milieu_Forme","Milieu_Forme.001","cage_T0","cage_T1","Couleur_Hexagone_T0","Couleur_Hexagone_T1","wall_gradient_color_2","wall_gradient_color_2.001","Fond_BackBoard_Transparent","dégradé_transparent_T0","dégradé_transparent_T1","grid_transperant","Detail_Milieu","Detail_Milieu.001"],t=["Glow","Glass"],i=["Plafond_Hexagone_T0","Plafond_Hexagone_T1","Plafond_Transparent"];n.traverse(s=>{if(!s.isMesh)return;s.receiveShadow=!0,s.castShadow=!i.includes(s.name),t.some(r=>s.name.includes(r))&&(console.log(`[ArenaManager] Disabling frustum culling for: ${s.name}`),s.frustumCulled=!1),s.material&&/^Hexagone_T[01]$/.test(s.material.name??"")&&(s.material=s.material.clone(),s.material.transparent=!0,s.material.opacity=.18,s.material.depthWrite=!1,s.renderOrder=1),s.material&&s.material.name==="bannière_pub"&&(s.visible=!1),s.material&&s.material.name==="Sol_Hexagone"&&(s.material=s.material.clone(),s.material.color.setScalar(.35),s.material.metalness=0,s.material.roughness=1),s.material&&s.material.name&&e.includes(s.material.name)&&(console.log(`[ArenaManager] Fixing visibility for: ${s.name} (material: ${s.material.name})`),s.material=s.material.clone(),s.material.side=ut,s.material.depthWrite=!1,s.renderOrder=1,s.frustumCulled=!1)})}class cF{constructor(e,t={}){this.scene=e,this.assetBase=t.assetBase,this.arenaMeshes=[],this.drawingCollider=null,this.drawingColliderMeshes=[],this.arenaDecorMesh=null,this.showArenaDecor=!0,this.dracoLoader=new KT,this.dracoLoader.setDecoderPath(Ri("draco/",this.assetBase)),this.gltfLoader=new ey,this.gltfLoader.setDRACOLoader(this.dracoLoader)}async loadArenaMeshes(){try{console.log("Loading arena mesh...");const t=(await oF(this.gltfLoader,this.assetBase)).clone(!0);t.traverse(i=>{i.isMesh&&this.arenaMeshes.push(i)}),console.log(`[ArenaManager] Collected ${this.arenaMeshes.length} meshes for raycasting`),this.scene.add(t),console.log("Arena mesh loaded successfully with correct orientation")}catch(e){console.error("Error loading arena mesh:",e);const t=new Nn(10240,8192),i=new kn({color:3355443,side:ut}),s=new Se(t,i);s.rotation.x=-Math.PI/2,s.receiveShadow=!0,this.scene.add(s),this.arenaMeshes.push(s)}}getArenaMeshes(){return this.arenaMeshes}getDrawingColliderMeshes(){return this.drawingColliderMeshes}async loadDrawingCollider(e=!1){try{console.log("[ArenaManager] Loading drawing collider...");const i=await new rF().loadAsync(Ri("models/stadium/DrawingArena.obj",this.assetBase));i.rotation.x=Math.PI/2,i.rotation.y=Math.PI,i.scale.setScalar(.99),i.position.y=20,i.traverse(s=>{s.isMesh&&(this.drawingColliderMeshes.push(s),s.castShadow=!1,s.receiveShadow=!1,e?s.material=new je({color:65280,transparent:!0,opacity:.7,side:ut}):s.material=new je({visible:!1}))}),this.drawingCollider=i,this.scene.add(i),console.log(`[ArenaManager] Drawing collider loaded with ${this.drawingColliderMeshes.length} meshes`)}catch(t){console.error("[ArenaManager] Failed to load drawing collider:",t)}}setDrawingColliderVisible(e){for(const t of this.drawingColliderMeshes)e?t.material=new je({color:65280,wireframe:!0,transparent:!0,opacity:.5}):t.material=new je({visible:!1})}async loadArenaDecor(e=!0){try{console.log("[ArenaManager] Loading arena decoration mesh...");const t=await this.gltfLoader.loadAsync(Ri("models/stadium/arene.glb",this.assetBase));this.arenaDecorMesh=t.scene,this.showArenaDecor=e,this.arenaDecorMesh.traverse(i=>{i.isMesh&&(i.receiveShadow=!0,i.castShadow=!0)}),this.arenaDecorMesh.visible=e,this.scene.add(this.arenaDecorMesh),console.log(`[ArenaManager] Arena decoration loaded, visible: ${e}`)}catch(t){console.error("[ArenaManager] Failed to load arena decoration:",t)}}setArenaDecorVisible(e){this.showArenaDecor=e,this.arenaDecorMesh&&(this.arenaDecorMesh.visible=e,console.log(`[ArenaManager] Arena decoration visibility set to: ${e}`))}isArenaDecorVisible(){return this.showArenaDecor}}var Pi=Uint8Array,lo=Uint16Array,uF=Int32Array,qT=new Pi([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),YT=new Pi([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),dF=new Pi([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),jT=function(n,e){for(var t=new lo(31),i=0;i<31;++i)t[i]=e+=1<>1|(Ut&21845)<<1;sa=(sa&52428)>>2|(sa&13107)<<2,sa=(sa&61680)>>4|(sa&3855)<<4,a_[Ut]=((sa&65280)>>8|(sa&255)<<8)>>1}var ql=(function(n,e,t){for(var i=n.length,s=0,a=new lo(e);s>l]=c}else for(o=new lo(i),s=0;s>15-n[s]);return o}),Ic=new Pi(288);for(var Ut=0;Ut<144;++Ut)Ic[Ut]=8;for(var Ut=144;Ut<256;++Ut)Ic[Ut]=9;for(var Ut=256;Ut<280;++Ut)Ic[Ut]=7;for(var Ut=280;Ut<288;++Ut)Ic[Ut]=8;var QT=new Pi(32);for(var Ut=0;Ut<32;++Ut)QT[Ut]=5;var mF=ql(Ic,9,1),_F=ql(QT,5,1),Np=function(n){for(var e=n[0],t=1;te&&(e=n[t]);return e},zi=function(n,e,t){var i=e/8|0;return(n[i]|n[i+1]<<8)>>(e&7)&t},Up=function(n,e){var t=e/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},gF=function(n){return(n+7)/8|0},yF=function(n,e,t){return(t==null||t>n.length)&&(t=n.length),new Pi(n.subarray(e,t))},vF=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Ki=function(n,e,t){var i=new Error(e||vF[n]);if(i.code=n,Error.captureStackTrace&&Error.captureStackTrace(i,Ki),!t)throw i;return i},bF=function(n,e,t,i){var s=n.length,a=0;if(!s||e.f&&!e.l)return t||new Pi(0);var r=!t,o=r||e.i!=2,l=e.i;r&&(t=new Pi(s*3));var c=function(we){var Re=t.length;if(we>Re){var k=new Pi(Math.max(Re*2,we));k.set(t),t=k}},u=e.f||0,d=e.p||0,h=e.b||0,f=e.l,p=e.d,g=e.m,_=e.n,m=s*8;do{if(!f){u=zi(n,d,1);var v=zi(n,d+1,3);if(d+=3,v)if(v==1)f=mF,p=_F,g=9,_=5;else if(v==2){var x=zi(n,d,31)+257,M=zi(n,d+10,15)+4,C=x+zi(n,d+5,31)+1;d+=14;for(var w=new Pi(C),E=new Pi(19),R=0;R>4;if(y<16)w[R++]=y;else{var F=0,W=0;for(y==16?(W=3+zi(n,d,3),d+=2,F=w[R-1]):y==17?(W=3+zi(n,d,7),d+=3):y==18&&(W=11+zi(n,d,127),d+=7);W--;)w[R++]=F}}var H=w.subarray(0,x),ie=w.subarray(x);g=Np(H),_=Np(ie),f=ql(H,g,1),p=ql(ie,_,1)}else Ki(1);else{var y=gF(d)+4,b=n[y-4]|n[y-3]<<8,S=y+b;if(S>s){l&&Ki(0);break}o&&c(h+b),t.set(n.subarray(y,S),h),e.b=h+=b,e.p=d=S*8,e.f=u;continue}if(d>m){l&&Ki(0);break}}o&&c(h+131072);for(var le=(1<>4;if(d+=F&15,d>m){l&&Ki(0);break}if(F||Ki(2),De<256)t[h++]=De;else if(De==256){Le=d,f=null;break}else{var Ke=De-254;if(De>264){var R=De-257,Oe=qT[R];Ke=zi(n,d,(1<>4;Z||Ki(3),d+=Z&15;var ie=pF[ae];if(ae>3){var Oe=YT[ae];ie+=Up(n,d)&(1<m){l&&Ki(0);break}o&&c(h+131072);var Te=h+Ke;if(h>4>7||(n[0]<<8|n[1])%31)&&Ki(6,"invalid zlib data"),(n[1]>>5&1)==1&&Ki(6,"invalid zlib data: "+(n[1]&32?"need":"unexpected")+" dictionary"),(n[1]>>3&4)+2};function SF(n,e){return bF(n.subarray(wF(n),-4),{i:2},e,e)}var TF=typeof TextDecoder<"u"&&new TextDecoder,MF=0;try{TF.decode(xF,{stream:!0}),MF=1}catch{}function eM(n,e,t){const i=t.length-n-1;if(e>=t[i])return i-1;if(e<=t[n])return n;let s=n,a=i,r=Math.floor((s+a)/2);for(;e=t[r+1];)e=g&&(p[f][0]=p[h][0]/o[v+1][m],_=p[f][0]*o[m][v]);const y=m>=-1?1:-m,b=d-1<=v?g-1:t-d;for(let x=y;x<=b;++x)p[f][x]=(p[h][x]-p[h][x-1])/o[v+1][m+x],_+=p[f][x]*o[m+x][v];d<=v&&(p[f][g]=-p[h][g-1]/o[v+1][d],_+=p[f][g]*o[d][v]),r[g][d]=_;const S=h;h=f,f=S}}let u=t;for(let d=1;d<=i;++d){for(let h=0;h<=t;++h)r[d][h]*=u;u*=t-d}return r}function RF(n,e,t,i,s){const a=st.toArray()),e.startKnot=this.startKnot,e.endKnot=this.endKnot,e}fromJSON(e){return super.fromJSON(e),this.degree=e.degree,this.knots=[...e.knots],this.controlPoints=e.controlPoints.map(t=>new Ye(t[0],t[1],t[2],t[3])),this.startKnot=e.startKnot,this.endKnot=e.endKnot,this}}let gt,Jt,Vn;class DF extends ln{constructor(e){super(e)}load(e,t,i,s){const a=this,r=a.path===""?Ws.extractUrlBase(e):a.path,o=new Kn(this.manager);o.setPath(a.path),o.setResponseType("arraybuffer"),o.setRequestHeader(a.requestHeader),o.setWithCredentials(a.withCredentials),o.load(e,function(l){try{t(a.parse(l,r))}catch(c){s?s(c):console.error(c),a.manager.itemError(e)}},i,s)}parse(e,t){if(zF(e))gt=new BF().parse(e);else{const s=iM(e);if(!HF(s))throw new Error("THREE.FBXLoader: Unknown format.");if(Rv(s)<7e3)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+Rv(s));gt=new UF().parse(s)}const i=new wf(this.manager).setPath(this.resourcePath||t).setCrossOrigin(this.crossOrigin);return new OF(i,this.manager).parse(gt)}}class OF{constructor(e,t){this.textureLoader=e,this.manager=t}parse(){Jt=this.parseConnections();const e=this.parseImages(),t=this.parseTextures(e),i=this.parseMaterials(t),s=this.parseDeformers(),a=new FF().parse(s);return this.parseScene(s,a,i),Vn}parseConnections(){const e=new Map;return"Connections"in gt&>.Connections.connections.forEach(function(i){const s=i[0],a=i[1],r=i[2];e.has(s)||e.set(s,{parents:[],children:[]});const o={ID:a,relationship:r};e.get(s).parents.push(o),e.has(a)||e.set(a,{parents:[],children:[]});const l={ID:s,relationship:r};e.get(a).children.push(l)}),e}parseImages(){const e={},t={};if("Video"in gt.Objects){const i=gt.Objects.Video;for(const s in i){const a=i[s],r=parseInt(s);if(e[r]=a.RelativeFilename||a.Filename,"Content"in a){const o=a.Content instanceof ArrayBuffer&&a.Content.byteLength>0,l=typeof a.Content=="string"&&a.Content!=="";if(o||l){const c=this.parseImage(i[s]);t[a.RelativeFilename||a.Filename]=c}}}}for(const i in e){const s=e[i];t[s]!==void 0?e[i]=t[s]:e[i]=e[i].split("\\").pop()}return e}parseImage(e){const t=e.Content,i=e.RelativeFilename||e.Filename,s=i.slice(i.lastIndexOf(".")+1).toLowerCase();let a;switch(s){case"bmp":a="image/bmp";break;case"jpg":case"jpeg":a="image/jpeg";break;case"png":a="image/png";break;case"tif":a="image/tiff";break;case"tga":this.manager.getHandler(".tga")===null&&console.warn("FBXLoader: TGA loader not found, skipping ",i),a="image/tga";break;case"webp":a="image/webp";break;default:console.warn('FBXLoader: Image type "'+s+'" is not supported.');return}if(typeof t=="string")return"data:"+a+";base64,"+t;{const r=new Uint8Array(t);return window.URL.createObjectURL(new Blob([r],{type:a}))}}parseTextures(e){const t=new Map;if("Texture"in gt.Objects){const i=gt.Objects.Texture;for(const s in i){const a=this.parseTexture(i[s],e);t.set(parseInt(s),a)}}return t}parseTexture(e,t){const i=this.loadTexture(e,t);i.ID=e.id,i.name=e.attrName;const s=e.WrapModeU,a=e.WrapModeV,r=s!==void 0?s.value:0,o=a!==void 0?a.value:0;if(i.wrapS=r===0?xs:Wn,i.wrapT=o===0?xs:Wn,"Scaling"in e){const l=e.Scaling.value;i.repeat.x=l[0],i.repeat.y=l[1]}if("Translation"in e){const l=e.Translation.value;i.offset.x=l[0],i.offset.y=l[1]}return i}loadTexture(e,t){const i=e.FileName.split(".").pop().toLowerCase();let s=this.manager.getHandler(`.${i}`);s===null&&(s=this.textureLoader);const a=s.path;a||s.setPath(this.textureLoader.path);const r=Jt.get(e.id).children;let o;if(r!==void 0&&r.length>0&&t[r[0].ID]!==void 0&&(o=t[r[0].ID],(o.indexOf("blob:")===0||o.indexOf("data:")===0)&&s.setPath(void 0)),o===void 0)return console.warn("FBXLoader: Undefined filename, creating placeholder texture."),new zt;const l=s.load(o);return s.setPath(a),l}parseMaterials(e){const t=new Map;if("Material"in gt.Objects){const i=gt.Objects.Material;for(const s in i){const a=this.parseMaterial(i[s],e);a!==null&&t.set(parseInt(s),a)}}return t}parseMaterial(e,t){const i=e.id,s=e.attrName;let a=e.ShadingModel;if(typeof a=="object"&&(a=a.value),!Jt.has(i))return null;const r=this.parseParameters(e,t,i);let o;switch(a.toLowerCase()){case"phong":o=new ir;break;case"lambert":o=new xf;break;default:console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.',a),o=new ir;break}return o.setValues(r),o.name=s,o}parseParameters(e,t,i){const s={};e.BumpFactor&&(s.bumpScale=e.BumpFactor.value),e.Diffuse?s.color=rt.colorSpaceToWorking(new de().fromArray(e.Diffuse.value),yt):e.DiffuseColor&&(e.DiffuseColor.type==="Color"||e.DiffuseColor.type==="ColorRGB")&&(s.color=rt.colorSpaceToWorking(new de().fromArray(e.DiffuseColor.value),yt)),e.DisplacementFactor&&(s.displacementScale=e.DisplacementFactor.value),e.Emissive?s.emissive=rt.colorSpaceToWorking(new de().fromArray(e.Emissive.value),yt):e.EmissiveColor&&(e.EmissiveColor.type==="Color"||e.EmissiveColor.type==="ColorRGB")&&(s.emissive=rt.colorSpaceToWorking(new de().fromArray(e.EmissiveColor.value),yt)),e.EmissiveFactor&&(s.emissiveIntensity=parseFloat(e.EmissiveFactor.value)),s.opacity=1-(e.TransparencyFactor?parseFloat(e.TransparencyFactor.value):0),(s.opacity===1||s.opacity===0)&&(s.opacity=e.Opacity?parseFloat(e.Opacity.value):null,s.opacity===null&&(s.opacity=1-(e.TransparentColor?parseFloat(e.TransparentColor.value[0]):0))),s.opacity<1&&(s.transparent=!0),e.ReflectionFactor&&(s.reflectivity=e.ReflectionFactor.value),e.Shininess&&(s.shininess=e.Shininess.value),e.Specular?s.specular=rt.colorSpaceToWorking(new de().fromArray(e.Specular.value),yt):e.SpecularColor&&e.SpecularColor.type==="Color"&&(s.specular=rt.colorSpaceToWorking(new de().fromArray(e.SpecularColor.value),yt));const a=this;return Jt.get(i).children.forEach(function(r){const o=r.relationship;switch(o){case"Bump":s.bumpMap=a.getTexture(t,r.ID);break;case"Maya|TEX_ao_map":s.aoMap=a.getTexture(t,r.ID);break;case"DiffuseColor":case"Maya|TEX_color_map":s.map=a.getTexture(t,r.ID),s.map!==void 0&&(s.map.colorSpace=yt);break;case"DisplacementColor":s.displacementMap=a.getTexture(t,r.ID);break;case"EmissiveColor":s.emissiveMap=a.getTexture(t,r.ID),s.emissiveMap!==void 0&&(s.emissiveMap.colorSpace=yt);break;case"NormalMap":case"Maya|TEX_normal_map":s.normalMap=a.getTexture(t,r.ID);break;case"ReflectionColor":s.envMap=a.getTexture(t,r.ID),s.envMap!==void 0&&(s.envMap.mapping=pr,s.envMap.colorSpace=yt);break;case"SpecularColor":s.specularMap=a.getTexture(t,r.ID),s.specularMap!==void 0&&(s.specularMap.colorSpace=yt);break;case"TransparentColor":case"TransparencyFactor":s.alphaMap=a.getTexture(t,r.ID),s.transparent=!0;break;default:console.warn("THREE.FBXLoader: %s map is not supported in three.js, skipping texture.",o);break}}),s}getTexture(e,t){return"LayeredTexture"in gt.Objects&&t in gt.Objects.LayeredTexture&&(console.warn("THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer."),t=Jt.get(t).children[0].ID),e.get(t)}parseDeformers(){const e={},t={};if("Deformer"in gt.Objects){const i=gt.Objects.Deformer;for(const s in i){const a=i[s],r=Jt.get(parseInt(s));if(a.attrType==="Skin"){const o=this.parseSkeleton(r,i);o.ID=s,r.parents.length>1&&console.warn("THREE.FBXLoader: skeleton attached to more than one geometry is not supported."),o.geometryID=r.parents[0].ID,e[s]=o}else if(a.attrType==="BlendShape"){const o={id:s};o.rawTargets=this.parseMorphTargets(r,i),o.id=s,r.parents.length>1&&console.warn("THREE.FBXLoader: morph target attached to more than one geometry is not supported."),t[s]=o}}}return{skeletons:e,morphTargets:t}}parseSkeleton(e,t){const i=[];return e.children.forEach(function(s){const a=t[s.ID];if(a.attrType!=="Cluster")return;const r={ID:s.ID,indices:[],weights:[],transformLink:new Ee().fromArray(a.TransformLink.a)};"Indexes"in a&&(r.indices=a.Indexes.a,r.weights=a.Weights.a),i.push(r)}),{rawBones:i,bones:[]}}parseMorphTargets(e,t){const i=[];for(let s=0;s1?r=o:o.length>0?r=o[0]:(r=new ir({name:ln.DEFAULT_MATERIAL_NAME,color:13421772}),o.push(r)),"color"in a.attributes&&o.forEach(function(l){l.vertexColors=!0}),a.groups.length>0){let l=!1;for(let c=0,u=a.groups.length;c=o.length)&&(d.materialIndex=o.length,l=!0)}if(l){const c=new ir;o.push(c)}}return a.FBX_Deformer?(s=new rf(a,r),s.normalizeSkinWeights()):s=new Se(a,r),s}createCurve(e,t){const i=e.children.reduce(function(a,r){return t.has(r.ID)&&(a=t.get(r.ID)),a},null),s=new Pt({name:ln.DEFAULT_MATERIAL_NAME,color:3342591,linewidth:1});return new On(i,s)}getTransformData(e,t){const i={};"InheritType"in t&&(i.inheritType=parseInt(t.InheritType.value)),"RotationOrder"in t?i.eulerOrder=hc(t.RotationOrder.value):i.eulerOrder=hc(0),"Lcl_Translation"in t&&(i.translation=t.Lcl_Translation.value),"PreRotation"in t&&(i.preRotation=t.PreRotation.value),"Lcl_Rotation"in t&&(i.rotation=t.Lcl_Rotation.value),"PostRotation"in t&&(i.postRotation=t.PostRotation.value),"Lcl_Scaling"in t&&(i.scale=t.Lcl_Scaling.value),"ScalingOffset"in t&&(i.scalingOffset=t.ScalingOffset.value),"ScalingPivot"in t&&(i.scalingPivot=t.ScalingPivot.value),"RotationOffset"in t&&(i.rotationOffset=t.RotationOffset.value),"RotationPivot"in t&&(i.rotationPivot=t.RotationPivot.value),e.userData.transformData=i}setLookAtProperties(e,t){"LookAtProperty"in t&&Jt.get(e.ID).children.forEach(function(s){if(s.relationship==="LookAtProperty"){const a=gt.Objects.Model[s.ID];if("Lcl_Translation"in a){const r=a.Lcl_Translation.value;e.target!==void 0?(e.target.position.fromArray(r),Vn.add(e.target)):e.lookAt(new T().fromArray(r))}}})}bindSkeleton(e,t,i){const s=this.parsePoseNodes();for(const a in e){const r=e[a];Jt.get(parseInt(r.ID)).parents.forEach(function(l){if(t.has(l.ID)){const c=l.ID;Jt.get(c).parents.forEach(function(d){i.has(d.ID)&&i.get(d.ID).bind(new Go(r.bones),s[d.ID])})}})}}parsePoseNodes(){const e={};if("Pose"in gt.Objects){const t=gt.Objects.Pose;for(const i in t)if(t[i].attrType==="BindPose"&&t[i].NbPoseNodes>0){const s=t[i].PoseNode;Array.isArray(s)?s.forEach(function(a){e[a.Node]=new Ee().fromArray(a.Matrix.a)}):e[s.Node]=new Ee().fromArray(s.Matrix.a)}}return e}addGlobalSceneSettings(){if("GlobalSettings"in gt){if("AmbientColor"in gt.GlobalSettings){const e=gt.GlobalSettings.AmbientColor.value,t=e[0],i=e[1],s=e[2];if(t!==0||i!==0||s!==0){const a=new de().setRGB(t,i,s,yt);Vn.add(new Pc(a,1))}}"UnitScaleFactor"in gt.GlobalSettings&&(Vn.userData.unitScaleFactor=gt.GlobalSettings.UnitScaleFactor.value)}}}class FF{constructor(){this.negativeMaterialIndices=!1}parse(e){const t=new Map;if("Geometry"in gt.Objects){const i=gt.Objects.Geometry;for(const s in i){const a=Jt.get(parseInt(s)),r=this.parseGeometry(a,i[s],e);t.set(parseInt(s),r)}}return this.negativeMaterialIndices===!0&&console.warn("THREE.FBXLoader: The FBX file contains invalid (negative) material indices. The asset might not render as expected."),t}parseGeometry(e,t,i){switch(t.attrType){case"Mesh":return this.parseMeshGeometry(e,t,i);case"NurbsCurve":return this.parseNurbsGeometry(t)}}parseMeshGeometry(e,t,i){const s=i.skeletons,a=[],r=e.parents.map(function(d){return gt.Objects.Model[d.ID]});if(r.length===0)return;const o=e.children.reduce(function(d,h){return s[h.ID]!==void 0&&(d=s[h.ID]),d},null);e.children.forEach(function(d){i.morphTargets[d.ID]!==void 0&&a.push(i.morphTargets[d.ID])});const l=r[0],c={};"RotationOrder"in l&&(c.eulerOrder=hc(l.RotationOrder.value)),"InheritType"in l&&(c.inheritType=parseInt(l.InheritType.value)),"GeometricTranslation"in l&&(c.translation=l.GeometricTranslation.value),"GeometricRotation"in l&&(c.rotation=l.GeometricRotation.value),"GeometricScaling"in l&&(c.scale=l.GeometricScaling.value);const u=nM(c);return this.genGeometry(t,o,a,u)}genGeometry(e,t,i,s){const a=new $e;e.attrName&&(a.name=e.attrName);const r=this.parseGeoNode(e,t),o=this.genBuffers(r),l=new Ce(o.vertex,3);if(l.applyMatrix4(s),a.setAttribute("position",l),o.colors.length>0&&a.setAttribute("color",new Ce(o.colors,3)),t&&(a.setAttribute("skinIndex",new Qh(o.weightsIndices,4)),a.setAttribute("skinWeight",new Ce(o.vertexWeights,4)),a.FBX_Deformer=t),o.normal.length>0){const c=new at().getNormalMatrix(s),u=new Ce(o.normal,3);u.applyNormalMatrix(c),a.setAttribute("normal",u)}if(o.uvs.forEach(function(c,u){const d=u===0?"uv":`uv${u}`;a.setAttribute(d,new Ce(o.uvs[u],2))}),r.material&&r.material.mappingType!=="AllSame"){let c=o.materialIndex[0],u=0;if(o.materialIndex.forEach(function(d,h){d!==c&&(a.addGroup(u,h-u,c),c=d,u=h)}),a.groups.length>0){const d=a.groups[a.groups.length-1],h=d.start+d.count;h!==o.materialIndex.length&&a.addGroup(h,o.materialIndex.length-h,c)}a.groups.length===0&&a.addGroup(0,o.materialIndex.length,o.materialIndex[0])}return this.addMorphTargets(a,e,i,s),a}parseGeoNode(e,t){const i={};if(i.vertexPositions=e.Vertices!==void 0?e.Vertices.a:[],i.vertexIndices=e.PolygonVertexIndex!==void 0?e.PolygonVertexIndex.a:[],e.LayerElementColor&&e.LayerElementColor[0].Colors&&(i.color=this.parseVertexColors(e.LayerElementColor[0])),e.LayerElementMaterial&&(i.material=this.parseMaterialIndices(e.LayerElementMaterial[0])),e.LayerElementNormal&&(i.normal=this.parseNormals(e.LayerElementNormal[0])),e.LayerElementUV){i.uv=[];let s=0;for(;e.LayerElementUV[s];)e.LayerElementUV[s].UV&&i.uv.push(this.parseUVs(e.LayerElementUV[s])),s++}return i.weightTable={},t!==null&&(i.skeleton=t,t.rawBones.forEach(function(s,a){s.indices.forEach(function(r,o){i.weightTable[r]===void 0&&(i.weightTable[r]=[]),i.weightTable[r].push({id:a,weight:s.weights[o]})})})),i}genBuffers(e){const t={vertex:[],normal:[],colors:[],uvs:[],materialIndex:[],vertexWeights:[],weightsIndices:[]};let i=0,s=0,a=!1,r=[],o=[],l=[],c=[],u=[],d=[];const h=this;return e.vertexIndices.forEach(function(f,p){let g,_=!1;f<0&&(f=f^-1,_=!0);let m=[],v=[];if(r.push(f*3,f*3+1,f*3+2),e.color){const y=Ru(p,i,f,e.color);l.push(y[0],y[1],y[2])}if(e.skeleton){if(e.weightTable[f]!==void 0&&e.weightTable[f].forEach(function(y){v.push(y.weight),m.push(y.id)}),v.length>4){a||(console.warn("THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights."),a=!0);const y=[0,0,0,0],b=[0,0,0,0];v.forEach(function(S,x){let M=S,C=m[x];b.forEach(function(w,E,R){if(M>w){R[E]=M,M=w;const L=y[E];y[E]=C,C=L}})}),m=y,v=b}for(;v.length<4;)v.push(0),m.push(0);for(let y=0;y<4;++y)u.push(v[y]),d.push(m[y])}if(e.normal){const y=Ru(p,i,f,e.normal);o.push(y[0],y[1],y[2])}e.material&&e.material.mappingType!=="AllSame"&&(g=Ru(p,i,f,e.material)[0],g<0&&(h.negativeMaterialIndices=!0,g=0)),e.uv&&e.uv.forEach(function(y,b){const S=Ru(p,i,f,y);c[b]===void 0&&(c[b]=[]),c[b].push(S[0]),c[b].push(S[1])}),s++,_&&(h.genFace(t,e,r,g,o,l,c,u,d,s),i++,s=0,r=[],o=[],l=[],c=[],u=[],d=[])}),t}getNormalNewell(e){const t=new T(0,0,0);for(let i=0;i.5?new T(0,1,0):new T(0,0,1)).cross(t).normalize(),a=t.clone().cross(s).normalize();return{normal:t,tangent:s,bitangent:a}}flattenVertex(e,t,i){return new ne(e.dot(t),e.dot(i))}genFace(e,t,i,s,a,r,o,l,c,u){let d;if(u>3){const h=[],f=t.baseVertexPositions||t.vertexPositions;for(let m=0;m1&&console.warn("THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.");const r=e.get(a[0].ID);i[s]={name:t[s].attrName,layer:r}}return i}addClip(e){let t=[];const i=this;return e.layer.forEach(function(s){t=t.concat(i.generateTracks(s))}),new ya(e.name,-1,t)}generateTracks(e){const t=[];let i=new T,s=new T;if(e.transform&&e.transform.decompose(i,new ht,s),i=i.toArray(),s=s.toArray(),e.T!==void 0&&Object.keys(e.T.curves).length>0){const a=this.generateVectorTrack(e.modelName,e.T.curves,i,"position");a!==void 0&&t.push(a)}if(e.R!==void 0&&Object.keys(e.R.curves).length>0){const a=this.generateRotationTrack(e.modelName,e.R.curves,e.preRotation,e.postRotation,e.eulerOrder);a!==void 0&&t.push(a)}if(e.S!==void 0&&Object.keys(e.S.curves).length>0){const a=this.generateVectorTrack(e.modelName,e.S.curves,s,"scale");a!==void 0&&t.push(a)}if(e.DeformPercent!==void 0){const a=this.generateMorphTrack(e);a!==void 0&&t.push(a)}return t}generateVectorTrack(e,t,i,s){const a=this.getTimesForAllAxes(t),r=this.getKeyframeTrackValues(a,t,i);return new qs(e+"."+s,a,r)}generateRotationTrack(e,t,i,s,a){let r,o;if(t.x!==void 0&&t.y!==void 0&&t.z!==void 0){const h=this.interpolateRotations(t.x,t.y,t.z,a);r=h[0],o=h[1]}const l=hc(0);i!==void 0&&(i=i.map(bt.degToRad),i.push(l),i=new rn().fromArray(i),i=new ht().setFromEuler(i)),s!==void 0&&(s=s.map(bt.degToRad),s.push(l),s=new rn().fromArray(s),s=new ht().setFromEuler(s).invert());const c=new ht,u=new rn,d=[];if(!o||!r)return new Ss(e+".quaternion",[0],[0]);for(let h=0;h2&&new ht().fromArray(d,(h-3)/3*4).dot(c)<0&&c.set(-c.x,-c.y,-c.z,-c.w),c.toArray(d,h/3*4);return new Ss(e+".quaternion",r,d)}generateMorphTrack(e){const t=e.DeformPercent.curves.morph,i=t.values.map(function(a){return a/100}),s=Vn.getObjectByName(e.modelName).morphTargetDictionary[e.morphName];return new ga(e.modelName+".morphTargetInfluences["+s+"]",t.times,i)}getTimesForAllAxes(e){let t=[];if(e.x!==void 0&&(t=t.concat(e.x.times)),e.y!==void 0&&(t=t.concat(e.y.times)),e.z!==void 0&&(t=t.concat(e.z.times)),t=t.sort(function(i,s){return i-s}),t.length>1){let i=1,s=t[0];for(let a=1;a=180||f[1]>=180||f[2]>=180){const g=Math.max(...f)/180,_=new rn(...c,s),m=new rn(...d,s),v=new ht().setFromEuler(_),y=new ht().setFromEuler(m);v.dot(y)&&y.set(-y.x,-y.y,-y.z,-y.w);const b=e.times[o-1],S=e.times[o]-b,x=new ht,M=new rn;for(let C=0;C<1;C+=1/g)x.copy(v.clone().slerp(y.clone(),C)),a.push(b+C*S),M.setFromQuaternion(x,s),r.push(M.x),r.push(M.y),r.push(M.z)}else a.push(e.times[o]),r.push(bt.degToRad(e.values[o])),r.push(bt.degToRad(t.values[o])),r.push(bt.degToRad(i.values[o]))}return[a,r]}}class UF{getPrevNode(){return this.nodeStack[this.currentIndent-2]}getCurrentNode(){return this.nodeStack[this.currentIndent-1]}getCurrentProp(){return this.currentProp}pushStack(e){this.nodeStack.push(e),this.currentIndent+=1}popStack(){this.nodeStack.pop(),this.currentIndent-=1}setCurrentProp(e,t){this.currentProp=e,this.currentPropName=t}parse(e){this.currentIndent=0,this.allNodes=new tM,this.nodeStack=[],this.currentProp=[],this.currentPropName="";const t=this,i=e.split(/[\r\n]+/);return i.forEach(function(s,a){const r=s.match(/^[\s\t]*;/),o=s.match(/^[\s\t]*$/);if(r||o)return;const l=s.match("^\\t{"+t.currentIndent+"}(\\w+):(.*){",""),c=s.match("^\\t{"+t.currentIndent+"}(\\w+):[\\s\\t\\r\\n](.*)"),u=s.match("^\\t{"+(t.currentIndent-1)+"}}");l?t.parseNodeBegin(s,l):c?t.parseNodeProperty(s,c,i[++a]):u?t.popStack():s.match(/^[^\s\t}]/)&&t.parseNodePropertyContinued(s)}),this.allNodes}parseNodeBegin(e,t){const i=t[1].trim().replace(/^"/,"").replace(/"$/,""),s=t[2].split(",").map(function(l){return l.trim().replace(/^"/,"").replace(/"$/,"")}),a={name:i},r=this.parseNodeAttr(s),o=this.getCurrentNode();this.currentIndent===0?this.allNodes.add(i,a):i in o?(i==="PoseNode"?o.PoseNode.push(a):o[i].id!==void 0&&(o[i]={},o[i][o[i].id]=o[i]),r.id!==""&&(o[i][r.id]=a)):typeof r.id=="number"?(o[i]={},o[i][r.id]=a):i!=="Properties70"&&(i==="PoseNode"?o[i]=[a]:o[i]=a),typeof r.id=="number"&&(a.id=r.id),r.name!==""&&(a.attrName=r.name),r.type!==""&&(a.attrType=r.type),this.pushStack(a)}parseNodeAttr(e){let t=e[0];e[0]!==""&&(t=parseInt(e[0]),isNaN(t)&&(t=e[0]));let i="",s="";return e.length>1&&(i=e[1].replace(/^(\w+)::/,""),s=e[2]),{id:t,name:i,type:s}}parseNodeProperty(e,t,i){let s=t[1].replace(/^"/,"").replace(/"$/,"").trim(),a=t[2].replace(/^"/,"").replace(/"$/,"").trim();s==="Content"&&a===","&&(a=i.replace(/"/g,"").replace(/,$/,"").trim());const r=this.getCurrentNode();if(r.name==="Properties70"){this.parseNodeSpecialProperty(e,s,a);return}if(s==="C"){const l=a.split(",").slice(1),c=parseInt(l[0]),u=parseInt(l[1]);let d=a.split(",").slice(3);d=d.map(function(h){return h.trim().replace(/^"/,"")}),s="connections",a=[c,u],$F(a,d),r[s]===void 0&&(r[s]=[])}s==="Node"&&(r.id=a),s in r&&Array.isArray(r[s])?r[s].push(a):s!=="a"?r[s]=a:r.a=a,this.setCurrentProp(r,s),s==="a"&&a.slice(-1)!==","&&(r.a=zp(a))}parseNodePropertyContinued(e){const t=this.getCurrentNode();t.a+=e,e.slice(-1)!==","&&(t.a=zp(t.a))}parseNodeSpecialProperty(e,t,i){const s=i.split('",').map(function(u){return u.trim().replace(/^\"/,"").replace(/\s/,"_")}),a=s[0],r=s[1],o=s[2],l=s[3];let c=s[4];switch(r){case"int":case"enum":case"bool":case"ULongLong":case"double":case"Number":case"FieldOfView":c=parseFloat(c);break;case"Color":case"ColorRGB":case"Vector3D":case"Lcl_Translation":case"Lcl_Rotation":case"Lcl_Scaling":c=zp(c);break}this.getPrevNode()[a]={type:r,type2:o,flag:l,value:c},this.setCurrentProp(this.getPrevNode(),a)}}class BF{parse(e){const t=new Av(e);t.skip(23);const i=t.getUint32();if(i<6400)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+i);const s=new tM;for(;!this.endOfContent(t);){const a=this.parseNode(t,i);a!==null&&s.add(a.name,a)}return s}endOfContent(e){return e.size()%16===0?(e.getOffset()+160+16&-16)>=e.size():e.getOffset()+160+16>=e.size()}parseNode(e,t){const i={},s=t>=7500?e.getUint64():e.getUint32(),a=t>=7500?e.getUint64():e.getUint32();t>=7500?e.getUint64():e.getUint32();const r=e.getUint8(),o=e.getString(r);if(s===0)return null;const l=[];for(let h=0;h0?l[0]:"",u=l.length>1?l[1]:"",d=l.length>2?l[2]:"";for(i.singleProperty=a===1&&e.getOffset()===s;s>e.getOffset();){const h=this.parseNode(e,t);h!==null&&this.parseSubNode(o,i,h)}return i.propertyList=l,typeof c=="number"&&(i.id=c),u!==""&&(i.attrName=u),d!==""&&(i.attrType=d),o!==""&&(i.name=o),i}parseSubNode(e,t,i){if(i.singleProperty===!0){const s=i.propertyList[0];Array.isArray(s)?(t[i.name]=i,i.a=s):t[i.name]=s}else if(e==="Connections"&&i.name==="C"){const s=[];i.propertyList.forEach(function(a,r){r!==0&&s.push(a)}),t.connections===void 0&&(t.connections=[]),t.connections.push(s)}else if(i.name==="Properties70")Object.keys(i).forEach(function(a){t[a]=i[a]});else if(e==="Properties70"&&i.name==="P"){let s=i.propertyList[0],a=i.propertyList[1];const r=i.propertyList[2],o=i.propertyList[3];let l;s.indexOf("Lcl ")===0&&(s=s.replace("Lcl ","Lcl_")),a.indexOf("Lcl ")===0&&(a=a.replace("Lcl ","Lcl_")),a==="Color"||a==="ColorRGB"||a==="Vector"||a==="Vector3D"||a.indexOf("Lcl_")===0?l=[i.propertyList[4],i.propertyList[5],i.propertyList[6]]:l=i.propertyList[4],t[s]={type:a,type2:r,flag:o,value:l}}else t[i.name]===void 0?typeof i.id=="number"?(t[i.name]={},t[i.name][i.id]=i):t[i.name]=i:i.name==="PoseNode"?(Array.isArray(t[i.name])||(t[i.name]=[t[i.name]]),t[i.name].push(i)):t[i.name][i.id]===void 0&&(t[i.name][i.id]=i)}parseProperty(e){const t=e.getString(1);let i;switch(t){case"C":return e.getBoolean();case"D":return e.getFloat64();case"F":return e.getFloat32();case"I":return e.getInt32();case"L":return e.getInt64();case"R":return i=e.getUint32(),e.getArrayBuffer(i);case"S":return i=e.getUint32(),e.getString(i);case"Y":return e.getInt16();case"b":case"c":case"d":case"f":case"i":case"l":const s=e.getUint32(),a=e.getUint32(),r=e.getUint32();if(a===0)switch(t){case"b":case"c":return e.getBooleanArray(s);case"d":return e.getFloat64Array(s);case"f":return e.getFloat32Array(s);case"i":return e.getInt32Array(s);case"l":return e.getInt64Array(s)}const o=SF(new Uint8Array(e.getArrayBuffer(r))),l=new Av(o.buffer);switch(t){case"b":case"c":return l.getBooleanArray(s);case"d":return l.getFloat64Array(s);case"f":return l.getFloat32Array(s);case"i":return l.getInt32Array(s);case"l":return l.getInt64Array(s)}break;default:throw new Error("THREE.FBXLoader: Unknown property type "+t)}}}class Av{constructor(e,t){this.dv=new DataView(e),this.offset=0,this.littleEndian=t!==void 0?t:!0,this._textDecoder=new TextDecoder}getOffset(){return this.offset}size(){return this.dv.buffer.byteLength}skip(e){this.offset+=e}getBoolean(){return(this.getUint8()&1)===1}getBooleanArray(e){const t=[];for(let i=0;i=0&&(i=new Uint8Array(this.dv.buffer,t,s)),this._textDecoder.decode(i)}}class tM{add(e,t){this[e]=t}}function zF(n){const e="Kaydara FBX Binary \0";return n.byteLength>=e.length&&e===iM(n,0,e.length)}function HF(n){const e=["K","a","y","d","a","r","a","\\","F","B","X","\\","B","i","n","a","r","y","\\","\\"];let t=0;function i(s){const a=n[s-1];return n=n.slice(t+s),t++,a}for(let s=0;s(console.warn(`⚠️ Could not load texture ${u}:`,d.message),null))])}this._processModelMaterials(s,a,e,i.format);const o=this._calculateModelScale(s,e,i.scale);if(s.userData.scaleInfo=o,s.userData.format=i.format,i.wheelSockets){s.userData.wheelSockets=!0,s.userData.wheelModelName=i.wheelModel;const l=this._findWheelSockets(s);s.userData.wheelSocketObjects=l,console.log(`🔌 Found ${Object.keys(l).length} wheel sockets`)}return{model:s,chassisTexture:a,wheelModel:r}}_findWheelSockets(e){const t={},i=["Wheel_BL","Wheel_BR","Wheel_FL","Wheel_FR"];console.log("🔍 Searching for wheel sockets..."),e.traverse(s=>{const a=s.name,r=a.toLowerCase();for(const o of i)(a===o||r===o.toLowerCase())&&(t[o]=s,console.log(` Found socket: "${a}" at position (${s.position.x.toFixed(2)}, ${s.position.y.toFixed(2)}, ${s.position.z.toFixed(2)})`))});for(const s of i)t[s]||console.warn(` ⚠️ Missing wheel socket: ${s}`);return Object.keys(t).length===0&&(console.warn("⚠️ No wheel sockets found! Listing all objects:"),e.traverse(s=>{console.log(` - "${s.name}" (${s.type})`)})),t}_calculateModelScale(e,t,i=null){const s=new bn().setFromObject(e),a=new T;s.getSize(a),console.log(`📐 ${t.toUpperCase()} model dimensions (raw):`),console.log(` Size: X=${a.x.toFixed(2)}, Y=${a.y.toFixed(2)}, Z=${a.z.toFixed(2)}`),console.log(` Min Y: ${s.min.y.toFixed(2)}, Max Y: ${s.max.y.toFixed(2)}`);const r=this.HITBOX_DIMENSIONS[t]||this.HITBOX_DIMENSIONS.octane;let o;if(i!==null)o=i,console.log(` Using override scale: ${o}`);else{const l=a.z,u=r.length*1/l;o=u*.55,console.log(` Target RL: ${r.length} x ${r.width} x ${r.height} uu`),console.log(` Scale to RL: ${u.toFixed(4)}, Final scale: ${o.toFixed(6)}`)}return{scale:o}}_loadFBX(e){return new Promise((t,i)=>{this.fbxLoader.load(e,s=>t(s),void 0,s=>i(new Error(`Failed to load FBX: ${e} - ${s.message}`)))})}_loadGLB(e){return new Promise((t,i)=>{this.gltfLoader.load(e,s=>{t(s.scene)},void 0,s=>i(new Error(`Failed to load GLB: ${e} - ${s.message}`)))})}async loadWheelModel(e){const t=Ri(`models/wheels/${e}`,this.assetBase);if(this.wheelModelCache.has(t))return this.wheelModelCache.get(t);if(this.wheelLoadingPromises.has(t))return this.wheelLoadingPromises.get(t);const i=this._loadGLB(t);this.wheelLoadingPromises.set(t,i);try{const s=await i;return console.log(`✓ Loaded wheel model: ${e}`),s.traverse(a=>{a.isMesh&&(a.castShadow=!0,a.receiveShadow=!0)}),this.wheelModelCache.set(t,s),s}catch(s){throw console.error(`Failed to load wheel model ${e}:`,s),s}finally{this.wheelLoadingPromises.delete(t)}}_loadTexture(e){return new Promise((t,i)=>{this.textureLoader.load(e,s=>{s.flipY=!1,s.colorSpace=yt,t(s)},void 0,s=>i(new Error(`Failed to load texture: ${e}`)))})}_processModelMaterials(e,t,i,s="fbx"){console.log(`📦 Processing materials for ${i} (${s}):`);const a=["body","paint"],r=[];e.traverse(o=>{o.isLight&&(r.push(o),console.log(` 🔦 Removing imported light: "${o.name||o.type}"`))}),r.forEach(o=>{o.parent&&o.parent.remove(o)}),e.traverse(o=>{o.isMesh&&(console.log(` Mesh: "${o.name}"`),(Array.isArray(o.material)?o.material:[o.material]).forEach((c,u)=>{console.log(` [${u}] Material: "${c.name}" - Color: #${c.color?.getHexString()||"none"}`);const d=(c.name||"").toLowerCase(),h=(o.name||"").toLowerCase(),f=a.some(p=>d.includes(p)||h.includes(p));if(s==="glb")(c.isMeshStandardMaterial||c.isMeshPhysicalMaterial)&&(console.log(` → GLB material (keeping as-is): metalness=${c.metalness?.toFixed(2)}, roughness=${c.roughness?.toFixed(2)}`),c.userData.originalColor=c.color?.clone(),c.userData.isBodyMaterial=f);else if(c.isMeshPhongMaterial||c.isMeshLambertMaterial||c.isMeshBasicMaterial){let p;f?(p=new kn({color:c.color,map:c.map,metalness:.8,roughness:.15}),console.log(" → Body material: shiny metallic")):(p=new kn({color:c.color,map:c.map,metalness:.1,roughness:.6}),console.log(" → Non-body material: matte")),p.name=c.name,Array.isArray(o.material)?o.material[u]=p:o.material=p}}))}),t?console.log(` ✓ Chassis texture loaded for ${i}`):s==="fbx"&&console.log(` ⚠️ No chassis texture for ${i}`)}getModelTypeForCar(e,t){return e&&this.carNameToModel[e]?this.carNameToModel[e]:this.hitboxToModel[t]||"octane"}getModelTypeForHitbox(e){return this.hitboxToModel[e]||"octane"}async createCarMesh(e,t=0){const i=this.getModelTypeForHitbox(e);try{const s=await this.loadModel(i);if(!s||!s.model)return console.warn(`No cached model for ${i}`),null;const a=s.model.userData.format||"fbx";let r;a==="glb"?(r=Hp(s.model),r.traverse(c=>{c.isMesh&&(Array.isArray(c.material)?c.material=c.material.map(u=>u.clone()):c.material&&(c.material=c.material.clone()))})):r=s.model.clone(),this.applyTeamColor(r,t);const o=new Et,l=s.model.userData.scaleInfo;return l&&r.scale.setScalar(l.scale),o.add(r),r.traverse(c=>{c.isMesh&&(c.castShadow=!0)}),o.userData.modelType=i,o.userData.hitboxType=e,o.userData.team=t,o.userData.isFBXModel=a==="fbx",o.userData.isGLBModel=a==="glb",o}catch(s){return console.error(`Failed to create car mesh for ${e}:`,s),null}}applyTeamColor(e,t){const i=t===0?this.TEAM_COLORS.blue:this.TEAM_COLORS.orange,s=["body","paint"];let a=!1;console.log("🔍 Analyzing car meshes for team coloring:"),e.traverse(r=>{if(r.isMesh){const o=Array.isArray(r.material)?r.material:[r.material];console.log(` Mesh: "${r.name}" with ${o.length} material(s)`),o.forEach((l,c)=>{console.log(` [${c}] Material: "${l.name}", isBodyMaterial: ${l.userData?.isBodyMaterial}`)})}}),e.traverse(r=>{r.isMesh&&(Array.isArray(r.material)?r.material:[r.material]).forEach((l,c)=>{const u=(l.name||"").toLowerCase(),d=(r.name||"").toLowerCase(),h=l.userData?.isBodyMaterial||s.some(f=>u.includes(f)||d.includes(f));if(console.log(` Checking "${l.name}" on "${r.name}": isBody=${h}`),h){a=!0;const f=l.clone();f.color=i.clone(),f.metalness=.39,f.roughness=.47,f.userData={...l.userData},Array.isArray(r.material)?r.material[c]=f:r.material=f,console.log(`🎨 Applied team color to: "${l.name}" on mesh "${r.name}" (index ${c})`)}})}),a||console.warn("⚠️ No body material found for team coloring! Check material names.")}updateTeamColor(e,t){this.applyTeamColor(e,t)}isModelReady(e,t){const i=this.getModelTypeForCar(e,t);return this.modelCache.has(this.modelCacheKey(i))}getCarMeshSync(e,t,i=0){const s=this.getModelTypeForCar(e,t),a=this.modelCache.get(this.modelCacheKey(s));if(!a||!a.model)return null;const r=a.model.userData.format||"fbx",o=a.model.userData.wheelSockets;let l;r==="glb"?(l=Hp(a.model),l.traverse(d=>{d.isMesh&&(Array.isArray(d.material)?d.material=d.material.map(h=>h.clone()):d.material&&(d.material=d.material.clone()))})):l=a.model.clone(),this.applyTeamColor(l,i);const c=new Et,u=a.model.userData.scaleInfo;return u&&l.scale.setScalar(u.scale),c.add(l),l.traverse(d=>{d.isMesh&&(d.castShadow=!0)}),c.userData.modelType=s,c.userData.carName=e,c.userData.hitboxType=t,c.userData.team=i,c.userData.isFBXModel=r==="fbx",c.userData.isGLBModel=r==="glb",c.userData.hasWheelSockets=o,o?c.userData.wheels=this._attachWheelsToSockets(l,a.wheelModel):c.userData.wheels=this._findWheelMeshes(l),c}_attachWheelsToSockets(e,t){const i=[],s={Wheel_FL:{side:"left",position:"front"},Wheel_FR:{side:"right",position:"front"},Wheel_BL:{side:"left",position:"rear"},Wheel_BR:{side:"right",position:"rear"}};if(!t)return console.warn("⚠️ No wheel model template available for socket attachment"),i;console.log("🔧 Attaching wheels to sockets...");const a={};e.traverse(r=>{const o=r.name;s[o]&&(a[o]=r)});for(const[r,o]of Object.entries(s)){const l=a[r];if(!l){console.warn(` ⚠️ Socket not found: ${r}`);continue}const c=Hp(t);c.traverse(u=>{u.isMesh&&(Array.isArray(u.material)?u.material=u.material.map(d=>d.clone()):u.material&&(u.material=u.material.clone()),u.castShadow=!0)}),c.position.set(0,0,0),c.rotation.set(0,0,0),l.add(c),console.log(` ✓ Attached wheel to ${r} (${o.position} ${o.side})`),i.push({mesh:c,steeringPivot:o.position==="front"?l:null,side:o.side,position:o.position,socket:l})}return console.log(`✓ Attached ${i.length} wheels to sockets`),i}_findWheelMeshes(e){const t=[],i={fl:{side:"left",position:"front"},fr:{side:"right",position:"front"},rl:{side:"left",position:"rear"},rr:{side:"right",position:"rear"}};console.log("🔍 Searching for wheels in model...");const s={};e.traverse(a=>{const o=a.name.toLowerCase().match(/^wheel_(fl|fr|rl|rr)_(y|z)$/);if(o){const l=o[1],c=o[2];s[l]||(s[l]={}),s[l][c]=a,console.log(` Found: "${a.name}" (${c==="y"?"wheel mesh":"steering pivot"})`)}});for(const[a,r]of Object.entries(s)){const o=i[a];if(!o)continue;const l=r.y,c=r.z;l&&(a==="fr"&&(l.rotation.z+=Math.PI,console.log(" Fixed FR wheel orientation (rotation.z += PI)")),t.push({mesh:l,steeringPivot:o.position==="front"?c:null,side:o.side,position:o.position}),console.log(`🛞 Wheel ${a.toUpperCase()}: mesh="${l.name}"${c&&o.position==="front"?`, steering="${c.name}"`:""}`))}return t.length===0?(console.warn("⚠️ No wheel meshes found. Expected: Wheel_FL_Y, Wheel_FR_Y, etc."),console.warn(" Listing all objects in model:"),e.traverse(a=>{console.log(` - "${a.name}" (${a.type})`)})):console.log(`✓ Found ${t.length} wheels`),t}dispose(){}}const ZF=2,Vp=new Map;function JF(n){const e=Ri("models/ball/scene.gltf",n);let t=Vp.get(e);if(!t){const i=new ey;t=new Promise(s=>{i.load(e,a=>{console.log("✓ Ball model loaded"),s(a.scene)},void 0,a=>{console.error("Failed to load ball model:",a),Vp.delete(e),s(null)})}),Vp.set(e,t)}return t}class QF{constructor(e,t,i={}){this.scene=e,this.effectsManager=t,this.assetBase=i.assetBase,this.actors={},this.ballActorId=null,this.ballIndicator=null,this.ballVerticalLine=null,this.playerNames=new Set,this.actorToPlayer={},this.actorLinks={},this.playerNameToCarActorId={},this.playerNameToPriActorId={},this.playerTeams={},this.actorLoadouts={},this.carBodyIds={},this.carModelLoader=new jF({assetBase:this.assetBase}),this.pendingCarReplacements=new Map,this._lastGoalScanTime=null,this._firedGoalTimes=new Set,this._p0=new T,this._p1=new T,this._v0=new T,this._v1=new T,this._nextRot=new ht,this._q0=new ht,this._q1=new ht,this._qResult=new ht,this.onPlayerFound=null,this.lastBallTouchTeam=0,this.BALL_TOUCH_DISTANCE=200,this.ballTimeline=[],this.playerTimelineMap={},this.timelineIndices={ball:0,players:{}},this.interpolantsInitialized=!1,this.animationMixer=null,this.animationActions={},this.animationClock=new Wg(!1),this.replayDuration=0,this.useAnimationSystem=!1,this.SMOOTHING_WINDOW=5,this.positionBuffers={},this.rotationBuffers={},this.interpolationEnabled=!0,this.interpolationMethod="lerp",this.smoothingWindowSize=12,this.lastFrameInfo=null,this._lowPassState=new Map,this._lowPassAlpha=.3,this._predictState=new Map,this._predictCorrectionTime=.1,this._smoothingBuffers=new Map,this._adaptiveState=new Map,this.ballModel=null,this._ballModelReplaced=!1,this.ballModelReady=JF(this.assetBase).then(s=>(this.ballModel=s,s!==null))}async waitForBallModel(){const e=await this.ballModelReady;return e&&!this._ballModelReplaced&&this.ballActorId&&this.actors[this.ballActorId]&&(this.replaceBallWithModel(this.ballActorId),this._ballModelReplaced=!0),e}replaceBallWithModel(e){const t=this.actors[e];if(!t||!this.ballModel)return;const i=this.ballModel.clone();i.userData=t.userData,i.position.copy(t.position),i.quaternion.copy(t.quaternion),i.scale.copy(t.scale);const s=92.75;i.scale.set(s,s,s),i.traverse(a=>{a.isMesh&&(a.castShadow=!0,a.receiveShadow=!0)}),this.scene.remove(t),this.scene.add(i),t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose(),this.actors[e]=i,console.log("✓ Ball replaced with GLTF model")}reset(){Object.values(this.actors).forEach(e=>{this.scene.remove(e),e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()}),this.actors={},this.ballActorId=null,this.ballIndicator&&(this.scene.remove(this.ballIndicator),this.ballIndicator.geometry&&this.ballIndicator.geometry.dispose(),this.ballIndicator.material&&this.ballIndicator.material.dispose(),this.ballIndicator=null),this.ballVerticalLine&&(this.scene.remove(this.ballVerticalLine),this.ballVerticalLine.geometry&&this.ballVerticalLine.geometry.dispose(),this.ballVerticalLine.material&&this.ballVerticalLine.material.dispose(),this.ballVerticalLine=null),this.actorToPlayer={},this.actorLinks={},this.playerNames.clear(),this.playerNameToCarActorId={},this.playerNameToPriActorId={},this.playerTeams={},this.actorLoadouts={},this.carBodyIds={},this.pendingCarReplacements.clear(),this._lastGoalScanTime=null,this._firedGoalTimes.clear(),this.ballTimeline=[],this.playerTimelineMap={},this.ballTimelineCorrected=[],this.playerTimelineMapCorrected={},this.ballTimelineFiltered=[],this.playerTimelineMapFiltered={},this.timelineIndices={ball:0,players:{}},this.timelineIndicesFiltered={ball:0,players:{}},this.timelineIndicesCorrected={ball:0,players:{}},this.interpolantsInitialized=!1,this.animationMixer?.stopAllAction?.(),this.animationMixer=null,this.animationActions={},this.replayDuration=0,this.positionBuffers={},this.rotationBuffers={},this._lowPassState.clear(),this._predictState.clear(),this._smoothingBuffers.clear(),this._adaptiveState.clear(),this._ballModelReplaced=!1}resetGoalExplosionPlaybackState(){this._lastGoalScanTime=null,this._firedGoalTimes.clear()}setPlayerTeams(e){this.playerTeams=e}initFromFramework(e){console.log("[ActorManager] Initializing actors from framework..."),this._createBallMesh();const t=e.playerList;t.forEach((i,s)=>{this._createCarMesh(i.name,i.team,s,i.carName,i.hitboxType);const a=this.playerNameToCarActorId[i.name];this.actors[a]}),console.log(`[ActorManager] Created ${t.length} car meshes + 1 ball`)}initInterpolants(e){console.log("[ActorManager] Initializing interpolation system..."),this.ballTimeline=e.ballTimeline||[],this.playerTimelineMap=e.playerTimelines||{},this.ballTimelineCorrected=this._correctTimeShiftedPositions(this.ballTimeline),this.playerTimelineMapCorrected={},Object.entries(this.playerTimelineMap).forEach(([s,a])=>{this.playerTimelineMapCorrected[s]=this._correctTimeShiftedPositions(a)}),this.ballTimelineFiltered=this._filterBadFrames(this.ballTimeline),this.playerTimelineMapFiltered={},Object.entries(this.playerTimelineMap).forEach(([s,a])=>{this.playerTimelineMapFiltered[s]=this._filterBadFrames(a)}),this.timelineIndices={ball:0,players:{}},this.timelineIndicesFiltered={ball:0,players:{}},this.timelineIndicesCorrected={ball:0,players:{}},Object.keys(this.playerTimelineMap).forEach(s=>{this.timelineIndices.players[s]=0,this.timelineIndicesFiltered.players[s]=0,this.timelineIndicesCorrected.players[s]=0}),this.ballTimeline.length>0&&(this.replayDuration=this.ballTimeline[this.ballTimeline.length-1].time),this.useAnimationSystem&&this._initAnimationSystem(),this.interpolantsInitialized=!0;const t=this.ballTimeline.length-this.ballTimelineFiltered.length,i=this.ballTimelineCorrected._correctedCount||0;console.log(` Ball: ${this.ballTimeline.length} keyframes (${i} corrected, ${t} filtered)`),Object.entries(this.playerTimelineMap).forEach(([s,a])=>{const r=this.playerTimelineMapCorrected[s]?._correctedCount||0;console.log(` ${s}: ${a.length} keyframes (${r} corrected)`)}),console.log(` Replay duration: ${this.replayDuration.toFixed(2)}s`),console.log("[ActorManager] Animation system ready")}_initAnimationSystem(){console.log("[ActorManager] Building Three.js animation clips..."),this.animationMixer=new DT(this.scene);const e=this.actors[this.ballActorId];if(e&&this.ballTimeline.length>0){const t=this._createAnimationClip("ball",this.ballTimeline,e);if(t){const i=this.animationMixer.clipAction(t,e);i.setLoop(ph),i.clampWhenFinished=!0,this.animationActions.ball=i,console.log(` ✓ Ball animation: ${t.duration.toFixed(2)}s`)}}Object.entries(this.playerTimelineMap).forEach(([t,i])=>{const s=this.playerNameToCarActorId[t],a=this.actors[s];if(a&&i.length>0){const r=this._createAnimationClip(t,i,a);if(r){const o=this.animationMixer.clipAction(r,a);o.setLoop(ph),o.clampWhenFinished=!0,this.animationActions[t]=o,console.log(` ✓ ${t} animation: ${r.duration.toFixed(2)}s`)}}}),console.log("[ActorManager] Animation clips ready")}_createAnimationClip(e,t,i){if(!t||t.length<2)return null;const s=[],a=[],r=[],o=t[0];o.time>0&&(s.push(0),o.position?a.push(o.position.x,o.position.y,o.position.z):a.push(0,0,0),o.rotation?r.push(o.rotation.x,o.rotation.y,o.rotation.z,o.rotation.w):r.push(0,0,0,1));for(const h of t){if(s.push(h.time),h.position)a.push(h.position.x,h.position.y,h.position.z);else{const f=a.length-3;f>=0?a.push(a[f],a[f+1],a[f+2]):a.push(0,0,0)}if(h.rotation)r.push(h.rotation.x,h.rotation.y,h.rotation.z,h.rotation.w);else{const f=r.length-4;f>=0?r.push(r[f],r[f+1],r[f+2],r[f+3]):r.push(0,0,0,1)}}const l=new qs(".position",s,a,mr),c=new Ss(".quaternion",s,r),u=s[s.length-1]-s[0];return new ya(e,u,[l,c])}startAnimations(){this.animationMixer&&(Object.values(this.animationActions).forEach(e=>{e.reset(),e.play()}),this.animationClock.start(),console.log("[ActorManager] Animations started"))}pauseAnimations(){this.animationMixer&&Object.values(this.animationActions).forEach(e=>{e.paused=!0})}resumeAnimations(){this.animationMixer&&Object.values(this.animationActions).forEach(e=>{e.paused=!1})}seekAnimations(e){this.animationMixer&&(Object.values(this.animationActions).forEach(t=>{t.time=e}),this.animationMixer.setTime(e))}updateAnimations(e){!this.animationMixer||!this.useAnimationSystem||this.animationMixer.update(e)}_subsampleTimeline(e){return!e||e.length<4?e:e.filter((t,i)=>i%2===0)}_getOrCreateSmoothingBuffer(e){return this.positionBuffers[e]||(this.positionBuffers[e]=[],this.rotationBuffers[e]=[]),{positions:this.positionBuffers[e],rotations:this.rotationBuffers[e]}}_smoothPosition(e,t){const i=this._getOrCreateSmoothingBuffer(e).positions;for(i.push({x:t.x,y:t.y,z:t.z});i.length>this.SMOOTHING_WINDOW;)i.shift();if(i.length===1)return t;let s=0,a=0,r=0;for(const o of i)s+=o.x,a+=o.y,r+=o.z;return{x:s/i.length,y:a/i.length,z:r/i.length}}_smoothRotation(e,t){const i=this._getOrCreateSmoothingBuffer(e).rotations;for(i.push({x:t.x,y:t.y,z:t.z,w:t.w});i.length>this.SMOOTHING_WINDOW;)i.shift();if(i.length<3)return t;const s=Math.floor(i.length/2);return i[s]}resetSmoothingBuffers(){this.positionBuffers={},this.rotationBuffers={},this._lowPassState.clear()}_findKeyframeIndex(e,t,i=0){if(!e||e.length===0)return-1;if(t<=e[0].time)return 0;if(t>=e[e.length-1].time)return e.length-2;let s=Math.max(0,Math.min(i,e.length-2));if(e[s].time<=t&&e[s+1].time>t)return s;if(s+2t)return s+1;let a=0,r=e.length-2;for(;a<=r;){const o=Math.floor((a+r)/2);if(e[o].time<=t&&e[o+1].time>t)return o;e[o].time>t?r=o-1:a=o+1}return Math.max(0,Math.min(a,e.length-2))}_applySmoothing(e,t){this._smoothingBuffers.has(e)||this._smoothingBuffers.set(e,[]);const i=this._smoothingBuffers.get(e);for(i.push({x:t.x,y:t.y,z:t.z});i.length>this.smoothingWindowSize;)i.shift();if(i.length===1)return t;let s=0,a=0,r=0;for(const o of i)s+=o.x,a+=o.y,r+=o.z;return{x:s/i.length,y:a/i.length,z:r/i.length}}_applyEmaSmoothing(e,t){const i=`ema-${e}`;if(!this._smoothingBuffers.has(i))return this._smoothingBuffers.set(i,{x:t.x,y:t.y,z:t.z}),t;const s=this._smoothingBuffers.get(i),a=Math.max(.05,Math.min(.5,1/this.smoothingWindowSize)),r={x:a*t.x+(1-a)*s.x,y:a*t.y+(1-a)*s.y,z:a*t.z+(1-a)*s.z};return this._smoothingBuffers.set(i,r),r}_applyDoubleEmaSmoothing(e,t){const i=`dema-${e}`;if(!this._smoothingBuffers.has(i))return this._smoothingBuffers.set(i,{level:{x:t.x,y:t.y,z:t.z},trend:{x:0,y:0,z:0}}),t;const s=this._smoothingBuffers.get(i),a=Math.max(.1,Math.min(.6,2/this.smoothingWindowSize)),r=a*.5,o={x:a*t.x+(1-a)*(s.level.x+s.trend.x),y:a*t.y+(1-a)*(s.level.y+s.trend.y),z:a*t.z+(1-a)*(s.level.z+s.trend.z)},l={x:r*(o.x-s.level.x)+(1-r)*s.trend.x,y:r*(o.y-s.level.y)+(1-r)*s.trend.y,z:r*(o.z-s.level.z)+(1-r)*s.trend.z};return s.level=o,s.trend=l,{x:o.x+l.x,y:o.y+l.y,z:o.z+l.z}}_applyWeightedSmoothing(e,t){const i=`wma-${e}`;this._smoothingBuffers.has(i)||this._smoothingBuffers.set(i,[]);const s=this._smoothingBuffers.get(i);for(s.push({x:t.x,y:t.y,z:t.z});s.length>this.smoothingWindowSize;)s.shift();if(s.length===1)return t;let a=0,r=0,o=0,l=0;for(let c=0;cthis.smoothingWindowSize;)s.shift();if(s.length===1)return t;const a=s.length/3;let r=0,o=0,l=0,c=0;for(let u=0;u.001&&(s.derivedVel={x:(t.x-s.lastPos.x)/a,y:(t.y-s.lastPos.y)/a,z:(t.z-s.lastPos.z)/a});const r=Math.sqrt(s.derivedVel.x**2+s.derivedVel.y**2+s.derivedVel.z**2),o=2,l=this.smoothingWindowSize,c=300,u=1500;let d;if(ru)d=o;else{const _=(r-c)/(u-c);d=Math.round(l-_*(l-o))}if(s.buffer.length>=2){const _=s.buffer[s.buffer.length-1],m=s.buffer[s.buffer.length-2],v={x:_.x-m.x,y:_.y-m.y,z:_.z-m.z},y={x:t.x-_.x,y:t.y-_.y,z:t.z-_.z},b=Math.sqrt(v.x**2+v.y**2+v.z**2),S=Math.sqrt(y.x**2+y.y**2+y.z**2);if(b>.1&&S>.1&&(v.x*y.x+v.y*y.y+v.z*y.z)/(b*S)<.5)for(;s.buffer.length>Math.max(2,d/2);)s.buffer.shift()}for(s.buffer.push({x:t.x,y:t.y,z:t.z});s.buffer.length>d;)s.buffer.shift();if(s.lastPos={x:t.x,y:t.y,z:t.z},s.lastTime=i,s.buffer.length===1)return t;let h=0,f=0,p=0,g=0;for(let _=0;_u+10&&(h.z=t.position.z+t.velocity.z*r-.5*c*r*r,h.zu+10&&(p.z=t.position.z+t.velocity.z*o-.5*c*o*o,p.z0&&o>0){const b=d*o;m>b*2&&(v=b*2/m)}const y=_*v+(1-v)*l;return{x:h.x+g.x*y,y:h.y+g.y*y,z:h.z+g.z*y}}_physicsTickInterpolate(e,t,i){const s=t.time-e.time,a=i-e.time,r=a/s;if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};const o=(e.velocity.x+t.velocity.x)/2,l=(e.velocity.y+t.velocity.y)/2,c=(e.velocity.z+t.velocity.z)/2,u=e.position.x+o*a,d=e.position.y+l*a,h=e.position.z+c*a,f=e.position.x+o*s,p=e.position.y+l*s,g=e.position.z+c*s,_=t.position.x-f,m=t.position.y-p,v=t.position.z-g;return{x:u+_*r,y:d+m*r,z:h+v*r}}_velocityOnlyInterpolate(e,t,i){const s=i-e.time,a=t.time-e.time,r=s/a;if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};const o=e.velocity.x+(t.velocity.x-e.velocity.x)*r/2,l=e.velocity.y+(t.velocity.y-e.velocity.y)*r/2,c=e.velocity.z+(t.velocity.z-e.velocity.z)*r/2;return{x:e.position.x+o*s,y:e.position.y+l*s,z:e.position.z+c*s}}_smartHybridInterpolate(e,t,i){const s=i-e.time,a=t.time-e.time,r=Math.max(0,Math.min(1,s/a));if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};const o=Math.sqrt(e.velocity.x**2+e.velocity.y**2+e.velocity.z**2),l=Math.sqrt(t.velocity.x**2+t.velocity.y**2+t.velocity.z**2);let c=1;o>10&&l>10&&(c=(e.velocity.x*t.velocity.x+e.velocity.y*t.velocity.y+e.velocity.z*t.velocity.z)/(o*l));const u=o>10?Math.abs(l-o)/o:0;if(c<.95||u>.1){const h=r*r*(3-2*r);return{x:e.position.x+(t.position.x-e.position.x)*h,y:e.position.y+(t.position.y-e.position.y)*h,z:e.position.z+(t.position.z-e.position.z)*h}}else{const h=(e.velocity.x+t.velocity.x)/2,f=(e.velocity.y+t.velocity.y)/2,p=(e.velocity.z+t.velocity.z)/2,g=e.position.x+h*s,_=e.position.y+f*s,m=e.position.z+p*s,v=e.position.x+h*a,y=e.position.y+f*a,b=e.position.z+p*a,S=t.position.x-v,x=t.position.y-y,M=t.position.z-b;return{x:g+S*r,y:_+x*r,z:m+M*r}}}_isBadFrame(e,t){if(!e.velocity||!t.velocity||!e.position||!t.position)return!1;const i=t.time-e.time;if(i<.001)return!1;const s=(e.velocity.x+t.velocity.x)/2,a=(e.velocity.y+t.velocity.y)/2,r=(e.velocity.z+t.velocity.z)/2,o=Math.sqrt(s**2+a**2+r**2);if(o<200)return!1;const l=t.position.x-e.position.x,c=t.position.y-e.position.y,u=t.position.z-e.position.z,d=Math.sqrt(l*l+c*c+u*u),h=o*i,f=d/h;return f<.6||f>1.4}_filterBadFrames(e){if(!e||e.length<2)return e;const t=[e[0]];for(let i=1;i0&&a.position&&a.velocity){const o=e[s-1];if(o.position&&o.velocity){const l=a.time-o.time;if(l>.001){const c=(o.velocity.x+a.velocity.x)/2,u=(o.velocity.y+a.velocity.y)/2,d=(o.velocity.z+a.velocity.z)/2,h=Math.sqrt(c**2+u**2+d**2);if(h>100){const f=a.position.x-o.position.x,p=a.position.y-o.position.y,g=a.position.z-o.position.z,_=Math.sqrt(f*f+p*p+g*g),m=h*l,v=_/m;let y=0;v>.15&&v<.35?y=l*.75:v>.4&&v<.6?y=l*.5:v>.65&&v<.85&&(y=l*.25),y>0&&(r.position.x+=a.velocity.x*y,r.position.y+=a.velocity.y*y,r.position.z+=a.velocity.z*y,i++)}}}}t.push(r)}return t._correctedCount=i,t}_timeShiftedInterpolate(e,t,i){const s=i-e.time,a=t.time-e.time,r=Math.max(0,Math.min(1,s/a));return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r}}_velocityAnchoredInterpolate(e,t,i,s,a,r){if(!t.velocity||!i.velocity){const m=(s-t.time)/(i.time-t.time);return{x:t.position.x+(i.position.x-t.position.x)*m,y:t.position.y+(i.position.y-t.position.y)*m,z:t.position.z+(i.position.z-t.position.z)*m}}this._velocityAnchorState||(this._velocityAnchorState=new Map);let o=this._velocityAnchorState.get(e);(!o||Math.abs(s-o.lastTime)>.5||r%10===0)&&(o={anchorPos:{...t.position},anchorTime:t.time,anchorIdx:r,lastTime:s},this._velocityAnchorState.set(e,o)),s-o.anchorTime;let u=o.anchorPos.x,d=o.anchorPos.y,h=o.anchorPos.z;const f=(t.velocity.x+i.velocity.x)/2,p=(t.velocity.y+i.velocity.y)/2,g=(t.velocity.z+i.velocity.z)/2,_=s-t.time;return o.anchorIdx===r?(u=o.anchorPos.x+f*_,d=o.anchorPos.y+p*_,h=o.anchorPos.z+g*_):(u=t.position.x+f*_,d=t.position.y+p*_,h=t.position.z+g*_),o.lastTime=s,{x:u,y:d,z:h}}_hermiteInterpolate(e,t,i){const s=t.time-e.time,a=i-e.time,r=Math.max(0,Math.min(1,a/s)),o={x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};if(!e.velocity||!t.velocity)return o;const l=r*r,c=l*r,u=2*c-3*l+1,d=c-2*l+r,h=-2*c+3*l,f=c-l,p={x:e.velocity.x*s,y:e.velocity.y*s,z:e.velocity.z*s},g={x:t.velocity.x*s,y:t.velocity.y*s,z:t.velocity.z*s},_={x:u*e.position.x+d*p.x+h*t.position.x+f*g.x,y:u*e.position.y+d*p.y+h*t.position.y+f*g.y,z:u*e.position.z+d*p.z+h*t.position.z+f*g.z},m=_.x-o.x,v=_.y-o.y,y=_.z-o.z,b=t.position.x-e.position.x,S=t.position.y-e.position.y,x=t.position.z-e.position.z;return m*m+v*v+y*y>b*b+S*S+x*x?o:_}_physicsSimInterpolate(e,t,i,s=!1){const a=t.time-e.time,r=i-e.time,o=Math.max(0,Math.min(1,r/a));if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*o,y:e.position.y+(t.position.y-e.position.y)*o,z:e.position.z+(t.position.z-e.position.z)*o};const l=-650,c=o*o,u=c*o,d=2*u-3*c+1,h=u-2*c+o,f=-2*u+3*c,p=u-c;let g=e.velocity.y*a,_=t.velocity.y*a;if(s){const m=.5*l*a*a;g+=m*.5,_+=m*.5}return{x:d*e.position.x+h*(e.velocity.x*a)+f*t.position.x+p*(t.velocity.x*a),y:d*e.position.y+h*g+f*t.position.y+p*_,z:d*e.position.z+h*(e.velocity.z*a)+f*t.position.z+p*(t.velocity.z*a)}}getBallPositionAt(e){if(!this.ballTimeline||this.ballTimeline.length<2)return null;const t=this.ballTimeline[0];if(e2e3)return s.sleeping?null:{...s.position};if(s.sleeping)return{...s.position};const d=(e-s.time)/r;let h;switch(this.interpolationMethod){case"catmull-rom":{const f=this.ballTimeline[Math.max(0,i-1)],p=this.ballTimeline[Math.min(this.ballTimeline.length-1,i+2)];f?.position&&p?.position?h=this._catmullRomInterpolate(f.position,s.position,a.position,p.position,d):h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}case"lerp-smooth":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applySmoothing("ball",h);break}case"lerp-ema":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyEmaSmoothing("ball",h);break}case"lerp-dema":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyDoubleEmaSmoothing("ball",h);break}case"lerp-wma":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyWeightedSmoothing("ball",h);break}case"lerp-gauss":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyGaussianSmoothing("ball",h);break}case"one-euro":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyOneEuroFilter("ball",h);break}case"predict-correct":{h=this._predictCorrectInterpolate("ball",s,a,e);break}case"velocity-smooth":{h=this._velocitySmoothInterpolate("ball",s,a,e,!0);break}case"physics-tick":{h=this._physicsTickInterpolate(s,a,e);break}case"hermite":{h=this._hermiteInterpolate(s,a,e);break}case"physics-sim":{const f=this.ballTimelineCorrected;if(f&&f.length>=2){const p=this._findKeyframeIndex(f,e,this.timelineIndicesCorrected.ball);this.timelineIndicesCorrected.ball=p;const g=f[p],_=f[p+1];if(g?.position&&_?.position){h=this._physicsSimInterpolate(g,_,e,!0);break}}h=this._physicsSimInterpolate(s,a,e,!0);break}case"velocity-only":{h=this._velocityOnlyInterpolate(s,a,e);break}case"smart-hybrid":{h=this._smartHybridInterpolate(s,a,e);break}case"time-shifted":{const f=this.ballTimelineFiltered;if(!f||f.length<2){h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}const p=this._findKeyframeIndex(f,e,this.timelineIndicesFiltered.ball);this.timelineIndicesFiltered.ball=p;const g=f[p],_=f[p+1];if(!g?.position||!_?.position){h=g?.position?{...g.position}:{...s.position};break}const m=_.time-g.time,v=m>0?Math.max(0,Math.min(1,(e-g.time)/m)):0;h={x:g.position.x+(_.position.x-g.position.x)*v,y:g.position.y+(_.position.y-g.position.y)*v,z:g.position.z+(_.position.z-g.position.z)*v};break}case"position-lerp":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}case"position-catmull":{const f=this.ballTimeline[Math.max(0,i-1)],p=this.ballTimeline[Math.min(this.ballTimeline.length-1,i+2)];f?.position&&p?.position?h=this._catmullRomInterpolate(f.position,s.position,a.position,p.position,d):h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}case"position-smooth":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyLowPassFilter("ball",h);break}case"adaptive-smooth":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyAdaptiveSmoothing("ball",h,e);break}default:{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}}return h}getBallRotationAt(e){if(!this.ballTimeline||this.ballTimeline.length<2)return null;const t=this.ballTimeline[0];if(e2e3)return{...s.rotation}}if(s.sleeping)return{...s.rotation};const o=(e-s.time)/r;return this._q0.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w),this._q1.set(a.rotation.x,a.rotation.y,a.rotation.z,a.rotation.w),this._qResult.slerpQuaternions(this._q0,this._q1,o),{x:this._qResult.x,y:this._qResult.y,z:this._qResult.z,w:this._qResult.w}}getPlayerPositionAt(e,t){const i=this.playerTimelineMap[e];if(!i||i.length<2)return null;const s=i[0];if(t=2){const h=this._findKeyframeIndex(d,t,this.timelineIndicesCorrected.players[e]||0);this.timelineIndicesCorrected.players[e]=h;const f=d[h],p=d[h+1];if(f?.position&&p?.position){u=this._physicsSimInterpolate(f,p,t,!1);break}}u=this._physicsSimInterpolate(r,o,t,!1);break}case"velocity-only":{u=this._velocityOnlyInterpolate(r,o,t);break}case"smart-hybrid":{u=this._smartHybridInterpolate(r,o,t);break}case"time-shifted":{const d=this.playerTimelineMapFiltered[e];if(!d||d.length<2){u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}const h=this._findKeyframeIndex(d,t,this.timelineIndicesFiltered.players[e]||0);this.timelineIndicesFiltered.players[e]=h;const f=d[h],p=d[h+1];if(!f?.position||!p?.position){u=f?.position?{...f.position}:{...r.position};break}const g=p.time-f.time,_=g>0?Math.max(0,Math.min(1,(t-f.time)/g)):0;u={x:f.position.x+(p.position.x-f.position.x)*_,y:f.position.y+(p.position.y-f.position.y)*_,z:f.position.z+(p.position.z-f.position.z)*_};break}case"position-lerp":{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}case"position-catmull":{const d=i[Math.max(0,a-1)],h=i[Math.min(i.length-1,a+2)];d?.position&&h?.position?u=this._catmullRomInterpolate(d.position,r.position,o.position,h.position,c):u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}case"position-smooth":{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c},u=this._applyLowPassFilter(`player-${e}`,u);break}case"adaptive-smooth":{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c},u=this._applyAdaptiveSmoothing(`player-${e}`,u,t);break}default:{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}}return u}getPlayerRotationAt(e,t){const i=this.playerTimelineMap[e];if(!i||i.length<2)return null;const s=i[0];if(t=2){const r=this.getBallPositionAt(t),o=this.getBallRotationAt(t);r?i.position.set(r.x,r.y,r.z):a=!1,o&&i.quaternion.set(o.x,o.y,o.z,o.w)}else i.position.set(s.position.x,s.position.y,s.position.z),i.quaternion.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w);if(i.userData.location.copy(i.position),i.userData.rotation.copy(i.quaternion),i.userData.velocity.set(s.velocity.x,s.velocity.y,s.velocity.z),s.angularVelocity&&i.userData.angularVelocity.set(s.angularVelocity.x,s.angularVelocity.y,s.angularVelocity.z),i.userData.sleeping=s.sleeping,i.visible=a&&s.visible!==!1&&!i.userData.isHiddenByGoal,this.ballIndicator&&(this.ballIndicator.position.set(i.position.x,2,i.position.z),this.ballIndicator.visible=i.visible),this.ballVerticalLine){const o=new Float32Array([i.position.x,2,i.position.z,i.position.x,i.position.y,i.position.z]);this.ballVerticalLine.geometry.setAttribute("position",new ot(o,3)),this.ballVerticalLine.geometry.attributes.position.needsUpdate=!0,this.ballVerticalLine.visible=i.visible}if(i.userData.velocity&&i.visible){let r=this.lastBallTouchTeam,o=this.BALL_TOUCH_DISTANCE;Object.keys(this.actors).forEach(l=>{const c=this.actors[l];if(c&&c.userData.isCar&&c.userData.playerId){const u=i.position.distanceTo(c.position);u{const a=this.playerNameToCarActorId[s.name];if(!a)return;const r=this.actors[a];if(!r)return;const o=s.name;if(!this.useAnimationSystem||!this.animationMixer)if(this.interpolantsInitialized&&this.playerTimelineMap[o]){const c=this.getPlayerPositionAt(o,t),u=this.getPlayerRotationAt(o,t);c&&r.position.set(c.x,c.y,c.z),u&&r.quaternion.set(u.x,u.y,u.z,u.w)}else r.position.set(s.position.x,s.position.y,s.position.z),r.quaternion.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w);r.userData.location.copy(r.position),r.userData.rotation.copy(r.quaternion),r.userData.velocity.set(s.velocity.x,s.velocity.y,s.velocity.z),r.userData.sleeping=s.sleeping,r.userData.steer=s.steer||0;const l=r.position.length()>.1;r.visible=s.isVisible&&l&&!r.userData.sleeping}),this._updateGoalExplosions(t)}_updateGoalExplosions(e){const t=this.effectsManager,i=t&&t.explosions?t.explosions.goalEvents:null;if(!(i instanceof Map)||i.size===0)return;const s=this._lastGoalScanTime;s!==null&&e=c&&e<=c+ZF&&(r=!0,o=!0),s!==null&&s=c&&!this._firedGoalTimes.has(c)){this._firedGoalTimes.add(c);const d=this.getBallPositionAt(c)||a&&a.position||null;d&&this.effectsManager.triggerGoalExplosion(d,l.team)}}a&&(a.userData.isHiddenByGoal=r,r&&(a.visible=!1)),o||this.effectsManager.clearGoalExplosions?.(),this._lastGoalScanTime=e}processFrame(e,t,i,s){if(e){if(e.new_actors&&e.new_actors.forEach(a=>{if(!this.actors[a.actor_id]){const r=t(a.object_id),o=r&&r.includes("Ball"),l=r&&r.includes("Car");if(o||l){let c;o?c=new vn(92.75,16,16):c=new ki(118,36,84);const u=new kn({color:o?16777215:Math.random()*16777215}),d=new Se(c,u);if(d.userData={location:new T,rotation:new ht,isCar:l,isBall:o,playerId:null,lastUpdateTime:e.time,bodyId:null,hasReceivedUpdate:!1},this.scene.add(d),this.actors[a.actor_id]=d,o){this.ballActorId=a.actor_id,this.ballModel&&this.replaceBallWithModel(a.actor_id);const h=92.75,f=new oi(h*.95,h,32),p=new je({color:16777215,side:ut});this.ballIndicator=new Se(f,p),this.ballIndicator.rotation.x=-Math.PI/2,this.ballIndicator.visible=!1,this.scene.add(this.ballIndicator);const g=new $e().setFromPoints([new T(0,0,0),new T(0,1,0)]),_=new Pt({color:16777215,opacity:.5,transparent:!0});this.ballVerticalLine=new On(g,_),this.ballVerticalLine.frustumCulled=!1,this.ballVerticalLine.visible=!1,this.scene.add(this.ballVerticalLine)}else l&&this.effectsManager.createBoostTrail(d,a.actor_id)}}}),e.deleted_actors&&e.deleted_actors.forEach(a=>{if(this.actors[a]){const r=this.actors[a];r.userData.isCar&&this.effectsManager.removeBoostTrail(a),this.scene.remove(r),r.geometry&&r.geometry.dispose(),r.material&&r.material.dispose(),delete this.actors[a],this.ballActorId===a&&(this.ballActorId=null,this.ballIndicator&&(this.scene.remove(this.ballIndicator),this.ballIndicator.geometry&&this.ballIndicator.geometry.dispose(),this.ballIndicator.material&&this.ballIndicator.material.dispose(),this.ballIndicator=null),this.ballVerticalLine&&(this.scene.remove(this.ballVerticalLine),this.ballVerticalLine.geometry&&this.ballVerticalLine.geometry.dispose(),this.ballVerticalLine.material&&this.ballVerticalLine.material.dispose(),this.ballVerticalLine=null))}}),e.updated_actors&&e.updated_actors.forEach(a=>{const r=this.actors[a.actor_id];a.attribute.TeamLoadout&&(this.actorLoadouts[a.actor_id]=a.attribute.TeamLoadout,r&&r.userData.isCar&&(r.userData.teamLoadout=a.attribute.TeamLoadout,this.resolveBodyId(r,a.actor_id)));const o=t(a.object_id),l=o&&(o.includes("PRI_TA")||o.includes("PlayerReplicationInfo"));if(a.attribute.String&&this.playerNames.has(a.attribute.String)){const c=a.attribute.String;this.actorToPlayer[a.actor_id]=c,l&&!this.playerNameToPriActorId[c]&&(this.playerNameToPriActorId[c]=a.actor_id,console.log(`[ActorManager] Mapped ${c} -> PRI Actor ${a.actor_id} (object: ${o})`)),this.checkCarPlayerLink(a.actor_id)}if(a.attribute.Reservation&&this.playerNames.has(a.attribute.Reservation.name)){const c=a.attribute.Reservation.name;this.actorToPlayer[a.actor_id]=c,l&&!this.playerNameToPriActorId[c]&&(this.playerNameToPriActorId[c]=a.actor_id,console.log(`[ActorManager] Mapped ${c} -> PRI Actor ${a.actor_id} (object: ${o})`)),this.checkCarPlayerLink(a.actor_id)}if(a.attribute.ActiveActor){const c=a.attribute.ActiveActor.actor;this.actorLinks[a.actor_id]||(this.actorLinks[a.actor_id]=new Set),this.actorLinks[a.actor_id].add(c),r&&r.userData.isCar&&this.checkCarPlayerLink(c,a.actor_id)}if(r&&a.attribute&&a.attribute.RigidBody){const c=a.attribute.RigidBody;if(c.location&&(r.userData.location.set(c.location.x,c.location.z,c.location.y),r.userData.lastUpdateTime=e.time,r.userData.hasReceivedUpdate=!0),c.linear_velocity&&(r.userData.velocity||(r.userData.velocity=new T),r.userData.velocity.set(c.linear_velocity.x,c.linear_velocity.z,c.linear_velocity.y)),c.rotation&&r.userData.rotation.set(c.rotation.x,c.rotation.z,c.rotation.y,-c.rotation.w),c.angular_velocity&&(r.userData.angularVelocity||(r.userData.angularVelocity=new T),r.userData.angularVelocity.set(c.angular_velocity.x,c.angular_velocity.z,c.angular_velocity.y)),c.sleeping!==void 0&&(r.userData.sleeping=c.sleeping,c.sleeping&&(r.userData.velocity&&r.userData.velocity.set(0,0,0),r.userData.angularVelocity&&r.userData.angularVelocity.set(0,0,0))),r.userData.isBall&&r.userData.isHiddenByGoal&&c.location){const u=c.location.x,d=c.location.y,h=c.location.z;Math.sqrt(u*u+d*d+h*h)<500&&(r.userData.isHiddenByGoal=!1)}}}),this.effectsManager.explosions.goalEvents.has(i)){const a=this.effectsManager.explosions.goalEvents.get(i),r=this.actors[this.ballActorId];r&&(s||(this.effectsManager.triggerGoalExplosion(r.position,a.team),console.log(`🎯 GOAL! Explosion at frame ${i} for team ${a.team} by ${a.playerName}`)),r.userData.isHiddenByGoal=!0)}if(this.effectsManager.explosions.demoEvents.has(i)){const a=this.effectsManager.explosions.demoEvents.get(i),r=this.actors[a.victimActorId];if(r){if(!s){const o=r.userData.playerId,l=o&&this.playerTeams&&this.playerTeams[o]||0;this.effectsManager.triggerDemoExplosion(r.position,l),console.log(`💥 DEMO! Explosion at frame ${i} for actor ${a.victimActorId}`)}r.userData.sleeping=!0}}}}resolveBodyId(e,t){if(!e||!e.userData.isCar||!e.userData.teamLoadout)return;let i=0;e.userData.playerId&&Object.prototype.hasOwnProperty.call(this.playerTeams,e.userData.playerId)&&(i=this.playerTeams[e.userData.playerId]);const s=e.userData.teamLoadout,a=i===1?s.orange?.body:s.blue?.body;a&&e.userData.bodyId!==a&&(e.userData.bodyId=a,this.updateCarHitbox(e,a,t))}updateCarHitbox(e,t,i){const s=tS(t),a=s?.name||"Octane",r=s?.hitboxType||"Octane";this.replaceCarWithModel(i,e,a,r)}async replaceCarWithModel(e,t,i,s){if(this.carModelLoader.isModelReady(i,s))this._doCarReplacement(e,t,i,s);else{this.pendingCarReplacements.set(e,{oldMesh:t,carName:i,hitboxType:s});try{const a=this.carModelLoader.getModelTypeForCar(i,s);await this.carModelLoader.loadModel(a);const r=this.pendingCarReplacements.get(e);r&&this.actors[e]===r.oldMesh&&this._doCarReplacement(e,r.oldMesh,r.carName,r.hitboxType),this.pendingCarReplacements.delete(e)}catch(a){console.warn(`Failed to load model for ${i} (${s}):`,a),this.pendingCarReplacements.delete(e),t&&(t.visible=!0)}}}_doCarReplacement(e,t,i,s){let a=0;t.userData.playerId&&Object.prototype.hasOwnProperty.call(this.playerTeams,t.userData.playerId)?a=this.playerTeams[t.userData.playerId]:t.userData.team!==void 0&&(a=t.userData.team);const r=this.carModelLoader.getCarMeshSync(i,s,a);if(!r){console.warn(`Could not get car mesh for ${i} (${s})`);return}const o=r.userData.wheels;r.userData={...t.userData},r.userData.isFBXModel=!0,r.userData.carName=i,r.userData.hitboxType=s,r.userData.wheels=o,r.position.copy(t.position),r.quaternion.copy(t.quaternion),this.scene.remove(t),t.geometry&&t.geometry.dispose(),t.material&&(Array.isArray(t.material)?t.material.forEach(c=>c.dispose()):t.material.dispose()),this.scene.add(r),this.actors[e]=r,this.effectsManager.removeBoostTrail(e),this.effectsManager.createBoostTrail(r,e);const l=this.carModelLoader.getModelTypeForCar(i,s);console.log(`🚗 Replaced car ${e} with ${l.toUpperCase()} model (${i}, ${s} hitbox, team ${a===0?"blue":"orange"})`)}checkCarPlayerLink(e,t){const i=this.actorToPlayer[e],s=this.actorLoadouts[e];if(!(!i&&!s))if(t){const a=this.actors[t];a&&a.userData.isCar&&(this.onPlayerFound&&this.onPlayerFound(i),a.userData.playerId=i,this.playerNameToCarActorId[i]=t,s&&(a.userData.teamLoadout=s),this.resolveBodyId(a,t))}else this.actorLinks[e]&&this.actorLinks[e].forEach(a=>{this.checkCarPlayerLink(e,a)})}updateInterpolation(e,t,i){const s=t[i];if(s&&Object.keys(this.actors).forEach(a=>{const r=this.actors[a],o=r.userData.location,l=r.userData.rotation;if(!o||!l||!r.userData.hasReceivedUpdate)return;let c=null,u=0;for(let d=i+1;dp.actor_id==a&&p.attribute&&p.attribute.RigidBody);if(f){c=f,u=h.time;break}}}if(c){const d=r.userData.lastUpdateTime||s.time,h=u;if(h>d){const f=(e-d)/(h-d),p=Math.max(0,Math.min(1,f)),g=h-d||.033,_=c.attribute.RigidBody;if(_.location)if(this._p0.copy(o),this._p1.set(_.location.x,_.location.z,_.location.y),r.userData.sleeping)r.position.copy(o);else{const m=c.attribute.RigidBody;if(r.userData.velocity&&m.linear_velocity){const v=p,y=v*v,b=y*v;if(g>.5)r.position.lerpVectors(o,this._p1,p);else{this._v0.copy(r.userData.velocity).multiplyScalar(g),this._v1.set(m.linear_velocity.x,m.linear_velocity.z,m.linear_velocity.y).multiplyScalar(g);const S=2*b-3*y+1,x=b-2*y+v,M=-2*b+3*y,C=b-y;r.position.set(S*this._p0.x+x*this._v0.x+M*this._p1.x+C*this._v1.x,S*this._p0.y+x*this._v0.y+M*this._p1.y+C*this._v1.y,S*this._p0.z+x*this._v0.z+M*this._p1.z+C*this._v1.z)}}else r.position.lerpVectors(o,this._p1,p)}else r.position.copy(o);_.rotation?(this._nextRot.set(_.rotation.x,_.rotation.z,_.rotation.y,-_.rotation.w),r.quaternion.slerpQuaternions(l,this._nextRot,p)):r.quaternion.copy(l);return}}r.position.copy(o),r.quaternion.copy(l)}),Object.keys(this.actors).forEach(a=>{const r=this.actors[a];if(r&&r.userData.isCar){const l=r.position.length()>.1,c=r.userData.sleeping===!0;r.visible=l&&!c}}),this.ballActorId&&this.actors[this.ballActorId]){const a=this.actors[this.ballActorId];if(a.visible=!a.userData.isHiddenByGoal,this.ballIndicator&&(this.ballIndicator.position.set(a.position.x,2,a.position.z),this.ballIndicator.visible=a.visible),this.ballVerticalLine){const o=new Float32Array([a.position.x,2,a.position.z,a.position.x,a.position.y,a.position.z]);this.ballVerticalLine.geometry.setAttribute("position",new ot(o,3)),this.ballVerticalLine.geometry.attributes.position.needsUpdate=!0,this.ballVerticalLine.visible=a.visible}if(a.userData.velocity&&a.visible){let r=this.lastBallTouchTeam,o=this.BALL_TOUCH_DISTANCE;Object.keys(this.actors).forEach(l=>{const c=this.actors[l];if(c&&c.userData.isCar&&c.userData.playerId){const u=a.position.distanceTo(c.position);if(u{const s=this.actors[i];if(!s||!s.userData.isCar||!s.userData.isFBXModel&&!s.userData.hasWheelSockets||!s.userData.wheels||s.userData.wheels.length===0)return;const a=s.position;let r=this._previousCarPositions.get(i);r||(r=a.clone(),this._previousCarPositions.set(i,r));const l=new T().subVectors(a,r).length();if(this._previousCarPositions.set(i,a.clone()),l<.01)return;const d=Math.min(l/e,.5)*1;let h=0;s.userData.steer!==void 0&&(h=-s.userData.steer*t),s.userData.wheels.forEach(f=>{if(f.socket){const p=f.side==="left"?1:-1;if(f.mesh.rotateZ(p*d),f.position==="front"&&f.steeringPivot){const g=f.side==="left"?-1:1;f.steeringPivot.rotation.y=g*h}}else{const p=f.side==="left"?-1:1;f.mesh.rotateY(p*d),f.position==="front"&&f.steeringPivot&&(f.steeringPivot.rotation.z=h)}})})}resetWheelTracking(){this._previousCarPositions&&this._previousCarPositions.clear()}updateSupersonicState(e,t,i){const s=this.playerNameToCarActorId[e];if(!s)return;const a=this.actors[s];if(!a||!a.userData.isCar)return;const r=a.userData.velocity||new T(0,0,0);this.effectsManager.updateSupersonicTrail(s,t,a.position,a.quaternion,r,i)}setInterpolationEnabled(e){this.interpolationEnabled=e,console.log(`[ActorManager] Interpolation ${e?"enabled":"disabled"}`)}setInterpolationMethod(e){if(!["lerp","hermite","catmull-rom","predict-correct","velocity-smooth","physics-tick","velocity-only","smart-hybrid","time-shifted","lerp-smooth","lerp-ema","lerp-dema","lerp-wma","lerp-gauss","one-euro","position-lerp","position-catmull","position-smooth","adaptive-smooth"].includes(e)){console.warn(`[ActorManager] Invalid interpolation method: ${e}`);return}this.interpolationMethod=e,this._smoothingBuffers.clear(),this._lowPassState.clear(),this._adaptiveState.clear(),this.resetSmoothingBuffers(),console.log(`[ActorManager] Interpolation method set to: ${e}`)}setSmoothingWindowSize(e){this.smoothingWindowSize=Math.max(1,Math.min(20,e)),this._smoothingBuffers.clear(),console.log(`[ActorManager] Smoothing window size set to: ${this.smoothingWindowSize}`)}getInterpolationSettings(){return{enabled:this.interpolationEnabled,method:this.interpolationMethod,smoothingWindowSize:this.smoothingWindowSize}}clearSmoothingBuffers(){this._smoothingBuffers.clear()}getFrameInfo(){return this.lastFrameInfo}createBallMeshForLive(){const e=new vn(92.75,16,16),t=new kn({color:16777215}),i=new Se(e,t);if(i.castShadow=!0,i.receiveShadow=!0,i.userData={location:new T,rotation:new ht,velocity:new T,angularVelocity:new T,isCar:!1,isBall:!0,playerId:null,sleeping:!1,isHiddenByGoal:!1},this.scene.add(i),this.ballModel){const s=this.ballModel.clone();s.position.copy(i.position),s.quaternion.copy(i.quaternion),s.userData={...i.userData};const a=92.75;return s.scale.set(a,a,a),s.traverse(r=>{r.isMesh&&(r.castShadow=!0,r.receiveShadow=!0)}),this.scene.remove(i),this.scene.add(s),i.geometry&&i.geometry.dispose(),i.material&&i.material.dispose(),console.log("✓ Live ball created with GLTF model"),s}return i}createCarMeshForLive(e,t,i,s=null){const a=`live_car_${t}`,r=new ki(118,36,84),o=e===0?3381759:16737792,l=new kn({color:o}),c=new Se(r,l);return c.castShadow=!0,c.receiveShadow=!0,c.visible=!1,c.userData={location:new T,rotation:new ht,velocity:new T,angularVelocity:new T,isCar:!0,isBall:!1,playerId:i,team:e,sleeping:!1,steer:0,bodyId:s,liveActorId:a},this.scene.add(c),this.actors[a]=c,this.playerNameToCarActorId[i]=a,this.effectsManager.createBoostTrail(c,a),s&&s>0?this.updateCarHitbox(c,s,a):this.replaceCarWithModel(a,c,"Octane","Octane"),console.log(`[ActorManager] Created live car for ${i} (team ${e===0?"blue":"orange"}, bodyId: ${s})`),c}updateBoostParticlesLive(e,t,i,s){const a=t&&i>0,r=s.userData.velocity||new T(0,0,0);this.effectsManager.updateBoostTrail(e,a,s.position,s.quaternion,r)}updateSupersonicTrailLive(e,t,i,s){const a=s.userData.velocity||new T(0,0,0);this.effectsManager.updateSupersonicTrail(e,t,s.position,s.quaternion,a,i)}removeLiveCar(e){const t=this.actors[e];t&&(this.scene.remove(t),t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose(),delete this.actors[e],this.effectsManager.removeBoostTrail(e))}removeLiveBall(e){e&&(this.scene.remove(e),e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose())}}function Ls(n,e,t){t===-1?(n.clearUpdateRanges?.(),n.addUpdateRange?.(0,n.count*n.itemSize)):n.addUpdateRange?(n.clearUpdateRanges(),n.addUpdateRange(e,t)):(n.updateRange.offset=e,n.updateRange.count=t)}class mt extends et{constructor(e,t){super(),this.active=!1,this.orientToMovement=!1,t&&(this.orientToMovement=!0),this.scene=e,this.geometry=null,this.mesh=null,this.nodeCenters=null,this.lastNodeCenter=null,this.currentNodeCenter=null,this.lastOrientationDir=null,this.nodeIDs=null,this.currentLength=0,this.currentEnd=0,this.currentNodeID=0,this.advanceFrequency=60,this.advancePeriod=1/this.advanceFrequency,this.lastAdvanceTime=0,this.paused=!1,this.pauseAdvanceUpdateTimeDiff=0,this._internalTime=0,this._useInternalTime=!1}setAdvanceFrequency(e){this.advanceFrequency=e,this.advancePeriod=1/this.advanceFrequency}initialize(e,t,i,s,a,r){this.deactivate(),this.destroyMesh(),this.length=t>0?t+1:0,this.dragTexture=i?1:0,this.targetObject=r,this.initializeLocalHeadGeometry(s,a),this.nodeIDs=[],this.nodeCenters=[];for(let o=0;o=this.length?0:this.currentEnd+1;if(i?this.updateNodePositionsFromTransformMatrix(s,i):this.updateNodePositionsFromOrientationTangent(s,t.position,t.tangent),this.currentLength>=1&&(this.connectNodes(this.currentEnd,s),this.currentLength>=this.length)){const a=this.currentEnd+1>=this.length?0:this.currentEnd+1;this.disconnectNodes(a)}this.currentLength=this.length&&(this.currentEnd=0),this.currentLength>=1&&(this.currentLengththis.advancePeriod?(this.advance(),this.lastAdvanceTime=t):this.updateHead()}}updateHead=(function(){const e=new Ee;return function(){this.currentEnd<0||(this.targetObject.updateMatrixWorld(),e.copy(this.targetObject.matrixWorld),this.updateNodePositionsFromTransformMatrix(this.currentEnd,e))}})();updateNodeID(e,t){this.nodeIDs[e]=t;const i=this.geometry.getAttribute("nodeID"),s=this.geometry.getAttribute("nodeVertexID");for(let a=0;a1e-4)){this.lastOrientationDir||(this.lastOrientationDir=new T),t.setFromUnitVectors(a,r),s.copy(this.currentNodeCenter);for(let f=0;f=7?(Lu.setRGB(parseFloat(d[4]),parseFloat(d[5]),parseFloat(d[6]),yt),t.colors.push(Lu.r,Lu.g,Lu.b)):t.colors.push(void 0,void 0,void 0);break;case"vn":t.normals.push(parseFloat(d[1]),parseFloat(d[2]),parseFloat(d[3]));break;case"vt":t.uvs.push(parseFloat(d[1]),parseFloat(d[2]));break}}else if(u==="f"){const h=c.slice(1).trim().split(Iv),f=[];for(let g=0,_=h.length;g<_;g++){const m=h[g];if(m.length>0){const v=m.split("/");f.push(v)}}const p=f[0];for(let g=1,_=f.length-1;g<_;g++){const m=f[g],v=f[g+1];t.addFace(p[0],m[0],v[0],p[1],m[1],v[1],p[2],m[2],v[2])}}else if(u==="l"){const d=c.substring(1).trim().split(" ");let h=[];const f=[];if(c.indexOf("/")===-1)h=d;else for(let p=0,g=d.length;p1){const h=s[1].trim().toLowerCase();t.object.smooth=h!=="0"&&h!=="off"}else t.object.smooth=!0;const d=t.object.currentMaterial();d&&(d.smooth=t.object.smooth)}else{if(c==="\0")continue;console.warn('THREE.OBJLoader: Unexpected line: "'+c+'"')}}t.finalize();const a=new Et;if(a.materialLibraries=[].concat(t.materialLibraries),!(t.objects.length===1&&t.objects[0].geometry.vertices.length===0)===!0)for(let o=0,l=t.objects.length;o0&&g.setAttribute("normal",new Ce(u.normals,3)),u.colors.length>0&&(p=!0,g.setAttribute("color",new Ce(u.colors,3))),u.hasUVIndices===!0&&g.setAttribute("uv",new Ce(u.uvs,2));const _=[];for(let v=0,y=d.length;v1){for(let v=0,y=d.length;v0){const o=new fa({size:1,sizeAttenuation:!1}),l=new $e;l.setAttribute("position",new Ce(t.vertices,3)),t.colors.length>0&&t.colors[0]!==void 0&&(l.setAttribute("color",new Ce(t.colors,3)),o.vertexColors=!0);const c=new fr(l,o);a.add(c)}return a}}const Vp=new Map;async function yF(n,e){const t=Pi("models/stadium/stadium.glb",e);let i=Vp.get(t);return i||(i=n.loadAsync(t).then(s=>{const a=s.scene;return vF(a),a}).catch(s=>{throw Vp.delete(t),s}),Vp.set(t,i)),i}function vF(n){const e=["Sol_Trait_T0","Sol_Trait_T1","Milieu_Forme","Milieu_Forme.001","cage_T0","cage_T1","Couleur_Hexagone_T0","Couleur_Hexagone_T1","wall_gradient_color_2","wall_gradient_color_2.001","Fond_BackBoard_Transparent","dégradé_transparent_T0","dégradé_transparent_T1","grid_transperant","Detail_Milieu","Detail_Milieu.001"],t=["Glow","Glass"],i=["Plafond_Hexagone_T0","Plafond_Hexagone_T1","Plafond_Transparent"];n.traverse(s=>{if(!s.isMesh)return;s.receiveShadow=!0,s.castShadow=!i.includes(s.name),t.some(r=>s.name.includes(r))&&(console.log(`[ArenaManager] Disabling frustum culling for: ${s.name}`),s.frustumCulled=!1),s.material&&/^Hexagone_T[01]$/.test(s.material.name??"")&&(s.material=s.material.clone(),s.material.transparent=!0,s.material.opacity=.18,s.material.depthWrite=!1,s.renderOrder=1),s.material&&s.material.name==="bannière_pub"&&(s.visible=!1),s.material&&s.material.name==="Sol_Hexagone"&&(s.material=s.material.clone(),s.material.color.setScalar(.35),s.material.metalness=0,s.material.roughness=1),s.material&&s.material.name&&e.includes(s.material.name)&&(console.log(`[ArenaManager] Fixing visibility for: ${s.name} (material: ${s.material.name})`),s.material=s.material.clone(),s.material.side=ut,s.material.depthWrite=!1,s.renderOrder=1,s.frustumCulled=!1)})}class bF{constructor(e,t={}){this.scene=e,this.assetBase=t.assetBase,this.arenaMeshes=[],this.drawingCollider=null,this.drawingColliderMeshes=[],this.arenaDecorMesh=null,this.showArenaDecor=!0,this.dracoLoader=new nM,this.dracoLoader.setDecoderPath(Pi("draco/",this.assetBase)),this.gltfLoader=new oy,this.gltfLoader.setDRACOLoader(this.dracoLoader)}async loadArenaMeshes(){try{console.log("Loading arena mesh...");const t=(await yF(this.gltfLoader,this.assetBase)).clone(!0);t.traverse(i=>{i.isMesh&&this.arenaMeshes.push(i)}),console.log(`[ArenaManager] Collected ${this.arenaMeshes.length} meshes for raycasting`),this.scene.add(t),console.log("Arena mesh loaded successfully with correct orientation")}catch(e){console.error("Error loading arena mesh:",e);const t=new Nn(10240,8192),i=new kn({color:3355443,side:ut}),s=new Se(t,i);s.rotation.x=-Math.PI/2,s.receiveShadow=!0,this.scene.add(s),this.arenaMeshes.push(s)}}getArenaMeshes(){return this.arenaMeshes}getDrawingColliderMeshes(){return this.drawingColliderMeshes}async loadDrawingCollider(e=!1){try{console.log("[ArenaManager] Loading drawing collider...");const i=await new gF().loadAsync(Pi("models/stadium/DrawingArena.obj",this.assetBase));i.rotation.x=Math.PI/2,i.rotation.y=Math.PI,i.scale.setScalar(.99),i.position.y=20,i.traverse(s=>{s.isMesh&&(this.drawingColliderMeshes.push(s),s.castShadow=!1,s.receiveShadow=!1,e?s.material=new je({color:65280,transparent:!0,opacity:.7,side:ut}):s.material=new je({visible:!1}))}),this.drawingCollider=i,this.scene.add(i),console.log(`[ArenaManager] Drawing collider loaded with ${this.drawingColliderMeshes.length} meshes`)}catch(t){console.error("[ArenaManager] Failed to load drawing collider:",t)}}setDrawingColliderVisible(e){for(const t of this.drawingColliderMeshes)e?t.material=new je({color:65280,wireframe:!0,transparent:!0,opacity:.5}):t.material=new je({visible:!1})}async loadArenaDecor(e=!0){try{console.log("[ArenaManager] Loading arena decoration mesh...");const t=await this.gltfLoader.loadAsync(Pi("models/stadium/arene.glb",this.assetBase));this.arenaDecorMesh=t.scene,this.showArenaDecor=e,this.arenaDecorMesh.traverse(i=>{i.isMesh&&(i.receiveShadow=!0,i.castShadow=!0)}),this.arenaDecorMesh.visible=e,this.scene.add(this.arenaDecorMesh),console.log(`[ArenaManager] Arena decoration loaded, visible: ${e}`)}catch(t){console.error("[ArenaManager] Failed to load arena decoration:",t)}}setArenaDecorVisible(e){this.showArenaDecor=e,this.arenaDecorMesh&&(this.arenaDecorMesh.visible=e,console.log(`[ArenaManager] Arena decoration visibility set to: ${e}`))}isArenaDecorVisible(){return this.showArenaDecor}}var Ii=Uint8Array,uo=Uint16Array,xF=Int32Array,iM=new Ii([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),sM=new Ii([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),wF=new Ii([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),aM=function(n,e){for(var t=new uo(31),i=0;i<31;++i)t[i]=e+=1<>1|(Ut&21845)<<1;sa=(sa&52428)>>2|(sa&13107)<<2,sa=(sa&61680)>>4|(sa&3855)<<4,h_[Ut]=((sa&65280)>>8|(sa&255)<<8)>>1}var Zl=(function(n,e,t){for(var i=n.length,s=0,a=new uo(e);s>l]=c}else for(o=new uo(i),s=0;s>15-n[s]);return o}),Oc=new Ii(288);for(var Ut=0;Ut<144;++Ut)Oc[Ut]=8;for(var Ut=144;Ut<256;++Ut)Oc[Ut]=9;for(var Ut=256;Ut<280;++Ut)Oc[Ut]=7;for(var Ut=280;Ut<288;++Ut)Oc[Ut]=8;var lM=new Ii(32);for(var Ut=0;Ut<32;++Ut)lM[Ut]=5;var EF=Zl(Oc,9,1),CF=Zl(lM,5,1),Gp=function(n){for(var e=n[0],t=1;te&&(e=n[t]);return e},Hi=function(n,e,t){var i=e/8|0;return(n[i]|n[i+1]<<8)>>(e&7)&t},$p=function(n,e){var t=e/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},AF=function(n){return(n+7)/8|0},RF=function(n,e,t){return(t==null||t>n.length)&&(t=n.length),new Ii(n.subarray(e,t))},PF=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],qi=function(n,e,t){var i=new Error(e||PF[n]);if(i.code=n,Error.captureStackTrace&&Error.captureStackTrace(i,qi),!t)throw i;return i},IF=function(n,e,t,i){var s=n.length,a=0;if(!s||e.f&&!e.l)return t||new Ii(0);var r=!t,o=r||e.i!=2,l=e.i;r&&(t=new Ii(s*3));var c=function(we){var Re=t.length;if(we>Re){var k=new Ii(Math.max(Re*2,we));k.set(t),t=k}},u=e.f||0,d=e.p||0,h=e.b||0,f=e.l,p=e.d,g=e.m,_=e.n,m=s*8;do{if(!f){u=Hi(n,d,1);var v=Hi(n,d+1,3);if(d+=3,v)if(v==1)f=EF,p=CF,g=9,_=5;else if(v==2){var x=Hi(n,d,31)+257,M=Hi(n,d+10,15)+4,C=x+Hi(n,d+5,31)+1;d+=14;for(var w=new Ii(C),E=new Ii(19),R=0;R>4;if(y<16)w[R++]=y;else{var F=0,W=0;for(y==16?(W=3+Hi(n,d,3),d+=2,F=w[R-1]):y==17?(W=3+Hi(n,d,7),d+=3):y==18&&(W=11+Hi(n,d,127),d+=7);W--;)w[R++]=F}}var H=w.subarray(0,x),ie=w.subarray(x);g=Gp(H),_=Gp(ie),f=Zl(H,g,1),p=Zl(ie,_,1)}else qi(1);else{var y=AF(d)+4,b=n[y-4]|n[y-3]<<8,S=y+b;if(S>s){l&&qi(0);break}o&&c(h+b),t.set(n.subarray(y,S),h),e.b=h+=b,e.p=d=S*8,e.f=u;continue}if(d>m){l&&qi(0);break}}o&&c(h+131072);for(var le=(1<>4;if(d+=F&15,d>m){l&&qi(0);break}if(F||qi(2),De<256)t[h++]=De;else if(De==256){Le=d,f=null;break}else{var Ke=De-254;if(De>264){var R=De-257,Oe=iM[R];Ke=Hi(n,d,(1<>4;Z||qi(3),d+=Z&15;var ie=MF[re];if(re>3){var Oe=sM[re];ie+=$p(n,d)&(1<m){l&&qi(0);break}o&&c(h+131072);var Te=h+Ke;if(h>4>7||(n[0]<<8|n[1])%31)&&qi(6,"invalid zlib data"),(n[1]>>5&1)==1&&qi(6,"invalid zlib data: "+(n[1]&32?"need":"unexpected")+" dictionary"),(n[1]>>3&4)+2};function DF(n,e){return IF(n.subarray(kF(n),-4),{i:2},e,e)}var OF=typeof TextDecoder<"u"&&new TextDecoder,FF=0;try{OF.decode(LF,{stream:!0}),FF=1}catch{}function cM(n,e,t){const i=t.length-n-1;if(e>=t[i])return i-1;if(e<=t[n])return n;let s=n,a=i,r=Math.floor((s+a)/2);for(;e=t[r+1];)e=g&&(p[f][0]=p[h][0]/o[v+1][m],_=p[f][0]*o[m][v]);const y=m>=-1?1:-m,b=d-1<=v?g-1:t-d;for(let x=y;x<=b;++x)p[f][x]=(p[h][x]-p[h][x-1])/o[v+1][m+x],_+=p[f][x]*o[m+x][v];d<=v&&(p[f][g]=-p[h][g-1]/o[v+1][d],_+=p[f][g]*o[d][v]),r[g][d]=_;const S=h;h=f,f=S}}let u=t;for(let d=1;d<=i;++d){for(let h=0;h<=t;++h)r[d][h]*=u;u*=t-d}return r}function zF(n,e,t,i,s){const a=st.toArray()),e.startKnot=this.startKnot,e.endKnot=this.endKnot,e}fromJSON(e){return super.fromJSON(e),this.degree=e.degree,this.knots=[...e.knots],this.controlPoints=e.controlPoints.map(t=>new Ye(t[0],t[1],t[2],t[3])),this.startKnot=e.startKnot,this.endKnot=e.endKnot,this}}let gt,Jt,Vn;class WF extends ln{constructor(e){super(e)}load(e,t,i,s){const a=this,r=a.path===""?Ws.extractUrlBase(e):a.path,o=new Kn(this.manager);o.setPath(a.path),o.setResponseType("arraybuffer"),o.setRequestHeader(a.requestHeader),o.setWithCredentials(a.withCredentials),o.load(e,function(l){try{t(a.parse(l,r))}catch(c){s?s(c):console.error(c),a.manager.itemError(e)}},i,s)}parse(e,t){if(ZF(e))gt=new jF().parse(e);else{const s=hM(e);if(!JF(s))throw new Error("THREE.FBXLoader: Unknown format.");if(Fv(s)<7e3)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+Fv(s));gt=new YF().parse(s)}const i=new Af(this.manager).setPath(this.resourcePath||t).setCrossOrigin(this.crossOrigin);return new XF(i,this.manager).parse(gt)}}class XF{constructor(e,t){this.textureLoader=e,this.manager=t}parse(){Jt=this.parseConnections();const e=this.parseImages(),t=this.parseTextures(e),i=this.parseMaterials(t),s=this.parseDeformers(),a=new KF().parse(s);return this.parseScene(s,a,i),Vn}parseConnections(){const e=new Map;return"Connections"in gt&>.Connections.connections.forEach(function(i){const s=i[0],a=i[1],r=i[2];e.has(s)||e.set(s,{parents:[],children:[]});const o={ID:a,relationship:r};e.get(s).parents.push(o),e.has(a)||e.set(a,{parents:[],children:[]});const l={ID:s,relationship:r};e.get(a).children.push(l)}),e}parseImages(){const e={},t={};if("Video"in gt.Objects){const i=gt.Objects.Video;for(const s in i){const a=i[s],r=parseInt(s);if(e[r]=a.RelativeFilename||a.Filename,"Content"in a){const o=a.Content instanceof ArrayBuffer&&a.Content.byteLength>0,l=typeof a.Content=="string"&&a.Content!=="";if(o||l){const c=this.parseImage(i[s]);t[a.RelativeFilename||a.Filename]=c}}}}for(const i in e){const s=e[i];t[s]!==void 0?e[i]=t[s]:e[i]=e[i].split("\\").pop()}return e}parseImage(e){const t=e.Content,i=e.RelativeFilename||e.Filename,s=i.slice(i.lastIndexOf(".")+1).toLowerCase();let a;switch(s){case"bmp":a="image/bmp";break;case"jpg":case"jpeg":a="image/jpeg";break;case"png":a="image/png";break;case"tif":a="image/tiff";break;case"tga":this.manager.getHandler(".tga")===null&&console.warn("FBXLoader: TGA loader not found, skipping ",i),a="image/tga";break;case"webp":a="image/webp";break;default:console.warn('FBXLoader: Image type "'+s+'" is not supported.');return}if(typeof t=="string")return"data:"+a+";base64,"+t;{const r=new Uint8Array(t);return window.URL.createObjectURL(new Blob([r],{type:a}))}}parseTextures(e){const t=new Map;if("Texture"in gt.Objects){const i=gt.Objects.Texture;for(const s in i){const a=this.parseTexture(i[s],e);t.set(parseInt(s),a)}}return t}parseTexture(e,t){const i=this.loadTexture(e,t);i.ID=e.id,i.name=e.attrName;const s=e.WrapModeU,a=e.WrapModeV,r=s!==void 0?s.value:0,o=a!==void 0?a.value:0;if(i.wrapS=r===0?xs:Wn,i.wrapT=o===0?xs:Wn,"Scaling"in e){const l=e.Scaling.value;i.repeat.x=l[0],i.repeat.y=l[1]}if("Translation"in e){const l=e.Translation.value;i.offset.x=l[0],i.offset.y=l[1]}return i}loadTexture(e,t){const i=e.FileName.split(".").pop().toLowerCase();let s=this.manager.getHandler(`.${i}`);s===null&&(s=this.textureLoader);const a=s.path;a||s.setPath(this.textureLoader.path);const r=Jt.get(e.id).children;let o;if(r!==void 0&&r.length>0&&t[r[0].ID]!==void 0&&(o=t[r[0].ID],(o.indexOf("blob:")===0||o.indexOf("data:")===0)&&s.setPath(void 0)),o===void 0)return console.warn("FBXLoader: Undefined filename, creating placeholder texture."),new zt;const l=s.load(o);return s.setPath(a),l}parseMaterials(e){const t=new Map;if("Material"in gt.Objects){const i=gt.Objects.Material;for(const s in i){const a=this.parseMaterial(i[s],e);a!==null&&t.set(parseInt(s),a)}}return t}parseMaterial(e,t){const i=e.id,s=e.attrName;let a=e.ShadingModel;if(typeof a=="object"&&(a=a.value),!Jt.has(i))return null;const r=this.parseParameters(e,t,i);let o;switch(a.toLowerCase()){case"phong":o=new sr;break;case"lambert":o=new Cf;break;default:console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.',a),o=new sr;break}return o.setValues(r),o.name=s,o}parseParameters(e,t,i){const s={};e.BumpFactor&&(s.bumpScale=e.BumpFactor.value),e.Diffuse?s.color=ot.colorSpaceToWorking(new de().fromArray(e.Diffuse.value),yt):e.DiffuseColor&&(e.DiffuseColor.type==="Color"||e.DiffuseColor.type==="ColorRGB")&&(s.color=ot.colorSpaceToWorking(new de().fromArray(e.DiffuseColor.value),yt)),e.DisplacementFactor&&(s.displacementScale=e.DisplacementFactor.value),e.Emissive?s.emissive=ot.colorSpaceToWorking(new de().fromArray(e.Emissive.value),yt):e.EmissiveColor&&(e.EmissiveColor.type==="Color"||e.EmissiveColor.type==="ColorRGB")&&(s.emissive=ot.colorSpaceToWorking(new de().fromArray(e.EmissiveColor.value),yt)),e.EmissiveFactor&&(s.emissiveIntensity=parseFloat(e.EmissiveFactor.value)),s.opacity=1-(e.TransparencyFactor?parseFloat(e.TransparencyFactor.value):0),(s.opacity===1||s.opacity===0)&&(s.opacity=e.Opacity?parseFloat(e.Opacity.value):null,s.opacity===null&&(s.opacity=1-(e.TransparentColor?parseFloat(e.TransparentColor.value[0]):0))),s.opacity<1&&(s.transparent=!0),e.ReflectionFactor&&(s.reflectivity=e.ReflectionFactor.value),e.Shininess&&(s.shininess=e.Shininess.value),e.Specular?s.specular=ot.colorSpaceToWorking(new de().fromArray(e.Specular.value),yt):e.SpecularColor&&e.SpecularColor.type==="Color"&&(s.specular=ot.colorSpaceToWorking(new de().fromArray(e.SpecularColor.value),yt));const a=this;return Jt.get(i).children.forEach(function(r){const o=r.relationship;switch(o){case"Bump":s.bumpMap=a.getTexture(t,r.ID);break;case"Maya|TEX_ao_map":s.aoMap=a.getTexture(t,r.ID);break;case"DiffuseColor":case"Maya|TEX_color_map":s.map=a.getTexture(t,r.ID),s.map!==void 0&&(s.map.colorSpace=yt);break;case"DisplacementColor":s.displacementMap=a.getTexture(t,r.ID);break;case"EmissiveColor":s.emissiveMap=a.getTexture(t,r.ID),s.emissiveMap!==void 0&&(s.emissiveMap.colorSpace=yt);break;case"NormalMap":case"Maya|TEX_normal_map":s.normalMap=a.getTexture(t,r.ID);break;case"ReflectionColor":s.envMap=a.getTexture(t,r.ID),s.envMap!==void 0&&(s.envMap.mapping=mr,s.envMap.colorSpace=yt);break;case"SpecularColor":s.specularMap=a.getTexture(t,r.ID),s.specularMap!==void 0&&(s.specularMap.colorSpace=yt);break;case"TransparentColor":case"TransparencyFactor":s.alphaMap=a.getTexture(t,r.ID),s.transparent=!0;break;default:console.warn("THREE.FBXLoader: %s map is not supported in three.js, skipping texture.",o);break}}),s}getTexture(e,t){return"LayeredTexture"in gt.Objects&&t in gt.Objects.LayeredTexture&&(console.warn("THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer."),t=Jt.get(t).children[0].ID),e.get(t)}parseDeformers(){const e={},t={};if("Deformer"in gt.Objects){const i=gt.Objects.Deformer;for(const s in i){const a=i[s],r=Jt.get(parseInt(s));if(a.attrType==="Skin"){const o=this.parseSkeleton(r,i);o.ID=s,r.parents.length>1&&console.warn("THREE.FBXLoader: skeleton attached to more than one geometry is not supported."),o.geometryID=r.parents[0].ID,e[s]=o}else if(a.attrType==="BlendShape"){const o={id:s};o.rawTargets=this.parseMorphTargets(r,i),o.id=s,r.parents.length>1&&console.warn("THREE.FBXLoader: morph target attached to more than one geometry is not supported."),t[s]=o}}}return{skeletons:e,morphTargets:t}}parseSkeleton(e,t){const i=[];return e.children.forEach(function(s){const a=t[s.ID];if(a.attrType!=="Cluster")return;const r={ID:s.ID,indices:[],weights:[],transformLink:new Ee().fromArray(a.TransformLink.a)};"Indexes"in a&&(r.indices=a.Indexes.a,r.weights=a.Weights.a),i.push(r)}),{rawBones:i,bones:[]}}parseMorphTargets(e,t){const i=[];for(let s=0;s1?r=o:o.length>0?r=o[0]:(r=new sr({name:ln.DEFAULT_MATERIAL_NAME,color:13421772}),o.push(r)),"color"in a.attributes&&o.forEach(function(l){l.vertexColors=!0}),a.groups.length>0){let l=!1;for(let c=0,u=a.groups.length;c=o.length)&&(d.materialIndex=o.length,l=!0)}if(l){const c=new sr;o.push(c)}}return a.FBX_Deformer?(s=new hf(a,r),s.normalizeSkinWeights()):s=new Se(a,r),s}createCurve(e,t){const i=e.children.reduce(function(a,r){return t.has(r.ID)&&(a=t.get(r.ID)),a},null),s=new Pt({name:ln.DEFAULT_MATERIAL_NAME,color:3342591,linewidth:1});return new On(i,s)}getTransformData(e,t){const i={};"InheritType"in t&&(i.inheritType=parseInt(t.InheritType.value)),"RotationOrder"in t?i.eulerOrder=_c(t.RotationOrder.value):i.eulerOrder=_c(0),"Lcl_Translation"in t&&(i.translation=t.Lcl_Translation.value),"PreRotation"in t&&(i.preRotation=t.PreRotation.value),"Lcl_Rotation"in t&&(i.rotation=t.Lcl_Rotation.value),"PostRotation"in t&&(i.postRotation=t.PostRotation.value),"Lcl_Scaling"in t&&(i.scale=t.Lcl_Scaling.value),"ScalingOffset"in t&&(i.scalingOffset=t.ScalingOffset.value),"ScalingPivot"in t&&(i.scalingPivot=t.ScalingPivot.value),"RotationOffset"in t&&(i.rotationOffset=t.RotationOffset.value),"RotationPivot"in t&&(i.rotationPivot=t.RotationPivot.value),e.userData.transformData=i}setLookAtProperties(e,t){"LookAtProperty"in t&&Jt.get(e.ID).children.forEach(function(s){if(s.relationship==="LookAtProperty"){const a=gt.Objects.Model[s.ID];if("Lcl_Translation"in a){const r=a.Lcl_Translation.value;e.target!==void 0?(e.target.position.fromArray(r),Vn.add(e.target)):e.lookAt(new T().fromArray(r))}}})}bindSkeleton(e,t,i){const s=this.parsePoseNodes();for(const a in e){const r=e[a];Jt.get(parseInt(r.ID)).parents.forEach(function(l){if(t.has(l.ID)){const c=l.ID;Jt.get(c).parents.forEach(function(d){i.has(d.ID)&&i.get(d.ID).bind(new Xo(r.bones),s[d.ID])})}})}}parsePoseNodes(){const e={};if("Pose"in gt.Objects){const t=gt.Objects.Pose;for(const i in t)if(t[i].attrType==="BindPose"&&t[i].NbPoseNodes>0){const s=t[i].PoseNode;Array.isArray(s)?s.forEach(function(a){e[a.Node]=new Ee().fromArray(a.Matrix.a)}):e[s.Node]=new Ee().fromArray(s.Matrix.a)}}return e}addGlobalSceneSettings(){if("GlobalSettings"in gt){if("AmbientColor"in gt.GlobalSettings){const e=gt.GlobalSettings.AmbientColor.value,t=e[0],i=e[1],s=e[2];if(t!==0||i!==0||s!==0){const a=new de().setRGB(t,i,s,yt);Vn.add(new Dc(a,1))}}"UnitScaleFactor"in gt.GlobalSettings&&(Vn.userData.unitScaleFactor=gt.GlobalSettings.UnitScaleFactor.value)}}}class KF{constructor(){this.negativeMaterialIndices=!1}parse(e){const t=new Map;if("Geometry"in gt.Objects){const i=gt.Objects.Geometry;for(const s in i){const a=Jt.get(parseInt(s)),r=this.parseGeometry(a,i[s],e);t.set(parseInt(s),r)}}return this.negativeMaterialIndices===!0&&console.warn("THREE.FBXLoader: The FBX file contains invalid (negative) material indices. The asset might not render as expected."),t}parseGeometry(e,t,i){switch(t.attrType){case"Mesh":return this.parseMeshGeometry(e,t,i);case"NurbsCurve":return this.parseNurbsGeometry(t)}}parseMeshGeometry(e,t,i){const s=i.skeletons,a=[],r=e.parents.map(function(d){return gt.Objects.Model[d.ID]});if(r.length===0)return;const o=e.children.reduce(function(d,h){return s[h.ID]!==void 0&&(d=s[h.ID]),d},null);e.children.forEach(function(d){i.morphTargets[d.ID]!==void 0&&a.push(i.morphTargets[d.ID])});const l=r[0],c={};"RotationOrder"in l&&(c.eulerOrder=_c(l.RotationOrder.value)),"InheritType"in l&&(c.inheritType=parseInt(l.InheritType.value)),"GeometricTranslation"in l&&(c.translation=l.GeometricTranslation.value),"GeometricRotation"in l&&(c.rotation=l.GeometricRotation.value),"GeometricScaling"in l&&(c.scale=l.GeometricScaling.value);const u=dM(c);return this.genGeometry(t,o,a,u)}genGeometry(e,t,i,s){const a=new $e;e.attrName&&(a.name=e.attrName);const r=this.parseGeoNode(e,t),o=this.genBuffers(r),l=new Ce(o.vertex,3);if(l.applyMatrix4(s),a.setAttribute("position",l),o.colors.length>0&&a.setAttribute("color",new Ce(o.colors,3)),t&&(a.setAttribute("skinIndex",new rf(o.weightsIndices,4)),a.setAttribute("skinWeight",new Ce(o.vertexWeights,4)),a.FBX_Deformer=t),o.normal.length>0){const c=new rt().getNormalMatrix(s),u=new Ce(o.normal,3);u.applyNormalMatrix(c),a.setAttribute("normal",u)}if(o.uvs.forEach(function(c,u){const d=u===0?"uv":`uv${u}`;a.setAttribute(d,new Ce(o.uvs[u],2))}),r.material&&r.material.mappingType!=="AllSame"){let c=o.materialIndex[0],u=0;if(o.materialIndex.forEach(function(d,h){d!==c&&(a.addGroup(u,h-u,c),c=d,u=h)}),a.groups.length>0){const d=a.groups[a.groups.length-1],h=d.start+d.count;h!==o.materialIndex.length&&a.addGroup(h,o.materialIndex.length-h,c)}a.groups.length===0&&a.addGroup(0,o.materialIndex.length,o.materialIndex[0])}return this.addMorphTargets(a,e,i,s),a}parseGeoNode(e,t){const i={};if(i.vertexPositions=e.Vertices!==void 0?e.Vertices.a:[],i.vertexIndices=e.PolygonVertexIndex!==void 0?e.PolygonVertexIndex.a:[],e.LayerElementColor&&e.LayerElementColor[0].Colors&&(i.color=this.parseVertexColors(e.LayerElementColor[0])),e.LayerElementMaterial&&(i.material=this.parseMaterialIndices(e.LayerElementMaterial[0])),e.LayerElementNormal&&(i.normal=this.parseNormals(e.LayerElementNormal[0])),e.LayerElementUV){i.uv=[];let s=0;for(;e.LayerElementUV[s];)e.LayerElementUV[s].UV&&i.uv.push(this.parseUVs(e.LayerElementUV[s])),s++}return i.weightTable={},t!==null&&(i.skeleton=t,t.rawBones.forEach(function(s,a){s.indices.forEach(function(r,o){i.weightTable[r]===void 0&&(i.weightTable[r]=[]),i.weightTable[r].push({id:a,weight:s.weights[o]})})})),i}genBuffers(e){const t={vertex:[],normal:[],colors:[],uvs:[],materialIndex:[],vertexWeights:[],weightsIndices:[]};let i=0,s=0,a=!1,r=[],o=[],l=[],c=[],u=[],d=[];const h=this;return e.vertexIndices.forEach(function(f,p){let g,_=!1;f<0&&(f=f^-1,_=!0);let m=[],v=[];if(r.push(f*3,f*3+1,f*3+2),e.color){const y=ku(p,i,f,e.color);l.push(y[0],y[1],y[2])}if(e.skeleton){if(e.weightTable[f]!==void 0&&e.weightTable[f].forEach(function(y){v.push(y.weight),m.push(y.id)}),v.length>4){a||(console.warn("THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights."),a=!0);const y=[0,0,0,0],b=[0,0,0,0];v.forEach(function(S,x){let M=S,C=m[x];b.forEach(function(w,E,R){if(M>w){R[E]=M,M=w;const L=y[E];y[E]=C,C=L}})}),m=y,v=b}for(;v.length<4;)v.push(0),m.push(0);for(let y=0;y<4;++y)u.push(v[y]),d.push(m[y])}if(e.normal){const y=ku(p,i,f,e.normal);o.push(y[0],y[1],y[2])}e.material&&e.material.mappingType!=="AllSame"&&(g=ku(p,i,f,e.material)[0],g<0&&(h.negativeMaterialIndices=!0,g=0)),e.uv&&e.uv.forEach(function(y,b){const S=ku(p,i,f,y);c[b]===void 0&&(c[b]=[]),c[b].push(S[0]),c[b].push(S[1])}),s++,_&&(h.genFace(t,e,r,g,o,l,c,u,d,s),i++,s=0,r=[],o=[],l=[],c=[],u=[],d=[])}),t}getNormalNewell(e){const t=new T(0,0,0);for(let i=0;i.5?new T(0,1,0):new T(0,0,1)).cross(t).normalize(),a=t.clone().cross(s).normalize();return{normal:t,tangent:s,bitangent:a}}flattenVertex(e,t,i){return new ne(e.dot(t),e.dot(i))}genFace(e,t,i,s,a,r,o,l,c,u){let d;if(u>3){const h=[],f=t.baseVertexPositions||t.vertexPositions;for(let m=0;m1&&console.warn("THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.");const r=e.get(a[0].ID);i[s]={name:t[s].attrName,layer:r}}return i}addClip(e){let t=[];const i=this;return e.layer.forEach(function(s){t=t.concat(i.generateTracks(s))}),new va(e.name,-1,t)}generateTracks(e){const t=[];let i=new T,s=new T;if(e.transform&&e.transform.decompose(i,new ht,s),i=i.toArray(),s=s.toArray(),e.T!==void 0&&Object.keys(e.T.curves).length>0){const a=this.generateVectorTrack(e.modelName,e.T.curves,i,"position");a!==void 0&&t.push(a)}if(e.R!==void 0&&Object.keys(e.R.curves).length>0){const a=this.generateRotationTrack(e.modelName,e.R.curves,e.preRotation,e.postRotation,e.eulerOrder);a!==void 0&&t.push(a)}if(e.S!==void 0&&Object.keys(e.S.curves).length>0){const a=this.generateVectorTrack(e.modelName,e.S.curves,s,"scale");a!==void 0&&t.push(a)}if(e.DeformPercent!==void 0){const a=this.generateMorphTrack(e);a!==void 0&&t.push(a)}return t}generateVectorTrack(e,t,i,s){const a=this.getTimesForAllAxes(t),r=this.getKeyframeTrackValues(a,t,i);return new qs(e+"."+s,a,r)}generateRotationTrack(e,t,i,s,a){let r,o;if(t.x!==void 0&&t.y!==void 0&&t.z!==void 0){const h=this.interpolateRotations(t.x,t.y,t.z,a);r=h[0],o=h[1]}const l=_c(0);i!==void 0&&(i=i.map(bt.degToRad),i.push(l),i=new rn().fromArray(i),i=new ht().setFromEuler(i)),s!==void 0&&(s=s.map(bt.degToRad),s.push(l),s=new rn().fromArray(s),s=new ht().setFromEuler(s).invert());const c=new ht,u=new rn,d=[];if(!o||!r)return new Ss(e+".quaternion",[0],[0]);for(let h=0;h2&&new ht().fromArray(d,(h-3)/3*4).dot(c)<0&&c.set(-c.x,-c.y,-c.z,-c.w),c.toArray(d,h/3*4);return new Ss(e+".quaternion",r,d)}generateMorphTrack(e){const t=e.DeformPercent.curves.morph,i=t.values.map(function(a){return a/100}),s=Vn.getObjectByName(e.modelName).morphTargetDictionary[e.morphName];return new ya(e.modelName+".morphTargetInfluences["+s+"]",t.times,i)}getTimesForAllAxes(e){let t=[];if(e.x!==void 0&&(t=t.concat(e.x.times)),e.y!==void 0&&(t=t.concat(e.y.times)),e.z!==void 0&&(t=t.concat(e.z.times)),t=t.sort(function(i,s){return i-s}),t.length>1){let i=1,s=t[0];for(let a=1;a=180||f[1]>=180||f[2]>=180){const g=Math.max(...f)/180,_=new rn(...c,s),m=new rn(...d,s),v=new ht().setFromEuler(_),y=new ht().setFromEuler(m);v.dot(y)&&y.set(-y.x,-y.y,-y.z,-y.w);const b=e.times[o-1],S=e.times[o]-b,x=new ht,M=new rn;for(let C=0;C<1;C+=1/g)x.copy(v.clone().slerp(y.clone(),C)),a.push(b+C*S),M.setFromQuaternion(x,s),r.push(M.x),r.push(M.y),r.push(M.z)}else a.push(e.times[o]),r.push(bt.degToRad(e.values[o])),r.push(bt.degToRad(t.values[o])),r.push(bt.degToRad(i.values[o]))}return[a,r]}}class YF{getPrevNode(){return this.nodeStack[this.currentIndent-2]}getCurrentNode(){return this.nodeStack[this.currentIndent-1]}getCurrentProp(){return this.currentProp}pushStack(e){this.nodeStack.push(e),this.currentIndent+=1}popStack(){this.nodeStack.pop(),this.currentIndent-=1}setCurrentProp(e,t){this.currentProp=e,this.currentPropName=t}parse(e){this.currentIndent=0,this.allNodes=new uM,this.nodeStack=[],this.currentProp=[],this.currentPropName="";const t=this,i=e.split(/[\r\n]+/);return i.forEach(function(s,a){const r=s.match(/^[\s\t]*;/),o=s.match(/^[\s\t]*$/);if(r||o)return;const l=s.match("^\\t{"+t.currentIndent+"}(\\w+):(.*){",""),c=s.match("^\\t{"+t.currentIndent+"}(\\w+):[\\s\\t\\r\\n](.*)"),u=s.match("^\\t{"+(t.currentIndent-1)+"}}");l?t.parseNodeBegin(s,l):c?t.parseNodeProperty(s,c,i[++a]):u?t.popStack():s.match(/^[^\s\t}]/)&&t.parseNodePropertyContinued(s)}),this.allNodes}parseNodeBegin(e,t){const i=t[1].trim().replace(/^"/,"").replace(/"$/,""),s=t[2].split(",").map(function(l){return l.trim().replace(/^"/,"").replace(/"$/,"")}),a={name:i},r=this.parseNodeAttr(s),o=this.getCurrentNode();this.currentIndent===0?this.allNodes.add(i,a):i in o?(i==="PoseNode"?o.PoseNode.push(a):o[i].id!==void 0&&(o[i]={},o[i][o[i].id]=o[i]),r.id!==""&&(o[i][r.id]=a)):typeof r.id=="number"?(o[i]={},o[i][r.id]=a):i!=="Properties70"&&(i==="PoseNode"?o[i]=[a]:o[i]=a),typeof r.id=="number"&&(a.id=r.id),r.name!==""&&(a.attrName=r.name),r.type!==""&&(a.attrType=r.type),this.pushStack(a)}parseNodeAttr(e){let t=e[0];e[0]!==""&&(t=parseInt(e[0]),isNaN(t)&&(t=e[0]));let i="",s="";return e.length>1&&(i=e[1].replace(/^(\w+)::/,""),s=e[2]),{id:t,name:i,type:s}}parseNodeProperty(e,t,i){let s=t[1].replace(/^"/,"").replace(/"$/,"").trim(),a=t[2].replace(/^"/,"").replace(/"$/,"").trim();s==="Content"&&a===","&&(a=i.replace(/"/g,"").replace(/,$/,"").trim());const r=this.getCurrentNode();if(r.name==="Properties70"){this.parseNodeSpecialProperty(e,s,a);return}if(s==="C"){const l=a.split(",").slice(1),c=parseInt(l[0]),u=parseInt(l[1]);let d=a.split(",").slice(3);d=d.map(function(h){return h.trim().replace(/^"/,"")}),s="connections",a=[c,u],tN(a,d),r[s]===void 0&&(r[s]=[])}s==="Node"&&(r.id=a),s in r&&Array.isArray(r[s])?r[s].push(a):s!=="a"?r[s]=a:r.a=a,this.setCurrentProp(r,s),s==="a"&&a.slice(-1)!==","&&(r.a=Xp(a))}parseNodePropertyContinued(e){const t=this.getCurrentNode();t.a+=e,e.slice(-1)!==","&&(t.a=Xp(t.a))}parseNodeSpecialProperty(e,t,i){const s=i.split('",').map(function(u){return u.trim().replace(/^\"/,"").replace(/\s/,"_")}),a=s[0],r=s[1],o=s[2],l=s[3];let c=s[4];switch(r){case"int":case"enum":case"bool":case"ULongLong":case"double":case"Number":case"FieldOfView":c=parseFloat(c);break;case"Color":case"ColorRGB":case"Vector3D":case"Lcl_Translation":case"Lcl_Rotation":case"Lcl_Scaling":c=Xp(c);break}this.getPrevNode()[a]={type:r,type2:o,flag:l,value:c},this.setCurrentProp(this.getPrevNode(),a)}}class jF{parse(e){const t=new Ov(e);t.skip(23);const i=t.getUint32();if(i<6400)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+i);const s=new uM;for(;!this.endOfContent(t);){const a=this.parseNode(t,i);a!==null&&s.add(a.name,a)}return s}endOfContent(e){return e.size()%16===0?(e.getOffset()+160+16&-16)>=e.size():e.getOffset()+160+16>=e.size()}parseNode(e,t){const i={},s=t>=7500?e.getUint64():e.getUint32(),a=t>=7500?e.getUint64():e.getUint32();t>=7500?e.getUint64():e.getUint32();const r=e.getUint8(),o=e.getString(r);if(s===0)return null;const l=[];for(let h=0;h0?l[0]:"",u=l.length>1?l[1]:"",d=l.length>2?l[2]:"";for(i.singleProperty=a===1&&e.getOffset()===s;s>e.getOffset();){const h=this.parseNode(e,t);h!==null&&this.parseSubNode(o,i,h)}return i.propertyList=l,typeof c=="number"&&(i.id=c),u!==""&&(i.attrName=u),d!==""&&(i.attrType=d),o!==""&&(i.name=o),i}parseSubNode(e,t,i){if(i.singleProperty===!0){const s=i.propertyList[0];Array.isArray(s)?(t[i.name]=i,i.a=s):t[i.name]=s}else if(e==="Connections"&&i.name==="C"){const s=[];i.propertyList.forEach(function(a,r){r!==0&&s.push(a)}),t.connections===void 0&&(t.connections=[]),t.connections.push(s)}else if(i.name==="Properties70")Object.keys(i).forEach(function(a){t[a]=i[a]});else if(e==="Properties70"&&i.name==="P"){let s=i.propertyList[0],a=i.propertyList[1];const r=i.propertyList[2],o=i.propertyList[3];let l;s.indexOf("Lcl ")===0&&(s=s.replace("Lcl ","Lcl_")),a.indexOf("Lcl ")===0&&(a=a.replace("Lcl ","Lcl_")),a==="Color"||a==="ColorRGB"||a==="Vector"||a==="Vector3D"||a.indexOf("Lcl_")===0?l=[i.propertyList[4],i.propertyList[5],i.propertyList[6]]:l=i.propertyList[4],t[s]={type:a,type2:r,flag:o,value:l}}else t[i.name]===void 0?typeof i.id=="number"?(t[i.name]={},t[i.name][i.id]=i):t[i.name]=i:i.name==="PoseNode"?(Array.isArray(t[i.name])||(t[i.name]=[t[i.name]]),t[i.name].push(i)):t[i.name][i.id]===void 0&&(t[i.name][i.id]=i)}parseProperty(e){const t=e.getString(1);let i;switch(t){case"C":return e.getBoolean();case"D":return e.getFloat64();case"F":return e.getFloat32();case"I":return e.getInt32();case"L":return e.getInt64();case"R":return i=e.getUint32(),e.getArrayBuffer(i);case"S":return i=e.getUint32(),e.getString(i);case"Y":return e.getInt16();case"b":case"c":case"d":case"f":case"i":case"l":const s=e.getUint32(),a=e.getUint32(),r=e.getUint32();if(a===0)switch(t){case"b":case"c":return e.getBooleanArray(s);case"d":return e.getFloat64Array(s);case"f":return e.getFloat32Array(s);case"i":return e.getInt32Array(s);case"l":return e.getInt64Array(s)}const o=DF(new Uint8Array(e.getArrayBuffer(r))),l=new Ov(o.buffer);switch(t){case"b":case"c":return l.getBooleanArray(s);case"d":return l.getFloat64Array(s);case"f":return l.getFloat32Array(s);case"i":return l.getInt32Array(s);case"l":return l.getInt64Array(s)}break;default:throw new Error("THREE.FBXLoader: Unknown property type "+t)}}}class Ov{constructor(e,t){this.dv=new DataView(e),this.offset=0,this.littleEndian=t!==void 0?t:!0,this._textDecoder=new TextDecoder}getOffset(){return this.offset}size(){return this.dv.buffer.byteLength}skip(e){this.offset+=e}getBoolean(){return(this.getUint8()&1)===1}getBooleanArray(e){const t=[];for(let i=0;i=0&&(i=new Uint8Array(this.dv.buffer,t,s)),this._textDecoder.decode(i)}}class uM{add(e,t){this[e]=t}}function ZF(n){const e="Kaydara FBX Binary \0";return n.byteLength>=e.length&&e===hM(n,0,e.length)}function JF(n){const e=["K","a","y","d","a","r","a","\\","F","B","X","\\","B","i","n","a","r","y","\\","\\"];let t=0;function i(s){const a=n[s-1];return n=n.slice(t+s),t++,a}for(let s=0;s(console.warn(`⚠️ Could not load texture ${u}:`,d.message),null))])}this._processModelMaterials(s,a,e,i.format);const o=this._calculateModelScale(s,e,i.scale);if(s.userData.scaleInfo=o,s.userData.format=i.format,i.wheelSockets){s.userData.wheelSockets=!0,s.userData.wheelModelName=i.wheelModel;const l=this._findWheelSockets(s);s.userData.wheelSocketObjects=l,console.log(`🔌 Found ${Object.keys(l).length} wheel sockets`)}return{model:s,chassisTexture:a,wheelModel:r}}_findWheelSockets(e){const t={},i=["Wheel_BL","Wheel_BR","Wheel_FL","Wheel_FR"];console.log("🔍 Searching for wheel sockets..."),e.traverse(s=>{const a=s.name,r=a.toLowerCase();for(const o of i)(a===o||r===o.toLowerCase())&&(t[o]=s,console.log(` Found socket: "${a}" at position (${s.position.x.toFixed(2)}, ${s.position.y.toFixed(2)}, ${s.position.z.toFixed(2)})`))});for(const s of i)t[s]||console.warn(` ⚠️ Missing wheel socket: ${s}`);return Object.keys(t).length===0&&(console.warn("⚠️ No wheel sockets found! Listing all objects:"),e.traverse(s=>{console.log(` - "${s.name}" (${s.type})`)})),t}_calculateModelScale(e,t,i=null){const s=new bn().setFromObject(e),a=new T;s.getSize(a),console.log(`📐 ${t.toUpperCase()} model dimensions (raw):`),console.log(` Size: X=${a.x.toFixed(2)}, Y=${a.y.toFixed(2)}, Z=${a.z.toFixed(2)}`),console.log(` Min Y: ${s.min.y.toFixed(2)}, Max Y: ${s.max.y.toFixed(2)}`);const r=this.HITBOX_DIMENSIONS[t]||this.HITBOX_DIMENSIONS.octane;let o;if(i!==null)o=i,console.log(` Using override scale: ${o}`);else{const l=a.z,u=r.length*1/l;o=u*.55,console.log(` Target RL: ${r.length} x ${r.width} x ${r.height} uu`),console.log(` Scale to RL: ${u.toFixed(4)}, Final scale: ${o.toFixed(6)}`)}return{scale:o}}_loadFBX(e){return new Promise((t,i)=>{this.fbxLoader.load(e,s=>t(s),void 0,s=>i(new Error(`Failed to load FBX: ${e} - ${s.message}`)))})}_loadGLB(e){return new Promise((t,i)=>{this.gltfLoader.load(e,s=>{t(s.scene)},void 0,s=>i(new Error(`Failed to load GLB: ${e} - ${s.message}`)))})}async loadWheelModel(e){const t=Pi(`models/wheels/${e}`,this.assetBase);if(this.wheelModelCache.has(t))return this.wheelModelCache.get(t);if(this.wheelLoadingPromises.has(t))return this.wheelLoadingPromises.get(t);const i=this._loadGLB(t);this.wheelLoadingPromises.set(t,i);try{const s=await i;return console.log(`✓ Loaded wheel model: ${e}`),s.traverse(a=>{a.isMesh&&(a.castShadow=!0,a.receiveShadow=!0)}),this.wheelModelCache.set(t,s),s}catch(s){throw console.error(`Failed to load wheel model ${e}:`,s),s}finally{this.wheelLoadingPromises.delete(t)}}_loadTexture(e){return new Promise((t,i)=>{this.textureLoader.load(e,s=>{s.flipY=!1,s.colorSpace=yt,t(s)},void 0,s=>i(new Error(`Failed to load texture: ${e}`)))})}_processModelMaterials(e,t,i,s="fbx"){console.log(`📦 Processing materials for ${i} (${s}):`);const a=["body","paint"],r=[];e.traverse(o=>{o.isLight&&(r.push(o),console.log(` 🔦 Removing imported light: "${o.name||o.type}"`))}),r.forEach(o=>{o.parent&&o.parent.remove(o)}),e.traverse(o=>{o.isMesh&&(console.log(` Mesh: "${o.name}"`),(Array.isArray(o.material)?o.material:[o.material]).forEach((c,u)=>{console.log(` [${u}] Material: "${c.name}" - Color: #${c.color?.getHexString()||"none"}`);const d=(c.name||"").toLowerCase(),h=(o.name||"").toLowerCase(),f=a.some(p=>d.includes(p)||h.includes(p));if(s==="glb")(c.isMeshStandardMaterial||c.isMeshPhysicalMaterial)&&(console.log(` → GLB material (keeping as-is): metalness=${c.metalness?.toFixed(2)}, roughness=${c.roughness?.toFixed(2)}`),c.userData.originalColor=c.color?.clone(),c.userData.isBodyMaterial=f);else if(c.isMeshPhongMaterial||c.isMeshLambertMaterial||c.isMeshBasicMaterial){let p;f?(p=new kn({color:c.color,map:c.map,metalness:.8,roughness:.15}),console.log(" → Body material: shiny metallic")):(p=new kn({color:c.color,map:c.map,metalness:.1,roughness:.6}),console.log(" → Non-body material: matte")),p.name=c.name,Array.isArray(o.material)?o.material[u]=p:o.material=p}}))}),t?console.log(` ✓ Chassis texture loaded for ${i}`):s==="fbx"&&console.log(` ⚠️ No chassis texture for ${i}`)}getModelTypeForCar(e,t){return e&&this.carNameToModel[e]?this.carNameToModel[e]:this.hitboxToModel[t]||"octane"}getModelTypeForHitbox(e){return this.hitboxToModel[e]||"octane"}async createCarMesh(e,t=0){const i=this.getModelTypeForHitbox(e);try{const s=await this.loadModel(i);if(!s||!s.model)return console.warn(`No cached model for ${i}`),null;const a=s.model.userData.format||"fbx";let r;a==="glb"?(r=Kp(s.model),r.traverse(c=>{c.isMesh&&(Array.isArray(c.material)?c.material=c.material.map(u=>u.clone()):c.material&&(c.material=c.material.clone()))})):r=s.model.clone(),this.applyTeamColor(r,t);const o=new Et,l=s.model.userData.scaleInfo;return l&&r.scale.setScalar(l.scale),o.add(r),r.traverse(c=>{c.isMesh&&(c.castShadow=!0)}),o.userData.modelType=i,o.userData.hitboxType=e,o.userData.team=t,o.userData.isFBXModel=a==="fbx",o.userData.isGLBModel=a==="glb",o}catch(s){return console.error(`Failed to create car mesh for ${e}:`,s),null}}applyTeamColor(e,t){const i=t===0?this.TEAM_COLORS.blue:this.TEAM_COLORS.orange,s=["body","paint"];let a=!1;console.log("🔍 Analyzing car meshes for team coloring:"),e.traverse(r=>{if(r.isMesh){const o=Array.isArray(r.material)?r.material:[r.material];console.log(` Mesh: "${r.name}" with ${o.length} material(s)`),o.forEach((l,c)=>{console.log(` [${c}] Material: "${l.name}", isBodyMaterial: ${l.userData?.isBodyMaterial}`)})}}),e.traverse(r=>{r.isMesh&&(Array.isArray(r.material)?r.material:[r.material]).forEach((l,c)=>{const u=(l.name||"").toLowerCase(),d=(r.name||"").toLowerCase(),h=l.userData?.isBodyMaterial||s.some(f=>u.includes(f)||d.includes(f));if(console.log(` Checking "${l.name}" on "${r.name}": isBody=${h}`),h){a=!0;const f=l.clone();f.color=i.clone(),f.metalness=.39,f.roughness=.47,f.userData={...l.userData},Array.isArray(r.material)?r.material[c]=f:r.material=f,console.log(`🎨 Applied team color to: "${l.name}" on mesh "${r.name}" (index ${c})`)}})}),a||console.warn("⚠️ No body material found for team coloring! Check material names.")}updateTeamColor(e,t){this.applyTeamColor(e,t)}isModelReady(e,t){const i=this.getModelTypeForCar(e,t);return this.modelCache.has(this.modelCacheKey(i))}getCarMeshSync(e,t,i=0){const s=this.getModelTypeForCar(e,t),a=this.modelCache.get(this.modelCacheKey(s));if(!a||!a.model)return null;const r=a.model.userData.format||"fbx",o=a.model.userData.wheelSockets;let l;r==="glb"?(l=Kp(a.model),l.traverse(d=>{d.isMesh&&(Array.isArray(d.material)?d.material=d.material.map(h=>h.clone()):d.material&&(d.material=d.material.clone()))})):l=a.model.clone(),this.applyTeamColor(l,i);const c=new Et,u=a.model.userData.scaleInfo;return u&&l.scale.setScalar(u.scale),c.add(l),l.traverse(d=>{d.isMesh&&(d.castShadow=!0)}),c.userData.modelType=s,c.userData.carName=e,c.userData.hitboxType=t,c.userData.team=i,c.userData.isFBXModel=r==="fbx",c.userData.isGLBModel=r==="glb",c.userData.hasWheelSockets=o,o?c.userData.wheels=this._attachWheelsToSockets(l,a.wheelModel):c.userData.wheels=this._findWheelMeshes(l),c}_attachWheelsToSockets(e,t){const i=[],s={Wheel_FL:{side:"left",position:"front"},Wheel_FR:{side:"right",position:"front"},Wheel_BL:{side:"left",position:"rear"},Wheel_BR:{side:"right",position:"rear"}};if(!t)return console.warn("⚠️ No wheel model template available for socket attachment"),i;console.log("🔧 Attaching wheels to sockets...");const a={};e.traverse(r=>{const o=r.name;s[o]&&(a[o]=r)});for(const[r,o]of Object.entries(s)){const l=a[r];if(!l){console.warn(` ⚠️ Socket not found: ${r}`);continue}const c=Kp(t);c.traverse(u=>{u.isMesh&&(Array.isArray(u.material)?u.material=u.material.map(d=>d.clone()):u.material&&(u.material=u.material.clone()),u.castShadow=!0)}),c.position.set(0,0,0),c.rotation.set(0,0,0),l.add(c),console.log(` ✓ Attached wheel to ${r} (${o.position} ${o.side})`),i.push({mesh:c,steeringPivot:o.position==="front"?l:null,side:o.side,position:o.position,socket:l})}return console.log(`✓ Attached ${i.length} wheels to sockets`),i}_findWheelMeshes(e){const t=[],i={fl:{side:"left",position:"front"},fr:{side:"right",position:"front"},rl:{side:"left",position:"rear"},rr:{side:"right",position:"rear"}};console.log("🔍 Searching for wheels in model...");const s={};e.traverse(a=>{const o=a.name.toLowerCase().match(/^wheel_(fl|fr|rl|rr)_(y|z)$/);if(o){const l=o[1],c=o[2];s[l]||(s[l]={}),s[l][c]=a,console.log(` Found: "${a.name}" (${c==="y"?"wheel mesh":"steering pivot"})`)}});for(const[a,r]of Object.entries(s)){const o=i[a];if(!o)continue;const l=r.y,c=r.z;l&&(a==="fr"&&(l.rotation.z+=Math.PI,console.log(" Fixed FR wheel orientation (rotation.z += PI)")),t.push({mesh:l,steeringPivot:o.position==="front"?c:null,side:o.side,position:o.position}),console.log(`🛞 Wheel ${a.toUpperCase()}: mesh="${l.name}"${c&&o.position==="front"?`, steering="${c.name}"`:""}`))}return t.length===0?(console.warn("⚠️ No wheel meshes found. Expected: Wheel_FL_Y, Wheel_FR_Y, etc."),console.warn(" Listing all objects in model:"),e.traverse(a=>{console.log(` - "${a.name}" (${a.type})`)})):console.log(`✓ Found ${t.length} wheels`),t}dispose(){}}const lN=2,qp=new Map;function cN(n){const e=Pi("models/ball/scene.gltf",n);let t=qp.get(e);if(!t){const i=new oy;t=new Promise(s=>{i.load(e,a=>{console.log("✓ Ball model loaded"),s(a.scene)},void 0,a=>{console.error("Failed to load ball model:",a),qp.delete(e),s(null)})}),qp.set(e,t)}return t}class uN{constructor(e,t,i={}){this.scene=e,this.effectsManager=t,this.assetBase=i.assetBase,this.actors={},this.ballActorId=null,this.ballIndicator=null,this.ballVerticalLine=null,this.playerNames=new Set,this.actorToPlayer={},this.actorLinks={},this.playerNameToCarActorId={},this.playerNameToPriActorId={},this.playerTeams={},this.actorLoadouts={},this.carBodyIds={},this.carModelLoader=new oN({assetBase:this.assetBase}),this.pendingCarReplacements=new Map,this._lastGoalScanTime=null,this._firedGoalTimes=new Set,this._p0=new T,this._p1=new T,this._v0=new T,this._v1=new T,this._nextRot=new ht,this._q0=new ht,this._q1=new ht,this._qResult=new ht,this.onPlayerFound=null,this.lastBallTouchTeam=0,this.BALL_TOUCH_DISTANCE=200,this.ballTimeline=[],this.playerTimelineMap={},this.timelineIndices={ball:0,players:{}},this.interpolantsInitialized=!1,this.animationMixer=null,this.animationActions={},this.animationClock=new Jg(!1),this.replayDuration=0,this.useAnimationSystem=!1,this.SMOOTHING_WINDOW=5,this.positionBuffers={},this.rotationBuffers={},this.interpolationEnabled=!0,this.interpolationMethod="lerp",this.smoothingWindowSize=12,this.lastFrameInfo=null,this._lowPassState=new Map,this._lowPassAlpha=.3,this._predictState=new Map,this._predictCorrectionTime=.1,this._smoothingBuffers=new Map,this._adaptiveState=new Map,this.ballModel=null,this._ballModelReplaced=!1,this.ballModelReady=cN(this.assetBase).then(s=>(this.ballModel=s,s!==null))}async waitForBallModel(){const e=await this.ballModelReady;return e&&!this._ballModelReplaced&&this.ballActorId&&this.actors[this.ballActorId]&&(this.replaceBallWithModel(this.ballActorId),this._ballModelReplaced=!0),e}replaceBallWithModel(e){const t=this.actors[e];if(!t||!this.ballModel)return;const i=this.ballModel.clone();i.userData=t.userData,i.position.copy(t.position),i.quaternion.copy(t.quaternion),i.scale.copy(t.scale);const s=92.75;i.scale.set(s,s,s),i.traverse(a=>{a.isMesh&&(a.castShadow=!0,a.receiveShadow=!0)}),this.scene.remove(t),this.scene.add(i),t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose(),this.actors[e]=i,console.log("✓ Ball replaced with GLTF model")}reset(){Object.values(this.actors).forEach(e=>{this.scene.remove(e),e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()}),this.actors={},this.ballActorId=null,this.ballIndicator&&(this.scene.remove(this.ballIndicator),this.ballIndicator.geometry&&this.ballIndicator.geometry.dispose(),this.ballIndicator.material&&this.ballIndicator.material.dispose(),this.ballIndicator=null),this.ballVerticalLine&&(this.scene.remove(this.ballVerticalLine),this.ballVerticalLine.geometry&&this.ballVerticalLine.geometry.dispose(),this.ballVerticalLine.material&&this.ballVerticalLine.material.dispose(),this.ballVerticalLine=null),this.actorToPlayer={},this.actorLinks={},this.playerNames.clear(),this.playerNameToCarActorId={},this.playerNameToPriActorId={},this.playerTeams={},this.actorLoadouts={},this.carBodyIds={},this.pendingCarReplacements.clear(),this._lastGoalScanTime=null,this._firedGoalTimes.clear(),this.ballTimeline=[],this.playerTimelineMap={},this.ballTimelineCorrected=[],this.playerTimelineMapCorrected={},this.ballTimelineFiltered=[],this.playerTimelineMapFiltered={},this.timelineIndices={ball:0,players:{}},this.timelineIndicesFiltered={ball:0,players:{}},this.timelineIndicesCorrected={ball:0,players:{}},this.interpolantsInitialized=!1,this.animationMixer?.stopAllAction?.(),this.animationMixer=null,this.animationActions={},this.replayDuration=0,this.positionBuffers={},this.rotationBuffers={},this._lowPassState.clear(),this._predictState.clear(),this._smoothingBuffers.clear(),this._adaptiveState.clear(),this._ballModelReplaced=!1}resetGoalExplosionPlaybackState(){this._lastGoalScanTime=null,this._firedGoalTimes.clear()}setPlayerTeams(e){this.playerTeams=e}initFromFramework(e){console.log("[ActorManager] Initializing actors from framework..."),this._createBallMesh();const t=e.playerList;t.forEach((i,s)=>{this._createCarMesh(i.name,i.team,s,i.carName,i.hitboxType);const a=this.playerNameToCarActorId[i.name];this.actors[a]}),console.log(`[ActorManager] Created ${t.length} car meshes + 1 ball`)}initInterpolants(e){console.log("[ActorManager] Initializing interpolation system..."),this.ballTimeline=e.ballTimeline||[],this.playerTimelineMap=e.playerTimelines||{},this.ballTimelineCorrected=this._correctTimeShiftedPositions(this.ballTimeline),this.playerTimelineMapCorrected={},Object.entries(this.playerTimelineMap).forEach(([s,a])=>{this.playerTimelineMapCorrected[s]=this._correctTimeShiftedPositions(a)}),this.ballTimelineFiltered=this._filterBadFrames(this.ballTimeline),this.playerTimelineMapFiltered={},Object.entries(this.playerTimelineMap).forEach(([s,a])=>{this.playerTimelineMapFiltered[s]=this._filterBadFrames(a)}),this.timelineIndices={ball:0,players:{}},this.timelineIndicesFiltered={ball:0,players:{}},this.timelineIndicesCorrected={ball:0,players:{}},Object.keys(this.playerTimelineMap).forEach(s=>{this.timelineIndices.players[s]=0,this.timelineIndicesFiltered.players[s]=0,this.timelineIndicesCorrected.players[s]=0}),this.ballTimeline.length>0&&(this.replayDuration=this.ballTimeline[this.ballTimeline.length-1].time),this.useAnimationSystem&&this._initAnimationSystem(),this.interpolantsInitialized=!0;const t=this.ballTimeline.length-this.ballTimelineFiltered.length,i=this.ballTimelineCorrected._correctedCount||0;console.log(` Ball: ${this.ballTimeline.length} keyframes (${i} corrected, ${t} filtered)`),Object.entries(this.playerTimelineMap).forEach(([s,a])=>{const r=this.playerTimelineMapCorrected[s]?._correctedCount||0;console.log(` ${s}: ${a.length} keyframes (${r} corrected)`)}),console.log(` Replay duration: ${this.replayDuration.toFixed(2)}s`),console.log("[ActorManager] Animation system ready")}_initAnimationSystem(){console.log("[ActorManager] Building Three.js animation clips..."),this.animationMixer=new GT(this.scene);const e=this.actors[this.ballActorId];if(e&&this.ballTimeline.length>0){const t=this._createAnimationClip("ball",this.ballTimeline,e);if(t){const i=this.animationMixer.clipAction(t,e);i.setLoop(bh),i.clampWhenFinished=!0,this.animationActions.ball=i,console.log(` ✓ Ball animation: ${t.duration.toFixed(2)}s`)}}Object.entries(this.playerTimelineMap).forEach(([t,i])=>{const s=this.playerNameToCarActorId[t],a=this.actors[s];if(a&&i.length>0){const r=this._createAnimationClip(t,i,a);if(r){const o=this.animationMixer.clipAction(r,a);o.setLoop(bh),o.clampWhenFinished=!0,this.animationActions[t]=o,console.log(` ✓ ${t} animation: ${r.duration.toFixed(2)}s`)}}}),console.log("[ActorManager] Animation clips ready")}_createAnimationClip(e,t,i){if(!t||t.length<2)return null;const s=[],a=[],r=[],o=t[0];o.time>0&&(s.push(0),o.position?a.push(o.position.x,o.position.y,o.position.z):a.push(0,0,0),o.rotation?r.push(o.rotation.x,o.rotation.y,o.rotation.z,o.rotation.w):r.push(0,0,0,1));for(const h of t){if(s.push(h.time),h.position)a.push(h.position.x,h.position.y,h.position.z);else{const f=a.length-3;f>=0?a.push(a[f],a[f+1],a[f+2]):a.push(0,0,0)}if(h.rotation)r.push(h.rotation.x,h.rotation.y,h.rotation.z,h.rotation.w);else{const f=r.length-4;f>=0?r.push(r[f],r[f+1],r[f+2],r[f+3]):r.push(0,0,0,1)}}const l=new qs(".position",s,a,_r),c=new Ss(".quaternion",s,r),u=s[s.length-1]-s[0];return new va(e,u,[l,c])}startAnimations(){this.animationMixer&&(Object.values(this.animationActions).forEach(e=>{e.reset(),e.play()}),this.animationClock.start(),console.log("[ActorManager] Animations started"))}pauseAnimations(){this.animationMixer&&Object.values(this.animationActions).forEach(e=>{e.paused=!0})}resumeAnimations(){this.animationMixer&&Object.values(this.animationActions).forEach(e=>{e.paused=!1})}seekAnimations(e){this.animationMixer&&(Object.values(this.animationActions).forEach(t=>{t.time=e}),this.animationMixer.setTime(e))}updateAnimations(e){!this.animationMixer||!this.useAnimationSystem||this.animationMixer.update(e)}_subsampleTimeline(e){return!e||e.length<4?e:e.filter((t,i)=>i%2===0)}_getOrCreateSmoothingBuffer(e){return this.positionBuffers[e]||(this.positionBuffers[e]=[],this.rotationBuffers[e]=[]),{positions:this.positionBuffers[e],rotations:this.rotationBuffers[e]}}_smoothPosition(e,t){const i=this._getOrCreateSmoothingBuffer(e).positions;for(i.push({x:t.x,y:t.y,z:t.z});i.length>this.SMOOTHING_WINDOW;)i.shift();if(i.length===1)return t;let s=0,a=0,r=0;for(const o of i)s+=o.x,a+=o.y,r+=o.z;return{x:s/i.length,y:a/i.length,z:r/i.length}}_smoothRotation(e,t){const i=this._getOrCreateSmoothingBuffer(e).rotations;for(i.push({x:t.x,y:t.y,z:t.z,w:t.w});i.length>this.SMOOTHING_WINDOW;)i.shift();if(i.length<3)return t;const s=Math.floor(i.length/2);return i[s]}resetSmoothingBuffers(){this.positionBuffers={},this.rotationBuffers={},this._lowPassState.clear()}_findKeyframeIndex(e,t,i=0){if(!e||e.length===0)return-1;if(t<=e[0].time)return 0;if(t>=e[e.length-1].time)return e.length-2;let s=Math.max(0,Math.min(i,e.length-2));if(e[s].time<=t&&e[s+1].time>t)return s;if(s+2t)return s+1;let a=0,r=e.length-2;for(;a<=r;){const o=Math.floor((a+r)/2);if(e[o].time<=t&&e[o+1].time>t)return o;e[o].time>t?r=o-1:a=o+1}return Math.max(0,Math.min(a,e.length-2))}_applySmoothing(e,t){this._smoothingBuffers.has(e)||this._smoothingBuffers.set(e,[]);const i=this._smoothingBuffers.get(e);for(i.push({x:t.x,y:t.y,z:t.z});i.length>this.smoothingWindowSize;)i.shift();if(i.length===1)return t;let s=0,a=0,r=0;for(const o of i)s+=o.x,a+=o.y,r+=o.z;return{x:s/i.length,y:a/i.length,z:r/i.length}}_applyEmaSmoothing(e,t){const i=`ema-${e}`;if(!this._smoothingBuffers.has(i))return this._smoothingBuffers.set(i,{x:t.x,y:t.y,z:t.z}),t;const s=this._smoothingBuffers.get(i),a=Math.max(.05,Math.min(.5,1/this.smoothingWindowSize)),r={x:a*t.x+(1-a)*s.x,y:a*t.y+(1-a)*s.y,z:a*t.z+(1-a)*s.z};return this._smoothingBuffers.set(i,r),r}_applyDoubleEmaSmoothing(e,t){const i=`dema-${e}`;if(!this._smoothingBuffers.has(i))return this._smoothingBuffers.set(i,{level:{x:t.x,y:t.y,z:t.z},trend:{x:0,y:0,z:0}}),t;const s=this._smoothingBuffers.get(i),a=Math.max(.1,Math.min(.6,2/this.smoothingWindowSize)),r=a*.5,o={x:a*t.x+(1-a)*(s.level.x+s.trend.x),y:a*t.y+(1-a)*(s.level.y+s.trend.y),z:a*t.z+(1-a)*(s.level.z+s.trend.z)},l={x:r*(o.x-s.level.x)+(1-r)*s.trend.x,y:r*(o.y-s.level.y)+(1-r)*s.trend.y,z:r*(o.z-s.level.z)+(1-r)*s.trend.z};return s.level=o,s.trend=l,{x:o.x+l.x,y:o.y+l.y,z:o.z+l.z}}_applyWeightedSmoothing(e,t){const i=`wma-${e}`;this._smoothingBuffers.has(i)||this._smoothingBuffers.set(i,[]);const s=this._smoothingBuffers.get(i);for(s.push({x:t.x,y:t.y,z:t.z});s.length>this.smoothingWindowSize;)s.shift();if(s.length===1)return t;let a=0,r=0,o=0,l=0;for(let c=0;cthis.smoothingWindowSize;)s.shift();if(s.length===1)return t;const a=s.length/3;let r=0,o=0,l=0,c=0;for(let u=0;u.001&&(s.derivedVel={x:(t.x-s.lastPos.x)/a,y:(t.y-s.lastPos.y)/a,z:(t.z-s.lastPos.z)/a});const r=Math.sqrt(s.derivedVel.x**2+s.derivedVel.y**2+s.derivedVel.z**2),o=2,l=this.smoothingWindowSize,c=300,u=1500;let d;if(ru)d=o;else{const _=(r-c)/(u-c);d=Math.round(l-_*(l-o))}if(s.buffer.length>=2){const _=s.buffer[s.buffer.length-1],m=s.buffer[s.buffer.length-2],v={x:_.x-m.x,y:_.y-m.y,z:_.z-m.z},y={x:t.x-_.x,y:t.y-_.y,z:t.z-_.z},b=Math.sqrt(v.x**2+v.y**2+v.z**2),S=Math.sqrt(y.x**2+y.y**2+y.z**2);if(b>.1&&S>.1&&(v.x*y.x+v.y*y.y+v.z*y.z)/(b*S)<.5)for(;s.buffer.length>Math.max(2,d/2);)s.buffer.shift()}for(s.buffer.push({x:t.x,y:t.y,z:t.z});s.buffer.length>d;)s.buffer.shift();if(s.lastPos={x:t.x,y:t.y,z:t.z},s.lastTime=i,s.buffer.length===1)return t;let h=0,f=0,p=0,g=0;for(let _=0;_u+10&&(h.z=t.position.z+t.velocity.z*r-.5*c*r*r,h.zu+10&&(p.z=t.position.z+t.velocity.z*o-.5*c*o*o,p.z0&&o>0){const b=d*o;m>b*2&&(v=b*2/m)}const y=_*v+(1-v)*l;return{x:h.x+g.x*y,y:h.y+g.y*y,z:h.z+g.z*y}}_physicsTickInterpolate(e,t,i){const s=t.time-e.time,a=i-e.time,r=a/s;if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};const o=(e.velocity.x+t.velocity.x)/2,l=(e.velocity.y+t.velocity.y)/2,c=(e.velocity.z+t.velocity.z)/2,u=e.position.x+o*a,d=e.position.y+l*a,h=e.position.z+c*a,f=e.position.x+o*s,p=e.position.y+l*s,g=e.position.z+c*s,_=t.position.x-f,m=t.position.y-p,v=t.position.z-g;return{x:u+_*r,y:d+m*r,z:h+v*r}}_velocityOnlyInterpolate(e,t,i){const s=i-e.time,a=t.time-e.time,r=s/a;if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};const o=e.velocity.x+(t.velocity.x-e.velocity.x)*r/2,l=e.velocity.y+(t.velocity.y-e.velocity.y)*r/2,c=e.velocity.z+(t.velocity.z-e.velocity.z)*r/2;return{x:e.position.x+o*s,y:e.position.y+l*s,z:e.position.z+c*s}}_smartHybridInterpolate(e,t,i){const s=i-e.time,a=t.time-e.time,r=Math.max(0,Math.min(1,s/a));if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};const o=Math.sqrt(e.velocity.x**2+e.velocity.y**2+e.velocity.z**2),l=Math.sqrt(t.velocity.x**2+t.velocity.y**2+t.velocity.z**2);let c=1;o>10&&l>10&&(c=(e.velocity.x*t.velocity.x+e.velocity.y*t.velocity.y+e.velocity.z*t.velocity.z)/(o*l));const u=o>10?Math.abs(l-o)/o:0;if(c<.95||u>.1){const h=r*r*(3-2*r);return{x:e.position.x+(t.position.x-e.position.x)*h,y:e.position.y+(t.position.y-e.position.y)*h,z:e.position.z+(t.position.z-e.position.z)*h}}else{const h=(e.velocity.x+t.velocity.x)/2,f=(e.velocity.y+t.velocity.y)/2,p=(e.velocity.z+t.velocity.z)/2,g=e.position.x+h*s,_=e.position.y+f*s,m=e.position.z+p*s,v=e.position.x+h*a,y=e.position.y+f*a,b=e.position.z+p*a,S=t.position.x-v,x=t.position.y-y,M=t.position.z-b;return{x:g+S*r,y:_+x*r,z:m+M*r}}}_isBadFrame(e,t){if(!e.velocity||!t.velocity||!e.position||!t.position)return!1;const i=t.time-e.time;if(i<.001)return!1;const s=(e.velocity.x+t.velocity.x)/2,a=(e.velocity.y+t.velocity.y)/2,r=(e.velocity.z+t.velocity.z)/2,o=Math.sqrt(s**2+a**2+r**2);if(o<200)return!1;const l=t.position.x-e.position.x,c=t.position.y-e.position.y,u=t.position.z-e.position.z,d=Math.sqrt(l*l+c*c+u*u),h=o*i,f=d/h;return f<.6||f>1.4}_filterBadFrames(e){if(!e||e.length<2)return e;const t=[e[0]];for(let i=1;i0&&a.position&&a.velocity){const o=e[s-1];if(o.position&&o.velocity){const l=a.time-o.time;if(l>.001){const c=(o.velocity.x+a.velocity.x)/2,u=(o.velocity.y+a.velocity.y)/2,d=(o.velocity.z+a.velocity.z)/2,h=Math.sqrt(c**2+u**2+d**2);if(h>100){const f=a.position.x-o.position.x,p=a.position.y-o.position.y,g=a.position.z-o.position.z,_=Math.sqrt(f*f+p*p+g*g),m=h*l,v=_/m;let y=0;v>.15&&v<.35?y=l*.75:v>.4&&v<.6?y=l*.5:v>.65&&v<.85&&(y=l*.25),y>0&&(r.position.x+=a.velocity.x*y,r.position.y+=a.velocity.y*y,r.position.z+=a.velocity.z*y,i++)}}}}t.push(r)}return t._correctedCount=i,t}_timeShiftedInterpolate(e,t,i){const s=i-e.time,a=t.time-e.time,r=Math.max(0,Math.min(1,s/a));return{x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r}}_velocityAnchoredInterpolate(e,t,i,s,a,r){if(!t.velocity||!i.velocity){const m=(s-t.time)/(i.time-t.time);return{x:t.position.x+(i.position.x-t.position.x)*m,y:t.position.y+(i.position.y-t.position.y)*m,z:t.position.z+(i.position.z-t.position.z)*m}}this._velocityAnchorState||(this._velocityAnchorState=new Map);let o=this._velocityAnchorState.get(e);(!o||Math.abs(s-o.lastTime)>.5||r%10===0)&&(o={anchorPos:{...t.position},anchorTime:t.time,anchorIdx:r,lastTime:s},this._velocityAnchorState.set(e,o)),s-o.anchorTime;let u=o.anchorPos.x,d=o.anchorPos.y,h=o.anchorPos.z;const f=(t.velocity.x+i.velocity.x)/2,p=(t.velocity.y+i.velocity.y)/2,g=(t.velocity.z+i.velocity.z)/2,_=s-t.time;return o.anchorIdx===r?(u=o.anchorPos.x+f*_,d=o.anchorPos.y+p*_,h=o.anchorPos.z+g*_):(u=t.position.x+f*_,d=t.position.y+p*_,h=t.position.z+g*_),o.lastTime=s,{x:u,y:d,z:h}}_hermiteInterpolate(e,t,i){const s=t.time-e.time,a=i-e.time,r=Math.max(0,Math.min(1,a/s)),o={x:e.position.x+(t.position.x-e.position.x)*r,y:e.position.y+(t.position.y-e.position.y)*r,z:e.position.z+(t.position.z-e.position.z)*r};if(!e.velocity||!t.velocity)return o;const l=r*r,c=l*r,u=2*c-3*l+1,d=c-2*l+r,h=-2*c+3*l,f=c-l,p={x:e.velocity.x*s,y:e.velocity.y*s,z:e.velocity.z*s},g={x:t.velocity.x*s,y:t.velocity.y*s,z:t.velocity.z*s},_={x:u*e.position.x+d*p.x+h*t.position.x+f*g.x,y:u*e.position.y+d*p.y+h*t.position.y+f*g.y,z:u*e.position.z+d*p.z+h*t.position.z+f*g.z},m=_.x-o.x,v=_.y-o.y,y=_.z-o.z,b=t.position.x-e.position.x,S=t.position.y-e.position.y,x=t.position.z-e.position.z;return m*m+v*v+y*y>b*b+S*S+x*x?o:_}_physicsSimInterpolate(e,t,i,s=!1){const a=t.time-e.time,r=i-e.time,o=Math.max(0,Math.min(1,r/a));if(!e.velocity||!t.velocity)return{x:e.position.x+(t.position.x-e.position.x)*o,y:e.position.y+(t.position.y-e.position.y)*o,z:e.position.z+(t.position.z-e.position.z)*o};const l=-650,c=o*o,u=c*o,d=2*u-3*c+1,h=u-2*c+o,f=-2*u+3*c,p=u-c;let g=e.velocity.y*a,_=t.velocity.y*a;if(s){const m=.5*l*a*a;g+=m*.5,_+=m*.5}return{x:d*e.position.x+h*(e.velocity.x*a)+f*t.position.x+p*(t.velocity.x*a),y:d*e.position.y+h*g+f*t.position.y+p*_,z:d*e.position.z+h*(e.velocity.z*a)+f*t.position.z+p*(t.velocity.z*a)}}getBallPositionAt(e){if(!this.ballTimeline||this.ballTimeline.length<2)return null;const t=this.ballTimeline[0];if(e2e3)return s.sleeping?null:{...s.position};if(s.sleeping)return{...s.position};const d=(e-s.time)/r;let h;switch(this.interpolationMethod){case"catmull-rom":{const f=this.ballTimeline[Math.max(0,i-1)],p=this.ballTimeline[Math.min(this.ballTimeline.length-1,i+2)];f?.position&&p?.position?h=this._catmullRomInterpolate(f.position,s.position,a.position,p.position,d):h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}case"lerp-smooth":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applySmoothing("ball",h);break}case"lerp-ema":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyEmaSmoothing("ball",h);break}case"lerp-dema":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyDoubleEmaSmoothing("ball",h);break}case"lerp-wma":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyWeightedSmoothing("ball",h);break}case"lerp-gauss":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyGaussianSmoothing("ball",h);break}case"one-euro":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyOneEuroFilter("ball",h);break}case"predict-correct":{h=this._predictCorrectInterpolate("ball",s,a,e);break}case"velocity-smooth":{h=this._velocitySmoothInterpolate("ball",s,a,e,!0);break}case"physics-tick":{h=this._physicsTickInterpolate(s,a,e);break}case"hermite":{h=this._hermiteInterpolate(s,a,e);break}case"physics-sim":{const f=this.ballTimelineCorrected;if(f&&f.length>=2){const p=this._findKeyframeIndex(f,e,this.timelineIndicesCorrected.ball);this.timelineIndicesCorrected.ball=p;const g=f[p],_=f[p+1];if(g?.position&&_?.position){h=this._physicsSimInterpolate(g,_,e,!0);break}}h=this._physicsSimInterpolate(s,a,e,!0);break}case"velocity-only":{h=this._velocityOnlyInterpolate(s,a,e);break}case"smart-hybrid":{h=this._smartHybridInterpolate(s,a,e);break}case"time-shifted":{const f=this.ballTimelineFiltered;if(!f||f.length<2){h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}const p=this._findKeyframeIndex(f,e,this.timelineIndicesFiltered.ball);this.timelineIndicesFiltered.ball=p;const g=f[p],_=f[p+1];if(!g?.position||!_?.position){h=g?.position?{...g.position}:{...s.position};break}const m=_.time-g.time,v=m>0?Math.max(0,Math.min(1,(e-g.time)/m)):0;h={x:g.position.x+(_.position.x-g.position.x)*v,y:g.position.y+(_.position.y-g.position.y)*v,z:g.position.z+(_.position.z-g.position.z)*v};break}case"position-lerp":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}case"position-catmull":{const f=this.ballTimeline[Math.max(0,i-1)],p=this.ballTimeline[Math.min(this.ballTimeline.length-1,i+2)];f?.position&&p?.position?h=this._catmullRomInterpolate(f.position,s.position,a.position,p.position,d):h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}case"position-smooth":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyLowPassFilter("ball",h);break}case"adaptive-smooth":{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d},h=this._applyAdaptiveSmoothing("ball",h,e);break}default:{h={x:s.position.x+(a.position.x-s.position.x)*d,y:s.position.y+(a.position.y-s.position.y)*d,z:s.position.z+(a.position.z-s.position.z)*d};break}}return h}getBallRotationAt(e){if(!this.ballTimeline||this.ballTimeline.length<2)return null;const t=this.ballTimeline[0];if(e2e3)return{...s.rotation}}if(s.sleeping)return{...s.rotation};const o=(e-s.time)/r;return this._q0.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w),this._q1.set(a.rotation.x,a.rotation.y,a.rotation.z,a.rotation.w),this._qResult.slerpQuaternions(this._q0,this._q1,o),{x:this._qResult.x,y:this._qResult.y,z:this._qResult.z,w:this._qResult.w}}getPlayerPositionAt(e,t){const i=this.playerTimelineMap[e];if(!i||i.length<2)return null;const s=i[0];if(t=2){const h=this._findKeyframeIndex(d,t,this.timelineIndicesCorrected.players[e]||0);this.timelineIndicesCorrected.players[e]=h;const f=d[h],p=d[h+1];if(f?.position&&p?.position){u=this._physicsSimInterpolate(f,p,t,!1);break}}u=this._physicsSimInterpolate(r,o,t,!1);break}case"velocity-only":{u=this._velocityOnlyInterpolate(r,o,t);break}case"smart-hybrid":{u=this._smartHybridInterpolate(r,o,t);break}case"time-shifted":{const d=this.playerTimelineMapFiltered[e];if(!d||d.length<2){u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}const h=this._findKeyframeIndex(d,t,this.timelineIndicesFiltered.players[e]||0);this.timelineIndicesFiltered.players[e]=h;const f=d[h],p=d[h+1];if(!f?.position||!p?.position){u=f?.position?{...f.position}:{...r.position};break}const g=p.time-f.time,_=g>0?Math.max(0,Math.min(1,(t-f.time)/g)):0;u={x:f.position.x+(p.position.x-f.position.x)*_,y:f.position.y+(p.position.y-f.position.y)*_,z:f.position.z+(p.position.z-f.position.z)*_};break}case"position-lerp":{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}case"position-catmull":{const d=i[Math.max(0,a-1)],h=i[Math.min(i.length-1,a+2)];d?.position&&h?.position?u=this._catmullRomInterpolate(d.position,r.position,o.position,h.position,c):u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}case"position-smooth":{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c},u=this._applyLowPassFilter(`player-${e}`,u);break}case"adaptive-smooth":{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c},u=this._applyAdaptiveSmoothing(`player-${e}`,u,t);break}default:{u={x:r.position.x+(o.position.x-r.position.x)*c,y:r.position.y+(o.position.y-r.position.y)*c,z:r.position.z+(o.position.z-r.position.z)*c};break}}return u}getPlayerRotationAt(e,t){const i=this.playerTimelineMap[e];if(!i||i.length<2)return null;const s=i[0];if(t=2){const r=this.getBallPositionAt(t),o=this.getBallRotationAt(t);r?i.position.set(r.x,r.y,r.z):a=!1,o&&i.quaternion.set(o.x,o.y,o.z,o.w)}else i.position.set(s.position.x,s.position.y,s.position.z),i.quaternion.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w);if(i.userData.location.copy(i.position),i.userData.rotation.copy(i.quaternion),i.userData.velocity.set(s.velocity.x,s.velocity.y,s.velocity.z),s.angularVelocity&&i.userData.angularVelocity.set(s.angularVelocity.x,s.angularVelocity.y,s.angularVelocity.z),i.userData.sleeping=s.sleeping,i.visible=a&&s.visible!==!1&&!i.userData.isHiddenByGoal,this.ballIndicator&&(this.ballIndicator.position.set(i.position.x,2,i.position.z),this.ballIndicator.visible=i.visible),this.ballVerticalLine){const o=new Float32Array([i.position.x,2,i.position.z,i.position.x,i.position.y,i.position.z]);this.ballVerticalLine.geometry.setAttribute("position",new lt(o,3)),this.ballVerticalLine.geometry.attributes.position.needsUpdate=!0,this.ballVerticalLine.visible=i.visible}if(i.userData.velocity&&i.visible){let r=this.lastBallTouchTeam,o=this.BALL_TOUCH_DISTANCE;Object.keys(this.actors).forEach(l=>{const c=this.actors[l];if(c&&c.userData.isCar&&c.userData.playerId){const u=i.position.distanceTo(c.position);u{const a=this.playerNameToCarActorId[s.name];if(!a)return;const r=this.actors[a];if(!r)return;const o=s.name;if(!this.useAnimationSystem||!this.animationMixer)if(this.interpolantsInitialized&&this.playerTimelineMap[o]){const c=this.getPlayerPositionAt(o,t),u=this.getPlayerRotationAt(o,t);c&&r.position.set(c.x,c.y,c.z),u&&r.quaternion.set(u.x,u.y,u.z,u.w)}else r.position.set(s.position.x,s.position.y,s.position.z),r.quaternion.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w);r.userData.location.copy(r.position),r.userData.rotation.copy(r.quaternion),r.userData.velocity.set(s.velocity.x,s.velocity.y,s.velocity.z),r.userData.sleeping=s.sleeping,r.userData.steer=s.steer||0;const l=r.position.length()>.1;r.visible=s.isVisible&&l&&!r.userData.sleeping}),this._updateGoalExplosions(t)}_updateGoalExplosions(e){const t=this.effectsManager,i=t&&t.explosions?t.explosions.goalEvents:null;if(!(i instanceof Map)||i.size===0)return;const s=this._lastGoalScanTime;s!==null&&e=c&&e<=c+lN&&(r=!0,o=!0),s!==null&&s=c&&!this._firedGoalTimes.has(c)){this._firedGoalTimes.add(c);const d=this.getBallPositionAt(c)||a&&a.position||null;d&&this.effectsManager.triggerGoalExplosion(d,l.team)}}a&&(a.userData.isHiddenByGoal=r,r&&(a.visible=!1)),o||this.effectsManager.clearGoalExplosions?.(),this._lastGoalScanTime=e}processFrame(e,t,i,s){if(e){if(e.new_actors&&e.new_actors.forEach(a=>{if(!this.actors[a.actor_id]){const r=t(a.object_id),o=r&&r.includes("Ball"),l=r&&r.includes("Car");if(o||l){let c;o?c=new vn(92.75,16,16):c=new Di(118,36,84);const u=new kn({color:o?16777215:Math.random()*16777215}),d=new Se(c,u);if(d.userData={location:new T,rotation:new ht,isCar:l,isBall:o,playerId:null,lastUpdateTime:e.time,bodyId:null,hasReceivedUpdate:!1},this.scene.add(d),this.actors[a.actor_id]=d,o){this.ballActorId=a.actor_id,this.ballModel&&this.replaceBallWithModel(a.actor_id);const h=92.75,f=new oi(h*.95,h,32),p=new je({color:16777215,side:ut});this.ballIndicator=new Se(f,p),this.ballIndicator.rotation.x=-Math.PI/2,this.ballIndicator.visible=!1,this.scene.add(this.ballIndicator);const g=new $e().setFromPoints([new T(0,0,0),new T(0,1,0)]),_=new Pt({color:16777215,opacity:.5,transparent:!0});this.ballVerticalLine=new On(g,_),this.ballVerticalLine.frustumCulled=!1,this.ballVerticalLine.visible=!1,this.scene.add(this.ballVerticalLine)}else l&&this.effectsManager.createBoostTrail(d,a.actor_id)}}}),e.deleted_actors&&e.deleted_actors.forEach(a=>{if(this.actors[a]){const r=this.actors[a];r.userData.isCar&&this.effectsManager.removeBoostTrail(a),this.scene.remove(r),r.geometry&&r.geometry.dispose(),r.material&&r.material.dispose(),delete this.actors[a],this.ballActorId===a&&(this.ballActorId=null,this.ballIndicator&&(this.scene.remove(this.ballIndicator),this.ballIndicator.geometry&&this.ballIndicator.geometry.dispose(),this.ballIndicator.material&&this.ballIndicator.material.dispose(),this.ballIndicator=null),this.ballVerticalLine&&(this.scene.remove(this.ballVerticalLine),this.ballVerticalLine.geometry&&this.ballVerticalLine.geometry.dispose(),this.ballVerticalLine.material&&this.ballVerticalLine.material.dispose(),this.ballVerticalLine=null))}}),e.updated_actors&&e.updated_actors.forEach(a=>{const r=this.actors[a.actor_id];a.attribute.TeamLoadout&&(this.actorLoadouts[a.actor_id]=a.attribute.TeamLoadout,r&&r.userData.isCar&&(r.userData.teamLoadout=a.attribute.TeamLoadout,this.resolveBodyId(r,a.actor_id)));const o=t(a.object_id),l=o&&(o.includes("PRI_TA")||o.includes("PlayerReplicationInfo"));if(a.attribute.String&&this.playerNames.has(a.attribute.String)){const c=a.attribute.String;this.actorToPlayer[a.actor_id]=c,l&&!this.playerNameToPriActorId[c]&&(this.playerNameToPriActorId[c]=a.actor_id,console.log(`[ActorManager] Mapped ${c} -> PRI Actor ${a.actor_id} (object: ${o})`)),this.checkCarPlayerLink(a.actor_id)}if(a.attribute.Reservation&&this.playerNames.has(a.attribute.Reservation.name)){const c=a.attribute.Reservation.name;this.actorToPlayer[a.actor_id]=c,l&&!this.playerNameToPriActorId[c]&&(this.playerNameToPriActorId[c]=a.actor_id,console.log(`[ActorManager] Mapped ${c} -> PRI Actor ${a.actor_id} (object: ${o})`)),this.checkCarPlayerLink(a.actor_id)}if(a.attribute.ActiveActor){const c=a.attribute.ActiveActor.actor;this.actorLinks[a.actor_id]||(this.actorLinks[a.actor_id]=new Set),this.actorLinks[a.actor_id].add(c),r&&r.userData.isCar&&this.checkCarPlayerLink(c,a.actor_id)}if(r&&a.attribute&&a.attribute.RigidBody){const c=a.attribute.RigidBody;if(c.location&&(r.userData.location.set(c.location.x,c.location.z,c.location.y),r.userData.lastUpdateTime=e.time,r.userData.hasReceivedUpdate=!0),c.linear_velocity&&(r.userData.velocity||(r.userData.velocity=new T),r.userData.velocity.set(c.linear_velocity.x,c.linear_velocity.z,c.linear_velocity.y)),c.rotation&&r.userData.rotation.set(c.rotation.x,c.rotation.z,c.rotation.y,-c.rotation.w),c.angular_velocity&&(r.userData.angularVelocity||(r.userData.angularVelocity=new T),r.userData.angularVelocity.set(c.angular_velocity.x,c.angular_velocity.z,c.angular_velocity.y)),c.sleeping!==void 0&&(r.userData.sleeping=c.sleeping,c.sleeping&&(r.userData.velocity&&r.userData.velocity.set(0,0,0),r.userData.angularVelocity&&r.userData.angularVelocity.set(0,0,0))),r.userData.isBall&&r.userData.isHiddenByGoal&&c.location){const u=c.location.x,d=c.location.y,h=c.location.z;Math.sqrt(u*u+d*d+h*h)<500&&(r.userData.isHiddenByGoal=!1)}}}),this.effectsManager.explosions.goalEvents.has(i)){const a=this.effectsManager.explosions.goalEvents.get(i),r=this.actors[this.ballActorId];r&&(s||(this.effectsManager.triggerGoalExplosion(r.position,a.team),console.log(`🎯 GOAL! Explosion at frame ${i} for team ${a.team} by ${a.playerName}`)),r.userData.isHiddenByGoal=!0)}if(this.effectsManager.explosions.demoEvents.has(i)){const a=this.effectsManager.explosions.demoEvents.get(i),r=this.actors[a.victimActorId];if(r){if(!s){const o=r.userData.playerId,l=o&&this.playerTeams&&this.playerTeams[o]||0;this.effectsManager.triggerDemoExplosion(r.position,l),console.log(`💥 DEMO! Explosion at frame ${i} for actor ${a.victimActorId}`)}r.userData.sleeping=!0}}}}resolveBodyId(e,t){if(!e||!e.userData.isCar||!e.userData.teamLoadout)return;let i=0;e.userData.playerId&&Object.prototype.hasOwnProperty.call(this.playerTeams,e.userData.playerId)&&(i=this.playerTeams[e.userData.playerId]);const s=e.userData.teamLoadout,a=i===1?s.orange?.body:s.blue?.body;a&&e.userData.bodyId!==a&&(e.userData.bodyId=a,this.updateCarHitbox(e,a,t))}updateCarHitbox(e,t,i){const s=uS(t),a=s?.name||"Octane",r=s?.hitboxType||"Octane";this.replaceCarWithModel(i,e,a,r)}async replaceCarWithModel(e,t,i,s){if(this.carModelLoader.isModelReady(i,s))this._doCarReplacement(e,t,i,s);else{this.pendingCarReplacements.set(e,{oldMesh:t,carName:i,hitboxType:s});try{const a=this.carModelLoader.getModelTypeForCar(i,s);await this.carModelLoader.loadModel(a);const r=this.pendingCarReplacements.get(e);r&&this.actors[e]===r.oldMesh&&this._doCarReplacement(e,r.oldMesh,r.carName,r.hitboxType),this.pendingCarReplacements.delete(e)}catch(a){console.warn(`Failed to load model for ${i} (${s}):`,a),this.pendingCarReplacements.delete(e),t&&(t.visible=!0)}}}_doCarReplacement(e,t,i,s){let a=0;t.userData.playerId&&Object.prototype.hasOwnProperty.call(this.playerTeams,t.userData.playerId)?a=this.playerTeams[t.userData.playerId]:t.userData.team!==void 0&&(a=t.userData.team);const r=this.carModelLoader.getCarMeshSync(i,s,a);if(!r){console.warn(`Could not get car mesh for ${i} (${s})`);return}const o=r.userData.wheels;r.userData={...t.userData},r.userData.isFBXModel=!0,r.userData.carName=i,r.userData.hitboxType=s,r.userData.wheels=o,r.position.copy(t.position),r.quaternion.copy(t.quaternion),this.scene.remove(t),t.geometry&&t.geometry.dispose(),t.material&&(Array.isArray(t.material)?t.material.forEach(c=>c.dispose()):t.material.dispose()),this.scene.add(r),this.actors[e]=r,this.effectsManager.removeBoostTrail(e),this.effectsManager.createBoostTrail(r,e);const l=this.carModelLoader.getModelTypeForCar(i,s);console.log(`🚗 Replaced car ${e} with ${l.toUpperCase()} model (${i}, ${s} hitbox, team ${a===0?"blue":"orange"})`)}checkCarPlayerLink(e,t){const i=this.actorToPlayer[e],s=this.actorLoadouts[e];if(!(!i&&!s))if(t){const a=this.actors[t];a&&a.userData.isCar&&(this.onPlayerFound&&this.onPlayerFound(i),a.userData.playerId=i,this.playerNameToCarActorId[i]=t,s&&(a.userData.teamLoadout=s),this.resolveBodyId(a,t))}else this.actorLinks[e]&&this.actorLinks[e].forEach(a=>{this.checkCarPlayerLink(e,a)})}updateInterpolation(e,t,i){const s=t[i];if(s&&Object.keys(this.actors).forEach(a=>{const r=this.actors[a],o=r.userData.location,l=r.userData.rotation;if(!o||!l||!r.userData.hasReceivedUpdate)return;let c=null,u=0;for(let d=i+1;dp.actor_id==a&&p.attribute&&p.attribute.RigidBody);if(f){c=f,u=h.time;break}}}if(c){const d=r.userData.lastUpdateTime||s.time,h=u;if(h>d){const f=(e-d)/(h-d),p=Math.max(0,Math.min(1,f)),g=h-d||.033,_=c.attribute.RigidBody;if(_.location)if(this._p0.copy(o),this._p1.set(_.location.x,_.location.z,_.location.y),r.userData.sleeping)r.position.copy(o);else{const m=c.attribute.RigidBody;if(r.userData.velocity&&m.linear_velocity){const v=p,y=v*v,b=y*v;if(g>.5)r.position.lerpVectors(o,this._p1,p);else{this._v0.copy(r.userData.velocity).multiplyScalar(g),this._v1.set(m.linear_velocity.x,m.linear_velocity.z,m.linear_velocity.y).multiplyScalar(g);const S=2*b-3*y+1,x=b-2*y+v,M=-2*b+3*y,C=b-y;r.position.set(S*this._p0.x+x*this._v0.x+M*this._p1.x+C*this._v1.x,S*this._p0.y+x*this._v0.y+M*this._p1.y+C*this._v1.y,S*this._p0.z+x*this._v0.z+M*this._p1.z+C*this._v1.z)}}else r.position.lerpVectors(o,this._p1,p)}else r.position.copy(o);_.rotation?(this._nextRot.set(_.rotation.x,_.rotation.z,_.rotation.y,-_.rotation.w),r.quaternion.slerpQuaternions(l,this._nextRot,p)):r.quaternion.copy(l);return}}r.position.copy(o),r.quaternion.copy(l)}),Object.keys(this.actors).forEach(a=>{const r=this.actors[a];if(r&&r.userData.isCar){const l=r.position.length()>.1,c=r.userData.sleeping===!0;r.visible=l&&!c}}),this.ballActorId&&this.actors[this.ballActorId]){const a=this.actors[this.ballActorId];if(a.visible=!a.userData.isHiddenByGoal,this.ballIndicator&&(this.ballIndicator.position.set(a.position.x,2,a.position.z),this.ballIndicator.visible=a.visible),this.ballVerticalLine){const o=new Float32Array([a.position.x,2,a.position.z,a.position.x,a.position.y,a.position.z]);this.ballVerticalLine.geometry.setAttribute("position",new lt(o,3)),this.ballVerticalLine.geometry.attributes.position.needsUpdate=!0,this.ballVerticalLine.visible=a.visible}if(a.userData.velocity&&a.visible){let r=this.lastBallTouchTeam,o=this.BALL_TOUCH_DISTANCE;Object.keys(this.actors).forEach(l=>{const c=this.actors[l];if(c&&c.userData.isCar&&c.userData.playerId){const u=a.position.distanceTo(c.position);if(u{const s=this.actors[i];if(!s||!s.userData.isCar||!s.userData.isFBXModel&&!s.userData.hasWheelSockets||!s.userData.wheels||s.userData.wheels.length===0)return;const a=s.position;let r=this._previousCarPositions.get(i);r||(r=a.clone(),this._previousCarPositions.set(i,r));const l=new T().subVectors(a,r).length();if(this._previousCarPositions.set(i,a.clone()),l<.01)return;const d=Math.min(l/e,.5)*1;let h=0;s.userData.steer!==void 0&&(h=-s.userData.steer*t),s.userData.wheels.forEach(f=>{if(f.socket){const p=f.side==="left"?1:-1;if(f.mesh.rotateZ(p*d),f.position==="front"&&f.steeringPivot){const g=f.side==="left"?-1:1;f.steeringPivot.rotation.y=g*h}}else{const p=f.side==="left"?-1:1;f.mesh.rotateY(p*d),f.position==="front"&&f.steeringPivot&&(f.steeringPivot.rotation.z=h)}})})}resetWheelTracking(){this._previousCarPositions&&this._previousCarPositions.clear()}updateSupersonicState(e,t,i){const s=this.playerNameToCarActorId[e];if(!s)return;const a=this.actors[s];if(!a||!a.userData.isCar)return;const r=a.userData.velocity||new T(0,0,0);this.effectsManager.updateSupersonicTrail(s,t,a.position,a.quaternion,r,i)}setInterpolationEnabled(e){this.interpolationEnabled=e,console.log(`[ActorManager] Interpolation ${e?"enabled":"disabled"}`)}setInterpolationMethod(e){if(!["lerp","hermite","catmull-rom","predict-correct","velocity-smooth","physics-tick","velocity-only","smart-hybrid","time-shifted","lerp-smooth","lerp-ema","lerp-dema","lerp-wma","lerp-gauss","one-euro","position-lerp","position-catmull","position-smooth","adaptive-smooth"].includes(e)){console.warn(`[ActorManager] Invalid interpolation method: ${e}`);return}this.interpolationMethod=e,this._smoothingBuffers.clear(),this._lowPassState.clear(),this._adaptiveState.clear(),this.resetSmoothingBuffers(),console.log(`[ActorManager] Interpolation method set to: ${e}`)}setSmoothingWindowSize(e){this.smoothingWindowSize=Math.max(1,Math.min(20,e)),this._smoothingBuffers.clear(),console.log(`[ActorManager] Smoothing window size set to: ${this.smoothingWindowSize}`)}getInterpolationSettings(){return{enabled:this.interpolationEnabled,method:this.interpolationMethod,smoothingWindowSize:this.smoothingWindowSize}}clearSmoothingBuffers(){this._smoothingBuffers.clear()}getFrameInfo(){return this.lastFrameInfo}createBallMeshForLive(){const e=new vn(92.75,16,16),t=new kn({color:16777215}),i=new Se(e,t);if(i.castShadow=!0,i.receiveShadow=!0,i.userData={location:new T,rotation:new ht,velocity:new T,angularVelocity:new T,isCar:!1,isBall:!0,playerId:null,sleeping:!1,isHiddenByGoal:!1},this.scene.add(i),this.ballModel){const s=this.ballModel.clone();s.position.copy(i.position),s.quaternion.copy(i.quaternion),s.userData={...i.userData};const a=92.75;return s.scale.set(a,a,a),s.traverse(r=>{r.isMesh&&(r.castShadow=!0,r.receiveShadow=!0)}),this.scene.remove(i),this.scene.add(s),i.geometry&&i.geometry.dispose(),i.material&&i.material.dispose(),console.log("✓ Live ball created with GLTF model"),s}return i}createCarMeshForLive(e,t,i,s=null){const a=`live_car_${t}`,r=new Di(118,36,84),o=e===0?3381759:16737792,l=new kn({color:o}),c=new Se(r,l);return c.castShadow=!0,c.receiveShadow=!0,c.visible=!1,c.userData={location:new T,rotation:new ht,velocity:new T,angularVelocity:new T,isCar:!0,isBall:!1,playerId:i,team:e,sleeping:!1,steer:0,bodyId:s,liveActorId:a},this.scene.add(c),this.actors[a]=c,this.playerNameToCarActorId[i]=a,this.effectsManager.createBoostTrail(c,a),s&&s>0?this.updateCarHitbox(c,s,a):this.replaceCarWithModel(a,c,"Octane","Octane"),console.log(`[ActorManager] Created live car for ${i} (team ${e===0?"blue":"orange"}, bodyId: ${s})`),c}updateBoostParticlesLive(e,t,i,s){const a=t&&i>0,r=s.userData.velocity||new T(0,0,0);this.effectsManager.updateBoostTrail(e,a,s.position,s.quaternion,r)}updateSupersonicTrailLive(e,t,i,s){const a=s.userData.velocity||new T(0,0,0);this.effectsManager.updateSupersonicTrail(e,t,s.position,s.quaternion,a,i)}removeLiveCar(e){const t=this.actors[e];t&&(this.scene.remove(t),t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose(),delete this.actors[e],this.effectsManager.removeBoostTrail(e))}removeLiveBall(e){e&&(this.scene.remove(e),e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose())}}function Ls(n,e,t){t===-1?(n.clearUpdateRanges?.(),n.addUpdateRange?.(0,n.count*n.itemSize)):n.addUpdateRange?(n.clearUpdateRanges(),n.addUpdateRange(e,t)):(n.updateRange.offset=e,n.updateRange.count=t)}class mt extends et{constructor(e,t){super(),this.active=!1,this.orientToMovement=!1,t&&(this.orientToMovement=!0),this.scene=e,this.geometry=null,this.mesh=null,this.nodeCenters=null,this.lastNodeCenter=null,this.currentNodeCenter=null,this.lastOrientationDir=null,this.nodeIDs=null,this.currentLength=0,this.currentEnd=0,this.currentNodeID=0,this.advanceFrequency=60,this.advancePeriod=1/this.advanceFrequency,this.lastAdvanceTime=0,this.paused=!1,this.pauseAdvanceUpdateTimeDiff=0,this._internalTime=0,this._useInternalTime=!1}setAdvanceFrequency(e){this.advanceFrequency=e,this.advancePeriod=1/this.advanceFrequency}initialize(e,t,i,s,a,r){this.deactivate(),this.destroyMesh(),this.length=t>0?t+1:0,this.dragTexture=i?1:0,this.targetObject=r,this.initializeLocalHeadGeometry(s,a),this.nodeIDs=[],this.nodeCenters=[];for(let o=0;o=this.length?0:this.currentEnd+1;if(i?this.updateNodePositionsFromTransformMatrix(s,i):this.updateNodePositionsFromOrientationTangent(s,t.position,t.tangent),this.currentLength>=1&&(this.connectNodes(this.currentEnd,s),this.currentLength>=this.length)){const a=this.currentEnd+1>=this.length?0:this.currentEnd+1;this.disconnectNodes(a)}this.currentLength=this.length&&(this.currentEnd=0),this.currentLength>=1&&(this.currentLengththis.advancePeriod?(this.advance(),this.lastAdvanceTime=t):this.updateHead()}}updateHead=(function(){const e=new Ee;return function(){this.currentEnd<0||(this.targetObject.updateMatrixWorld(),e.copy(this.targetObject.matrixWorld),this.updateNodePositionsFromTransformMatrix(this.currentEnd,e))}})();updateNodeID(e,t){this.nodeIDs[e]=t;const i=this.geometry.getAttribute("nodeID"),s=this.geometry.getAttribute("nodeVertexID");for(let a=0;a1e-4)){this.lastOrientationDir||(this.lastOrientationDir=new T),t.setFromUnitVectors(a,r),s.copy(this.currentNodeCenter);for(let f=0;fe.add(a)),this.mainTrail=this._createMainTrail(),this.secondaryTrails=this._createSecondaryTrails(),this._updateColors(),this._updateIntensity(),this.mainTrail.activate(),this.secondaryTrails.forEach(a=>a.activate())}_createMainTrail(){const e=new mt(this.scene,!1),t=Iv(),i=this.config.mainTrailWidth,s=[new T(0,-i,0),new T(0,i,0),new T(-i,0,0),new T(i,0,0),new T(0,0,-i),new T(0,0,i)];return e.initialize(t,this.config.trailLength,!1,0,s,this.mainTarget),e.setAdvanceFrequency(60),e.mesh&&(e.mesh.frustumCulled=!1,e.mesh.renderOrder=100),e}_createSecondaryTrails(){const e=[];for(let t=0;t<4;t++){const i=new mt(this.scene,!1),s=Iv(),a=this.config.secondaryTrailWidth,r=[new T(0,-a,0),new T(0,a,0),new T(-a,0,0),new T(a,0,0),new T(0,0,-a),new T(0,0,a)];i.initialize(s,this.config.trailLength,!1,0,r,this.secondaryTargets[t]),i.setAdvanceFrequency(60),i.mesh&&(i.mesh.frustumCulled=!1,i.mesh.renderOrder=100),e.push(i)}return e}_updateColors(){const e=this.teamColors[this.team]||this.teamColors[0];this.mainTrail?.material&&(this.mainTrail.material.uniforms.headColor.value.copy(e.head),this.mainTrail.material.uniforms.tailColor.value.copy(e.tail));const t=e.head.clone();t.w=e.head.w*.85;const i=e.tail.clone();this.secondaryTrails.forEach(s=>{s?.material&&(s.material.uniforms.headColor.value.copy(t),s.material.uniforms.tailColor.value.copy(i))})}_updateIntensity(){this.mainTrail?.material&&(this.mainTrail.material.uniforms.intensityMultiplier.value=this.intensity),this.secondaryTrails.forEach(e=>{e?.material&&(e.material.uniforms.intensityMultiplier.value=this.intensity)})}setTeam(e){this.team!==e&&(this.team=e,this._updateColors())}setIntensity(e){this.intensity=e,this.dying||this._updateIntensity()}startDying(){this.dying||(this.dying=!0,this.deathTime=0,this.mainTrail.pause(),this.secondaryTrails.forEach(e=>e.pause()))}updatePosition(e,t,i){if(this.dying)return;const s=t.clone().normalize();this.mainTarget.position.copy(e),this.mainTarget.updateMatrixWorld();for(let a=0;a<4;a++){const o=a/4*Math.PI*2+i,l=new T(Math.cos(o)*this.config.secondaryTrailOffset,Math.sin(o)*this.config.secondaryTrailOffset,0);if(s.lengthSq()>.001){const c=new T(0,0,1),u=new ht;u.setFromUnitVectors(c,s),l.applyQuaternion(u)}this.secondaryTargets[a].position.copy(e).add(l),this.secondaryTargets[a].updateMatrixWorld()}}update(e){if(this.dying){this.deathTime+=e;const t=Math.min(1,this.deathTime/this.maxDeathTime),i=this.intensity*(1-t);this.mainTrail?.material&&(this.mainTrail.material.uniforms.intensityMultiplier.value=i),this.secondaryTrails.forEach(s=>{s?.material&&(s.material.uniforms.intensityMultiplier.value=i)}),this.deathTime>=this.maxDeathTime&&(this.active=!1)}this.mainTrail.isActive&&this.mainTrail.update(e),this.secondaryTrails.forEach(t=>{t.isActive&&t.update(e)})}dispose(){this.mainTrail.deactivate(),this.secondaryTrails.forEach(e=>e.deactivate()),this.mainTrail.geometry&&this.mainTrail.geometry.dispose(),this.mainTrail.material&&this.mainTrail.material.dispose(),this.secondaryTrails.forEach(e=>{e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()}),this.scene.remove(this.mainTarget),this.secondaryTargets.forEach(e=>this.scene.remove(e))}}class tN{constructor(e,t=0){this.scene=e,this.team=t,this.active=!1,this.ballRadius=92.75,this.config={trailLength:60,mainTrailWidth:15,secondaryTrailWidth:1.5,secondaryTrailOffset:this.ballRadius*.7},this.rotationSpeed=Math.PI/3,this.currentRotation=0,this.minVelocity=1500,this.maxVelocity=6e3,this.minIntensity=.3,this.maxIntensity=1,this.wasEmitting=!1,this.segments=[],this.currentSegment=null,this.currentIntensity=1}_calculateIntensity(e){if(e<=this.minVelocity)return this.minIntensity;if(e>=this.maxVelocity)return this.maxIntensity;const t=(e-this.minVelocity)/(this.maxVelocity-this.minVelocity);return this.minIntensity+t*(this.maxIntensity-this.minIntensity)}setTeam(e){this.team!==e&&(this.team=e,this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.startDying(),this.currentSegment=null))}activate(){this.active||(this.active=!0,this.currentSegment=null,this.wasEmitting=!1)}deactivate(){this.active&&(this.active=!1,this.currentSegment&&(this.currentSegment.startDying(),this.currentSegment=null))}emit(e,t,i){const s=t.length();if(!(s>=this.minVelocity)){this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.startDying(),this.currentSegment=null),this.wasEmitting=!1;return}this.currentIntensity=this._calculateIntensity(s),this.active||this.activate(),!this.wasEmitting||!this.currentSegment?(this.currentSegment&&!this.currentSegment.dying&&this.currentSegment.startDying(),this.currentSegment=new eN(this.scene,this.team,this.config,this.currentIntensity),this.segments.push(this.currentSegment)):this.currentSegment.setIntensity(this.currentIntensity),this.wasEmitting=!0,this.currentRotation+=this.rotationSpeed*i,this.currentRotation>Math.PI*2&&(this.currentRotation-=Math.PI*2),this.currentSegment.updatePosition(e,t,this.currentRotation)}update(e){for(let t=this.segments.length-1;t>=0;t--){const i=this.segments[t];i.update(e),i.active||(i.dispose(),this.segments.splice(t,1))}}reset(){for(const e of this.segments)e.dispose();this.segments=[],this.currentSegment=null,this.currentRotation=0,this.wasEmitting=!1}addToScene(e){}removeFromScene(e){for(const t of this.segments)t.startDying();this.currentSegment=null}dispose(){for(const e of this.segments)e.dispose();this.segments=[],this.currentSegment=null}}let Pu=null,Iu=null,Lu=null,Lv=!1;function nN(){Lv||(rN(),oN(),lN(),Lv=!0)}let gi=null;class iN{constructor(e,t,i,s=2){this.scene=e,this.renderer=t,this.camera=i,this.maxExplosions=s,this.explosions=[],this.warmedUp=!1,this.initPool()}initPool(){this.sphereGeo=new vn(1,16,12),this.coreGeo=new vn(1,12,8),this.ringGeo=new oi(.5,1,32),this.particleGeo=new Nn(1,1),this.coreMaterial=new je({color:16777130,transparent:!0,opacity:.9,blending:Vt,side:ut,depthWrite:!1}),this.sphereMaterial=new je({color:16737792,transparent:!0,opacity:.5,blending:Vt,side:ut,depthWrite:!1}),this.ringMaterial=new je({color:16746496,transparent:!0,opacity:.7,blending:Vt,side:ut,depthWrite:!1}),this.particleMaterial=new je({color:16763904,transparent:!0,opacity:.8,blending:Vt,side:ut,depthWrite:!1});for(let e=0;e!i.active);t||(t=this.explosions[0],this.resetExplosion(t)),t.active=!0,t.elapsed=0,t.position.copy(e),t.container.position.copy(e),t.container.visible=!0,t.core.scale.set(.1,.1,.1),t.coreMat.opacity=1,t.sphere.scale.set(.1,.1,.1),t.sphere.material.opacity=.6,t.ring.scale.set(.1,.1,.1),t.ring.material.opacity=.8,t.particleMat.opacity=.9,t.particles.forEach((i,s)=>{i.mesh.position.set(0,0,0);const a=s/12*Math.PI*2,r=(Math.random()-.3)*Math.PI,o=350+Math.random()*250;i.velocity.set(Math.cos(a)*Math.cos(r)*o,Math.sin(r)*o+100,Math.sin(a)*Math.cos(r)*o)})}resetExplosion(e){e.active=!1,e.container.visible=!1}update(e){for(const t of this.explosions){if(!t.active)continue;t.elapsed+=e;const i=t.elapsed/t.duration;if(i>=1){this.resetExplosion(t);continue}const s=30+i*80;t.core.scale.set(s,s,s),t.coreMat.opacity=1*Math.pow(1-i,2);const a=50+i*200;t.sphere.scale.set(a,a,a),t.sphere.material.opacity=.6*(1-i);const r=80+i*350;t.ring.scale.set(r,r,r),t.ring.material.opacity=.8*(1-i*i),t.particleMat.opacity=.9*(1-i);for(const o of t.particles)o.mesh.position.add(o.velocity.clone().multiplyScalar(e)),o.velocity.y-=300*e,this.camera&&o.mesh.lookAt(this.camera.position)}}dispose(){for(const e of this.explosions)this.scene.remove(e.container),e.coreMat.dispose(),e.sphere.material.dispose(),e.ring.material.dispose(),e.particleMat.dispose();this.coreGeo.dispose(),this.sphereGeo.dispose(),this.ringGeo.dispose(),this.particleGeo.dispose(),this.coreMaterial.dispose(),this.sphereMaterial.dispose(),this.ringMaterial.dispose(),this.particleMaterial.dispose()}}function aM(n,e=null,t=null){return gi&&gi.scene!==n&&(gi.dispose?.(),gi=null),gi||(gi=new iN(n,e,t)),e&&t&&!gi.warmedUp&&(gi.renderer=e,gi.camera=t,gi.warmup()),gi}function sN(n,e,t){aM(n,e,t),rM(n,e,t)}let Gn=null;const kv={0:{core:6737151,sphere:35071,ring:43775,particles:8969727},1:{core:16768358,sphere:16737792,ring:16746496,particles:16755268}};class aN{constructor(e,t,i,s=2){this.scene=e,this.renderer=t,this.camera=i,this.maxExplosions=s,this.explosions=[],this.warmedUp=!1,this.initPool()}initPool(){this.coreGeo=new vn(1,16,12),this.sphereGeo=new vn(1,20,14),this.ringGeo=new oi(.3,1,48),this.particleGeo=new Nn(1,1),this.rayGeo=new Nn(1,1);for(let e=0;e!l.active);i||(i=this.explosions[0],this.resetExplosion(i));const s=i.materials[t]||i.materials[0];i.core.material=s.core,i.core2.material=s.core.clone(),i.core3.material=s.sphere.clone(),i.sphere.material=s.sphere;for(const l of i.rings)l.mesh.material=s.ring.clone();for(const l of i.rays)l.mesh.material=s.rays.clone();for(const l of i.particles)l.mesh.material=s.particles.clone();i.active=!0,i.elapsed=0,i.currentTeam=t,i.position.copy(e),i.container.position.copy(e),i.container.visible=!0,i.rotationOffset=0,i.core.scale.set(.1,.1,.1),i.core.material.opacity=1,i.core2.scale.set(.1,.1,.1),i.core2.material.opacity=.8,i.core3.scale.set(.1,.1,.1),i.core3.material.opacity=.5,i.sphere.scale.set(.1,.1,.1),i.sphere.material.opacity=.4;for(const l of i.rings)l.mesh.scale.set(.1,.1,.1),l.mesh.material.opacity=.9;for(let l=0;l=i.particles.length);d++){const h=i.particles[o];h.mesh.position.set(0,0,0),h.mesh.material.opacity=1;const f=h.initialScale;h.mesh.scale.set(f,f,f);const p=c+(Math.random()-.5)*.3,g=u+(Math.random()-.5)*.2,v=1800*(1-d/r*.5)+Math.random()*300;h.velocity.set(Math.cos(p)*Math.cos(g)*v,Math.sin(g)*v+300,Math.sin(p)*Math.cos(g)*v),h.delay=d*.02,o++}}for(;o=1){this.resetExplosion(t);continue}t.rotationOffset+=e*2;const s=this.easeOutElastic(Math.min(i*2,1)),a=this.easeOutExpo(i),r=this.easeOutBack(Math.min(i*1.5,1)),o=1+Math.sin(t.elapsed*15)*.15*(1-i),l=(150+s*300)*o;t.core.scale.set(l,l,l),t.core.material.opacity=1*Math.pow(1-i,1.2);const c=1+Math.sin(t.elapsed*12+1)*.12*(1-i),u=(200+r*400)*c;t.core2.scale.set(u,u,u),t.core2.material.opacity=.7*Math.pow(1-i,1.5);const d=300+a*600;t.core3.scale.set(d,d,d),t.core3.material.opacity=.4*Math.pow(1-i,2);const h=400+a*1200;t.sphere.scale.set(h,h,h),t.sphere.material.opacity=.3*(1-i*i);for(let g=0;g0){g.mesh.position.add(g.velocity.clone().multiplyScalar(e)),g.velocity.y-=600*e,g.velocity.multiplyScalar(.995);const m=Math.max(.3,1-i*.7),v=g.initialScale*m;g.mesh.scale.set(v,v,v)}g.mesh.material.opacity=1*Math.pow(1-i,1.2),this.camera&&g.mesh.lookAt(this.camera.position)}}}dispose(){for(const e of this.explosions){this.scene.remove(e.container);for(const t of Object.values(e.materials))t.core.dispose(),t.sphere.dispose(),t.ring.dispose(),t.particles.dispose(),t.rays.dispose()}this.coreGeo.dispose(),this.sphereGeo.dispose(),this.ringGeo.dispose(),this.particleGeo.dispose(),this.rayGeo.dispose()}}function rM(n,e=null,t=null){return Gn&&Gn.scene!==n&&(Gn.dispose?.(),Gn=null),Gn||(Gn=new aN(n,e,t)),e&&t&&!Gn.warmedUp&&(Gn.renderer=e,Gn.camera=t,Gn.warmup()),Gn}function rN(){if(Pu)return Pu;const n=document.createElement("canvas");n.width=64,n.height=64;const e=n.getContext("2d"),t=e.createRadialGradient(32,32,0,32,32,32);return t.addColorStop(0,"rgba(255,255,255,1)"),t.addColorStop(.2,"rgba(255,255,255,0.8)"),t.addColorStop(.5,"rgba(255,255,255,0.3)"),t.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=t,e.fillRect(0,0,64,64),Pu=new Ec(n),Pu}function oN(){if(Iu)return Iu;const n=document.createElement("canvas");n.width=128,n.height=128;const e=n.getContext("2d"),t=e.createRadialGradient(64,64,0,64,64,64);return t.addColorStop(0,"rgba(255,255,255,1)"),t.addColorStop(.1,"rgba(255,200,100,0.9)"),t.addColorStop(.4,"rgba(255,100,50,0.4)"),t.addColorStop(.7,"rgba(255,50,0,0.1)"),t.addColorStop(1,"rgba(0,0,0,0)"),e.fillStyle=t,e.fillRect(0,0,128,128),Iu=new Ec(n),Iu}function lN(){if(Lu)return Lu;const n=document.createElement("canvas");n.width=64,n.height=64;const e=n.getContext("2d"),t=e.createImageData(64,64);for(let i=0;ie.add(a)),this.mainTrail=this._createMainTrail(),this.secondaryTrails=this._createSecondaryTrails(),this._updateColors(),this._updateIntensity(),this.mainTrail.activate(),this.secondaryTrails.forEach(a=>a.activate())}_createMainTrail(){const e=new mt(this.scene,!1),t=Uv(),i=this.config.mainTrailWidth,s=[new T(0,-i,0),new T(0,i,0),new T(-i,0,0),new T(i,0,0),new T(0,0,-i),new T(0,0,i)];return e.initialize(t,this.config.trailLength,!1,0,s,this.mainTarget),e.setAdvanceFrequency(60),e.mesh&&(e.mesh.frustumCulled=!1,e.mesh.renderOrder=100),e}_createSecondaryTrails(){const e=[];for(let t=0;t<4;t++){const i=new mt(this.scene,!1),s=Uv(),a=this.config.secondaryTrailWidth,r=[new T(0,-a,0),new T(0,a,0),new T(-a,0,0),new T(a,0,0),new T(0,0,-a),new T(0,0,a)];i.initialize(s,this.config.trailLength,!1,0,r,this.secondaryTargets[t]),i.setAdvanceFrequency(60),i.mesh&&(i.mesh.frustumCulled=!1,i.mesh.renderOrder=100),e.push(i)}return e}_updateColors(){const e=this.teamColors[this.team]||this.teamColors[0];this.mainTrail?.material&&(this.mainTrail.material.uniforms.headColor.value.copy(e.head),this.mainTrail.material.uniforms.tailColor.value.copy(e.tail));const t=e.head.clone();t.w=e.head.w*.85;const i=e.tail.clone();this.secondaryTrails.forEach(s=>{s?.material&&(s.material.uniforms.headColor.value.copy(t),s.material.uniforms.tailColor.value.copy(i))})}_updateIntensity(){this.mainTrail?.material&&(this.mainTrail.material.uniforms.intensityMultiplier.value=this.intensity),this.secondaryTrails.forEach(e=>{e?.material&&(e.material.uniforms.intensityMultiplier.value=this.intensity)})}setTeam(e){this.team!==e&&(this.team=e,this._updateColors())}setIntensity(e){this.intensity=e,this.dying||this._updateIntensity()}startDying(){this.dying||(this.dying=!0,this.deathTime=0,this.mainTrail.pause(),this.secondaryTrails.forEach(e=>e.pause()))}updatePosition(e,t,i){if(this.dying)return;const s=t.clone().normalize();this.mainTarget.position.copy(e),this.mainTarget.updateMatrixWorld();for(let a=0;a<4;a++){const o=a/4*Math.PI*2+i,l=new T(Math.cos(o)*this.config.secondaryTrailOffset,Math.sin(o)*this.config.secondaryTrailOffset,0);if(s.lengthSq()>.001){const c=new T(0,0,1),u=new ht;u.setFromUnitVectors(c,s),l.applyQuaternion(u)}this.secondaryTargets[a].position.copy(e).add(l),this.secondaryTargets[a].updateMatrixWorld()}}update(e){if(this.dying){this.deathTime+=e;const t=Math.min(1,this.deathTime/this.maxDeathTime),i=this.intensity*(1-t);this.mainTrail?.material&&(this.mainTrail.material.uniforms.intensityMultiplier.value=i),this.secondaryTrails.forEach(s=>{s?.material&&(s.material.uniforms.intensityMultiplier.value=i)}),this.deathTime>=this.maxDeathTime&&(this.active=!1)}this.mainTrail.isActive&&this.mainTrail.update(e),this.secondaryTrails.forEach(t=>{t.isActive&&t.update(e)})}dispose(){this.mainTrail.deactivate(),this.secondaryTrails.forEach(e=>e.deactivate()),this.mainTrail.geometry&&this.mainTrail.geometry.dispose(),this.mainTrail.material&&this.mainTrail.material.dispose(),this.secondaryTrails.forEach(e=>{e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()}),this.scene.remove(this.mainTarget),this.secondaryTargets.forEach(e=>this.scene.remove(e))}}class hN{constructor(e,t=0){this.scene=e,this.team=t,this.active=!1,this.ballRadius=92.75,this.config={trailLength:60,mainTrailWidth:15,secondaryTrailWidth:1.5,secondaryTrailOffset:this.ballRadius*.7},this.rotationSpeed=Math.PI/3,this.currentRotation=0,this.minVelocity=1500,this.maxVelocity=6e3,this.minIntensity=.3,this.maxIntensity=1,this.wasEmitting=!1,this.segments=[],this.currentSegment=null,this.currentIntensity=1}_calculateIntensity(e){if(e<=this.minVelocity)return this.minIntensity;if(e>=this.maxVelocity)return this.maxIntensity;const t=(e-this.minVelocity)/(this.maxVelocity-this.minVelocity);return this.minIntensity+t*(this.maxIntensity-this.minIntensity)}setTeam(e){this.team!==e&&(this.team=e,this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.startDying(),this.currentSegment=null))}activate(){this.active||(this.active=!0,this.currentSegment=null,this.wasEmitting=!1)}deactivate(){this.active&&(this.active=!1,this.currentSegment&&(this.currentSegment.startDying(),this.currentSegment=null))}emit(e,t,i){const s=t.length();if(!(s>=this.minVelocity)){this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.startDying(),this.currentSegment=null),this.wasEmitting=!1;return}this.currentIntensity=this._calculateIntensity(s),this.active||this.activate(),!this.wasEmitting||!this.currentSegment?(this.currentSegment&&!this.currentSegment.dying&&this.currentSegment.startDying(),this.currentSegment=new dN(this.scene,this.team,this.config,this.currentIntensity),this.segments.push(this.currentSegment)):this.currentSegment.setIntensity(this.currentIntensity),this.wasEmitting=!0,this.currentRotation+=this.rotationSpeed*i,this.currentRotation>Math.PI*2&&(this.currentRotation-=Math.PI*2),this.currentSegment.updatePosition(e,t,this.currentRotation)}update(e){for(let t=this.segments.length-1;t>=0;t--){const i=this.segments[t];i.update(e),i.active||(i.dispose(),this.segments.splice(t,1))}}reset(){for(const e of this.segments)e.dispose();this.segments=[],this.currentSegment=null,this.currentRotation=0,this.wasEmitting=!1}addToScene(e){}removeFromScene(e){for(const t of this.segments)t.startDying();this.currentSegment=null}dispose(){for(const e of this.segments)e.dispose();this.segments=[],this.currentSegment=null}}let Du=null,Ou=null,Fu=null,Bv=!1;function fN(){Bv||(gN(),yN(),vN(),Bv=!0)}let gi=null;class pN{constructor(e,t,i,s=2){this.scene=e,this.renderer=t,this.camera=i,this.maxExplosions=s,this.explosions=[],this.warmedUp=!1,this.initPool()}initPool(){this.sphereGeo=new vn(1,16,12),this.coreGeo=new vn(1,12,8),this.ringGeo=new oi(.5,1,32),this.particleGeo=new Nn(1,1),this.coreMaterial=new je({color:16777130,transparent:!0,opacity:.9,blending:Vt,side:ut,depthWrite:!1}),this.sphereMaterial=new je({color:16737792,transparent:!0,opacity:.5,blending:Vt,side:ut,depthWrite:!1}),this.ringMaterial=new je({color:16746496,transparent:!0,opacity:.7,blending:Vt,side:ut,depthWrite:!1}),this.particleMaterial=new je({color:16763904,transparent:!0,opacity:.8,blending:Vt,side:ut,depthWrite:!1});for(let e=0;e!i.active);t||(t=this.explosions[0],this.resetExplosion(t)),t.active=!0,t.elapsed=0,t.position.copy(e),t.container.position.copy(e),t.container.visible=!0,t.core.scale.set(.1,.1,.1),t.coreMat.opacity=1,t.sphere.scale.set(.1,.1,.1),t.sphere.material.opacity=.6,t.ring.scale.set(.1,.1,.1),t.ring.material.opacity=.8,t.particleMat.opacity=.9,t.particles.forEach((i,s)=>{i.mesh.position.set(0,0,0);const a=s/12*Math.PI*2,r=(Math.random()-.3)*Math.PI,o=350+Math.random()*250;i.velocity.set(Math.cos(a)*Math.cos(r)*o,Math.sin(r)*o+100,Math.sin(a)*Math.cos(r)*o)})}resetExplosion(e){e.active=!1,e.container.visible=!1}update(e){for(const t of this.explosions){if(!t.active)continue;t.elapsed+=e;const i=t.elapsed/t.duration;if(i>=1){this.resetExplosion(t);continue}const s=30+i*80;t.core.scale.set(s,s,s),t.coreMat.opacity=1*Math.pow(1-i,2);const a=50+i*200;t.sphere.scale.set(a,a,a),t.sphere.material.opacity=.6*(1-i);const r=80+i*350;t.ring.scale.set(r,r,r),t.ring.material.opacity=.8*(1-i*i),t.particleMat.opacity=.9*(1-i);for(const o of t.particles)o.mesh.position.add(o.velocity.clone().multiplyScalar(e)),o.velocity.y-=300*e,this.camera&&o.mesh.lookAt(this.camera.position)}}dispose(){for(const e of this.explosions)this.scene.remove(e.container),e.coreMat.dispose(),e.sphere.material.dispose(),e.ring.material.dispose(),e.particleMat.dispose();this.coreGeo.dispose(),this.sphereGeo.dispose(),this.ringGeo.dispose(),this.particleGeo.dispose(),this.coreMaterial.dispose(),this.sphereMaterial.dispose(),this.ringMaterial.dispose(),this.particleMaterial.dispose()}}function pM(n,e=null,t=null){return gi&&gi.scene!==n&&(gi.dispose?.(),gi=null),gi||(gi=new pN(n,e,t)),e&&t&&!gi.warmedUp&&(gi.renderer=e,gi.camera=t,gi.warmup()),gi}function mN(n,e,t){pM(n,e,t),mM(n,e,t)}let Gn=null;const zv={0:{core:6737151,sphere:35071,ring:43775,particles:8969727},1:{core:16768358,sphere:16737792,ring:16746496,particles:16755268}};class _N{constructor(e,t,i,s=2){this.scene=e,this.renderer=t,this.camera=i,this.maxExplosions=s,this.explosions=[],this.warmedUp=!1,this.initPool()}initPool(){this.coreGeo=new vn(1,16,12),this.sphereGeo=new vn(1,20,14),this.ringGeo=new oi(.3,1,48),this.particleGeo=new Nn(1,1),this.rayGeo=new Nn(1,1);for(let e=0;e!l.active);i||(i=this.explosions[0],this.resetExplosion(i));const s=i.materials[t]||i.materials[0];i.core.material=s.core,i.core2.material=s.core.clone(),i.core3.material=s.sphere.clone(),i.sphere.material=s.sphere;for(const l of i.rings)l.mesh.material=s.ring.clone();for(const l of i.rays)l.mesh.material=s.rays.clone();for(const l of i.particles)l.mesh.material=s.particles.clone();i.active=!0,i.elapsed=0,i.currentTeam=t,i.position.copy(e),i.container.position.copy(e),i.container.visible=!0,i.rotationOffset=0,i.core.scale.set(.1,.1,.1),i.core.material.opacity=1,i.core2.scale.set(.1,.1,.1),i.core2.material.opacity=.8,i.core3.scale.set(.1,.1,.1),i.core3.material.opacity=.5,i.sphere.scale.set(.1,.1,.1),i.sphere.material.opacity=.4;for(const l of i.rings)l.mesh.scale.set(.1,.1,.1),l.mesh.material.opacity=.9;for(let l=0;l=i.particles.length);d++){const h=i.particles[o];h.mesh.position.set(0,0,0),h.mesh.material.opacity=1;const f=h.initialScale;h.mesh.scale.set(f,f,f);const p=c+(Math.random()-.5)*.3,g=u+(Math.random()-.5)*.2,v=1800*(1-d/r*.5)+Math.random()*300;h.velocity.set(Math.cos(p)*Math.cos(g)*v,Math.sin(g)*v+300,Math.sin(p)*Math.cos(g)*v),h.delay=d*.02,o++}}for(;o=1){this.resetExplosion(t);continue}t.rotationOffset+=e*2;const s=this.easeOutElastic(Math.min(i*2,1)),a=this.easeOutExpo(i),r=this.easeOutBack(Math.min(i*1.5,1)),o=1+Math.sin(t.elapsed*15)*.15*(1-i),l=(150+s*300)*o;t.core.scale.set(l,l,l),t.core.material.opacity=1*Math.pow(1-i,1.2);const c=1+Math.sin(t.elapsed*12+1)*.12*(1-i),u=(200+r*400)*c;t.core2.scale.set(u,u,u),t.core2.material.opacity=.7*Math.pow(1-i,1.5);const d=300+a*600;t.core3.scale.set(d,d,d),t.core3.material.opacity=.4*Math.pow(1-i,2);const h=400+a*1200;t.sphere.scale.set(h,h,h),t.sphere.material.opacity=.3*(1-i*i);for(let g=0;g0){g.mesh.position.add(g.velocity.clone().multiplyScalar(e)),g.velocity.y-=600*e,g.velocity.multiplyScalar(.995);const m=Math.max(.3,1-i*.7),v=g.initialScale*m;g.mesh.scale.set(v,v,v)}g.mesh.material.opacity=1*Math.pow(1-i,1.2),this.camera&&g.mesh.lookAt(this.camera.position)}}}dispose(){for(const e of this.explosions){this.scene.remove(e.container);for(const t of Object.values(e.materials))t.core.dispose(),t.sphere.dispose(),t.ring.dispose(),t.particles.dispose(),t.rays.dispose()}this.coreGeo.dispose(),this.sphereGeo.dispose(),this.ringGeo.dispose(),this.particleGeo.dispose(),this.rayGeo.dispose()}}function mM(n,e=null,t=null){return Gn&&Gn.scene!==n&&(Gn.dispose?.(),Gn=null),Gn||(Gn=new _N(n,e,t)),e&&t&&!Gn.warmedUp&&(Gn.renderer=e,Gn.camera=t,Gn.warmup()),Gn}function gN(){if(Du)return Du;const n=document.createElement("canvas");n.width=64,n.height=64;const e=n.getContext("2d"),t=e.createRadialGradient(32,32,0,32,32,32);return t.addColorStop(0,"rgba(255,255,255,1)"),t.addColorStop(.2,"rgba(255,255,255,0.8)"),t.addColorStop(.5,"rgba(255,255,255,0.3)"),t.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=t,e.fillRect(0,0,64,64),Du=new Pc(n),Du}function yN(){if(Ou)return Ou;const n=document.createElement("canvas");n.width=128,n.height=128;const e=n.getContext("2d"),t=e.createRadialGradient(64,64,0,64,64,64);return t.addColorStop(0,"rgba(255,255,255,1)"),t.addColorStop(.1,"rgba(255,200,100,0.9)"),t.addColorStop(.4,"rgba(255,100,50,0.4)"),t.addColorStop(.7,"rgba(255,50,0,0.1)"),t.addColorStop(1,"rgba(0,0,0,0)"),e.fillStyle=t,e.fillRect(0,0,128,128),Ou=new Pc(n),Ou}function vN(){if(Fu)return Fu;const n=document.createElement("canvas");n.width=64,n.height=64;const e=n.getContext("2d"),t=e.createImageData(64,64);for(let i=0;i=o.maxLife){o.active=!1,i[r]=0,s[r]=0;continue}t[r*3]+=o.velocity.x*e,t[r*3+1]+=o.velocity.y*e,t[r*3+2]+=o.velocity.z*e;const l=o.life/o.maxLife;i[r]=Math.pow(1-l,.5);const c=o.initialSize||3;s[r]=c*(1-l*.7),a[r*3]=1,a[r*3+1]=Math.max(.2,.9-l*.7),a[r*3+2]=Math.max(0,.4-l*.4),o.velocity.y+=20*e}this.geometry.attributes.position.needsUpdate=!0,this.geometry.attributes.alpha.needsUpdate=!0,this.geometry.attributes.size.needsUpdate=!0,this.geometry.attributes.color.needsUpdate=!0}addToScene(e){e.add(this.points)}removeFromScene(e){e.remove(this.points)}dispose(){this.geometry.dispose(),this.points.material.dispose()}}class uN{constructor(e,t,i,s){this.scene=e,this.team=t,this.trailWidth=i,this.trailLength=s,this.active=!0,this.dying=!1,this.deathTime=0,this.maxDeathTime=1.5,this.teamColors={0:new Ye(.3,.6,1,.9),1:new Ye(1,.5,.15,.9)},this.leftTarget=new et,this.rightTarget=new et,e.add(this.leftTarget),e.add(this.rightTarget),this.leftTrail=this.createTrail(this.leftTarget),this.rightTrail=this.createTrail(this.rightTarget),this.updateColors(),this.leftTrail.activate(),this.rightTrail.activate()}createTrail(e){const t=new mt(this.scene,!1),i=mt.createBaseMaterial();i.blending=Vt,i.depthWrite=!1,i.side=ut;const s=this.trailWidth,a=[new T(0,0,0),new T(0,s,0),new T(-s/2,s/2,0),new T(s/2,s/2,0)];return t.initialize(i,this.trailLength,!1,0,a,e),t.setAdvanceFrequency(60),t.mesh&&(t.mesh.frustumCulled=!1),t}updateColors(){const e=this.teamColors[this.team]||this.teamColors[0],t=new Ye(e.x*.3,e.y*.3,e.z*.3,0);this.leftTrail?.material&&(this.leftTrail.material.uniforms.headColor.value.copy(e),this.leftTrail.material.uniforms.tailColor.value.copy(t)),this.rightTrail?.material&&(this.rightTrail.material.uniforms.headColor.value.copy(e),this.rightTrail.material.uniforms.tailColor.value.copy(t))}startDying(){this.dying||(this.dying=!0,this.deathTime=0,this.leftTrail.pause(),this.rightTrail.pause())}updatePosition(e,t,i){this.dying||(this.leftTarget.position.copy(e),this.rightTarget.position.copy(t),this.leftTarget.quaternion.copy(i),this.rightTarget.quaternion.copy(i),this.leftTarget.updateMatrixWorld(),this.rightTarget.updateMatrixWorld())}update(e){if(this.dying){this.deathTime+=e;const i=1-Math.min(1,this.deathTime/this.maxDeathTime),s=this.teamColors[this.team]||this.teamColors[0],a=new Ye(s.x,s.y,s.z,s.w*i),r=new Ye(s.x*.3,s.y*.3,s.z*.3,0);this.leftTrail?.material&&(this.leftTrail.material.uniforms.headColor.value.copy(a),this.leftTrail.material.uniforms.tailColor.value.copy(r)),this.rightTrail?.material&&(this.rightTrail.material.uniforms.headColor.value.copy(a),this.rightTrail.material.uniforms.tailColor.value.copy(r)),this.deathTime>=this.maxDeathTime&&(this.active=!1)}this.leftTrail.isActive&&this.leftTrail.update(e),this.rightTrail.isActive&&this.rightTrail.update(e)}dispose(){this.leftTrail.deactivate(),this.rightTrail.deactivate(),this.leftTrail.geometry&&this.leftTrail.geometry.dispose(),this.rightTrail.geometry&&this.rightTrail.geometry.dispose(),this.leftTrail.material&&this.leftTrail.material.dispose(),this.rightTrail.material&&this.rightTrail.material.dispose(),this.scene.remove(this.leftTarget),this.scene.remove(this.rightTarget)}}class dN{constructor(e,t=0){this.scene=e,this.team=t,this.active=!1,this.trailLength=80,this.trailWidth=15,this.arenaBounds={floor:0,ceiling:2044,wallX:4096,wallZ:5120},this.groundedThreshold=50,this.segments=[],this.currentSegment=null,this.wasGrounded=!0}setTeam(e){this.team!==e&&(this.team=e,this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.team=e,this.currentSegment.updateColors()))}setActive(e){e&&!this.active?(this.currentSegment=null,this.wasGrounded=!0):!e&&this.active&&this.currentSegment&&(this.currentSegment.startDying(),this.currentSegment=null),this.active=e}isGrounded(e){const t=this.groundedThreshold,i=this.arenaBounds;if(e.yi.ceiling-t)return{grounded:!0,surface:"ceiling",normal:new T(0,-1,0)};if(Math.abs(e.x)>i.wallX-t){const s=e.x>0?-1:1;return{grounded:!0,surface:"wall",normal:new T(s,0,0)}}if(Math.abs(e.z)>i.wallZ-t){const s=e.z>0?-1:1;return{grounded:!0,surface:"wall",normal:new T(0,0,s)}}return{grounded:!1,surface:null,normal:null}}emit(e,t,i){if(!this.active)return;const s=this.isGrounded(e);if(!s.grounded){this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.startDying(),this.currentSegment=null),this.wasGrounded=!1;return}(!this.wasGrounded||!this.currentSegment)&&(this.currentSegment&&!this.currentSegment.dying&&this.currentSegment.startDying(),this.currentSegment=new uN(this.scene,this.team,this.trailWidth,this.trailLength),this.segments.push(this.currentSegment)),this.wasGrounded=!0;const r=new T(-30,5,40),o=new T(-30,5,-40);r.applyQuaternion(t),o.applyQuaternion(t);const l=e.clone().add(r),c=e.clone().add(o),u=2;if(s.surface==="floor")l.y=u,c.y=u;else if(s.surface==="ceiling")l.y=this.arenaBounds.ceiling-u,c.y=this.arenaBounds.ceiling-u;else if(s.surface==="wall"){if(s.normal.x!==0){const d=s.normal.x>0?-this.arenaBounds.wallX+u:this.arenaBounds.wallX-u;l.x=d,c.x=d}else if(s.normal.z!==0){const d=s.normal.z>0?-this.arenaBounds.wallZ+u:this.arenaBounds.wallZ-u;l.z=d,c.z=d}}this.currentSegment.updatePosition(l,c,t)}update(e){for(let t=this.segments.length-1;t>=0;t--){const i=this.segments[t];i.update(e),i.active||(i.dispose(),this.segments.splice(t,1))}}addToScene(e){}removeFromScene(e){for(const t of this.segments)t.startDying();this.currentSegment=null}dispose(){for(const e of this.segments)e.dispose();this.segments=[],this.currentSegment=null}}class hN{constructor(e){this.scene=e,this.renderer=null,this.camera=null,this.explosions={active:[],goalEvents:new Map,demoEvents:new Map},this.boostTrails=new Map,this.supersonicTrails=new Map,this.ballTrail=null,nN()}setRenderContext(e,t){this.renderer=e,this.camera=t,sN(this.scene,e,t)}reset(){this.explosions.active.forEach(e=>e.removeFromScene(this.scene)),this.explosions.active=[],this.clearGoalExplosions(),this.boostTrails.forEach(e=>{e.removeFromScene(this.scene),e.dispose()}),this.boostTrails.clear(),this.supersonicTrails.forEach(e=>{e.removeFromScene(this.scene),e.dispose()}),this.supersonicTrails.clear(),this.ballTrail&&(this.ballTrail.removeFromScene(this.scene),this.ballTrail.dispose(),this.ballTrail=null)}clearEvents(){this.explosions.goalEvents.clear(),this.explosions.demoEvents.clear()}setGoalEvents(e){this.explosions.goalEvents.clear();for(const t of e??[])Number.isFinite(t.frame)&&this.explosions.goalEvents.set(t.frame,{time:t.time,team:t.team??0,playerName:t.playerName??""})}resetBallTrail(){this.ballTrail&&this.ballTrail.reset()}clearGoalExplosions(){Gn&&Gn.clearActive();for(const e of this.explosions.active)e.removeFromScene(this.scene);this.explosions.active=[]}createBoostTrail(e,t){if(this.boostTrails.has(t)){const s=this.boostTrails.get(t);s.removeFromScene(this.scene),s.dispose()}const i=new cN(e);return i.addToScene(this.scene),this.boostTrails.set(t,i),i}removeBoostTrail(e){const t=this.boostTrails.get(e);t&&(t.removeFromScene(this.scene),t.dispose(),this.boostTrails.delete(e))}updateBoostTrail(e,t,i,s,a){const r=this.boostTrails.get(e);r&&(r.setActive(t),t&&r.emit(i,s,a,this._playbackSpeed||1))}createSupersonicTrail(e,t){if(this.supersonicTrails.has(e)){const s=this.supersonicTrails.get(e);s.removeFromScene(this.scene),s.dispose()}const i=new dN(this.scene,t);return i.addToScene(this.scene),this.supersonicTrails.set(e,i),i}removeSupersonicTrail(e){const t=this.supersonicTrails.get(e);t&&(t.removeFromScene(this.scene),t.dispose(),this.supersonicTrails.delete(e))}updateSupersonicTrail(e,t,i,s,a,r){let o=this.supersonicTrails.get(e);!o&&t&&(o=this.createSupersonicTrail(e,r)),o&&(r!==void 0&&o.team!==r&&o.setTeam(r),o.setActive(t),t&&o.emit(i,s,a))}createBallTrail(){return this.ballTrail&&(this.ballTrail.removeFromScene(this.scene),this.ballTrail.dispose()),this.ballTrail=new tN(this.scene,0),this.ballTrail.addToScene(this.scene),console.log("✓ Spiral ball trail created and added to scene"),this.ballTrail}updateBallTrail(e,t,i){this.ballTrail||this.createBallTrail(),i!==void 0&&this.ballTrail.team!==i&&this.ballTrail.setTeam(i);const s=1/60*(this._playbackSpeed||1);this.ballTrail.emit(e,t,s)}triggerGoalExplosion(e,t){const i=rM(this.scene,this.renderer,this.camera);i&&(this.camera&&(i.camera=this.camera),i.trigger(e,t))}triggerDemoExplosion(e,t,i){const s=aM(this.scene);s&&s.trigger(e)}update(e,t=!0,i=1){this._playbackSpeed=i;const s=e*i;gi&&gi.update(s),Gn&&Gn.update(s);for(let a=this.explosions.active.length-1;a>=0;a--){const r=this.explosions.active[a];r.update(s)&&(r.removeFromScene(this.scene),this.explosions.active.splice(a,1))}t&&(this.boostTrails.forEach(a=>{a.update(s)}),this.supersonicTrails.forEach(a=>{a.update(s)}),this.ballTrail&&this.ballTrail.update(s))}}const Dv={Octane:65535,Dominus:16746496,Plank:8978176,Breakout:16711816,Hybrid:8913151,Merc:16776960},fN={0:5744895,1:16751680};function pN(n,e){return e===0||e===1?fN[e]:Dv[n]||Dv.Octane}class mN{constructor(e){this.scene=e,this.hitboxes=new Map,this.enabled=!1}setEnabled(e){this.enabled=e,this.hitboxes.forEach(({mesh:t})=>{t.visible=e})}createHitboxWireframe(e,t){const i=Ny[e]||Ny.Octane,s=pN(e,t),a=i.length,r=i.width,o=i.height,l=i.offsetX,c=i.offsetZ;console.log(`[HitboxManager] Creating hitbox for ${e}:`,{dims:i,length:a,width:r,height:o,offsetX:l,offsetY:c});const u=new Et,d=new ki(a,o,r),h=new je({color:s,transparent:!0,opacity:.35,depthTest:!1,depthWrite:!1,side:ut}),f=new Se(d,h);f.frustumCulled=!1,f.renderOrder=1,f.position.set(l,c,0),u.add(f);const p=new hf(d),g=new Pt({color:s,linewidth:2,transparent:!0,opacity:.9,depthTest:!1}),_=new Fn(p,g);_.frustumCulled=!1,_.renderOrder=2,_.position.set(l,c,0),u.add(_);const m=3.33,v=new vn(m,8,6),y=new Fg(v),b=new Pt({color:16777215,linewidth:1,transparent:!0,opacity:.9,depthTest:!1}),S=new Fn(y,b);return S.frustumCulled=!1,u.add(S),u.userData.hitboxType=e,u.userData.team=t??null,u.frustumCulled=!1,u}addHitbox(e,t,i){const s=i===0||i===1?i:null;if(this.hitboxes.has(e)){const r=this.hitboxes.get(e);if(r.hitboxType===t&&r.team===s)return;this.scene.remove(r.mesh),r.mesh.traverse(o=>{o.geometry&&o.geometry.dispose(),o.material&&o.material.dispose()})}const a=this.createHitboxWireframe(t,s);a.visible=this.enabled,this.scene.add(a),this.hitboxes.set(e,{mesh:a,hitboxType:t,team:s})}removeHitbox(e){if(this.hitboxes.has(e)){const{mesh:t}=this.hitboxes.get(e);this.scene.remove(t),t.traverse(i=>{i.geometry&&i.geometry.dispose(),i.material&&i.material.dispose()}),this.hitboxes.delete(e)}}updateHitboxes(e,t,i,s){if(!this.enabled)return;for(const[r,o]of Object.entries(t)){const l=e[o];if(!l||!l.userData.isCar)continue;const c=i?i(r):"Octane",u=s?s(r):null;this.addHitbox(o,c,u);const{mesh:d}=this.hitboxes.get(o);d.position.copy(l.position),d.quaternion.copy(l.quaternion),d.visible=this.enabled&&l.visible}const a=new Set(Object.values(t));for(const r of this.hitboxes.keys())a.has(r)||this.removeHitbox(r)}reset(){this.hitboxes.forEach(({mesh:e})=>{this.scene.remove(e),e.traverse(t=>{t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose()})}),this.hitboxes.clear()}dispose(){this.reset()}}const oM=["baseGroup","glowMesh","innerGlowMesh","lensColumnMesh","lensRimMesh","topGlowMesh","coreGlowMesh","highlightMesh"];function Gp(n,e,t,i){const s=new Se(new Wo(n,32),new je({color:e,transparent:!0,opacity:t,blending:Vt,side:ut,depthWrite:!1}));return s.rotation.x=-Math.PI/2,s.renderOrder=i,s}function Ov(n,e){n&&n.traverse(t=>{const i=t;if(!i.isMesh||!(i.material instanceof je))return;const s=i.userData.baseOpacity;i.material.opacity=(s??i.material.opacity)*e})}function ku(n,e,t){n.rotation.x=-Math.PI/2,n.renderOrder=t,n.frustumCulled=!1,n.userData.baseOpacity=e,n.material.transparent=!0,n.material.opacity=e,n.material.side=ut,n.material.depthWrite=!1}function _N(n){const e=new Et;e.renderOrder=98,e.frustumCulled=!1;const t=new je({color:1118477}),i=new je({color:16752640,blending:Vt}),s=new Se(new Wo(n*.55,48),t.clone());ku(s,.86,98),e.add(s);const a=new Se(new oi(n*.45,n*.62,48),new je({color:16765242,blending:Vt}));ku(a,.78,100),a.position.y=1.4,e.add(a);function r(o,l,c){const u=new $s;return[[o*Math.cos(-c*.72),o*Math.sin(-c*.72)],[l*Math.cos(-c),l*Math.sin(-c)],[l*Math.cos(c),l*Math.sin(c)],[o*Math.cos(c*.72),o*Math.sin(c*.72)]].forEach(([h,f],p)=>{p===0?u.moveTo(h,f):u.lineTo(h,f)}),u.closePath(),u}for(let o=0;o<3;o+=1){const l=o*(Math.PI*2)/3+Math.PI/2,c=new Se(new vr(r(n*.52,n*1.42,.33)),t.clone());ku(c,.86,98),c.rotation.z=l,e.add(c);const u=new Se(new vr(r(n*.66,n*1.2,.21)),i.clone());ku(u,.86,99),u.position.y=1.1,u.rotation.z=l,e.add(u)}return e}function Fv(n,e){for(const t of oM){const i=n.userData[t];i&&(i.visible=e)}}function gN(){let n=new Map;function e(i){const s=i.player.adapter.boostPads;!s||s.size===0||(console.log(`[boost-pads] Creating ${s.size} boost pads...`),n=new Map,s.forEach((a,r)=>{const o=a.isBig;let l,c,u;if(o){l=new vn(37,24,18),c=new li({color:16757274,emissive:16747008,emissiveIntensity:.42,metalness:.04,roughness:.08,clearcoat:1,clearcoatRoughness:.025,transmission:.18,thickness:30,ior:1.42,envMapIntensity:1.9,blending:Vt,transparent:!0,opacity:.68,depthWrite:!1}),u=new Se(l,c),u.renderOrder=100;const p=_N(37*2.05);p.position.y=-140,u.add(p),u.userData.baseGroup=p;const g=new Se(new gr(37*.12,37*.18,112,24,1,!0),new je({color:16761664,transparent:!0,opacity:.28,blending:Vt,side:ut,depthWrite:!1}));g.position.y=-62,g.renderOrder=99,u.add(g),u.userData.lensColumnMesh=g;const _=new Se(new vn(37*1.03,24,14),new je({color:16768890,transparent:!0,opacity:.32,blending:Vt,side:dn,depthWrite:!1}));_.renderOrder=101,u.add(_),u.userData.lensRimMesh=_;const m=new vn(37*1.3,20,14),v=new je({color:16758315,transparent:!0,opacity:.16,blending:Vt,side:dn,depthWrite:!1}),y=new Se(m,v);y.renderOrder=99,u.add(y),u.userData.glowMesh=y;const b=new vn(37*1.12,20,14),S=new je({color:16761130,transparent:!0,opacity:.22,blending:Vt,side:dn,depthWrite:!1}),x=new Se(b,S);x.renderOrder=99,u.add(x),u.userData.innerGlowMesh=x,u.userData.needsLight=!0}else{l=new gr(45,45*.92,8,32),c=new li({color:16761370,emissive:16750336,emissiveIntensity:.72,metalness:.88,roughness:.14,clearcoat:1,clearcoatRoughness:.05,envMapIntensity:2,transparent:!0,opacity:1,depthWrite:!1}),u=new Se(l,c),u.renderOrder=100;const g=Gp(45*1.42,16756736,.34,101);g.position.y=8/2+.15,u.add(g),u.userData.topGlowMesh=g;const _=Gp(45*.74,16777114,.42,102);_.position.y=8/2+.35,u.add(_),u.userData.coreGlowMesh=_;const m=Gp(45*.42,16775376,.46,103);m.position.set(-45*.18,8/2+.55,-45*.12),m.scale.y=.34,u.add(m),u.userData.highlightMesh=m}const h=o?130:10;if(u.position.set(a.position.x,h,a.position.y),u.userData.padId=r,u.userData.isBig=o,u.userData.isAvailable=!0,i.scene.add(u),n.set(r,u),u.userData.needsLight){const f=new br(16751872,.7,480);f.decay=0,f.position.set(a.position.x,h-50,a.position.y),i.scene.add(f),u.userData.light=f}}),console.log(`[boost-pads] ✓ Created ${n.size} boost pad meshes`))}function t(i){i.player.adapter.boostPads.forEach((a,r)=>{const o=n.get(r);if(!o)return;const l=a.isAvailable;o.userData.isAvailable!==l&&(o.userData.isAvailable=l,l?(o.material.color.setHex(a.isBig?16757274:16761370),o.material.emissive.setHex(a.isBig?16747008:16750336),o.material.emissiveIntensity=a.isBig?.42:.72,o.material.opacity=a.isBig?.68:1,o.visible=!0,Fv(o,!0),Ov(o.userData.baseGroup,1),o.userData.light&&(o.userData.light.intensity=.85),o.userData.glowMesh&&(o.userData.glowMesh.visible=!0),o.userData.innerGlowMesh&&(o.userData.innerGlowMesh.visible=!0)):(o.material.color.setHex(a.isBig?9063424:9065472),o.material.emissive.setHex(0),o.material.emissiveIntensity=0,o.material.opacity=.2,o.visible=!0,Fv(o,!1),o.userData.baseGroup&&(o.userData.baseGroup.visible=!0,Ov(o.userData.baseGroup,.26)),o.userData.light&&(o.userData.light.intensity=0),o.userData.glowMesh&&(o.userData.glowMesh.visible=!1),o.userData.innerGlowMesh&&(o.userData.innerGlowMesh.visible=!1)))})}return{id:"boost-pads",setup(i){e(i)},beforeRender(i){t(i)},teardown(i){n.forEach(s=>{i.scene.remove(s),s.geometry.dispose(),s.material.dispose();for(const r of oM){const o=s.userData[r];o&&o.traverse(l=>{const c=l;c.isMesh&&(c.geometry.dispose(),c.material.dispose())})}const a=s.userData.light;a&&(i.scene.remove(a),a.dispose())}),n.clear()}}}const yN=2;function vN(n){if(n.frames.length===0)return null;const e=new Map;for(const s of n.frames)e.set(s.gameState,(e.get(s.gameState)??0)+1);let t=null,i=-1;for(const[s,a]of e.entries())a<=i||(t=s,i=a);return t}function bN(n,e){if(e===null)return null;for(const t of n.frames){if(t.gameState===e)break;return t.gameState}return null}function lM(n,e){return e===null?n.kickoffCountdown<=0:n.gameState===e}function ty(n,e){return n.kickoffCountdown>0?!0:e!==null&&n.gameState===e}function xN(n,e){return n.ballFrames[e]?.position?!0:n.players.some(t=>t.frames[e]?.position)}function wN(n,e,t,i){return ty(e,i)&&xN(n,t)}function SN(n,e){return n.timelineEvents.some(t=>t.kind==="goal"&&e.time>=t.time&&e.timec){const h=a.at(-1);h&&h.endTime>=c?h.endTime=Math.max(h.endTime,d):a.push({startTime:c,endTime:d})}o=u}return a}function MN(n,e,t){const i=bt.clamp(t,0,n);for(const s of e){if(i0&&(n.frames[s-1]?.kickoffCountdown??0)>0;)s-=1;let a=e+1;for(;a0;)a+=1;let r=0;for(let c=s;cl>s&&lM(o,t));return!r||r.time===e?null:r.time}function LN(n,e,t,i){const s=Bh(n,e),a=n.frames[s];if(!a||!dd(n,a,s,t,i))return null;const r=n.frames.find((c,u)=>u>s&&!dd(n,c,u,t,i));if(r)return r.time===e?null:r.time;let o=s;for(;o>0&&dd(n,n.frames[o-1],o-1,t,i);)o-=1;const l=n.frames[o]?.time;return l===void 0||l===e?null:l}function kN(n){return!!n?.position&&n?.isPresent!==!1}function DN(n,e,t){for(let i=n.length-1;i>=0;i-=1){const s=n[i],a=t-s.time;if(!(a<0)){if(a>PN)break;if(s.kind==="demo"&&s.secondaryPlayerId===e)return s}}return null}const ON="space",FN={space:{id:"space",skyboxUrl:"/skyboxes/PlanetaryEarth4k.hdr",exposure:1.45,rotation:{x:8,y:0,z:28},animation:{enabled:!0,speed:2}}};function NN(n){if(n===!1)return null;if(typeof n=="string"){const e=FN[n];return e||(console.warn(`[player] unknown environment "${n}"; using neutral default`),null)}return n}const UN=new Proxy({},{get:()=>()=>{}});function Uv(n){if(!n)return null;const e={};for(const t of Object.keys(n)){const i=n[t];typeof i=="number"&&Number.isFinite(i)&&(e[t]=i)}return e}const Bv=48,Du=.14,BN=16,zN=16,HN=.003,VN=.05,GN=1.08,zv=4120,Hv=5140,$N=0,WN=2200,XN=new T(0,700,0),KN=new T(-1,0,0),qN=new T(0,-1,0),YN=new T(0,900,0),jN=new T(0,1,0),ZN=new T(9600,-5500,12600).normalize();function JN(n,e){const t=Number.isFinite(e)&&e>0?e:1.7777777777777777,i=n==="overhead"?XN.clone():YN.clone(),s=n==="overhead"?KN.clone():jN.clone(),a=n==="overhead"?qN.clone():ZN.clone(),r=QN({aspect:t,fov:Bv,forward:a,margin:GN,target:i,up:s});return{position:i.clone().addScaledVector(a,-r),target:i,up:s,fov:Bv}}function QN(n){const{aspect:e,fov:t,forward:i,margin:s,target:a,up:r}=n,o=i.clone().normalize(),l=new T().crossVectors(o,r).normalize(),c=new T().crossVectors(l,o).normalize(),u=Math.tan(bt.degToRad(t)/2),d=u*e;let h=1;for(const f of[-zv,zv])for(const p of[$N,WN])for(const g of[-Hv,Hv]){const _=new T(f,p,g).sub(a),m=Math.abs(_.dot(l)),v=Math.abs(_.dot(c)),y=_.dot(o);h=Math.max(h,m/d-y,v/u-y)}return Math.max(1,h*s)}function e3(n){const e=new Et;return e.name="replayRoot",e.matrixAutoUpdate=!1,e.matrix.set(1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1),n.add(e),e}class t3 extends EventTarget{container;adapter;replay;options;sceneManager;arenaManager;actorManager;effectsManager;hitboxManager;controls;replayRoot;sceneState;effectsEnabled;ready;plugins=[];beforeRenderCallbacks=[];resizeObserver=null;animationFrameId=null;disposed=!1;playing=!1;readyResolved=!1;speed;loop;currentTime=0;lastTickAt=null;freeCameraTransition=null;cameraDistanceScaleValue;customCameraSettingsValue;cameraViewModeValue;attachedPlayerIdValue;ballCamEnabledValue;boostMeterEnabledValue;boostPickupAnimationEnabledValue;hitboxWireframesEnabledValue;hitboxOnlyModeEnabledValue;hitboxTypeByName=null;hitboxTeamByName=null;hitboxesActive=!1;skipPostGoalTransitionsEnabledValue;skipKickoffsEnabledValue;attachmentTouched=!1;liveGameState=null;kickoffGameState=null;timelineSegmentsCacheKey=null;timelineSegmentsCache=[];constructor(e,t,i={},s=null){super(),this.container=e,this.adapter=t,this.replay=s,this.options=i,this.updateReplayGameStates(),this.speed=Math.max(.1,i.initialPlaybackRate??i.speed??1),this.loop=i.loop??!1,this.cameraDistanceScaleValue=Math.max(.25,i.initialCameraDistanceScale??1),this.customCameraSettingsValue=Uv(i.initialCustomCameraSettings),this.attachedPlayerIdValue=i.initialAttachedPlayerId??null,this.cameraViewModeValue=i.initialCameraViewMode??(this.attachedPlayerIdValue?"follow":"free"),this.ballCamEnabledValue=i.initialBallCamEnabled??null,this.boostMeterEnabledValue=i.initialBoostMeterEnabled??!1,this.boostPickupAnimationEnabledValue=i.initialBoostPickupAnimationEnabled??!0,this.hitboxWireframesEnabledValue=i.initialHitboxWireframesEnabled??!1,this.hitboxOnlyModeEnabledValue=i.initialHitboxOnlyModeEnabled??!1,this.skipPostGoalTransitionsEnabledValue=i.initialSkipPostGoalTransitionsEnabled??!0,this.skipKickoffsEnabledValue=i.initialSkipKickoffsEnabled??!1,this.sceneManager=new vO(e,{assetBase:i.assetBase,preserveDrawingBuffer:i.preserveDrawingBuffer}),this.sceneManager.initDefaultEnvironment(),this.applyEnvironmentSpec(i.environment??ON),this.arenaManager=new cF(this.scene,{assetBase:i.assetBase}),this.effectsEnabled=i.effects??!0,this.effectsManager=this.effectsEnabled?new hN(this.scene):UN,this.actorManager=new QF(this.scene,this.effectsManager,{assetBase:i.assetBase}),i.motionInterpolation&&this.setMotionInterpolation(i.motionInterpolation),this.actorManager.initFromFramework(t),this.actorManager.initInterpolants(t.getTimelines()),this.hitboxManager=new mN(this.scene),this.syncGoalEvents(),this.controls=new eO(this.camera,this.renderer.domElement),this.controls.zoomSpeed=2.5,this.camera.position.set(0,4e3,6e3),this.controls.target.set(0,200,0),this.controls.update(),this.replayRoot=e3(this.scene),this.sceneState=this.createSceneState(),this.ready=Promise.all([this.arenaManager.loadArenaMeshes().catch(a=>{console.warn("[player] arena load failed",a)}),this.prepareReplayAssets()]).then(()=>{this.markReady()}),this.installResizeHandling();for(const a of i.plugins??[])this.installPlugin(a,!1);this.plugins.some(a=>a.plugin.id==="boost-pads")||this.installPlugin(gN(),!1),this.applyInitialCameraOptions(),this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded(),this.scheduleAnimationFrame(),this.emitChange(),i.autoplay&&this.play()}get scene(){return this.sceneManager.scene}get camera(){return this.sceneManager.camera}get renderer(){return this.sceneManager.renderer}get duration(){return this.adapter.duration}async replaceReplay(e,t,i={}){if(this.disposed)throw new Error("Cannot replace replay on a disposed ReplayPlayer");const s=i.preservePlayback??this.playing;this.playing&&this.setPlayingInternal(!1),this.teardownPlugins(),this.effectsManager.reset(),this.effectsManager.clearEvents?.(),this.hitboxManager.reset(),this.actorManager.reset(),this.adapter=e,this.replay=t,this.updateReplayGameStates(),this.timelineSegmentsCacheKey=null,this.timelineSegmentsCache=[],this.hitboxTypeByName=null,this.hitboxTeamByName=null,this.hitboxesActive=!1,this.freeCameraTransition=null,this.actorManager.initFromFramework(e),this.actorManager.initInterpolants(e.getTimelines()),this.syncGoalEvents();const a=this.attachedPlayerIdValue&&this.adapter.playerList.some(r=>r.id===this.attachedPlayerIdValue)?this.attachedPlayerIdValue:null;a!==this.attachedPlayerIdValue&&(this.attachedPlayerIdValue=a,this.cameraViewModeValue==="follow"&&(this.cameraViewModeValue="free")),this.seekInternal(i.currentTime??0),this.readyResolved=!1,this.ready=this.prepareReplayAssets().then(()=>{this.markReady()}),await this.ready,this.setupPlugins(),this.applyInitialCameraOptions(),this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded(),s&&this.setPlayingInternal(!0),this.render(),this.emitChange()}setEnvironment(e){this.applyEnvironmentSpec(e)}applyEnvironmentSpec(e){const t=NN(e);if(!t){this.sceneManager.setDefaultBackground();return}this.sceneManager.applyEnvironment(t).catch(i=>{console.warn(`[player] environment "${t.id}" failed to load`,i)})}play(){this.playing||(this.setPlayingInternal(!0),this.emitChange())}pause(){this.playing&&(this.setPlayingInternal(!1),this.emitChange())}togglePlayback(){this.playing?this.pause():this.play()}seek(e){this.seekInternal(e),this.playing&&(this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded()),this.emitChange()}setPlaybackRate(e){this.speed=Math.max(.1,e),this.emitChange()}setLoop(e){this.loop=e}setMotionInterpolation(e){this.actorManager.interpolationMethod=e==="linear"?"lerp":"hermite"}setFrameIndex(e){const t=this.adapter.frameTimes;if(t.length===0||!Number.isFinite(e))return;const i=Math.min(Math.max(Math.trunc(e),0),t.length-1);this.playing&&this.setPlayingInternal(!1),this.seekInternal(t[i]),this.emitChange()}stepFrames(e){Number.isFinite(e)&&this.setFrameIndex(this.adapter.frameIndexAt(this.currentTime)+Math.trunc(e))}stepForwardFrame(){this.stepFrames(1)}stepBackwardFrame(){this.stepFrames(-1)}setCameraDistanceScale(e){this.cameraDistanceScaleValue=Math.max(.25,e),this.getCameraPlugin()?.setDistanceScale(this.cameraDistanceScaleValue),this.emitChange()}setCustomCameraSettings(e){this.applyCustomCameraSettings(e),this.emitChange()}setAttachedPlayer(e){this.attachedPlayerIdValue=e,this.cameraViewModeValue=e?"follow":"free",this.attachmentTouched=!0,this.freeCameraTransition=null,this.syncCameraAttachment(),this.emitChange()}setCameraViewMode(e){this.cameraViewModeValue=e,this.attachmentTouched=!0,this.freeCameraTransition=null,this.syncCameraAttachment(),this.emitChange()}setFreeCameraPreset(e,t={}){this.cameraViewModeValue="free",this.attachmentTouched=!0,this.syncCameraAttachment();const i=JN(e,this.camera.aspect);t.instant?(this.camera.position.copy(i.position),this.controls.target.copy(i.target),this.camera.up.copy(i.up).normalize(),this.camera.fov=i.fov,this.camera.updateProjectionMatrix(),this.camera.lookAt(i.target),this.controls.enabled=!0,this.freeCameraTransition=null):this.freeCameraTransition=i,this.emitChange()}setBallCamEnabled(e){this.ballCamEnabledValue=e,this.getCameraPlugin()?.setBallCam(e),this.emitChange()}setBoostMeterEnabled(e){this.boostMeterEnabledValue=e,this.emitChange()}setBoostPickupAnimationEnabled(e){this.boostPickupAnimationEnabledValue=e,this.emitChange()}setHitboxWireframesEnabled(e){this.hitboxWireframesEnabledValue=e,this.emitChange()}setHitboxOnlyModeEnabled(e){this.hitboxOnlyModeEnabledValue=e,this.emitChange()}setSkipPostGoalTransitionsEnabled(e){this.skipPostGoalTransitionsEnabledValue=e,e&&this.playing&&this.skipPostGoalTransitionIfNeeded(),this.emitChange()}setSkipKickoffsEnabled(e){this.skipKickoffsEnabledValue=e,e&&this.playing&&(this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded()),this.emitChange()}setState(e){e.speed!==void 0&&(this.speed=Math.max(.1,e.speed)),e.cameraDistanceScale!==void 0&&(this.cameraDistanceScaleValue=Math.max(.25,e.cameraDistanceScale),this.getCameraPlugin()?.setDistanceScale(this.cameraDistanceScaleValue)),e.customCameraSettings!==void 0&&this.applyCustomCameraSettings(e.customCameraSettings),e.cameraViewMode!==void 0&&(this.cameraViewModeValue=e.cameraViewMode,this.attachmentTouched=!0),e.attachedPlayerId!==void 0&&(this.attachedPlayerIdValue=e.attachedPlayerId,this.attachmentTouched=!0,e.cameraViewMode===void 0&&(this.cameraViewModeValue=e.attachedPlayerId?"follow":"free")),(e.cameraViewMode!==void 0||e.attachedPlayerId!==void 0)&&(this.freeCameraTransition=null,this.syncCameraAttachment()),e.useReplayBallCam===!0?(this.ballCamEnabledValue=null,this.getCameraPlugin()?.setBallCam(null)):e.ballCamEnabled!==void 0&&(this.ballCamEnabledValue=e.ballCamEnabled,this.getCameraPlugin()?.setBallCam(e.ballCamEnabled)),e.boostMeterEnabled!==void 0&&(this.boostMeterEnabledValue=e.boostMeterEnabled),e.boostPickupAnimationEnabled!==void 0&&(this.boostPickupAnimationEnabledValue=e.boostPickupAnimationEnabled),e.hitboxWireframesEnabled!==void 0&&(this.hitboxWireframesEnabledValue=e.hitboxWireframesEnabled),e.hitboxOnlyModeEnabled!==void 0&&(this.hitboxOnlyModeEnabledValue=e.hitboxOnlyModeEnabled),e.skipPostGoalTransitionsEnabled!==void 0&&(this.skipPostGoalTransitionsEnabledValue=e.skipPostGoalTransitionsEnabled),e.skipKickoffsEnabled!==void 0&&(this.skipKickoffsEnabledValue=e.skipKickoffsEnabled),e.currentTime!==void 0&&this.seekInternal(e.currentTime),e.playing!==void 0&&e.playing!==this.playing&&this.setPlayingInternal(e.playing),this.playing&&(e.currentTime!==void 0||e.playing!==void 0)&&(this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded()),this.emitChange()}getState(){const e=this.adapter.frameIndexAt(this.currentTime),t=this.getCameraPlugin();let i=this.cameraViewModeValue,s=this.attachedPlayerIdValue;if(t)if(t.getMode()==="follow"){i="follow";const a=t.getTarget();s=(a?this.adapter.playerList.find(o=>o.name===a):void 0)?.id??s}else i="free",s=null;return{currentTime:this.currentTime,duration:this.duration,frameIndex:e,activeMetadata:this.replay?AN(this.replay,e,this.currentTime):null,playing:this.playing,speed:this.speed,cameraDistanceScale:this.cameraDistanceScaleValue,customCameraSettings:this.customCameraSettingsValue,cameraViewMode:i,attachedPlayerId:s,ballCamEnabled:t?t.getBallCam():this.ballCamEnabledValue??!1,useReplayBallCam:this.ballCamEnabledValue===null,effectiveBallCamEnabled:t?t.getBallCam():this.ballCamEnabledValue??!1,boostMeterEnabled:this.boostMeterEnabledValue,boostPickupAnimationEnabled:this.boostPickupAnimationEnabledValue,hitboxWireframesEnabled:this.hitboxWireframesEnabledValue,hitboxOnlyModeEnabled:this.hitboxOnlyModeEnabledValue,skipPostGoalTransitionsEnabled:this.skipPostGoalTransitionsEnabledValue,skipKickoffsEnabled:this.skipKickoffsEnabledValue}}getSnapshot(){return this.getState()}getTimelineDuration(){return this.replay?.duration??this.duration}getTimelineCurrentTime(){return this.projectReplayTimeToTimeline(this.currentTime).timelineTime}getTimelineSegments(){if(!this.replay)return[];const e=`${this.skipPostGoalTransitionsEnabledValue}:${this.skipKickoffsEnabledValue}`;return this.timelineSegmentsCacheKey===e?this.timelineSegmentsCache:(this.timelineSegmentsCacheKey=e,this.timelineSegmentsCache=TN(this.replay,this.skipPostGoalTransitionsEnabledValue,this.skipKickoffsEnabledValue,this.liveGameState,this.kickoffGameState),this.timelineSegmentsCache)}projectReplayTimeToTimeline(e){return MN(this.replay?.duration??this.duration,this.getTimelineSegments(),e)}projectTimelineTimeToReplay(e){return EN(this.replay?.duration??this.duration,this.getTimelineDuration(),this.getTimelineSegments(),e)}subscribe(e){const t=i=>{e(i.detail)};return this.addEventListener("change",t),e(this.getState()),()=>{this.removeEventListener("change",t)}}onBeforeRender(e){return this.beforeRenderCallbacks.push(e),()=>{const t=this.beforeRenderCallbacks.indexOf(e);t>=0&&this.beforeRenderCallbacks.splice(t,1)}}addPlugin(e){return this.installPlugin(e,!0)}removePlugin(e){const t=this.plugins.findIndex(s=>s.plugin.id===e);if(t<0)return!1;const[i]=this.plugins.splice(t,1);return i.plugin.teardown?.(this.createPluginContext()),!0}getPlugins(){return this.plugins.map(e=>e.plugin)}destroy(){if(!this.disposed){for(this.disposed=!0,this.playing=!1,this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.beforeRenderCallbacks.length=0;this.plugins.length>0;)this.plugins.pop()?.plugin.teardown?.(this.createPluginContext());this.controls.dispose(),this.effectsEnabled&&this.effectsManager.reset(),this.hitboxManager.dispose(),this.actorManager.reset(),this.sceneManager.dispose()}}dispose(){this.destroy()}setPlayingInternal(e){this.playing=e,this.lastTickAt=null,e?this.actorManager.resumeAnimations():this.actorManager.pauseAnimations()}prepareReplayAssets(){return this.actorManager.waitForBallModel().catch(()=>!1).then(()=>{if(this.effectsEnabled)try{this.effectsManager.setRenderContext(this.renderer,this.camera)}catch(e){console.warn("[player] explosion warmup failed",e)}})}markReady(){this.readyResolved=!0,this.lastTickAt=null}updateReplayGameStates(){if(!this.replay){this.liveGameState=null,this.kickoffGameState=null;return}this.liveGameState=vN(this.replay),this.kickoffGameState=bN(this.replay,this.liveGameState)}syncGoalEvents(){this.effectsEnabled&&(this.effectsManager.clearEvents?.(),this.replay&&this.effectsManager.setGoalEvents(this.replay.timelineEvents.filter(e=>e.kind==="goal").map(e=>({frame:e.frame,time:e.time,team:e.isTeamZero?0:1,playerName:e.playerName??""}))))}teardownPlugins(){const e=this.createPluginContext();for(const t of this.plugins)t.plugin.teardown?.(e)}setupPlugins(){for(const e of this.plugins)e.plugin.setup?.(this.createPluginContext()),e.plugin.id==="camera"&&this.pushCameraParityState(),e.plugin.onStateChange?.(this.createPluginStateContext(this.getState()))}seekInternal(e){this.currentTime=bt.clamp(e,0,this.duration),this.actorManager.seekAnimations(this.currentTime),this.effectsManager.resetBallTrail(),this.effectsManager.clearGoalExplosions?.(),this.actorManager.resetGoalExplosionPlaybackState(),this.actorManager.resetWheelTracking()}getPlaybackEndTime(){return this.replay?CN(this.replay.duration,this.getTimelineSegments()):this.duration}skipPastKickoffIfNeeded(){if(!this.replay||!this.skipKickoffsEnabledValue)return!1;const e=IN(this.replay,this.currentTime,this.liveGameState,this.kickoffGameState);return e===null?!1:(this.seekInternal(e),!0)}skipPostGoalTransitionIfNeeded(){if(!this.replay||!this.skipPostGoalTransitionsEnabledValue)return!1;const e=LN(this.replay,this.currentTime,this.liveGameState,this.kickoffGameState);return e===null?!1:(this.seekInternal(e),!0)}getCameraPlugin(){const e=this.plugins.find(t=>t.plugin.id==="camera")?.plugin;return e&&typeof e.follow=="function"?e:null}playerNameForId(e){return this.adapter.playerList.find(t=>t.id===e)?.name??null}applyReplayBallCam(){if(this.ballCamEnabledValue!==null||this.cameraViewModeValue!=="follow"||!this.attachedPlayerIdValue)return;const e=this.playerNameForId(this.attachedPlayerIdValue);if(!e)return;const t=this.adapter.getAllPlayers().find(i=>i.name===e);t&&this.getCameraPlugin()?.setBallCam(t.isBallCam)}syncCameraAttachment(){const e=this.getCameraPlugin();if(e){if(this.cameraViewModeValue==="follow"&&this.attachedPlayerIdValue){const t=this.playerNameForId(this.attachedPlayerIdValue);if(!t){console.warn(`[player] no player with id ${JSON.stringify(this.attachedPlayerIdValue)}`);return}this.camera.up.set(0,1,0),e.follow(t);return}e.getMode()==="follow"&&e.release()}}applyCustomCameraSettings(e){this.customCameraSettingsValue=Uv(e);const t=this.getCameraPlugin();t&&(t.setCameraSettings(null),this.customCameraSettingsValue&&t.setCameraSettings(this.customCameraSettingsValue))}pushCameraParityState(){const e=this.getCameraPlugin();e&&(this.cameraDistanceScaleValue!==1&&e.setDistanceScale(this.cameraDistanceScaleValue),this.customCameraSettingsValue&&e.setCameraSettings(this.customCameraSettingsValue),this.ballCamEnabledValue!==null&&e.setBallCam(this.ballCamEnabledValue),this.attachmentTouched&&this.syncCameraAttachment())}applyInitialCameraOptions(){const e=this.options;(e.initialAttachedPlayerId!==void 0||e.initialCameraViewMode!==void 0)&&(this.attachmentTouched=!0),this.pushCameraParityState()}computeFrameRenderInfo(){const e=this.adapter.frameTimes,t=this.adapter.frameIndexAt(this.currentTime),i=Math.min(t+1,Math.max(e.length-1,0)),s=e[t]??0,a=e[i]??s,r=a>s?bt.clamp((this.currentTime-s)/(a-s),0,1):0;return{frameIndex:t,nextFrameIndex:i,alpha:r,currentTime:this.currentTime}}installResizeHandling(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>this.sceneManager.onWindowResize()),this.resizeObserver.observe(this.container))}scheduleAnimationFrame(){this.animationFrameId!==null||this.disposed||(this.animationFrameId=requestAnimationFrame(this.tick))}tick=e=>{if(this.animationFrameId=null,this.disposed)return;let t=!1,i=0;if(this.playing&&this.readyResolved){i=this.lastTickAt===null?0:Math.min(.1,(e-this.lastTickAt)/1e3),this.lastTickAt=e;let s=this.currentTime+i*this.speed;const a=this.getPlaybackEndTime();s>=a&&(this.loop?(s=0,this.actorManager.seekAnimations(0),this.effectsManager.resetBallTrail(),this.effectsManager.clearGoalExplosions?.(),this.actorManager.resetGoalExplosionPlaybackState(),this.actorManager.resetWheelTracking()):(s=a,this.playing=!1)),t=s!==this.currentTime||!this.playing,this.currentTime=s,this.playing&&(t=this.skipPostGoalTransitionIfNeeded()||t,t=this.skipPastKickoffIfNeeded()||t)}else this.playing&&(this.lastTickAt=null);this.render(i),t&&this.emitChange(),this.scheduleAnimationFrame()};renderFrame(e=0){if(this.adapter.seek(this.currentTime),this.playing&&this.actorManager.updateAnimations(e*this.speed),this.actorManager.updateFromFramework(this.adapter,this.currentTime),this.updatePlayerStates(),this.applyReplayBallCam(),this.updateHitboxVisualization(),this.effectsManager.update(e,this.playing,this.speed),this.playing&&this.actorManager.updateWheelRotations(),this.sceneManager.updateSkyboxAnimation(this.playing?e*this.speed:0),this.controls.update(),this.beforeRenderCallbacks.length>0){const t=this.computeFrameRenderInfo();for(const i of[...this.beforeRenderCallbacks])i(t)}if(this.plugins.length>0){const t=this.createRenderContext();for(const i of this.plugins)i.plugin.beforeRender?.(t)}this.updateFreeCameraTransition(),this.renderer.render(this.scene,this.camera)}render(e=0){this.renderFrame(e)}updateFreeCameraTransition(){const e=this.freeCameraTransition;if(!e)return;this.controls.enabled=!1,this.camera.position.lerp(e.position,Du),this.controls.target.lerp(e.target,Du),this.camera.up.lerp(e.up,Du).normalize(),this.camera.fov=bt.lerp(this.camera.fov,e.fov,Du),this.camera.updateProjectionMatrix(),this.camera.lookAt(this.controls.target);const t=this.camera.position.distanceToSquared(e.position)<=BN,i=this.controls.target.distanceToSquared(e.target)<=zN,s=this.camera.up.angleTo(e.up)<=HN,a=Math.abs(this.camera.fov-e.fov)<=VN;!t||!i||!s||!a||(this.camera.position.copy(e.position),this.controls.target.copy(e.target),this.camera.up.copy(e.up).normalize(),this.camera.fov=e.fov,this.camera.updateProjectionMatrix(),this.camera.lookAt(e.target),this.controls.enabled=!0,this.freeCameraTransition=null)}updatePlayerStates(){if(!this.playing)return;const e=this.hitboxOnlyModeEnabledValue;for(const t of this.adapter.getAllPlayers())this.actorManager.updateBoostState(t.name,t.isBoosting&&!e,t.isKickoffReset),this.actorManager.updateSupersonicState(t.name,t.isSupersonic&&!e,t.team)}updateHitboxVisualization(){const e=this.hitboxWireframesEnabledValue||this.hitboxOnlyModeEnabledValue;if(!e&&!this.hitboxesActive||(this.hitboxesActive=e,this.hitboxManager.setEnabled(e),!e))return;const t=this.actorManager;if(this.hitboxTypeByName||(this.hitboxTypeByName=new Map(this.adapter.getAllPlayers().map(i=>[i.name,i.hitboxType]))),this.hitboxTeamByName||(this.hitboxTeamByName=new Map(this.adapter.getAllPlayers().map(i=>[i.name,i.team]))),this.hitboxManager.updateHitboxes(t.actors,t.playerNameToCarActorId,i=>this.hitboxTypeByName?.get(i)??"Octane",i=>this.hitboxTeamByName?.get(i)??null),this.hitboxOnlyModeEnabledValue)for(const i of Object.values(t.playerNameToCarActorId)){const s=i===void 0?void 0:t.actors[i];s&&(s.visible=!1)}}installPlugin(e,t){const i=typeof e=="function"?e():e;if(this.plugins.some(a=>a.plugin.id===i.id))throw new Error(`Player plugin "${i.id}" is already installed`);const s={definition:e,plugin:i};return this.plugins.push(s),i.setup?.(this.createPluginContext()),i.id==="camera"&&this.pushCameraParityState(),i.onStateChange?.(this.createPluginStateContext(this.getState())),t&&this.render(),()=>{const a=this.plugins.indexOf(s);a<0||(this.plugins.splice(a,1),i.teardown?.(this.createPluginContext()))}}createSceneState(){const e=this.actorManager,t=this,i=new Se;return{get scene(){return t.scene},replayRoot:this.replayRoot,get camera(){return t.camera},get renderer(){return t.renderer},controls:this.controls,resize:()=>this.sceneManager.onWindowResize(),dispose:()=>this.destroy(),get ballMesh(){return(e.ballActorId!=null?e.actors[e.ballActorId]:null)??i},get playerMeshes(){const s=new Map;for(const a of t.adapter.playerList){const r=e.playerNameToCarActorId[a.name],o=r!=null?e.actors[r]:void 0;o&&s.set(a.id,o)}return s},playerBodyMeshes:new Map,playerHitboxes:new Map,playerBoostTrails:new Map,playerBoostMeters:new Map,playerDemoIndicators:new Map,updateWallVisibility:()=>{}}}createPluginContext(){return{player:this,replay:this.replay,options:this.options,scene:this.scene,camera:this.camera,renderer:this.renderer,container:this.container}}createPluginStateContext(e){return{...this.createPluginContext(),state:e}}createRenderContext(){const e=this.actorManager,t=this.adapter.ball,i={position:t.position,rotation:t.rotation,velocity:t.velocity,visible:t.visible,object3d:e.ballActorId!=null?e.actors[e.ballActorId]??null:null},s=this.adapter.getAllPlayers().map(a=>{const r=e.playerNameToCarActorId[a.name];return{id:a.id,name:a.name,team:a.team,carName:a.carName,hitboxType:a.hitboxType,position:a.position,rotation:a.rotation,velocity:a.velocity,boost:a.boost,isBoosting:a.isBoosting,visible:a.isVisible,object3d:r!=null?e.actors[r]??null:null}});return{...this.createPluginContext(),...this.computeFrameRenderInfo(),state:this.getState(),time:this.currentTime,ball:i,cars:s}}emitChange(){const e=this.getState(),t=this.createPluginStateContext(e);for(const i of this.plugins)i.plugin.onStateChange?.(t);this.dispatchEvent(new CustomEvent("change",{detail:e}))}}const Xt={LEFT:1,RIGHT:2,MIDDLE:4},$=Object.freeze({NONE:0,ROTATE:1,TRUCK:2,SCREEN_PAN:4,OFFSET:8,DOLLY:16,ZOOM:32,TOUCH_ROTATE:64,TOUCH_TRUCK:128,TOUCH_SCREEN_PAN:256,TOUCH_OFFSET:512,TOUCH_DOLLY:1024,TOUCH_ZOOM:2048,TOUCH_DOLLY_TRUCK:4096,TOUCH_DOLLY_SCREEN_PAN:8192,TOUCH_DOLLY_OFFSET:16384,TOUCH_DOLLY_ROTATE:32768,TOUCH_ZOOM_TRUCK:65536,TOUCH_ZOOM_OFFSET:131072,TOUCH_ZOOM_SCREEN_PAN:262144,TOUCH_ZOOM_ROTATE:524288}),Zr={NONE:0,IN:1,OUT:-1};function za(n){return n.isPerspectiveCamera}function ra(n){return n.isOrthographicCamera}const Jr=Math.PI*2,Vv=Math.PI/2,uM=1e-5,ml=Math.PI/180;function Gi(n,e,t){return Math.max(e,Math.min(t,n))}function Ft(n,e=uM){return Math.abs(n)0==f>u&&(f=u,t.value=(f-u)/a),f}function $v(n,e,t,i,s=1/0,a,r){i=Math.max(1e-4,i);const o=2/i,l=o*a,c=1/(1+l+.48*l*l+.235*l*l*l);let u=e.x,d=e.y,h=e.z,f=n.x-u,p=n.y-d,g=n.z-h;const _=u,m=d,v=h,y=s*i,b=y*y,S=f*f+p*p+g*g;if(S>b){const U=Math.sqrt(S);f=f/U*y,p=p/U*y,g=g/U*y}u=n.x-f,d=n.y-p,h=n.z-g;const x=(t.x+o*f)*a,M=(t.y+o*p)*a,C=(t.z+o*g)*a;t.x=(t.x-o*x)*c,t.y=(t.y-o*M)*c,t.z=(t.z-o*C)*c,r.x=u+(f+x)*c,r.y=d+(p+M)*c,r.z=h+(g+C)*c;const w=_-n.x,E=m-n.y,R=v-n.z,L=r.x-_,O=r.y-m,D=r.z-v;return w*L+E*O+R*D>0&&(r.x=_,r.y=m,r.z=v,t.x=(r.x-_)/a,t.y=(r.y-m)/a,t.z=(r.z-v)/a),r}function $p(n,e){e.set(0,0),n.forEach(t=>{e.x+=t.clientX,e.y+=t.clientY}),e.x/=n.length,e.y/=n.length}function Wp(n,e){return ra(n)?(console.warn(`${e} is not supported in OrthographicCamera`),!0):!1}class n3{constructor(){this._listeners={}}addEventListener(e,t){const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){const i=this._listeners;return i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){const s=this._listeners[e];if(s!==void 0){const a=s.indexOf(t);a!==-1&&s.splice(a,1)}}removeAllEventListeners(e){if(!e){this._listeners={};return}Array.isArray(this._listeners[e])&&(this._listeners[e].length=0)}dispatchEvent(e){const i=this._listeners[e.type];if(i!==void 0){e.target=this;const s=i.slice(0);for(let a=0,r=s.length;a{},this._enabled=!0,this._state=$.NONE,this._viewport=null,this._changedDolly=0,this._changedZoom=0,this._hasRested=!0,this._boundaryEnclosesCamera=!1,this._needsUpdate=!0,this._updatedLastTime=!1,this._elementRect=new DOMRect,this._isDragging=!1,this._dragNeedsUpdate=!0,this._activePointers=[],this._lockedPointer=null,this._interactiveArea=new DOMRect(0,0,1,1),this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._isUserControllingOffset=!1,this._isUserControllingZoom=!1,this._lastDollyDirection=Zr.NONE,this._thetaVelocity={value:0},this._phiVelocity={value:0},this._radiusVelocity={value:0},this._targetVelocity=new nt.Vector3,this._focalOffsetVelocity=new nt.Vector3,this._zoomVelocity={value:0},this._truckInternal=(m,v,y,b)=>{let S,x;if(za(this._camera)){const M=pt.copy(this._camera.position).sub(this._target),C=this._camera.getEffectiveFOV()*ml,w=M.length()*Math.tan(C*.5);S=this.truckSpeed*m*w/this._elementRect.height,x=this.truckSpeed*v*w/this._elementRect.height}else if(ra(this._camera)){const M=this._camera;S=this.truckSpeed*m*(M.right-M.left)/M.zoom/this._elementRect.width,x=this.truckSpeed*v*(M.top-M.bottom)/M.zoom/this._elementRect.height}else return;b?(y?this.setFocalOffset(this._focalOffsetEnd.x+S,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(S,0,!0),this.forward(-x,!0)):y?this.setFocalOffset(this._focalOffsetEnd.x+S,this._focalOffsetEnd.y+x,this._focalOffsetEnd.z,!0):this.truck(S,x,!0)},this._rotateInternal=(m,v)=>{const y=Jr*this.azimuthRotateSpeed*m/this._elementRect.height,b=Jr*this.polarRotateSpeed*v/this._elementRect.height;this.rotate(y,b,!0)},this._dollyInternal=(m,v,y)=>{const b=Math.pow(.95,-m*this.dollySpeed),S=this._sphericalEnd.radius,x=this._sphericalEnd.radius*b,M=Gi(x,this.minDistance,this.maxDistance),C=M-x;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(x,!0):this.infinityDolly&&!this.dollyToCursor?(this.dollyInFixed(C,!0),this._dollyToNoClamp(M,!0)):this._dollyToNoClamp(M,!0),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?x:M)-S,this._dollyControlCoord.set(v,y)),this._lastDollyDirection=Math.sign(-m)},this._zoomInternal=(m,v,y)=>{const b=Math.pow(.95,m*this.dollySpeed),S=this._zoom,x=this._zoom*b;this.zoomTo(x,!0),this.dollyToCursor&&(this._changedZoom+=x-S,this._dollyControlCoord.set(v,y))},typeof nt>"u"&&console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information."),this._camera=e,this._yAxisUpSpace=new nt.Quaternion().setFromUnitVectors(this._camera.up,Nu),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=$.NONE,this._target=new nt.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new nt.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=new nt.Spherical().setFromVector3(pt.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace)),this._sphericalEnd=this._spherical.clone(),this._lastDistance=this._spherical.radius,this._zoom=this._camera.zoom,this._zoomEnd=this._zoom,this._lastZoom=this._zoom,this._nearPlaneCorners=[new nt.Vector3,new nt.Vector3,new nt.Vector3,new nt.Vector3],this._updateNearPlaneCorners(),this._boundary=new nt.Box3(new nt.Vector3(-1/0,-1/0,-1/0),new nt.Vector3(1/0,1/0,1/0)),this._cameraUp0=this._camera.up.clone(),this._target0=this._target.clone(),this._position0=this._camera.position.clone(),this._zoom0=this._zoom,this._focalOffset0=this._focalOffset.clone(),this._dollyControlCoord=new nt.Vector2,this.mouseButtons={left:$.ROTATE,middle:$.DOLLY,right:$.TRUCK,wheel:za(this._camera)?$.DOLLY:ra(this._camera)?$.ZOOM:$.NONE},this.touches={one:$.TOUCH_ROTATE,two:za(this._camera)?$.TOUCH_DOLLY_TRUCK:ra(this._camera)?$.TOUCH_ZOOM_TRUCK:$.NONE,three:$.TOUCH_TRUCK};const i=new nt.Vector2,s=new nt.Vector2,a=new nt.Vector2,r=m=>{if(!this._enabled||!this._domElement)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const b=this._domElement.getBoundingClientRect(),S=m.clientX/b.width,x=m.clientY/b.height;if(Sthis._interactiveArea.right||xthis._interactiveArea.bottom)return}const v=m.pointerType!=="mouse"?null:(m.buttons&Xt.LEFT)===Xt.LEFT?Xt.LEFT:(m.buttons&Xt.MIDDLE)===Xt.MIDDLE?Xt.MIDDLE:(m.buttons&Xt.RIGHT)===Xt.RIGHT?Xt.RIGHT:null;if(v!==null){const b=this._findPointerByMouseButton(v);b&&this._disposePointer(b)}if((m.buttons&Xt.LEFT)===Xt.LEFT&&this._lockedPointer)return;const y={pointerId:m.pointerId,clientX:m.clientX,clientY:m.clientY,deltaX:0,deltaY:0,mouseButton:v};this._activePointers.push(y),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),this._isDragging=!0,h(m)},o=m=>{m.cancelable&&m.preventDefault();const v=m.pointerId,y=this._lockedPointer||this._findPointerById(v);if(y){if(y.clientX=m.clientX,y.clientY=m.clientY,y.deltaX=m.movementX,y.deltaY=m.movementY,this._state=0,m.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else(!this._isDragging&&this._lockedPointer||this._isDragging&&(m.buttons&Xt.LEFT)===Xt.LEFT)&&(this._state=this._state|this.mouseButtons.left),this._isDragging&&(m.buttons&Xt.MIDDLE)===Xt.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),this._isDragging&&(m.buttons&Xt.RIGHT)===Xt.RIGHT&&(this._state=this._state|this.mouseButtons.right);f()}},l=m=>{const v=this._findPointerById(m.pointerId);if(!(v&&v===this._lockedPointer)){if(v&&this._disposePointer(v),m.pointerType==="touch")switch(this._activePointers.length){case 0:this._state=$.NONE;break;case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else this._state=$.NONE;p()}};let c=-1;const u=m=>{if(!this._domElement||!this._enabled||this.mouseButtons.wheel===$.NONE)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const x=this._domElement.getBoundingClientRect(),M=m.clientX/x.width,C=m.clientY/x.height;if(Mthis._interactiveArea.right||Cthis._interactiveArea.bottom)return}if(m.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===$.ROTATE||this.mouseButtons.wheel===$.TRUCK){const x=performance.now();c-x<1e3&&this._getClientRect(this._elementRect),c=x}const v=s3?-1:-3,y=m.deltaMode===1||m.ctrlKey?m.deltaY/v:m.deltaY/(v*10),b=this.dollyToCursor?(m.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,S=this.dollyToCursor?(m.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case $.ROTATE:{this._rotateInternal(m.deltaX,m.deltaY),this._isUserControllingRotate=!0;break}case $.TRUCK:{this._truckInternal(m.deltaX,m.deltaY,!1,!1),this._isUserControllingTruck=!0;break}case $.SCREEN_PAN:{this._truckInternal(m.deltaX,m.deltaY,!1,!0),this._isUserControllingTruck=!0;break}case $.OFFSET:{this._truckInternal(m.deltaX,m.deltaY,!0,!1),this._isUserControllingOffset=!0;break}case $.DOLLY:{this._dollyInternal(-y,b,S),this._isUserControllingDolly=!0;break}case $.ZOOM:{this._zoomInternal(-y,b,S),this._isUserControllingZoom=!0;break}}this.dispatchEvent({type:"control"})},d=m=>{if(!(!this._domElement||!this._enabled)){if(this.mouseButtons.right===r_.ACTION.NONE){const v=m instanceof PointerEvent?m.pointerId:0,y=this._findPointerById(v);y&&this._disposePointer(y),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l);return}m.preventDefault()}},h=m=>{if(!this._enabled)return;if($p(this._activePointers,Zn),this._getClientRect(this._elementRect),i.copy(Zn),s.copy(Zn),this._activePointers.length>=2){const y=Zn.x-this._activePointers[1].clientX,b=Zn.y-this._activePointers[1].clientY,S=Math.sqrt(y*y+b*b);a.set(0,S);const x=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,M=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;s.set(x,M)}if(this._state=0,!m)this._lockedPointer&&(this._state=this._state|this.mouseButtons.left);else if("pointerType"in m&&m.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else!this._lockedPointer&&(m.buttons&Xt.LEFT)===Xt.LEFT&&(this._state=this._state|this.mouseButtons.left),(m.buttons&Xt.MIDDLE)===Xt.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),(m.buttons&Xt.RIGHT)===Xt.RIGHT&&(this._state=this._state|this.mouseButtons.right);((this._state&$.ROTATE)===$.ROTATE||(this._state&$.TOUCH_ROTATE)===$.TOUCH_ROTATE||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE)&&(this._sphericalEnd.theta=this._spherical.theta,this._sphericalEnd.phi=this._spherical.phi,this._thetaVelocity.value=0,this._phiVelocity.value=0),((this._state&$.TRUCK)===$.TRUCK||(this._state&$.SCREEN_PAN)===$.SCREEN_PAN||(this._state&$.TOUCH_TRUCK)===$.TOUCH_TRUCK||(this._state&$.TOUCH_SCREEN_PAN)===$.TOUCH_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN)&&(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),((this._state&$.DOLLY)===$.DOLLY||(this._state&$.TOUCH_DOLLY)===$.TOUCH_DOLLY||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE)&&(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),((this._state&$.ZOOM)===$.ZOOM||(this._state&$.TOUCH_ZOOM)===$.TOUCH_ZOOM||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_ZOOM_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE)&&(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),((this._state&$.OFFSET)===$.OFFSET||(this._state&$.TOUCH_OFFSET)===$.TOUCH_OFFSET||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET)&&(this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0)),this.dispatchEvent({type:"controlstart"})},f=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,$p(this._activePointers,Zn);const v=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,y=v?-v.deltaX:s.x-Zn.x,b=v?-v.deltaY:s.y-Zn.y;if(s.copy(Zn),((this._state&$.ROTATE)===$.ROTATE||(this._state&$.TOUCH_ROTATE)===$.TOUCH_ROTATE||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE)&&(this._rotateInternal(y,b),this._isUserControllingRotate=!0),(this._state&$.DOLLY)===$.DOLLY||(this._state&$.ZOOM)===$.ZOOM){const S=this.dollyToCursor?(i.x-this._elementRect.x)/this._elementRect.width*2-1:0,x=this.dollyToCursor?(i.y-this._elementRect.y)/this._elementRect.height*-2+1:0,M=this.dollyDragInverted?-1:1;(this._state&$.DOLLY)===$.DOLLY?(this._dollyInternal(M*b*Fu,S,x),this._isUserControllingDolly=!0):(this._zoomInternal(M*b*Fu,S,x),this._isUserControllingZoom=!0)}if((this._state&$.TOUCH_DOLLY)===$.TOUCH_DOLLY||(this._state&$.TOUCH_ZOOM)===$.TOUCH_ZOOM||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_ZOOM_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE){const S=Zn.x-this._activePointers[1].clientX,x=Zn.y-this._activePointers[1].clientY,M=Math.sqrt(S*S+x*x),C=a.y-M;a.set(0,M);const w=this.dollyToCursor?(s.x-this._elementRect.x)/this._elementRect.width*2-1:0,E=this.dollyToCursor?(s.y-this._elementRect.y)/this._elementRect.height*-2+1:0;(this._state&$.TOUCH_DOLLY)===$.TOUCH_DOLLY||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET?(this._dollyInternal(C*Fu,w,E),this._isUserControllingDolly=!0):(this._zoomInternal(C*Fu,w,E),this._isUserControllingZoom=!0)}((this._state&$.TRUCK)===$.TRUCK||(this._state&$.TOUCH_TRUCK)===$.TOUCH_TRUCK||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK)&&(this._truckInternal(y,b,!1,!1),this._isUserControllingTruck=!0),((this._state&$.SCREEN_PAN)===$.SCREEN_PAN||(this._state&$.TOUCH_SCREEN_PAN)===$.TOUCH_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_ZOOM_SCREEN_PAN)&&(this._truckInternal(y,b,!1,!0),this._isUserControllingTruck=!0),((this._state&$.OFFSET)===$.OFFSET||(this._state&$.TOUCH_OFFSET)===$.TOUCH_OFFSET||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET)&&(this._truckInternal(y,b,!0,!1),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},p=()=>{$p(this._activePointers,Zn),s.copy(Zn),this._dragNeedsUpdate=!1,(this._activePointers.length===0||this._activePointers.length===1&&this._activePointers[0]===this._lockedPointer)&&(this._isDragging=!1),this._activePointers.length===0&&this._domElement&&(this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this.dispatchEvent({type:"controlend"}))};this.lockPointer=()=>{!this._enabled||!this._domElement||(this.cancel(),this._lockedPointer={pointerId:-1,clientX:0,clientY:0,deltaX:0,deltaY:0,mouseButton:null},this._activePointers.push(this._lockedPointer),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.requestPointerLock(),this._domElement.ownerDocument.addEventListener("pointerlockchange",g),this._domElement.ownerDocument.addEventListener("pointerlockerror",_),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),h())},this.unlockPointer=()=>{var m,v,y;this._lockedPointer!==null&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),(m=this._domElement)===null||m===void 0||m.ownerDocument.exitPointerLock(),(v=this._domElement)===null||v===void 0||v.ownerDocument.removeEventListener("pointerlockchange",g),(y=this._domElement)===null||y===void 0||y.ownerDocument.removeEventListener("pointerlockerror",_),this.cancel()};const g=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},_=()=>{this.unlockPointer()};this._addAllEventListeners=m=>{this._domElement=m,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",r),this._domElement.addEventListener("pointercancel",l),this._domElement.addEventListener("wheel",u,{passive:!1}),this._domElement.addEventListener("contextmenu",d)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect="",this._domElement.removeEventListener("pointerdown",r),this._domElement.removeEventListener("pointercancel",l),this._domElement.removeEventListener("wheel",u,{passive:!1}),this._domElement.removeEventListener("contextmenu",d),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.removeEventListener("pointerlockchange",g),this._domElement.ownerDocument.removeEventListener("pointerlockerror",_))},this.cancel=()=>{this._state!==$.NONE&&(this._state=$.NONE,this._activePointers.length=0,p())},t&&this.connect(t),this.update(0)}get camera(){return this._camera}set camera(e){this._camera=e,this.updateCameraUp(),this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0}get enabled(){return this._enabled}set enabled(e){this._enabled=e,this._domElement&&(e?(this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none"):(this.cancel(),this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect=""))}get active(){return!this._hasRested}get currentAction(){return this._state}get distance(){return this._spherical.radius}set distance(e){this._spherical.radius===e&&this._sphericalEnd.radius===e||(this._spherical.radius=e,this._sphericalEnd.radius=e,this._needsUpdate=!0)}get azimuthAngle(){return this._spherical.theta}set azimuthAngle(e){this._spherical.theta===e&&this._sphericalEnd.theta===e||(this._spherical.theta=e,this._sphericalEnd.theta=e,this._needsUpdate=!0)}get polarAngle(){return this._spherical.phi}set polarAngle(e){this._spherical.phi===e&&this._sphericalEnd.phi===e||(this._spherical.phi=e,this._sphericalEnd.phi=e,this._needsUpdate=!0)}get boundaryEnclosesCamera(){return this._boundaryEnclosesCamera}set boundaryEnclosesCamera(e){this._boundaryEnclosesCamera=e,this._needsUpdate=!0}set interactiveArea(e){this._interactiveArea.width=Gi(e.width,0,1),this._interactiveArea.height=Gi(e.height,0,1),this._interactiveArea.x=Gi(e.x,0,1-this._interactiveArea.width),this._interactiveArea.y=Gi(e.y,0,1-this._interactiveArea.height)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}rotate(e,t,i=!1){return this.rotateTo(this._sphericalEnd.theta+e,this._sphericalEnd.phi+t,i)}rotateAzimuthTo(e,t=!1){return this.rotateTo(e,this._sphericalEnd.phi,t)}rotatePolarTo(e,t=!1){return this.rotateTo(this._sphericalEnd.theta,e,t)}rotateTo(e,t,i=!1){this._isUserControllingRotate=!1;const s=Gi(e,this.minAzimuthAngle,this.maxAzimuthAngle),a=Gi(t,this.minPolarAngle,this.maxPolarAngle);this._sphericalEnd.theta=s,this._sphericalEnd.phi=a,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,i||(this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi);const r=!i||Rt(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Rt(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(r)}dolly(e,t=!1){return this.dollyTo(this._sphericalEnd.radius-e,t)}dollyTo(e,t=!1){return this._isUserControllingDolly=!1,this._lastDollyDirection=Zr.NONE,this._changedDolly=0,this._dollyToNoClamp(Gi(e,this.minDistance,this.maxDistance),t)}_dollyToNoClamp(e,t=!1){const i=this._sphericalEnd.radius;if(this.colliderMeshes.length>=1){const r=this._collisionTest(),o=Rt(r,this._spherical.radius);if(!(i>e)&&o)return Promise.resolve();this._sphericalEnd.radius=Math.min(e,r)}else this._sphericalEnd.radius=e;this._needsUpdate=!0,t||(this._spherical.radius=this._sphericalEnd.radius);const a=!t||Rt(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(a)}dollyInFixed(e,t=!1){this._targetEnd.add(this._getCameraDirection(yl).multiplyScalar(e)),t||this._target.copy(this._targetEnd);const i=!t||Rt(this._target.x,this._targetEnd.x,this.restThreshold)&&Rt(this._target.y,this._targetEnd.y,this.restThreshold)&&Rt(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(i)}zoom(e,t=!1){return this.zoomTo(this._zoomEnd+e,t)}zoomTo(e,t=!1){this._isUserControllingZoom=!1,this._zoomEnd=Gi(e,this.minZoom,this.maxZoom),this._needsUpdate=!0,t||(this._zoom=this._zoomEnd);const i=!t||Rt(this._zoom,this._zoomEnd,this.restThreshold);return this._changedZoom=0,this._createOnRestPromise(i)}pan(e,t,i=!1){return console.warn("`pan` has been renamed to `truck`"),this.truck(e,t,i)}truck(e,t,i=!1){this._camera.updateMatrix(),os.setFromMatrixColumn(this._camera.matrix,0),ls.setFromMatrixColumn(this._camera.matrix,1),os.multiplyScalar(e),ls.multiplyScalar(-t);const s=pt.copy(os).add(ls),a=Mt.copy(this._targetEnd).add(s);return this.moveTo(a.x,a.y,a.z,i)}forward(e,t=!1){pt.setFromMatrixColumn(this._camera.matrix,0),pt.crossVectors(this._camera.up,pt),pt.multiplyScalar(e);const i=Mt.copy(this._targetEnd).add(pt);return this.moveTo(i.x,i.y,i.z,t)}elevate(e,t=!1){return pt.copy(this._camera.up).multiplyScalar(e),this.moveTo(this._targetEnd.x+pt.x,this._targetEnd.y+pt.y,this._targetEnd.z+pt.z,t)}moveTo(e,t,i,s=!1){this._isUserControllingTruck=!1;const a=pt.set(e,t,i).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,a,this.boundaryFriction),this._needsUpdate=!0,s||this._target.copy(this._targetEnd);const r=!s||Rt(this._target.x,this._targetEnd.x,this.restThreshold)&&Rt(this._target.y,this._targetEnd.y,this.restThreshold)&&Rt(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(r)}lookInDirectionOf(e,t,i,s=!1){const o=pt.set(e,t,i).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd);return this.setPosition(o.x,o.y,o.z,s)}fitToBox(e,t,{cover:i=!1,paddingLeft:s=0,paddingRight:a=0,paddingBottom:r=0,paddingTop:o=0}={}){const l=[],c=e.isBox3?eo.copy(e):eo.setFromObject(e);c.isEmpty()&&(console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve());const u=Gv(this._sphericalEnd.theta,Vv),d=Gv(this._sphericalEnd.phi,Vv);l.push(this.rotateTo(u,d,t));const h=pt.setFromSpherical(this._sphericalEnd).normalize(),f=Yv.setFromUnitVectors(h,Kp),p=Rt(Math.abs(h.y),1);p&&f.multiply(Yp.setFromAxisAngle(Nu,u)),f.multiply(this._yAxisUpSpaceInverse);const g=qv.makeEmpty();Mt.copy(c.min).applyQuaternion(f),g.expandByPoint(Mt),Mt.copy(c.min).setX(c.max.x).applyQuaternion(f),g.expandByPoint(Mt),Mt.copy(c.min).setY(c.max.y).applyQuaternion(f),g.expandByPoint(Mt),Mt.copy(c.max).setZ(c.min.z).applyQuaternion(f),g.expandByPoint(Mt),Mt.copy(c.min).setZ(c.max.z).applyQuaternion(f),g.expandByPoint(Mt),Mt.copy(c.max).setY(c.min.y).applyQuaternion(f),g.expandByPoint(Mt),Mt.copy(c.max).setX(c.min.x).applyQuaternion(f),g.expandByPoint(Mt),Mt.copy(c.max).applyQuaternion(f),g.expandByPoint(Mt),g.min.x-=s,g.min.y-=r,g.max.x+=a,g.max.y+=o,f.setFromUnitVectors(Kp,h),p&&f.premultiply(Yp.invert()),f.premultiply(this._yAxisUpSpace);const _=g.getSize(pt),m=g.getCenter(Mt).applyQuaternion(f);if(za(this._camera)){const v=this.getDistanceToFitBox(_.x,_.y,_.z,i);l.push(this.moveTo(m.x,m.y,m.z,t)),l.push(this.dollyTo(v,t)),l.push(this.setFocalOffset(0,0,0,t))}else if(ra(this._camera)){const v=this._camera,y=v.right-v.left,b=v.top-v.bottom,S=i?Math.max(y/_.x,b/_.y):Math.min(y/_.x,b/_.y);l.push(this.moveTo(m.x,m.y,m.z,t)),l.push(this.zoomTo(S,t)),l.push(this.setFocalOffset(0,0,0,t))}return Promise.all(l)}fitToSphere(e,t){const i=[],a="isObject3D"in e?r_.createBoundingSphere(e,qp):qp.copy(e);if(i.push(this.moveTo(a.center.x,a.center.y,a.center.z,t)),za(this._camera)){const r=this.getDistanceToFitSphere(a.radius);i.push(this.dollyTo(r,t))}else if(ra(this._camera)){const r=this._camera.right-this._camera.left,o=this._camera.top-this._camera.bottom,l=2*a.radius,c=Math.min(r/l,o/l);i.push(this.zoomTo(c,t))}return i.push(this.setFocalOffset(0,0,0,t)),Promise.all(i)}setLookAt(e,t,i,s,a,r,o=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Zr.NONE,this._changedDolly=0;const l=Mt.set(s,a,r),c=pt.set(e,t,i);this._targetEnd.copy(l),this._sphericalEnd.setFromVector3(c.sub(l).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,o||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const u=!o||Rt(this._target.x,this._targetEnd.x,this.restThreshold)&&Rt(this._target.y,this._targetEnd.y,this.restThreshold)&&Rt(this._target.z,this._targetEnd.z,this.restThreshold)&&Rt(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Rt(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Rt(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(u)}lerpLookAt(e,t,i,s,a,r,o,l,c,u,d,h,f,p=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Zr.NONE,this._changedDolly=0;const g=pt.set(s,a,r),_=Mt.set(e,t,i);Mi.setFromVector3(_.sub(g).applyQuaternion(this._yAxisUpSpace));const m=Qr.set(u,d,h),v=Mt.set(o,l,c);vl.setFromVector3(v.sub(m).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(g.lerp(m,f));const y=vl.theta-Mi.theta,b=vl.phi-Mi.phi,S=vl.radius-Mi.radius;this._sphericalEnd.set(Mi.radius+S*f,Mi.phi+b*f,Mi.theta+y*f),this.normalizeRotations(),this._needsUpdate=!0,p||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const x=!p||Rt(this._target.x,this._targetEnd.x,this.restThreshold)&&Rt(this._target.y,this._targetEnd.y,this.restThreshold)&&Rt(this._target.z,this._targetEnd.z,this.restThreshold)&&Rt(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Rt(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Rt(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(x)}setPosition(e,t,i,s=!1){return this.setLookAt(e,t,i,this._targetEnd.x,this._targetEnd.y,this._targetEnd.z,s)}setTarget(e,t,i,s=!1){const a=this.getPosition(pt),r=this.setLookAt(a.x,a.y,a.z,e,t,i,s);return this._sphericalEnd.phi=Gi(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),r}setFocalOffset(e,t,i,s=!1){this._isUserControllingOffset=!1,this._focalOffsetEnd.set(e,t,i),this._needsUpdate=!0,s||this._focalOffset.copy(this._focalOffsetEnd);const a=!s||Rt(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&Rt(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&Rt(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(a)}setOrbitPoint(e,t,i){this._camera.updateMatrixWorld(),os.setFromMatrixColumn(this._camera.matrixWorldInverse,0),ls.setFromMatrixColumn(this._camera.matrixWorldInverse,1),Ha.setFromMatrixColumn(this._camera.matrixWorldInverse,2);const s=pt.set(e,t,i),a=s.distanceTo(this._camera.position),r=s.sub(this._camera.position);os.multiplyScalar(r.x),ls.multiplyScalar(r.y),Ha.multiplyScalar(r.z),pt.copy(os).add(ls).add(Ha),pt.z=pt.z+a,this.dollyTo(a,!1),this.setFocalOffset(-pt.x,pt.y,-pt.z,!1),this.moveTo(e,t,i,!1)}setBoundary(e){if(!e){this._boundary.min.set(-1/0,-1/0,-1/0),this._boundary.max.set(1/0,1/0,1/0),this._needsUpdate=!0;return}this._boundary.copy(e),this._boundary.clampPoint(this._targetEnd,this._targetEnd),this._needsUpdate=!0}setViewport(e,t,i,s){if(e===null){this._viewport=null;return}this._viewport=this._viewport||new nt.Vector4,typeof e=="number"?this._viewport.set(e,t,i,s):this._viewport.copy(e)}getDistanceToFitBox(e,t,i,s=!1){if(Wp(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const a=e/t,r=this._camera.getEffectiveFOV()*ml,o=this._camera.aspect;return((s?a>o:at.pointerId===e)}_findPointerByMouseButton(e){return this._activePointers.find(t=>t.mouseButton===e)}_disposePointer(e){this._activePointers.splice(this._activePointers.indexOf(e),1)}_encloseToBoundary(e,t,i){const s=t.lengthSq();if(s===0)return e;const a=Mt.copy(t).add(e),o=this._boundary.clampPoint(a,Qr).sub(a),l=o.lengthSq();if(l===0)return e.add(t);if(l===s)return e;if(i===0)return e.add(t).add(o);{const c=1+i*l/t.dot(o);return e.add(Mt.copy(t).multiplyScalar(c)).add(o.multiplyScalar(1-i))}}_updateNearPlaneCorners(){if(za(this._camera)){const e=this._camera,t=e.near,i=e.getEffectiveFOV()*ml,s=Math.tan(i*.5)*t,a=s*e.aspect;this._nearPlaneCorners[0].set(-a,-s,0),this._nearPlaneCorners[1].set(a,-s,0),this._nearPlaneCorners[2].set(a,s,0),this._nearPlaneCorners[3].set(-a,s,0)}else if(ra(this._camera)){const e=this._camera,t=1/e.zoom,i=e.left*t,s=e.right*t,a=e.top*t,r=e.bottom*t;this._nearPlaneCorners[0].set(i,a,0),this._nearPlaneCorners[1].set(s,a,0),this._nearPlaneCorners[2].set(s,r,0),this._nearPlaneCorners[3].set(i,r,0)}}_collisionTest(){let e=1/0;if(!(this.colliderMeshes.length>=1)||Wp(this._camera,"_collisionTest"))return e;const i=this._getTargetDirection(yl);jp.lookAt(Wv,i,this._camera.up);for(let s=0;s<4;s++){const a=Mt.copy(this._nearPlaneCorners[s]);a.applyMatrix4(jp);const r=Qr.addVectors(this._target,a);Uu.set(r,i),Uu.far=this._spherical.radius+1;const o=Uu.intersectObjects(this.colliderMeshes);o.length!==0&&o[0].distance{const i=()=>{this.removeEventListener("rest",i),t()};this.addEventListener("rest",i)}))}_addAllEventListeners(e){}_removeAllEventListeners(){}get dampingFactor(){return console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead."),0}set dampingFactor(e){console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead.")}get draggingDampingFactor(){return console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead."),0}set draggingDampingFactor(e){console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead.")}static createBoundingSphere(e,t=new nt.Sphere){const i=t,s=i.center;eo.makeEmpty(),e.traverseVisible(r=>{r.isMesh&&eo.expandByObject(r)}),eo.getCenter(s);let a=0;return e.traverseVisible(r=>{if(!r.isMesh)return;const o=r;if(!o.geometry)return;const l=o.geometry.clone();l.applyMatrix4(o.matrixWorld);const u=l.attributes.position;for(let d=0,h=u.count;di.preventDefault()),this.isFollowingViewer=!1,this.followTargetPosition=new T,this.followTargetQuaternion=new ht,this.followPositionLerpFactor=.12,this.followRotationSlerpFactor=.1,this.hasFollowTarget=!1,this.isRightMouseDown=!1,this.lastMouseX=null,this.lastMouseY=null,this.savedCameraState=null,this.isInReplayMode=!1}setMode(e){if(this.mode=e,e==="ballOrbit"){if(this.controls.enabled=!0,this.lastBallOrbitPos=null,this.ballOrbitScrollHandler||(this.ballOrbitScrollHandler=t=>{if(this.mode==="ballOrbit"&&!this.isFollowingViewer){t.preventDefault();const i=Math.max(this.controls.distance*.2,100);t.deltaY>0?this.controls.dolly(-i,!0):this.controls.dolly(i,!0)}},this.domElement.addEventListener("wheel",this.ballOrbitScrollHandler,{passive:!1})),this.targetBall){const t=this.targetBall.position;this.camera.position.distanceTo(t),this.controls.setLookAt(this.camera.position.x,this.camera.position.y,this.camera.position.z,t.x,t.y,t.z,!1)}return}if(e==="free"){if(this.controls.enabled=!1,!this.freeCamKeys){this.freeCamKeys={forward:!1,backward:!1,left:!1,right:!1,up:!1,down:!1},this.freeCamSpeed=2e3,this.freeCamRotation={yaw:0,pitch:0};const t=new T;this.camera.getWorldDirection(t),this.freeCamRotation.yaw=Math.atan2(t.x,t.z),this.freeCamRotation.pitch=Math.asin(-t.y),this.onKeyDown=i=>this.handleFreeCamKeyDown(i),this.onKeyUp=i=>this.handleFreeCamKeyUp(i),this.onMouseMove=i=>this.handleFreeCamMouseMove(i),this.onMouseDown=i=>{i.button===2&&this.mode==="free"&&!this.isFollowingViewer&&(this.isRightMouseDown=!0,this.domElement.requestPointerLock?.())},this.onMouseUp=i=>{i.button===2&&(this.isRightMouseDown=!1,document.pointerLockElement===this.domElement&&document.exitPointerLock?.())},this.onPointerLockChange=()=>{document.pointerLockElement!==this.domElement&&(this.isRightMouseDown=!1)},this.onMouseLeave=()=>{document.pointerLockElement!==this.domElement&&(this.isRightMouseDown=!1)},this.onWindowBlur=()=>{this.isRightMouseDown=!1,document.pointerLockElement===this.domElement&&document.exitPointerLock?.(),this.freeCamKeys&&(this.freeCamKeys.forward=!1,this.freeCamKeys.backward=!1,this.freeCamKeys.left=!1,this.freeCamKeys.right=!1,this.freeCamKeys.up=!1,this.freeCamKeys.down=!1)},this.onVisibilityChange=()=>{document.hidden&&(this.isRightMouseDown=!1,document.pointerLockElement===this.domElement&&document.exitPointerLock?.(),this.freeCamKeys&&(this.freeCamKeys.forward=!1,this.freeCamKeys.backward=!1,this.freeCamKeys.left=!1,this.freeCamKeys.right=!1,this.freeCamKeys.up=!1,this.freeCamKeys.down=!1))},document.addEventListener("keydown",this.onKeyDown),document.addEventListener("keyup",this.onKeyUp),document.addEventListener("mousemove",this.onMouseMove),this.domElement.addEventListener("mousedown",this.onMouseDown),document.addEventListener("mouseup",this.onMouseUp),document.addEventListener("pointerlockchange",this.onPointerLockChange),this.domElement.addEventListener("mouseleave",this.onMouseLeave),window.addEventListener("blur",this.onWindowBlur),document.addEventListener("visibilitychange",this.onVisibilityChange)}this.isRightMouseDown=!1}else this.controls.enabled=!1,this.lastIsBallCam=null,this.currentBlend=0,this.targetBlend=0}setTargetCar(e){if(this.targetCar!==e&&(this.currentBallCamAngle=null,this.targetCar&&e)){this.targetHandoff={elapsed:0,duration:a3,startPosition:this.camera.position.clone(),startQuaternion:this.camera.quaternion.clone()};const t=new T().subVectors(this.camera.position,e.position);t.y=0,t.length()>.01&&(t.normalize(),this.smoothedCarYaw=Math.atan2(-t.x,-t.z)),this.lastCarPos&&this.lastCarPos.copy(e.position)}this.targetCar=e}setTargetBall(e){this.targetBall=e}handleFreeCamKeyDown(e){if(this.mode!=="free"||this.isFollowingViewer)return;const t=e.target;if(!(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable))switch(e.code){case"KeyW":case"ArrowUp":this.freeCamKeys.forward=!0;break;case"KeyS":case"ArrowDown":this.freeCamKeys.backward=!0;break;case"KeyA":case"ArrowLeft":this.freeCamKeys.left=!0;break;case"KeyD":case"ArrowRight":this.freeCamKeys.right=!0;break;case"Space":this.freeCamKeys.up=!0;break;case"ShiftLeft":case"ShiftRight":this.freeCamKeys.down=!0;break}}handleFreeCamKeyUp(e){switch(e.code){case"KeyW":case"ArrowUp":this.freeCamKeys.forward=!1;break;case"KeyS":case"ArrowDown":this.freeCamKeys.backward=!1;break;case"KeyA":case"ArrowLeft":this.freeCamKeys.left=!1;break;case"KeyD":case"ArrowRight":this.freeCamKeys.right=!1;break;case"Space":this.freeCamKeys.up=!1;break;case"ShiftLeft":case"ShiftRight":this.freeCamKeys.down=!1;break}}handleFreeCamMouseMove(e){if(this.mode!=="free"||!this.isRightMouseDown||this.isFollowingViewer)return;const t=e.movementX||0,i=e.movementY||0,s=.003;this.freeCamRotation.yaw-=t*s,this.freeCamRotation.pitch+=i*s,this.freeCamRotation.pitch=Math.max(-Math.PI/2+.01,Math.min(Math.PI/2-.01,this.freeCamRotation.pitch))}updateFreeCam(e){if(!this.freeCamKeys)return;const t=new T(Math.sin(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch),-Math.sin(this.freeCamRotation.pitch),Math.cos(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch));t.normalize();const i=new T(Math.sin(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch),-Math.sin(this.freeCamRotation.pitch),Math.cos(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch));i.normalize();const s=new T(Math.sin(this.freeCamRotation.yaw-Math.PI/2),0,Math.cos(this.freeCamRotation.yaw-Math.PI/2)),a=new T(0,1,0),r=new T,o=this.freeCamSpeed*e;this.freeCamKeys.forward&&r.add(i.clone().multiplyScalar(o)),this.freeCamKeys.backward&&r.add(i.clone().multiplyScalar(-o)),this.freeCamKeys.right&&r.add(s.clone().multiplyScalar(o)),this.freeCamKeys.left&&r.add(s.clone().multiplyScalar(-o)),this.freeCamKeys.up&&r.add(a.clone().multiplyScalar(o)),this.freeCamKeys.down&&r.add(a.clone().multiplyScalar(-o)),r.length()>0&&r.normalize().multiplyScalar(o),this.camera.position.add(r);const l=this.camera.position.clone().add(t);this.camera.lookAt(l),this.controls.setLookAt(this.camera.position.x,this.camera.position.y,this.camera.position.z,l.x,l.y,l.z,!1)}update(e,t=!0){if(this.isFollowingViewer){this.updateFollowInterpolation(e);return}if(this.mode==="free"){this.updateFreeCam(e),this.controls.update(e);return}if(this.mode==="ballOrbit"){if(this.targetBall){const p=this.targetBall.position;this.lastBallOrbitPos||(this.lastBallOrbitPos=p.clone());const g=new T().subVectors(p,this.lastBallOrbitPos);if(this.controls.setTarget(p.x,p.y,p.z,!1),g.lengthSq()>.01){const _=new T;this.controls.getPosition(_);const m=_.x+g.x,v=_.y+g.y,y=_.z+g.z;this.controls.setPosition(m,v,y,!1),this.lastBallOrbitPos.copy(p)}}this.controls.update(e);return}if(!this.targetCar){this.controls.update(e);return}const i=this.targetCar.position.clone(),s=this.targetCar.quaternion;if(this.lastIsBallCam!==null&&this.lastIsBallCam!==t&&!t){const p=new T().subVectors(this.camera.position,i);p.y=0,p.length()>.01&&(p.normalize(),this.smoothedCarYaw=Math.atan2(-p.x,-p.z))}this.lastIsBallCam=t;const a=this.calculateCarCamPosition(i,s,e),r=this.calculateBallCamPosition(i,s,e);this.targetBlend=t?1:0;const o=Math.max(.15,Math.min(.6,this.baseDuration/this.transitionSpeed)),l=e/o;this.currentBlendthis.targetBlend&&(this.currentBlend=Math.max(this.currentBlend-l,this.targetBlend));const c=this.currentBlend,u=c*c*(3-2*c),d=new T().lerpVectors(a.cameraPos,r.cameraPos,u);this._tempMatrix.lookAt(a.cameraPos,a.lookTarget,new T(0,1,0)),this._tempQuatCarCam.setFromRotationMatrix(this._tempMatrix),this._tempMatrix.lookAt(r.cameraPos,r.lookTarget,new T(0,1,0)),this._tempQuatBallCam.setFromRotationMatrix(this._tempMatrix),this._tempQuatCarCam.dot(this._tempQuatBallCam)<0&&this._tempQuatBallCam.set(-this._tempQuatBallCam.x,-this._tempQuatBallCam.y,-this._tempQuatBallCam.z,-this._tempQuatBallCam.w);const h=new ht().slerpQuaternions(this._tempQuatCarCam,this._tempQuatBallCam,u);if(this.targetHandoff){this.targetHandoff.elapsed+=e;const p=Math.min(1,this.targetHandoff.elapsed/this.targetHandoff.duration),g=p*p*(3-2*p),_=d.clone(),m=h.clone();d.lerpVectors(this.targetHandoff.startPosition,_,g),h.slerpQuaternions(this.targetHandoff.startQuaternion,m,g),p>=1&&(this.targetHandoff=null)}if(this.camera.position.copy(d),this.camera.quaternion.copy(h),this.followAngle!==0){const p=this.followAngle*Math.PI/180;this.camera.rotateX(-p)}this.currentCamPos||(this.currentCamPos=new T),this.currentLookTarget||(this.currentLookTarget=new T),this.currentCamPos.copy(d);const f=new T(0,0,-1).applyQuaternion(this.camera.quaternion);this.currentLookTarget.copy(d).add(f.multiplyScalar(100)),this.enforceMinHeight()}calculateBallCamPosition(e,t,i=1/60){if(!this.targetBall)return this.calculateCarCamPosition(e,t,i);const s=this.targetBall.position.clone(),a=new T().subVectors(e,s);a.y=0,a.normalize();const r=e.clone().add(a.multiplyScalar(this.followDistance)),o=s.y-e.y,c=Math.min(1,Math.max(0,o/800));r.y=e.y+this.followHeight-c*100,r.y.01)s.normalize(),u=Math.atan2(s.x,s.z);else if(a>.05){s.normalize();let y=Math.atan2(s.x,s.z)-o;for(;y>Math.PI;)y-=Math.PI*2;for(;y<-Math.PI;)y+=Math.PI*2;Math.abs(y)>Math.PI/2?u=o+Math.PI:u=o}else u=o;this.lastCarPos.copy(e),this.smoothedCarYaw===void 0&&(this.smoothedCarYaw=u);let d=u-this.smoothedCarYaw;for(;d>Math.PI;)d-=Math.PI*2;for(;d<-Math.PI;)d+=Math.PI*2;const h=c?this.swivelSpeed*.4:this.swivelSpeed;this.smoothedCarYaw+=d*Math.min(1,h*(1/60));const f=-Math.sin(this.smoothedCarYaw),p=-Math.cos(this.smoothedCarYaw),g=new T(e.x+f*this.followDistance,e.y+this.followHeight,e.z+p*this.followDistance);g.yMath.PI;)s-=Math.PI*2;for(;s<-Math.PI;)s+=Math.PI*2;this.followCurrentOrbitParams.azimuth+=s*.15,this.followCurrentOrbitParams.polar+=(this.followTargetOrbitParams.polar-this.followCurrentOrbitParams.polar)*.15,this.controls.setTarget(t.x,t.y,t.z,!1),this.controls.dollyTo(this.followCurrentOrbitParams.distance,!1),this.controls.rotateTo(this.followCurrentOrbitParams.azimuth,this.followCurrentOrbitParams.polar,!1),this.controls.update(e)}}else{if(this.camera.position.lerp(this.followTargetPosition,this.followPositionLerpFactor),this.camera.quaternion.slerp(this.followTargetQuaternion,this.followRotationSlerpFactor),this.freeCamRotation){const i=new T;this.camera.getWorldDirection(i),this.freeCamRotation.yaw=Math.atan2(i.x,i.z),this.freeCamRotation.pitch=Math.asin(-i.y)}const t=new T;this.camera.getWorldDirection(t),t.multiplyScalar(100).add(this.camera.position),this.controls.setLookAt(this.camera.position.x,this.camera.position.y,this.camera.position.z,t.x,t.y,t.z,!1)}}setDefaultFreecamPosition(){if(this.camera.position.copy(this.defaultFreecamPosition),this.camera.lookAt(this.defaultFreecamLookAt),this.freeCamRotation){const e=new T;this.camera.getWorldDirection(e),this.freeCamRotation.yaw=Math.atan2(e.x,e.z),this.freeCamRotation.pitch=Math.asin(-e.y)}this.controls.setLookAt(this.defaultFreecamPosition.x,this.defaultFreecamPosition.y,this.defaultFreecamPosition.z,this.defaultFreecamLookAt.x,this.defaultFreecamLookAt.y,this.defaultFreecamLookAt.z,!1)}getIsPointerLocked(){return this.isPointerLocked||!1}setPointerLockCallback(e){this.onPointerLockStateChange=e}dispose(){this.controls.dispose(),this.ballOrbitScrollHandler&&this.domElement.removeEventListener("wheel",this.ballOrbitScrollHandler),this.onKeyDown&&document.removeEventListener("keydown",this.onKeyDown),this.onKeyUp&&document.removeEventListener("keyup",this.onKeyUp),this.onMouseMove&&document.removeEventListener("mousemove",this.onMouseMove),this.onMouseDown&&this.domElement.removeEventListener("mousedown",this.onMouseDown),this.onMouseUp&&document.removeEventListener("mouseup",this.onMouseUp),this.onPointerLockChange&&document.removeEventListener("pointerlockchange",this.onPointerLockChange),this.onMouseLeave&&this.domElement.removeEventListener("mouseleave",this.onMouseLeave),this.onWindowBlur&&window.removeEventListener("blur",this.onWindowBlur),this.onVisibilityChange&&document.removeEventListener("visibilitychange",this.onVisibilityChange)}}function Zv(n){if(n.pitch===void 0||n.angle!==void 0)return n;const{pitch:e,...t}=n;return{...t,angle:e}}const o3={distance:260,height:90,angle:-4,stiffness:.45,swivelSpeed:4.3,transitionSpeed:1.3,fov:110};function l3(n={}){let e=null,t=null,i=n.mode??(n.follow?"follow":"orbit"),s=n.follow??null,a=n.ballCam??null,r=a??!0,o=Zv({...n.settings}),l=1;const c=n.useRecordedSettings!==!1;let u=null;const d=new T;let h=!1;function f(){if(!(!t||!e)){if(t.player.controls.enabled=i==="orbit",i==="free")e.setMode("free");else if(i==="ballOrbit"){const y=_();y&&e.setTargetBall(y),e.setMode("ballOrbit")}else e.setMode("car");u=null}}function p(){return!c||!t||!s?null:t.player.adapter.getPlayer(s)?.cameraSettings??null}function g(){const y={...o3,...p(),...o};return l!==1&&y.distance!==void 0&&(y.distance*=l),y}function _(){if(!t)return null;const y=t.player.actorManager;return y.ballActorId!=null?y.actors[y.ballActorId]??null:null}function m(y){const b=g().fov;if(!b)return;const S=b*Math.PI/180,x=16/9,M=2*Math.atan(Math.tan(S/2)/x),C=2*Math.atan(Math.tan(S/2)/y.aspect),w=Math.max(M,C)*180/Math.PI;Math.abs(y.fov-w)>.1&&(y.fov=w,y.updateProjectionMatrix())}function v(y,b){if(!e)return;if(i==="free"){o.freeCamSpeed&&(e.freeCamSpeed=o.freeCamSpeed),e.update(b);return}if(i==="ballOrbit"){y.ball.object3d&&e.setTargetBall(y.ball.object3d),e.update(b);return}const x=(s?y.cars.find(C=>C.name===s):void 0)?.object3d??null;if(!x){e.update(b);return}e.setTargetCar(x),y.ball.object3d&&e.setTargetBall(y.ball.object3d),e.setFollowSettings(g());const M=s?y.player.adapter.getPlayer(s):void 0;r=a??M?.isBallCam??!0,d.copy(x.position),h=!0,e.update(b,r)}return{id:"camera",setup(y){t=y,e=new r3(y.camera,y.renderer.domElement),f()},beforeRender(y){if(!e||(m(y.camera),i==="orbit"))return;const b=performance.now(),S=u===null?1/60:Math.min(.1,(b-u)/1e3);u=b,v(y,S)},teardown(){i="orbit",t&&(t.player.controls.enabled=!0),e?.dispose(),e=null,t=null},setMode(y){y!==i&&(i=y,f())},getMode(){return i},follow(y){s=y,i="follow",f()},release(){i="orbit",t&&h&&t.player.controls.target.copy(d),f()},getTarget(){return s},setBallCam(y){a=y,y!==null&&(r=y)},getBallCam(){return r},setCameraSettings(y){o=y===null?{}:{...o,...Zv(y)}},setDistanceScale(y){l=Math.max(.25,y)},getDistanceScale(){return l},getCameraSettings(){return g()},getRecordedSettings(){const y=p();return y?{...y}:null}}}const c3={"top-left":"top: 8px; left: 8px;","top-right":"top: 8px; right: 8px;","bottom-left":"bottom: 8px; left: 8px;","bottom-right":"bottom: 8px; right: 8px;"};function u3(n={}){const e=n.corner??"top-right",t=n.updateIntervalMs??500,i=()=>typeof n.mount=="function"?n.mount():n.mount??null;let s=null,a=null,r=null,o=0,l=performance.now(),c=0,u=0;const d=typeof n.onSample=="function";return{id:"fps-overlay",setup(h){if(l=performance.now(),o=0,u=h.player.getState().frameIndex,c=u,d)return;const f=i(),p=f!=null;s=document.createElement("div"),s.className="player-fps-overlay",s.style.cssText=p?` + `,transparent:!0,depthWrite:!1,blending:Vt});this.points=new fr(t,o),this.points.frustumCulled=!1,this.nextParticleIndex=0}setActive(e){this.active=e}emit(e,t,i,s=1){if(!this.active)return;const a=Math.floor(Math.random()*3)+3,r=Math.max(1,Math.round(a*s));for(let o=0;o=o.maxLife){o.active=!1,i[r]=0,s[r]=0;continue}t[r*3]+=o.velocity.x*e,t[r*3+1]+=o.velocity.y*e,t[r*3+2]+=o.velocity.z*e;const l=o.life/o.maxLife;i[r]=Math.pow(1-l,.5);const c=o.initialSize||3;s[r]=c*(1-l*.7),a[r*3]=1,a[r*3+1]=Math.max(.2,.9-l*.7),a[r*3+2]=Math.max(0,.4-l*.4),o.velocity.y+=20*e}this.geometry.attributes.position.needsUpdate=!0,this.geometry.attributes.alpha.needsUpdate=!0,this.geometry.attributes.size.needsUpdate=!0,this.geometry.attributes.color.needsUpdate=!0}addToScene(e){e.add(this.points)}removeFromScene(e){e.remove(this.points)}dispose(){this.geometry.dispose(),this.points.material.dispose()}}class xN{constructor(e,t,i,s){this.scene=e,this.team=t,this.trailWidth=i,this.trailLength=s,this.active=!0,this.dying=!1,this.deathTime=0,this.maxDeathTime=1.5,this.teamColors={0:new Ye(.3,.6,1,.9),1:new Ye(1,.5,.15,.9)},this.leftTarget=new et,this.rightTarget=new et,e.add(this.leftTarget),e.add(this.rightTarget),this.leftTrail=this.createTrail(this.leftTarget),this.rightTrail=this.createTrail(this.rightTarget),this.updateColors(),this.leftTrail.activate(),this.rightTrail.activate()}createTrail(e){const t=new mt(this.scene,!1),i=mt.createBaseMaterial();i.blending=Vt,i.depthWrite=!1,i.side=ut;const s=this.trailWidth,a=[new T(0,0,0),new T(0,s,0),new T(-s/2,s/2,0),new T(s/2,s/2,0)];return t.initialize(i,this.trailLength,!1,0,a,e),t.setAdvanceFrequency(60),t.mesh&&(t.mesh.frustumCulled=!1),t}updateColors(){const e=this.teamColors[this.team]||this.teamColors[0],t=new Ye(e.x*.3,e.y*.3,e.z*.3,0);this.leftTrail?.material&&(this.leftTrail.material.uniforms.headColor.value.copy(e),this.leftTrail.material.uniforms.tailColor.value.copy(t)),this.rightTrail?.material&&(this.rightTrail.material.uniforms.headColor.value.copy(e),this.rightTrail.material.uniforms.tailColor.value.copy(t))}startDying(){this.dying||(this.dying=!0,this.deathTime=0,this.leftTrail.pause(),this.rightTrail.pause())}updatePosition(e,t,i){this.dying||(this.leftTarget.position.copy(e),this.rightTarget.position.copy(t),this.leftTarget.quaternion.copy(i),this.rightTarget.quaternion.copy(i),this.leftTarget.updateMatrixWorld(),this.rightTarget.updateMatrixWorld())}update(e){if(this.dying){this.deathTime+=e;const i=1-Math.min(1,this.deathTime/this.maxDeathTime),s=this.teamColors[this.team]||this.teamColors[0],a=new Ye(s.x,s.y,s.z,s.w*i),r=new Ye(s.x*.3,s.y*.3,s.z*.3,0);this.leftTrail?.material&&(this.leftTrail.material.uniforms.headColor.value.copy(a),this.leftTrail.material.uniforms.tailColor.value.copy(r)),this.rightTrail?.material&&(this.rightTrail.material.uniforms.headColor.value.copy(a),this.rightTrail.material.uniforms.tailColor.value.copy(r)),this.deathTime>=this.maxDeathTime&&(this.active=!1)}this.leftTrail.isActive&&this.leftTrail.update(e),this.rightTrail.isActive&&this.rightTrail.update(e)}dispose(){this.leftTrail.deactivate(),this.rightTrail.deactivate(),this.leftTrail.geometry&&this.leftTrail.geometry.dispose(),this.rightTrail.geometry&&this.rightTrail.geometry.dispose(),this.leftTrail.material&&this.leftTrail.material.dispose(),this.rightTrail.material&&this.rightTrail.material.dispose(),this.scene.remove(this.leftTarget),this.scene.remove(this.rightTarget)}}class wN{constructor(e,t=0){this.scene=e,this.team=t,this.active=!1,this.trailLength=80,this.trailWidth=15,this.arenaBounds={floor:0,ceiling:2044,wallX:4096,wallZ:5120},this.groundedThreshold=50,this.segments=[],this.currentSegment=null,this.wasGrounded=!0}setTeam(e){this.team!==e&&(this.team=e,this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.team=e,this.currentSegment.updateColors()))}setActive(e){e&&!this.active?(this.currentSegment=null,this.wasGrounded=!0):!e&&this.active&&this.currentSegment&&(this.currentSegment.startDying(),this.currentSegment=null),this.active=e}isGrounded(e){const t=this.groundedThreshold,i=this.arenaBounds;if(e.yi.ceiling-t)return{grounded:!0,surface:"ceiling",normal:new T(0,-1,0)};if(Math.abs(e.x)>i.wallX-t){const s=e.x>0?-1:1;return{grounded:!0,surface:"wall",normal:new T(s,0,0)}}if(Math.abs(e.z)>i.wallZ-t){const s=e.z>0?-1:1;return{grounded:!0,surface:"wall",normal:new T(0,0,s)}}return{grounded:!1,surface:null,normal:null}}emit(e,t,i){if(!this.active)return;const s=this.isGrounded(e);if(!s.grounded){this.currentSegment&&!this.currentSegment.dying&&(this.currentSegment.startDying(),this.currentSegment=null),this.wasGrounded=!1;return}(!this.wasGrounded||!this.currentSegment)&&(this.currentSegment&&!this.currentSegment.dying&&this.currentSegment.startDying(),this.currentSegment=new xN(this.scene,this.team,this.trailWidth,this.trailLength),this.segments.push(this.currentSegment)),this.wasGrounded=!0;const r=new T(-30,5,40),o=new T(-30,5,-40);r.applyQuaternion(t),o.applyQuaternion(t);const l=e.clone().add(r),c=e.clone().add(o),u=2;if(s.surface==="floor")l.y=u,c.y=u;else if(s.surface==="ceiling")l.y=this.arenaBounds.ceiling-u,c.y=this.arenaBounds.ceiling-u;else if(s.surface==="wall"){if(s.normal.x!==0){const d=s.normal.x>0?-this.arenaBounds.wallX+u:this.arenaBounds.wallX-u;l.x=d,c.x=d}else if(s.normal.z!==0){const d=s.normal.z>0?-this.arenaBounds.wallZ+u:this.arenaBounds.wallZ-u;l.z=d,c.z=d}}this.currentSegment.updatePosition(l,c,t)}update(e){for(let t=this.segments.length-1;t>=0;t--){const i=this.segments[t];i.update(e),i.active||(i.dispose(),this.segments.splice(t,1))}}addToScene(e){}removeFromScene(e){for(const t of this.segments)t.startDying();this.currentSegment=null}dispose(){for(const e of this.segments)e.dispose();this.segments=[],this.currentSegment=null}}class SN{constructor(e){this.scene=e,this.renderer=null,this.camera=null,this.explosions={active:[],goalEvents:new Map,demoEvents:new Map},this.boostTrails=new Map,this.supersonicTrails=new Map,this.ballTrail=null,fN()}setRenderContext(e,t){this.renderer=e,this.camera=t,mN(this.scene,e,t)}reset(){this.explosions.active.forEach(e=>e.removeFromScene(this.scene)),this.explosions.active=[],this.clearGoalExplosions(),this.boostTrails.forEach(e=>{e.removeFromScene(this.scene),e.dispose()}),this.boostTrails.clear(),this.supersonicTrails.forEach(e=>{e.removeFromScene(this.scene),e.dispose()}),this.supersonicTrails.clear(),this.ballTrail&&(this.ballTrail.removeFromScene(this.scene),this.ballTrail.dispose(),this.ballTrail=null)}clearEvents(){this.explosions.goalEvents.clear(),this.explosions.demoEvents.clear()}setGoalEvents(e){this.explosions.goalEvents.clear();for(const t of e??[])Number.isFinite(t.frame)&&this.explosions.goalEvents.set(t.frame,{time:t.time,team:t.team??0,playerName:t.playerName??""})}resetBallTrail(){this.ballTrail&&this.ballTrail.reset()}clearGoalExplosions(){Gn&&Gn.clearActive();for(const e of this.explosions.active)e.removeFromScene(this.scene);this.explosions.active=[]}createBoostTrail(e,t){if(this.boostTrails.has(t)){const s=this.boostTrails.get(t);s.removeFromScene(this.scene),s.dispose()}const i=new bN(e);return i.addToScene(this.scene),this.boostTrails.set(t,i),i}removeBoostTrail(e){const t=this.boostTrails.get(e);t&&(t.removeFromScene(this.scene),t.dispose(),this.boostTrails.delete(e))}updateBoostTrail(e,t,i,s,a){const r=this.boostTrails.get(e);r&&(r.setActive(t),t&&r.emit(i,s,a,this._playbackSpeed||1))}createSupersonicTrail(e,t){if(this.supersonicTrails.has(e)){const s=this.supersonicTrails.get(e);s.removeFromScene(this.scene),s.dispose()}const i=new wN(this.scene,t);return i.addToScene(this.scene),this.supersonicTrails.set(e,i),i}removeSupersonicTrail(e){const t=this.supersonicTrails.get(e);t&&(t.removeFromScene(this.scene),t.dispose(),this.supersonicTrails.delete(e))}updateSupersonicTrail(e,t,i,s,a,r){let o=this.supersonicTrails.get(e);!o&&t&&(o=this.createSupersonicTrail(e,r)),o&&(r!==void 0&&o.team!==r&&o.setTeam(r),o.setActive(t),t&&o.emit(i,s,a))}createBallTrail(){return this.ballTrail&&(this.ballTrail.removeFromScene(this.scene),this.ballTrail.dispose()),this.ballTrail=new hN(this.scene,0),this.ballTrail.addToScene(this.scene),console.log("✓ Spiral ball trail created and added to scene"),this.ballTrail}updateBallTrail(e,t,i){this.ballTrail||this.createBallTrail(),i!==void 0&&this.ballTrail.team!==i&&this.ballTrail.setTeam(i);const s=1/60*(this._playbackSpeed||1);this.ballTrail.emit(e,t,s)}triggerGoalExplosion(e,t){const i=mM(this.scene,this.renderer,this.camera);i&&(this.camera&&(i.camera=this.camera),i.trigger(e,t))}triggerDemoExplosion(e,t,i){const s=pM(this.scene);s&&s.trigger(e)}update(e,t=!0,i=1){this._playbackSpeed=i;const s=e*i;gi&&gi.update(s),Gn&&Gn.update(s);for(let a=this.explosions.active.length-1;a>=0;a--){const r=this.explosions.active[a];r.update(s)&&(r.removeFromScene(this.scene),this.explosions.active.splice(a,1))}t&&(this.boostTrails.forEach(a=>{a.update(s)}),this.supersonicTrails.forEach(a=>{a.update(s)}),this.ballTrail&&this.ballTrail.update(s))}}const Hv={Octane:65535,Dominus:16746496,Plank:8978176,Breakout:16711816,Hybrid:8913151,Merc:16776960},TN={0:5744895,1:16751680};function MN(n,e){return e===0||e===1?TN[e]:Hv[n]||Hv.Octane}class EN{constructor(e){this.scene=e,this.hitboxes=new Map,this.enabled=!1}setEnabled(e){this.enabled=e,this.hitboxes.forEach(({mesh:t})=>{t.visible=e})}createHitboxWireframe(e,t){const i=$y[e]||$y.Octane,s=MN(e,t),a=i.length,r=i.width,o=i.height,l=i.offsetX,c=i.offsetZ;console.log(`[HitboxManager] Creating hitbox for ${e}:`,{dims:i,length:a,width:r,height:o,offsetX:l,offsetY:c});const u=new Et,d=new Di(a,o,r),h=new je({color:s,transparent:!0,opacity:.35,depthTest:!1,depthWrite:!1,side:ut}),f=new Se(d,h);f.frustumCulled=!1,f.renderOrder=1,f.position.set(l,c,0),u.add(f);const p=new yf(d),g=new Pt({color:s,linewidth:2,transparent:!0,opacity:.9,depthTest:!1}),_=new Fn(p,g);_.frustumCulled=!1,_.renderOrder=2,_.position.set(l,c,0),u.add(_);const m=3.33,v=new vn(m,8,6),y=new Gg(v),b=new Pt({color:16777215,linewidth:1,transparent:!0,opacity:.9,depthTest:!1}),S=new Fn(y,b);return S.frustumCulled=!1,u.add(S),u.userData.hitboxType=e,u.userData.team=t??null,u.frustumCulled=!1,u}addHitbox(e,t,i){const s=i===0||i===1?i:null;if(this.hitboxes.has(e)){const r=this.hitboxes.get(e);if(r.hitboxType===t&&r.team===s)return;this.scene.remove(r.mesh),r.mesh.traverse(o=>{o.geometry&&o.geometry.dispose(),o.material&&o.material.dispose()})}const a=this.createHitboxWireframe(t,s);a.visible=this.enabled,this.scene.add(a),this.hitboxes.set(e,{mesh:a,hitboxType:t,team:s})}removeHitbox(e){if(this.hitboxes.has(e)){const{mesh:t}=this.hitboxes.get(e);this.scene.remove(t),t.traverse(i=>{i.geometry&&i.geometry.dispose(),i.material&&i.material.dispose()}),this.hitboxes.delete(e)}}updateHitboxes(e,t,i,s){if(!this.enabled)return;for(const[r,o]of Object.entries(t)){const l=e[o];if(!l||!l.userData.isCar)continue;const c=i?i(r):"Octane",u=s?s(r):null;this.addHitbox(o,c,u);const{mesh:d}=this.hitboxes.get(o);d.position.copy(l.position),d.quaternion.copy(l.quaternion),d.visible=this.enabled&&l.visible}const a=new Set(Object.values(t));for(const r of this.hitboxes.keys())a.has(r)||this.removeHitbox(r)}reset(){this.hitboxes.forEach(({mesh:e})=>{this.scene.remove(e),e.traverse(t=>{t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose()})}),this.hitboxes.clear()}dispose(){this.reset()}}const _M=["baseGroup","glowMesh","innerGlowMesh","lensColumnMesh","lensRimMesh","topGlowMesh","coreGlowMesh","highlightMesh"];function Yp(n,e,t,i){const s=new Se(new qo(n,32),new je({color:e,transparent:!0,opacity:t,blending:Vt,side:ut,depthWrite:!1}));return s.rotation.x=-Math.PI/2,s.renderOrder=i,s}function Vv(n,e){n&&n.traverse(t=>{const i=t;if(!i.isMesh||!(i.material instanceof je))return;const s=i.userData.baseOpacity;i.material.opacity=(s??i.material.opacity)*e})}function Nu(n,e,t){n.rotation.x=-Math.PI/2,n.renderOrder=t,n.frustumCulled=!1,n.userData.baseOpacity=e,n.material.transparent=!0,n.material.opacity=e,n.material.side=ut,n.material.depthWrite=!1}function CN(n){const e=new Et;e.renderOrder=98,e.frustumCulled=!1;const t=new je({color:1118477}),i=new je({color:16752640,blending:Vt}),s=new Se(new qo(n*.55,48),t.clone());Nu(s,.86,98),e.add(s);const a=new Se(new oi(n*.45,n*.62,48),new je({color:16765242,blending:Vt}));Nu(a,.78,100),a.position.y=1.4,e.add(a);function r(o,l,c){const u=new $s;return[[o*Math.cos(-c*.72),o*Math.sin(-c*.72)],[l*Math.cos(-c),l*Math.sin(-c)],[l*Math.cos(c),l*Math.sin(c)],[o*Math.cos(c*.72),o*Math.sin(c*.72)]].forEach(([h,f],p)=>{p===0?u.moveTo(h,f):u.lineTo(h,f)}),u.closePath(),u}for(let o=0;o<3;o+=1){const l=o*(Math.PI*2)/3+Math.PI/2,c=new Se(new br(r(n*.52,n*1.42,.33)),t.clone());Nu(c,.86,98),c.rotation.z=l,e.add(c);const u=new Se(new br(r(n*.66,n*1.2,.21)),i.clone());Nu(u,.86,99),u.position.y=1.1,u.rotation.z=l,e.add(u)}return e}function Gv(n,e){for(const t of _M){const i=n.userData[t];i&&(i.visible=e)}}function AN(){let n=new Map;function e(i){const s=i.player.adapter.boostPads;!s||s.size===0||(console.log(`[boost-pads] Creating ${s.size} boost pads...`),n=new Map,s.forEach((a,r)=>{const o=a.isBig;let l,c,u;if(o){l=new vn(37,24,18),c=new li({color:16757274,emissive:16747008,emissiveIntensity:.42,metalness:.04,roughness:.08,clearcoat:1,clearcoatRoughness:.025,transmission:.18,thickness:30,ior:1.42,envMapIntensity:1.9,blending:Vt,transparent:!0,opacity:.68,depthWrite:!1}),u=new Se(l,c),u.renderOrder=100;const p=CN(37*2.05);p.position.y=-140,u.add(p),u.userData.baseGroup=p;const g=new Se(new yr(37*.12,37*.18,112,24,1,!0),new je({color:16761664,transparent:!0,opacity:.28,blending:Vt,side:ut,depthWrite:!1}));g.position.y=-62,g.renderOrder=99,u.add(g),u.userData.lensColumnMesh=g;const _=new Se(new vn(37*1.03,24,14),new je({color:16768890,transparent:!0,opacity:.32,blending:Vt,side:dn,depthWrite:!1}));_.renderOrder=101,u.add(_),u.userData.lensRimMesh=_;const m=new vn(37*1.3,20,14),v=new je({color:16758315,transparent:!0,opacity:.16,blending:Vt,side:dn,depthWrite:!1}),y=new Se(m,v);y.renderOrder=99,u.add(y),u.userData.glowMesh=y;const b=new vn(37*1.12,20,14),S=new je({color:16761130,transparent:!0,opacity:.22,blending:Vt,side:dn,depthWrite:!1}),x=new Se(b,S);x.renderOrder=99,u.add(x),u.userData.innerGlowMesh=x,u.userData.needsLight=!0}else{l=new yr(45,45*.92,8,32),c=new li({color:16761370,emissive:16750336,emissiveIntensity:.72,metalness:.88,roughness:.14,clearcoat:1,clearcoatRoughness:.05,envMapIntensity:2,transparent:!0,opacity:1,depthWrite:!1}),u=new Se(l,c),u.renderOrder=100;const g=Yp(45*1.42,16756736,.34,101);g.position.y=8/2+.15,u.add(g),u.userData.topGlowMesh=g;const _=Yp(45*.74,16777114,.42,102);_.position.y=8/2+.35,u.add(_),u.userData.coreGlowMesh=_;const m=Yp(45*.42,16775376,.46,103);m.position.set(-45*.18,8/2+.55,-45*.12),m.scale.y=.34,u.add(m),u.userData.highlightMesh=m}const h=o?130:10;if(u.position.set(a.position.x,h,a.position.y),u.userData.padId=r,u.userData.isBig=o,u.userData.isAvailable=!0,i.scene.add(u),n.set(r,u),u.userData.needsLight){const f=new xr(16751872,.7,480);f.decay=0,f.position.set(a.position.x,h-50,a.position.y),i.scene.add(f),u.userData.light=f}}),console.log(`[boost-pads] ✓ Created ${n.size} boost pad meshes`))}function t(i){i.player.adapter.boostPads.forEach((a,r)=>{const o=n.get(r);if(!o)return;const l=a.isAvailable;o.userData.isAvailable!==l&&(o.userData.isAvailable=l,l?(o.material.color.setHex(a.isBig?16757274:16761370),o.material.emissive.setHex(a.isBig?16747008:16750336),o.material.emissiveIntensity=a.isBig?.42:.72,o.material.opacity=a.isBig?.68:1,o.visible=!0,Gv(o,!0),Vv(o.userData.baseGroup,1),o.userData.light&&(o.userData.light.intensity=.85),o.userData.glowMesh&&(o.userData.glowMesh.visible=!0),o.userData.innerGlowMesh&&(o.userData.innerGlowMesh.visible=!0)):(o.material.color.setHex(a.isBig?9063424:9065472),o.material.emissive.setHex(0),o.material.emissiveIntensity=0,o.material.opacity=.2,o.visible=!0,Gv(o,!1),o.userData.baseGroup&&(o.userData.baseGroup.visible=!0,Vv(o.userData.baseGroup,.26)),o.userData.light&&(o.userData.light.intensity=0),o.userData.glowMesh&&(o.userData.glowMesh.visible=!1),o.userData.innerGlowMesh&&(o.userData.innerGlowMesh.visible=!1)))})}return{id:"boost-pads",setup(i){e(i)},beforeRender(i){t(i)},teardown(i){n.forEach(s=>{i.scene.remove(s),s.geometry.dispose(),s.material.dispose();for(const r of _M){const o=s.userData[r];o&&o.traverse(l=>{const c=l;c.isMesh&&(c.geometry.dispose(),c.material.dispose())})}const a=s.userData.light;a&&(i.scene.remove(a),a.dispose())}),n.clear()}}}const RN=2;function PN(n){if(n.frames.length===0)return null;const e=new Map;for(const s of n.frames)e.set(s.gameState,(e.get(s.gameState)??0)+1);let t=null,i=-1;for(const[s,a]of e.entries())a<=i||(t=s,i=a);return t}function IN(n,e){if(e===null)return null;for(const t of n.frames){if(t.gameState===e)break;return t.gameState}return null}function gM(n,e){return e===null?n.kickoffCountdown<=0:n.gameState===e}function ly(n,e){return n.kickoffCountdown>0?!0:e!==null&&n.gameState===e}function LN(n,e){return n.ballFrames[e]?.position?!0:n.players.some(t=>t.frames[e]?.position)}function kN(n,e,t,i){return ly(e,i)&&LN(n,t)}function DN(n,e){return n.timelineEvents.some(t=>t.kind==="goal"&&e.time>=t.time&&e.timec){const h=a.at(-1);h&&h.endTime>=c?h.endTime=Math.max(h.endTime,d):a.push({startTime:c,endTime:d})}o=u}return a}function FN(n,e,t){const i=bt.clamp(t,0,n);for(const s of e){if(i0&&(n.frames[s-1]?.kickoffCountdown??0)>0;)s-=1;let a=e+1;for(;a0;)a+=1;let r=0;for(let c=s;cl>s&&gM(o,t));return!r||r.time===e?null:r.time}function GN(n,e,t,i){const s=Wh(n,e),a=n.frames[s];if(!a||!md(n,a,s,t,i))return null;const r=n.frames.find((c,u)=>u>s&&!md(n,c,u,t,i));if(r)return r.time===e?null:r.time;let o=s;for(;o>0&&md(n,n.frames[o-1],o-1,t,i);)o-=1;const l=n.frames[o]?.time;return l===void 0||l===e?null:l}function $N(n){return!!n?.position&&n?.isPresent!==!1}function WN(n,e,t){for(let i=n.length-1;i>=0;i-=1){const s=n[i],a=t-s.time;if(!(a<0)){if(a>HN)break;if(s.kind==="demo"&&s.secondaryPlayerId===e)return s}}return null}const XN="space",KN={space:{id:"space",skyboxUrl:"/skyboxes/PlanetaryEarth4k.hdr",exposure:1.45,rotation:{x:8,y:0,z:28},animation:{enabled:!0,speed:2}}};function qN(n){if(n===!1)return null;if(typeof n=="string"){const e=KN[n];return e||(console.warn(`[player] unknown environment "${n}"; using neutral default`),null)}return n}const YN=new Proxy({},{get:()=>()=>{}});function Wv(n){if(!n)return null;const e={};for(const t of Object.keys(n)){const i=n[t];typeof i=="number"&&Number.isFinite(i)&&(e[t]=i)}return e}const Xv=48,Uu=.14,jN=16,ZN=16,JN=.003,QN=.05,eU=1.08,Kv=4120,qv=5140,tU=0,nU=2200,iU=new T(0,700,0),sU=new T(-1,0,0),aU=new T(0,-1,0),rU=new T(0,900,0),oU=new T(0,1,0),lU=new T(9600,-5500,12600).normalize();function cU(n,e){const t=Number.isFinite(e)&&e>0?e:1.7777777777777777,i=n==="overhead"?iU.clone():rU.clone(),s=n==="overhead"?sU.clone():oU.clone(),a=n==="overhead"?aU.clone():lU.clone(),r=uU({aspect:t,fov:Xv,forward:a,margin:eU,target:i,up:s});return{position:i.clone().addScaledVector(a,-r),target:i,up:s,fov:Xv}}function uU(n){const{aspect:e,fov:t,forward:i,margin:s,target:a,up:r}=n,o=i.clone().normalize(),l=new T().crossVectors(o,r).normalize(),c=new T().crossVectors(l,o).normalize(),u=Math.tan(bt.degToRad(t)/2),d=u*e;let h=1;for(const f of[-Kv,Kv])for(const p of[tU,nU])for(const g of[-qv,qv]){const _=new T(f,p,g).sub(a),m=Math.abs(_.dot(l)),v=Math.abs(_.dot(c)),y=_.dot(o);h=Math.max(h,m/d-y,v/u-y)}return Math.max(1,h*s)}function dU(n){const e=new Et;return e.name="replayRoot",e.matrixAutoUpdate=!1,e.matrix.set(1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1),n.add(e),e}class hU extends EventTarget{container;adapter;replay;options;sceneManager;arenaManager;actorManager;effectsManager;hitboxManager;controls;replayRoot;sceneState;effectsEnabled;ready;plugins=[];beforeRenderCallbacks=[];resizeObserver=null;animationFrameId=null;disposed=!1;playing=!1;readyResolved=!1;speed;loop;currentTime=0;lastTickAt=null;freeCameraTransition=null;cameraDistanceScaleValue;customCameraSettingsValue;cameraViewModeValue;attachedPlayerIdValue;ballCamEnabledValue;boostMeterEnabledValue;boostPickupAnimationEnabledValue;hitboxWireframesEnabledValue;hitboxOnlyModeEnabledValue;hitboxTypeByName=null;hitboxTeamByName=null;hitboxesActive=!1;skipPostGoalTransitionsEnabledValue;skipKickoffsEnabledValue;attachmentTouched=!1;liveGameState=null;kickoffGameState=null;timelineSegmentsCacheKey=null;timelineSegmentsCache=[];constructor(e,t,i={},s=null){super(),this.container=e,this.adapter=t,this.replay=s,this.options=i,this.updateReplayGameStates(),this.speed=Math.max(.1,i.initialPlaybackRate??i.speed??1),this.loop=i.loop??!1,this.cameraDistanceScaleValue=Math.max(.25,i.initialCameraDistanceScale??1),this.customCameraSettingsValue=Wv(i.initialCustomCameraSettings),this.attachedPlayerIdValue=i.initialAttachedPlayerId??null,this.cameraViewModeValue=i.initialCameraViewMode??(this.attachedPlayerIdValue?"follow":"free"),this.ballCamEnabledValue=i.initialBallCamEnabled??null,this.boostMeterEnabledValue=i.initialBoostMeterEnabled??!1,this.boostPickupAnimationEnabledValue=i.initialBoostPickupAnimationEnabled??!0,this.hitboxWireframesEnabledValue=i.initialHitboxWireframesEnabled??!1,this.hitboxOnlyModeEnabledValue=i.initialHitboxOnlyModeEnabled??!1,this.skipPostGoalTransitionsEnabledValue=i.initialSkipPostGoalTransitionsEnabled??!0,this.skipKickoffsEnabledValue=i.initialSkipKickoffsEnabled??!1,this.sceneManager=new PO(e,{assetBase:i.assetBase,preserveDrawingBuffer:i.preserveDrawingBuffer}),this.sceneManager.initDefaultEnvironment(),this.applyEnvironmentSpec(i.environment??XN),this.arenaManager=new bF(this.scene,{assetBase:i.assetBase}),this.effectsEnabled=i.effects??!0,this.effectsManager=this.effectsEnabled?new SN(this.scene):YN,this.actorManager=new uN(this.scene,this.effectsManager,{assetBase:i.assetBase}),i.motionInterpolation&&this.setMotionInterpolation(i.motionInterpolation),this.actorManager.initFromFramework(t),this.actorManager.initInterpolants(t.getTimelines()),this.hitboxManager=new EN(this.scene),this.syncGoalEvents(),this.controls=new dO(this.camera,this.renderer.domElement),this.controls.zoomSpeed=2.5,this.camera.position.set(0,4e3,6e3),this.controls.target.set(0,200,0),this.controls.update(),this.replayRoot=dU(this.scene),this.sceneState=this.createSceneState(),this.ready=Promise.all([this.arenaManager.loadArenaMeshes().catch(a=>{console.warn("[player] arena load failed",a)}),this.prepareReplayAssets()]).then(()=>{this.markReady()}),this.installResizeHandling();for(const a of i.plugins??[])this.installPlugin(a,!1);this.plugins.some(a=>a.plugin.id==="boost-pads")||this.installPlugin(AN(),!1),this.applyInitialCameraOptions(),this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded(),this.scheduleAnimationFrame(),this.emitChange(),i.autoplay&&this.play()}get scene(){return this.sceneManager.scene}get camera(){return this.sceneManager.camera}get renderer(){return this.sceneManager.renderer}get duration(){return this.adapter.duration}async replaceReplay(e,t,i={}){if(this.disposed)throw new Error("Cannot replace replay on a disposed ReplayPlayer");const s=i.preservePlayback??this.playing;this.playing&&this.setPlayingInternal(!1),this.teardownPlugins(),this.effectsManager.reset(),this.effectsManager.clearEvents?.(),this.hitboxManager.reset(),this.actorManager.reset(),this.adapter=e,this.replay=t,this.updateReplayGameStates(),this.timelineSegmentsCacheKey=null,this.timelineSegmentsCache=[],this.hitboxTypeByName=null,this.hitboxTeamByName=null,this.hitboxesActive=!1,this.freeCameraTransition=null,this.actorManager.initFromFramework(e),this.actorManager.initInterpolants(e.getTimelines()),this.syncGoalEvents();const a=this.attachedPlayerIdValue&&this.adapter.playerList.some(r=>r.id===this.attachedPlayerIdValue)?this.attachedPlayerIdValue:null;a!==this.attachedPlayerIdValue&&(this.attachedPlayerIdValue=a,this.cameraViewModeValue==="follow"&&(this.cameraViewModeValue="free")),this.seekInternal(i.currentTime??0),this.readyResolved=!1,this.ready=this.prepareReplayAssets().then(()=>{this.markReady()}),await this.ready,this.setupPlugins(),this.applyInitialCameraOptions(),this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded(),s&&this.setPlayingInternal(!0),this.render(),this.emitChange()}setEnvironment(e){this.applyEnvironmentSpec(e)}applyEnvironmentSpec(e){const t=qN(e);if(!t){this.sceneManager.setDefaultBackground();return}this.sceneManager.applyEnvironment(t).catch(i=>{console.warn(`[player] environment "${t.id}" failed to load`,i)})}play(){this.playing||(this.setPlayingInternal(!0),this.emitChange())}pause(){this.playing&&(this.setPlayingInternal(!1),this.emitChange())}togglePlayback(){this.playing?this.pause():this.play()}seek(e){this.seekInternal(e),this.playing&&(this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded()),this.emitChange()}setPlaybackRate(e){this.speed=Math.max(.1,e),this.emitChange()}setLoop(e){this.loop=e}setMotionInterpolation(e){this.actorManager.interpolationMethod=e==="linear"?"lerp":"hermite"}setFrameIndex(e){const t=this.adapter.frameTimes;if(t.length===0||!Number.isFinite(e))return;const i=Math.min(Math.max(Math.trunc(e),0),t.length-1);this.playing&&this.setPlayingInternal(!1),this.seekInternal(t[i]),this.emitChange()}stepFrames(e){Number.isFinite(e)&&this.setFrameIndex(this.adapter.frameIndexAt(this.currentTime)+Math.trunc(e))}stepForwardFrame(){this.stepFrames(1)}stepBackwardFrame(){this.stepFrames(-1)}setCameraDistanceScale(e){this.cameraDistanceScaleValue=Math.max(.25,e),this.getCameraPlugin()?.setDistanceScale(this.cameraDistanceScaleValue),this.emitChange()}setCustomCameraSettings(e){this.applyCustomCameraSettings(e),this.emitChange()}setAttachedPlayer(e){this.attachedPlayerIdValue=e,this.cameraViewModeValue=e?"follow":"free",this.attachmentTouched=!0,this.freeCameraTransition=null,this.syncCameraAttachment(),this.emitChange()}setCameraViewMode(e){this.cameraViewModeValue=e,this.attachmentTouched=!0,this.freeCameraTransition=null,this.syncCameraAttachment(),this.emitChange()}setFreeCameraPreset(e,t={}){this.cameraViewModeValue="free",this.attachmentTouched=!0,this.syncCameraAttachment();const i=cU(e,this.camera.aspect);t.instant?(this.camera.position.copy(i.position),this.controls.target.copy(i.target),this.camera.up.copy(i.up).normalize(),this.camera.fov=i.fov,this.camera.updateProjectionMatrix(),this.camera.lookAt(i.target),this.controls.enabled=!0,this.freeCameraTransition=null):this.freeCameraTransition=i,this.emitChange()}setBallCamEnabled(e){this.ballCamEnabledValue=e,this.getCameraPlugin()?.setBallCam(e),this.emitChange()}setBoostMeterEnabled(e){this.boostMeterEnabledValue=e,this.emitChange()}setBoostPickupAnimationEnabled(e){this.boostPickupAnimationEnabledValue=e,this.emitChange()}setHitboxWireframesEnabled(e){this.hitboxWireframesEnabledValue=e,this.emitChange()}setHitboxOnlyModeEnabled(e){this.hitboxOnlyModeEnabledValue=e,this.emitChange()}setSkipPostGoalTransitionsEnabled(e){this.skipPostGoalTransitionsEnabledValue=e,e&&this.playing&&this.skipPostGoalTransitionIfNeeded(),this.emitChange()}setSkipKickoffsEnabled(e){this.skipKickoffsEnabledValue=e,e&&this.playing&&(this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded()),this.emitChange()}setState(e){e.speed!==void 0&&(this.speed=Math.max(.1,e.speed)),e.cameraDistanceScale!==void 0&&(this.cameraDistanceScaleValue=Math.max(.25,e.cameraDistanceScale),this.getCameraPlugin()?.setDistanceScale(this.cameraDistanceScaleValue)),e.customCameraSettings!==void 0&&this.applyCustomCameraSettings(e.customCameraSettings),e.cameraViewMode!==void 0&&(this.cameraViewModeValue=e.cameraViewMode,this.attachmentTouched=!0),e.attachedPlayerId!==void 0&&(this.attachedPlayerIdValue=e.attachedPlayerId,this.attachmentTouched=!0,e.cameraViewMode===void 0&&(this.cameraViewModeValue=e.attachedPlayerId?"follow":"free")),(e.cameraViewMode!==void 0||e.attachedPlayerId!==void 0)&&(this.freeCameraTransition=null,this.syncCameraAttachment()),e.useReplayBallCam===!0?(this.ballCamEnabledValue=null,this.getCameraPlugin()?.setBallCam(null)):e.ballCamEnabled!==void 0&&(this.ballCamEnabledValue=e.ballCamEnabled,this.getCameraPlugin()?.setBallCam(e.ballCamEnabled)),e.boostMeterEnabled!==void 0&&(this.boostMeterEnabledValue=e.boostMeterEnabled),e.boostPickupAnimationEnabled!==void 0&&(this.boostPickupAnimationEnabledValue=e.boostPickupAnimationEnabled),e.hitboxWireframesEnabled!==void 0&&(this.hitboxWireframesEnabledValue=e.hitboxWireframesEnabled),e.hitboxOnlyModeEnabled!==void 0&&(this.hitboxOnlyModeEnabledValue=e.hitboxOnlyModeEnabled),e.skipPostGoalTransitionsEnabled!==void 0&&(this.skipPostGoalTransitionsEnabledValue=e.skipPostGoalTransitionsEnabled),e.skipKickoffsEnabled!==void 0&&(this.skipKickoffsEnabledValue=e.skipKickoffsEnabled),e.currentTime!==void 0&&this.seekInternal(e.currentTime),e.playing!==void 0&&e.playing!==this.playing&&this.setPlayingInternal(e.playing),this.playing&&(e.currentTime!==void 0||e.playing!==void 0)&&(this.skipPostGoalTransitionIfNeeded(),this.skipPastKickoffIfNeeded()),this.emitChange()}getState(){const e=this.adapter.frameIndexAt(this.currentTime),t=this.getCameraPlugin();let i=this.cameraViewModeValue,s=this.attachedPlayerIdValue;if(t)if(t.getMode()==="follow"){i="follow";const a=t.getTarget();s=(a?this.adapter.playerList.find(o=>o.name===a):void 0)?.id??s}else i="free",s=null;return{currentTime:this.currentTime,duration:this.duration,frameIndex:e,activeMetadata:this.replay?BN(this.replay,e,this.currentTime):null,playing:this.playing,speed:this.speed,cameraDistanceScale:this.cameraDistanceScaleValue,customCameraSettings:this.customCameraSettingsValue,cameraViewMode:i,attachedPlayerId:s,ballCamEnabled:t?t.getBallCam():this.ballCamEnabledValue??!1,useReplayBallCam:this.ballCamEnabledValue===null,effectiveBallCamEnabled:t?t.getBallCam():this.ballCamEnabledValue??!1,boostMeterEnabled:this.boostMeterEnabledValue,boostPickupAnimationEnabled:this.boostPickupAnimationEnabledValue,hitboxWireframesEnabled:this.hitboxWireframesEnabledValue,hitboxOnlyModeEnabled:this.hitboxOnlyModeEnabledValue,skipPostGoalTransitionsEnabled:this.skipPostGoalTransitionsEnabledValue,skipKickoffsEnabled:this.skipKickoffsEnabledValue}}getSnapshot(){return this.getState()}getTimelineDuration(){return this.replay?.duration??this.duration}getTimelineCurrentTime(){return this.projectReplayTimeToTimeline(this.currentTime).timelineTime}getTimelineSegments(){if(!this.replay)return[];const e=`${this.skipPostGoalTransitionsEnabledValue}:${this.skipKickoffsEnabledValue}`;return this.timelineSegmentsCacheKey===e?this.timelineSegmentsCache:(this.timelineSegmentsCacheKey=e,this.timelineSegmentsCache=ON(this.replay,this.skipPostGoalTransitionsEnabledValue,this.skipKickoffsEnabledValue,this.liveGameState,this.kickoffGameState),this.timelineSegmentsCache)}projectReplayTimeToTimeline(e){return FN(this.replay?.duration??this.duration,this.getTimelineSegments(),e)}projectTimelineTimeToReplay(e){return NN(this.replay?.duration??this.duration,this.getTimelineDuration(),this.getTimelineSegments(),e)}subscribe(e){const t=i=>{e(i.detail)};return this.addEventListener("change",t),e(this.getState()),()=>{this.removeEventListener("change",t)}}onBeforeRender(e){return this.beforeRenderCallbacks.push(e),()=>{const t=this.beforeRenderCallbacks.indexOf(e);t>=0&&this.beforeRenderCallbacks.splice(t,1)}}addPlugin(e){return this.installPlugin(e,!0)}removePlugin(e){const t=this.plugins.findIndex(s=>s.plugin.id===e);if(t<0)return!1;const[i]=this.plugins.splice(t,1);return i.plugin.teardown?.(this.createPluginContext()),!0}getPlugins(){return this.plugins.map(e=>e.plugin)}destroy(){if(!this.disposed){for(this.disposed=!0,this.playing=!1,this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.beforeRenderCallbacks.length=0;this.plugins.length>0;)this.plugins.pop()?.plugin.teardown?.(this.createPluginContext());this.controls.dispose(),this.effectsEnabled&&this.effectsManager.reset(),this.hitboxManager.dispose(),this.actorManager.reset(),this.sceneManager.dispose()}}dispose(){this.destroy()}setPlayingInternal(e){this.playing=e,this.lastTickAt=null,e?this.actorManager.resumeAnimations():this.actorManager.pauseAnimations()}prepareReplayAssets(){return this.actorManager.waitForBallModel().catch(()=>!1).then(()=>{if(this.effectsEnabled)try{this.effectsManager.setRenderContext(this.renderer,this.camera)}catch(e){console.warn("[player] explosion warmup failed",e)}})}markReady(){this.readyResolved=!0,this.lastTickAt=null}updateReplayGameStates(){if(!this.replay){this.liveGameState=null,this.kickoffGameState=null;return}this.liveGameState=PN(this.replay),this.kickoffGameState=IN(this.replay,this.liveGameState)}syncGoalEvents(){this.effectsEnabled&&(this.effectsManager.clearEvents?.(),this.replay&&this.effectsManager.setGoalEvents(this.replay.timelineEvents.filter(e=>e.kind==="goal").map(e=>({frame:e.frame,time:e.time,team:e.isTeamZero?0:1,playerName:e.playerName??""}))))}teardownPlugins(){const e=this.createPluginContext();for(const t of this.plugins)t.plugin.teardown?.(e)}setupPlugins(){for(const e of this.plugins)e.plugin.setup?.(this.createPluginContext()),e.plugin.id==="camera"&&this.pushCameraParityState(),e.plugin.onStateChange?.(this.createPluginStateContext(this.getState()))}seekInternal(e){this.currentTime=bt.clamp(e,0,this.duration),this.actorManager.seekAnimations(this.currentTime),this.effectsManager.resetBallTrail(),this.effectsManager.clearGoalExplosions?.(),this.actorManager.resetGoalExplosionPlaybackState(),this.actorManager.resetWheelTracking()}getPlaybackEndTime(){return this.replay?UN(this.replay.duration,this.getTimelineSegments()):this.duration}skipPastKickoffIfNeeded(){if(!this.replay||!this.skipKickoffsEnabledValue)return!1;const e=VN(this.replay,this.currentTime,this.liveGameState,this.kickoffGameState);return e===null?!1:(this.seekInternal(e),!0)}skipPostGoalTransitionIfNeeded(){if(!this.replay||!this.skipPostGoalTransitionsEnabledValue)return!1;const e=GN(this.replay,this.currentTime,this.liveGameState,this.kickoffGameState);return e===null?!1:(this.seekInternal(e),!0)}getCameraPlugin(){const e=this.plugins.find(t=>t.plugin.id==="camera")?.plugin;return e&&typeof e.follow=="function"?e:null}playerNameForId(e){return this.adapter.playerList.find(t=>t.id===e)?.name??null}applyReplayBallCam(){if(this.ballCamEnabledValue!==null||this.cameraViewModeValue!=="follow"||!this.attachedPlayerIdValue)return;const e=this.playerNameForId(this.attachedPlayerIdValue);if(!e)return;const t=this.adapter.getAllPlayers().find(i=>i.name===e);t&&this.getCameraPlugin()?.setBallCam(t.isBallCam)}syncCameraAttachment(){const e=this.getCameraPlugin();if(e){if(this.cameraViewModeValue==="follow"&&this.attachedPlayerIdValue){const t=this.playerNameForId(this.attachedPlayerIdValue);if(!t){console.warn(`[player] no player with id ${JSON.stringify(this.attachedPlayerIdValue)}`);return}this.camera.up.set(0,1,0),e.follow(t);return}e.getMode()==="follow"&&e.release()}}applyCustomCameraSettings(e){this.customCameraSettingsValue=Wv(e);const t=this.getCameraPlugin();t&&(t.setCameraSettings(null),this.customCameraSettingsValue&&t.setCameraSettings(this.customCameraSettingsValue))}pushCameraParityState(){const e=this.getCameraPlugin();e&&(this.cameraDistanceScaleValue!==1&&e.setDistanceScale(this.cameraDistanceScaleValue),this.customCameraSettingsValue&&e.setCameraSettings(this.customCameraSettingsValue),this.ballCamEnabledValue!==null&&e.setBallCam(this.ballCamEnabledValue),this.attachmentTouched&&this.syncCameraAttachment())}applyInitialCameraOptions(){const e=this.options;(e.initialAttachedPlayerId!==void 0||e.initialCameraViewMode!==void 0)&&(this.attachmentTouched=!0),this.pushCameraParityState()}computeFrameRenderInfo(){const e=this.adapter.frameTimes,t=this.adapter.frameIndexAt(this.currentTime),i=Math.min(t+1,Math.max(e.length-1,0)),s=e[t]??0,a=e[i]??s,r=a>s?bt.clamp((this.currentTime-s)/(a-s),0,1):0;return{frameIndex:t,nextFrameIndex:i,alpha:r,currentTime:this.currentTime}}installResizeHandling(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>this.sceneManager.onWindowResize()),this.resizeObserver.observe(this.container))}scheduleAnimationFrame(){this.animationFrameId!==null||this.disposed||(this.animationFrameId=requestAnimationFrame(this.tick))}tick=e=>{if(this.animationFrameId=null,this.disposed)return;let t=!1,i=0;if(this.playing&&this.readyResolved){i=this.lastTickAt===null?0:Math.min(.1,(e-this.lastTickAt)/1e3),this.lastTickAt=e;let s=this.currentTime+i*this.speed;const a=this.getPlaybackEndTime();s>=a&&(this.loop?(s=0,this.actorManager.seekAnimations(0),this.effectsManager.resetBallTrail(),this.effectsManager.clearGoalExplosions?.(),this.actorManager.resetGoalExplosionPlaybackState(),this.actorManager.resetWheelTracking()):(s=a,this.playing=!1)),t=s!==this.currentTime||!this.playing,this.currentTime=s,this.playing&&(t=this.skipPostGoalTransitionIfNeeded()||t,t=this.skipPastKickoffIfNeeded()||t)}else this.playing&&(this.lastTickAt=null);this.render(i),t&&this.emitChange(),this.scheduleAnimationFrame()};renderFrame(e=0){if(this.adapter.seek(this.currentTime),this.playing&&this.actorManager.updateAnimations(e*this.speed),this.actorManager.updateFromFramework(this.adapter,this.currentTime),this.updatePlayerStates(),this.applyReplayBallCam(),this.updateHitboxVisualization(),this.effectsManager.update(e,this.playing,this.speed),this.playing&&this.actorManager.updateWheelRotations(),this.sceneManager.updateSkyboxAnimation(this.playing?e*this.speed:0),this.controls.update(),this.beforeRenderCallbacks.length>0){const t=this.computeFrameRenderInfo();for(const i of[...this.beforeRenderCallbacks])i(t)}if(this.plugins.length>0){const t=this.createRenderContext();for(const i of this.plugins)i.plugin.beforeRender?.(t)}this.updateFreeCameraTransition(),this.renderer.render(this.scene,this.camera)}render(e=0){this.renderFrame(e)}updateFreeCameraTransition(){const e=this.freeCameraTransition;if(!e)return;this.controls.enabled=!1,this.camera.position.lerp(e.position,Uu),this.controls.target.lerp(e.target,Uu),this.camera.up.lerp(e.up,Uu).normalize(),this.camera.fov=bt.lerp(this.camera.fov,e.fov,Uu),this.camera.updateProjectionMatrix(),this.camera.lookAt(this.controls.target);const t=this.camera.position.distanceToSquared(e.position)<=jN,i=this.controls.target.distanceToSquared(e.target)<=ZN,s=this.camera.up.angleTo(e.up)<=JN,a=Math.abs(this.camera.fov-e.fov)<=QN;!t||!i||!s||!a||(this.camera.position.copy(e.position),this.controls.target.copy(e.target),this.camera.up.copy(e.up).normalize(),this.camera.fov=e.fov,this.camera.updateProjectionMatrix(),this.camera.lookAt(e.target),this.controls.enabled=!0,this.freeCameraTransition=null)}updatePlayerStates(){if(!this.playing)return;const e=this.hitboxOnlyModeEnabledValue;for(const t of this.adapter.getAllPlayers())this.actorManager.updateBoostState(t.name,t.isBoosting&&!e,t.isKickoffReset),this.actorManager.updateSupersonicState(t.name,t.isSupersonic&&!e,t.team)}updateHitboxVisualization(){const e=this.hitboxWireframesEnabledValue||this.hitboxOnlyModeEnabledValue;if(!e&&!this.hitboxesActive||(this.hitboxesActive=e,this.hitboxManager.setEnabled(e),!e))return;const t=this.actorManager;if(this.hitboxTypeByName||(this.hitboxTypeByName=new Map(this.adapter.getAllPlayers().map(i=>[i.name,i.hitboxType]))),this.hitboxTeamByName||(this.hitboxTeamByName=new Map(this.adapter.getAllPlayers().map(i=>[i.name,i.team]))),this.hitboxManager.updateHitboxes(t.actors,t.playerNameToCarActorId,i=>this.hitboxTypeByName?.get(i)??"Octane",i=>this.hitboxTeamByName?.get(i)??null),this.hitboxOnlyModeEnabledValue)for(const i of Object.values(t.playerNameToCarActorId)){const s=i===void 0?void 0:t.actors[i];s&&(s.visible=!1)}}installPlugin(e,t){const i=typeof e=="function"?e():e;if(this.plugins.some(a=>a.plugin.id===i.id))throw new Error(`Player plugin "${i.id}" is already installed`);const s={definition:e,plugin:i};return this.plugins.push(s),i.setup?.(this.createPluginContext()),i.id==="camera"&&this.pushCameraParityState(),i.onStateChange?.(this.createPluginStateContext(this.getState())),t&&this.render(),()=>{const a=this.plugins.indexOf(s);a<0||(this.plugins.splice(a,1),i.teardown?.(this.createPluginContext()))}}createSceneState(){const e=this.actorManager,t=this,i=new Se;return{get scene(){return t.scene},replayRoot:this.replayRoot,get camera(){return t.camera},get renderer(){return t.renderer},controls:this.controls,resize:()=>this.sceneManager.onWindowResize(),dispose:()=>this.destroy(),get ballMesh(){return(e.ballActorId!=null?e.actors[e.ballActorId]:null)??i},get playerMeshes(){const s=new Map;for(const a of t.adapter.playerList){const r=e.playerNameToCarActorId[a.name],o=r!=null?e.actors[r]:void 0;o&&s.set(a.id,o)}return s},playerBodyMeshes:new Map,playerHitboxes:new Map,playerBoostTrails:new Map,playerBoostMeters:new Map,playerDemoIndicators:new Map,updateWallVisibility:()=>{}}}createPluginContext(){return{player:this,replay:this.replay,options:this.options,scene:this.scene,camera:this.camera,renderer:this.renderer,container:this.container}}createPluginStateContext(e){return{...this.createPluginContext(),state:e}}createRenderContext(){const e=this.actorManager,t=this.adapter.ball,i={position:t.position,rotation:t.rotation,velocity:t.velocity,visible:t.visible,object3d:e.ballActorId!=null?e.actors[e.ballActorId]??null:null},s=this.adapter.getAllPlayers().map(a=>{const r=e.playerNameToCarActorId[a.name];return{id:a.id,name:a.name,team:a.team,carName:a.carName,hitboxType:a.hitboxType,position:a.position,rotation:a.rotation,velocity:a.velocity,boost:a.boost,isBoosting:a.isBoosting,visible:a.isVisible,object3d:r!=null?e.actors[r]??null:null}});return{...this.createPluginContext(),...this.computeFrameRenderInfo(),state:this.getState(),time:this.currentTime,ball:i,cars:s}}emitChange(){const e=this.getState(),t=this.createPluginStateContext(e);for(const i of this.plugins)i.plugin.onStateChange?.(t);this.dispatchEvent(new CustomEvent("change",{detail:e}))}}const Xt={LEFT:1,RIGHT:2,MIDDLE:4},$=Object.freeze({NONE:0,ROTATE:1,TRUCK:2,SCREEN_PAN:4,OFFSET:8,DOLLY:16,ZOOM:32,TOUCH_ROTATE:64,TOUCH_TRUCK:128,TOUCH_SCREEN_PAN:256,TOUCH_OFFSET:512,TOUCH_DOLLY:1024,TOUCH_ZOOM:2048,TOUCH_DOLLY_TRUCK:4096,TOUCH_DOLLY_SCREEN_PAN:8192,TOUCH_DOLLY_OFFSET:16384,TOUCH_DOLLY_ROTATE:32768,TOUCH_ZOOM_TRUCK:65536,TOUCH_ZOOM_OFFSET:131072,TOUCH_ZOOM_SCREEN_PAN:262144,TOUCH_ZOOM_ROTATE:524288}),Jr={NONE:0,IN:1,OUT:-1};function Ha(n){return n.isPerspectiveCamera}function ra(n){return n.isOrthographicCamera}const Qr=Math.PI*2,Yv=Math.PI/2,vM=1e-5,yl=Math.PI/180;function $i(n,e,t){return Math.max(e,Math.min(t,n))}function Ft(n,e=vM){return Math.abs(n)0==f>u&&(f=u,t.value=(f-u)/a),f}function Zv(n,e,t,i,s=1/0,a,r){i=Math.max(1e-4,i);const o=2/i,l=o*a,c=1/(1+l+.48*l*l+.235*l*l*l);let u=e.x,d=e.y,h=e.z,f=n.x-u,p=n.y-d,g=n.z-h;const _=u,m=d,v=h,y=s*i,b=y*y,S=f*f+p*p+g*g;if(S>b){const U=Math.sqrt(S);f=f/U*y,p=p/U*y,g=g/U*y}u=n.x-f,d=n.y-p,h=n.z-g;const x=(t.x+o*f)*a,M=(t.y+o*p)*a,C=(t.z+o*g)*a;t.x=(t.x-o*x)*c,t.y=(t.y-o*M)*c,t.z=(t.z-o*C)*c,r.x=u+(f+x)*c,r.y=d+(p+M)*c,r.z=h+(g+C)*c;const w=_-n.x,E=m-n.y,R=v-n.z,L=r.x-_,O=r.y-m,D=r.z-v;return w*L+E*O+R*D>0&&(r.x=_,r.y=m,r.z=v,t.x=(r.x-_)/a,t.y=(r.y-m)/a,t.z=(r.z-v)/a),r}function jp(n,e){e.set(0,0),n.forEach(t=>{e.x+=t.clientX,e.y+=t.clientY}),e.x/=n.length,e.y/=n.length}function Zp(n,e){return ra(n)?(console.warn(`${e} is not supported in OrthographicCamera`),!0):!1}class fU{constructor(){this._listeners={}}addEventListener(e,t){const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){const i=this._listeners;return i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){const s=this._listeners[e];if(s!==void 0){const a=s.indexOf(t);a!==-1&&s.splice(a,1)}}removeAllEventListeners(e){if(!e){this._listeners={};return}Array.isArray(this._listeners[e])&&(this._listeners[e].length=0)}dispatchEvent(e){const i=this._listeners[e.type];if(i!==void 0){e.target=this;const s=i.slice(0);for(let a=0,r=s.length;a{},this._enabled=!0,this._state=$.NONE,this._viewport=null,this._changedDolly=0,this._changedZoom=0,this._hasRested=!0,this._boundaryEnclosesCamera=!1,this._needsUpdate=!0,this._updatedLastTime=!1,this._elementRect=new DOMRect,this._isDragging=!1,this._dragNeedsUpdate=!0,this._activePointers=[],this._lockedPointer=null,this._interactiveArea=new DOMRect(0,0,1,1),this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._isUserControllingOffset=!1,this._isUserControllingZoom=!1,this._lastDollyDirection=Jr.NONE,this._thetaVelocity={value:0},this._phiVelocity={value:0},this._radiusVelocity={value:0},this._targetVelocity=new nt.Vector3,this._focalOffsetVelocity=new nt.Vector3,this._zoomVelocity={value:0},this._truckInternal=(m,v,y,b)=>{let S,x;if(Ha(this._camera)){const M=pt.copy(this._camera.position).sub(this._target),C=this._camera.getEffectiveFOV()*yl,w=M.length()*Math.tan(C*.5);S=this.truckSpeed*m*w/this._elementRect.height,x=this.truckSpeed*v*w/this._elementRect.height}else if(ra(this._camera)){const M=this._camera;S=this.truckSpeed*m*(M.right-M.left)/M.zoom/this._elementRect.width,x=this.truckSpeed*v*(M.top-M.bottom)/M.zoom/this._elementRect.height}else return;b?(y?this.setFocalOffset(this._focalOffsetEnd.x+S,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(S,0,!0),this.forward(-x,!0)):y?this.setFocalOffset(this._focalOffsetEnd.x+S,this._focalOffsetEnd.y+x,this._focalOffsetEnd.z,!0):this.truck(S,x,!0)},this._rotateInternal=(m,v)=>{const y=Qr*this.azimuthRotateSpeed*m/this._elementRect.height,b=Qr*this.polarRotateSpeed*v/this._elementRect.height;this.rotate(y,b,!0)},this._dollyInternal=(m,v,y)=>{const b=Math.pow(.95,-m*this.dollySpeed),S=this._sphericalEnd.radius,x=this._sphericalEnd.radius*b,M=$i(x,this.minDistance,this.maxDistance),C=M-x;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(x,!0):this.infinityDolly&&!this.dollyToCursor?(this.dollyInFixed(C,!0),this._dollyToNoClamp(M,!0)):this._dollyToNoClamp(M,!0),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?x:M)-S,this._dollyControlCoord.set(v,y)),this._lastDollyDirection=Math.sign(-m)},this._zoomInternal=(m,v,y)=>{const b=Math.pow(.95,m*this.dollySpeed),S=this._zoom,x=this._zoom*b;this.zoomTo(x,!0),this.dollyToCursor&&(this._changedZoom+=x-S,this._dollyControlCoord.set(v,y))},typeof nt>"u"&&console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information."),this._camera=e,this._yAxisUpSpace=new nt.Quaternion().setFromUnitVectors(this._camera.up,Hu),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=$.NONE,this._target=new nt.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new nt.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=new nt.Spherical().setFromVector3(pt.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace)),this._sphericalEnd=this._spherical.clone(),this._lastDistance=this._spherical.radius,this._zoom=this._camera.zoom,this._zoomEnd=this._zoom,this._lastZoom=this._zoom,this._nearPlaneCorners=[new nt.Vector3,new nt.Vector3,new nt.Vector3,new nt.Vector3],this._updateNearPlaneCorners(),this._boundary=new nt.Box3(new nt.Vector3(-1/0,-1/0,-1/0),new nt.Vector3(1/0,1/0,1/0)),this._cameraUp0=this._camera.up.clone(),this._target0=this._target.clone(),this._position0=this._camera.position.clone(),this._zoom0=this._zoom,this._focalOffset0=this._focalOffset.clone(),this._dollyControlCoord=new nt.Vector2,this.mouseButtons={left:$.ROTATE,middle:$.DOLLY,right:$.TRUCK,wheel:Ha(this._camera)?$.DOLLY:ra(this._camera)?$.ZOOM:$.NONE},this.touches={one:$.TOUCH_ROTATE,two:Ha(this._camera)?$.TOUCH_DOLLY_TRUCK:ra(this._camera)?$.TOUCH_ZOOM_TRUCK:$.NONE,three:$.TOUCH_TRUCK};const i=new nt.Vector2,s=new nt.Vector2,a=new nt.Vector2,r=m=>{if(!this._enabled||!this._domElement)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const b=this._domElement.getBoundingClientRect(),S=m.clientX/b.width,x=m.clientY/b.height;if(Sthis._interactiveArea.right||xthis._interactiveArea.bottom)return}const v=m.pointerType!=="mouse"?null:(m.buttons&Xt.LEFT)===Xt.LEFT?Xt.LEFT:(m.buttons&Xt.MIDDLE)===Xt.MIDDLE?Xt.MIDDLE:(m.buttons&Xt.RIGHT)===Xt.RIGHT?Xt.RIGHT:null;if(v!==null){const b=this._findPointerByMouseButton(v);b&&this._disposePointer(b)}if((m.buttons&Xt.LEFT)===Xt.LEFT&&this._lockedPointer)return;const y={pointerId:m.pointerId,clientX:m.clientX,clientY:m.clientY,deltaX:0,deltaY:0,mouseButton:v};this._activePointers.push(y),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),this._isDragging=!0,h(m)},o=m=>{m.cancelable&&m.preventDefault();const v=m.pointerId,y=this._lockedPointer||this._findPointerById(v);if(y){if(y.clientX=m.clientX,y.clientY=m.clientY,y.deltaX=m.movementX,y.deltaY=m.movementY,this._state=0,m.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else(!this._isDragging&&this._lockedPointer||this._isDragging&&(m.buttons&Xt.LEFT)===Xt.LEFT)&&(this._state=this._state|this.mouseButtons.left),this._isDragging&&(m.buttons&Xt.MIDDLE)===Xt.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),this._isDragging&&(m.buttons&Xt.RIGHT)===Xt.RIGHT&&(this._state=this._state|this.mouseButtons.right);f()}},l=m=>{const v=this._findPointerById(m.pointerId);if(!(v&&v===this._lockedPointer)){if(v&&this._disposePointer(v),m.pointerType==="touch")switch(this._activePointers.length){case 0:this._state=$.NONE;break;case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else this._state=$.NONE;p()}};let c=-1;const u=m=>{if(!this._domElement||!this._enabled||this.mouseButtons.wheel===$.NONE)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const x=this._domElement.getBoundingClientRect(),M=m.clientX/x.width,C=m.clientY/x.height;if(Mthis._interactiveArea.right||Cthis._interactiveArea.bottom)return}if(m.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===$.ROTATE||this.mouseButtons.wheel===$.TRUCK){const x=performance.now();c-x<1e3&&this._getClientRect(this._elementRect),c=x}const v=mU?-1:-3,y=m.deltaMode===1||m.ctrlKey?m.deltaY/v:m.deltaY/(v*10),b=this.dollyToCursor?(m.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,S=this.dollyToCursor?(m.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case $.ROTATE:{this._rotateInternal(m.deltaX,m.deltaY),this._isUserControllingRotate=!0;break}case $.TRUCK:{this._truckInternal(m.deltaX,m.deltaY,!1,!1),this._isUserControllingTruck=!0;break}case $.SCREEN_PAN:{this._truckInternal(m.deltaX,m.deltaY,!1,!0),this._isUserControllingTruck=!0;break}case $.OFFSET:{this._truckInternal(m.deltaX,m.deltaY,!0,!1),this._isUserControllingOffset=!0;break}case $.DOLLY:{this._dollyInternal(-y,b,S),this._isUserControllingDolly=!0;break}case $.ZOOM:{this._zoomInternal(-y,b,S),this._isUserControllingZoom=!0;break}}this.dispatchEvent({type:"control"})},d=m=>{if(!(!this._domElement||!this._enabled)){if(this.mouseButtons.right===f_.ACTION.NONE){const v=m instanceof PointerEvent?m.pointerId:0,y=this._findPointerById(v);y&&this._disposePointer(y),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l);return}m.preventDefault()}},h=m=>{if(!this._enabled)return;if(jp(this._activePointers,Zn),this._getClientRect(this._elementRect),i.copy(Zn),s.copy(Zn),this._activePointers.length>=2){const y=Zn.x-this._activePointers[1].clientX,b=Zn.y-this._activePointers[1].clientY,S=Math.sqrt(y*y+b*b);a.set(0,S);const x=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,M=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;s.set(x,M)}if(this._state=0,!m)this._lockedPointer&&(this._state=this._state|this.mouseButtons.left);else if("pointerType"in m&&m.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else!this._lockedPointer&&(m.buttons&Xt.LEFT)===Xt.LEFT&&(this._state=this._state|this.mouseButtons.left),(m.buttons&Xt.MIDDLE)===Xt.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),(m.buttons&Xt.RIGHT)===Xt.RIGHT&&(this._state=this._state|this.mouseButtons.right);((this._state&$.ROTATE)===$.ROTATE||(this._state&$.TOUCH_ROTATE)===$.TOUCH_ROTATE||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE)&&(this._sphericalEnd.theta=this._spherical.theta,this._sphericalEnd.phi=this._spherical.phi,this._thetaVelocity.value=0,this._phiVelocity.value=0),((this._state&$.TRUCK)===$.TRUCK||(this._state&$.SCREEN_PAN)===$.SCREEN_PAN||(this._state&$.TOUCH_TRUCK)===$.TOUCH_TRUCK||(this._state&$.TOUCH_SCREEN_PAN)===$.TOUCH_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN)&&(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),((this._state&$.DOLLY)===$.DOLLY||(this._state&$.TOUCH_DOLLY)===$.TOUCH_DOLLY||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE)&&(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),((this._state&$.ZOOM)===$.ZOOM||(this._state&$.TOUCH_ZOOM)===$.TOUCH_ZOOM||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_ZOOM_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE)&&(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),((this._state&$.OFFSET)===$.OFFSET||(this._state&$.TOUCH_OFFSET)===$.TOUCH_OFFSET||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET)&&(this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0)),this.dispatchEvent({type:"controlstart"})},f=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,jp(this._activePointers,Zn);const v=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,y=v?-v.deltaX:s.x-Zn.x,b=v?-v.deltaY:s.y-Zn.y;if(s.copy(Zn),((this._state&$.ROTATE)===$.ROTATE||(this._state&$.TOUCH_ROTATE)===$.TOUCH_ROTATE||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE)&&(this._rotateInternal(y,b),this._isUserControllingRotate=!0),(this._state&$.DOLLY)===$.DOLLY||(this._state&$.ZOOM)===$.ZOOM){const S=this.dollyToCursor?(i.x-this._elementRect.x)/this._elementRect.width*2-1:0,x=this.dollyToCursor?(i.y-this._elementRect.y)/this._elementRect.height*-2+1:0,M=this.dollyDragInverted?-1:1;(this._state&$.DOLLY)===$.DOLLY?(this._dollyInternal(M*b*zu,S,x),this._isUserControllingDolly=!0):(this._zoomInternal(M*b*zu,S,x),this._isUserControllingZoom=!0)}if((this._state&$.TOUCH_DOLLY)===$.TOUCH_DOLLY||(this._state&$.TOUCH_ZOOM)===$.TOUCH_ZOOM||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_ZOOM_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_ZOOM_ROTATE)===$.TOUCH_ZOOM_ROTATE){const S=Zn.x-this._activePointers[1].clientX,x=Zn.y-this._activePointers[1].clientY,M=Math.sqrt(S*S+x*x),C=a.y-M;a.set(0,M);const w=this.dollyToCursor?(s.x-this._elementRect.x)/this._elementRect.width*2-1:0,E=this.dollyToCursor?(s.y-this._elementRect.y)/this._elementRect.height*-2+1:0;(this._state&$.TOUCH_DOLLY)===$.TOUCH_DOLLY||(this._state&$.TOUCH_DOLLY_ROTATE)===$.TOUCH_DOLLY_ROTATE||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET?(this._dollyInternal(C*zu,w,E),this._isUserControllingDolly=!0):(this._zoomInternal(C*zu,w,E),this._isUserControllingZoom=!0)}((this._state&$.TRUCK)===$.TRUCK||(this._state&$.TOUCH_TRUCK)===$.TOUCH_TRUCK||(this._state&$.TOUCH_DOLLY_TRUCK)===$.TOUCH_DOLLY_TRUCK||(this._state&$.TOUCH_ZOOM_TRUCK)===$.TOUCH_ZOOM_TRUCK)&&(this._truckInternal(y,b,!1,!1),this._isUserControllingTruck=!0),((this._state&$.SCREEN_PAN)===$.SCREEN_PAN||(this._state&$.TOUCH_SCREEN_PAN)===$.TOUCH_SCREEN_PAN||(this._state&$.TOUCH_DOLLY_SCREEN_PAN)===$.TOUCH_DOLLY_SCREEN_PAN||(this._state&$.TOUCH_ZOOM_SCREEN_PAN)===$.TOUCH_ZOOM_SCREEN_PAN)&&(this._truckInternal(y,b,!1,!0),this._isUserControllingTruck=!0),((this._state&$.OFFSET)===$.OFFSET||(this._state&$.TOUCH_OFFSET)===$.TOUCH_OFFSET||(this._state&$.TOUCH_DOLLY_OFFSET)===$.TOUCH_DOLLY_OFFSET||(this._state&$.TOUCH_ZOOM_OFFSET)===$.TOUCH_ZOOM_OFFSET)&&(this._truckInternal(y,b,!0,!1),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},p=()=>{jp(this._activePointers,Zn),s.copy(Zn),this._dragNeedsUpdate=!1,(this._activePointers.length===0||this._activePointers.length===1&&this._activePointers[0]===this._lockedPointer)&&(this._isDragging=!1),this._activePointers.length===0&&this._domElement&&(this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this.dispatchEvent({type:"controlend"}))};this.lockPointer=()=>{!this._enabled||!this._domElement||(this.cancel(),this._lockedPointer={pointerId:-1,clientX:0,clientY:0,deltaX:0,deltaY:0,mouseButton:null},this._activePointers.push(this._lockedPointer),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.requestPointerLock(),this._domElement.ownerDocument.addEventListener("pointerlockchange",g),this._domElement.ownerDocument.addEventListener("pointerlockerror",_),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),h())},this.unlockPointer=()=>{var m,v,y;this._lockedPointer!==null&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),(m=this._domElement)===null||m===void 0||m.ownerDocument.exitPointerLock(),(v=this._domElement)===null||v===void 0||v.ownerDocument.removeEventListener("pointerlockchange",g),(y=this._domElement)===null||y===void 0||y.ownerDocument.removeEventListener("pointerlockerror",_),this.cancel()};const g=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},_=()=>{this.unlockPointer()};this._addAllEventListeners=m=>{this._domElement=m,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",r),this._domElement.addEventListener("pointercancel",l),this._domElement.addEventListener("wheel",u,{passive:!1}),this._domElement.addEventListener("contextmenu",d)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect="",this._domElement.removeEventListener("pointerdown",r),this._domElement.removeEventListener("pointercancel",l),this._domElement.removeEventListener("wheel",u,{passive:!1}),this._domElement.removeEventListener("contextmenu",d),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.removeEventListener("pointerlockchange",g),this._domElement.ownerDocument.removeEventListener("pointerlockerror",_))},this.cancel=()=>{this._state!==$.NONE&&(this._state=$.NONE,this._activePointers.length=0,p())},t&&this.connect(t),this.update(0)}get camera(){return this._camera}set camera(e){this._camera=e,this.updateCameraUp(),this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0}get enabled(){return this._enabled}set enabled(e){this._enabled=e,this._domElement&&(e?(this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none"):(this.cancel(),this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect=""))}get active(){return!this._hasRested}get currentAction(){return this._state}get distance(){return this._spherical.radius}set distance(e){this._spherical.radius===e&&this._sphericalEnd.radius===e||(this._spherical.radius=e,this._sphericalEnd.radius=e,this._needsUpdate=!0)}get azimuthAngle(){return this._spherical.theta}set azimuthAngle(e){this._spherical.theta===e&&this._sphericalEnd.theta===e||(this._spherical.theta=e,this._sphericalEnd.theta=e,this._needsUpdate=!0)}get polarAngle(){return this._spherical.phi}set polarAngle(e){this._spherical.phi===e&&this._sphericalEnd.phi===e||(this._spherical.phi=e,this._sphericalEnd.phi=e,this._needsUpdate=!0)}get boundaryEnclosesCamera(){return this._boundaryEnclosesCamera}set boundaryEnclosesCamera(e){this._boundaryEnclosesCamera=e,this._needsUpdate=!0}set interactiveArea(e){this._interactiveArea.width=$i(e.width,0,1),this._interactiveArea.height=$i(e.height,0,1),this._interactiveArea.x=$i(e.x,0,1-this._interactiveArea.width),this._interactiveArea.y=$i(e.y,0,1-this._interactiveArea.height)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}rotate(e,t,i=!1){return this.rotateTo(this._sphericalEnd.theta+e,this._sphericalEnd.phi+t,i)}rotateAzimuthTo(e,t=!1){return this.rotateTo(e,this._sphericalEnd.phi,t)}rotatePolarTo(e,t=!1){return this.rotateTo(this._sphericalEnd.theta,e,t)}rotateTo(e,t,i=!1){this._isUserControllingRotate=!1;const s=$i(e,this.minAzimuthAngle,this.maxAzimuthAngle),a=$i(t,this.minPolarAngle,this.maxPolarAngle);this._sphericalEnd.theta=s,this._sphericalEnd.phi=a,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,i||(this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi);const r=!i||Rt(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Rt(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(r)}dolly(e,t=!1){return this.dollyTo(this._sphericalEnd.radius-e,t)}dollyTo(e,t=!1){return this._isUserControllingDolly=!1,this._lastDollyDirection=Jr.NONE,this._changedDolly=0,this._dollyToNoClamp($i(e,this.minDistance,this.maxDistance),t)}_dollyToNoClamp(e,t=!1){const i=this._sphericalEnd.radius;if(this.colliderMeshes.length>=1){const r=this._collisionTest(),o=Rt(r,this._spherical.radius);if(!(i>e)&&o)return Promise.resolve();this._sphericalEnd.radius=Math.min(e,r)}else this._sphericalEnd.radius=e;this._needsUpdate=!0,t||(this._spherical.radius=this._sphericalEnd.radius);const a=!t||Rt(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(a)}dollyInFixed(e,t=!1){this._targetEnd.add(this._getCameraDirection(xl).multiplyScalar(e)),t||this._target.copy(this._targetEnd);const i=!t||Rt(this._target.x,this._targetEnd.x,this.restThreshold)&&Rt(this._target.y,this._targetEnd.y,this.restThreshold)&&Rt(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(i)}zoom(e,t=!1){return this.zoomTo(this._zoomEnd+e,t)}zoomTo(e,t=!1){this._isUserControllingZoom=!1,this._zoomEnd=$i(e,this.minZoom,this.maxZoom),this._needsUpdate=!0,t||(this._zoom=this._zoomEnd);const i=!t||Rt(this._zoom,this._zoomEnd,this.restThreshold);return this._changedZoom=0,this._createOnRestPromise(i)}pan(e,t,i=!1){return console.warn("`pan` has been renamed to `truck`"),this.truck(e,t,i)}truck(e,t,i=!1){this._camera.updateMatrix(),ls.setFromMatrixColumn(this._camera.matrix,0),cs.setFromMatrixColumn(this._camera.matrix,1),ls.multiplyScalar(e),cs.multiplyScalar(-t);const s=pt.copy(ls).add(cs),a=Mt.copy(this._targetEnd).add(s);return this.moveTo(a.x,a.y,a.z,i)}forward(e,t=!1){pt.setFromMatrixColumn(this._camera.matrix,0),pt.crossVectors(this._camera.up,pt),pt.multiplyScalar(e);const i=Mt.copy(this._targetEnd).add(pt);return this.moveTo(i.x,i.y,i.z,t)}elevate(e,t=!1){return pt.copy(this._camera.up).multiplyScalar(e),this.moveTo(this._targetEnd.x+pt.x,this._targetEnd.y+pt.y,this._targetEnd.z+pt.z,t)}moveTo(e,t,i,s=!1){this._isUserControllingTruck=!1;const a=pt.set(e,t,i).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,a,this.boundaryFriction),this._needsUpdate=!0,s||this._target.copy(this._targetEnd);const r=!s||Rt(this._target.x,this._targetEnd.x,this.restThreshold)&&Rt(this._target.y,this._targetEnd.y,this.restThreshold)&&Rt(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(r)}lookInDirectionOf(e,t,i,s=!1){const o=pt.set(e,t,i).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd);return this.setPosition(o.x,o.y,o.z,s)}fitToBox(e,t,{cover:i=!1,paddingLeft:s=0,paddingRight:a=0,paddingBottom:r=0,paddingTop:o=0}={}){const l=[],c=e.isBox3?to.copy(e):to.setFromObject(e);c.isEmpty()&&(console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve());const u=jv(this._sphericalEnd.theta,Yv),d=jv(this._sphericalEnd.phi,Yv);l.push(this.rotateTo(u,d,t));const h=pt.setFromSpherical(this._sphericalEnd).normalize(),f=nb.setFromUnitVectors(h,Qp),p=Rt(Math.abs(h.y),1);p&&f.multiply(tm.setFromAxisAngle(Hu,u)),f.multiply(this._yAxisUpSpaceInverse);const g=tb.makeEmpty();Mt.copy(c.min).applyQuaternion(f),g.expandByPoint(Mt),Mt.copy(c.min).setX(c.max.x).applyQuaternion(f),g.expandByPoint(Mt),Mt.copy(c.min).setY(c.max.y).applyQuaternion(f),g.expandByPoint(Mt),Mt.copy(c.max).setZ(c.min.z).applyQuaternion(f),g.expandByPoint(Mt),Mt.copy(c.min).setZ(c.max.z).applyQuaternion(f),g.expandByPoint(Mt),Mt.copy(c.max).setY(c.min.y).applyQuaternion(f),g.expandByPoint(Mt),Mt.copy(c.max).setX(c.min.x).applyQuaternion(f),g.expandByPoint(Mt),Mt.copy(c.max).applyQuaternion(f),g.expandByPoint(Mt),g.min.x-=s,g.min.y-=r,g.max.x+=a,g.max.y+=o,f.setFromUnitVectors(Qp,h),p&&f.premultiply(tm.invert()),f.premultiply(this._yAxisUpSpace);const _=g.getSize(pt),m=g.getCenter(Mt).applyQuaternion(f);if(Ha(this._camera)){const v=this.getDistanceToFitBox(_.x,_.y,_.z,i);l.push(this.moveTo(m.x,m.y,m.z,t)),l.push(this.dollyTo(v,t)),l.push(this.setFocalOffset(0,0,0,t))}else if(ra(this._camera)){const v=this._camera,y=v.right-v.left,b=v.top-v.bottom,S=i?Math.max(y/_.x,b/_.y):Math.min(y/_.x,b/_.y);l.push(this.moveTo(m.x,m.y,m.z,t)),l.push(this.zoomTo(S,t)),l.push(this.setFocalOffset(0,0,0,t))}return Promise.all(l)}fitToSphere(e,t){const i=[],a="isObject3D"in e?f_.createBoundingSphere(e,em):em.copy(e);if(i.push(this.moveTo(a.center.x,a.center.y,a.center.z,t)),Ha(this._camera)){const r=this.getDistanceToFitSphere(a.radius);i.push(this.dollyTo(r,t))}else if(ra(this._camera)){const r=this._camera.right-this._camera.left,o=this._camera.top-this._camera.bottom,l=2*a.radius,c=Math.min(r/l,o/l);i.push(this.zoomTo(c,t))}return i.push(this.setFocalOffset(0,0,0,t)),Promise.all(i)}setLookAt(e,t,i,s,a,r,o=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Jr.NONE,this._changedDolly=0;const l=Mt.set(s,a,r),c=pt.set(e,t,i);this._targetEnd.copy(l),this._sphericalEnd.setFromVector3(c.sub(l).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,o||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const u=!o||Rt(this._target.x,this._targetEnd.x,this.restThreshold)&&Rt(this._target.y,this._targetEnd.y,this.restThreshold)&&Rt(this._target.z,this._targetEnd.z,this.restThreshold)&&Rt(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Rt(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Rt(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(u)}lerpLookAt(e,t,i,s,a,r,o,l,c,u,d,h,f,p=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Jr.NONE,this._changedDolly=0;const g=pt.set(s,a,r),_=Mt.set(e,t,i);Mi.setFromVector3(_.sub(g).applyQuaternion(this._yAxisUpSpace));const m=eo.set(u,d,h),v=Mt.set(o,l,c);wl.setFromVector3(v.sub(m).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(g.lerp(m,f));const y=wl.theta-Mi.theta,b=wl.phi-Mi.phi,S=wl.radius-Mi.radius;this._sphericalEnd.set(Mi.radius+S*f,Mi.phi+b*f,Mi.theta+y*f),this.normalizeRotations(),this._needsUpdate=!0,p||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const x=!p||Rt(this._target.x,this._targetEnd.x,this.restThreshold)&&Rt(this._target.y,this._targetEnd.y,this.restThreshold)&&Rt(this._target.z,this._targetEnd.z,this.restThreshold)&&Rt(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Rt(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Rt(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(x)}setPosition(e,t,i,s=!1){return this.setLookAt(e,t,i,this._targetEnd.x,this._targetEnd.y,this._targetEnd.z,s)}setTarget(e,t,i,s=!1){const a=this.getPosition(pt),r=this.setLookAt(a.x,a.y,a.z,e,t,i,s);return this._sphericalEnd.phi=$i(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),r}setFocalOffset(e,t,i,s=!1){this._isUserControllingOffset=!1,this._focalOffsetEnd.set(e,t,i),this._needsUpdate=!0,s||this._focalOffset.copy(this._focalOffsetEnd);const a=!s||Rt(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&Rt(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&Rt(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(a)}setOrbitPoint(e,t,i){this._camera.updateMatrixWorld(),ls.setFromMatrixColumn(this._camera.matrixWorldInverse,0),cs.setFromMatrixColumn(this._camera.matrixWorldInverse,1),Va.setFromMatrixColumn(this._camera.matrixWorldInverse,2);const s=pt.set(e,t,i),a=s.distanceTo(this._camera.position),r=s.sub(this._camera.position);ls.multiplyScalar(r.x),cs.multiplyScalar(r.y),Va.multiplyScalar(r.z),pt.copy(ls).add(cs).add(Va),pt.z=pt.z+a,this.dollyTo(a,!1),this.setFocalOffset(-pt.x,pt.y,-pt.z,!1),this.moveTo(e,t,i,!1)}setBoundary(e){if(!e){this._boundary.min.set(-1/0,-1/0,-1/0),this._boundary.max.set(1/0,1/0,1/0),this._needsUpdate=!0;return}this._boundary.copy(e),this._boundary.clampPoint(this._targetEnd,this._targetEnd),this._needsUpdate=!0}setViewport(e,t,i,s){if(e===null){this._viewport=null;return}this._viewport=this._viewport||new nt.Vector4,typeof e=="number"?this._viewport.set(e,t,i,s):this._viewport.copy(e)}getDistanceToFitBox(e,t,i,s=!1){if(Zp(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const a=e/t,r=this._camera.getEffectiveFOV()*yl,o=this._camera.aspect;return((s?a>o:at.pointerId===e)}_findPointerByMouseButton(e){return this._activePointers.find(t=>t.mouseButton===e)}_disposePointer(e){this._activePointers.splice(this._activePointers.indexOf(e),1)}_encloseToBoundary(e,t,i){const s=t.lengthSq();if(s===0)return e;const a=Mt.copy(t).add(e),o=this._boundary.clampPoint(a,eo).sub(a),l=o.lengthSq();if(l===0)return e.add(t);if(l===s)return e;if(i===0)return e.add(t).add(o);{const c=1+i*l/t.dot(o);return e.add(Mt.copy(t).multiplyScalar(c)).add(o.multiplyScalar(1-i))}}_updateNearPlaneCorners(){if(Ha(this._camera)){const e=this._camera,t=e.near,i=e.getEffectiveFOV()*yl,s=Math.tan(i*.5)*t,a=s*e.aspect;this._nearPlaneCorners[0].set(-a,-s,0),this._nearPlaneCorners[1].set(a,-s,0),this._nearPlaneCorners[2].set(a,s,0),this._nearPlaneCorners[3].set(-a,s,0)}else if(ra(this._camera)){const e=this._camera,t=1/e.zoom,i=e.left*t,s=e.right*t,a=e.top*t,r=e.bottom*t;this._nearPlaneCorners[0].set(i,a,0),this._nearPlaneCorners[1].set(s,a,0),this._nearPlaneCorners[2].set(s,r,0),this._nearPlaneCorners[3].set(i,r,0)}}_collisionTest(){let e=1/0;if(!(this.colliderMeshes.length>=1)||Zp(this._camera,"_collisionTest"))return e;const i=this._getTargetDirection(xl);nm.lookAt(Jv,i,this._camera.up);for(let s=0;s<4;s++){const a=Mt.copy(this._nearPlaneCorners[s]);a.applyMatrix4(nm);const r=eo.addVectors(this._target,a);Vu.set(r,i),Vu.far=this._spherical.radius+1;const o=Vu.intersectObjects(this.colliderMeshes);o.length!==0&&o[0].distance{const i=()=>{this.removeEventListener("rest",i),t()};this.addEventListener("rest",i)}))}_addAllEventListeners(e){}_removeAllEventListeners(){}get dampingFactor(){return console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead."),0}set dampingFactor(e){console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead.")}get draggingDampingFactor(){return console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead."),0}set draggingDampingFactor(e){console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead.")}static createBoundingSphere(e,t=new nt.Sphere){const i=t,s=i.center;to.makeEmpty(),e.traverseVisible(r=>{r.isMesh&&to.expandByObject(r)}),to.getCenter(s);let a=0;return e.traverseVisible(r=>{if(!r.isMesh)return;const o=r;if(!o.geometry)return;const l=o.geometry.clone();l.applyMatrix4(o.matrixWorld);const u=l.attributes.position;for(let d=0,h=u.count;di.preventDefault()),this.isFollowingViewer=!1,this.followTargetPosition=new T,this.followTargetQuaternion=new ht,this.followPositionLerpFactor=.12,this.followRotationSlerpFactor=.1,this.hasFollowTarget=!1,this.isRightMouseDown=!1,this.lastMouseX=null,this.lastMouseY=null,this.savedCameraState=null,this.isInReplayMode=!1}setMode(e){if(this.mode=e,e==="ballOrbit"){if(this.controls.enabled=!0,this.lastBallOrbitPos=null,this.ballOrbitScrollHandler||(this.ballOrbitScrollHandler=t=>{if(this.mode==="ballOrbit"&&!this.isFollowingViewer){t.preventDefault();const i=Math.max(this.controls.distance*.2,100);t.deltaY>0?this.controls.dolly(-i,!0):this.controls.dolly(i,!0)}},this.domElement.addEventListener("wheel",this.ballOrbitScrollHandler,{passive:!1})),this.targetBall){const t=this.targetBall.position;this.camera.position.distanceTo(t),this.controls.setLookAt(this.camera.position.x,this.camera.position.y,this.camera.position.z,t.x,t.y,t.z,!1)}return}if(e==="free"){if(this.controls.enabled=!1,!this.freeCamKeys){this.freeCamKeys={forward:!1,backward:!1,left:!1,right:!1,up:!1,down:!1},this.freeCamSpeed=2e3,this.freeCamRotation={yaw:0,pitch:0};const t=new T;this.camera.getWorldDirection(t),this.freeCamRotation.yaw=Math.atan2(t.x,t.z),this.freeCamRotation.pitch=Math.asin(-t.y),this.onKeyDown=i=>this.handleFreeCamKeyDown(i),this.onKeyUp=i=>this.handleFreeCamKeyUp(i),this.onMouseMove=i=>this.handleFreeCamMouseMove(i),this.onMouseDown=i=>{i.button===2&&this.mode==="free"&&!this.isFollowingViewer&&(this.isRightMouseDown=!0,this.domElement.requestPointerLock?.())},this.onMouseUp=i=>{i.button===2&&(this.isRightMouseDown=!1,document.pointerLockElement===this.domElement&&document.exitPointerLock?.())},this.onPointerLockChange=()=>{document.pointerLockElement!==this.domElement&&(this.isRightMouseDown=!1)},this.onMouseLeave=()=>{document.pointerLockElement!==this.domElement&&(this.isRightMouseDown=!1)},this.onWindowBlur=()=>{this.isRightMouseDown=!1,document.pointerLockElement===this.domElement&&document.exitPointerLock?.(),this.freeCamKeys&&(this.freeCamKeys.forward=!1,this.freeCamKeys.backward=!1,this.freeCamKeys.left=!1,this.freeCamKeys.right=!1,this.freeCamKeys.up=!1,this.freeCamKeys.down=!1)},this.onVisibilityChange=()=>{document.hidden&&(this.isRightMouseDown=!1,document.pointerLockElement===this.domElement&&document.exitPointerLock?.(),this.freeCamKeys&&(this.freeCamKeys.forward=!1,this.freeCamKeys.backward=!1,this.freeCamKeys.left=!1,this.freeCamKeys.right=!1,this.freeCamKeys.up=!1,this.freeCamKeys.down=!1))},document.addEventListener("keydown",this.onKeyDown),document.addEventListener("keyup",this.onKeyUp),document.addEventListener("mousemove",this.onMouseMove),this.domElement.addEventListener("mousedown",this.onMouseDown),document.addEventListener("mouseup",this.onMouseUp),document.addEventListener("pointerlockchange",this.onPointerLockChange),this.domElement.addEventListener("mouseleave",this.onMouseLeave),window.addEventListener("blur",this.onWindowBlur),document.addEventListener("visibilitychange",this.onVisibilityChange)}this.isRightMouseDown=!1}else this.controls.enabled=!1,this.lastIsBallCam=null,this.currentBlend=0,this.targetBlend=0}setTargetCar(e){if(this.targetCar!==e&&(this.currentBallCamAngle=null,this.targetCar&&e)){this.targetHandoff={elapsed:0,duration:_U,startPosition:this.camera.position.clone(),startQuaternion:this.camera.quaternion.clone()};const t=new T().subVectors(this.camera.position,e.position);t.y=0,t.length()>.01&&(t.normalize(),this.smoothedCarYaw=Math.atan2(-t.x,-t.z)),this.lastCarPos&&this.lastCarPos.copy(e.position)}this.targetCar=e}setTargetBall(e){this.targetBall=e}handleFreeCamKeyDown(e){if(this.mode!=="free"||this.isFollowingViewer)return;const t=e.target;if(!(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable))switch(e.code){case"KeyW":case"ArrowUp":this.freeCamKeys.forward=!0;break;case"KeyS":case"ArrowDown":this.freeCamKeys.backward=!0;break;case"KeyA":case"ArrowLeft":this.freeCamKeys.left=!0;break;case"KeyD":case"ArrowRight":this.freeCamKeys.right=!0;break;case"Space":this.freeCamKeys.up=!0;break;case"ShiftLeft":case"ShiftRight":this.freeCamKeys.down=!0;break}}handleFreeCamKeyUp(e){switch(e.code){case"KeyW":case"ArrowUp":this.freeCamKeys.forward=!1;break;case"KeyS":case"ArrowDown":this.freeCamKeys.backward=!1;break;case"KeyA":case"ArrowLeft":this.freeCamKeys.left=!1;break;case"KeyD":case"ArrowRight":this.freeCamKeys.right=!1;break;case"Space":this.freeCamKeys.up=!1;break;case"ShiftLeft":case"ShiftRight":this.freeCamKeys.down=!1;break}}handleFreeCamMouseMove(e){if(this.mode!=="free"||!this.isRightMouseDown||this.isFollowingViewer)return;const t=e.movementX||0,i=e.movementY||0,s=.003;this.freeCamRotation.yaw-=t*s,this.freeCamRotation.pitch+=i*s,this.freeCamRotation.pitch=Math.max(-Math.PI/2+.01,Math.min(Math.PI/2-.01,this.freeCamRotation.pitch))}updateFreeCam(e){if(!this.freeCamKeys)return;const t=new T(Math.sin(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch),-Math.sin(this.freeCamRotation.pitch),Math.cos(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch));t.normalize();const i=new T(Math.sin(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch),-Math.sin(this.freeCamRotation.pitch),Math.cos(this.freeCamRotation.yaw)*Math.cos(this.freeCamRotation.pitch));i.normalize();const s=new T(Math.sin(this.freeCamRotation.yaw-Math.PI/2),0,Math.cos(this.freeCamRotation.yaw-Math.PI/2)),a=new T(0,1,0),r=new T,o=this.freeCamSpeed*e;this.freeCamKeys.forward&&r.add(i.clone().multiplyScalar(o)),this.freeCamKeys.backward&&r.add(i.clone().multiplyScalar(-o)),this.freeCamKeys.right&&r.add(s.clone().multiplyScalar(o)),this.freeCamKeys.left&&r.add(s.clone().multiplyScalar(-o)),this.freeCamKeys.up&&r.add(a.clone().multiplyScalar(o)),this.freeCamKeys.down&&r.add(a.clone().multiplyScalar(-o)),r.length()>0&&r.normalize().multiplyScalar(o),this.camera.position.add(r);const l=this.camera.position.clone().add(t);this.camera.lookAt(l),this.controls.setLookAt(this.camera.position.x,this.camera.position.y,this.camera.position.z,l.x,l.y,l.z,!1)}update(e,t=!0){if(this.isFollowingViewer){this.updateFollowInterpolation(e);return}if(this.mode==="free"){this.updateFreeCam(e),this.controls.update(e);return}if(this.mode==="ballOrbit"){if(this.targetBall){const p=this.targetBall.position;this.lastBallOrbitPos||(this.lastBallOrbitPos=p.clone());const g=new T().subVectors(p,this.lastBallOrbitPos);if(this.controls.setTarget(p.x,p.y,p.z,!1),g.lengthSq()>.01){const _=new T;this.controls.getPosition(_);const m=_.x+g.x,v=_.y+g.y,y=_.z+g.z;this.controls.setPosition(m,v,y,!1),this.lastBallOrbitPos.copy(p)}}this.controls.update(e);return}if(!this.targetCar){this.controls.update(e);return}const i=this.targetCar.position.clone(),s=this.targetCar.quaternion;if(this.lastIsBallCam!==null&&this.lastIsBallCam!==t&&!t){const p=new T().subVectors(this.camera.position,i);p.y=0,p.length()>.01&&(p.normalize(),this.smoothedCarYaw=Math.atan2(-p.x,-p.z))}this.lastIsBallCam=t;const a=this.calculateCarCamPosition(i,s,e),r=this.calculateBallCamPosition(i,s,e);this.targetBlend=t?1:0;const o=Math.max(.15,Math.min(.6,this.baseDuration/this.transitionSpeed)),l=e/o;this.currentBlendthis.targetBlend&&(this.currentBlend=Math.max(this.currentBlend-l,this.targetBlend));const c=this.currentBlend,u=c*c*(3-2*c),d=new T().lerpVectors(a.cameraPos,r.cameraPos,u);this._tempMatrix.lookAt(a.cameraPos,a.lookTarget,new T(0,1,0)),this._tempQuatCarCam.setFromRotationMatrix(this._tempMatrix),this._tempMatrix.lookAt(r.cameraPos,r.lookTarget,new T(0,1,0)),this._tempQuatBallCam.setFromRotationMatrix(this._tempMatrix),this._tempQuatCarCam.dot(this._tempQuatBallCam)<0&&this._tempQuatBallCam.set(-this._tempQuatBallCam.x,-this._tempQuatBallCam.y,-this._tempQuatBallCam.z,-this._tempQuatBallCam.w);const h=new ht().slerpQuaternions(this._tempQuatCarCam,this._tempQuatBallCam,u);if(this.targetHandoff){this.targetHandoff.elapsed+=e;const p=Math.min(1,this.targetHandoff.elapsed/this.targetHandoff.duration),g=p*p*(3-2*p),_=d.clone(),m=h.clone();d.lerpVectors(this.targetHandoff.startPosition,_,g),h.slerpQuaternions(this.targetHandoff.startQuaternion,m,g),p>=1&&(this.targetHandoff=null)}if(this.camera.position.copy(d),this.camera.quaternion.copy(h),this.followAngle!==0){const p=this.followAngle*Math.PI/180;this.camera.rotateX(-p)}this.currentCamPos||(this.currentCamPos=new T),this.currentLookTarget||(this.currentLookTarget=new T),this.currentCamPos.copy(d);const f=new T(0,0,-1).applyQuaternion(this.camera.quaternion);this.currentLookTarget.copy(d).add(f.multiplyScalar(100)),this.enforceMinHeight()}calculateBallCamPosition(e,t,i=1/60){if(!this.targetBall)return this.calculateCarCamPosition(e,t,i);const s=this.targetBall.position.clone(),a=new T().subVectors(e,s);a.y=0,a.normalize();const r=e.clone().add(a.multiplyScalar(this.followDistance)),o=s.y-e.y,c=Math.min(1,Math.max(0,o/800));r.y=e.y+this.followHeight-c*100,r.y.01)s.normalize(),u=Math.atan2(s.x,s.z);else if(a>.05){s.normalize();let y=Math.atan2(s.x,s.z)-o;for(;y>Math.PI;)y-=Math.PI*2;for(;y<-Math.PI;)y+=Math.PI*2;Math.abs(y)>Math.PI/2?u=o+Math.PI:u=o}else u=o;this.lastCarPos.copy(e),this.smoothedCarYaw===void 0&&(this.smoothedCarYaw=u);let d=u-this.smoothedCarYaw;for(;d>Math.PI;)d-=Math.PI*2;for(;d<-Math.PI;)d+=Math.PI*2;const h=c?this.swivelSpeed*.4:this.swivelSpeed;this.smoothedCarYaw+=d*Math.min(1,h*(1/60));const f=-Math.sin(this.smoothedCarYaw),p=-Math.cos(this.smoothedCarYaw),g=new T(e.x+f*this.followDistance,e.y+this.followHeight,e.z+p*this.followDistance);g.yMath.PI;)s-=Math.PI*2;for(;s<-Math.PI;)s+=Math.PI*2;this.followCurrentOrbitParams.azimuth+=s*.15,this.followCurrentOrbitParams.polar+=(this.followTargetOrbitParams.polar-this.followCurrentOrbitParams.polar)*.15,this.controls.setTarget(t.x,t.y,t.z,!1),this.controls.dollyTo(this.followCurrentOrbitParams.distance,!1),this.controls.rotateTo(this.followCurrentOrbitParams.azimuth,this.followCurrentOrbitParams.polar,!1),this.controls.update(e)}}else{if(this.camera.position.lerp(this.followTargetPosition,this.followPositionLerpFactor),this.camera.quaternion.slerp(this.followTargetQuaternion,this.followRotationSlerpFactor),this.freeCamRotation){const i=new T;this.camera.getWorldDirection(i),this.freeCamRotation.yaw=Math.atan2(i.x,i.z),this.freeCamRotation.pitch=Math.asin(-i.y)}const t=new T;this.camera.getWorldDirection(t),t.multiplyScalar(100).add(this.camera.position),this.controls.setLookAt(this.camera.position.x,this.camera.position.y,this.camera.position.z,t.x,t.y,t.z,!1)}}setDefaultFreecamPosition(){if(this.camera.position.copy(this.defaultFreecamPosition),this.camera.lookAt(this.defaultFreecamLookAt),this.freeCamRotation){const e=new T;this.camera.getWorldDirection(e),this.freeCamRotation.yaw=Math.atan2(e.x,e.z),this.freeCamRotation.pitch=Math.asin(-e.y)}this.controls.setLookAt(this.defaultFreecamPosition.x,this.defaultFreecamPosition.y,this.defaultFreecamPosition.z,this.defaultFreecamLookAt.x,this.defaultFreecamLookAt.y,this.defaultFreecamLookAt.z,!1)}getIsPointerLocked(){return this.isPointerLocked||!1}setPointerLockCallback(e){this.onPointerLockStateChange=e}dispose(){this.controls.dispose(),this.ballOrbitScrollHandler&&this.domElement.removeEventListener("wheel",this.ballOrbitScrollHandler),this.onKeyDown&&document.removeEventListener("keydown",this.onKeyDown),this.onKeyUp&&document.removeEventListener("keyup",this.onKeyUp),this.onMouseMove&&document.removeEventListener("mousemove",this.onMouseMove),this.onMouseDown&&this.domElement.removeEventListener("mousedown",this.onMouseDown),this.onMouseUp&&document.removeEventListener("mouseup",this.onMouseUp),this.onPointerLockChange&&document.removeEventListener("pointerlockchange",this.onPointerLockChange),this.onMouseLeave&&this.domElement.removeEventListener("mouseleave",this.onMouseLeave),this.onWindowBlur&&window.removeEventListener("blur",this.onWindowBlur),this.onVisibilityChange&&document.removeEventListener("visibilitychange",this.onVisibilityChange)}}function sb(n){if(n.pitch===void 0||n.angle!==void 0)return n;const{pitch:e,...t}=n;return{...t,angle:e}}const yU={distance:260,height:90,angle:-4,stiffness:.45,swivelSpeed:4.3,transitionSpeed:1.3,fov:110};function vU(n={}){let e=null,t=null,i=n.mode??(n.follow?"follow":"orbit"),s=n.follow??null,a=n.ballCam??null,r=a??!0,o=sb({...n.settings}),l=1;const c=n.useRecordedSettings!==!1;let u=null;const d=new T;let h=!1;function f(){if(!(!t||!e)){if(t.player.controls.enabled=i==="orbit",i==="free")e.setMode("free");else if(i==="ballOrbit"){const y=_();y&&e.setTargetBall(y),e.setMode("ballOrbit")}else e.setMode("car");u=null}}function p(){return!c||!t||!s?null:t.player.adapter.getPlayer(s)?.cameraSettings??null}function g(){const y={...yU,...p(),...o};return l!==1&&y.distance!==void 0&&(y.distance*=l),y}function _(){if(!t)return null;const y=t.player.actorManager;return y.ballActorId!=null?y.actors[y.ballActorId]??null:null}function m(y){const b=g().fov;if(!b)return;const S=b*Math.PI/180,x=16/9,M=2*Math.atan(Math.tan(S/2)/x),C=2*Math.atan(Math.tan(S/2)/y.aspect),w=Math.max(M,C)*180/Math.PI;Math.abs(y.fov-w)>.1&&(y.fov=w,y.updateProjectionMatrix())}function v(y,b){if(!e)return;if(i==="free"){o.freeCamSpeed&&(e.freeCamSpeed=o.freeCamSpeed),e.update(b);return}if(i==="ballOrbit"){y.ball.object3d&&e.setTargetBall(y.ball.object3d),e.update(b);return}const x=(s?y.cars.find(C=>C.name===s):void 0)?.object3d??null;if(!x){e.update(b);return}e.setTargetCar(x),y.ball.object3d&&e.setTargetBall(y.ball.object3d),e.setFollowSettings(g());const M=s?y.player.adapter.getPlayer(s):void 0;r=a??M?.isBallCam??!0,d.copy(x.position),h=!0,e.update(b,r)}return{id:"camera",setup(y){t=y,e=new gU(y.camera,y.renderer.domElement),f()},beforeRender(y){if(!e||(m(y.camera),i==="orbit"))return;const b=performance.now(),S=u===null?1/60:Math.min(.1,(b-u)/1e3);u=b,v(y,S)},teardown(){i="orbit",t&&(t.player.controls.enabled=!0),e?.dispose(),e=null,t=null},setMode(y){y!==i&&(i=y,f())},getMode(){return i},follow(y){s=y,i="follow",f()},release(){i="orbit",t&&h&&t.player.controls.target.copy(d),f()},getTarget(){return s},setBallCam(y){a=y,y!==null&&(r=y)},getBallCam(){return r},setCameraSettings(y){o=y===null?{}:{...o,...sb(y)}},setDistanceScale(y){l=Math.max(.25,y)},getDistanceScale(){return l},getCameraSettings(){return g()},getRecordedSettings(){const y=p();return y?{...y}:null}}}const bU={"top-left":"top: 8px; left: 8px;","top-right":"top: 8px; right: 8px;","bottom-left":"bottom: 8px; left: 8px;","bottom-right":"bottom: 8px; right: 8px;"};function xU(n={}){const e=n.corner??"top-right",t=n.updateIntervalMs??500,i=()=>typeof n.mount=="function"?n.mount():n.mount??null;let s=null,a=null,r=null,o=0,l=performance.now(),c=0,u=0;const d=typeof n.onSample=="function";return{id:"fps-overlay",setup(h){if(l=performance.now(),o=0,u=h.player.getState().frameIndex,c=u,d)return;const f=i(),p=f!=null;s=document.createElement("div"),s.className="player-fps-overlay",s.style.cssText=p?` display: inline-flex; gap: 10px; align-items: center; font: 600 11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace; color: #c8d4e6; letter-spacing: 0.02em; white-space: nowrap; `:` - position: absolute; ${c3[e]} + position: absolute; ${bU[e]} z-index: 30; pointer-events: none; user-select: none; display: flex; gap: 10px; font: 600 11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace; @@ -3938,7 +3938,7 @@ void main() { border: 1px solid rgba(255, 255, 255, 0.12); border-radius: 6px; padding: 4px 8px; letter-spacing: 0.02em; white-space: nowrap; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6); - `;const g=document.createElement("span");g.append("Render "),a=document.createElement("span"),a.style.color="#7fd4ff",a.textContent="– fps",g.append(a);const _=document.createElement("span");_.append("Replay "),r=document.createElement("span"),r.style.color="#9affc0",r.textContent="– fps",_.append(r),s.append(g,_),f?f.appendChild(s):(getComputedStyle(h.container).position==="static"&&(h.container.style.position="relative"),h.container.appendChild(s))},beforeRender(h){o+=1,u=h.frameIndex;const f=performance.now(),p=f-l;if(pd3(u,i,s,a,n.currentTime))}}function Bu(n){return{...n,setup:n.setup?e=>{n.setup?.(o_(e,n.id))}:void 0,onStateChange:n.onStateChange?e=>{n.onStateChange?.(hM(e,n.id))}:void 0,beforeRender:n.beforeRender?e=>{n.beforeRender?.(h3(e,n.id))}:void 0,teardown:n.teardown?e=>{n.teardown?.(o_(e,n.id))}:void 0}}const f3=255;function Ys(n){return n==null?null:n*100/f3}const p3=1.35,m3="#57a8ff",_3="#ff9c40",g3=256,y3=160,v3=360,b3=225,x3=260,w3=430,fM=18,Jv=120;function S3(n){return n?m3:_3}function T3(n){return n.events.filter(e=>!e.available&&e.playerId)}function pM(n,e){const t=document.createElement("canvas");t.width=g3,t.height=y3;const i=t.getContext("2d");if(!i)throw new Error("Unable to create boost pickup count canvas");i.clearRect(0,0,t.width,t.height),i.textAlign="center",i.textBaseline="middle",i.lineJoin="round",i.font="800 124px sans-serif",i.lineWidth=18,i.strokeStyle="rgba(4, 10, 18, 0.88)",i.strokeText(`${n}`,t.width/2,t.height/2),i.fillStyle=e,i.fillText(`${n}`,t.width/2,t.height/2);const s=new Ec(t);return s.colorSpace=yt,s.needsUpdate=!0,s}function M3(n){n?.dispose()}function E3(n){const e=new Et;e.visible=!1,e.renderOrder=60,e.frustumCulled=!1;const t=pM(1,n),i=new sf({map:t,transparent:!0,depthTest:!1,depthWrite:!1}),s=new af(i);s.scale.set(v3,b3,1),s.renderOrder=62,s.frustumCulled=!1,e.add(s);const a=new je({color:n,transparent:!0,opacity:0,side:ut,depthTest:!1,depthWrite:!1,blending:Vt}),r=new Se(new oi(Jv*.72,Jv,36),a);return r.position.z=fM,r.renderOrder=61,r.frustumCulled=!1,e.add(r),{group:e,textMaterial:i,ringMaterial:a}}function C3(n,e){n.currentCount!==e&&(M3(n.textMaterial.map),n.textMaterial.map=pM(e,n.color),n.textMaterial.needsUpdate=!0,n.currentCount=e)}function A3(n){const e=new Map;for(const s of n.replay.players)e.set(s.id,s);const t=[];for(const s of n.replay.boostPads)for(const a of T3(s))t.push({pad:s,event:a});t.sort((s,a)=>s.event.time!==a.event.time?s.event.time-a.event.time:s.event.frame!==a.event.frame?s.event.frame-a.event.frame:s.pad.index-a.pad.index);const i=[];for(const{pad:s,event:a}of t){if(!a.playerId)continue;const r=e.get(a.playerId);if(!r)continue;const o=S3(r.isTeamZero),{group:l,textMaterial:c,ringMaterial:u}=E3(o);l.position.copy(s.position),n.scene.replayRoot.add(l),i.push({time:a.time,pad:s,event:a,player:r,color:o,currentCount:1,position:new T(s.position.x,s.position.y,s.position.z),size:s.size,group:l,textMaterial:c,ringMaterial:u})}return i}function R3(n,e,t){const i=bt.clamp(e/t,0,1),s=1-Math.pow(1-i,3),a=i*i,r=n.size==="big"?w3:x3,o=n.size==="big"?360:280,l=1+Math.sin(i*Math.PI)*.22;n.group.visible=!0,n.group.position.set(n.position.x,n.position.y,n.position.z+r+s*o),n.group.scale.setScalar(l),n.textMaterial.opacity=Math.max(0,1-a),n.ringMaterial.opacity=Math.max(0,.48*(1-i));const c=n.group.children[1];if(c){const u=.75+s*(n.size==="big"?2.8:1.85);c.scale.setScalar(u),c.position.z=fM-r-s*o}}function P3(n={}){const e=Math.max(.1,n.durationSeconds??p3);let t=[];function i(a){return n.includePickup?.({pad:a.pad,event:a.event,player:a.player})??!0}function s(){for(const a of t)a.group.visible=!1}return{id:"boost-pickup-animation",setup(a){t=A3(a)},beforeRender(a){if(!a.state.boostPickupAnimationEnabled){s();return}const r=a.currentTime-e,o=new Map;for(const l of t){if(l.time>a.currentTime){l.group.visible=!1;continue}if(!i(l)){l.group.visible=!1;continue}const c=(o.get(l.player.id)??0)+1;if(o.set(l.player.id,c),l.time{(r instanceof Se||r instanceof af)&&r.geometry?.dispose()}),a.textMaterial.map?.dispose(),a.textMaterial.dispose(),a.ringMaterial.dispose();t=[]}}}const I3=60,L3=["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"];function k3(n){if(n&&MediaRecorder.isTypeSupported(n))return n;for(const e of L3)if(MediaRecorder.isTypeSupported(e))return e;return""}function D3(n){return n instanceof Error?n.message:String(n)}function O3(n={}){let e=null,t=null,i=[],s=null,a=0,r=0,o="",l=0,c=null,u=null,d=null,h=null,f=!1,p=null;const g=new Set;function _(){return{state:t?t.state==="recording"?"recording":"stopping":c?"error":s?"ready":"idle",elapsedSeconds:r,mimeType:o,sizeBytes:l,error:c}}function m(){const x=_();n.onStatusChange?.(x);for(const M of g)M(x)}function v(){if(!e)throw new Error("Canvas recorder plugin is not installed");return e}function y(x){t=null,h=null,f=!1,s=x,l=x?.size??0,p&&e&&e.player.setState({currentTime:p.currentTime,speed:p.speed,playing:p.playing}),p=null,x&&n.onComplete?.(x),m(),d?.(x),d=null,u=null}function b(x){c=D3(x),t=null,h=null,f=!1,p=null,m(),d?.(null),d=null,u=null}const S={id:"canvas-recorder",setup(x){e=x},beforeRender(x){t?.state==="recording"&&(r=(performance.now()-a)/1e3,m()),t?.state==="recording"&&h!==null&&x.currentTime>=h&&S.stop()},onStateChange(x){f&&t?.state==="recording"&&!x.state.playing&&r>0&&S.stop()},teardown(){t?.state==="recording"&&t.stop(),e=null,t=null,h=null,f=!1,p=null,d?.(null),d=null,u=null,g.clear()},start(x={}){const M=v();if(t?.state==="recording")throw new Error("Canvas recording is already in progress");if(typeof MediaRecorder>"u")throw new Error("MediaRecorder is not available in this browser");const C=M.scene.renderer.domElement;if(!C.captureStream)throw new Error("Canvas captureStream is not available in this browser");c=null,s=null,i=[],l=0,r=0,a=performance.now(),o=k3(x.mimeType??n.mimeType);const w=Math.max(1,x.fps??n.fps??I3),E=C.captureStream(w);t=new MediaRecorder(E,{mimeType:o,videoBitsPerSecond:x.videoBitsPerSecond??n.videoBitsPerSecond}),u=new Promise(R=>{d=R}),t.addEventListener("dataavailable",R=>{R.data.size>0&&(i.push(R.data),l+=R.data.size,m())}),t.addEventListener("stop",()=>{E.getTracks().forEach(R=>R.stop()),y(new Blob(i,{type:o||"video/webm"}))},{once:!0}),t.addEventListener("error",R=>{E.getTracks().forEach(L=>L.stop()),b(R.error??R)},{once:!0}),t.start(1e3),m()},stop(){if(!t)return Promise.resolve(s);if(t.state==="inactive")return u??Promise.resolve(s);const x=u??new Promise(M=>{d=M});return t.stop(),m(),x},clear(){if(t?.state==="recording")throw new Error("Cannot clear a recording while recording is in progress");s=null,i=[],l=0,r=0,c=null,m()},getRecording(){return s},getStatus(){return _()},subscribe(x){return g.add(x),x(_()),()=>{g.delete(x)}},recordRange(x={}){const M=v(),C=M.player.getState();(x.restorePlaybackState??!0)&&(p=C);const w=x.playbackRate??C.speed,E=x.startTime??C.currentTime;h=x.endTime??C.duration,f=!0,M.player.setState({currentTime:E,speed:w,playing:!1}),S.start(x);const R=u;return M.player.play(),(R??Promise.resolve(null)).then(L=>{if(!L)throw new Error("Recording stopped without producing a video");return L})},recordFullReplay(x={}){return S.recordRange({...x,startTime:x.startTime??0,endTime:x.endTime??v().replay.duration})}};return S}const Qv="subtr-actor-timeline-overlay-styles";function F3(){if(document.getElementById(Qv))return;const n=document.createElement("style");n.id=Qv,n.textContent=` + `;const g=document.createElement("span");g.append("Render "),a=document.createElement("span"),a.style.color="#7fd4ff",a.textContent="– fps",g.append(a);const _=document.createElement("span");_.append("Replay "),r=document.createElement("span"),r.style.color="#9affc0",r.textContent="– fps",_.append(r),s.append(g,_),f?f.appendChild(s):(getComputedStyle(h.container).position==="static"&&(h.container.style.position="relative"),h.container.appendChild(s))},beforeRender(h){o+=1,u=h.frameIndex;const f=performance.now(),p=f-l;if(pwU(u,i,s,a,n.currentTime))}}function Gu(n){return{...n,setup:n.setup?e=>{n.setup?.(p_(e,n.id))}:void 0,onStateChange:n.onStateChange?e=>{n.onStateChange?.(xM(e,n.id))}:void 0,beforeRender:n.beforeRender?e=>{n.beforeRender?.(SU(e,n.id))}:void 0,teardown:n.teardown?e=>{n.teardown?.(p_(e,n.id))}:void 0}}const TU=255;function Ys(n){return n==null?null:n*100/TU}const MU=1.35,EU="#57a8ff",CU="#ff9c40",AU=256,RU=160,PU=360,IU=225,LU=260,kU=430,wM=18,ab=120;function DU(n){return n?EU:CU}function OU(n){return n.events.filter(e=>!e.available&&e.playerId)}function SM(n,e){const t=document.createElement("canvas");t.width=AU,t.height=RU;const i=t.getContext("2d");if(!i)throw new Error("Unable to create boost pickup count canvas");i.clearRect(0,0,t.width,t.height),i.textAlign="center",i.textBaseline="middle",i.lineJoin="round",i.font="800 124px sans-serif",i.lineWidth=18,i.strokeStyle="rgba(4, 10, 18, 0.88)",i.strokeText(`${n}`,t.width/2,t.height/2),i.fillStyle=e,i.fillText(`${n}`,t.width/2,t.height/2);const s=new Pc(t);return s.colorSpace=yt,s.needsUpdate=!0,s}function FU(n){n?.dispose()}function NU(n){const e=new Et;e.visible=!1,e.renderOrder=60,e.frustumCulled=!1;const t=SM(1,n),i=new uf({map:t,transparent:!0,depthTest:!1,depthWrite:!1}),s=new df(i);s.scale.set(PU,IU,1),s.renderOrder=62,s.frustumCulled=!1,e.add(s);const a=new je({color:n,transparent:!0,opacity:0,side:ut,depthTest:!1,depthWrite:!1,blending:Vt}),r=new Se(new oi(ab*.72,ab,36),a);return r.position.z=wM,r.renderOrder=61,r.frustumCulled=!1,e.add(r),{group:e,textMaterial:i,ringMaterial:a}}function UU(n,e){n.currentCount!==e&&(FU(n.textMaterial.map),n.textMaterial.map=SM(e,n.color),n.textMaterial.needsUpdate=!0,n.currentCount=e)}function BU(n){const e=new Map;for(const s of n.replay.players)e.set(s.id,s);const t=[];for(const s of n.replay.boostPads)for(const a of OU(s))t.push({pad:s,event:a});t.sort((s,a)=>s.event.time!==a.event.time?s.event.time-a.event.time:s.event.frame!==a.event.frame?s.event.frame-a.event.frame:s.pad.index-a.pad.index);const i=[];for(const{pad:s,event:a}of t){if(!a.playerId)continue;const r=e.get(a.playerId);if(!r)continue;const o=DU(r.isTeamZero),{group:l,textMaterial:c,ringMaterial:u}=NU(o);l.position.copy(s.position),n.scene.replayRoot.add(l),i.push({time:a.time,pad:s,event:a,player:r,color:o,currentCount:1,position:new T(s.position.x,s.position.y,s.position.z),size:s.size,group:l,textMaterial:c,ringMaterial:u})}return i}function zU(n,e,t){const i=bt.clamp(e/t,0,1),s=1-Math.pow(1-i,3),a=i*i,r=n.size==="big"?kU:LU,o=n.size==="big"?360:280,l=1+Math.sin(i*Math.PI)*.22;n.group.visible=!0,n.group.position.set(n.position.x,n.position.y,n.position.z+r+s*o),n.group.scale.setScalar(l),n.textMaterial.opacity=Math.max(0,1-a),n.ringMaterial.opacity=Math.max(0,.48*(1-i));const c=n.group.children[1];if(c){const u=.75+s*(n.size==="big"?2.8:1.85);c.scale.setScalar(u),c.position.z=wM-r-s*o}}function HU(n={}){const e=Math.max(.1,n.durationSeconds??MU);let t=[];function i(a){return n.includePickup?.({pad:a.pad,event:a.event,player:a.player})??!0}function s(){for(const a of t)a.group.visible=!1}return{id:"boost-pickup-animation",setup(a){t=BU(a)},beforeRender(a){if(!a.state.boostPickupAnimationEnabled){s();return}const r=a.currentTime-e,o=new Map;for(const l of t){if(l.time>a.currentTime){l.group.visible=!1;continue}if(!i(l)){l.group.visible=!1;continue}const c=(o.get(l.player.id)??0)+1;if(o.set(l.player.id,c),l.time{(r instanceof Se||r instanceof df)&&r.geometry?.dispose()}),a.textMaterial.map?.dispose(),a.textMaterial.dispose(),a.ringMaterial.dispose();t=[]}}}const VU=60,GU=["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"];function $U(n){if(n&&MediaRecorder.isTypeSupported(n))return n;for(const e of GU)if(MediaRecorder.isTypeSupported(e))return e;return""}function WU(n){return n instanceof Error?n.message:String(n)}function XU(n={}){let e=null,t=null,i=[],s=null,a=0,r=0,o="",l=0,c=null,u=null,d=null,h=null,f=!1,p=null;const g=new Set;function _(){return{state:t?t.state==="recording"?"recording":"stopping":c?"error":s?"ready":"idle",elapsedSeconds:r,mimeType:o,sizeBytes:l,error:c}}function m(){const x=_();n.onStatusChange?.(x);for(const M of g)M(x)}function v(){if(!e)throw new Error("Canvas recorder plugin is not installed");return e}function y(x){t=null,h=null,f=!1,s=x,l=x?.size??0,p&&e&&e.player.setState({currentTime:p.currentTime,speed:p.speed,playing:p.playing}),p=null,x&&n.onComplete?.(x),m(),d?.(x),d=null,u=null}function b(x){c=WU(x),t=null,h=null,f=!1,p=null,m(),d?.(null),d=null,u=null}const S={id:"canvas-recorder",setup(x){e=x},beforeRender(x){t?.state==="recording"&&(r=(performance.now()-a)/1e3,m()),t?.state==="recording"&&h!==null&&x.currentTime>=h&&S.stop()},onStateChange(x){f&&t?.state==="recording"&&!x.state.playing&&r>0&&S.stop()},teardown(){t?.state==="recording"&&t.stop(),e=null,t=null,h=null,f=!1,p=null,d?.(null),d=null,u=null,g.clear()},start(x={}){const M=v();if(t?.state==="recording")throw new Error("Canvas recording is already in progress");if(typeof MediaRecorder>"u")throw new Error("MediaRecorder is not available in this browser");const C=M.scene.renderer.domElement;if(!C.captureStream)throw new Error("Canvas captureStream is not available in this browser");c=null,s=null,i=[],l=0,r=0,a=performance.now(),o=$U(x.mimeType??n.mimeType);const w=Math.max(1,x.fps??n.fps??VU),E=C.captureStream(w);t=new MediaRecorder(E,{mimeType:o,videoBitsPerSecond:x.videoBitsPerSecond??n.videoBitsPerSecond}),u=new Promise(R=>{d=R}),t.addEventListener("dataavailable",R=>{R.data.size>0&&(i.push(R.data),l+=R.data.size,m())}),t.addEventListener("stop",()=>{E.getTracks().forEach(R=>R.stop()),y(new Blob(i,{type:o||"video/webm"}))},{once:!0}),t.addEventListener("error",R=>{E.getTracks().forEach(L=>L.stop()),b(R.error??R)},{once:!0}),t.start(1e3),m()},stop(){if(!t)return Promise.resolve(s);if(t.state==="inactive")return u??Promise.resolve(s);const x=u??new Promise(M=>{d=M});return t.stop(),m(),x},clear(){if(t?.state==="recording")throw new Error("Cannot clear a recording while recording is in progress");s=null,i=[],l=0,r=0,c=null,m()},getRecording(){return s},getStatus(){return _()},subscribe(x){return g.add(x),x(_()),()=>{g.delete(x)}},recordRange(x={}){const M=v(),C=M.player.getState();(x.restorePlaybackState??!0)&&(p=C);const w=x.playbackRate??C.speed,E=x.startTime??C.currentTime;h=x.endTime??C.duration,f=!0,M.player.setState({currentTime:E,speed:w,playing:!1}),S.start(x);const R=u;return M.player.play(),(R??Promise.resolve(null)).then(L=>{if(!L)throw new Error("Recording stopped without producing a video");return L})},recordFullReplay(x={}){return S.recordRange({...x,startTime:x.startTime??0,endTime:x.endTime??v().replay.duration})}};return S}const rb="subtr-actor-timeline-overlay-styles";function KU(){if(document.getElementById(rb))return;const n=document.createElement("style");n.id=rb,n.textContent=` .sap-tl-root { position: absolute; inset: 0; @@ -4411,8 +4411,8 @@ void main() { font-size: 0.72rem; } } - `,document.head.append(n)}const N3=new Set(["goal","save","bookmark"]),U3=.2,Zp=60,B3=2,z3=4,H3=.01,eb=.01;function l_(n){if(!Number.isFinite(n))return"--:--.--";const e=Math.max(0,n),t=Math.floor(e/60),i=Math.floor(e%60),s=Math.floor((e-Math.floor(e))*100);return`${t}:${String(i).padStart(2,"0")}.${String(s).padStart(2,"0")}`}function tb(n){switch(n.kind){case"goal":return 5;case"demo":return 4;case"save":return 3;case"assist":return 2;case"shot":case"bookmark":return 1;default:return 0}}function V3(n){switch(n.kind){case"goal":case"goal-context":case"goal-tag":return z3;default:return B3}}function ny(n){return n.seekTime!==void 0&&Number.isFinite(n.seekTime)?Math.max(0,n.seekTime):Number.isFinite(n.time)?Math.max(0,n.time-V3(n)):0}function G3(n){if(n.color)return n.color;if(n.isTeamZero===!0)return"#3b82f6";if(n.isTeamZero===!1)return"#f59e0b";switch(n.kind){case"goal":return"#f5f7fa";case"demo":return"#ef4444";case"save":return"#34d399";case"assist":return"#c084fc";case"shot":return"#60a5fa";case"bookmark":return"#facc15";default:return"#d1d9e0"}}function $3(n){if(n.events.length>1)return`${n.events.length}`;const e=n.events[0];return e?e.shortLabel&&e.shortLabel.trim()!==""?e.shortLabel.slice(0,3).toUpperCase():e.kind.slice(0,1).toUpperCase():""}function c_(n){return[...n].sort((e,t)=>{const i=tb(t)-tb(e);return i!==0?i:e.time-t.time})}function W3(n){return n.events.map(e=>`${l_(e.time)} ${e.label??e.kind}`).join(` -`)}function mM(n){const e=new Map;for(const t of n){const i=t.frame!==void 0?`frame:${t.frame}`:`time:${t.time.toFixed(2)}`,s=e.get(i);if(s){s.events.push(t);continue}e.set(i,{key:i,time:t.time,events:[t]})}return[...e.values()].map(t=>({...t,events:c_(t.events)})).sort((t,i)=>t.time-i.time)}function nb(n){if(n.length<=Zp)return n;const e=n[0]?.time??0,i=(n[n.length-1]?.time??e)-e;if(i<=0)return[{key:"compact:0",time:e,events:c_(n.flatMap(r=>r.events))}];const s=i/Zp,a=new Map;for(const r of n){const o=Math.min(Zp-1,Math.max(0,Math.floor((r.time-e)/s))),l=a.get(o);if(l){l.events.push(...r.events);continue}a.set(o,{key:`compact:${o}`,time:r.time,events:[...r.events]})}return[...a.values()].map(r=>({...r,events:c_(r.events)})).sort((r,o)=>r.time-o.time)}function _M(n,e){return n?typeof n=="function"?n(e):n:[]}function X3(n,e){const t=[];for(const i of n){const s=_M(i.source,e);s.length!==0&&t.push({key:i.key,label:i.label,buckets:mM(s)})}return t}function K3(n,e){return n?typeof n=="function"?n(e):n:[]}function q3(n,e){const t=new Set,i=[];for(const s of n)for(const a of K3(s,e)){const r=a.id;if(r!==void 0){if(t.has(r))continue;t.add(r)}i.push(a)}return i}function Y3(n){const e=new Map;for(const t of n){const i=t.lane??"default",s=t.laneLabel??t.lane??"",a=e.get(i);if(a){a.ranges.push(t);continue}e.set(i,{key:i,label:s,ranges:[t]})}return[...e.values()].map(t=>({...t,ranges:[...t.ranges].sort((i,s)=>i.startTime-s.startTime)}))}function j3(n){return n.color?n.color:n.isTeamZero===!0?"#3b82f6":n.isTeamZero===!1?"#f59e0b":"#d1d9e0"}function Z3(n,e){if(n.replayEvents)return _M(n.replayEvents,e);if(n.includeReplayEvents===!1)return[];const t=new Set(n.replayEventKinds??N3);return e.replay.timelineEvents.filter(i=>t.has(i.kind))}function J3(n,e){const t=e.player.projectReplayTimeToTimeline(ny(n));if(!t.hiddenBySkip)return t.seekTime;const i=Math.min(e.player.getTimelineDuration(),t.timelineTime+H3);return e.player.projectTimelineTimeToReplay(i)}function zu(n,e){return`${n/Math.max(e,1e-4)*100}%`}function Q3(n,e,t){let i=n.timelineTime,s=e.timelineTime;return s<=i&&(n.hiddenBySkip||e.hiddenBySkip)&&(i>=t?(i=Math.max(0,t-eb),s=t):s=Math.min(t,i+eb)),{startTimelineTime:i,endTimelineTime:s}}function eU(n={}){const e=n.pauseWhileScrubbing??!0;let t=0;const i=n.events?[{key:"events:initial",label:n.eventsLabel??"Events",source:n.events}]:[],s=n.ranges?[n.ranges]:[];let a=null,r=null,o=null,l=null,c=null,u=null,d=null,h=null,f=null,p=null,g=null,_=null,m=!1,v="",y=!1,b=!1,S=null,x=[],M=[],C=null;const w=new Map,E=[],R=[],L=[],O=[];let D=0,U=new Set;function F(){S&&(Oe(S),H({...S,state:S.player.getState()}))}function W(){S&&(Z(S),H({...S,state:S.player.getState()}))}function H(X){if(!l||!c||!u||!d||!h||!f||!r)return;const se=X.player.getTimelineCurrentTime(),we=X.player.getTimelineDuration(),Re=[we.toFixed(4),X.state.skipKickoffsEnabled?"1":"0",X.state.skipPostGoalTransitionsEnabled?"1":"0"].join(":");C!==Re&&(Oe(X),Z(X),C=Re),l.min="0",l.max=`${we}`,l.step="0.01",l.value=`${Math.min(se,we)}`,c.dataset.playing=X.state.playing?"true":"false",c.setAttribute("aria-label",X.state.playing?"Pause replay":"Play replay"),c.title=X.state.playing?"Pause replay":"Play replay",u.textContent=X.state.playing?"||":">",d.textContent=X.state.playing?"Pause":"Play",h.textContent=l_(se),f.textContent=`-${l_(we-se)}`,r.dataset.scrubbing=y?"true":"false",De(se);for(const G of R){const j=Math.max(0,G.startTimelineTime),Y=Math.min(we,G.endTimelineTime);if(Math.max(0,Y-j)<=1e-4){G.element.hidden=!0;continue}G.element.hidden=!1,G.element.dataset.active=se>=j&&se<=Y?"true":"false"}const k=zu(Math.min(se,we),we);for(const G of O)G.element.style.left=k;for(const G of L)G.element.style.left=k}function ie(X){let se=0,we=E.length;for(;seD)for(let G=D;G{se.player.seek(J3(Re,se))}),G.dataset.active="false",G.dataset.passed="false";const j={element:G,timelineTime:k.timelineTime,active:!1,passed:!1};return w.set(X.key,j),E.push(j),G}function Oe(X){if(!g||!p)return;g.replaceChildren(),p.replaceChildren(),w.clear(),E.splice(0,E.length),D=0,U=new Set,O.splice(0,O.length);const se=Z3(n,X);x=[],se.length>0&&x.push({key:"replay",label:n.replayEventsLabel??"Replay",buckets:mM(se)}),x.push(...X3(i,X));const we=Math.max(X.player.getTimelineDuration(),1e-4),Re=x[0];if(Re?.key==="replay")for(const G of nb(Re.buckets)){const j=Ke({...G,key:`${Re.key}:${G.key}`},X,we);j&&g.append(j)}const k=x.filter(G=>G.key!=="replay");p.hidden=k.length===0;for(const G of k){const j=document.createElement("div");j.className="sap-tl-event-lane",j.dataset.label=G.label;const Y=document.createElement("span");Y.className="sap-tl-event-lane-label",Y.textContent=G.label,Y.setAttribute("aria-label",G.label),j.append(Y);const Q=document.createElement("div");Q.className="sap-tl-event-lane-track";const ge=document.createElement("div");ge.className="sap-tl-markers";for(const ye of nb(G.buckets)){const We=Ke({...ye,key:`${G.key}:${ye.key}`},X,we);We&&ge.append(We)}const ue=document.createElement("div");ue.className="sap-tl-event-playhead",Q.append(ge,ue),O.push({element:ue}),j.append(Q),p.append(j)}E.sort((G,j)=>G.timelineTime-j.timelineTime)}function Z(X){if(!o)return;o.replaceChildren(),R.splice(0,R.length),L.splice(0,L.length);const se=q3(s,X).filter(Re=>Number.isFinite(Re.startTime)&&Number.isFinite(Re.endTime)&&Re.endTime>Re.startTime);M=Y3(se);const we=Math.max(X.player.getTimelineDuration(),1e-4);if(M.length===0){o.hidden=!0;return}o.hidden=!1;for(const Re of M){const k=document.createElement("div");k.className="sap-tl-range-lane";const G=document.createElement("div");if(G.className="sap-tl-range-lane-track",Re.label){k.dataset.label=Re.label;const Y=document.createElement("span");Y.className="sap-tl-range-lane-label",Y.textContent=Re.label,Y.setAttribute("aria-label",Re.label),k.append(Y)}for(const Y of Re.ranges){const Q=X.player.projectReplayTimeToTimeline(Y.startTime),ge=X.player.projectReplayTimeToTimeline(Y.endTime),{startTimelineTime:ue,endTimelineTime:ye}=Q3(Q,ge,we),We=document.createElement("div");We.className="sap-tl-range-segment",Y.className&&We.classList.add(Y.className),We.style.background=j3(Y),We.title=Y.label??Re.label,We.dataset.active="false",We.style.left=zu(ue,we),We.style.width=zu(Math.max(0,ye-ue),we),G.append(We),R.push({range:Y,element:We,startTimelineTime:ue,endTimelineTime:ye})}const j=document.createElement("div");j.className="sap-tl-range-playhead",G.append(j),L.push({element:j}),k.append(G),o.append(k)}}function ae(){y&&(y=!1,r?.setAttribute("data-scrubbing","false"),b&&S?.player.play(),b=!1)}function Te(){if(y||(y=!0,r?.setAttribute("data-scrubbing","true"),!e))return;const X=S?.player;X&&(b=X.getState().playing,b&&X.pause())}return{id:"timeline-overlay",addEventSource(X,se={}){return i.push({key:se.id??`events:${t++}`,label:se.label??"Events",source:X}),F(),()=>{this.removeEventSource(X)}},removeEventSource(X){const se=i.findIndex(we=>we.source===X);return se<0?!1:(i.splice(se,1),F(),!0)},refreshEvents(){F()},addRangeSource(X){return s.push(X),W(),()=>{this.removeRangeSource(X)}},removeRangeSource(X){const se=s.indexOf(X);return se<0?!1:(s.splice(se,1),W(),!0)},refreshRanges(){W()},setup(X){S=X,F3(),getComputedStyle(X.container).position==="static"&&(m=!0,v=X.container.style.position,X.container.style.position="relative"),a=document.createElement("div"),a.className="sap-tl-root",r=document.createElement("div"),r.className="sap-tl-shell",r.dataset.scrubbing="false";const se=document.createElement("div");se.className="sap-tl-topline";const we=document.createElement("div");we.className="sap-tl-primary",c=document.createElement("button"),c.type="button",c.className="sap-tl-toggle sap-tl-track-toggle",u=document.createElement("span"),u.className="sap-tl-toggle-icon",u.setAttribute("aria-hidden","true"),u.textContent=">",d=document.createElement("span"),d.className="sap-tl-toggle-label",d.textContent="Play",c.append(u,d),c.addEventListener("click",()=>{X.player.togglePlayback()}),h=document.createElement("span"),h.className="sap-tl-current",h.textContent="0:00.00",f=document.createElement("span"),f.className="sap-tl-remaining",f.textContent="-0:00.00",we.append(h),se.append(we,f);const Re=document.createElement("div");Re.className="sap-tl-track-wrap",o=document.createElement("div"),o.className="sap-tl-ranges",o.hidden=!0,p=document.createElement("div"),p.className="sap-tl-event-lanes",p.hidden=!0;const k=document.createElement("div");k.className="sap-tl-track-rail";const G=document.createElement("div");G.className="sap-tl-main-rail",g=document.createElement("div"),g.className="sap-tl-markers",l=document.createElement("input"),l.className="sap-tl-range",l.type="range",l.min="0",l.max=`${X.replay.duration}`,l.step="0.01",l.value="0";const j=()=>{Te()},Y=()=>{l&&X.player.seek(X.player.projectTimelineTimeToReplay(Number(l.value)))},Q=()=>{ae()};l.addEventListener("pointerdown",j),l.addEventListener("input",Y),l.addEventListener("change",Q),window.addEventListener("pointerup",Q),window.addEventListener("pointercancel",Q),_=()=>{l?.removeEventListener("pointerdown",j),l?.removeEventListener("input",Y),l?.removeEventListener("change",Q),window.removeEventListener("pointerup",Q),window.removeEventListener("pointercancel",Q)},k.append(G,g,l),Re.append(o,p,c,k),r.append(se,Re),a.append(r),X.container.append(a),Oe(X),Z(X),H({...X,state:X.player.getState()})},onStateChange(X){S=X,H(X)},teardown(X){_?.(),_=null,ae(),a?.remove(),a=null,r=null,o=null,p=null,l=null,c=null,u=null,d=null,h=null,f=null,g=null,S=null,x=[],M=[],C=null,w.clear(),E.splice(0,E.length),R.splice(0,R.length),L.splice(0,L.length),O.splice(0,O.length),D=0,U=new Set,m&&(X.container.style.position=v,m=!1)}}}function tU(n,e,t={}){const i=new nS(e.raw,{motionSmoothing:t.motionSmoothing,smoothingBlendFactor:t.smoothingBlendFactor,smoothingAnchorInterval:t.smoothingAnchorInterval,timelineCompaction:t.timelineCompaction,disableFrameFiltering:t.disableFrameFiltering}),s=new t3(n,i,t,e.replay);return s.getPlugins().some(a=>a.id==="camera")||s.addPlugin(l3()),s}const nU="https://ballchasing.com",iU=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function sU(n,e){const i=(e instanceof URL?e.href:e).replace(/\/+$/,"");return new URL(`${i}/${n.replace(/^\/+/,"")}`)}function ib(n){return iU.test(n.trim())}function iy(n){const e=n.trim();if(ib(e))return e.toLowerCase();let t;try{t=new URL(e)}catch{throw new Error(`Invalid Ballchasing replay id: ${n}`)}if(!/(^|\.)ballchasing\.com$/i.test(t.hostname))throw new Error(`Invalid Ballchasing replay URL: ${n}`);const i=t.pathname.split("/").filter(Boolean),s=i.findIndex(o=>o==="replay"),a=i.findIndex(o=>o==="replays"),r=s>=0?i[s+1]:a>=0?i[a+1]:void 0;if(!r||!ib(r))throw new Error(`Invalid Ballchasing replay URL: ${n}`);return r.toLowerCase()}function aU(n){return`ballchasing-${iy(n)}.replay`}function rU(n,e=nU){const t=iy(n);return sU(`dl/replay/${encodeURIComponent(t)}`,e)}const u_=250,sb="subtr-actor-ballchasing-overlay-styles",Jp="#3b82f6",ab="#f59e0b";function oU(){if(document.getElementById(sb))return;const n=document.createElement("style");n.id=sb,n.textContent=` + `,document.head.append(n)}const qU=new Set(["goal","save","bookmark"]),YU=.2,im=60,jU=2,ZU=4,JU=.01,ob=.01;function m_(n){if(!Number.isFinite(n))return"--:--.--";const e=Math.max(0,n),t=Math.floor(e/60),i=Math.floor(e%60),s=Math.floor((e-Math.floor(e))*100);return`${t}:${String(i).padStart(2,"0")}.${String(s).padStart(2,"0")}`}function lb(n){switch(n.kind){case"goal":return 5;case"demo":return 4;case"save":return 3;case"assist":return 2;case"shot":case"bookmark":return 1;default:return 0}}function QU(n){switch(n.kind){case"goal":case"goal-context":case"goal-tag":return ZU;default:return jU}}function cy(n){return n.seekTime!==void 0&&Number.isFinite(n.seekTime)?Math.max(0,n.seekTime):Number.isFinite(n.time)?Math.max(0,n.time-QU(n)):0}function e3(n){if(n.color)return n.color;if(n.isTeamZero===!0)return"#3b82f6";if(n.isTeamZero===!1)return"#f59e0b";switch(n.kind){case"goal":return"#f5f7fa";case"demo":return"#ef4444";case"save":return"#34d399";case"assist":return"#c084fc";case"shot":return"#60a5fa";case"bookmark":return"#facc15";default:return"#d1d9e0"}}function t3(n){if(n.events.length>1)return`${n.events.length}`;const e=n.events[0];return e?e.shortLabel&&e.shortLabel.trim()!==""?e.shortLabel.slice(0,3).toUpperCase():e.kind.slice(0,1).toUpperCase():""}function __(n){return[...n].sort((e,t)=>{const i=lb(t)-lb(e);return i!==0?i:e.time-t.time})}function n3(n){return n.events.map(e=>`${m_(e.time)} ${e.label??e.kind}`).join(` +`)}function TM(n){const e=new Map;for(const t of n){const i=t.frame!==void 0?`frame:${t.frame}`:`time:${t.time.toFixed(2)}`,s=e.get(i);if(s){s.events.push(t);continue}e.set(i,{key:i,time:t.time,events:[t]})}return[...e.values()].map(t=>({...t,events:__(t.events)})).sort((t,i)=>t.time-i.time)}function cb(n){if(n.length<=im)return n;const e=n[0]?.time??0,i=(n[n.length-1]?.time??e)-e;if(i<=0)return[{key:"compact:0",time:e,events:__(n.flatMap(r=>r.events))}];const s=i/im,a=new Map;for(const r of n){const o=Math.min(im-1,Math.max(0,Math.floor((r.time-e)/s))),l=a.get(o);if(l){l.events.push(...r.events);continue}a.set(o,{key:`compact:${o}`,time:r.time,events:[...r.events]})}return[...a.values()].map(r=>({...r,events:__(r.events)})).sort((r,o)=>r.time-o.time)}function MM(n,e){return n?typeof n=="function"?n(e):n:[]}function i3(n,e){const t=[];for(const i of n){const s=MM(i.source,e);s.length!==0&&t.push({key:i.key,label:i.label,buckets:TM(s)})}return t}function s3(n,e){return n?typeof n=="function"?n(e):n:[]}function a3(n,e){const t=new Set,i=[];for(const s of n)for(const a of s3(s,e)){const r=a.id;if(r!==void 0){if(t.has(r))continue;t.add(r)}i.push(a)}return i}function r3(n){const e=new Map;for(const t of n){const i=t.lane??"default",s=t.laneLabel??t.lane??"",a=e.get(i);if(a){a.ranges.push(t);continue}e.set(i,{key:i,label:s,ranges:[t]})}return[...e.values()].map(t=>({...t,ranges:[...t.ranges].sort((i,s)=>i.startTime-s.startTime)}))}function o3(n){return n.color?n.color:n.isTeamZero===!0?"#3b82f6":n.isTeamZero===!1?"#f59e0b":"#d1d9e0"}function l3(n,e){if(n.replayEvents)return MM(n.replayEvents,e);if(n.includeReplayEvents===!1)return[];const t=new Set(n.replayEventKinds??qU);return e.replay.timelineEvents.filter(i=>t.has(i.kind))}function c3(n,e){const t=e.player.projectReplayTimeToTimeline(cy(n));if(!t.hiddenBySkip)return t.seekTime;const i=Math.min(e.player.getTimelineDuration(),t.timelineTime+JU);return e.player.projectTimelineTimeToReplay(i)}function $u(n,e){return`${n/Math.max(e,1e-4)*100}%`}function u3(n,e,t){let i=n.timelineTime,s=e.timelineTime;return s<=i&&(n.hiddenBySkip||e.hiddenBySkip)&&(i>=t?(i=Math.max(0,t-ob),s=t):s=Math.min(t,i+ob)),{startTimelineTime:i,endTimelineTime:s}}function d3(n={}){const e=n.pauseWhileScrubbing??!0;let t=0;const i=n.events?[{key:"events:initial",label:n.eventsLabel??"Events",source:n.events}]:[],s=n.ranges?[n.ranges]:[];let a=null,r=null,o=null,l=null,c=null,u=null,d=null,h=null,f=null,p=null,g=null,_=null,m=!1,v="",y=!1,b=!1,S=null,x=[],M=[],C=null;const w=new Map,E=[],R=[],L=[],O=[];let D=0,U=new Set;function F(){S&&(Oe(S),H({...S,state:S.player.getState()}))}function W(){S&&(Z(S),H({...S,state:S.player.getState()}))}function H(X){if(!l||!c||!u||!d||!h||!f||!r)return;const se=X.player.getTimelineCurrentTime(),we=X.player.getTimelineDuration(),Re=[we.toFixed(4),X.state.skipKickoffsEnabled?"1":"0",X.state.skipPostGoalTransitionsEnabled?"1":"0"].join(":");C!==Re&&(Oe(X),Z(X),C=Re),l.min="0",l.max=`${we}`,l.step="0.01",l.value=`${Math.min(se,we)}`,c.dataset.playing=X.state.playing?"true":"false",c.setAttribute("aria-label",X.state.playing?"Pause replay":"Play replay"),c.title=X.state.playing?"Pause replay":"Play replay",u.textContent=X.state.playing?"||":">",d.textContent=X.state.playing?"Pause":"Play",h.textContent=m_(se),f.textContent=`-${m_(we-se)}`,r.dataset.scrubbing=y?"true":"false",De(se);for(const G of R){const j=Math.max(0,G.startTimelineTime),Y=Math.min(we,G.endTimelineTime);if(Math.max(0,Y-j)<=1e-4){G.element.hidden=!0;continue}G.element.hidden=!1,G.element.dataset.active=se>=j&&se<=Y?"true":"false"}const k=$u(Math.min(se,we),we);for(const G of O)G.element.style.left=k;for(const G of L)G.element.style.left=k}function ie(X){let se=0,we=E.length;for(;seD)for(let G=D;G{se.player.seek(c3(Re,se))}),G.dataset.active="false",G.dataset.passed="false";const j={element:G,timelineTime:k.timelineTime,active:!1,passed:!1};return w.set(X.key,j),E.push(j),G}function Oe(X){if(!g||!p)return;g.replaceChildren(),p.replaceChildren(),w.clear(),E.splice(0,E.length),D=0,U=new Set,O.splice(0,O.length);const se=l3(n,X);x=[],se.length>0&&x.push({key:"replay",label:n.replayEventsLabel??"Replay",buckets:TM(se)}),x.push(...i3(i,X));const we=Math.max(X.player.getTimelineDuration(),1e-4),Re=x[0];if(Re?.key==="replay")for(const G of cb(Re.buckets)){const j=Ke({...G,key:`${Re.key}:${G.key}`},X,we);j&&g.append(j)}const k=x.filter(G=>G.key!=="replay");p.hidden=k.length===0;for(const G of k){const j=document.createElement("div");j.className="sap-tl-event-lane",j.dataset.label=G.label;const Y=document.createElement("span");Y.className="sap-tl-event-lane-label",Y.textContent=G.label,Y.setAttribute("aria-label",G.label),j.append(Y);const Q=document.createElement("div");Q.className="sap-tl-event-lane-track";const ge=document.createElement("div");ge.className="sap-tl-markers";for(const ye of cb(G.buckets)){const We=Ke({...ye,key:`${G.key}:${ye.key}`},X,we);We&&ge.append(We)}const ue=document.createElement("div");ue.className="sap-tl-event-playhead",Q.append(ge,ue),O.push({element:ue}),j.append(Q),p.append(j)}E.sort((G,j)=>G.timelineTime-j.timelineTime)}function Z(X){if(!o)return;o.replaceChildren(),R.splice(0,R.length),L.splice(0,L.length);const se=a3(s,X).filter(Re=>Number.isFinite(Re.startTime)&&Number.isFinite(Re.endTime)&&Re.endTime>Re.startTime);M=r3(se);const we=Math.max(X.player.getTimelineDuration(),1e-4);if(M.length===0){o.hidden=!0;return}o.hidden=!1;for(const Re of M){const k=document.createElement("div");k.className="sap-tl-range-lane";const G=document.createElement("div");if(G.className="sap-tl-range-lane-track",Re.label){k.dataset.label=Re.label;const Y=document.createElement("span");Y.className="sap-tl-range-lane-label",Y.textContent=Re.label,Y.setAttribute("aria-label",Re.label),k.append(Y)}for(const Y of Re.ranges){const Q=X.player.projectReplayTimeToTimeline(Y.startTime),ge=X.player.projectReplayTimeToTimeline(Y.endTime),{startTimelineTime:ue,endTimelineTime:ye}=u3(Q,ge,we),We=document.createElement("div");We.className="sap-tl-range-segment",Y.className&&We.classList.add(Y.className),We.style.background=o3(Y),We.title=Y.label??Re.label,We.dataset.active="false",We.style.left=$u(ue,we),We.style.width=$u(Math.max(0,ye-ue),we),G.append(We),R.push({range:Y,element:We,startTimelineTime:ue,endTimelineTime:ye})}const j=document.createElement("div");j.className="sap-tl-range-playhead",G.append(j),L.push({element:j}),k.append(G),o.append(k)}}function re(){y&&(y=!1,r?.setAttribute("data-scrubbing","false"),b&&S?.player.play(),b=!1)}function Te(){if(y||(y=!0,r?.setAttribute("data-scrubbing","true"),!e))return;const X=S?.player;X&&(b=X.getState().playing,b&&X.pause())}return{id:"timeline-overlay",addEventSource(X,se={}){return i.push({key:se.id??`events:${t++}`,label:se.label??"Events",source:X}),F(),()=>{this.removeEventSource(X)}},removeEventSource(X){const se=i.findIndex(we=>we.source===X);return se<0?!1:(i.splice(se,1),F(),!0)},refreshEvents(){F()},addRangeSource(X){return s.push(X),W(),()=>{this.removeRangeSource(X)}},removeRangeSource(X){const se=s.indexOf(X);return se<0?!1:(s.splice(se,1),W(),!0)},refreshRanges(){W()},setup(X){S=X,KU(),getComputedStyle(X.container).position==="static"&&(m=!0,v=X.container.style.position,X.container.style.position="relative"),a=document.createElement("div"),a.className="sap-tl-root",r=document.createElement("div"),r.className="sap-tl-shell",r.dataset.scrubbing="false";const se=document.createElement("div");se.className="sap-tl-topline";const we=document.createElement("div");we.className="sap-tl-primary",c=document.createElement("button"),c.type="button",c.className="sap-tl-toggle sap-tl-track-toggle",u=document.createElement("span"),u.className="sap-tl-toggle-icon",u.setAttribute("aria-hidden","true"),u.textContent=">",d=document.createElement("span"),d.className="sap-tl-toggle-label",d.textContent="Play",c.append(u,d),c.addEventListener("click",()=>{X.player.togglePlayback()}),h=document.createElement("span"),h.className="sap-tl-current",h.textContent="0:00.00",f=document.createElement("span"),f.className="sap-tl-remaining",f.textContent="-0:00.00",we.append(h),se.append(we,f);const Re=document.createElement("div");Re.className="sap-tl-track-wrap",o=document.createElement("div"),o.className="sap-tl-ranges",o.hidden=!0,p=document.createElement("div"),p.className="sap-tl-event-lanes",p.hidden=!0;const k=document.createElement("div");k.className="sap-tl-track-rail";const G=document.createElement("div");G.className="sap-tl-main-rail",g=document.createElement("div"),g.className="sap-tl-markers",l=document.createElement("input"),l.className="sap-tl-range",l.type="range",l.min="0",l.max=`${X.replay.duration}`,l.step="0.01",l.value="0";const j=()=>{Te()},Y=()=>{l&&X.player.seek(X.player.projectTimelineTimeToReplay(Number(l.value)))},Q=()=>{re()};l.addEventListener("pointerdown",j),l.addEventListener("input",Y),l.addEventListener("change",Q),window.addEventListener("pointerup",Q),window.addEventListener("pointercancel",Q),_=()=>{l?.removeEventListener("pointerdown",j),l?.removeEventListener("input",Y),l?.removeEventListener("change",Q),window.removeEventListener("pointerup",Q),window.removeEventListener("pointercancel",Q)},k.append(G,g,l),Re.append(o,p,c,k),r.append(se,Re),a.append(r),X.container.append(a),Oe(X),Z(X),H({...X,state:X.player.getState()})},onStateChange(X){S=X,H(X)},teardown(X){_?.(),_=null,re(),a?.remove(),a=null,r=null,o=null,p=null,l=null,c=null,u=null,d=null,h=null,f=null,g=null,S=null,x=[],M=[],C=null,w.clear(),E.splice(0,E.length),R.splice(0,R.length),L.splice(0,L.length),O.splice(0,O.length),D=0,U=new Set,m&&(X.container.style.position=v,m=!1)}}}function h3(n,e,t={}){const i=new dS(e.raw,{motionSmoothing:t.motionSmoothing,smoothingBlendFactor:t.smoothingBlendFactor,smoothingAnchorInterval:t.smoothingAnchorInterval,timelineCompaction:t.timelineCompaction,disableFrameFiltering:t.disableFrameFiltering}),s=new hU(n,i,t,e.replay);return s.getPlugins().some(a=>a.id==="camera")||s.addPlugin(vU()),s}const f3="https://ballchasing.com",p3=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function m3(n,e){const i=(e instanceof URL?e.href:e).replace(/\/+$/,"");return new URL(`${i}/${n.replace(/^\/+/,"")}`)}function ub(n){return p3.test(n.trim())}function uy(n){const e=n.trim();if(ub(e))return e.toLowerCase();let t;try{t=new URL(e)}catch{throw new Error(`Invalid Ballchasing replay id: ${n}`)}if(!/(^|\.)ballchasing\.com$/i.test(t.hostname))throw new Error(`Invalid Ballchasing replay URL: ${n}`);const i=t.pathname.split("/").filter(Boolean),s=i.findIndex(o=>o==="replay"),a=i.findIndex(o=>o==="replays"),r=s>=0?i[s+1]:a>=0?i[a+1]:void 0;if(!r||!ub(r))throw new Error(`Invalid Ballchasing replay URL: ${n}`);return r.toLowerCase()}function _3(n){return`ballchasing-${uy(n)}.replay`}function g3(n,e=f3){const t=uy(n);return m3(`dl/replay/${encodeURIComponent(t)}`,e)}const g_=250,db="subtr-actor-ballchasing-overlay-styles",sm="#3b82f6",hb="#f59e0b";function y3(){if(document.getElementById(db))return;const n=document.createElement("style");n.id=db,n.textContent=` .sap-bc-overlay-root { position: absolute; inset: 0; @@ -4541,14 +4541,14 @@ void main() { right: calc(50% + 2.7rem); flex-direction: row; justify-content: flex-end; - border-bottom: 2px solid ${Jp}; + border-bottom: 2px solid ${sm}; } .sap-bc-team-hud-orange { left: calc(50% + 2.7rem); flex-direction: row; justify-content: flex-start; - border-bottom: 2px solid ${ab}; + border-bottom: 2px solid ${hb}; } .sap-bc-hud-player { @@ -4656,7 +4656,7 @@ void main() { .sap-bc-followed-boost-ring { --sap-bc-followed-boost: 0%; - --sap-bc-followed-color: ${Jp}; + --sap-bc-followed-color: ${sm}; position: relative; display: grid; place-items: center; @@ -4676,11 +4676,11 @@ void main() { } .sap-bc-followed-hud-blue .sap-bc-followed-boost-ring { - --sap-bc-followed-color: ${Jp}; + --sap-bc-followed-color: ${sm}; } .sap-bc-followed-hud-orange .sap-bc-followed-boost-ring { - --sap-bc-followed-color: ${ab}; + --sap-bc-followed-color: ${hb}; } .sap-bc-followed-boost-value { @@ -4795,7 +4795,7 @@ void main() { font-size: 0.68rem; } } - `,document.head.append(n)}function lU(n,e){const t=n.players[e],i=t.frame?.boostAmount??0,s=t.nextFrame?.boostAmount??i;return bt.lerp(i,s,n.alpha)}function cU(n,e){const t=n.replay.players.find(h=>h.id===e);if(!t)return null;const i=Bh(n.replay,n.state.currentTime),s=Math.min(i+1,n.replay.frames.length-1),a=n.replay.frames[i],r=n.replay.frames[s]??a,o=a?.time??n.state.currentTime,l=r?.time??o,c=l>o?bt.clamp((n.state.currentTime-o)/(l-o),0,1):0,u=t.frames[i]?.boostAmount??0,d=t.frames[s]?.boostAmount??u;return bt.lerp(u,d,c)}function rb(n,e,t,i){if(!n||!e)return;const s=Math.max(0,Math.min(100,Math.round(Ys(t))));n.style.width=`${s}%`,e.textContent=`${s} ${i}`}function ob(n,e,t,i){if(!n)return;const s=Math.max(0,Math.min(100,Math.round(Ys(e))));n.root.hidden=!1,n.root.classList.toggle("sap-bc-followed-hud-blue",i),n.root.classList.toggle("sap-bc-followed-hud-orange",!i),n.root.setAttribute("aria-label",`${t} boost ${s}`),n.ring.style.setProperty("--sap-bc-followed-boost",`${s}%`),n.value.textContent=`${s}`,n.name.textContent=t}function lb(n,e,t,i){if(!n)return;const s=()=>{e.player.setAttachedPlayer(t)};n.classList.add("sap-bc-player-selectable"),n.tabIndex=0,n.setAttribute("role","button"),n.setAttribute("aria-label",`Follow ${i}`),n.title=`Follow ${i}`,n.addEventListener("click",s),n.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),s())})}function uU(n,e,t,i,s){if(n.getWorldPosition(s),s.add(e),s.project(t),s.z<-1||s.z>1)return!1;const a=i.clientWidth||1,r=i.clientHeight||1;return s.x=(s.x+1)*a/2,s.y=(1-s.y)*r/2,!(s.x<-80||s.x>a+80||s.y<-80||s.y>r+80)}function dU(n={}){const e=n.showFloatingNames??!0,t=n.showFloatingBoostBars??!0,i=n.showTeamBoostHud??!0,s=n.showFollowedPlayerHud??!0;let a=null,r=null,o=null,l=null,c=null,u=!1,d="";const h=new Map,f=n.floatingLiftUu,p=new T,g=new T;function _(){const b=typeof f=="function"?f():f;return typeof b=="number"&&Number.isFinite(b)?b:u_}function m(b){for(const[S,x]of h.entries()){const M=S===b;x.floatingRoot?.classList.toggle("sap-bc-player-following",M),x.teamHudEntry?.classList.toggle("sap-bc-player-following",M),x.floatingRoot?.setAttribute("aria-pressed",M?"true":"false"),x.teamHudEntry?.setAttribute("aria-pressed",M?"true":"false")}}function v(b){if(!c||!b.state.attachedPlayerId){c&&(c.root.hidden=!0);return}const S=b.replay.players.find(M=>M.id===b.state.attachedPlayerId);if(!S){c.root.hidden=!0;return}const x=cU(b,S.id);if(x===null){c.root.hidden=!0;return}ob(c,x,S.name,S.isTeamZero)}function y(b,S){if(oU(),getComputedStyle(S).position==="static"&&(u=!0,d=S.style.position,S.style.position="relative"),a=document.createElement("div"),a.className="sap-bc-overlay-root",e||t?(r=document.createElement("div"),r.className="sap-bc-floating-layer",a.append(r)):r=null,i?(o=document.createElement("div"),o.className="sap-bc-team-hud sap-bc-team-hud-blue",l=document.createElement("div"),l.className="sap-bc-team-hud sap-bc-team-hud-orange",a.append(o,l)):(o=null,l=null),s){const x=document.createElement("div");x.className="sap-bc-followed-hud",x.hidden=!0;const M=document.createElement("div");M.className="sap-bc-followed-boost-ring";const C=document.createElement("span");C.className="sap-bc-followed-boost-value",M.append(C);const w=document.createElement("div");w.className="sap-bc-followed-meta",w.textContent="Boost";const E=document.createElement("span");E.className="sap-bc-followed-name",w.append(E),x.append(M,w),a.append(x),c={root:x,ring:M,value:C,name:E}}else c=null;for(const x of b.replay.players){let M=null,C=null,w=null,E=null;r&&(M=document.createElement("div"),M.className="sap-bc-floating-track",M.hidden=!0,(e||t)&&(C=document.createElement("div"),C.className=`sap-bc-boost-bar ${x.isTeamZero?"sap-bc-boost-bar-blue":"sap-bc-boost-bar-orange"}`,w=document.createElement("div"),w.className=`sap-bc-boost-fill ${x.isTeamZero?"sap-bc-boost-fill-blue":"sap-bc-boost-fill-orange"}`,E=document.createElement("span"),E.className="sap-bc-boost-text",C.append(w,E),M.append(C)),lb(M,b,x.id,x.name),r.append(M));let R=null,L=null,O=null;if(i){R=document.createElement("div"),R.className="sap-bc-hud-player";const D=document.createElement("div");D.className=`sap-bc-hud-boost-bar ${x.isTeamZero?"sap-bc-boost-bar-blue":"sap-bc-boost-bar-orange"}`,L=document.createElement("div"),L.className=`sap-bc-hud-boost-fill ${x.isTeamZero?"sap-bc-boost-fill-blue":"sap-bc-boost-fill-orange"}`,O=document.createElement("span"),O.className="sap-bc-hud-boost-text",D.append(L,O),R.append(D),lb(R,b,x.id,x.name),(x.isTeamZero?o:l)?.append(R)}h.set(x.id,{floatingRoot:M,floatingBoostFill:w,floatingBoostText:E,teamHudEntry:R,teamHudFill:L,teamHudText:O})}S.append(a),m(b.player.getState().attachedPlayerId),v({...b,state:b.player.getState()})}return{id:"ballchasing-overlay",setup(b){y(b,b.container)},onStateChange(b){m(b.state.attachedPlayerId),v(b)},teardown(b){a?.remove(),a=null,r=null,o=null,l=null,c=null,h.clear(),u&&(b.container.style.position=d,u=!1)},beforeRender(b){if(!a)return;g.copy(b.scene.camera.up).normalize().multiplyScalar(_()*(b.options.fieldScale??1));let S=!1;for(const[x,M]of b.players.entries()){const C=h.get(M.track.id);if(!C)continue;const w=lU(b,x),E=C.floatingRoot?.classList.contains("sap-bc-player-following")??!1;E&&(ob(c,w,M.track.name,M.track.isTeamZero),S=!0),rb(C.floatingBoostFill,C.floatingBoostText,w,M.track.name),rb(C.teamHudFill,C.teamHudText,w,M.track.name);const R=M.mesh,L=R!==null&&M.interpolatedPosition!==null;if(C.teamHudEntry?.classList.toggle("sap-bc-hud-player-inactive",!L),!!C.floatingRoot){if(E||!L||!uU(R,g,b.scene.camera,b.container,p)){C.floatingRoot.hidden=!0;continue}C.floatingRoot.hidden=!1,C.floatingRoot.style.transform=`translate(${p.x.toFixed(1)}px, ${p.y.toFixed(1)}px) translate(-50%, -100%)`}}!S&&c&&(c.root.hidden=!0)}}}function hU(){return` + `,document.head.append(n)}function v3(n,e){const t=n.players[e],i=t.frame?.boostAmount??0,s=t.nextFrame?.boostAmount??i;return bt.lerp(i,s,n.alpha)}function b3(n,e){const t=n.replay.players.find(h=>h.id===e);if(!t)return null;const i=Wh(n.replay,n.state.currentTime),s=Math.min(i+1,n.replay.frames.length-1),a=n.replay.frames[i],r=n.replay.frames[s]??a,o=a?.time??n.state.currentTime,l=r?.time??o,c=l>o?bt.clamp((n.state.currentTime-o)/(l-o),0,1):0,u=t.frames[i]?.boostAmount??0,d=t.frames[s]?.boostAmount??u;return bt.lerp(u,d,c)}function fb(n,e,t,i){if(!n||!e)return;const s=Math.max(0,Math.min(100,Math.round(Ys(t))));n.style.width=`${s}%`,e.textContent=`${s} ${i}`}function pb(n,e,t,i){if(!n)return;const s=Math.max(0,Math.min(100,Math.round(Ys(e))));n.root.hidden=!1,n.root.classList.toggle("sap-bc-followed-hud-blue",i),n.root.classList.toggle("sap-bc-followed-hud-orange",!i),n.root.setAttribute("aria-label",`${t} boost ${s}`),n.ring.style.setProperty("--sap-bc-followed-boost",`${s}%`),n.value.textContent=`${s}`,n.name.textContent=t}function mb(n,e,t,i){if(!n)return;const s=()=>{e.player.setAttachedPlayer(t)};n.classList.add("sap-bc-player-selectable"),n.tabIndex=0,n.setAttribute("role","button"),n.setAttribute("aria-label",`Follow ${i}`),n.title=`Follow ${i}`,n.addEventListener("click",s),n.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),s())})}function x3(n,e,t,i,s){if(n.getWorldPosition(s),s.add(e),s.project(t),s.z<-1||s.z>1)return!1;const a=i.clientWidth||1,r=i.clientHeight||1;return s.x=(s.x+1)*a/2,s.y=(1-s.y)*r/2,!(s.x<-80||s.x>a+80||s.y<-80||s.y>r+80)}function w3(n={}){const e=n.showFloatingNames??!0,t=n.showFloatingBoostBars??!0,i=n.showTeamBoostHud??!0,s=n.showFollowedPlayerHud??!0;let a=null,r=null,o=null,l=null,c=null,u=!1,d="";const h=new Map,f=n.floatingLiftUu,p=new T,g=new T;function _(){const b=typeof f=="function"?f():f;return typeof b=="number"&&Number.isFinite(b)?b:g_}function m(b){for(const[S,x]of h.entries()){const M=S===b;x.floatingRoot?.classList.toggle("sap-bc-player-following",M),x.teamHudEntry?.classList.toggle("sap-bc-player-following",M),x.floatingRoot?.setAttribute("aria-pressed",M?"true":"false"),x.teamHudEntry?.setAttribute("aria-pressed",M?"true":"false")}}function v(b){if(!c||!b.state.attachedPlayerId){c&&(c.root.hidden=!0);return}const S=b.replay.players.find(M=>M.id===b.state.attachedPlayerId);if(!S){c.root.hidden=!0;return}const x=b3(b,S.id);if(x===null){c.root.hidden=!0;return}pb(c,x,S.name,S.isTeamZero)}function y(b,S){if(y3(),getComputedStyle(S).position==="static"&&(u=!0,d=S.style.position,S.style.position="relative"),a=document.createElement("div"),a.className="sap-bc-overlay-root",e||t?(r=document.createElement("div"),r.className="sap-bc-floating-layer",a.append(r)):r=null,i?(o=document.createElement("div"),o.className="sap-bc-team-hud sap-bc-team-hud-blue",l=document.createElement("div"),l.className="sap-bc-team-hud sap-bc-team-hud-orange",a.append(o,l)):(o=null,l=null),s){const x=document.createElement("div");x.className="sap-bc-followed-hud",x.hidden=!0;const M=document.createElement("div");M.className="sap-bc-followed-boost-ring";const C=document.createElement("span");C.className="sap-bc-followed-boost-value",M.append(C);const w=document.createElement("div");w.className="sap-bc-followed-meta",w.textContent="Boost";const E=document.createElement("span");E.className="sap-bc-followed-name",w.append(E),x.append(M,w),a.append(x),c={root:x,ring:M,value:C,name:E}}else c=null;for(const x of b.replay.players){let M=null,C=null,w=null,E=null;r&&(M=document.createElement("div"),M.className="sap-bc-floating-track",M.hidden=!0,(e||t)&&(C=document.createElement("div"),C.className=`sap-bc-boost-bar ${x.isTeamZero?"sap-bc-boost-bar-blue":"sap-bc-boost-bar-orange"}`,w=document.createElement("div"),w.className=`sap-bc-boost-fill ${x.isTeamZero?"sap-bc-boost-fill-blue":"sap-bc-boost-fill-orange"}`,E=document.createElement("span"),E.className="sap-bc-boost-text",C.append(w,E),M.append(C)),mb(M,b,x.id,x.name),r.append(M));let R=null,L=null,O=null;if(i){R=document.createElement("div"),R.className="sap-bc-hud-player";const D=document.createElement("div");D.className=`sap-bc-hud-boost-bar ${x.isTeamZero?"sap-bc-boost-bar-blue":"sap-bc-boost-bar-orange"}`,L=document.createElement("div"),L.className=`sap-bc-hud-boost-fill ${x.isTeamZero?"sap-bc-boost-fill-blue":"sap-bc-boost-fill-orange"}`,O=document.createElement("span"),O.className="sap-bc-hud-boost-text",D.append(L,O),R.append(D),mb(R,b,x.id,x.name),(x.isTeamZero?o:l)?.append(R)}h.set(x.id,{floatingRoot:M,floatingBoostFill:w,floatingBoostText:E,teamHudEntry:R,teamHudFill:L,teamHudText:O})}S.append(a),m(b.player.getState().attachedPlayerId),v({...b,state:b.player.getState()})}return{id:"ballchasing-overlay",setup(b){y(b,b.container)},onStateChange(b){m(b.state.attachedPlayerId),v(b)},teardown(b){a?.remove(),a=null,r=null,o=null,l=null,c=null,h.clear(),u&&(b.container.style.position=d,u=!1)},beforeRender(b){if(!a)return;g.copy(b.scene.camera.up).normalize().multiplyScalar(_()*(b.options.fieldScale??1));let S=!1;for(const[x,M]of b.players.entries()){const C=h.get(M.track.id);if(!C)continue;const w=v3(b,x),E=C.floatingRoot?.classList.contains("sap-bc-player-following")??!1;E&&(pb(c,w,M.track.name,M.track.isTeamZero),S=!0),fb(C.floatingBoostFill,C.floatingBoostText,w,M.track.name),fb(C.teamHudFill,C.teamHudText,w,M.track.name);const R=M.mesh,L=R!==null&&M.interpolatedPosition!==null;if(C.teamHudEntry?.classList.toggle("sap-bc-hud-player-inactive",!L),!!C.floatingRoot){if(E||!L||!x3(R,g,b.scene.camera,b.container,p)){C.floatingRoot.hidden=!0;continue}C.floatingRoot.hidden=!1,C.floatingRoot.style.transform=`translate(${p.x.toFixed(1)}px, ${p.y.toFixed(1)}px) translate(-50%, -100%)`}}!S&&c&&(c.root.hidden=!0)}}}const S3="modulepreload",T3=function(n,e){return new URL(n,e).href},_b={},M3=function(e,t,i){let s=Promise.resolve();if(t&&t.length>0){let c=function(u){return Promise.all(u.map(d=>Promise.resolve(d).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};const r=document.getElementsByTagName("link"),o=document.querySelector("meta[property=csp-nonce]"),l=o?.nonce||o?.getAttribute("nonce");s=c(t.map(u=>{if(u=T3(u,i),u in _b)return;_b[u]=!0;const d=u.endsWith(".css"),h=d?'[rel="stylesheet"]':"";if(i)for(let p=r.length-1;p>=0;p--){const g=r[p];if(g.href===u&&(!d||g.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${u}"]${h}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":S3,d||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),d)return new Promise((p,g)=>{f.addEventListener("load",p),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${u}`)))})}))}function a(r){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=r,window.dispatchEvent(o),!o.defaultPrevented)throw r}return s.then(r=>{for(const o of r||[])o.status==="rejected"&&a(o.reason);return e().catch(a)})};function E3(){return{guid:{a:0,b:0,c:0,d:0},code:null,name:null,training_type:"Training_None",difficulty:"D_Easy",creator_name:null,description:null,tags:[],map_name:null,created_at:0n,updated_at:0n,creator_player_id:{uid:0n,epic_account_id:null,platform:null,splitscreen_id:0},rounds:[],player_team_number:0,unowned:!1,perfect_completed:!1,shots_completed:0}}let am=null;async function C3(){return am||(am=(async()=>{const n=await M3(()=>import("./rl_replay_subtr_actor-Cnltgw4Z.js"),[],import.meta.url),e=n.default;return typeof e=="function"&&await e(),n})()),am}async function gb(n){return n?.bindings??C3()}function A3(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function no(n){try{return n()}catch(e){throw e instanceof Error?e:new Error(String(e))}}class ca{constructor(e,t){this.bindings=e,this.lossless=t}lossless;cachedPack=null;static async load(e,t){return ca.fromBytes(e,await gb(t))}static fromBytes(e,t){const i=no(()=>t.parse_training_pack_lossless(A3(e)));return new ca(t,i)}static async create(e,t){return ca.createWithBindings(await gb(t),e)}static createWithBindings(e,t){const i={...E3(),...t},s=no(()=>e.new_training_pack(i));return new ca(e,s)}static fromLosslessJson(e,t){const i=new ca(t,e);return i.view(),i}view(){return this.cachedPack||(this.cachedPack=no(()=>this.bindings.training_pack_from_lossless(this.lossless))),this.cachedPack}apply(e){this.lossless=no(e),this.cachedPack=null}get losslessJson(){return this.lossless}get pack(){return structuredClone(this.view())}toJSON(){return this.pack}get name(){return this.view().name}get code(){return this.view().code}get description(){return this.view().description}get creatorName(){return this.view().creator_name}get trainingType(){return this.view().training_type}get difficulty(){return this.view().difficulty}get mapName(){return this.view().map_name}get guid(){return{...this.view().guid}}get tags(){return[...this.view().tags]}get rounds(){return structuredClone(this.view().rounds)}get roundCount(){return this.view().rounds.length}updateMetadata(e){const t={...this.view(),...e};this.apply(()=>this.bindings.update_training_pack_metadata(this.lossless,t))}setName(e){this.updateMetadata({name:e})}setCode(e){this.updateMetadata({code:e})}setDescription(e){this.updateMetadata({description:e})}setCreatorName(e){this.updateMetadata({creator_name:e})}setTrainingType(e){this.updateMetadata({training_type:e})}setDifficulty(e){this.updateMetadata({difficulty:e})}setMapName(e){this.updateMetadata({map_name:e})}setTags(e){this.updateMetadata({tags:e})}setGuid(e){this.updateMetadata({guid:e})}addRound(e){this.apply(()=>this.bindings.training_pack_add_round(this.lossless,e))}insertRound(e,t){this.apply(()=>this.bindings.training_pack_insert_round(this.lossless,e,t))}removeRound(e){const t=this.view().rounds[e];return this.apply(()=>this.bindings.training_pack_remove_round(this.lossless,e)),structuredClone(t)}moveRound(e,t){this.apply(()=>this.bindings.training_pack_move_round(this.lossless,e,t))}duplicateRound(e){this.apply(()=>this.bindings.training_pack_duplicate_round(this.lossless,e))}getRoundArchetypes(e){return no(()=>this.bindings.training_pack_round_archetypes(this.lossless,e))}setRoundArchetype(e,t,i){this.apply(()=>this.bindings.training_pack_set_round_archetype(this.lossless,e,t,i))}addRoundArchetype(e,t){this.apply(()=>this.bindings.training_pack_add_round_archetype(this.lossless,e,t))}removeRoundArchetype(e,t){const i=this.getRoundArchetypes(e)[t];return this.apply(()=>this.bindings.training_pack_remove_round_archetype(this.lossless,e,t)),i}setRoundBall(e,t){this.apply(()=>this.bindings.training_pack_set_round_ball(this.lossless,e,t))}addRoundCar(e,t){this.addRoundArchetype(e,{kind:"CarSpawnPoint",...t})}setRoundTimeLimit(e,t){this.apply(()=>this.bindings.training_pack_set_round_time_limit(this.lossless,e,t))}appendRoundsFrom(e){const t=e.view().rounds.length;return this.apply(()=>this.bindings.training_pack_append_rounds(this.lossless,e.lossless)),t}toBytes(){return no(()=>this.bindings.serialize_training_pack(this.lossless))}}const EM=8,R3=17,P3=32768/Math.PI;function Jl(n){return Math.round(n*P3)}function _d(n,e){const{x:t,y:i,z:s,w:a}=e,r=2*(i*n.z-s*n.y),o=2*(s*n.x-t*n.z),l=2*(t*n.y-i*n.x);return{x:n.x+a*r+(i*l-s*o),y:n.y+a*o+(s*r-t*l),z:n.z+a*l+(t*o-i*r)}}function I3(n){const e=n?.x??0,t=n?.y??0,i=n?.z??0,s=Math.hypot(e,t),a=Math.hypot(s,i);return a===0?{rotator:{pitch:0,yaw:0,roll:0},speed:0}:{rotator:{pitch:Jl(Math.atan2(i,s)),yaw:Jl(Math.atan2(t,e)),roll:0},speed:a}}function L3(n){const e=_d({x:1,y:0,z:0},n),t=_d({x:0,y:1,z:0},n),i=_d({x:0,y:0,z:1},n);return{pitch:Jl(Math.atan2(e.z,Math.hypot(e.x,e.y))),yaw:Jl(Math.atan2(e.y,e.x)),roll:Jl(Math.atan2(t.z,i.z))}}const k3=1,D3=300,O3=400,F3=20;function N3(n,e){const t=D3,i=O3,s=F3,a=n.linearVelocity,r=a?.x??0,o=a?.y??0,l=a?.z??0,c=Math.hypot(r,o,l);if(c<=t)return null;const u=n.rotation?_d({x:1,y:0,z:0},n.rotation):{x:1,y:0,z:0},d=r*u.x+o*u.y+l*u.z,h=d(e>>>0).toString(16).padStart(8,"0").toUpperCase()).join("")}function $3(n){return`${G3(n)}.Tem`}function W3(n=Math.floor(Date.now()/1e3)){const e=BigInt(n);return{guid:V3(),name:"Captured Training Pack",training_type:"Training_Striker",difficulty:"D_Medium",map_name:"Park_P",created_at:e,updated_at:e}}function X3(){return`
@@ -4822,6 +4822,7 @@ void main() { + @@ -5219,6 +5220,70 @@ void main() {
+ +
--
--
-`}const tn="#3b82f6",nn="#f59e0b",fU=new Set(["wavedash"]),pU=new Set(["air_dribble","ball_carry","ceiling_shot","double_tap","flick","flip_reset","half_flip","half_volley","one_timer","speed_flip","wall_aerial","wall_aerial_shot","wavedash"]);function Dn(n){return n.split(/[_-]+/).filter(e=>e.length>0).map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1)}`).join(" ")}function cb(n){return pU.has(n)&&!fU.has(n)}function Ef(n){return n===!0?tn:n===!1?nn:null}const gM=["timeline","core_player","player_possession","possession","loose_possession","ball_half","ball_third","territorial_pressure","movement","player_activity","field_third","field_half","ball_depth","depth_role","ball_proximity","shadow_defense","rotation_role","first_man_change","goal_context","backboard","ceiling_shot","wall_aerial","wall_aerial_shot","center","flick","flip_reset","dodge_reset","double_tap","fifty_fifty","kickoff","one_timer","pass","ball_carry","controlled_play","rush","dodge","speed_flip","half_flip","half_volley","wavedash","whiff","powerslide","touch","boost_pickups","boost_respawn","bump","demolition"],yM=["air_dribble","ball_carry","ceiling_shot","double_tap","flick","flip_reset","half_flip","half_volley","one_timer","speed_flip","wall_aerial","wall_aerial_shot","wavedash"],sy=[...new Set([...gM,...yM])],mU=new Set(yM);function mo(){return Object.fromEntries(sy.map(n=>[n,0]))}function Qp(n){return{...n??mo()}}function Hu(n,e){n[e]+=1}function _U(n){return sy.includes(n)}function vM(n){if(n==null)return null;if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function d_(n){return vM(n.meta.primary_player)}function gU(n){return n.meta.team_is_team_0??null}function yU(n){const e=n.meta.stream;return!mU.has(e)||!_U(e)?null:e}function h_(n){const e=n.meta.timing.type==="span"?n.meta.timing.end_frame:n.meta.timing.frame;return typeof e=="number"&&Number.isFinite(e)?e:null}function f_(n){const e=n.meta.timing.type==="span"?n.meta.timing.end_time:n.meta.timing.time;return typeof e=="number"&&Number.isFinite(e)?e:null}function vU(n,e){const t=h_(n);if(t!==null)return t<=e.frame_number;const i=f_(n);return i!==null&&i<=e.time}function bU(n){return[...n].sort((e,t)=>{const i=h_(e),s=h_(t);if(i!==s)return(i??Number.POSITIVE_INFINITY)-(s??Number.POSITIVE_INFINITY);const a=f_(e),r=f_(t);return a!==r?(a??Number.POSITIVE_INFINITY)-(r??Number.POSITIVE_INFINITY):(d_(e)??"").localeCompare(d_(t)??"")})}function bM(n){const e=xM(n);for(const t of n.frames)e.applyFrame(t);return n}function xM(n){const e=sy.map(s=>({eventType:s,events:bU(pc(n).filter(a=>a.meta.stream===s)),index:0})),t=new Map,i={teamZero:mo(),teamOne:mo()};return{applyFrame(s){for(const a of e)for(;a.index({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function wU(n,e,t,i){n.is_last_backboard=i,n.time_since_last_backboard=n.last_backboard_time==null?null:Math.max(0,t-n.last_backboard_time),n.frames_since_last_backboard=n.last_backboard_frame==null?null:Math.max(0,e-n.last_backboard_frame)}function SU(n,e,t,i){n.count+=1,n.last_backboard_time=e.time,n.last_backboard_frame=e.frame,n.time_since_last_backboard=Math.max(0,i-e.time),n.frames_since_last_backboard=Math.max(0,t-e.frame)}function TU(n,e){Object.assign(n,e??wM())}function db(n,e){n.count=e}function MU(n){const e=SM(n);for(const t of n.frames)e.applyFrame(t);return n}function SM(n){const e=xU(be(n,"backboard"));let t=0,i=0,s=0,a=null;const r=new Map;return{applyFrame(o){for(const[c,u]of r)wU(u,o.frame_number,o.time,c===a);let l=!1;for(;t({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function p_(n){return`${n.key}\0${n.value}`}function Vu(n){return n.map(p_).join("")}function TM(n,e){e.sort((s,a)=>p_(s).localeCompare(p_(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Vu(s.labels)===Vu(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Vu(s.labels).localeCompare(Vu(a.labels))))}function fb(n,e){return n.labeled_event_counts?.entries.filter(t=>t.labels.some(i=>i.key==="origin"&&i.value===e)).reduce((t,i)=>t+i.count,0)??0}function MM(n){return n.labeled_event_counts?.entries.reduce((e,t)=>e+t.count,0)??0}function EM(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function pb(n,e){TM(n,[{key:"kind",value:"carry"}]),n.carry_count=MM(n),n.total_carry_time+=e.duration,n.total_straight_line_distance+=e.straight_line_distance,n.total_path_distance+=e.path_distance,n.longest_carry_time=Math.max(n.longest_carry_time,e.duration),n.furthest_carry_distance=Math.max(n.furthest_carry_distance,e.straight_line_distance),n.fastest_carry_speed=Math.max(n.fastest_carry_speed,e.average_speed),n.carry_speed_sum+=e.average_speed,n.average_horizontal_gap_sum+=e.average_horizontal_gap,n.average_vertical_gap_sum+=e.average_vertical_gap}function mb(n,e){e.air_dribble_origin!=null&&TM(n,[{key:"origin",value:e.air_dribble_origin}]),n.count=MM(n),n.ground_to_air_count=fb(n,"ground_to_air"),n.wall_to_air_count=fb(n,"wall_to_air"),n.total_time+=e.duration,n.total_straight_line_distance+=e.straight_line_distance,n.total_path_distance+=e.path_distance,n.longest_time=Math.max(n.longest_time,e.duration),n.furthest_distance=Math.max(n.furthest_distance,e.straight_line_distance),n.fastest_speed=Math.max(n.fastest_speed,e.average_speed),n.speed_sum+=e.average_speed,n.average_horizontal_gap_sum+=e.average_horizontal_gap,n.average_vertical_gap_sum+=e.average_vertical_gap,n.total_touch_count+=e.touch_count,n.max_touch_count=Math.max(n.max_touch_count,e.touch_count)}function em(n,e){Object.assign(n,e??hd()),e?.labeled_event_counts?n.labeled_event_counts=EM(e.labeled_event_counts):delete n.labeled_event_counts}function tm(n,e){Object.assign(n,e??fd()),e?.labeled_event_counts?n.labeled_event_counts=EM(e.labeled_event_counts):delete n.labeled_event_counts}function CU(n){const e=CM(n);for(const t of n.frames)e.applyFrame(t);return n}function CM(n){const e=EU(be(n,"ball_carry"));let t=0;const i=new Map,s=new Map,a=hd(),r=hd(),o=fd(),l=fd();return{applyFrame(c){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function RU(n,e){n.bumps_inflicted+=1,e.is_team_bump&&(n.team_bumps_inflicted+=1),n.last_bump_time=e.time,n.last_bump_frame=e.frame,n.last_bump_strength=e.strength,n.max_bump_strength=Math.max(n.max_bump_strength,e.strength),n.cumulative_bump_strength+=e.strength}function PU(n,e){n.bumps_taken+=1,e.is_team_bump&&(n.team_bumps_taken+=1)}function IU(n,e){n.bumps_inflicted+=1,e.is_team_bump&&(n.team_bumps_inflicted+=1)}function LU(n,e){Object.assign(n,e??m_())}function gb(n,e){Object.assign(n,e)}function kU(n){const e=AM(n);for(const t of n.frames)e.applyFrame(t);return n}function AM(n){const e=AU(be(n,"bump"));let t=0;const i=new Map,s=_b(),a=_b();return{applyFrame(r){for(;t=t&&n0&&(s.overfill_total=an(s.overfill_total,i),e.field_half==="opponent"&&(s.overfill_from_stolen=an(s.overfill_from_stolen,i)))}function bb(n,e){e.boost_granted!=null&&(n.stats.amount_respawned=an(n.stats.amount_respawned,on(e.boost_granted)))}class BU{constructor(e){this.points=e}index=0;sample(e){for(;this.index+1e?0:on(t.value)}}function v_(n,e){return`${n}:${e}`}function zU(n){const e=new Map,t=n.accumulation_tracks;for(const i of t??[]){const s=Il(i.player_id);e.set(v_(s,i.quantity),new BU(i.points))}return e}function HU(n){return[...be(n,"boost_pickup")].sort((e,t)=>e.frame-t.frame||e.time-t.time)}function VU(n){return[...be(n,"respawn")].sort((e,t)=>e.frame-t.frame||e.time-t.time)}function sm(n,e){for(const t of RM)n[t]=e[t]}function PM(n){const e=HU(n),t=VU(n),i=zU(n);let s=0,a=0;const r=new Map,o=im(),l=im(),c=(d,h)=>{const f=Il(d);let p=r.get(f);return p||(p=im(),r.set(f,p)),p.isTeamZero=h,p},u=(d,h,f)=>{const p=g=>i.get(v_(h,g))?.sample(f)??0;d.amount_used=p("boost_used"),d.amount_used_while_grounded=p("boost_used_grounded"),d.amount_used_while_airborne=p("boost_used_airborne"),d.amount_used_while_supersonic=p("boost_used_supersonic")};return{applyFrame(d,h){for(;s({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function b_(n){return`${n.key}\0${n.value}`}function $u(n){return n.map(b_).join("")}function qU(n,e){e.sort((s,a)=>b_(s).localeCompare(b_(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>$u(s.labels)===$u(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>$u(s.labels).localeCompare($u(a.labels))))}function YU(n,e){return n.labeled_event_counts?.entries.filter(t=>t.labels.some(i=>i.key==="confidence_band"&&i.value===e)).reduce((t,i)=>t+i.count,0)??0}function jU(n){return n.labeled_event_counts?.entries.reduce((e,t)=>e+t.count,0)??0}function ZU(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function JU(n,e,t,i){n.is_last_ceiling_shot=i,n.time_since_last_ceiling_shot=n.last_ceiling_shot_time==null?null:Math.max(0,IM(t,n.last_ceiling_shot_time)),n.frames_since_last_ceiling_shot=n.last_ceiling_shot_frame==null?null:Math.max(0,e-n.last_ceiling_shot_frame)}function QU(n,e,t,i){qU(n,[{key:"confidence_band",value:e.confidence>=WU?"high":"standard"}]),n.count=jU(n),n.high_confidence_count=YU(n,"high"),n.is_last_ceiling_shot=!0,n.last_ceiling_shot_time=e.time,n.last_ceiling_shot_frame=e.frame,n.time_since_last_ceiling_shot=Math.max(0,IM(i,e.time)),n.frames_since_last_ceiling_shot=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=XU(n.cumulative_confidence,e.confidence)}function eB(n,e){Object.assign(n,e??LM()),e?.labeled_event_counts?n.labeled_event_counts=ZU(e.labeled_event_counts):delete n.labeled_event_counts}function tB(n){const e=kM(n);for(const t of n.frames)e.applyFrame(t);return n}function kM(n){const e=KU(be(n,"ceiling_shot"));let t=0,i=null;const s=new Map;return{applyFrame(a){if(a.is_live_play){for(const[r,o]of s)JU(o,a.frame_number,a.time,i===r);for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function aB(n,e){Object.assign(n,e??ay())}function Sb(n,e){Object.assign(n,e)}function Tb(n,e){n.score+=e.score_delta,n.goals+=e.goals_delta,n.assists+=e.assists_delta,n.saves+=e.saves_delta,n.shots+=e.shots_delta}function DM(n,e){if(e.time_after_kickoff!=null){const t=Math.max(0,e.time_after_kickoff);t<10?n.kickoff_goal_count+=1:t<20?n.short_goal_count+=1:t<40?n.medium_goal_count+=1:n.long_goal_count+=1}if(e.goal_buildup==="counter_attack"?n.counter_attack_goal_count+=1:e.goal_buildup==="sustained_pressure"?n.sustained_pressure_goal_count+=1:e.goal_buildup!=null&&(n.other_buildup_goal_count+=1),e.ball_air_time_before_goal!=null){const t=Math.max(0,e.ball_air_time_before_goal);n.goal_ball_air_time_sample_count+=1,n.cumulative_goal_ball_air_time=cs(n.cumulative_goal_ball_air_time,t),n.last_goal_ball_air_time=t}}function am(n,e){return n!=null&&e!=null&&fc(n)===fc(e)}function Mb(n,e){return n?e.y:-e.y}function rB(n,e){if(n.ball_position==null||e.position==null)return!1;const t=!n.scoring_team_is_team_0,i=Mb(t,n.ball_position);if(i>nB)return!1;const s=Mb(t,e.position);return s=sB}function oB(n,e,t){const i=t.is_team_0===e.scoring_team_is_team_0,s=am(t.player,e.defending_team_most_back_player),a=am(t.player,e.scoring_team_most_back_player);s&&(n.goals_conceded_while_last_defender+=1),a&&(n.goals_for_while_most_back+=1),s&&(n.goals_against_while_most_back+=1),!i&&rB(e,t)&&(n.caught_ahead_of_play_on_conceded_goals+=1),!i&&t.boost_amount!=null&&(n.goal_against_boost_sample_count+=1,n.cumulative_boost_on_goals_against=cs(n.cumulative_boost_on_goals_against,t.boost_amount),n.last_boost_on_goal_against=t.boost_amount),!i&&t.average_boost_in_leadup!=null&&t.min_boost_in_leadup!=null&&(n.goal_against_boost_leadup_sample_count+=1,n.cumulative_average_boost_in_goal_against_leadup=cs(n.cumulative_average_boost_in_goal_against_leadup,t.average_boost_in_leadup),n.cumulative_min_boost_in_goal_against_leadup=cs(n.cumulative_min_boost_in_goal_against_leadup,t.min_boost_in_leadup),n.last_average_boost_in_goal_against_leadup=t.average_boost_in_leadup,n.last_min_boost_in_goal_against_leadup=t.min_boost_in_leadup),!i&&t.position!=null&&(n.goal_against_position_sample_count+=1,n.cumulative_goal_against_position_x=cs(n.cumulative_goal_against_position_x,t.position.x),n.cumulative_goal_against_position_y=cs(n.cumulative_goal_against_position_y,t.position.y),n.cumulative_goal_against_position_z=cs(n.cumulative_goal_against_position_z,t.position.z),n.last_goal_against_position={...t.position});const r=am(t.player,e.scorer),o=r?e.scorer_last_touch?.ball_position:null;o!=null&&(n.scoring_goal_last_touch_position_sample_count+=1,n.cumulative_scoring_goal_last_touch_position_x=cs(n.cumulative_scoring_goal_last_touch_position_x,o.x),n.cumulative_scoring_goal_last_touch_position_y=cs(n.cumulative_scoring_goal_last_touch_position_y,o.y),n.cumulative_scoring_goal_last_touch_position_z=cs(n.cumulative_scoring_goal_last_touch_position_z,o.z),n.last_scoring_goal_last_touch_position={...o}),r&&DM(n,e)}function lB(n,e,t,i){DM(i.scoring_team_is_team_0?e:t,i);for(const s of i.players){const a=fc(s.player),r=n.get(a)??ay();n.set(a,r),oB(r,i,s)}}function cB(n){const e=OM(n);for(const t of n.frames)e.applyFrame(t);return n}function OM(n){const e=wb(be(n,"core_player")),t=wb(be(n,"goal_context"));let i=0,s=0;const a=new Map,r=x_(),o=x_();return{applyFrame(l){for(;i({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function Ab(n,e){n.count+=1,n.total_time=Eb(n.total_time,e.duration),n.longest_time=Math.max(n.longest_time,e.duration),n.touch_count+=e.touch_count,n.total_advance_distance=Eb(n.total_advance_distance,e.total_advance_distance)}function om(n,e){Object.assign(n,e??pd())}function dB(n){const e=FM(n);for(const t of n.frames)e.applyFrame(t);return n}function FM(n){const e=uB(be(n,"controlled_play"));let t=0;const i=new Map,s=pd(),a=pd();return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function fB(n,e){n.count+=1,e.on_ball&&(n.on_ball_count+=1)}function pB(n,e){Object.assign(n,e??NM())}function mB(n){const e=UM(n);for(const t of n.frames)e.applyFrame(t);return n}function UM(n){const e=hB(be(n,"dodge_reset"));let t=0;const i=new Map;return{applyFrame(s){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function gB(n,e,t,i){n.is_last_double_tap=i,n.time_since_last_double_tap=n.last_double_tap_time==null?null:Math.max(0,t-n.last_double_tap_time),n.frames_since_last_double_tap=n.last_double_tap_frame==null?null:Math.max(0,e-n.last_double_tap_frame)}function yB(n,e,t,i){n.count+=1,n.last_double_tap_time=e.time,n.last_double_tap_frame=e.frame,n.time_since_last_double_tap=Math.max(0,i-e.time),n.frames_since_last_double_tap=Math.max(0,t-e.frame)}function vB(n,e){Object.assign(n,e??BM())}function Ib(n,e){n.count=e}function bB(n){const e=zM(n);for(const t of n.frames)e.applyFrame(t);return n}function zM(n){const e=_B(be(n,"double_tap"));let t=0,i=0,s=0,a=null;const r=new Map;return{applyFrame(o){for(const[c,u]of r)gB(u,o.frame_number,o.time,c===a);let l=!1;for(;t({event:e,index:t})).sort((e,t)=>e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function wB(n,e){Object.assign(n,e??HM())}function Db(n,e){Object.assign(n,e)}function SB(n){const e=VM(n);for(const t of n.frames)e.applyFrame(t);return n}function VM(n){const e=xB(be(n,"demolition"));let t=0;const i=new Map,s=kb(),a=kb();function r(o){const l=Lb(o),c=i.get(l)??HM();return i.set(l,c),c}return{applyFrame(o){for(;t({event:e,index:t})).sort((e,t)=>e.event.resolve_frame!==t.event.resolve_frame?e.event.resolve_frame-t.event.resolve_frame:e.event.resolve_time!==t.event.resolve_time?e.event.resolve_time-t.event.resolve_time:e.index-t.index).map(({event:e})=>e)}function MB(n){return{key:"phase",value:n?"kickoff":"open_play"}}function EB(n,e){return e==null?{key:"outcome",value:"neutral"}:{key:"outcome",value:e===n?"win":"loss"}}function CB(n,e){return e==null?{key:"possession_after",value:"neutral"}:{key:"possession_after",value:e===n?"self":"opponent"}}function AB(n,e){return{key:"dodge_state",value:(n?e.team_zero_dodge_contact:e.team_one_dodge_contact)?"dodge":"no_dodge"}}function S_(n){return`${n.key}\0${n.value}`}function Wu(n){return n.map(S_).join("")}function RB(n,e){e.sort((s,a)=>S_(s).localeCompare(S_(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Wu(s.labels)===Wu(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Wu(s.labels).localeCompare(Wu(a.labels))))}function PB(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function Fb(n,e,t){n.count+=1,t.winning_team_is_team_0==null?n.neutral_outcomes+=1:t.winning_team_is_team_0===e?n.wins+=1:n.losses+=1,t.possession_team_is_team_0==null?n.neutral_possession_after_count+=1:t.possession_team_is_team_0===e?n.possession_after_count+=1:n.opponent_possession_after_count+=1,t.is_kickoff&&(n.kickoff_count+=1,t.winning_team_is_team_0==null?n.kickoff_neutral_outcomes+=1:t.winning_team_is_team_0===e?n.kickoff_wins+=1:n.kickoff_losses+=1,t.possession_team_is_team_0==null?n.kickoff_neutral_possession_after_count+=1:t.possession_team_is_team_0===e?n.kickoff_possession_after_count+=1:n.kickoff_opponent_possession_after_count+=1)}function Nb(n,e,t){RB(n,[MB(t.is_kickoff),EB(e,t.winning_team_is_team_0),CB(e,t.possession_team_is_team_0),AB(e,t)]),n.count+=1,t.winning_team_is_team_0==null?n.neutral_outcomes+=1:t.winning_team_is_team_0===e?n.wins+=1:n.losses+=1,t.possession_team_is_team_0===e&&(n.possession_after_count+=1),t.is_kickoff&&(n.kickoff_count+=1,t.winning_team_is_team_0==null?n.kickoff_neutral_outcomes+=1:t.winning_team_is_team_0===e?n.kickoff_wins+=1:n.kickoff_losses+=1,t.possession_team_is_team_0===e&&(n.kickoff_possession_after_count+=1))}function IB(n,e){Object.assign(n,e??w_()),e?.labeled_event_counts?n.labeled_event_counts=PB(e.labeled_event_counts):delete n.labeled_event_counts}function Ub(n,e){Object.assign(n,e)}function LB(n){const e=GM(n);for(const t of n.frames)e.applyFrame(t);return n}function GM(n){const e=TB(be(n,"fifty_fifty"));let t=0;const i=Ob(),s=Ob(),a=new Map;return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function T_(n){return`${n.key}\0${n.value}`}function Xu(n){return n.map(T_).join("")}function XM(n,e){e.sort((s,a)=>T_(s).localeCompare(T_(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Xu(s.labels)===Xu(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Xu(s.labels).localeCompare(Xu(a.labels))))}function DB(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function OB(n){return[{key:"kickoff_spawn",value:n.spawn_position},{key:"taker_outcome",value:n.outcome},{key:"kickoff_approach",value:n.approach},{key:"approach_flip_direction",value:n.approach_flip_direction}]}function FB(n){return[{key:"kickoff_spawn",value:n.spawn_position},{key:"support_behavior",value:n.support_behavior}]}function zb(n,e,t){n.count+=1,t.outcome==="neutral"?n.neutral_outcomes+=1:t.outcome===(e?"team_zero_win":"team_one_win")?n.wins+=1:t.outcome===(e?"team_one_win":"team_zero_win")&&(n.losses+=1),t.kickoff_possession_outcome==="contested"?n.contested_kickoff_possessions+=1:t.kickoff_possession_outcome===(e?"team_zero_possession":"team_one_possession")?n.kickoff_possessions+=1:t.kickoff_possession_outcome===(e?"team_one_possession":"team_zero_possession")?n.opponent_kickoff_possessions+=1:t.kickoff_possession_outcome===(e?"team_zero_advantage":"team_one_advantage")?n.kickoff_possession_advantages+=1:n.opponent_kickoff_possession_advantages+=1,t.kickoff_goal&&(n.kickoff_goal_count+=1,t.scoring_team_is_team_0===e?n.kickoff_goals_for+=1:t.scoring_team_is_team_0!=null&&(n.kickoff_goals_against+=1)),t.win_strength!=null&&(n.win_strength_sample_count+=1,n.cumulative_win_strength+=t.win_strength)}function Hb(n,e,t){t&&(t.boost_after!=null&&(n.boost_after_sample_count+=1,n.cumulative_boost_after+=t.boost_after,e.boost_after_sample_count+=1,e.cumulative_boost_after+=t.boost_after),t.outcome==="fake"?(n.fake_count+=1,e.fake_count+=1):t.outcome==="missed"&&(n.missed_count+=1,e.missed_count+=1))}function NB(n,e,t){n.count+=1,XM(n,OB(t)),t.outcome==="touched"?n.touches+=1:t.outcome==="fake"?n.fakes+=1:t.outcome==="missed"&&(n.misses+=1),e.kickoff_goal&&e.scoring_team_is_team_0===t.is_team_0&&(n.kickoff_goal_count+=1),t.boost_after!=null&&(n.boost_after_sample_count+=1,n.cumulative_boost_after+=t.boost_after)}function UB(n,e,t){n.count+=1,XM(n,FB(t)),t.first_touch_time!=null&&(n.touches+=1),t.support_behavior==="go_for_boost"?n.support_go_for_boosts+=1:t.support_behavior==="cheat"?n.support_cheats+=1:t.support_behavior==="other"&&(n.support_other+=1),e.kickoff_goal&&e.scoring_team_is_team_0===t.is_team_0&&(n.kickoff_goal_count+=1),t.boost_after!=null&&(n.boost_after_sample_count+=1,n.cumulative_boost_after+=t.boost_after)}function Ku(n,e,t){const i=$M(t.player),s=n.get(i)??WM();n.set(i,s),"outcome"in t?NB(s,e,t):UB(s,e,t)}function Vb(n,e){Object.assign(n,e)}function BB(n,e){Object.assign(n,e??WM()),e?.labeled_event_counts?n.labeled_event_counts=DB(e.labeled_event_counts):delete n.labeled_event_counts}function zB(n){const e=KM(n);for(const t of n.frames)e.applyFrame(t);return n}function KM(n){const e=kB(be(n,"kickoff"));let t=0;const i=Bb(),s=Bb(),a=new Map;return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function M_(n){return`${n.key}\0${n.value}`}function qu(n){return n.map(M_).join("")}function GB(n,e){e.sort((s,a)=>M_(s).localeCompare(M_(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>qu(s.labels)===qu(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>qu(s.labels).localeCompare(qu(a.labels))))}function $B(n,e){return n.labeled_event_counts?.entries.filter(t=>t.labels.some(i=>i.key==="confidence_band"&&i.value===e)).reduce((t,i)=>t+i.count,0)??0}function WB(n){return n==="forward"||n==="reverse"||n==="side"?n:"other"}function XB(n){return n==="left"||n==="right"?n:"center"}function KB(n){return n.labeled_event_counts?.entries.reduce((e,t)=>e+t.count,0)??0}function qB(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function YB(n,e,t,i){n.is_last_flick=i,n.time_since_last_flick=n.last_flick_time==null?null:Math.max(0,qM(t,n.last_flick_time)),n.frames_since_last_flick=n.last_flick_frame==null?null:Math.max(0,e-n.last_flick_frame)}function jB(n,e,t,i){GB(n,[{key:"confidence_band",value:e.confidence>=HB?"high":"standard"},{key:"kind",value:WB(e.kind)},{key:"direction",value:XB(e.direction)}]),n.count=KB(n),n.high_confidence_count=$B(n,"high"),n.is_last_flick=!0,n.last_flick_time=e.time,n.last_flick_frame=e.frame,n.time_since_last_flick=Math.max(0,qM(i,e.time)),n.frames_since_last_flick=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=cm(n.cumulative_confidence,e.confidence),n.cumulative_setup_duration=cm(n.cumulative_setup_duration,e.setup_duration),n.cumulative_ball_speed_change=cm(n.cumulative_ball_speed_change,e.ball_speed_change)}function ZB(n,e){Object.assign(n,e??YM()),e?.labeled_event_counts?n.labeled_event_counts=qB(e.labeled_event_counts):delete n.labeled_event_counts}function JB(n){const e=jM(n);for(const t of n.frames)e.applyFrame(t);return n}function jM(n){const e=VB(be(n,"flick"));let t=0,i=null;const s=new Map;return{applyFrame(a){if(a.is_live_play){for(const[r,o]of s)YB(o,a.frame_number,a.time,r===i);for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function ez(n,e){n.count+=1,n.total_time_to_use+=e.time_since_reset,n.min_time_to_use=n.min_time_to_use===null?e.time_since_reset:Math.min(n.min_time_to_use,e.time_since_reset)}function tz(n,e){Object.assign(n,e??ZM())}function nz(n){const e=JM(n);for(const t of n.frames)e.applyFrame(t);return n}function JM(n){const e=QB(be(n,"flip_reset"));let t=0;const i=new Map;return{applyFrame(s){for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function sz(n,e,t,i){n.is_last_half_volley=i,n.time_since_last_half_volley=n.last_half_volley_time==null?null:Math.max(0,eE(t,n.last_half_volley_time)),n.frames_since_last_half_volley=n.last_half_volley_frame==null?null:Math.max(0,e-n.last_half_volley_frame)}function az(n,e,t,i){n.count+=1,n.total_ball_speed=QM(n.total_ball_speed,e.ball_speed),n.fastest_ball_speed=Math.max(n.fastest_ball_speed,e.ball_speed),n.last_half_volley_time=e.time,n.last_half_volley_frame=e.frame,n.time_since_last_half_volley=Math.max(0,eE(i,e.time)),n.frames_since_last_half_volley=Math.max(0,t-e.frame)}function rz(n,e){Object.assign(n,e??tE())}function Xb(n,e){Object.assign(n,e)}function oz(n){const e=nE(n);for(const t of n.frames)e.applyFrame(t);return n}function nE(n){const e=iz(be(n,"half_volley"));let t=0,i=null;const s=new Map,a={count:0,total_ball_speed:0,fastest_ball_speed:0},r={count:0,total_ball_speed:0,fastest_ball_speed:0};return{applyFrame(o){for(const[l,c]of s)sz(c,o.frame_number,o.time,o.is_live_play&&l===i);if(!o.is_live_play)i=null;else{let l=!1;for(;te.frame!==t.frame?e.frame-t.frame:e.time!==t.time?e.time-t.time:Yi(e.player).localeCompare(Yi(t.player)))}function dz(n){return[...n].sort((e,t)=>e.resolved_frame!==t.resolved_frame?e.resolved_frame-t.resolved_frame:e.resolved_time!==t.resolved_time?e.resolved_time-t.resolved_time:e.frame!==t.frame?e.frame-t.frame:e.time!==t.time?e.time-t.time:Yi(e.player).localeCompare(Yi(t.player)))}function um(){return{count:0,highConfidenceCount:0,lastTime:null,lastFrame:null,lastResolvedTime:null,lastResolvedFrame:null,lastQuality:null,bestQuality:0,cumulativeQuality:0,labeledCounts:{entries:[]}}}function vo(n){return Math.fround(n)}function hz(n,e){return vo(vo(n)+vo(e))}function fz(n,e){return{key:"confidence_band",value:n>=e?"high":"standard"}}function pz(n,e){const t=e.sort((s,a)=>s.key===a.key?s.value.localeCompare(a.value):s.key.localeCompare(a.key)),i=n.entries.find(s=>s.labels.length===t.length&&s.labels.every((a,r)=>a.key===t[r]?.key&&a.value===t[r]?.value));if(i){i.count+=1;return}n.entries.push({labels:t,count:1}),n.entries.sort((s,a)=>JSON.stringify(s.labels).localeCompare(JSON.stringify(a.labels)))}function Yo(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function dm(n,e,t,i,s){n.count+=1,e.confidence>=s&&(n.highConfidenceCount+=1),pz(n.labeledCounts,[fz(e.confidence,s)]),n.lastTime=e.time,n.lastFrame=e.frame,n.lastResolvedTime=i,n.lastResolvedFrame=t,n.lastQuality=e.confidence,n.bestQuality=Math.max(n.bestQuality,e.confidence),n.cumulativeQuality=hz(n.cumulativeQuality,e.confidence)}function ry(n,e){return n?.lastTime==null?null:n.lastResolvedFrame===e.frame_number?0:Math.max(0,vo(vo(e.time)-vo(n.lastTime)))}function oy(n,e){return n?.lastFrame==null?null:n.lastResolvedFrame===e.frame_number?0:Math.max(0,e.frame_number-n.lastFrame)}function iE(n,e,t,i){n.count=e?.count??0,n.high_confidence_count=e?.highConfidenceCount??0,n.is_last_speed_flip=i,n.last_speed_flip_time=e?.lastTime??null,n.last_speed_flip_frame=e?.lastFrame??null,n.time_since_last_speed_flip=ry(e,t),n.frames_since_last_speed_flip=oy(e,t),n.last_quality=e?.lastQuality??null,n.best_quality=e?.bestQuality??0,n.cumulative_quality=e?.cumulativeQuality??0,e?.labeledCounts.entries.length?n.labeled_event_counts=Yo(e.labeledCounts):delete n.labeled_event_counts}function sE(n,e,t,i){n.count=e?.count??0,n.high_confidence_count=e?.highConfidenceCount??0,n.is_last_half_flip=i,n.last_half_flip_time=e?.lastTime??null,n.last_half_flip_frame=e?.lastFrame??null,n.time_since_last_half_flip=ry(e,t),n.frames_since_last_half_flip=oy(e,t),n.last_quality=e?.lastQuality??null,n.best_quality=e?.bestQuality??0,n.cumulative_quality=e?.cumulativeQuality??0,e?.labeledCounts.entries.length?n.labeled_event_counts=Yo(e.labeledCounts):delete n.labeled_event_counts}function aE(n,e,t,i){n.count=e?.count??0,n.high_confidence_count=e?.highConfidenceCount??0,n.is_last_wavedash=i,n.last_wavedash_time=e?.lastTime??null,n.last_wavedash_frame=e?.lastFrame??null,n.time_since_last_wavedash=ry(e,t),n.frames_since_last_wavedash=oy(e,t),n.last_quality=e?.lastQuality??null,n.best_quality=e?.bestQuality??0,n.cumulative_quality=e?.cumulativeQuality??0,e?.labeledCounts.entries.length?n.labeled_event_counts=Yo(e.labeledCounts):delete n.labeled_event_counts}function mz(n){const e={...n};return n.labeled_event_counts?e.labeled_event_counts=Yo(n.labeled_event_counts):delete e.labeled_event_counts,e}function _z(n){const e={...n};return n.labeled_event_counts?e.labeled_event_counts=Yo(n.labeled_event_counts):delete e.labeled_event_counts,e}function gz(n){const e={...n};return n.labeled_event_counts?e.labeled_event_counts=Yo(n.labeled_event_counts):delete e.labeled_event_counts,e}function yz(n,e){if(e){Object.assign(n,e);return}iE(n,void 0,{frame_number:0,time:0},!1)}function vz(n,e){if(e){Object.assign(n,e);return}sE(n,void 0,{frame_number:0,time:0},!1)}function bz(n,e){if(e){Object.assign(n,e);return}aE(n,void 0,{frame_number:0,time:0},!1)}function xz(n){return n.is_live_play||n.ball_has_been_hit===!1}function wz(n){const e=rE(n);for(const t of n.frames)e.applyFrame(t);return n}function rE(n){const e=dz(be(n,"speed_flip")),t=Kb(be(n,"half_flip")),i=Kb(be(n,"wavedash"));let s=0,a=0,r=0,o=null,l=null,c=null;const u=new Map,d=new Map,h=new Map,f=new Map,p=new Map,g=new Map;return{applyFrame(_){if(xz(_)){for(;sSz.map(e=>({labels:[{key:"height_band",value:n},{key:"speed_band",value:e}],value:0}))).sort((n,e)=>JSON.stringify(n.labels).localeCompare(JSON.stringify(e.labels)))}}function md(n=!1){return{tracked_time:0,total_distance:0,speed_integral:0,time_slow_speed:0,time_boost_speed:0,time_supersonic_speed:0,time_on_ground:0,time_low_air:0,time_high_air:0,labeled_tracked_time:n?Ez():{entries:[]}}}function Cz(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function Az(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function Rz(n,e,t){const i=Az(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=us(s.value,t):(n.entries.push({labels:i,value:pa(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function Pz(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),value:e.value}))}}function Yb(n,e){const t=pa(e.dt);n.tracked_time=us(n.tracked_time,t),n.total_distance=us(n.total_distance,e.distance),n.speed_integral=us(n.speed_integral,Mz(e.speed,t)),e.speed_band==="slow"?n.time_slow_speed=us(n.time_slow_speed,t):e.speed_band==="boost"?n.time_boost_speed=us(n.time_boost_speed,t):e.speed_band==="supersonic"&&(n.time_supersonic_speed=us(n.time_supersonic_speed,t)),e.height_band==="ground"?n.time_on_ground=us(n.time_on_ground,t):e.height_band==="low_air"?n.time_low_air=us(n.time_low_air,t):e.height_band==="high_air"&&(n.time_high_air=us(n.time_high_air,t));const i=n.labeled_tracked_time??{entries:[]};n.labeled_tracked_time=i,Rz(i,[{key:"speed_band",value:e.speed_band},{key:"height_band",value:e.height_band}],t)}function hm(n,e){const t=e??md(!0),i=t.labeled_tracked_time;Object.assign(n,t,{labeled_tracked_time:i?Pz(i):void 0}),i?.entries.length||delete n.labeled_tracked_time}function Iz(n){const e=oE(n);for(const t of n.frames)e.applyFrame(t);return n}function oE(n){const e=Cz(be(n,"movement"));let t=0;const i=new Map,s=md(),a=md();return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function kz(n,e,t,i){n.is_last_one_timer=i,n.time_since_last_one_timer=n.last_one_timer_time==null?null:Math.max(0,t-n.last_one_timer_time),n.frames_since_last_one_timer=n.last_one_timer_frame==null?null:Math.max(0,e-n.last_one_timer_frame)}function Dz(n,e,t,i){n.count+=1,n.total_ball_speed+=e.ball_speed,n.fastest_ball_speed=Math.max(n.fastest_ball_speed,e.ball_speed),n.total_pass_distance+=e.pass_travel_distance,n.last_one_timer_time=e.time,n.last_one_timer_frame=e.frame,n.time_since_last_one_timer=Math.max(0,i-e.time),n.frames_since_last_one_timer=Math.max(0,t-e.frame)}function Oz(n,e){Object.assign(n,e??lE())}function Zb(n,e){Object.assign(n,e)}function Fz(n){const e=cE(n);for(const t of n.frames)e.applyFrame(t);return n}function cE(n){const e=Lz(be(n,"one_timer"));let t=0,i=null;const s=new Map,a={count:0,total_ball_speed:0,fastest_ball_speed:0},r={count:0,total_ball_speed:0,fastest_ball_speed:0};return{applyFrame(o){for(const[l,c]of s)kz(c,o.frame_number,o.time,o.is_live_play&&l===i);if(!o.is_live_play)i=null;else{let l=!1;for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.index-t.index}).map(({event:e})=>e)}function Uz(n,e,t,i){n.is_last_completed_pass=i,n.time_since_last_completed_pass=n.last_completed_pass_time==null?null:Math.max(0,t-n.last_completed_pass_time),n.frames_since_last_completed_pass=n.last_completed_pass_frame==null?null:Math.max(0,e-n.last_completed_pass_frame)}function Bz(n,e,t,i){n.completed_pass_count+=1,n.total_pass_distance+=e.ball_travel_distance,n.total_pass_advance+=e.ball_advance_distance,n.longest_pass_distance=Math.max(n.longest_pass_distance,e.ball_travel_distance),n.last_completed_pass_time=e.time,n.last_completed_pass_frame=e.frame,n.time_since_last_completed_pass=Math.max(0,i-e.time),n.frames_since_last_completed_pass=Math.max(0,t-e.frame)}function zz(n,e){Object.assign(n,e??E_())}function Jb(n,e){Object.assign(n,e)}function Hz(n){const e=uE(n);for(const t of n.frames)e.applyFrame(t);return n}function uE(n){const e=Nz(be(n,"pass"));let t=0,i=null;const s=new Map,a={completed_pass_count:0,total_pass_distance:0,total_pass_advance:0,longest_pass_distance:0},r={completed_pass_count:0,total_pass_distance:0,total_pass_advance:0,longest_pass_distance:0};return{applyFrame(o){for(const[l,c]of s)Uz(c,o.frame_number,o.time,o.is_live_play&&l===i);if(!o.is_live_play)i=null;else{let l=!1;for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function $z(n){return C_(n)}function Wz(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function dE(n,e,t){const i=Wz(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=Ll(s.value,t):(n.entries.push({labels:i,value:Yl(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function Xz(n,e){return n.key==="possession_state"&&n.value==="team_zero"?{key:"possession_state",value:e?"own":"opponent"}:n.key==="possession_state"&&n.value==="team_one"?{key:"possession_state",value:e?"opponent":"own"}:n.key==="field_third"&&n.value==="team_zero_third"?{key:"field_third",value:e?"defensive_third":"offensive_third"}:n.key==="field_third"&&n.value==="team_one_third"?{key:"field_third",value:e?"offensive_third":"defensive_third"}:n.key==="field_half"&&n.value==="team_zero_side"?{key:"field_half",value:e?"defensive_half":"offensive_half"}:n.key==="field_half"&&n.value==="team_one_side"?{key:"field_half",value:e?"offensive_half":"defensive_half"}:{...n}}function Qb(n,e){const t={entries:[]};for(const i of n.labeled_time.entries)dE(t,i.labels.map(s=>Xz(s,e)),i.value);return{tracked_time:n.tracked_time,possession_time:e?n.team_zero_time:n.team_one_time,opponent_possession_time:e?n.team_one_time:n.team_zero_time,neutral_time:n.neutral_time,labeled_time:t}}function Kz(n,e){n.active=e.active,n.possessionState=e.possession_state}function qz(n,e,t){if(!e.active)return;const i=Yl(t.dt);n.tracked_time=Ll(n.tracked_time,i),e.possessionState==="team_zero"?n.team_zero_time=Ll(n.team_zero_time,i):e.possessionState==="team_one"?n.team_one_time=Ll(n.team_one_time,i):n.neutral_time=Ll(n.neutral_time,i);const s=[{key:"possession_state",value:e.possessionState}];e.fieldThird!=null&&s.push({key:"field_third",value:e.fieldThird}),e.fieldHalf!=null&&s.push({key:"field_half",value:e.fieldHalf}),dE(n.labeled_time,s,i)}function ex(n,e){Object.assign(n,e??Gz())}function Yz(n){const e=hE(n);for(const t of n.frames)e.applyFrame(t);return n}function hE(n){const e=$z(be(n,"possession")),t=C_(be(n,"ball_third")),i=C_(be(n,"ball_half"));let s=0,a=0,r=0;const o=Vz(),l={active:!1,possessionState:"neutral",fieldThird:null,fieldHalf:null};return{applyFrame(c){for(;s({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function Va(n,e){const t=wh(e.player),i=n.get(t)??fE();return n.set(t,i),i}function Zz(n,e){switch(n.active_game_time=Kt(n.active_game_time,e.duration),e.state){case"tracked":n.tracked_time=Kt(n.tracked_time,e.duration);break;case"demolished":n.time_demolished=Kt(n.time_demolished,e.duration);break}}function Jz(n,e){switch(e.state){case"defensive":n.time_defensive_third=Kt(n.time_defensive_third,e.duration);break;case"neutral":n.time_neutral_third=Kt(n.time_neutral_third,e.duration);break;case"offensive":n.time_offensive_third=Kt(n.time_offensive_third,e.duration);break}}function Qz(n,e){switch(e.state){case"defensive":n.time_defensive_half=Kt(n.time_defensive_half,e.duration);break;case"offensive":n.time_offensive_half=Kt(n.time_offensive_half,e.duration);break}}function e5(n,e){switch(e.state){case"behind_ball":n.time_behind_ball=Kt(n.time_behind_ball,e.duration);break;case"level_with_ball":n.time_level_with_ball=Kt(n.time_level_with_ball,e.duration);break;case"ahead_of_ball":n.time_in_front_of_ball=Kt(n.time_in_front_of_ball,e.duration);break}}function t5(n,e){switch(e.state){case"no_teammates":n.time_no_teammates=Kt(n.time_no_teammates,e.duration);break;case"most_back":n.time_most_back=Kt(n.time_most_back,e.duration);break;case"most_forward":n.time_most_forward=Kt(n.time_most_forward,e.duration);break;case"mid":n.time_mid_role=Kt(n.time_mid_role,e.duration);break;case"other":n.time_other_role=Kt(n.time_other_role,e.duration);break}}function n5(n,e,t){t.state.closest_to_ball_team&&(e.tracked_time=Kt(e.tracked_time,t.duration),e.time_closest_to_ball_team=Kt(e.time_closest_to_ball_team,t.duration),n.time_closest_to_ball_team=Kt(n.time_closest_to_ball_team,t.duration)),t.state.closest_to_ball_absolute&&(e.time_closest_to_ball_absolute=Kt(e.time_closest_to_ball_absolute,t.duration),n.time_closest_to_ball_absolute=Kt(n.time_closest_to_ball_absolute,t.duration)),t.state.farthest_from_ball&&(n.time_farthest_from_ball=Kt(n.time_farthest_from_ball,t.duration))}function i5(n,e){e.state==="shadowing"&&(n.time_shadow_defense=Kt(n.time_shadow_defense,e.duration))}function s5(n,e){Object.assign(n,e??fE())}function tx(n,e){Object.assign(n,e??A_())}function Ga(n,e){const t=jz(n),i=new Array(t.length).fill(0);return{applyThroughFrame(s){for(let a=0;as.frame_number)break;const o=a5(r,s),l=o-i[a];l>0&&(i[a]=o,e({...r,duration:l}))}}}}function a5(n,e){if(e.frame_number>=n.end_frame)return n.duration;const t=n.end_time-n.time;if(t<=0)return 0;const i=Math.max(0,e.time-n.time);return n.duration*Math.min(1,i/t)}function r5(n){const e=pE(n);for(const t of n.frames)e.applyFrame(t);return n}function pE(n){const e=new Map,t=A_(),i=A_(),s=[Ga(be(n,"player_activity"),a=>Zz(Va(e,a),a)),Ga(be(n,"field_third"),a=>Jz(Va(e,a),a)),Ga(be(n,"field_half"),a=>Qz(Va(e,a),a)),Ga(be(n,"ball_depth"),a=>e5(Va(e,a),a)),Ga(be(n,"depth_role"),a=>t5(Va(e,a),a)),Ga(be(n,"ball_proximity"),a=>n5(Va(e,a),a.is_team_0?t:i,a)),Ga(be(n,"shadow_defense"),a=>i5(Va(e,a),a))];return{applyFrame(a){for(const r of s)r.applyThroughFrame(a);tx(a.team_zero.positioning,t),tx(a.team_one.positioning,i);for(const r of a.players)s5(r.positioning,e.get(wh(r.player_id))),o5(r.positioning,n,r.player_id)}}}function o5(n,e,t){const i=e.positioning_summary;if(!Array.isArray(i))return;const s=wh(t),a=i.find(r=>!r||typeof r!="object"?!1:wh(r.player_id)===s);a?.distance&&Object.assign(n,a.distance)}function pm(n){if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function kl(){return{total_duration:0,press_count:0}}function l5(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function c5(n){return n.gameplay_phase==="active_play"||n.gameplay_phase==="kickoff_waiting_for_touch"}function mm(n,e){Object.assign(n,e??kl())}function u5(n){const e=mE(n);for(const t of n.frames)e.applyFrame(t);return n}function mE(n){const e=l5(be(n,"powerslide"));let t=0;const i=new Map,s=new Map,a=kl(),r=kl();return{applyFrame(o){const l=c5(o);for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function p5(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function _E(n,e,t){const i=p5(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=Dl(s.value,t):(n.entries.push({labels:i,value:jl(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function m5(n,e){return n.key==="field_half"&&n.value==="team_zero_side"?{key:"field_half",value:e?"defensive_half":"offensive_half"}:n.key==="field_half"&&n.value==="team_one_side"?{key:"field_half",value:e?"offensive_half":"defensive_half"}:{...n}}function nx(n,e){const t={entries:[]};for(const i of n.labeled_time.entries)_E(t,i.labels.map(s=>m5(s,e)),i.value);return{tracked_time:n.tracked_time,defensive_half_time:e?n.team_zero_side_time:n.team_one_side_time,offensive_half_time:e?n.team_one_side_time:n.team_zero_side_time,neutral_time:n.neutral_time,labeled_time:t}}function _5(n,e){n.active=e.active,n.fieldHalf=e.field_half}function g5(n,e,t){if(!e.active)return;const i=jl(t.dt);n.tracked_time=Dl(n.tracked_time,i),e.fieldHalf==="team_zero_side"?n.team_zero_side_time=Dl(n.team_zero_side_time,i):e.fieldHalf==="team_one_side"?n.team_one_side_time=Dl(n.team_one_side_time,i):n.neutral_time=Dl(n.neutral_time,i),_E(n.labeled_time,[{key:"field_half",value:e.fieldHalf}],i)}function ix(n,e){Object.assign(n,e??h5())}function y5(n){const e=gE(n);for(const t of n.frames)e.applyFrame(t);return n}function gE(n){const e=f5(be(n,"ball_half"));let t=0;const i=d5(),s={active:!1,fieldHalf:"neutral"};return{applyFrame(a){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function w5(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function yE(n,e,t){const i=w5(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=Ol(s.value,t):(n.entries.push({labels:i,value:Zl(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function S5(n,e){return n.key==="field_third"&&n.value==="team_zero_third"?{key:"field_third",value:e?"defensive_third":"offensive_third"}:n.key==="field_third"&&n.value==="team_one_third"?{key:"field_third",value:e?"offensive_third":"defensive_third"}:{...n}}function sx(n,e){const t={entries:[]};for(const i of n.labeled_time.entries)yE(t,i.labels.map(s=>S5(s,e)),i.value);return{tracked_time:n.tracked_time,defensive_third_time:e?n.team_zero_third_time:n.team_one_third_time,neutral_third_time:n.neutral_third_time,offensive_third_time:e?n.team_one_third_time:n.team_zero_third_time,labeled_time:t}}function T5(n,e){n.active=e.active,n.fieldThird=e.field_third}function M5(n,e,t){if(!e.active)return;const i=Zl(t.dt);n.tracked_time=Ol(n.tracked_time,i),e.fieldThird==="team_zero_third"?n.team_zero_third_time=Ol(n.team_zero_third_time,i):e.fieldThird==="team_one_third"?n.team_one_third_time=Ol(n.team_one_third_time,i):n.neutral_third_time=Ol(n.neutral_third_time,i),yE(n.labeled_time,[{key:"field_third",value:e.fieldThird}],i)}function ax(n,e){Object.assign(n,e??b5())}function E5(n){const e=vE(n);for(const t of n.frames)e.applyFrame(t);return n}function vE(n){const e=x5(be(n,"ball_third"));let t=0;const i=v5(),s={active:!1,fieldThird:"neutral_third"};return{applyFrame(a){for(;t({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function A5(n,e,t){n.session_count+=1,n.session_time=Yu(n.session_time,t.duration),n.offensive_half_time=Yu(n.offensive_half_time,t.offensive_half_time),n.offensive_third_time=Yu(n.offensive_third_time,t.offensive_third_time),n.longest_session_time=Math.max(n.longest_session_time,t.duration),n.average_session_time=n.session_count===0?0:_d(n.session_time/n.session_count),e.opponent_session_count+=1,e.opponent_session_time=Yu(e.opponent_session_time,t.duration),e.opponent_longest_session_time=Math.max(e.opponent_longest_session_time,t.duration)}function ox(n,e){Object.assign(n,e)}function R5(n){const e=bE(n);for(const t of n.frames)e.applyFrame(t);return n}function bE(n){const e=C5(be(n,"territorial_pressure"));let t=0;const i=rx(),s=rx();return{applyFrame(a){for(;t=e[t].end_frame;){const r=e[t];A5(r.team_is_team_0?i:s,r.team_is_team_0?s:i,r),t+=1}ox(a.team_zero.territorial_pressure,i),ox(a.team_one.territorial_pressure,s)}}}function io(n,e){return Math.fround(Math.fround(n)+Math.fround(e))}function xE(n){if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function wE(){return{active_game_time:0,time_first_man:0,time_second_man:0,time_third_man:0,time_ambiguous_role:0,longest_first_man_stint_time:0,first_man_stint_count:0,became_first_man_count:0,lost_first_man_count:0,current_role_state:"unknown"}}function lx(){return{first_man_changes_for_team:0,rotation_count:0}}function cx(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function P5(n,e,t,i,s){const a=n.stats;switch(a.active_game_time=io(a.active_game_time,t),a.current_role_state=e.state,e.state){case"first_man":{n.lastFirstManEndTime!==null&&e.time-n.lastFirstManEndTime<=s?n.currentFirstManStintTime=io(n.currentFirstManStintTime,t):(n.currentFirstManStintTime=t,a.first_man_stint_count+=1),n.lastFirstManEndTime=i,a.longest_first_man_stint_time=Math.max(a.longest_first_man_stint_time,n.currentFirstManStintTime),a.time_first_man=io(a.time_first_man,t);break}case"second_man":a.time_second_man=io(a.time_second_man,t);break;case"third_man":a.time_third_man=io(a.time_third_man,t);break;case"ambiguous":a.time_ambiguous_role=io(a.time_ambiguous_role,t);break}}function I5(n,e){if(e.frame_number>=n.end_frame)return n.duration;const t=n.end_time-n.time;if(t<=0)return 0;const i=Math.max(0,e.time-n.time);return n.duration*Math.min(1,i/t)}function R_(n,e){const t=xE(e),i=n.get(t)??{currentFirstManStintTime:0,lastFirstManEndTime:null,stats:wE()};return n.set(t,i),i}function L5(n,e,t){n.first_man_changes_for_team+=1,n.rotation_count+=1,R_(e,t.previous_first_man).stats.lost_first_man_count+=1,R_(e,t.next_first_man).stats.became_first_man_count+=1}function k5(n,e){Object.assign(n,e??wE())}function ux(n,e){Object.assign(n,e)}function D5(n){const e=SE(n);for(const t of n.frames)e.applyFrame(t);return n}function SE(n){const e=cx(be(n,"rotation_role")),t=cx(be(n,"first_man_change")),i=n.config.rotation_first_man_stint_end_grace_seconds,s=new Array(e.length).fill(0);let a=0;const r=new Map,o=lx(),l=lx();return{applyFrame(c){for(let u=0;uc.frame_number)break;const h=I5(d,c),f=h-s[u];if(f>0){s[u]=h;const p=c.frame_number>=d.end_frame?d.end_time:Math.min(c.time,d.end_time);P5(R_(r,d.player),d,f,p,i)}}for(;a({event:e,index:t})).sort((e,t)=>e.event.start_frame!==t.event.start_frame?e.event.start_frame-t.event.start_frame:e.event.start_time!==t.event.start_time?e.event.start_time-t.event.start_time:e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.index-t.index).map(({event:e})=>e)}function F5(n,e){n.count+=1,e.attackers===2&&e.defenders===1?n.two_v_one_count+=1:e.attackers===2&&e.defenders===2?n.two_v_two_count+=1:e.attackers===2&&e.defenders===3?n.two_v_three_count+=1:e.attackers===3&&e.defenders===1?n.three_v_one_count+=1:e.attackers===3&&e.defenders===2?n.three_v_two_count+=1:e.attackers===3&&e.defenders===3&&(n.three_v_three_count+=1)}function hx(n,e){Object.assign(n,e)}function N5(n){const e=TE(n);for(const t of n.frames)e.applyFrame(t);return n}function TE(n){const e=O5(be(n,"rush"));let t=0;const i=dx(),s=dx(),a=n.config.rush_min_possession_retained_seconds;return{applyFrame(r){for(;t=e[t].start_frame&&r.time-e[t].start_time>=a;){const o=e[t];F5(o.is_team_0?i:s,o),t+=1}hx(r.team_zero.rush,i),hx(r.team_one.rush,s)}}}const U5=["control","hard_hit","medium_hit"],B5=["ground","high_air","low_air"],z5=["air","ground","wall"],H5=["dodge","no_dodge"];function bo(n){return Math.fround(n)}function gd(n,e){return bo(bo(n)+bo(e))}function ME(n,e){return bo(bo(n)-bo(e))}function _m(n){if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function V5(){return{entries:H5.flatMap(n=>B5.flatMap(e=>U5.flatMap(t=>z5.map(i=>({labels:[{key:"dodge_state",value:n},{key:"height_band",value:e},{key:"kind",value:t},{key:"surface",value:i}],count:0}))))).sort((n,e)=>JSON.stringify(n.labels).localeCompare(JSON.stringify(e.labels)))}}function EE(){return{touch_count:0,control_touch_count:0,medium_hit_count:0,hard_hit_count:0,aerial_touch_count:0,high_aerial_touch_count:0,wall_touch_count:0,first_touch_count:0,is_last_touch:!1,last_touch_time:null,last_touch_frame:null,time_since_last_touch:null,frames_since_last_touch:null,last_ball_speed_change:null,max_ball_speed_change:0,cumulative_ball_speed_change:0,total_ball_travel_distance:0,total_ball_advance_distance:0,total_ball_retreat_distance:0,labeled_touch_counts:V5()}}const G5=EE();function fx(){return{stats:EE(),labeledCountsVersion:0,labeledCountsSnapshot:void 0,labeledCountsSnapshotVersion:-1}}function $5(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function W5(n,e){e.sort((s,a)=>s.key===a.key?s.value.localeCompare(a.value):s.key.localeCompare(a.key));const t=n.labeled_touch_counts?.entries??[];n.labeled_touch_counts={entries:t};const i=t.find(s=>s.labels.length===e.length&&s.labels.every((a,r)=>a.key===e[r]?.key&&a.value===e[r]?.value));i?i.count+=1:(t.push({labels:e,count:1}),t.sort((s,a)=>JSON.stringify(s.labels).localeCompare(JSON.stringify(a.labels))))}function X5(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function ju(n,e){return n.tags?.find(t=>t.group===e)?.value??null}function K5(n,e,t){const i=ju(e,"kind")??"control",s=ju(e,"height_band")??"ground",a=ju(e,"surface")??"ground",r=ju(e,"dodge_state")??"no_dodge",o=n.stats;o.touch_count+=1,i==="control"?o.control_touch_count+=1:i==="medium_hit"?o.medium_hit_count+=1:i==="hard_hit"&&(o.hard_hit_count+=1),s==="low_air"?o.aerial_touch_count+=1:s==="high_air"&&(o.aerial_touch_count+=1,o.high_aerial_touch_count+=1),a==="wall"&&(o.wall_touch_count+=1),W5(o,[{key:"kind",value:i},{key:"height_band",value:s},{key:"surface",value:a},{key:"dodge_state",value:r}]),n.labeledCountsVersion+=1,o.last_touch_time=e.time,o.last_touch_frame=e.frame,o.time_since_last_touch=Math.max(0,ME(t.time,e.time)),o.frames_since_last_touch=Math.max(0,t.frame_number-e.frame),o.last_ball_speed_change=e.ball_speed_change,o.max_ball_speed_change=Math.max(o.max_ball_speed_change,e.ball_speed_change),o.cumulative_ball_speed_change=gd(o.cumulative_ball_speed_change,e.ball_speed_change)}function q5(n){return n.labeledCountsSnapshotVersion!==n.labeledCountsVersion&&(n.labeledCountsSnapshot=n.stats.labeled_touch_counts?X5(n.stats.labeled_touch_counts):void 0,n.labeledCountsSnapshotVersion=n.labeledCountsVersion),n.labeledCountsSnapshot}function Y5(n,e){if(!e){Object.assign(n,G5);return}Object.assign(n,e.stats,{labeled_touch_counts:q5(e)})}function j5(n){const e=CE(n);for(const t of n.frames)e.applyFrame(t);return n}function CE(n){const e=$5(be(n,"touch")),t=e.flatMap(o=>o.ball_movement?[{player:o.player,movement:o.ball_movement}]:[]).sort((o,l)=>o.movement.end_frame!==l.movement.end_frame?o.movement.end_frame-l.movement.end_frame:o.movement.end_time-l.movement.end_time);let i=0,s=0,a=null;const r=new Map;return{applyFrame(o){if(!o.is_live_play)a=null;else{for(const l of r.values()){const c=l.stats;c.is_last_touch=!1,c.last_touch_time!=null&&(c.time_since_last_touch=Math.max(0,ME(o.time,c.last_touch_time))),c.last_touch_frame!=null&&(c.frames_since_last_touch=Math.max(0,o.frame_number-c.last_touch_frame))}for(;i({event:e,index:t})).sort((e,t)=>e.event.resolved_frame!==t.event.resolved_frame?e.event.resolved_frame-t.event.resolved_frame:e.event.resolved_time!==t.event.resolved_time?e.event.resolved_time-t.event.resolved_time:e.index-t.index).map(({event:e})=>e)}function Q5(n,e,t){n.is_last_whiff=!1,n.time_since_last_whiff=n.last_whiff_time==null?null:Math.max(0,t-n.last_whiff_time),n.frames_since_last_whiff=n.last_whiff_frame==null?null:Math.max(0,e-n.last_whiff_frame)}function eH(n,e,t,i){if((e.kind??"whiff")==="beaten_to_ball"){n.beaten_to_ball_count+=1;return}n.whiff_count+=1,e.aerial?n.aerial_whiff_count+=1:n.grounded_whiff_count+=1,e.dodge_active&&(n.dodge_whiff_count+=1),n.is_last_whiff=!0,n.last_whiff_time=e.time,n.last_whiff_frame=e.frame,n.time_since_last_whiff=Math.max(0,i-e.time),n.frames_since_last_whiff=Math.max(0,t-e.frame),n.last_closest_approach_distance=e.closest_approach_distance,n.best_closest_approach_distance=n.best_closest_approach_distance==null?e.closest_approach_distance:Math.min(n.best_closest_approach_distance,e.closest_approach_distance),n.cumulative_closest_approach_distance+=e.closest_approach_distance}function px(n,e){Object.assign(n,e??P_())}function tH(n){const e=AE(n);for(const t of n.frames)e.applyFrame(t);return n}function AE(n){const e=J5(be(n,"whiff"));let t=0,i=null;const s=new Map,a=new Map;return{applyFrame(r){if(r.is_live_play){for(const o of s.values())Q5(o,r.frame_number,r.time);for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function sH(n,e,t,i){n.is_last_wall_aerial=i,n.time_since_last_wall_aerial=n.last_wall_aerial_time==null?null:Math.max(0,RE(t,n.last_wall_aerial_time)),n.frames_since_last_wall_aerial=n.last_wall_aerial_frame==null?null:Math.max(0,e-n.last_wall_aerial_frame)}function aH(n,e,t,i){n.count+=1,e.confidence>=nH&&(n.high_confidence_count+=1),n.is_last_wall_aerial=!0,n.last_wall_aerial_time=e.time,n.last_wall_aerial_frame=e.frame,n.time_since_last_wall_aerial=Math.max(0,RE(i,e.time)),n.frames_since_last_wall_aerial=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=Zu(n.cumulative_confidence,e.confidence),n.cumulative_setup_duration=Zu(n.cumulative_setup_duration,e.setup_duration),n.cumulative_takeoff_to_touch_time=Zu(n.cumulative_takeoff_to_touch_time,e.time_since_takeoff),n.cumulative_touch_height=Zu(n.cumulative_touch_height,e.player_position[2]??0)}function rH(n,e){Object.assign(n,e??PE())}function oH(n){const e=IE(n);for(const t of n.frames)e.applyFrame(t);return n}function IE(n){const e=iH(be(n,"wall_aerial"));let t=0,i=null;const s=new Map;return{applyFrame(a){for(const[r,o]of s)sH(o,a.frame_number,a.time,a.is_live_play&&r===i);if(!a.is_live_play)i=null;else{for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function uH(n,e,t,i){n.is_last_wall_aerial_shot=i,n.time_since_last_wall_aerial_shot=n.last_wall_aerial_shot_time==null?null:Math.max(0,LE(t,n.last_wall_aerial_shot_time)),n.frames_since_last_wall_aerial_shot=n.last_wall_aerial_shot_frame==null?null:Math.max(0,e-n.last_wall_aerial_shot_frame)}function dH(n,e,t,i){n.count+=1,e.confidence>=lH&&(n.high_confidence_count+=1),n.is_last_wall_aerial_shot=!0,n.last_wall_aerial_shot_time=e.time,n.last_wall_aerial_shot_frame=e.frame,n.time_since_last_wall_aerial_shot=Math.max(0,LE(i,e.time)),n.frames_since_last_wall_aerial_shot=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=ym(n.cumulative_confidence,e.confidence),n.cumulative_takeoff_to_shot_time=ym(n.cumulative_takeoff_to_shot_time,e.time_since_takeoff),n.cumulative_shot_height=ym(n.cumulative_shot_height,e.player_position[2]??0)}function hH(n,e){Object.assign(n,e??kE())}function fH(n){const e=DE(n);for(const t of n.frames)e.applyFrame(t);return n}function DE(n){const e=cH(be(n,"wall_aerial_shot"));let t=0,i=null;const s=new Map;return{applyFrame(a){for(const[r,o]of s)uH(o,a.frame_number,a.time,a.is_live_play&&r===i);if(!a.is_live_play)i=null;else{let r=!1;for(;t[f.frame_number,p])),a=new Map,r={...n,frames:[]},o=gH.flatMap(f=>f.createFrameAccumulator?[f.createFrameAccumulator(r)]:[]),l=Math.max(1,t.materializationChunkSize??pH),c=Math.max(l,t.maxMaterializationChunkSize??mH);let u=-1,d=l;const h=f=>{if(f<=u)return;const p=Math.min(i.length-1,Math.max(f,u+d));for(let g=u+1;g<=p;g+=1){const _=i[g],m=_?xH(bH(_)):void 0;if(m){for(const v of o)v.applyFrame(m);a.set(m.frame_number,m)}}u=p,d=Math.min(c,i.length,d*_H)};return{get(f){const p=s.get(f);if(p!==void 0)return h(p),a.get(f)}}}function vH(n){return!n||typeof n!="object"?n:{...n}}function bH(n){return{...n,team_zero:{...n.team_zero},team_one:{...n.team_one},players:n.players.map(e=>({...e,player_id:vH(e.player_id)}))}}function xH(n){return{...n,team_zero:Bo(n.team_zero??{}),team_one:Bo(n.team_one??{}),players:n.players.map(t=>cy(t))}}function pc(n){return n.events?.events??[]}function be(n,e){return pc(n).filter(t=>t.payload.kind===e).map(t=>t.payload.payload)}const wH=new Set(["is_team_0","name","player_id"]);function gx(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0}function SH(n){return!n||typeof n!="object"||Array.isArray(n)?!1:Object.keys(n).every(e=>wH.has(e))}function TH(n){return gx(n.team_zero)&&gx(n.team_one)&&n.players.every(e=>SH(e))}function MH(n){return new Map(bM(n).frames.map(e=>[e.frame_number,e]))}function OE(n,e,t){const i=n.frames.filter(s=>TH(s)).length;if(i===n.frames.length)return yH(n,e,t);if(i>0)throw new Error("stats timeline frames must be either all compact scaffolds or all materialized snapshots");return MH(n)}function Ht(n,e){return n.get(e)??null}const uy=[{stage:"validating",index:1,total:9,label:"Parse replay",start:0,end:.08},{stage:"processing",index:2,total:9,label:"Process replay frames",start:.08,end:.62},{stage:"building-stats",index:3,total:9,label:"Build stats events",start:.62,end:.7},{stage:"serializing-replay",index:4,total:9,label:"Serialize replay data",start:.7,end:.76},{stage:"serializing-stats",index:5,total:9,label:"Serialize stats timeline",start:.76,end:.86},{stage:"normalizing",index:6,total:9,label:"Normalize replay model",start:.86,end:.91},{stage:"decoding-replay",index:7,total:9,label:"Decode replay data",start:.91,end:.94},{stage:"decoding-stats",index:8,total:9,label:"Decode stats chunks",start:.94,end:.96},{stage:"deriving-stats",index:9,total:9,label:"Derive stats snapshots",start:.96,end:1}];function FE(n){return Math.max(0,Math.min(1,n))}function vm(n,e,t){if(n!==void 0)return FE((n-e)/(t-e))}function dy(n){if(n.stage!=="stats-timeline")return n;const e=n.progress;return e===void 0?{...n,stage:"building-stats"}:e<.35?{...n,stage:"building-stats",progress:vm(e,0,.35)}:e<.55?{...n,stage:"serializing-replay",progress:vm(e,.35,.55)}:{...n,stage:"serializing-stats",progress:vm(e,.55,.92)}}function NE(n){const e=dy(n);return uy.find(t=>t.stage===e.stage)}function EH(){return uy.map(({stage:n,index:e,total:t,label:i})=>({stage:n,index:e,total:t,label:i}))}function CH(n){const e=NE(n);return{stage:e.stage,index:e.index,total:e.total,label:e.label}}function AH(n){const e=dy(n),t=NE(e);return uy.map(({stage:i,index:s,total:a,label:r})=>{if(st.index)return{stage:i,index:s,total:a,label:r,state:"pending",completion:0,indeterminate:!1};const o=e.progress!==void 0;return{stage:i,index:s,total:a,label:r,state:"active",completion:o?FE(e.progress??0):1,indeterminate:!o}})}function jo(n){const e=dy(n),t=e.progress===void 0?null:Math.round(e.progress*100);switch(e.stage){case"validating":return"Parsing replay...";case"processing":return t!==null&&e.totalFrames!==void 0?`Processing replay frames... ${t}% (${e.processedFrames??0}/${e.totalFrames})`:"Processing replay frames...";case"building-stats":return t!==null?e.totalFrames!==void 0?`Building stats events... ${t}% (${e.processedFrames??0}/${e.totalFrames})`:`Building stats events... ${t}%`:"Building stats events...";case"serializing-replay":return t!==null?`Serializing replay data... ${t}%`:"Serializing replay data...";case"serializing-stats":return t!==null?`Serializing stats timeline... ${t}%`:"Serializing stats timeline...";case"decoding-replay":return t!==null?`Decoding replay data... ${t}%`:"Decoding replay data...";case"decoding-stats":return t!==null?e.totalChunks!==void 0?`Decoding stats chunks... ${t}% (${e.processedChunks??0}/${e.totalChunks})`:`Decoding stats chunks... ${t}%`:"Decoding stats chunks...";case"deriving-stats":return t!==null?`Deriving stats snapshots... ${t}%`:"Deriving stats snapshots...";case"normalizing":return t!==null?`Normalizing replay model... ${t}%`:"Normalizing replay model...";default:return"Loading replay..."}}function RH(n){return n instanceof Error?n:new Error(String(n))}function Fs(n,e){return JSON.parse(n.decode(new Uint8Array(e)))}async function PH(n,e,t){t?.({stage:"decoding-stats",progress:0});const i=Fs(n,e.configBuffer);t?.({stage:"decoding-stats",progress:.05}),await ar();const s=Fs(n,e.replayMetaBuffer);t?.({stage:"decoding-stats",progress:.1}),await ar();const a=Fs(n,e.eventsBuffer),r=Fs(n,e.activitySummaryBuffer),o=Fs(n,e.positioningSummaryBuffer),l=Fs(n,e.accumulationTracksBuffer);t?.({stage:"decoding-stats",progress:.15}),await ar();const c=[],u=e.frameChunkBuffers.length;for(let d=0;d{let t=!1,i=null;const s=()=>{t||(t=!0,i!==null&&clearTimeout(i),e())};i=setTimeout(s,n),requestAnimationFrame(()=>s())})}async function Cf(n,e={}){if(typeof Worker>"u")throw new Error("Replay loading worker is not available in this environment");const t=new Worker(new URL(""+new URL("replayLoader.worker-D3pjMe81.js",import.meta.url).href,import.meta.url),{type:"module"}),i=n.slice(),s=e.reportEveryNFrames??100;return new Promise((a,r)=>{const o=()=>{t.terminate()};t.onmessage=async c=>{const u=c.data;if(u.type==="progress"){e.onProgress?.(u.progress);return}if(u.type==="error"){o(),r(new Error(u.error));return}o();try{const d=new TextDecoder;e.onProgress?.({stage:"decoding-replay",progress:0}),await ar();const h=Fs(d,u.replayBuffer);e.onProgress?.({stage:"decoding-replay",progress:.5}),await ar();const f=Fs(d,u.rawReplayBuffer);e.onProgress?.({stage:"decoding-replay",progress:1}),await ar();const p=await PH(d,u.statsTimelineParts,e.onProgress),g=OE(p);a({replay:h,raw:f,statsTimeline:p,statsFrameLookup:g})}catch(d){r(RH(d))}},t.onerror=c=>{o(),r(new Error(c.message||"Replay loading worker failed"))};const l={type:"load-replay",bytes:i.buffer,reportEveryNFrames:s};t.postMessage(l,[i.buffer])})}function IH(n){const e=document.createElement("div");e.className="replay-load-modal",e.hidden=!0;const t=document.createElement("div");t.className="replay-load-modal__dialog",t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-labelledby","replay-load-modal-title");const i=document.createElement("p");i.className="replay-load-modal__eyebrow",i.textContent="Replay loading";const s=document.createElement("h2");s.id="replay-load-modal-title",s.className="replay-load-modal__title",s.textContent="Preparing replay pipeline";const a=document.createElement("p");a.className="replay-load-modal__status",a.textContent="Preparing replay...";const r=document.createElement("div");r.className="replay-load-modal__phase-list";const o=new Map;for(const f of EH()){const p=document.createElement("div");p.className="replay-load-modal__phase-row",p.dataset.state="pending";const g=document.createElement("p");g.className="replay-load-modal__phase-label",g.textContent=`${f.index}. ${f.label}`;const _=document.createElement("div");_.className="replay-load-modal__phase-bar";const m=document.createElement("div");m.className="replay-load-modal__phase-fill",m.dataset.indeterminate="false",_.append(m),p.append(g,_),r.append(p),o.set(f.stage,{row:p,fill:m})}const l=document.createElement("p");l.className="replay-load-modal__meta",t.append(i,s,a,r,l),e.append(t),n.append(e);let c="";const u=()=>{for(const{row:f,fill:p}of o.values())f.dataset.state="pending",p.style.width="0%",p.dataset.indeterminate="false"},d=f=>{for(const p of AH(f)){const g=o.get(p.stage);g&&(g.row.dataset.state=p.state,g.fill.dataset.indeterminate=p.indeterminate?"true":"false",g.fill.style.width=`${Math.round(p.completion*100)}%`)}},h=f=>{e.hidden=!f};return{show(f,p="Preparing replay..."){c=f,h(!0),u(),s.textContent="Preparing replay pipeline",a.textContent=p,l.textContent=`Loading ${f}`},update(f){h(!0);const p=CH(f);if(d(f),s.textContent=`Phase ${p.index} of ${p.total}: ${p.label}`,a.textContent=jo(f),f.stage==="processing"&&f.totalFrames!==void 0){l.textContent=`${f.processedFrames??0}/${f.totalFrames} frames`;return}if(f.stage==="decoding-stats"&&f.totalChunks!==void 0){l.textContent=`${f.processedChunks??0}/${f.totalChunks} chunks`;return}l.textContent=c?`Loading ${c}`:""},hide(){h(!1)},destroy(){e.remove()}}}const LH=["free","follow"];function UE(n){return n.useReplayBallCam??!1?"player":n.ballCamEnabled?"on":"off"}function yx(n){return n.useReplayBallCam?"player":n.ballCam===!0?"on":n.ballCam===!1?"off":"player"}const BE={fov:110,height:100,pitch:-4,distance:270,stiffness:0,swivelSpeed:1,transitionSpeed:1};class hy{constructor(e){this.options=e}lastFreeCameraPreset=null;get freeCameraPreset(){return this.lastFreeCameraPreset}set freeCameraPreset(e){this.lastFreeCameraPreset=e}ballCamModeValue="player";get ballCamMode(){return this.ballCamModeValue}autoPossessionEnabledValue=!1;get autoPossessionEnabled(){return this.autoPossessionEnabledValue}static ballCamEnabledForMode(e){return e==="player"?null:e==="on"}followPlayerWithReplayCamera(e,t={}){const i=this.options.getReplayPlayer();i&&(t.preserveAutoPossession||this.setAutoPossessionEnabled(!1,{requestConfigSync:!1}),i.setAttachedPlayer(e),i.setCameraViewMode("follow"),t.usePlayerCameraSettings!==!1&&i.setCustomCameraSettings(null),this.setBallCamMode(t.ballCam??"player"),this.lastFreeCameraPreset=null,t.requestConfigSync!==!1&&this.options.requestConfigSync())}setAutoPossessionEnabled(e,t={}){if(this.autoPossessionEnabledValue===e){this.renderAutoPossessionButton();return}this.autoPossessionEnabledValue=e,this.renderAutoPossessionButton(),t.notify!==!1&&this.options.onAutoPossessionChange?.(e),t.requestConfigSync!==!1&&this.options.requestConfigSync()}renderBallCamButtons(){const{ballCamOffButton:e,ballCamOnButton:t,ballCamPlayerButton:i}=this.options.elements,s=[["off",e],["on",t],["player",i]];for(const[a,r]of s){const o=a===this.ballCamModeValue;r.dataset.active=o?"true":"false",r.setAttribute("aria-pressed",o?"true":"false")}}renderAutoPossessionButton(){this.options.elements.cameraViewAutoPossession.checked=this.autoPossessionEnabledValue}disableAutoPossessionForManualCameraControl(){this.setAutoPossessionEnabled(!1,{requestConfigSync:!1})}setBallCamMode(e){this.ballCamModeValue=e,this.options.getReplayPlayer()?.setBallCamEnabled(hy.ballCamEnabledForMode(e)),this.renderBallCamButtons()}get nameplateLiftUu(){const e=Number(this.options.elements.nameplateLift.value);return Number.isFinite(e)?e:u_}applyNameplateLiftUu(e){const{nameplateLift:t,nameplateLiftReadout:i}=this.options.elements,s=e??u_;t.value=`${s}`,i.textContent=Jn(s,"",0)}installEventListeners(e){const{elements:t}=this.options;t.usePlayerCameraSettings.addEventListener("change",()=>{const s=t.usePlayerCameraSettings.checked;t.cameraSettingsControls.hidden=s,this.options.getReplayPlayer()?.setCustomCameraSettings(s?null:this.readCustomCameraSettings()),this.options.requestConfigSync()},{signal:e});for(const s of[t.customCameraFov,t.customCameraHeight,t.customCameraPitch,t.customCameraDistance,t.customCameraStiffness,t.customCameraSwivelSpeed,t.customCameraTransitionSpeed])s.addEventListener("input",()=>{const a=this.readCustomCameraSettings();this.syncCustomCameraSettingControls(a),this.options.getReplayPlayer()?.setCustomCameraSettings(a),this.options.requestConfigSync()},{signal:e});t.attachedPlayer.addEventListener("change",()=>{const s=this.options.getReplayPlayer(),a=t.attachedPlayer.value||null;this.disableAutoPossessionForManualCameraControl(),s?.setAttachedPlayer(a),a&&(s?.setCustomCameraSettings(null),this.setBallCamMode("player")),this.lastFreeCameraPreset=null,this.options.requestConfigSync()},{signal:e}),t.cameraViewFreeButton.addEventListener("click",()=>{this.options.getReplayPlayer()?.setCameraViewMode("free"),this.disableAutoPossessionForManualCameraControl(),this.lastFreeCameraPreset=null,this.options.requestConfigSync()},{signal:e}),t.cameraViewFollowButton.addEventListener("click",()=>{const s=this.options.getReplayPlayer();this.disableAutoPossessionForManualCameraControl(),s?.setCameraViewMode("follow"),s?.getState().attachedPlayerId&&(s.setCustomCameraSettings(null),this.setBallCamMode("player")),this.lastFreeCameraPreset=null,this.options.requestConfigSync()},{signal:e}),t.cameraViewOverheadButton.addEventListener("click",()=>{this.options.getReplayPlayer()?.setFreeCameraPreset("overhead"),this.disableAutoPossessionForManualCameraControl(),this.lastFreeCameraPreset="overhead",this.options.requestConfigSync()},{signal:e}),t.cameraViewSideButton.addEventListener("click",()=>{this.options.getReplayPlayer()?.setFreeCameraPreset("side"),this.disableAutoPossessionForManualCameraControl(),this.lastFreeCameraPreset="side",this.options.requestConfigSync()},{signal:e});const i=[["off",t.ballCamOffButton],["on",t.ballCamOnButton],["player",t.ballCamPlayerButton]];for(const[s,a]of i)a.addEventListener("click",()=>{this.setBallCamMode(s),this.options.requestConfigSync()},{signal:e});t.cameraViewAutoPossession.addEventListener("change",()=>{this.setAutoPossessionEnabled(t.cameraViewAutoPossession.checked)},{signal:e}),t.nameplateLift.addEventListener("input",()=>{t.nameplateLiftReadout.textContent=Jn(this.nameplateLiftUu,"",0),this.options.requestConfigSync()},{signal:e})}setTransportEnabled(e,t){this.options.elements.attachedPlayer.disabled=!e,this.syncModeButtons(e?t:void 0)}syncState(e){const{elements:t}=this.options;t.usePlayerCameraSettings.checked=e.customCameraSettings===null,t.cameraSettingsControls.hidden=t.usePlayerCameraSettings.checked,this.syncCustomCameraSettingControls(e.customCameraSettings??this.getFallbackCameraSettings()),this.ballCamModeValue=UE(e),this.renderBallCamButtons(),t.attachedPlayer.value=e.attachedPlayerId??"",this.syncAvailability(e),this.renderProfile(e)}syncAvailability(e){this.syncModeButtons(e);const i=this.options.getReplayPlayer()!==null&&e?.cameraViewMode==="follow"&&(e.attachedPlayerId??null)!==null;this.options.elements.usePlayerCameraSettings.disabled=!i,this.setCameraSettingControlsEnabled(i&&e?.customCameraSettings!==null),this.options.elements.ballCamOffButton.disabled=!i,this.options.elements.ballCamOnButton.disabled=!i,this.options.elements.ballCamPlayerButton.disabled=!i,this.renderBallCamButtons()}syncModeButtons(e){const t=e?.cameraViewMode??"free",i=this.options.getReplayPlayer()!==null&&e!==void 0,s=(e?.attachedPlayerId??null)!==null;for(const l of LH){const c=this.getCameraViewButton(l);c.disabled=!i||l==="follow"&&!s;const u=l===t;c.dataset.active=u?"true":"false",c.setAttribute("aria-pressed",u?"true":"false")}const{cameraViewOverheadButton:a,cameraViewSideButton:r}=this.options.elements,{cameraViewAutoPossession:o}=this.options.elements;a.disabled=!i,r.disabled=!i,o.disabled=!i,a.dataset.active="false",r.dataset.active="false",this.renderAutoPossessionButton(),a.setAttribute("aria-pressed","false"),r.setAttribute("aria-pressed","false")}populateAttachedPlayerOptions(e){const{attachedPlayer:t}=this.options.elements;t.replaceChildren(),t.append(new Option("Free camera",""));for(const i of e)t.append(new Option(`${i.name} (${i.isTeamZero?"Blue":"Orange"})`,i.id))}renderProfile(e){const t=this.options.elements,i=this.options.getReplayPlayer(),s=e?.attachedPlayerId??null;if(!i||e?.cameraViewMode!=="follow"||s===null){this.renderEmptyProfile("Free camera");return}const a=i.replay.players.find(o=>o.id===s);if(!a){this.renderEmptyProfile("Unknown");return}const r=this.getEffectiveCameraSettings(e);t.cameraProfileReadout.textContent=e.customCameraSettings===null?a.name:`${a.name} custom`,t.cameraFovReadout.textContent=Jn(r.fov,"",0),t.cameraHeightReadout.textContent=Jn(r.height,"",0),t.cameraPitchReadout.textContent=Jn(r.pitch,"",0),t.cameraBaseDistanceReadout.textContent=Jn(r.distance,"",0),t.cameraStiffnessReadout.textContent=Jn(r.stiffness,"",2)}getFallbackCameraSettings(){return BE}getAttachedPlayerCameraSettings(e){const t=this.options.getReplayPlayer();return!t||e===null?null:t.replay.players.find(i=>i.id===e)?.cameraSettings??null}getEffectiveCameraSettings(e){return{...this.getFallbackCameraSettings(),...this.getAttachedPlayerCameraSettings(e.attachedPlayerId)??{},...e.customCameraSettings??{}}}readCustomCameraSettings(){const e=this.options.elements;return{fov:Number(e.customCameraFov.value),height:Number(e.customCameraHeight.value),pitch:Number(e.customCameraPitch.value),distance:Number(e.customCameraDistance.value),stiffness:Number(e.customCameraStiffness.value),swivelSpeed:Number(e.customCameraSwivelSpeed.value),transitionSpeed:Number(e.customCameraTransitionSpeed.value)}}setCameraSettingControlsEnabled(e){const t=this.options.elements;t.cameraSettingsControls.hidden=t.usePlayerCameraSettings.checked,t.customCameraFov.disabled=!e,t.customCameraHeight.disabled=!e,t.customCameraPitch.disabled=!e,t.customCameraDistance.disabled=!e,t.customCameraStiffness.disabled=!e,t.customCameraSwivelSpeed.disabled=!e,t.customCameraTransitionSpeed.disabled=!e}syncCustomCameraSettingControls(e){const t=this.options.elements,i=this.getFallbackCameraSettings(),s=e.fov??i.fov,a=e.height??i.height,r=e.pitch??i.pitch,o=e.distance??i.distance,l=e.stiffness??i.stiffness,c=e.swivelSpeed??i.swivelSpeed,u=e.transitionSpeed??i.transitionSpeed;t.customCameraFov.value=`${s}`,t.customCameraHeight.value=`${a}`,t.customCameraPitch.value=`${r}`,t.customCameraDistance.value=`${o}`,t.customCameraStiffness.value=`${l}`,t.customCameraSwivelSpeed.value=`${c}`,t.customCameraTransitionSpeed.value=`${u}`,t.customCameraFovReadout.textContent=Jn(s,"",0),t.customCameraHeightReadout.textContent=Jn(a,"",0),t.customCameraPitchReadout.textContent=Jn(r,"",0),t.customCameraDistanceReadout.textContent=Jn(o,"",0),t.customCameraStiffnessReadout.textContent=Jn(l,"",2),t.customCameraSwivelSpeedReadout.textContent=Jn(c,"",1),t.customCameraTransitionSpeedReadout.textContent=Jn(u,"",2)}getCameraViewButton(e){switch(e){case"free":return this.options.elements.cameraViewFreeButton;case"follow":return this.options.elements.cameraViewFollowButton}}renderEmptyProfile(e){const t=this.options.elements;t.cameraProfileReadout.textContent=e,t.cameraFovReadout.textContent="--",t.cameraHeightReadout.textContent="--",t.cameraPitchReadout.textContent="--",t.cameraBaseDistanceReadout.textContent="--",t.cameraStiffnessReadout.textContent="--"}}function Jn(n,e="",t=0){return n===void 0||Number.isNaN(n)?"--":`${n.toFixed(t)}${e}`}function kH(n){return new hy(n)}const vx="subtr-actor-touch-overlay-styles",fy=5882879,py=16761180,bx=120,xx=4,DH=196,bm=24,wx=210,Sx=5,OH=.1,FH=48,NH=["team","intention","kind","height_band","surface","dodge_state","flag"],UH=[{label:"Blue team",color:fy},{label:"Orange team",color:py}],zE=[{label:"Shot",color:16711880},{label:"Save",color:58998},{label:"Clear",color:16764928},{label:"Boom",color:16020150},{label:"Pass",color:47103},{label:"Control",color:0},{label:"Advance",color:16486972}],yd=[{label:"Control",color:0},{label:"Medium hit",color:16436245},{label:"Hard hit",color:16735596}],vd=[{label:"Ground",color:10741301},{label:"Low air",color:3718648},{label:"High air",color:8490232}],HE=[{label:"Ground",color:8702998},{label:"Air",color:6333946},{label:"Wall",color:16347926}],I_=[{label:"No dodge",color:9741240},{label:"Dodge",color:15235577}],L_=[{label:"First touch",color:16777215},{label:"Contested",color:15680580}],BH=[{title:"Team",entries:UH},{title:"Intention",entries:zE},{title:"Hit strength",entries:yd},{title:"Height",entries:vd},{title:"Surface",entries:HE},{title:"Dodge",entries:I_},{title:"Flags",entries:L_}];function Lc(n){return Object.fromEntries(n.map(e=>[e.label.toLowerCase().replaceAll(" ","_"),e.color]))}const VE=Lc(zE),GE={...Lc(yd),medium_hit:yd[1].color,hard_hit:yd[2].color},$E={...Lc(vd),low_air:vd[1].color,high_air:vd[2].color},WE=Lc(HE),XE={...Lc(I_),no_dodge:I_[0].color},k_={first_touch:L_[0].color,contested:L_[1].color},qi=10134961;function ei(n,e){const t=n.tags;if(!Array.isArray(t))return null;const i=t.find(s=>s.group===e);return i?i.value:null}function KE(n){return ei(n,"possession")??ei(n,"action")}function Ct(n){const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function xm(n,e){return Math.max(0,n-e)}function bd(n){return n==="team"||n==="intention"||n==="kind"||n==="height_band"||n==="surface"||n==="dodge_state"||n==="flag"}function So(n){const e=Array.isArray(n)?n:n?[n]:["team"],t=new Set,i=[];for(const s of e)bd(s)&&!t.has(s)&&(t.add(s),i.push(s));return i.length>0?i:["team"]}function qE(n){return n[n.length-1]??"team"}function zH(n,e,t){const i=HH(n,qE(t)),s=i?` · ${i.replaceAll("_"," ")}`:"";if(e==="markers")return`${n.playerName}${s}`;const a=Math.round(n.totalBallAdvanceDistance),r=Math.round(n.totalBallRetreatDistance);return a>0&&r>0?`${n.playerName} +${a} / -${r} uu${s}`:r>0?`${n.playerName} -${r} uu${s}`:`${n.playerName} +${a} uu${s}`}function HH(n,e){return e==="intention"?n.intention:e==="kind"?n.kind:e==="height_band"?n.heightBand:e==="surface"?n.surface:e==="dodge_state"?n.dodgeState:e==="flag"?n.contested?"contested":n.firstTouch?"first_touch":null:null}function VH(n){return n.split("_").filter(Boolean).map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1)}`).join(" ")}function bl(n,e,t){return typeof e!="string"||e.length===0?null:{key:n,value:e,label:VH(e),color:t[e]??qi}}function Tx(n,e,t){return e!==!0?null:{key:n,value:"true",label:t,color:k_[n]??qi}}function GH(n){const e=ei(n,"reception")==="first_touch",t=ei(n,"contested")!=null;return[bl("intention",KE(n),VE),bl("kind",ei(n,"kind"),GE),bl("height_band",ei(n,"height_band"),$E),bl("surface",ei(n,"surface"),WE),bl("dodge_state",ei(n,"dodge_state"),XE),Tx("first_touch",e,"First touch"),Tx("contested",t,"Contested")].filter(i=>i!=null)}function YE(n,e){return e==="intention"?VE[n.intention??""]??qi:e==="kind"?GE[n.kind??""]??qi:e==="height_band"?$E[n.heightBand??""]??qi:e==="surface"?WE[n.surface??""]??qi:e==="dodge_state"?XE[n.dodgeState??""]??qi:e==="flag"?n.contested?k_.contested??qi:n.firstTouch?k_.first_touch??qi:qi:n.isTeamZero?fy:py}function $H(n,e){return(e.length>0?e:["team"]).map(i=>YE(n,i))}function jE(n,e){const t=[],i=[...be(n,"touch")].sort((s,a)=>s.frame!==a.frame?s.frame-a.frame:s.time!==a.time?s.time-a.time:0);for(const s of i){const a=Ct(s.player),r=e.ballFrames[s.frame]?.position;if(!r)continue;const o=s.ball_movement,c=(o?e.ballFrames[o.end_frame]?.position:null)??r,u=t.length,d=GH(s);t.push({id:`touch-stat:${s.frame}:${a}:${u+1}`,time:e.frames[s.frame]?.time??s.time,frame:s.frame,isTeamZero:s.is_team_0,playerId:a,playerName:e.players.find(h=>h.id===a)?.name??a,kind:ei(s,"kind"),intention:KE(s),heightBand:ei(s,"height_band"),surface:ei(s,"surface"),dodgeState:ei(s,"dodge_state"),firstTouch:ei(s,"reception")==="first_touch",contested:ei(s,"contested")!=null,classifications:d,position:{x:r.x,y:r.y,z:r.z},endPosition:{x:c.x,y:c.y,z:c.z},totalBallTravelDistance:o?xm(o.travel_distance,0):0,totalBallAdvanceDistance:o?xm(o.advance_distance,0):0,totalBallRetreatDistance:o?xm(o.retreat_distance,0):0})}return t}function WH(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function XH(){if(document.getElementById(vx))return;const n=document.createElement("style");n.id=vx,n.textContent=` +`}const tn="#3b82f6",nn="#f59e0b",K3=new Set(["wavedash"]),q3=new Set(["air_dribble","ball_carry","ceiling_shot","double_tap","flick","flip_reset","half_flip","half_volley","one_timer","speed_flip","wall_aerial","wall_aerial_shot","wavedash"]);function Dn(n){return n.split(/[_-]+/).filter(e=>e.length>0).map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1)}`).join(" ")}function yb(n){return q3.has(n)&&!K3.has(n)}function Lf(n){return n===!0?tn:n===!1?nn:null}const AM=["timeline","core_player","player_possession","possession","loose_possession","ball_half","ball_third","territorial_pressure","movement","player_activity","field_third","field_half","ball_depth","depth_role","ball_proximity","shadow_defense","rotation_role","first_man_change","goal_context","backboard","ceiling_shot","wall_aerial","wall_aerial_shot","center","flick","flip_reset","dodge_reset","double_tap","fifty_fifty","kickoff","one_timer","pass","ball_carry","controlled_play","rush","dodge","speed_flip","half_flip","half_volley","wavedash","whiff","powerslide","touch","boost_pickups","boost_respawn","bump","demolition"],RM=["air_dribble","ball_carry","ceiling_shot","double_tap","flick","flip_reset","half_flip","half_volley","one_timer","speed_flip","wall_aerial","wall_aerial_shot","wavedash"],dy=[...new Set([...AM,...RM])],Y3=new Set(RM);function go(){return Object.fromEntries(dy.map(n=>[n,0]))}function rm(n){return{...n??go()}}function Wu(n,e){n[e]+=1}function j3(n){return dy.includes(n)}function PM(n){if(n==null)return null;if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function y_(n){return PM(n.meta.primary_player)}function Z3(n){return n.meta.team_is_team_0??null}function J3(n){const e=n.meta.stream;return!Y3.has(e)||!j3(e)?null:e}function v_(n){const e=n.meta.timing.type==="span"?n.meta.timing.end_frame:n.meta.timing.frame;return typeof e=="number"&&Number.isFinite(e)?e:null}function b_(n){const e=n.meta.timing.type==="span"?n.meta.timing.end_time:n.meta.timing.time;return typeof e=="number"&&Number.isFinite(e)?e:null}function Q3(n,e){const t=v_(n);if(t!==null)return t<=e.frame_number;const i=b_(n);return i!==null&&i<=e.time}function eB(n){return[...n].sort((e,t)=>{const i=v_(e),s=v_(t);if(i!==s)return(i??Number.POSITIVE_INFINITY)-(s??Number.POSITIVE_INFINITY);const a=b_(e),r=b_(t);return a!==r?(a??Number.POSITIVE_INFINITY)-(r??Number.POSITIVE_INFINITY):(y_(e)??"").localeCompare(y_(t)??"")})}function IM(n){const e=LM(n);for(const t of n.frames)e.applyFrame(t);return n}function LM(n){const e=dy.map(s=>({eventType:s,events:eB(yc(n).filter(a=>a.meta.stream===s)),index:0})),t=new Map,i={teamZero:go(),teamOne:go()};return{applyFrame(s){for(const a of e)for(;a.index({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function nB(n,e,t,i){n.is_last_backboard=i,n.time_since_last_backboard=n.last_backboard_time==null?null:Math.max(0,t-n.last_backboard_time),n.frames_since_last_backboard=n.last_backboard_frame==null?null:Math.max(0,e-n.last_backboard_frame)}function iB(n,e,t,i){n.count+=1,n.last_backboard_time=e.time,n.last_backboard_frame=e.frame,n.time_since_last_backboard=Math.max(0,i-e.time),n.frames_since_last_backboard=Math.max(0,t-e.frame)}function sB(n,e){Object.assign(n,e??kM())}function bb(n,e){n.count=e}function aB(n){const e=DM(n);for(const t of n.frames)e.applyFrame(t);return n}function DM(n){const e=tB(be(n,"backboard"));let t=0,i=0,s=0,a=null;const r=new Map;return{applyFrame(o){for(const[c,u]of r)nB(u,o.frame_number,o.time,c===a);let l=!1;for(;t({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function x_(n){return`${n.key}\0${n.value}`}function Xu(n){return n.map(x_).join("")}function OM(n,e){e.sort((s,a)=>x_(s).localeCompare(x_(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Xu(s.labels)===Xu(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Xu(s.labels).localeCompare(Xu(a.labels))))}function wb(n,e){return n.labeled_event_counts?.entries.filter(t=>t.labels.some(i=>i.key==="origin"&&i.value===e)).reduce((t,i)=>t+i.count,0)??0}function FM(n){return n.labeled_event_counts?.entries.reduce((e,t)=>e+t.count,0)??0}function NM(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function Sb(n,e){OM(n,[{key:"kind",value:"carry"}]),n.carry_count=FM(n),n.total_carry_time+=e.duration,n.total_straight_line_distance+=e.straight_line_distance,n.total_path_distance+=e.path_distance,n.longest_carry_time=Math.max(n.longest_carry_time,e.duration),n.furthest_carry_distance=Math.max(n.furthest_carry_distance,e.straight_line_distance),n.fastest_carry_speed=Math.max(n.fastest_carry_speed,e.average_speed),n.carry_speed_sum+=e.average_speed,n.average_horizontal_gap_sum+=e.average_horizontal_gap,n.average_vertical_gap_sum+=e.average_vertical_gap}function Tb(n,e){e.air_dribble_origin!=null&&OM(n,[{key:"origin",value:e.air_dribble_origin}]),n.count=FM(n),n.ground_to_air_count=wb(n,"ground_to_air"),n.wall_to_air_count=wb(n,"wall_to_air"),n.total_time+=e.duration,n.total_straight_line_distance+=e.straight_line_distance,n.total_path_distance+=e.path_distance,n.longest_time=Math.max(n.longest_time,e.duration),n.furthest_distance=Math.max(n.furthest_distance,e.straight_line_distance),n.fastest_speed=Math.max(n.fastest_speed,e.average_speed),n.speed_sum+=e.average_speed,n.average_horizontal_gap_sum+=e.average_horizontal_gap,n.average_vertical_gap_sum+=e.average_vertical_gap,n.total_touch_count+=e.touch_count,n.max_touch_count=Math.max(n.max_touch_count,e.touch_count)}function om(n,e){Object.assign(n,e??gd()),e?.labeled_event_counts?n.labeled_event_counts=NM(e.labeled_event_counts):delete n.labeled_event_counts}function lm(n,e){Object.assign(n,e??yd()),e?.labeled_event_counts?n.labeled_event_counts=NM(e.labeled_event_counts):delete n.labeled_event_counts}function oB(n){const e=UM(n);for(const t of n.frames)e.applyFrame(t);return n}function UM(n){const e=rB(be(n,"ball_carry"));let t=0;const i=new Map,s=new Map,a=gd(),r=gd(),o=yd(),l=yd();return{applyFrame(c){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function cB(n,e){n.bumps_inflicted+=1,e.is_team_bump&&(n.team_bumps_inflicted+=1),n.last_bump_time=e.time,n.last_bump_frame=e.frame,n.last_bump_strength=e.strength,n.max_bump_strength=Math.max(n.max_bump_strength,e.strength),n.cumulative_bump_strength+=e.strength}function uB(n,e){n.bumps_taken+=1,e.is_team_bump&&(n.team_bumps_taken+=1)}function dB(n,e){n.bumps_inflicted+=1,e.is_team_bump&&(n.team_bumps_inflicted+=1)}function hB(n,e){Object.assign(n,e??w_())}function Eb(n,e){Object.assign(n,e)}function fB(n){const e=BM(n);for(const t of n.frames)e.applyFrame(t);return n}function BM(n){const e=lB(be(n,"bump"));let t=0;const i=new Map,s=Mb(),a=Mb();return{applyFrame(r){for(;t=t&&n0&&(s.overfill_total=an(s.overfill_total,i),e.field_half==="opponent"&&(s.overfill_from_stolen=an(s.overfill_from_stolen,i)))}function Rb(n,e){e.boost_granted!=null&&(n.stats.amount_respawned=an(n.stats.amount_respawned,on(e.boost_granted)))}class vB{constructor(e){this.points=e}index=0;sample(e){for(;this.index+1e?0:on(t.value)}}function E_(n,e){return`${n}:${e}`}function bB(n){const e=new Map,t=n.accumulation_tracks;for(const i of t??[]){const s=Dl(i.player_id);e.set(E_(s,i.quantity),new vB(i.points))}return e}function xB(n){return[...be(n,"boost_pickup")].sort((e,t)=>e.frame-t.frame||e.time-t.time)}function wB(n){return[...be(n,"respawn")].sort((e,t)=>e.frame-t.frame||e.time-t.time)}function dm(n,e){for(const t of zM)n[t]=e[t]}function HM(n){const e=xB(n),t=wB(n),i=bB(n);let s=0,a=0;const r=new Map,o=um(),l=um(),c=(d,h)=>{const f=Dl(d);let p=r.get(f);return p||(p=um(),r.set(f,p)),p.isTeamZero=h,p},u=(d,h,f)=>{const p=g=>i.get(E_(h,g))?.sample(f)??0;d.amount_used=p("boost_used"),d.amount_used_while_grounded=p("boost_used_grounded"),d.amount_used_while_airborne=p("boost_used_airborne"),d.amount_used_while_supersonic=p("boost_used_supersonic")};return{applyFrame(d,h){for(;s({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function C_(n){return`${n.key}\0${n.value}`}function qu(n){return n.map(C_).join("")}function AB(n,e){e.sort((s,a)=>C_(s).localeCompare(C_(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>qu(s.labels)===qu(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>qu(s.labels).localeCompare(qu(a.labels))))}function RB(n,e){return n.labeled_event_counts?.entries.filter(t=>t.labels.some(i=>i.key==="confidence_band"&&i.value===e)).reduce((t,i)=>t+i.count,0)??0}function PB(n){return n.labeled_event_counts?.entries.reduce((e,t)=>e+t.count,0)??0}function IB(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function LB(n,e,t,i){n.is_last_ceiling_shot=i,n.time_since_last_ceiling_shot=n.last_ceiling_shot_time==null?null:Math.max(0,VM(t,n.last_ceiling_shot_time)),n.frames_since_last_ceiling_shot=n.last_ceiling_shot_frame==null?null:Math.max(0,e-n.last_ceiling_shot_frame)}function kB(n,e,t,i){AB(n,[{key:"confidence_band",value:e.confidence>=MB?"high":"standard"}]),n.count=PB(n),n.high_confidence_count=RB(n,"high"),n.is_last_ceiling_shot=!0,n.last_ceiling_shot_time=e.time,n.last_ceiling_shot_frame=e.frame,n.time_since_last_ceiling_shot=Math.max(0,VM(i,e.time)),n.frames_since_last_ceiling_shot=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=EB(n.cumulative_confidence,e.confidence)}function DB(n,e){Object.assign(n,e??GM()),e?.labeled_event_counts?n.labeled_event_counts=IB(e.labeled_event_counts):delete n.labeled_event_counts}function OB(n){const e=$M(n);for(const t of n.frames)e.applyFrame(t);return n}function $M(n){const e=CB(be(n,"ceiling_shot"));let t=0,i=null;const s=new Map;return{applyFrame(a){if(a.is_live_play){for(const[r,o]of s)LB(o,a.frame_number,a.time,i===r);for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function BB(n,e){Object.assign(n,e??hy())}function Lb(n,e){Object.assign(n,e)}function kb(n,e){n.score+=e.score_delta,n.goals+=e.goals_delta,n.assists+=e.assists_delta,n.saves+=e.saves_delta,n.shots+=e.shots_delta}function WM(n,e){if(e.time_after_kickoff!=null){const t=Math.max(0,e.time_after_kickoff);t<10?n.kickoff_goal_count+=1:t<20?n.short_goal_count+=1:t<40?n.medium_goal_count+=1:n.long_goal_count+=1}if(e.goal_buildup==="counter_attack"?n.counter_attack_goal_count+=1:e.goal_buildup==="sustained_pressure"?n.sustained_pressure_goal_count+=1:e.goal_buildup!=null&&(n.other_buildup_goal_count+=1),e.ball_air_time_before_goal!=null){const t=Math.max(0,e.ball_air_time_before_goal);n.goal_ball_air_time_sample_count+=1,n.cumulative_goal_ball_air_time=us(n.cumulative_goal_ball_air_time,t),n.last_goal_ball_air_time=t}}function hm(n,e){return n!=null&&e!=null&&gc(n)===gc(e)}function Db(n,e){return n?e.y:-e.y}function zB(n,e){if(n.ball_position==null||e.position==null)return!1;const t=!n.scoring_team_is_team_0,i=Db(t,n.ball_position);if(i>FB)return!1;const s=Db(t,e.position);return s=UB}function HB(n,e,t){const i=t.is_team_0===e.scoring_team_is_team_0,s=hm(t.player,e.defending_team_most_back_player),a=hm(t.player,e.scoring_team_most_back_player);s&&(n.goals_conceded_while_last_defender+=1),a&&(n.goals_for_while_most_back+=1),s&&(n.goals_against_while_most_back+=1),!i&&zB(e,t)&&(n.caught_ahead_of_play_on_conceded_goals+=1),!i&&t.boost_amount!=null&&(n.goal_against_boost_sample_count+=1,n.cumulative_boost_on_goals_against=us(n.cumulative_boost_on_goals_against,t.boost_amount),n.last_boost_on_goal_against=t.boost_amount),!i&&t.average_boost_in_leadup!=null&&t.min_boost_in_leadup!=null&&(n.goal_against_boost_leadup_sample_count+=1,n.cumulative_average_boost_in_goal_against_leadup=us(n.cumulative_average_boost_in_goal_against_leadup,t.average_boost_in_leadup),n.cumulative_min_boost_in_goal_against_leadup=us(n.cumulative_min_boost_in_goal_against_leadup,t.min_boost_in_leadup),n.last_average_boost_in_goal_against_leadup=t.average_boost_in_leadup,n.last_min_boost_in_goal_against_leadup=t.min_boost_in_leadup),!i&&t.position!=null&&(n.goal_against_position_sample_count+=1,n.cumulative_goal_against_position_x=us(n.cumulative_goal_against_position_x,t.position.x),n.cumulative_goal_against_position_y=us(n.cumulative_goal_against_position_y,t.position.y),n.cumulative_goal_against_position_z=us(n.cumulative_goal_against_position_z,t.position.z),n.last_goal_against_position={...t.position});const r=hm(t.player,e.scorer),o=r?e.scorer_last_touch?.ball_position:null;o!=null&&(n.scoring_goal_last_touch_position_sample_count+=1,n.cumulative_scoring_goal_last_touch_position_x=us(n.cumulative_scoring_goal_last_touch_position_x,o.x),n.cumulative_scoring_goal_last_touch_position_y=us(n.cumulative_scoring_goal_last_touch_position_y,o.y),n.cumulative_scoring_goal_last_touch_position_z=us(n.cumulative_scoring_goal_last_touch_position_z,o.z),n.last_scoring_goal_last_touch_position={...o}),r&&WM(n,e)}function VB(n,e,t,i){WM(i.scoring_team_is_team_0?e:t,i);for(const s of i.players){const a=gc(s.player),r=n.get(a)??hy();n.set(a,r),HB(r,i,s)}}function GB(n){const e=XM(n);for(const t of n.frames)e.applyFrame(t);return n}function XM(n){const e=Ib(be(n,"core_player")),t=Ib(be(n,"goal_context"));let i=0,s=0;const a=new Map,r=A_(),o=A_();return{applyFrame(l){for(;i({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function Nb(n,e){n.count+=1,n.total_time=Ob(n.total_time,e.duration),n.longest_time=Math.max(n.longest_time,e.duration),n.touch_count+=e.touch_count,n.total_advance_distance=Ob(n.total_advance_distance,e.total_advance_distance)}function pm(n,e){Object.assign(n,e??vd())}function WB(n){const e=KM(n);for(const t of n.frames)e.applyFrame(t);return n}function KM(n){const e=$B(be(n,"controlled_play"));let t=0;const i=new Map,s=vd(),a=vd();return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function KB(n,e){n.count+=1,e.on_ball&&(n.on_ball_count+=1)}function qB(n,e){Object.assign(n,e??qM())}function YB(n){const e=YM(n);for(const t of n.frames)e.applyFrame(t);return n}function YM(n){const e=XB(be(n,"dodge_reset"));let t=0;const i=new Map;return{applyFrame(s){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function ZB(n,e,t,i){n.is_last_double_tap=i,n.time_since_last_double_tap=n.last_double_tap_time==null?null:Math.max(0,t-n.last_double_tap_time),n.frames_since_last_double_tap=n.last_double_tap_frame==null?null:Math.max(0,e-n.last_double_tap_frame)}function JB(n,e,t,i){n.count+=1,n.last_double_tap_time=e.time,n.last_double_tap_frame=e.frame,n.time_since_last_double_tap=Math.max(0,i-e.time),n.frames_since_last_double_tap=Math.max(0,t-e.frame)}function QB(n,e){Object.assign(n,e??jM())}function zb(n,e){n.count=e}function ez(n){const e=ZM(n);for(const t of n.frames)e.applyFrame(t);return n}function ZM(n){const e=jB(be(n,"double_tap"));let t=0,i=0,s=0,a=null;const r=new Map;return{applyFrame(o){for(const[c,u]of r)ZB(u,o.frame_number,o.time,c===a);let l=!1;for(;t({event:e,index:t})).sort((e,t)=>e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function nz(n,e){Object.assign(n,e??JM())}function Gb(n,e){Object.assign(n,e)}function iz(n){const e=QM(n);for(const t of n.frames)e.applyFrame(t);return n}function QM(n){const e=tz(be(n,"demolition"));let t=0;const i=new Map,s=Vb(),a=Vb();function r(o){const l=Hb(o),c=i.get(l)??JM();return i.set(l,c),c}return{applyFrame(o){for(;t({event:e,index:t})).sort((e,t)=>e.event.resolve_frame!==t.event.resolve_frame?e.event.resolve_frame-t.event.resolve_frame:e.event.resolve_time!==t.event.resolve_time?e.event.resolve_time-t.event.resolve_time:e.index-t.index).map(({event:e})=>e)}function az(n){return{key:"phase",value:n?"kickoff":"open_play"}}function rz(n,e){return e==null?{key:"outcome",value:"neutral"}:{key:"outcome",value:e===n?"win":"loss"}}function oz(n,e){return e==null?{key:"possession_after",value:"neutral"}:{key:"possession_after",value:e===n?"self":"opponent"}}function lz(n,e){return{key:"dodge_state",value:(n?e.team_zero_dodge_contact:e.team_one_dodge_contact)?"dodge":"no_dodge"}}function P_(n){return`${n.key}\0${n.value}`}function Yu(n){return n.map(P_).join("")}function cz(n,e){e.sort((s,a)=>P_(s).localeCompare(P_(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Yu(s.labels)===Yu(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Yu(s.labels).localeCompare(Yu(a.labels))))}function uz(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function Wb(n,e,t){n.count+=1,t.winning_team_is_team_0==null?n.neutral_outcomes+=1:t.winning_team_is_team_0===e?n.wins+=1:n.losses+=1,t.possession_team_is_team_0==null?n.neutral_possession_after_count+=1:t.possession_team_is_team_0===e?n.possession_after_count+=1:n.opponent_possession_after_count+=1,t.is_kickoff&&(n.kickoff_count+=1,t.winning_team_is_team_0==null?n.kickoff_neutral_outcomes+=1:t.winning_team_is_team_0===e?n.kickoff_wins+=1:n.kickoff_losses+=1,t.possession_team_is_team_0==null?n.kickoff_neutral_possession_after_count+=1:t.possession_team_is_team_0===e?n.kickoff_possession_after_count+=1:n.kickoff_opponent_possession_after_count+=1)}function Xb(n,e,t){cz(n,[az(t.is_kickoff),rz(e,t.winning_team_is_team_0),oz(e,t.possession_team_is_team_0),lz(e,t)]),n.count+=1,t.winning_team_is_team_0==null?n.neutral_outcomes+=1:t.winning_team_is_team_0===e?n.wins+=1:n.losses+=1,t.possession_team_is_team_0===e&&(n.possession_after_count+=1),t.is_kickoff&&(n.kickoff_count+=1,t.winning_team_is_team_0==null?n.kickoff_neutral_outcomes+=1:t.winning_team_is_team_0===e?n.kickoff_wins+=1:n.kickoff_losses+=1,t.possession_team_is_team_0===e&&(n.kickoff_possession_after_count+=1))}function dz(n,e){Object.assign(n,e??R_()),e?.labeled_event_counts?n.labeled_event_counts=uz(e.labeled_event_counts):delete n.labeled_event_counts}function Kb(n,e){Object.assign(n,e)}function hz(n){const e=eE(n);for(const t of n.frames)e.applyFrame(t);return n}function eE(n){const e=sz(be(n,"fifty_fifty"));let t=0;const i=$b(),s=$b(),a=new Map;return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function I_(n){return`${n.key}\0${n.value}`}function ju(n){return n.map(I_).join("")}function iE(n,e){e.sort((s,a)=>I_(s).localeCompare(I_(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>ju(s.labels)===ju(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>ju(s.labels).localeCompare(ju(a.labels))))}function pz(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function mz(n){return[{key:"kickoff_spawn",value:n.spawn_position},{key:"taker_outcome",value:n.outcome},{key:"kickoff_approach",value:n.approach},{key:"approach_flip_direction",value:n.approach_flip_direction}]}function _z(n){return[{key:"kickoff_spawn",value:n.spawn_position},{key:"support_behavior",value:n.support_behavior}]}function Yb(n,e,t){n.count+=1,t.outcome==="neutral"?n.neutral_outcomes+=1:t.outcome===(e?"team_zero_win":"team_one_win")?n.wins+=1:t.outcome===(e?"team_one_win":"team_zero_win")&&(n.losses+=1),t.kickoff_possession_outcome==="contested"?n.contested_kickoff_possessions+=1:t.kickoff_possession_outcome===(e?"team_zero_possession":"team_one_possession")?n.kickoff_possessions+=1:t.kickoff_possession_outcome===(e?"team_one_possession":"team_zero_possession")?n.opponent_kickoff_possessions+=1:t.kickoff_possession_outcome===(e?"team_zero_advantage":"team_one_advantage")?n.kickoff_possession_advantages+=1:n.opponent_kickoff_possession_advantages+=1,t.kickoff_goal&&(n.kickoff_goal_count+=1,t.scoring_team_is_team_0===e?n.kickoff_goals_for+=1:t.scoring_team_is_team_0!=null&&(n.kickoff_goals_against+=1)),t.win_strength!=null&&(n.win_strength_sample_count+=1,n.cumulative_win_strength+=t.win_strength)}function jb(n,e,t){t&&(t.boost_after!=null&&(n.boost_after_sample_count+=1,n.cumulative_boost_after+=t.boost_after,e.boost_after_sample_count+=1,e.cumulative_boost_after+=t.boost_after),t.outcome==="fake"?(n.fake_count+=1,e.fake_count+=1):t.outcome==="missed"&&(n.missed_count+=1,e.missed_count+=1))}function gz(n,e,t){n.count+=1,iE(n,mz(t)),t.outcome==="touched"?n.touches+=1:t.outcome==="fake"?n.fakes+=1:t.outcome==="missed"&&(n.misses+=1),e.kickoff_goal&&e.scoring_team_is_team_0===t.is_team_0&&(n.kickoff_goal_count+=1),t.boost_after!=null&&(n.boost_after_sample_count+=1,n.cumulative_boost_after+=t.boost_after)}function yz(n,e,t){n.count+=1,iE(n,_z(t)),t.first_touch_time!=null&&(n.touches+=1),t.support_behavior==="go_for_boost"?n.support_go_for_boosts+=1:t.support_behavior==="cheat"?n.support_cheats+=1:t.support_behavior==="other"&&(n.support_other+=1),e.kickoff_goal&&e.scoring_team_is_team_0===t.is_team_0&&(n.kickoff_goal_count+=1),t.boost_after!=null&&(n.boost_after_sample_count+=1,n.cumulative_boost_after+=t.boost_after)}function Zu(n,e,t){const i=tE(t.player),s=n.get(i)??nE();n.set(i,s),"outcome"in t?gz(s,e,t):yz(s,e,t)}function Zb(n,e){Object.assign(n,e)}function vz(n,e){Object.assign(n,e??nE()),e?.labeled_event_counts?n.labeled_event_counts=pz(e.labeled_event_counts):delete n.labeled_event_counts}function bz(n){const e=sE(n);for(const t of n.frames)e.applyFrame(t);return n}function sE(n){const e=fz(be(n,"kickoff"));let t=0;const i=qb(),s=qb(),a=new Map;return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function L_(n){return`${n.key}\0${n.value}`}function Ju(n){return n.map(L_).join("")}function Sz(n,e){e.sort((s,a)=>L_(s).localeCompare(L_(a)));const t=n.labeled_event_counts??={entries:[]},i=t.entries.find(s=>Ju(s.labels)===Ju(e));i?i.count+=1:(t.entries.push({labels:[...e],count:1}),t.entries.sort((s,a)=>Ju(s.labels).localeCompare(Ju(a.labels))))}function Tz(n,e){return n.labeled_event_counts?.entries.filter(t=>t.labels.some(i=>i.key==="confidence_band"&&i.value===e)).reduce((t,i)=>t+i.count,0)??0}function Mz(n){return n==="forward"||n==="reverse"||n==="side"?n:"other"}function Ez(n){return n==="left"||n==="right"?n:"center"}function Cz(n){return n.labeled_event_counts?.entries.reduce((e,t)=>e+t.count,0)??0}function Az(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function Rz(n,e,t,i){n.is_last_flick=i,n.time_since_last_flick=n.last_flick_time==null?null:Math.max(0,aE(t,n.last_flick_time)),n.frames_since_last_flick=n.last_flick_frame==null?null:Math.max(0,e-n.last_flick_frame)}function Pz(n,e,t,i){Sz(n,[{key:"confidence_band",value:e.confidence>=xz?"high":"standard"},{key:"kind",value:Mz(e.kind)},{key:"direction",value:Ez(e.direction)}]),n.count=Cz(n),n.high_confidence_count=Tz(n,"high"),n.is_last_flick=!0,n.last_flick_time=e.time,n.last_flick_frame=e.frame,n.time_since_last_flick=Math.max(0,aE(i,e.time)),n.frames_since_last_flick=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=_m(n.cumulative_confidence,e.confidence),n.cumulative_setup_duration=_m(n.cumulative_setup_duration,e.setup_duration),n.cumulative_ball_speed_change=_m(n.cumulative_ball_speed_change,e.ball_speed_change)}function Iz(n,e){Object.assign(n,e??rE()),e?.labeled_event_counts?n.labeled_event_counts=Az(e.labeled_event_counts):delete n.labeled_event_counts}function Lz(n){const e=oE(n);for(const t of n.frames)e.applyFrame(t);return n}function oE(n){const e=wz(be(n,"flick"));let t=0,i=null;const s=new Map;return{applyFrame(a){if(a.is_live_play){for(const[r,o]of s)Rz(o,a.frame_number,a.time,r===i);for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function Dz(n,e){n.count+=1,n.total_time_to_use+=e.time_since_reset,n.min_time_to_use=n.min_time_to_use===null?e.time_since_reset:Math.min(n.min_time_to_use,e.time_since_reset)}function Oz(n,e){Object.assign(n,e??lE())}function Fz(n){const e=cE(n);for(const t of n.frames)e.applyFrame(t);return n}function cE(n){const e=kz(be(n,"flip_reset"));let t=0;const i=new Map;return{applyFrame(s){for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function Uz(n,e,t,i){n.is_last_half_volley=i,n.time_since_last_half_volley=n.last_half_volley_time==null?null:Math.max(0,dE(t,n.last_half_volley_time)),n.frames_since_last_half_volley=n.last_half_volley_frame==null?null:Math.max(0,e-n.last_half_volley_frame)}function Bz(n,e,t,i){n.count+=1,n.total_ball_speed=uE(n.total_ball_speed,e.ball_speed),n.fastest_ball_speed=Math.max(n.fastest_ball_speed,e.ball_speed),n.last_half_volley_time=e.time,n.last_half_volley_frame=e.frame,n.time_since_last_half_volley=Math.max(0,dE(i,e.time)),n.frames_since_last_half_volley=Math.max(0,t-e.frame)}function zz(n,e){Object.assign(n,e??hE())}function tx(n,e){Object.assign(n,e)}function Hz(n){const e=fE(n);for(const t of n.frames)e.applyFrame(t);return n}function fE(n){const e=Nz(be(n,"half_volley"));let t=0,i=null;const s=new Map,a={count:0,total_ball_speed:0,fastest_ball_speed:0},r={count:0,total_ball_speed:0,fastest_ball_speed:0};return{applyFrame(o){for(const[l,c]of s)Uz(c,o.frame_number,o.time,o.is_live_play&&l===i);if(!o.is_live_play)i=null;else{let l=!1;for(;te.frame!==t.frame?e.frame-t.frame:e.time!==t.time?e.time-t.time:ji(e.player).localeCompare(ji(t.player)))}function Wz(n){return[...n].sort((e,t)=>e.resolved_frame!==t.resolved_frame?e.resolved_frame-t.resolved_frame:e.resolved_time!==t.resolved_time?e.resolved_time-t.resolved_time:e.frame!==t.frame?e.frame-t.frame:e.time!==t.time?e.time-t.time:ji(e.player).localeCompare(ji(t.player)))}function gm(){return{count:0,highConfidenceCount:0,lastTime:null,lastFrame:null,lastResolvedTime:null,lastResolvedFrame:null,lastQuality:null,bestQuality:0,cumulativeQuality:0,labeledCounts:{entries:[]}}}function xo(n){return Math.fround(n)}function Xz(n,e){return xo(xo(n)+xo(e))}function Kz(n,e){return{key:"confidence_band",value:n>=e?"high":"standard"}}function qz(n,e){const t=e.sort((s,a)=>s.key===a.key?s.value.localeCompare(a.value):s.key.localeCompare(a.key)),i=n.entries.find(s=>s.labels.length===t.length&&s.labels.every((a,r)=>a.key===t[r]?.key&&a.value===t[r]?.value));if(i){i.count+=1;return}n.entries.push({labels:t,count:1}),n.entries.sort((s,a)=>JSON.stringify(s.labels).localeCompare(JSON.stringify(a.labels)))}function Jo(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function ym(n,e,t,i,s){n.count+=1,e.confidence>=s&&(n.highConfidenceCount+=1),qz(n.labeledCounts,[Kz(e.confidence,s)]),n.lastTime=e.time,n.lastFrame=e.frame,n.lastResolvedTime=i,n.lastResolvedFrame=t,n.lastQuality=e.confidence,n.bestQuality=Math.max(n.bestQuality,e.confidence),n.cumulativeQuality=Xz(n.cumulativeQuality,e.confidence)}function fy(n,e){return n?.lastTime==null?null:n.lastResolvedFrame===e.frame_number?0:Math.max(0,xo(xo(e.time)-xo(n.lastTime)))}function py(n,e){return n?.lastFrame==null?null:n.lastResolvedFrame===e.frame_number?0:Math.max(0,e.frame_number-n.lastFrame)}function pE(n,e,t,i){n.count=e?.count??0,n.high_confidence_count=e?.highConfidenceCount??0,n.is_last_speed_flip=i,n.last_speed_flip_time=e?.lastTime??null,n.last_speed_flip_frame=e?.lastFrame??null,n.time_since_last_speed_flip=fy(e,t),n.frames_since_last_speed_flip=py(e,t),n.last_quality=e?.lastQuality??null,n.best_quality=e?.bestQuality??0,n.cumulative_quality=e?.cumulativeQuality??0,e?.labeledCounts.entries.length?n.labeled_event_counts=Jo(e.labeledCounts):delete n.labeled_event_counts}function mE(n,e,t,i){n.count=e?.count??0,n.high_confidence_count=e?.highConfidenceCount??0,n.is_last_half_flip=i,n.last_half_flip_time=e?.lastTime??null,n.last_half_flip_frame=e?.lastFrame??null,n.time_since_last_half_flip=fy(e,t),n.frames_since_last_half_flip=py(e,t),n.last_quality=e?.lastQuality??null,n.best_quality=e?.bestQuality??0,n.cumulative_quality=e?.cumulativeQuality??0,e?.labeledCounts.entries.length?n.labeled_event_counts=Jo(e.labeledCounts):delete n.labeled_event_counts}function _E(n,e,t,i){n.count=e?.count??0,n.high_confidence_count=e?.highConfidenceCount??0,n.is_last_wavedash=i,n.last_wavedash_time=e?.lastTime??null,n.last_wavedash_frame=e?.lastFrame??null,n.time_since_last_wavedash=fy(e,t),n.frames_since_last_wavedash=py(e,t),n.last_quality=e?.lastQuality??null,n.best_quality=e?.bestQuality??0,n.cumulative_quality=e?.cumulativeQuality??0,e?.labeledCounts.entries.length?n.labeled_event_counts=Jo(e.labeledCounts):delete n.labeled_event_counts}function Yz(n){const e={...n};return n.labeled_event_counts?e.labeled_event_counts=Jo(n.labeled_event_counts):delete e.labeled_event_counts,e}function jz(n){const e={...n};return n.labeled_event_counts?e.labeled_event_counts=Jo(n.labeled_event_counts):delete e.labeled_event_counts,e}function Zz(n){const e={...n};return n.labeled_event_counts?e.labeled_event_counts=Jo(n.labeled_event_counts):delete e.labeled_event_counts,e}function Jz(n,e){if(e){Object.assign(n,e);return}pE(n,void 0,{frame_number:0,time:0},!1)}function Qz(n,e){if(e){Object.assign(n,e);return}mE(n,void 0,{frame_number:0,time:0},!1)}function eH(n,e){if(e){Object.assign(n,e);return}_E(n,void 0,{frame_number:0,time:0},!1)}function tH(n){return n.is_live_play||n.ball_has_been_hit===!1}function nH(n){const e=gE(n);for(const t of n.frames)e.applyFrame(t);return n}function gE(n){const e=Wz(be(n,"speed_flip")),t=nx(be(n,"half_flip")),i=nx(be(n,"wavedash"));let s=0,a=0,r=0,o=null,l=null,c=null;const u=new Map,d=new Map,h=new Map,f=new Map,p=new Map,g=new Map;return{applyFrame(_){if(tH(_)){for(;siH.map(e=>({labels:[{key:"height_band",value:n},{key:"speed_band",value:e}],value:0}))).sort((n,e)=>JSON.stringify(n.labels).localeCompare(JSON.stringify(e.labels)))}}function bd(n=!1){return{tracked_time:0,total_distance:0,speed_integral:0,time_slow_speed:0,time_boost_speed:0,time_supersonic_speed:0,time_on_ground:0,time_low_air:0,time_high_air:0,labeled_tracked_time:n?rH():{entries:[]}}}function oH(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function lH(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function cH(n,e,t){const i=lH(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=ds(s.value,t):(n.entries.push({labels:i,value:ma(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function uH(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),value:e.value}))}}function sx(n,e){const t=ma(e.dt);n.tracked_time=ds(n.tracked_time,t),n.total_distance=ds(n.total_distance,e.distance),n.speed_integral=ds(n.speed_integral,aH(e.speed,t)),e.speed_band==="slow"?n.time_slow_speed=ds(n.time_slow_speed,t):e.speed_band==="boost"?n.time_boost_speed=ds(n.time_boost_speed,t):e.speed_band==="supersonic"&&(n.time_supersonic_speed=ds(n.time_supersonic_speed,t)),e.height_band==="ground"?n.time_on_ground=ds(n.time_on_ground,t):e.height_band==="low_air"?n.time_low_air=ds(n.time_low_air,t):e.height_band==="high_air"&&(n.time_high_air=ds(n.time_high_air,t));const i=n.labeled_tracked_time??{entries:[]};n.labeled_tracked_time=i,cH(i,[{key:"speed_band",value:e.speed_band},{key:"height_band",value:e.height_band}],t)}function vm(n,e){const t=e??bd(!0),i=t.labeled_tracked_time;Object.assign(n,t,{labeled_tracked_time:i?uH(i):void 0}),i?.entries.length||delete n.labeled_tracked_time}function dH(n){const e=yE(n);for(const t of n.frames)e.applyFrame(t);return n}function yE(n){const e=oH(be(n,"movement"));let t=0;const i=new Map,s=bd(),a=bd();return{applyFrame(r){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function fH(n,e,t,i){n.is_last_one_timer=i,n.time_since_last_one_timer=n.last_one_timer_time==null?null:Math.max(0,t-n.last_one_timer_time),n.frames_since_last_one_timer=n.last_one_timer_frame==null?null:Math.max(0,e-n.last_one_timer_frame)}function pH(n,e,t,i){n.count+=1,n.total_ball_speed+=e.ball_speed,n.fastest_ball_speed=Math.max(n.fastest_ball_speed,e.ball_speed),n.total_pass_distance+=e.pass_travel_distance,n.last_one_timer_time=e.time,n.last_one_timer_frame=e.frame,n.time_since_last_one_timer=Math.max(0,i-e.time),n.frames_since_last_one_timer=Math.max(0,t-e.frame)}function mH(n,e){Object.assign(n,e??vE())}function rx(n,e){Object.assign(n,e)}function _H(n){const e=bE(n);for(const t of n.frames)e.applyFrame(t);return n}function bE(n){const e=hH(be(n,"one_timer"));let t=0,i=null;const s=new Map,a={count:0,total_ball_speed:0,fastest_ball_speed:0},r={count:0,total_ball_speed:0,fastest_ball_speed:0};return{applyFrame(o){for(const[l,c]of s)fH(c,o.frame_number,o.time,o.is_live_play&&l===i);if(!o.is_live_play)i=null;else{let l=!1;for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.index-t.index}).map(({event:e})=>e)}function yH(n,e,t,i){n.is_last_completed_pass=i,n.time_since_last_completed_pass=n.last_completed_pass_time==null?null:Math.max(0,t-n.last_completed_pass_time),n.frames_since_last_completed_pass=n.last_completed_pass_frame==null?null:Math.max(0,e-n.last_completed_pass_frame)}function vH(n,e,t,i){n.completed_pass_count+=1,n.total_pass_distance+=e.ball_travel_distance,n.total_pass_advance+=e.ball_advance_distance,n.longest_pass_distance=Math.max(n.longest_pass_distance,e.ball_travel_distance),n.last_completed_pass_time=e.time,n.last_completed_pass_frame=e.frame,n.time_since_last_completed_pass=Math.max(0,i-e.time),n.frames_since_last_completed_pass=Math.max(0,t-e.frame)}function bH(n,e){Object.assign(n,e??k_())}function ox(n,e){Object.assign(n,e)}function xH(n){const e=xE(n);for(const t of n.frames)e.applyFrame(t);return n}function xE(n){const e=gH(be(n,"pass"));let t=0,i=null;const s=new Map,a={completed_pass_count:0,total_pass_distance:0,total_pass_advance:0,longest_pass_distance:0},r={completed_pass_count:0,total_pass_distance:0,total_pass_advance:0,longest_pass_distance:0};return{applyFrame(o){for(const[l,c]of s)yH(c,o.frame_number,o.time,o.is_live_play&&l===i);if(!o.is_live_play)i=null;else{let l=!1;for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function TH(n){return D_(n)}function MH(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function wE(n,e,t){const i=MH(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=Ol(s.value,t):(n.entries.push({labels:i,value:Ql(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function EH(n,e){return n.key==="possession_state"&&n.value==="team_zero"?{key:"possession_state",value:e?"own":"opponent"}:n.key==="possession_state"&&n.value==="team_one"?{key:"possession_state",value:e?"opponent":"own"}:n.key==="field_third"&&n.value==="team_zero_third"?{key:"field_third",value:e?"defensive_third":"offensive_third"}:n.key==="field_third"&&n.value==="team_one_third"?{key:"field_third",value:e?"offensive_third":"defensive_third"}:n.key==="field_half"&&n.value==="team_zero_side"?{key:"field_half",value:e?"defensive_half":"offensive_half"}:n.key==="field_half"&&n.value==="team_one_side"?{key:"field_half",value:e?"offensive_half":"defensive_half"}:{...n}}function lx(n,e){const t={entries:[]};for(const i of n.labeled_time.entries)wE(t,i.labels.map(s=>EH(s,e)),i.value);return{tracked_time:n.tracked_time,possession_time:e?n.team_zero_time:n.team_one_time,opponent_possession_time:e?n.team_one_time:n.team_zero_time,neutral_time:n.neutral_time,labeled_time:t}}function CH(n,e){n.active=e.active,n.possessionState=e.possession_state}function AH(n,e,t){if(!e.active)return;const i=Ql(t.dt);n.tracked_time=Ol(n.tracked_time,i),e.possessionState==="team_zero"?n.team_zero_time=Ol(n.team_zero_time,i):e.possessionState==="team_one"?n.team_one_time=Ol(n.team_one_time,i):n.neutral_time=Ol(n.neutral_time,i);const s=[{key:"possession_state",value:e.possessionState}];e.fieldThird!=null&&s.push({key:"field_third",value:e.fieldThird}),e.fieldHalf!=null&&s.push({key:"field_half",value:e.fieldHalf}),wE(n.labeled_time,s,i)}function cx(n,e){Object.assign(n,e??SH())}function RH(n){const e=SE(n);for(const t of n.frames)e.applyFrame(t);return n}function SE(n){const e=TH(be(n,"possession")),t=D_(be(n,"ball_third")),i=D_(be(n,"ball_half"));let s=0,a=0,r=0;const o=wH(),l={active:!1,possessionState:"neutral",fieldThird:null,fieldHalf:null};return{applyFrame(c){for(;s({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function Ga(n,e){const t=Ah(e.player),i=n.get(t)??TE();return n.set(t,i),i}function IH(n,e){switch(n.active_game_time=Kt(n.active_game_time,e.duration),e.state){case"tracked":n.tracked_time=Kt(n.tracked_time,e.duration);break;case"demolished":n.time_demolished=Kt(n.time_demolished,e.duration);break}}function LH(n,e){switch(e.state){case"defensive":n.time_defensive_third=Kt(n.time_defensive_third,e.duration);break;case"neutral":n.time_neutral_third=Kt(n.time_neutral_third,e.duration);break;case"offensive":n.time_offensive_third=Kt(n.time_offensive_third,e.duration);break}}function kH(n,e){switch(e.state){case"defensive":n.time_defensive_half=Kt(n.time_defensive_half,e.duration);break;case"offensive":n.time_offensive_half=Kt(n.time_offensive_half,e.duration);break}}function DH(n,e){switch(e.state){case"behind_ball":n.time_behind_ball=Kt(n.time_behind_ball,e.duration);break;case"level_with_ball":n.time_level_with_ball=Kt(n.time_level_with_ball,e.duration);break;case"ahead_of_ball":n.time_in_front_of_ball=Kt(n.time_in_front_of_ball,e.duration);break}}function OH(n,e){switch(e.state){case"no_teammates":n.time_no_teammates=Kt(n.time_no_teammates,e.duration);break;case"most_back":n.time_most_back=Kt(n.time_most_back,e.duration);break;case"most_forward":n.time_most_forward=Kt(n.time_most_forward,e.duration);break;case"mid":n.time_mid_role=Kt(n.time_mid_role,e.duration);break;case"other":n.time_other_role=Kt(n.time_other_role,e.duration);break}}function FH(n,e,t){t.state.closest_to_ball_team&&(e.tracked_time=Kt(e.tracked_time,t.duration),e.time_closest_to_ball_team=Kt(e.time_closest_to_ball_team,t.duration),n.time_closest_to_ball_team=Kt(n.time_closest_to_ball_team,t.duration)),t.state.closest_to_ball_absolute&&(e.time_closest_to_ball_absolute=Kt(e.time_closest_to_ball_absolute,t.duration),n.time_closest_to_ball_absolute=Kt(n.time_closest_to_ball_absolute,t.duration)),t.state.farthest_from_ball&&(n.time_farthest_from_ball=Kt(n.time_farthest_from_ball,t.duration))}function NH(n,e){e.state==="shadowing"&&(n.time_shadow_defense=Kt(n.time_shadow_defense,e.duration))}function UH(n,e){Object.assign(n,e??TE())}function ux(n,e){Object.assign(n,e??O_())}function $a(n,e){const t=PH(n),i=new Array(t.length).fill(0);return{applyThroughFrame(s){for(let a=0;as.frame_number)break;const o=BH(r,s),l=o-i[a];l>0&&(i[a]=o,e({...r,duration:l}))}}}}function BH(n,e){if(e.frame_number>=n.end_frame)return n.duration;const t=n.end_time-n.time;if(t<=0)return 0;const i=Math.max(0,e.time-n.time);return n.duration*Math.min(1,i/t)}function zH(n){const e=ME(n);for(const t of n.frames)e.applyFrame(t);return n}function ME(n){const e=new Map,t=O_(),i=O_(),s=[$a(be(n,"player_activity"),a=>IH(Ga(e,a),a)),$a(be(n,"field_third"),a=>LH(Ga(e,a),a)),$a(be(n,"field_half"),a=>kH(Ga(e,a),a)),$a(be(n,"ball_depth"),a=>DH(Ga(e,a),a)),$a(be(n,"depth_role"),a=>OH(Ga(e,a),a)),$a(be(n,"ball_proximity"),a=>FH(Ga(e,a),a.is_team_0?t:i,a)),$a(be(n,"shadow_defense"),a=>NH(Ga(e,a),a))];return{applyFrame(a){for(const r of s)r.applyThroughFrame(a);ux(a.team_zero.positioning,t),ux(a.team_one.positioning,i);for(const r of a.players)UH(r.positioning,e.get(Ah(r.player_id))),HH(r.positioning,n,r.player_id)}}}function HH(n,e,t){const i=e.positioning_summary;if(!Array.isArray(i))return;const s=Ah(t),a=i.find(r=>!r||typeof r!="object"?!1:Ah(r.player_id)===s);a?.distance&&Object.assign(n,a.distance)}function xm(n){if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function Fl(){return{total_duration:0,press_count:0}}function VH(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function GH(n){return n.gameplay_phase==="active_play"||n.gameplay_phase==="kickoff_waiting_for_touch"}function wm(n,e){Object.assign(n,e??Fl())}function $H(n){const e=EE(n);for(const t of n.frames)e.applyFrame(t);return n}function EE(n){const e=VH(be(n,"powerslide"));let t=0;const i=new Map,s=new Map,a=Fl(),r=Fl();return{applyFrame(o){const l=GH(o);for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function qH(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function CE(n,e,t){const i=qH(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=Nl(s.value,t):(n.entries.push({labels:i,value:ec(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function YH(n,e){return n.key==="field_half"&&n.value==="team_zero_side"?{key:"field_half",value:e?"defensive_half":"offensive_half"}:n.key==="field_half"&&n.value==="team_one_side"?{key:"field_half",value:e?"offensive_half":"defensive_half"}:{...n}}function dx(n,e){const t={entries:[]};for(const i of n.labeled_time.entries)CE(t,i.labels.map(s=>YH(s,e)),i.value);return{tracked_time:n.tracked_time,defensive_half_time:e?n.team_zero_side_time:n.team_one_side_time,offensive_half_time:e?n.team_one_side_time:n.team_zero_side_time,neutral_time:n.neutral_time,labeled_time:t}}function jH(n,e){n.active=e.active,n.fieldHalf=e.field_half}function ZH(n,e,t){if(!e.active)return;const i=ec(t.dt);n.tracked_time=Nl(n.tracked_time,i),e.fieldHalf==="team_zero_side"?n.team_zero_side_time=Nl(n.team_zero_side_time,i):e.fieldHalf==="team_one_side"?n.team_one_side_time=Nl(n.team_one_side_time,i):n.neutral_time=Nl(n.neutral_time,i),CE(n.labeled_time,[{key:"field_half",value:e.fieldHalf}],i)}function hx(n,e){Object.assign(n,e??XH())}function JH(n){const e=AE(n);for(const t of n.frames)e.applyFrame(t);return n}function AE(n){const e=KH(be(n,"ball_half"));let t=0;const i=WH(),s={active:!1,fieldHalf:"neutral"};return{applyFrame(a){for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function n5(n){return n.sort((e,t)=>e.key===t.key?e.value.localeCompare(t.value):e.key.localeCompare(t.key))}function RE(n,e,t){const i=n5(e),s=n.entries.find(a=>a.labels.length===i.length&&a.labels.every((r,o)=>r.key===i[o]?.key&&r.value===i[o]?.value));s?s.value=Ul(s.value,t):(n.entries.push({labels:i,value:tc(t)}),n.entries.sort((a,r)=>JSON.stringify(a.labels).localeCompare(JSON.stringify(r.labels))))}function i5(n,e){return n.key==="field_third"&&n.value==="team_zero_third"?{key:"field_third",value:e?"defensive_third":"offensive_third"}:n.key==="field_third"&&n.value==="team_one_third"?{key:"field_third",value:e?"offensive_third":"defensive_third"}:{...n}}function fx(n,e){const t={entries:[]};for(const i of n.labeled_time.entries)RE(t,i.labels.map(s=>i5(s,e)),i.value);return{tracked_time:n.tracked_time,defensive_third_time:e?n.team_zero_third_time:n.team_one_third_time,neutral_third_time:n.neutral_third_time,offensive_third_time:e?n.team_one_third_time:n.team_zero_third_time,labeled_time:t}}function s5(n,e){n.active=e.active,n.fieldThird=e.field_third}function a5(n,e,t){if(!e.active)return;const i=tc(t.dt);n.tracked_time=Ul(n.tracked_time,i),e.fieldThird==="team_zero_third"?n.team_zero_third_time=Ul(n.team_zero_third_time,i):e.fieldThird==="team_one_third"?n.team_one_third_time=Ul(n.team_one_third_time,i):n.neutral_third_time=Ul(n.neutral_third_time,i),RE(n.labeled_time,[{key:"field_third",value:e.fieldThird}],i)}function px(n,e){Object.assign(n,e??e5())}function r5(n){const e=PE(n);for(const t of n.frames)e.applyFrame(t);return n}function PE(n){const e=t5(be(n,"ball_third"));let t=0;const i=QH(),s={active:!1,fieldThird:"neutral_third"};return{applyFrame(a){for(;t({event:e,index:t})).sort((e,t)=>e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.event.end_time!==t.event.end_time?e.event.end_time-t.event.end_time:e.index-t.index).map(({event:e})=>e)}function l5(n,e,t){n.session_count+=1,n.session_time=Qu(n.session_time,t.duration),n.offensive_half_time=Qu(n.offensive_half_time,t.offensive_half_time),n.offensive_third_time=Qu(n.offensive_third_time,t.offensive_third_time),n.longest_session_time=Math.max(n.longest_session_time,t.duration),n.average_session_time=n.session_count===0?0:xd(n.session_time/n.session_count),e.opponent_session_count+=1,e.opponent_session_time=Qu(e.opponent_session_time,t.duration),e.opponent_longest_session_time=Math.max(e.opponent_longest_session_time,t.duration)}function _x(n,e){Object.assign(n,e)}function c5(n){const e=IE(n);for(const t of n.frames)e.applyFrame(t);return n}function IE(n){const e=o5(be(n,"territorial_pressure"));let t=0;const i=mx(),s=mx();return{applyFrame(a){for(;t=e[t].end_frame;){const r=e[t];l5(r.team_is_team_0?i:s,r.team_is_team_0?s:i,r),t+=1}_x(a.team_zero.territorial_pressure,i),_x(a.team_one.territorial_pressure,s)}}}function ao(n,e){return Math.fround(Math.fround(n)+Math.fround(e))}function LE(n){if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function kE(){return{active_game_time:0,time_first_man:0,time_second_man:0,time_third_man:0,time_ambiguous_role:0,longest_first_man_stint_time:0,first_man_stint_count:0,became_first_man_count:0,lost_first_man_count:0,current_role_state:"unknown"}}function gx(){return{first_man_changes_for_team:0,rotation_count:0}}function yx(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function u5(n,e,t,i,s){const a=n.stats;switch(a.active_game_time=ao(a.active_game_time,t),a.current_role_state=e.state,e.state){case"first_man":{n.lastFirstManEndTime!==null&&e.time-n.lastFirstManEndTime<=s?n.currentFirstManStintTime=ao(n.currentFirstManStintTime,t):(n.currentFirstManStintTime=t,a.first_man_stint_count+=1),n.lastFirstManEndTime=i,a.longest_first_man_stint_time=Math.max(a.longest_first_man_stint_time,n.currentFirstManStintTime),a.time_first_man=ao(a.time_first_man,t);break}case"second_man":a.time_second_man=ao(a.time_second_man,t);break;case"third_man":a.time_third_man=ao(a.time_third_man,t);break;case"ambiguous":a.time_ambiguous_role=ao(a.time_ambiguous_role,t);break}}function d5(n,e){if(e.frame_number>=n.end_frame)return n.duration;const t=n.end_time-n.time;if(t<=0)return 0;const i=Math.max(0,e.time-n.time);return n.duration*Math.min(1,i/t)}function F_(n,e){const t=LE(e),i=n.get(t)??{currentFirstManStintTime:0,lastFirstManEndTime:null,stats:kE()};return n.set(t,i),i}function h5(n,e,t){n.first_man_changes_for_team+=1,n.rotation_count+=1,F_(e,t.previous_first_man).stats.lost_first_man_count+=1,F_(e,t.next_first_man).stats.became_first_man_count+=1}function f5(n,e){Object.assign(n,e??kE())}function vx(n,e){Object.assign(n,e)}function p5(n){const e=DE(n);for(const t of n.frames)e.applyFrame(t);return n}function DE(n){const e=yx(be(n,"rotation_role")),t=yx(be(n,"first_man_change")),i=n.config.rotation_first_man_stint_end_grace_seconds,s=new Array(e.length).fill(0);let a=0;const r=new Map,o=gx(),l=gx();return{applyFrame(c){for(let u=0;uc.frame_number)break;const h=d5(d,c),f=h-s[u];if(f>0){s[u]=h;const p=c.frame_number>=d.end_frame?d.end_time:Math.min(c.time,d.end_time);u5(F_(r,d.player),d,f,p,i)}}for(;a({event:e,index:t})).sort((e,t)=>e.event.start_frame!==t.event.start_frame?e.event.start_frame-t.event.start_frame:e.event.start_time!==t.event.start_time?e.event.start_time-t.event.start_time:e.event.end_frame!==t.event.end_frame?e.event.end_frame-t.event.end_frame:e.index-t.index).map(({event:e})=>e)}function _5(n,e){n.count+=1,e.attackers===2&&e.defenders===1?n.two_v_one_count+=1:e.attackers===2&&e.defenders===2?n.two_v_two_count+=1:e.attackers===2&&e.defenders===3?n.two_v_three_count+=1:e.attackers===3&&e.defenders===1?n.three_v_one_count+=1:e.attackers===3&&e.defenders===2?n.three_v_two_count+=1:e.attackers===3&&e.defenders===3&&(n.three_v_three_count+=1)}function xx(n,e){Object.assign(n,e)}function g5(n){const e=OE(n);for(const t of n.frames)e.applyFrame(t);return n}function OE(n){const e=m5(be(n,"rush"));let t=0;const i=bx(),s=bx(),a=n.config.rush_min_possession_retained_seconds;return{applyFrame(r){for(;t=e[t].start_frame&&r.time-e[t].start_time>=a;){const o=e[t];_5(o.is_team_0?i:s,o),t+=1}xx(r.team_zero.rush,i),xx(r.team_one.rush,s)}}}const y5=["control","hard_hit","medium_hit"],v5=["ground","high_air","low_air"],b5=["air","ground","wall"],x5=["dodge","no_dodge"];function wo(n){return Math.fround(n)}function wd(n,e){return wo(wo(n)+wo(e))}function FE(n,e){return wo(wo(n)-wo(e))}function Sm(n){if(!n||typeof n!="object")return String(n);const[e,t]=Object.entries(n)[0]??["Unknown","unknown"];return`${e}:${typeof t=="string"?t:JSON.stringify(t)}`}function w5(){return{entries:x5.flatMap(n=>v5.flatMap(e=>y5.flatMap(t=>b5.map(i=>({labels:[{key:"dodge_state",value:n},{key:"height_band",value:e},{key:"kind",value:t},{key:"surface",value:i}],count:0}))))).sort((n,e)=>JSON.stringify(n.labels).localeCompare(JSON.stringify(e.labels)))}}function NE(){return{touch_count:0,control_touch_count:0,medium_hit_count:0,hard_hit_count:0,aerial_touch_count:0,high_aerial_touch_count:0,wall_touch_count:0,first_touch_count:0,is_last_touch:!1,last_touch_time:null,last_touch_frame:null,time_since_last_touch:null,frames_since_last_touch:null,last_ball_speed_change:null,max_ball_speed_change:0,cumulative_ball_speed_change:0,total_ball_travel_distance:0,total_ball_advance_distance:0,total_ball_retreat_distance:0,labeled_touch_counts:w5()}}const S5=NE();function wx(){return{stats:NE(),labeledCountsVersion:0,labeledCountsSnapshot:void 0,labeledCountsSnapshotVersion:-1}}function T5(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function M5(n,e){e.sort((s,a)=>s.key===a.key?s.value.localeCompare(a.value):s.key.localeCompare(a.key));const t=n.labeled_touch_counts?.entries??[];n.labeled_touch_counts={entries:t};const i=t.find(s=>s.labels.length===e.length&&s.labels.every((a,r)=>a.key===e[r]?.key&&a.value===e[r]?.value));i?i.count+=1:(t.push({labels:e,count:1}),t.sort((s,a)=>JSON.stringify(s.labels).localeCompare(JSON.stringify(a.labels))))}function E5(n){return{entries:n.entries.map(e=>({labels:e.labels.map(t=>({...t})),count:e.count}))}}function ed(n,e){return n.tags?.find(t=>t.group===e)?.value??null}function C5(n,e,t){const i=ed(e,"kind")??"control",s=ed(e,"height_band")??"ground",a=ed(e,"surface")??"ground",r=ed(e,"dodge_state")??"no_dodge",o=n.stats;o.touch_count+=1,i==="control"?o.control_touch_count+=1:i==="medium_hit"?o.medium_hit_count+=1:i==="hard_hit"&&(o.hard_hit_count+=1),s==="low_air"?o.aerial_touch_count+=1:s==="high_air"&&(o.aerial_touch_count+=1,o.high_aerial_touch_count+=1),a==="wall"&&(o.wall_touch_count+=1),M5(o,[{key:"kind",value:i},{key:"height_band",value:s},{key:"surface",value:a},{key:"dodge_state",value:r}]),n.labeledCountsVersion+=1,o.last_touch_time=e.time,o.last_touch_frame=e.frame,o.time_since_last_touch=Math.max(0,FE(t.time,e.time)),o.frames_since_last_touch=Math.max(0,t.frame_number-e.frame),o.last_ball_speed_change=e.ball_speed_change,o.max_ball_speed_change=Math.max(o.max_ball_speed_change,e.ball_speed_change),o.cumulative_ball_speed_change=wd(o.cumulative_ball_speed_change,e.ball_speed_change)}function A5(n){return n.labeledCountsSnapshotVersion!==n.labeledCountsVersion&&(n.labeledCountsSnapshot=n.stats.labeled_touch_counts?E5(n.stats.labeled_touch_counts):void 0,n.labeledCountsSnapshotVersion=n.labeledCountsVersion),n.labeledCountsSnapshot}function R5(n,e){if(!e){Object.assign(n,S5);return}Object.assign(n,e.stats,{labeled_touch_counts:A5(e)})}function P5(n){const e=UE(n);for(const t of n.frames)e.applyFrame(t);return n}function UE(n){const e=T5(be(n,"touch")),t=e.flatMap(o=>o.ball_movement?[{player:o.player,movement:o.ball_movement}]:[]).sort((o,l)=>o.movement.end_frame!==l.movement.end_frame?o.movement.end_frame-l.movement.end_frame:o.movement.end_time-l.movement.end_time);let i=0,s=0,a=null;const r=new Map;return{applyFrame(o){if(!o.is_live_play)a=null;else{for(const l of r.values()){const c=l.stats;c.is_last_touch=!1,c.last_touch_time!=null&&(c.time_since_last_touch=Math.max(0,FE(o.time,c.last_touch_time))),c.last_touch_frame!=null&&(c.frames_since_last_touch=Math.max(0,o.frame_number-c.last_touch_frame))}for(;i({event:e,index:t})).sort((e,t)=>e.event.resolved_frame!==t.event.resolved_frame?e.event.resolved_frame-t.event.resolved_frame:e.event.resolved_time!==t.event.resolved_time?e.event.resolved_time-t.event.resolved_time:e.index-t.index).map(({event:e})=>e)}function k5(n,e,t){n.is_last_whiff=!1,n.time_since_last_whiff=n.last_whiff_time==null?null:Math.max(0,t-n.last_whiff_time),n.frames_since_last_whiff=n.last_whiff_frame==null?null:Math.max(0,e-n.last_whiff_frame)}function D5(n,e,t,i){if((e.kind??"whiff")==="beaten_to_ball"){n.beaten_to_ball_count+=1;return}n.whiff_count+=1,e.aerial?n.aerial_whiff_count+=1:n.grounded_whiff_count+=1,e.dodge_active&&(n.dodge_whiff_count+=1),n.is_last_whiff=!0,n.last_whiff_time=e.time,n.last_whiff_frame=e.frame,n.time_since_last_whiff=Math.max(0,i-e.time),n.frames_since_last_whiff=Math.max(0,t-e.frame),n.last_closest_approach_distance=e.closest_approach_distance,n.best_closest_approach_distance=n.best_closest_approach_distance==null?e.closest_approach_distance:Math.min(n.best_closest_approach_distance,e.closest_approach_distance),n.cumulative_closest_approach_distance+=e.closest_approach_distance}function Sx(n,e){Object.assign(n,e??N_())}function O5(n){const e=BE(n);for(const t of n.frames)e.applyFrame(t);return n}function BE(n){const e=L5(be(n,"whiff"));let t=0,i=null;const s=new Map,a=new Map;return{applyFrame(r){if(r.is_live_play){for(const o of s.values())k5(o,r.frame_number,r.time);for(;t({event:e,index:t})).sort((e,t)=>{const i=e.event.sample_frame??e.event.frame,s=t.event.sample_frame??t.event.frame;if(i!==s)return i-s;const a=e.event.sample_time??e.event.time,r=t.event.sample_time??t.event.time;return a!==r?a-r:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index}).map(({event:e})=>e)}function U5(n,e,t,i){n.is_last_wall_aerial=i,n.time_since_last_wall_aerial=n.last_wall_aerial_time==null?null:Math.max(0,zE(t,n.last_wall_aerial_time)),n.frames_since_last_wall_aerial=n.last_wall_aerial_frame==null?null:Math.max(0,e-n.last_wall_aerial_frame)}function B5(n,e,t,i){n.count+=1,e.confidence>=F5&&(n.high_confidence_count+=1),n.is_last_wall_aerial=!0,n.last_wall_aerial_time=e.time,n.last_wall_aerial_frame=e.frame,n.time_since_last_wall_aerial=Math.max(0,zE(i,e.time)),n.frames_since_last_wall_aerial=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=td(n.cumulative_confidence,e.confidence),n.cumulative_setup_duration=td(n.cumulative_setup_duration,e.setup_duration),n.cumulative_takeoff_to_touch_time=td(n.cumulative_takeoff_to_touch_time,e.time_since_takeoff),n.cumulative_touch_height=td(n.cumulative_touch_height,e.player_position[2]??0)}function z5(n,e){Object.assign(n,e??HE())}function H5(n){const e=VE(n);for(const t of n.frames)e.applyFrame(t);return n}function VE(n){const e=N5(be(n,"wall_aerial"));let t=0,i=null;const s=new Map;return{applyFrame(a){for(const[r,o]of s)U5(o,a.frame_number,a.time,a.is_live_play&&r===i);if(!a.is_live_play)i=null;else{for(;t({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function $5(n,e,t,i){n.is_last_wall_aerial_shot=i,n.time_since_last_wall_aerial_shot=n.last_wall_aerial_shot_time==null?null:Math.max(0,GE(t,n.last_wall_aerial_shot_time)),n.frames_since_last_wall_aerial_shot=n.last_wall_aerial_shot_frame==null?null:Math.max(0,e-n.last_wall_aerial_shot_frame)}function W5(n,e,t,i){n.count+=1,e.confidence>=V5&&(n.high_confidence_count+=1),n.is_last_wall_aerial_shot=!0,n.last_wall_aerial_shot_time=e.time,n.last_wall_aerial_shot_frame=e.frame,n.time_since_last_wall_aerial_shot=Math.max(0,GE(i,e.time)),n.frames_since_last_wall_aerial_shot=Math.max(0,t-e.frame),n.last_confidence=e.confidence,n.best_confidence=Math.max(n.best_confidence,e.confidence),n.cumulative_confidence=Mm(n.cumulative_confidence,e.confidence),n.cumulative_takeoff_to_shot_time=Mm(n.cumulative_takeoff_to_shot_time,e.time_since_takeoff),n.cumulative_shot_height=Mm(n.cumulative_shot_height,e.player_position[2]??0)}function X5(n,e){Object.assign(n,e??$E())}function K5(n){const e=WE(n);for(const t of n.frames)e.applyFrame(t);return n}function WE(n){const e=G5(be(n,"wall_aerial_shot"));let t=0,i=null;const s=new Map;return{applyFrame(a){for(const[r,o]of s)$5(o,a.frame_number,a.time,a.is_live_play&&r===i);if(!a.is_live_play)i=null;else{let r=!1;for(;t[f.frame_number,p])),a=new Map,r={...n,frames:[]},o=Z5.flatMap(f=>f.createFrameAccumulator?[f.createFrameAccumulator(r)]:[]),l=Math.max(1,t.materializationChunkSize??q5),c=Math.max(l,t.maxMaterializationChunkSize??Y5);let u=-1,d=l;const h=f=>{if(f<=u)return;const p=Math.min(i.length-1,Math.max(f,u+d));for(let g=u+1;g<=p;g+=1){const _=i[g],m=_?tV(eV(_)):void 0;if(m){for(const v of o)v.applyFrame(m);a.set(m.frame_number,m)}}u=p,d=Math.min(c,i.length,d*j5)};return{get(f){const p=s.get(f);if(p!==void 0)return h(p),a.get(f)}}}function Q5(n){return!n||typeof n!="object"?n:{...n}}function eV(n){return{...n,team_zero:{...n.team_zero},team_one:{...n.team_one},players:n.players.map(e=>({...e,player_id:Q5(e.player_id)}))}}function tV(n){return{...n,team_zero:Vo(n.team_zero??{}),team_one:Vo(n.team_one??{}),players:n.players.map(t=>_y(t))}}function yc(n){return n.events?.events??[]}function be(n,e){return yc(n).filter(t=>t.payload.kind===e).map(t=>t.payload.payload)}const nV=new Set(["is_team_0","name","player_id"]);function Ex(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0}function iV(n){return!n||typeof n!="object"||Array.isArray(n)?!1:Object.keys(n).every(e=>nV.has(e))}function sV(n){return Ex(n.team_zero)&&Ex(n.team_one)&&n.players.every(e=>iV(e))}function aV(n){return new Map(IM(n).frames.map(e=>[e.frame_number,e]))}function XE(n,e,t){const i=n.frames.filter(s=>sV(s)).length;if(i===n.frames.length)return J5(n,e,t);if(i>0)throw new Error("stats timeline frames must be either all compact scaffolds or all materialized snapshots");return aV(n)}function Ht(n,e){return n.get(e)??null}const gy=[{stage:"validating",index:1,total:9,label:"Parse replay",start:0,end:.08},{stage:"processing",index:2,total:9,label:"Process replay frames",start:.08,end:.62},{stage:"building-stats",index:3,total:9,label:"Build stats events",start:.62,end:.7},{stage:"serializing-replay",index:4,total:9,label:"Serialize replay data",start:.7,end:.76},{stage:"serializing-stats",index:5,total:9,label:"Serialize stats timeline",start:.76,end:.86},{stage:"normalizing",index:6,total:9,label:"Normalize replay model",start:.86,end:.91},{stage:"decoding-replay",index:7,total:9,label:"Decode replay data",start:.91,end:.94},{stage:"decoding-stats",index:8,total:9,label:"Decode stats chunks",start:.94,end:.96},{stage:"deriving-stats",index:9,total:9,label:"Derive stats snapshots",start:.96,end:1}];function KE(n){return Math.max(0,Math.min(1,n))}function Em(n,e,t){if(n!==void 0)return KE((n-e)/(t-e))}function yy(n){if(n.stage!=="stats-timeline")return n;const e=n.progress;return e===void 0?{...n,stage:"building-stats"}:e<.35?{...n,stage:"building-stats",progress:Em(e,0,.35)}:e<.55?{...n,stage:"serializing-replay",progress:Em(e,.35,.55)}:{...n,stage:"serializing-stats",progress:Em(e,.55,.92)}}function qE(n){const e=yy(n);return gy.find(t=>t.stage===e.stage)}function rV(){return gy.map(({stage:n,index:e,total:t,label:i})=>({stage:n,index:e,total:t,label:i}))}function oV(n){const e=qE(n);return{stage:e.stage,index:e.index,total:e.total,label:e.label}}function lV(n){const e=yy(n),t=qE(e);return gy.map(({stage:i,index:s,total:a,label:r})=>{if(st.index)return{stage:i,index:s,total:a,label:r,state:"pending",completion:0,indeterminate:!1};const o=e.progress!==void 0;return{stage:i,index:s,total:a,label:r,state:"active",completion:o?KE(e.progress??0):1,indeterminate:!o}})}function Qo(n){const e=yy(n),t=e.progress===void 0?null:Math.round(e.progress*100);switch(e.stage){case"validating":return"Parsing replay...";case"processing":return t!==null&&e.totalFrames!==void 0?`Processing replay frames... ${t}% (${e.processedFrames??0}/${e.totalFrames})`:"Processing replay frames...";case"building-stats":return t!==null?e.totalFrames!==void 0?`Building stats events... ${t}% (${e.processedFrames??0}/${e.totalFrames})`:`Building stats events... ${t}%`:"Building stats events...";case"serializing-replay":return t!==null?`Serializing replay data... ${t}%`:"Serializing replay data...";case"serializing-stats":return t!==null?`Serializing stats timeline... ${t}%`:"Serializing stats timeline...";case"decoding-replay":return t!==null?`Decoding replay data... ${t}%`:"Decoding replay data...";case"decoding-stats":return t!==null?e.totalChunks!==void 0?`Decoding stats chunks... ${t}% (${e.processedChunks??0}/${e.totalChunks})`:`Decoding stats chunks... ${t}%`:"Decoding stats chunks...";case"deriving-stats":return t!==null?`Deriving stats snapshots... ${t}%`:"Deriving stats snapshots...";case"normalizing":return t!==null?`Normalizing replay model... ${t}%`:"Normalizing replay model...";default:return"Loading replay..."}}function cV(n){return n instanceof Error?n:new Error(String(n))}function Fs(n,e){return JSON.parse(n.decode(new Uint8Array(e)))}async function uV(n,e,t){t?.({stage:"decoding-stats",progress:0});const i=Fs(n,e.configBuffer);t?.({stage:"decoding-stats",progress:.05}),await rr();const s=Fs(n,e.replayMetaBuffer);t?.({stage:"decoding-stats",progress:.1}),await rr();const a=Fs(n,e.eventsBuffer),r=Fs(n,e.activitySummaryBuffer),o=Fs(n,e.positioningSummaryBuffer),l=Fs(n,e.accumulationTracksBuffer);t?.({stage:"decoding-stats",progress:.15}),await rr();const c=[],u=e.frameChunkBuffers.length;for(let d=0;d{let t=!1,i=null;const s=()=>{t||(t=!0,i!==null&&clearTimeout(i),e())};i=setTimeout(s,n),requestAnimationFrame(()=>s())})}async function kf(n,e={}){if(typeof Worker>"u")throw new Error("Replay loading worker is not available in this environment");const t=new Worker(new URL(""+new URL("replayLoader.worker-BOmyAjmY.js",import.meta.url).href,import.meta.url),{type:"module"}),i=n.slice(),s=e.reportEveryNFrames??100;return new Promise((a,r)=>{const o=()=>{t.terminate()};t.onmessage=async c=>{const u=c.data;if(u.type==="progress"){e.onProgress?.(u.progress);return}if(u.type==="error"){o(),r(new Error(u.error));return}o();try{const d=new TextDecoder;e.onProgress?.({stage:"decoding-replay",progress:0}),await rr();const h=Fs(d,u.replayBuffer);e.onProgress?.({stage:"decoding-replay",progress:.5}),await rr();const f=Fs(d,u.rawReplayBuffer);e.onProgress?.({stage:"decoding-replay",progress:1}),await rr();const p=await uV(d,u.statsTimelineParts,e.onProgress),g=XE(p);a({replay:h,raw:f,statsTimeline:p,statsFrameLookup:g})}catch(d){r(cV(d))}},t.onerror=c=>{o(),r(new Error(c.message||"Replay loading worker failed"))};const l={type:"load-replay",bytes:i.buffer,reportEveryNFrames:s};t.postMessage(l,[i.buffer])})}function dV(n){const e=document.createElement("div");e.className="replay-load-modal",e.hidden=!0;const t=document.createElement("div");t.className="replay-load-modal__dialog",t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-labelledby","replay-load-modal-title");const i=document.createElement("p");i.className="replay-load-modal__eyebrow",i.textContent="Replay loading";const s=document.createElement("h2");s.id="replay-load-modal-title",s.className="replay-load-modal__title",s.textContent="Preparing replay pipeline";const a=document.createElement("p");a.className="replay-load-modal__status",a.textContent="Preparing replay...";const r=document.createElement("div");r.className="replay-load-modal__phase-list";const o=new Map;for(const f of rV()){const p=document.createElement("div");p.className="replay-load-modal__phase-row",p.dataset.state="pending";const g=document.createElement("p");g.className="replay-load-modal__phase-label",g.textContent=`${f.index}. ${f.label}`;const _=document.createElement("div");_.className="replay-load-modal__phase-bar";const m=document.createElement("div");m.className="replay-load-modal__phase-fill",m.dataset.indeterminate="false",_.append(m),p.append(g,_),r.append(p),o.set(f.stage,{row:p,fill:m})}const l=document.createElement("p");l.className="replay-load-modal__meta",t.append(i,s,a,r,l),e.append(t),n.append(e);let c="";const u=()=>{for(const{row:f,fill:p}of o.values())f.dataset.state="pending",p.style.width="0%",p.dataset.indeterminate="false"},d=f=>{for(const p of lV(f)){const g=o.get(p.stage);g&&(g.row.dataset.state=p.state,g.fill.dataset.indeterminate=p.indeterminate?"true":"false",g.fill.style.width=`${Math.round(p.completion*100)}%`)}},h=f=>{e.hidden=!f};return{show(f,p="Preparing replay..."){c=f,h(!0),u(),s.textContent="Preparing replay pipeline",a.textContent=p,l.textContent=`Loading ${f}`},update(f){h(!0);const p=oV(f);if(d(f),s.textContent=`Phase ${p.index} of ${p.total}: ${p.label}`,a.textContent=Qo(f),f.stage==="processing"&&f.totalFrames!==void 0){l.textContent=`${f.processedFrames??0}/${f.totalFrames} frames`;return}if(f.stage==="decoding-stats"&&f.totalChunks!==void 0){l.textContent=`${f.processedChunks??0}/${f.totalChunks} chunks`;return}l.textContent=c?`Loading ${c}`:""},hide(){h(!1)},destroy(){e.remove()}}}const hV=["free","follow"];function YE(n){return n.useReplayBallCam??!1?"player":n.ballCamEnabled?"on":"off"}function Cx(n){return n.useReplayBallCam?"player":n.ballCam===!0?"on":n.ballCam===!1?"off":"player"}const jE={fov:110,height:100,pitch:-4,distance:270,stiffness:0,swivelSpeed:1,transitionSpeed:1};class vy{constructor(e){this.options=e}lastFreeCameraPreset=null;get freeCameraPreset(){return this.lastFreeCameraPreset}set freeCameraPreset(e){this.lastFreeCameraPreset=e}ballCamModeValue="player";get ballCamMode(){return this.ballCamModeValue}autoPossessionEnabledValue=!1;get autoPossessionEnabled(){return this.autoPossessionEnabledValue}static ballCamEnabledForMode(e){return e==="player"?null:e==="on"}followPlayerWithReplayCamera(e,t={}){const i=this.options.getReplayPlayer();i&&(t.preserveAutoPossession||this.setAutoPossessionEnabled(!1,{requestConfigSync:!1}),i.setAttachedPlayer(e),i.setCameraViewMode("follow"),t.usePlayerCameraSettings!==!1&&i.setCustomCameraSettings(null),this.setBallCamMode(t.ballCam??"player"),this.lastFreeCameraPreset=null,t.requestConfigSync!==!1&&this.options.requestConfigSync())}setAutoPossessionEnabled(e,t={}){if(this.autoPossessionEnabledValue===e){this.renderAutoPossessionButton();return}this.autoPossessionEnabledValue=e,this.renderAutoPossessionButton(),t.notify!==!1&&this.options.onAutoPossessionChange?.(e),t.requestConfigSync!==!1&&this.options.requestConfigSync()}renderBallCamButtons(){const{ballCamOffButton:e,ballCamOnButton:t,ballCamPlayerButton:i}=this.options.elements,s=[["off",e],["on",t],["player",i]];for(const[a,r]of s){const o=a===this.ballCamModeValue;r.dataset.active=o?"true":"false",r.setAttribute("aria-pressed",o?"true":"false")}}renderAutoPossessionButton(){this.options.elements.cameraViewAutoPossession.checked=this.autoPossessionEnabledValue}disableAutoPossessionForManualCameraControl(){this.setAutoPossessionEnabled(!1,{requestConfigSync:!1})}setBallCamMode(e){this.ballCamModeValue=e,this.options.getReplayPlayer()?.setBallCamEnabled(vy.ballCamEnabledForMode(e)),this.renderBallCamButtons()}get nameplateLiftUu(){const e=Number(this.options.elements.nameplateLift.value);return Number.isFinite(e)?e:g_}applyNameplateLiftUu(e){const{nameplateLift:t,nameplateLiftReadout:i}=this.options.elements,s=e??g_;t.value=`${s}`,i.textContent=Jn(s,"",0)}installEventListeners(e){const{elements:t}=this.options;t.usePlayerCameraSettings.addEventListener("change",()=>{const s=t.usePlayerCameraSettings.checked;t.cameraSettingsControls.hidden=s,this.options.getReplayPlayer()?.setCustomCameraSettings(s?null:this.readCustomCameraSettings()),this.options.requestConfigSync()},{signal:e});for(const s of[t.customCameraFov,t.customCameraHeight,t.customCameraPitch,t.customCameraDistance,t.customCameraStiffness,t.customCameraSwivelSpeed,t.customCameraTransitionSpeed])s.addEventListener("input",()=>{const a=this.readCustomCameraSettings();this.syncCustomCameraSettingControls(a),this.options.getReplayPlayer()?.setCustomCameraSettings(a),this.options.requestConfigSync()},{signal:e});t.attachedPlayer.addEventListener("change",()=>{const s=this.options.getReplayPlayer(),a=t.attachedPlayer.value||null;this.disableAutoPossessionForManualCameraControl(),s?.setAttachedPlayer(a),a&&(s?.setCustomCameraSettings(null),this.setBallCamMode("player")),this.lastFreeCameraPreset=null,this.options.requestConfigSync()},{signal:e}),t.cameraViewFreeButton.addEventListener("click",()=>{this.options.getReplayPlayer()?.setCameraViewMode("free"),this.disableAutoPossessionForManualCameraControl(),this.lastFreeCameraPreset=null,this.options.requestConfigSync()},{signal:e}),t.cameraViewFollowButton.addEventListener("click",()=>{const s=this.options.getReplayPlayer();this.disableAutoPossessionForManualCameraControl(),s?.setCameraViewMode("follow"),s?.getState().attachedPlayerId&&(s.setCustomCameraSettings(null),this.setBallCamMode("player")),this.lastFreeCameraPreset=null,this.options.requestConfigSync()},{signal:e}),t.cameraViewOverheadButton.addEventListener("click",()=>{this.options.getReplayPlayer()?.setFreeCameraPreset("overhead"),this.disableAutoPossessionForManualCameraControl(),this.lastFreeCameraPreset="overhead",this.options.requestConfigSync()},{signal:e}),t.cameraViewSideButton.addEventListener("click",()=>{this.options.getReplayPlayer()?.setFreeCameraPreset("side"),this.disableAutoPossessionForManualCameraControl(),this.lastFreeCameraPreset="side",this.options.requestConfigSync()},{signal:e});const i=[["off",t.ballCamOffButton],["on",t.ballCamOnButton],["player",t.ballCamPlayerButton]];for(const[s,a]of i)a.addEventListener("click",()=>{this.setBallCamMode(s),this.options.requestConfigSync()},{signal:e});t.cameraViewAutoPossession.addEventListener("change",()=>{this.setAutoPossessionEnabled(t.cameraViewAutoPossession.checked)},{signal:e}),t.nameplateLift.addEventListener("input",()=>{t.nameplateLiftReadout.textContent=Jn(this.nameplateLiftUu,"",0),this.options.requestConfigSync()},{signal:e})}setTransportEnabled(e,t){this.options.elements.attachedPlayer.disabled=!e,this.syncModeButtons(e?t:void 0)}syncState(e){const{elements:t}=this.options;t.usePlayerCameraSettings.checked=e.customCameraSettings===null,t.cameraSettingsControls.hidden=t.usePlayerCameraSettings.checked,this.syncCustomCameraSettingControls(e.customCameraSettings??this.getFallbackCameraSettings()),this.ballCamModeValue=YE(e),this.renderBallCamButtons(),t.attachedPlayer.value=e.attachedPlayerId??"",this.syncAvailability(e),this.renderProfile(e)}syncAvailability(e){this.syncModeButtons(e);const i=this.options.getReplayPlayer()!==null&&e?.cameraViewMode==="follow"&&(e.attachedPlayerId??null)!==null;this.options.elements.usePlayerCameraSettings.disabled=!i,this.setCameraSettingControlsEnabled(i&&e?.customCameraSettings!==null),this.options.elements.ballCamOffButton.disabled=!i,this.options.elements.ballCamOnButton.disabled=!i,this.options.elements.ballCamPlayerButton.disabled=!i,this.renderBallCamButtons()}syncModeButtons(e){const t=e?.cameraViewMode??"free",i=this.options.getReplayPlayer()!==null&&e!==void 0,s=(e?.attachedPlayerId??null)!==null;for(const l of hV){const c=this.getCameraViewButton(l);c.disabled=!i||l==="follow"&&!s;const u=l===t;c.dataset.active=u?"true":"false",c.setAttribute("aria-pressed",u?"true":"false")}const{cameraViewOverheadButton:a,cameraViewSideButton:r}=this.options.elements,{cameraViewAutoPossession:o}=this.options.elements;a.disabled=!i,r.disabled=!i,o.disabled=!i,a.dataset.active="false",r.dataset.active="false",this.renderAutoPossessionButton(),a.setAttribute("aria-pressed","false"),r.setAttribute("aria-pressed","false")}populateAttachedPlayerOptions(e){const{attachedPlayer:t}=this.options.elements;t.replaceChildren(),t.append(new Option("Free camera",""));for(const i of e)t.append(new Option(`${i.name} (${i.isTeamZero?"Blue":"Orange"})`,i.id))}renderProfile(e){const t=this.options.elements,i=this.options.getReplayPlayer(),s=e?.attachedPlayerId??null;if(!i||e?.cameraViewMode!=="follow"||s===null){this.renderEmptyProfile("Free camera");return}const a=i.replay.players.find(o=>o.id===s);if(!a){this.renderEmptyProfile("Unknown");return}const r=this.getEffectiveCameraSettings(e);t.cameraProfileReadout.textContent=e.customCameraSettings===null?a.name:`${a.name} custom`,t.cameraFovReadout.textContent=Jn(r.fov,"",0),t.cameraHeightReadout.textContent=Jn(r.height,"",0),t.cameraPitchReadout.textContent=Jn(r.pitch,"",0),t.cameraBaseDistanceReadout.textContent=Jn(r.distance,"",0),t.cameraStiffnessReadout.textContent=Jn(r.stiffness,"",2)}getFallbackCameraSettings(){return jE}getAttachedPlayerCameraSettings(e){const t=this.options.getReplayPlayer();return!t||e===null?null:t.replay.players.find(i=>i.id===e)?.cameraSettings??null}getEffectiveCameraSettings(e){return{...this.getFallbackCameraSettings(),...this.getAttachedPlayerCameraSettings(e.attachedPlayerId)??{},...e.customCameraSettings??{}}}readCustomCameraSettings(){const e=this.options.elements;return{fov:Number(e.customCameraFov.value),height:Number(e.customCameraHeight.value),pitch:Number(e.customCameraPitch.value),distance:Number(e.customCameraDistance.value),stiffness:Number(e.customCameraStiffness.value),swivelSpeed:Number(e.customCameraSwivelSpeed.value),transitionSpeed:Number(e.customCameraTransitionSpeed.value)}}setCameraSettingControlsEnabled(e){const t=this.options.elements;t.cameraSettingsControls.hidden=t.usePlayerCameraSettings.checked,t.customCameraFov.disabled=!e,t.customCameraHeight.disabled=!e,t.customCameraPitch.disabled=!e,t.customCameraDistance.disabled=!e,t.customCameraStiffness.disabled=!e,t.customCameraSwivelSpeed.disabled=!e,t.customCameraTransitionSpeed.disabled=!e}syncCustomCameraSettingControls(e){const t=this.options.elements,i=this.getFallbackCameraSettings(),s=e.fov??i.fov,a=e.height??i.height,r=e.pitch??i.pitch,o=e.distance??i.distance,l=e.stiffness??i.stiffness,c=e.swivelSpeed??i.swivelSpeed,u=e.transitionSpeed??i.transitionSpeed;t.customCameraFov.value=`${s}`,t.customCameraHeight.value=`${a}`,t.customCameraPitch.value=`${r}`,t.customCameraDistance.value=`${o}`,t.customCameraStiffness.value=`${l}`,t.customCameraSwivelSpeed.value=`${c}`,t.customCameraTransitionSpeed.value=`${u}`,t.customCameraFovReadout.textContent=Jn(s,"",0),t.customCameraHeightReadout.textContent=Jn(a,"",0),t.customCameraPitchReadout.textContent=Jn(r,"",0),t.customCameraDistanceReadout.textContent=Jn(o,"",0),t.customCameraStiffnessReadout.textContent=Jn(l,"",2),t.customCameraSwivelSpeedReadout.textContent=Jn(c,"",1),t.customCameraTransitionSpeedReadout.textContent=Jn(u,"",2)}getCameraViewButton(e){switch(e){case"free":return this.options.elements.cameraViewFreeButton;case"follow":return this.options.elements.cameraViewFollowButton}}renderEmptyProfile(e){const t=this.options.elements;t.cameraProfileReadout.textContent=e,t.cameraFovReadout.textContent="--",t.cameraHeightReadout.textContent="--",t.cameraPitchReadout.textContent="--",t.cameraBaseDistanceReadout.textContent="--",t.cameraStiffnessReadout.textContent="--"}}function Jn(n,e="",t=0){return n===void 0||Number.isNaN(n)?"--":`${n.toFixed(t)}${e}`}function fV(n){return new vy(n)}const Ax="subtr-actor-touch-overlay-styles",by=5882879,xy=16761180,Rx=120,Px=4,pV=196,Cm=24,Ix=210,Lx=5,mV=.1,_V=48,gV=["team","intention","kind","height_band","surface","dodge_state","flag"],yV=[{label:"Blue team",color:by},{label:"Orange team",color:xy}],ZE=[{label:"Shot",color:16711880},{label:"Save",color:58998},{label:"Clear",color:16764928},{label:"Boom",color:16020150},{label:"Pass",color:47103},{label:"Control",color:0},{label:"Advance",color:16486972}],Sd=[{label:"Control",color:0},{label:"Medium hit",color:16436245},{label:"Hard hit",color:16735596}],Td=[{label:"Ground",color:10741301},{label:"Low air",color:3718648},{label:"High air",color:8490232}],JE=[{label:"Ground",color:8702998},{label:"Air",color:6333946},{label:"Wall",color:16347926}],U_=[{label:"No dodge",color:9741240},{label:"Dodge",color:15235577}],B_=[{label:"First touch",color:16777215},{label:"Contested",color:15680580}],vV=[{title:"Team",entries:yV},{title:"Intention",entries:ZE},{title:"Hit strength",entries:Sd},{title:"Height",entries:Td},{title:"Surface",entries:JE},{title:"Dodge",entries:U_},{title:"Flags",entries:B_}];function Fc(n){return Object.fromEntries(n.map(e=>[e.label.toLowerCase().replaceAll(" ","_"),e.color]))}const QE=Fc(ZE),e1={...Fc(Sd),medium_hit:Sd[1].color,hard_hit:Sd[2].color},t1={...Fc(Td),low_air:Td[1].color,high_air:Td[2].color},n1=Fc(JE),i1={...Fc(U_),no_dodge:U_[0].color},z_={first_touch:B_[0].color,contested:B_[1].color},Yi=10134961;function ei(n,e){const t=n.tags;if(!Array.isArray(t))return null;const i=t.find(s=>s.group===e);return i?i.value:null}function s1(n){return ei(n,"possession")??ei(n,"action")}function Ct(n){const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function Am(n,e){return Math.max(0,n-e)}function Md(n){return n==="team"||n==="intention"||n==="kind"||n==="height_band"||n==="surface"||n==="dodge_state"||n==="flag"}function Mo(n){const e=Array.isArray(n)?n:n?[n]:["team"],t=new Set,i=[];for(const s of e)Md(s)&&!t.has(s)&&(t.add(s),i.push(s));return i.length>0?i:["team"]}function a1(n){return n[n.length-1]??"team"}function bV(n,e,t){const i=xV(n,a1(t)),s=i?` · ${i.replaceAll("_"," ")}`:"";if(e==="markers")return`${n.playerName}${s}`;const a=Math.round(n.totalBallAdvanceDistance),r=Math.round(n.totalBallRetreatDistance);return a>0&&r>0?`${n.playerName} +${a} / -${r} uu${s}`:r>0?`${n.playerName} -${r} uu${s}`:`${n.playerName} +${a} uu${s}`}function xV(n,e){return e==="intention"?n.intention:e==="kind"?n.kind:e==="height_band"?n.heightBand:e==="surface"?n.surface:e==="dodge_state"?n.dodgeState:e==="flag"?n.contested?"contested":n.firstTouch?"first_touch":null:null}function wV(n){return n.split("_").filter(Boolean).map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1)}`).join(" ")}function Sl(n,e,t){return typeof e!="string"||e.length===0?null:{key:n,value:e,label:wV(e),color:t[e]??Yi}}function kx(n,e,t){return e!==!0?null:{key:n,value:"true",label:t,color:z_[n]??Yi}}function SV(n){const e=ei(n,"reception")==="first_touch",t=ei(n,"contested")!=null;return[Sl("intention",s1(n),QE),Sl("kind",ei(n,"kind"),e1),Sl("height_band",ei(n,"height_band"),t1),Sl("surface",ei(n,"surface"),n1),Sl("dodge_state",ei(n,"dodge_state"),i1),kx("first_touch",e,"First touch"),kx("contested",t,"Contested")].filter(i=>i!=null)}function r1(n,e){return e==="intention"?QE[n.intention??""]??Yi:e==="kind"?e1[n.kind??""]??Yi:e==="height_band"?t1[n.heightBand??""]??Yi:e==="surface"?n1[n.surface??""]??Yi:e==="dodge_state"?i1[n.dodgeState??""]??Yi:e==="flag"?n.contested?z_.contested??Yi:n.firstTouch?z_.first_touch??Yi:Yi:n.isTeamZero?by:xy}function TV(n,e){return(e.length>0?e:["team"]).map(i=>r1(n,i))}function o1(n,e){const t=[],i=[...be(n,"touch")].sort((s,a)=>s.frame!==a.frame?s.frame-a.frame:s.time!==a.time?s.time-a.time:0);for(const s of i){const a=Ct(s.player),r=e.ballFrames[s.frame]?.position;if(!r)continue;const o=s.ball_movement,c=(o?e.ballFrames[o.end_frame]?.position:null)??r,u=t.length,d=SV(s);t.push({id:`touch-stat:${s.frame}:${a}:${u+1}`,time:e.frames[s.frame]?.time??s.time,frame:s.frame,isTeamZero:s.is_team_0,playerId:a,playerName:e.players.find(h=>h.id===a)?.name??a,kind:ei(s,"kind"),intention:s1(s),heightBand:ei(s,"height_band"),surface:ei(s,"surface"),dodgeState:ei(s,"dodge_state"),firstTouch:ei(s,"reception")==="first_touch",contested:ei(s,"contested")!=null,classifications:d,position:{x:r.x,y:r.y,z:r.z},endPosition:{x:c.x,y:c.y,z:c.z},totalBallTravelDistance:o?Am(o.travel_distance,0):0,totalBallAdvanceDistance:o?Am(o.advance_distance,0):0,totalBallRetreatDistance:o?Am(o.retreat_distance,0):0})}return t}function MV(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function EV(){if(document.getElementById(Ax))return;const n=document.createElement("style");n.id=Ax,n.textContent=` .sap-touch-overlay-root { position: absolute; inset: 0; @@ -5504,45 +5569,45 @@ void main() { border-color: rgba(255, 193, 92, 0.5); background: rgba(76, 41, 7, 0.84); } - `,document.head.append(n)}function KH(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}function ZE(n){return[n.line.material,n.cone.material].flatMap(e=>Array.isArray(e)?e:[e])}function Mx(n,e){for(const t of ZE(n))t.transparent=!0,t.opacity=e,t.depthWrite=!1,t.depthTest=!1}function Ex(n){n.removeFromParent(),n.line.geometry.dispose(),n.cone.geometry.dispose();for(const e of ZE(n))e.dispose()}function D_(n){for(const e of n.ringSegments){e.removeFromParent(),e.geometry.dispose();const t=Array.isArray(e.material)?e.material:[e.material];for(const i of t)i.dispose()}n.ringSegments=[],n.ringColorsKey=""}function qH(n,e,t){const i=new oi(e,t,48,1),s=new je({color:n,transparent:!0,opacity:.7,side:ut,depthWrite:!1,depthTest:!1}),a=new Se(i,s);return a.rotation.x=-Math.PI/2,a.renderOrder=40,a}function YH(n,e){const t=e.length>0?e:[qi],i=t.join("|");if(n.ringColorsKey===i)return;D_(n);const s=t.length,a=xx*Math.max(0,s-1),r=(DH-bx-a)/s,o=t.map((l,c)=>{const u=bx+c*(r+xx);return qH(l,u,u+r)});for(const l of o)n.ring.add(l),n.ringSegments.push(l);n.ringColorsKey=i}function jH(n,e){for(const t of n.ringSegments){const i=Array.isArray(t.material)?t.material:[t.material];for(const s of i)s.opacity=e}}class ZH{scene;container;group=new Et;labelRoot;projectedPosition=new T;worldPosition=new T;arrowStart=new T;arrowEnd=new T;arrowDirection=new T;labelOffset=new T(0,0,wx);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=Sx;mode="markers";colorModes=["team"];constructor(e,t,i,s,a){XH(),this.scene=e,this.container=t,this.decaySeconds=Math.max(.1,a?.decaySeconds??Sx),this.mode=a?.mode??"markers",this.colorModes=So(a?.colorModes??a?.colorMode),this.labelOffset.set(0,0,wx),this.markers=jE(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="touch-event-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-touch-overlay-root",this.container.append(this.labelRoot)}getDecaySeconds(){return this.decaySeconds}setDecaySeconds(e){this.decaySeconds=Math.max(.1,e)}getMode(){return this.mode}setMode(e){this.mode=e}getColorModes(){return[...this.colorModes]}setColorMode(e){this.setColorModes([e])}setColorModes(e){this.colorModes=So([...e])}update(e){const t=WH(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.ring.removeFromParent(),D_(a),Ex(a.arrow),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.1+.6*r,c=.95+(1-r)*.28,u=qE(this.colorModes),d=YE(s,u),h=$H(s,this.colorModes);YH(o,h),jH(o,l),o.arrow.setColor(d),o.ring.position.set(s.position.x,s.position.y,s.position.z+bm),o.ring.scale.setScalar(c),o.label.textContent=zH(s,this.mode,this.colorModes),o.label.classList.toggle("sap-touch-overlay-label-advancement",this.mode==="advancement");const f=u==="team";o.label.classList.toggle("sap-touch-overlay-label-blue",f&&s.isTeamZero),o.label.classList.toggle("sap-touch-overlay-label-orange",f&&!s.isTeamZero),o.label.style.borderColor=f?"":`#${d.toString(16).padStart(6,"0")}cc`,o.label.style.background=f?"":`#${d.toString(16).padStart(6,"0")}66`,this.updateArrow(o,s,l),this.worldPosition.set(s.position.x,s.position.y,s.position.z),this.worldPosition.add(this.labelOffset),this.scene.replayRoot.localToWorld(this.worldPosition),KH(this.worldPosition,this.scene.camera,this.container,this.projectedPosition)?(o.label.hidden=!1,o.label.style.opacity=`${.22+.78*r}`,o.label.style.transform=`translate(${this.projectedPosition.x.toFixed(1)}px, ${this.projectedPosition.y.toFixed(1)}px) translate(-50%, -100%)`):o.label.hidden=!0}}dispose(){for(const e of this.views.values())e.ring.removeFromParent(),D_(e),Ex(e.arrow),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition,this.changedContainerPosition=!1)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=new Et;i.renderOrder=40,this.group.add(i);const s=new jg(new T(0,1,0),new T,1,e.isTeamZero?fy:py,1,1);s.visible=!1,s.renderOrder=45,s.line.renderOrder=45,s.cone.renderOrder=45,Mx(s,.7),this.group.add(s);const a=document.createElement("div");a.className=`sap-touch-overlay-label ${e.isTeamZero?"sap-touch-overlay-label-blue":"sap-touch-overlay-label-orange"}`,a.textContent=e.playerName,a.hidden=!0,this.labelRoot.append(a);const r={marker:e,ring:i,ringSegments:[],ringColorsKey:"",arrow:s,label:a};return this.views.set(e.id,r),r}updateArrow(e,t,i){if(this.mode!=="advancement"||t.totalBallTravelDistance<=OH){e.arrow.visible=!1;return}this.arrowStart.set(t.position.x,t.position.y,t.position.z+bm*2),this.arrowEnd.set(t.endPosition.x,t.endPosition.y,t.endPosition.z+bm*2),this.arrowDirection.copy(this.arrowEnd).sub(this.arrowStart);const s=this.arrowDirection.length();if(s0&&r>0)return a/r}const t=n.frames[0],i=n.frames.at(-1);if(t&&i){const s=i.frame_number-t.frame_number,a=i.time-t.time;if(s>0&&a>0)return s/a}return tV}function iV(n,e={}){if(!n)return[];const t=e.preRollSeconds??JH,i=e.minPossessionSeconds??QH,s=e.samePlayerBridgeSeconds??eV,a=be(n,"player_possession").map(d=>({playerId:Ct(d.player_id),startFrame:Math.max(0,Math.trunc(xl(d.start_frame))),endFrame:Math.max(0,Math.trunc(xl(d.end_frame))),startTime:xl(d.start_time),endTime:xl(d.end_time),duration:xl(d.duration),sustainedControl:d.sustained_control})).filter(d=>d.endFrame>d.startFrame&&(d.sustainedControl||d.duration>=i)).sort((d,h)=>d.startFrame-h.startFrame||d.endFrame-h.endFrame),r=nV(n,a),o=Math.max(0,Math.round(t*r)),l=Math.max(0,Math.round(s*r)),c=[];let u=null;for(const d of a){let h=Math.max(0,d.startFrame-o);u&&u.playerId!==d.playerId&&(h=Math.max(h,u.endFrame));const f=c.at(-1);if(f&&f.playerId===d.playerId&&h<=f.endFrame+l){c[c.length-1]={...f,endFrame:Math.max(f.endFrame,d.endFrame),possessionEndFrame:Math.max(f.possessionEndFrame,d.endFrame)},u=d;continue}c.push({playerId:d.playerId,startFrame:h,endFrame:d.endFrame,possessionStartFrame:d.startFrame,possessionEndFrame:d.endFrame}),u=d}return c.map((d,h)=>({...d,endFrame:c[h+1]?.startFrame??Number.POSITIVE_INFINITY}))}function sV(n,e){const t=Math.max(0,Math.trunc(e));return n.find(s=>t>=s.startFrame&&tthis.update(i))))}reset(){this.unsubscribeBeforeRender?.(),this.unsubscribeBeforeRender=null,this.sourcePlayer=null,this.sourceTimeline=null,this.spans=[]}syncCurrentFrame(){const e=this.options.getReplayPlayer();if(!e)return;const t=e.getState();this.update({frameIndex:t.frameIndex,nextFrameIndex:t.frameIndex,alpha:0,currentTime:t.currentTime})}update(e){const t=this.options.getCameraControlsController(),i=this.options.getReplayPlayer();if(!t?.autoPossessionEnabled||!i)return;const s=sV(this.spans,e.frameIndex);if(!s||!i.replay.players.some(r=>r.id===s))return;const a=i.getState();a.cameraViewMode==="follow"&&a.attachedPlayerId===s||t.followPlayerWithReplayCamera(s,{ballCam:"player",preserveAutoPossession:!0,requestConfigSync:!1,usePlayerCameraSettings:!1})}}function rV(n){return new aV(n)}const oV=236,mc=4120,lV=2300,cV=16185075,uV=.18,dV=1118481,xd=5882879,wd=16761180,hV=.55,wm=.12,Cx=.28,fV=3,pV=4,Ax=5,Rx=2,mV=6,_V=856343,gV=.42,yV=18,vV=.24,bV=10,Px=220,xV=200,JE=140,wV=220,SV=100,TV=120;function MV(n){const e=xV/2;if(n){const s=-mc+Px,a=-e;return{minX:s,maxX:a,centerX:(s+a)/2,width:a-s}}const t=e,i=mc-Px;return{minX:t,maxX:i,centerX:(t+i)/2,width:i-t}}function EV(n,e,t){if(n.length<2)return[];const i=Math.min(...n),s=Math.max(...n),a=s-i,r=e?-1:1,o=-r;return a<=t?[{kind:"other",centerY:(i+s)/2,halfDepth:Math.max(t-a/2,t*.35),directions:[r,o]}]:[{kind:"back",centerY:e?i:s,halfDepth:t,directions:[r]},{kind:"forward",centerY:e?s:i,halfDepth:t,directions:[o]}]}function CV(n,e){const t=new $s;return t.moveTo(0,e/2),t.lineTo(n/2,-e/2),t.lineTo(-n/2,-e/2),t.closePath(),new vr(t)}function Ix(n){const e=SV*n,t=new je({color:dV,transparent:!0,opacity:.9,side:ut,depthWrite:!1,depthTest:!1}),i=new Et;i.visible=!1;const s=new Nn(JE*.55*n,1),a=new Se(s,t);a.position.z=Ax,a.renderOrder=22,i.add(a);const r=CV(TV*n,e),o=new Se(r,t);return o.position.z=Ax,o.renderOrder=23,i.add(o),{group:i,shaftGeom:s,shaftMesh:a,headGeom:r,headMesh:o,material:t,headLength:e}}function Sm(n,e,t,i){const s=Math.max(t-n.headLength,n.headLength*.2);n.group.position.x=e,n.group.rotation.z=i>0?0:Math.PI,n.shaftMesh.scale.y=s,n.shaftMesh.position.y=-n.headLength/2,n.headMesh.position.y=t/2-n.headLength/2,n.group.visible=!0}function Sh(n){n.group.visible=!1}function so(n,e){const t=new Et;t.visible=!1;const i=new je({color:cV,transparent:!0,opacity:uV,side:ut,depthWrite:!1,depthTest:!1}),s=new Nn(1,1),a=new Se(s,i);a.position.z=fV,a.renderOrder=20,t.add(a);const r=new je({color:e,transparent:!0,opacity:hV,side:ut,depthWrite:!1,depthTest:!1}),o=new Nn(1,1),l=new Se(o,r);l.position.z=pV,l.renderOrder=21,t.add(l);const c=Ix(n),u=Ix(n);return t.add(c.group),t.add(u.group),{group:t,floorGeom:s,floorMesh:a,floorMaterial:i,stripeGeom:o,stripeMesh:l,stripeMaterial:r,primaryMarker:c,secondaryMarker:u}}function AV(n){n.group.visible=!1,Sh(n.primaryMarker),Sh(n.secondaryMarker)}function RV(n,e,t,i){const s=e.halfDepth*2*i,a=mc*2*i,r=t.width*i,o=t.centerX*i,l=JE*i,c=Math.max(s-32*i,n.primaryMarker.headLength*1.15),u=Math.min(c,Math.max(wV*i,s*.6));if(n.group.position.y=e.centerY*i,n.floorMesh.position.x=0,n.floorMesh.scale.set(a,s,1),n.stripeMesh.position.x=o,n.stripeMesh.scale.set(l,s,1),Sh(n.primaryMarker),Sh(n.secondaryMarker),e.directions.length===1)Sm(n.primaryMarker,o,u,e.directions[0]);else{const d=r*.18;Sm(n.primaryMarker,o-d,u,e.directions[0]),Sm(n.secondaryMarker,o+d,u,e.directions[1])}n.group.visible=!0}function Lx(n){n.group.removeFromParent(),n.shaftGeom.dispose(),n.headGeom.dispose(),n.material.dispose()}class PV{replay;blueBack;blueForward;blueOther;orangeBack;orangeForward;orangeOther;constructor(e,t,i){this.replay=t,this.blueBack=so(i,xd),this.blueForward=so(i,xd),this.blueOther=so(i,xd),this.orangeBack=so(i,wd),this.orangeForward=so(i,wd),this.orangeOther=so(i,wd);for(const s of this.getZones())e.add(s.group)}update(e,t){const{frameIndex:i}=e,s=oV;for(const a of[!0,!1]){const r=this.replay.players.filter(d=>d.isTeamZero===a).length,o=[];for(const d of this.replay.players){if(d.isTeamZero!==a)continue;const h=d.frames[i];h?.position&&o.push(h.position.y)}const l=MV(a),c=this.getTeamZones(a);for(const d of c.values())AV(d);if(r<2||o.length!==r)continue;const u=EV(o,a,s);for(const d of u){const h=c.get(d.kind);h&&RV(h,d,l,t)}}}dispose(){for(const e of this.getZones())e.group.removeFromParent(),e.floorGeom.dispose(),e.floorMaterial.dispose(),e.stripeGeom.dispose(),e.stripeMaterial.dispose(),Lx(e.primaryMarker),Lx(e.secondaryMarker)}getTeamZones(e){return e?new Map([["back",this.blueBack],["forward",this.blueForward],["other",this.blueOther]]):new Map([["back",this.orangeBack],["forward",this.orangeForward],["other",this.orangeOther]])}getZones(){return[this.blueBack,this.blueForward,this.blueOther,this.orangeBack,this.orangeForward,this.orangeOther]}}function IV(n){return n==null||Number.isNaN(n)?null:n<0?"team-zero":"team-one"}class LV{group;teamZeroSide;teamOneSide;constructor(e,t){this.group=new Et,this.teamZeroSide=this.createHalfFieldSide(xd),this.teamOneSide=this.createHalfFieldSide(wd);const i=mc*t,s=5120*t;this.teamZeroSide.mesh.position.set(0,-s/2,Rx),this.teamZeroSide.mesh.scale.set(i*2,s,1),this.teamOneSide.mesh.position.set(0,s/2,Rx),this.teamOneSide.mesh.scale.set(i*2,s,1),this.group.add(this.teamZeroSide.mesh),this.group.add(this.teamOneSide.mesh),e.add(this.group)}update(e){const t=IV(e);this.teamZeroSide.material.opacity=t==="team-zero"?Cx:wm,this.teamOneSide.material.opacity=t==="team-one"?Cx:wm}dispose(){this.group.removeFromParent(),this.teamZeroSide.mesh.geometry.dispose(),this.teamZeroSide.material.dispose(),this.teamOneSide.mesh.geometry.dispose(),this.teamOneSide.material.dispose()}createHalfFieldSide(e){const t=new Nn(1,1),i=new je({color:e,transparent:!0,opacity:wm,side:ut,depthWrite:!1,depthTest:!1}),s=new Se(t,i);return s.renderOrder=18,{mesh:s,material:i}}}function kV(n,e){const t=new Et,i=mc*2*e,s=(a,r,o)=>{const l=new Nn(i,r*e),c=new je({color:_V,transparent:!0,opacity:o,side:ut,depthWrite:!1,depthTest:!1}),u=new Se(l,c);return u.position.set(0,a,mV),u.renderOrder=24,u};for(const a of[-1,1]){const r=a*lV*e;t.add(s(r,yV,gV))}return t.add(s(0,bV,vV)),n.add(t),t}function un(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function O_(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function Hi(n,e){return`
${n}${e}
`}function DV(n,e){return` - ${Hi("50s",un(n?.count))} - ${Hi("Blue wins",`${un(n?.wins)} (${O_(n?.wins,n?.count)})`)} - ${Hi("Orange wins",`${un(n?.losses)} (${O_(n?.losses,n?.count)})`)} - ${Hi("Neutral",un(n?.neutral_outcomes))} - ${Hi("Blue poss after",un(n?.possession_after_count))} - ${Hi("Orange poss after",un(n?.opponent_possession_after_count))} - ${Hi("Kickoff 50s",un(n?.kickoff_count))} - ${Hi("Blue kickoff wins",un(n?.kickoff_wins))} - ${Hi("Orange kickoff wins",un(n?.kickoff_losses))} - ${Hi("Blue kickoff poss",un(n?.kickoff_possession_after_count))} - ${Hi("Orange kickoff poss",un(n?.kickoff_opponent_possession_after_count))} - `}function kx(n){return` + `,document.head.append(n)}function CV(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}function l1(n){return[n.line.material,n.cone.material].flatMap(e=>Array.isArray(e)?e:[e])}function Dx(n,e){for(const t of l1(n))t.transparent=!0,t.opacity=e,t.depthWrite=!1,t.depthTest=!1}function Ox(n){n.removeFromParent(),n.line.geometry.dispose(),n.cone.geometry.dispose();for(const e of l1(n))e.dispose()}function H_(n){for(const e of n.ringSegments){e.removeFromParent(),e.geometry.dispose();const t=Array.isArray(e.material)?e.material:[e.material];for(const i of t)i.dispose()}n.ringSegments=[],n.ringColorsKey=""}function AV(n,e,t){const i=new oi(e,t,48,1),s=new je({color:n,transparent:!0,opacity:.7,side:ut,depthWrite:!1,depthTest:!1}),a=new Se(i,s);return a.rotation.x=-Math.PI/2,a.renderOrder=40,a}function RV(n,e){const t=e.length>0?e:[Yi],i=t.join("|");if(n.ringColorsKey===i)return;H_(n);const s=t.length,a=Px*Math.max(0,s-1),r=(pV-Rx-a)/s,o=t.map((l,c)=>{const u=Rx+c*(r+Px);return AV(l,u,u+r)});for(const l of o)n.ring.add(l),n.ringSegments.push(l);n.ringColorsKey=i}function PV(n,e){for(const t of n.ringSegments){const i=Array.isArray(t.material)?t.material:[t.material];for(const s of i)s.opacity=e}}class IV{scene;container;group=new Et;labelRoot;projectedPosition=new T;worldPosition=new T;arrowStart=new T;arrowEnd=new T;arrowDirection=new T;labelOffset=new T(0,0,Ix);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=Lx;mode="markers";colorModes=["team"];constructor(e,t,i,s,a){EV(),this.scene=e,this.container=t,this.decaySeconds=Math.max(.1,a?.decaySeconds??Lx),this.mode=a?.mode??"markers",this.colorModes=Mo(a?.colorModes??a?.colorMode),this.labelOffset.set(0,0,Ix),this.markers=o1(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="touch-event-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-touch-overlay-root",this.container.append(this.labelRoot)}getDecaySeconds(){return this.decaySeconds}setDecaySeconds(e){this.decaySeconds=Math.max(.1,e)}getMode(){return this.mode}setMode(e){this.mode=e}getColorModes(){return[...this.colorModes]}setColorMode(e){this.setColorModes([e])}setColorModes(e){this.colorModes=Mo([...e])}update(e){const t=MV(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.ring.removeFromParent(),H_(a),Ox(a.arrow),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.1+.6*r,c=.95+(1-r)*.28,u=a1(this.colorModes),d=r1(s,u),h=TV(s,this.colorModes);RV(o,h),PV(o,l),o.arrow.setColor(d),o.ring.position.set(s.position.x,s.position.y,s.position.z+Cm),o.ring.scale.setScalar(c),o.label.textContent=bV(s,this.mode,this.colorModes),o.label.classList.toggle("sap-touch-overlay-label-advancement",this.mode==="advancement");const f=u==="team";o.label.classList.toggle("sap-touch-overlay-label-blue",f&&s.isTeamZero),o.label.classList.toggle("sap-touch-overlay-label-orange",f&&!s.isTeamZero),o.label.style.borderColor=f?"":`#${d.toString(16).padStart(6,"0")}cc`,o.label.style.background=f?"":`#${d.toString(16).padStart(6,"0")}66`,this.updateArrow(o,s,l),this.worldPosition.set(s.position.x,s.position.y,s.position.z),this.worldPosition.add(this.labelOffset),this.scene.replayRoot.localToWorld(this.worldPosition),CV(this.worldPosition,this.scene.camera,this.container,this.projectedPosition)?(o.label.hidden=!1,o.label.style.opacity=`${.22+.78*r}`,o.label.style.transform=`translate(${this.projectedPosition.x.toFixed(1)}px, ${this.projectedPosition.y.toFixed(1)}px) translate(-50%, -100%)`):o.label.hidden=!0}}dispose(){for(const e of this.views.values())e.ring.removeFromParent(),H_(e),Ox(e.arrow),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition,this.changedContainerPosition=!1)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=new Et;i.renderOrder=40,this.group.add(i);const s=new iy(new T(0,1,0),new T,1,e.isTeamZero?by:xy,1,1);s.visible=!1,s.renderOrder=45,s.line.renderOrder=45,s.cone.renderOrder=45,Dx(s,.7),this.group.add(s);const a=document.createElement("div");a.className=`sap-touch-overlay-label ${e.isTeamZero?"sap-touch-overlay-label-blue":"sap-touch-overlay-label-orange"}`,a.textContent=e.playerName,a.hidden=!0,this.labelRoot.append(a);const r={marker:e,ring:i,ringSegments:[],ringColorsKey:"",arrow:s,label:a};return this.views.set(e.id,r),r}updateArrow(e,t,i){if(this.mode!=="advancement"||t.totalBallTravelDistance<=mV){e.arrow.visible=!1;return}this.arrowStart.set(t.position.x,t.position.y,t.position.z+Cm*2),this.arrowEnd.set(t.endPosition.x,t.endPosition.y,t.endPosition.z+Cm*2),this.arrowDirection.copy(this.arrowEnd).sub(this.arrowStart);const s=this.arrowDirection.length();if(s<_V){e.arrow.visible=!1;return}this.arrowDirection.normalize(),e.arrow.visible=!0,e.arrow.position.copy(this.arrowStart),e.arrow.setDirection(this.arrowDirection),e.arrow.setLength(s,Math.min(140,Math.max(42,s*.18)),Math.min(86,Math.max(24,s*.1))),Dx(e.arrow,Math.min(.86,i+.12))}}const LV=.8,kV=.45,DV=.5,OV=30;function Tl(n){return Number.isFinite(n)?n:0}function FV(n,e){for(const s of e){const a=s.endFrame-s.startFrame,r=s.endTime-s.startTime;if(a>0&&r>0)return a/r}const t=n.frames[0],i=n.frames.at(-1);if(t&&i){const s=i.frame_number-t.frame_number,a=i.time-t.time;if(s>0&&a>0)return s/a}return OV}function NV(n,e={}){if(!n)return[];const t=e.preRollSeconds??LV,i=e.minPossessionSeconds??kV,s=e.samePlayerBridgeSeconds??DV,a=be(n,"player_possession").map(d=>({playerId:Ct(d.player_id),startFrame:Math.max(0,Math.trunc(Tl(d.start_frame))),endFrame:Math.max(0,Math.trunc(Tl(d.end_frame))),startTime:Tl(d.start_time),endTime:Tl(d.end_time),duration:Tl(d.duration),sustainedControl:d.sustained_control})).filter(d=>d.endFrame>d.startFrame&&(d.sustainedControl||d.duration>=i)).sort((d,h)=>d.startFrame-h.startFrame||d.endFrame-h.endFrame),r=FV(n,a),o=Math.max(0,Math.round(t*r)),l=Math.max(0,Math.round(s*r)),c=[];let u=null;for(const d of a){let h=Math.max(0,d.startFrame-o);u&&u.playerId!==d.playerId&&(h=Math.max(h,u.endFrame));const f=c.at(-1);if(f&&f.playerId===d.playerId&&h<=f.endFrame+l){c[c.length-1]={...f,endFrame:Math.max(f.endFrame,d.endFrame),possessionEndFrame:Math.max(f.possessionEndFrame,d.endFrame)},u=d;continue}c.push({playerId:d.playerId,startFrame:h,endFrame:d.endFrame,possessionStartFrame:d.startFrame,possessionEndFrame:d.endFrame}),u=d}return c.map((d,h)=>({...d,endFrame:c[h+1]?.startFrame??Number.POSITIVE_INFINITY}))}function UV(n,e){const t=Math.max(0,Math.trunc(e));return n.find(s=>t>=s.startFrame&&tthis.update(i))))}reset(){this.unsubscribeBeforeRender?.(),this.unsubscribeBeforeRender=null,this.sourcePlayer=null,this.sourceTimeline=null,this.spans=[]}syncCurrentFrame(){const e=this.options.getReplayPlayer();if(!e)return;const t=e.getState();this.update({frameIndex:t.frameIndex,nextFrameIndex:t.frameIndex,alpha:0,currentTime:t.currentTime})}update(e){const t=this.options.getCameraControlsController(),i=this.options.getReplayPlayer();if(!t?.autoPossessionEnabled||!i)return;const s=UV(this.spans,e.frameIndex);if(!s||!i.replay.players.some(r=>r.id===s))return;const a=i.getState();a.cameraViewMode==="follow"&&a.attachedPlayerId===s||t.followPlayerWithReplayCamera(s,{ballCam:"player",preserveAutoPossession:!0,requestConfigSync:!1,usePlayerCameraSettings:!1})}}function zV(n){return new BV(n)}const HV=236,vc=4120,VV=2300,GV=16185075,$V=.18,WV=1118481,Ed=5882879,Cd=16761180,XV=.55,Rm=.12,Fx=.28,KV=3,qV=4,Nx=5,Ux=2,YV=6,jV=856343,ZV=.42,JV=18,QV=.24,e4=10,Bx=220,t4=200,c1=140,n4=220,i4=100,s4=120;function a4(n){const e=t4/2;if(n){const s=-vc+Bx,a=-e;return{minX:s,maxX:a,centerX:(s+a)/2,width:a-s}}const t=e,i=vc-Bx;return{minX:t,maxX:i,centerX:(t+i)/2,width:i-t}}function r4(n,e,t){if(n.length<2)return[];const i=Math.min(...n),s=Math.max(...n),a=s-i,r=e?-1:1,o=-r;return a<=t?[{kind:"other",centerY:(i+s)/2,halfDepth:Math.max(t-a/2,t*.35),directions:[r,o]}]:[{kind:"back",centerY:e?i:s,halfDepth:t,directions:[r]},{kind:"forward",centerY:e?s:i,halfDepth:t,directions:[o]}]}function o4(n,e){const t=new $s;return t.moveTo(0,e/2),t.lineTo(n/2,-e/2),t.lineTo(-n/2,-e/2),t.closePath(),new br(t)}function zx(n){const e=i4*n,t=new je({color:WV,transparent:!0,opacity:.9,side:ut,depthWrite:!1,depthTest:!1}),i=new Et;i.visible=!1;const s=new Nn(c1*.55*n,1),a=new Se(s,t);a.position.z=Nx,a.renderOrder=22,i.add(a);const r=o4(s4*n,e),o=new Se(r,t);return o.position.z=Nx,o.renderOrder=23,i.add(o),{group:i,shaftGeom:s,shaftMesh:a,headGeom:r,headMesh:o,material:t,headLength:e}}function Pm(n,e,t,i){const s=Math.max(t-n.headLength,n.headLength*.2);n.group.position.x=e,n.group.rotation.z=i>0?0:Math.PI,n.shaftMesh.scale.y=s,n.shaftMesh.position.y=-n.headLength/2,n.headMesh.position.y=t/2-n.headLength/2,n.group.visible=!0}function Rh(n){n.group.visible=!1}function ro(n,e){const t=new Et;t.visible=!1;const i=new je({color:GV,transparent:!0,opacity:$V,side:ut,depthWrite:!1,depthTest:!1}),s=new Nn(1,1),a=new Se(s,i);a.position.z=KV,a.renderOrder=20,t.add(a);const r=new je({color:e,transparent:!0,opacity:XV,side:ut,depthWrite:!1,depthTest:!1}),o=new Nn(1,1),l=new Se(o,r);l.position.z=qV,l.renderOrder=21,t.add(l);const c=zx(n),u=zx(n);return t.add(c.group),t.add(u.group),{group:t,floorGeom:s,floorMesh:a,floorMaterial:i,stripeGeom:o,stripeMesh:l,stripeMaterial:r,primaryMarker:c,secondaryMarker:u}}function l4(n){n.group.visible=!1,Rh(n.primaryMarker),Rh(n.secondaryMarker)}function c4(n,e,t,i){const s=e.halfDepth*2*i,a=vc*2*i,r=t.width*i,o=t.centerX*i,l=c1*i,c=Math.max(s-32*i,n.primaryMarker.headLength*1.15),u=Math.min(c,Math.max(n4*i,s*.6));if(n.group.position.y=e.centerY*i,n.floorMesh.position.x=0,n.floorMesh.scale.set(a,s,1),n.stripeMesh.position.x=o,n.stripeMesh.scale.set(l,s,1),Rh(n.primaryMarker),Rh(n.secondaryMarker),e.directions.length===1)Pm(n.primaryMarker,o,u,e.directions[0]);else{const d=r*.18;Pm(n.primaryMarker,o-d,u,e.directions[0]),Pm(n.secondaryMarker,o+d,u,e.directions[1])}n.group.visible=!0}function Hx(n){n.group.removeFromParent(),n.shaftGeom.dispose(),n.headGeom.dispose(),n.material.dispose()}class u4{replay;blueBack;blueForward;blueOther;orangeBack;orangeForward;orangeOther;constructor(e,t,i){this.replay=t,this.blueBack=ro(i,Ed),this.blueForward=ro(i,Ed),this.blueOther=ro(i,Ed),this.orangeBack=ro(i,Cd),this.orangeForward=ro(i,Cd),this.orangeOther=ro(i,Cd);for(const s of this.getZones())e.add(s.group)}update(e,t){const{frameIndex:i}=e,s=HV;for(const a of[!0,!1]){const r=this.replay.players.filter(d=>d.isTeamZero===a).length,o=[];for(const d of this.replay.players){if(d.isTeamZero!==a)continue;const h=d.frames[i];h?.position&&o.push(h.position.y)}const l=a4(a),c=this.getTeamZones(a);for(const d of c.values())l4(d);if(r<2||o.length!==r)continue;const u=r4(o,a,s);for(const d of u){const h=c.get(d.kind);h&&c4(h,d,l,t)}}}dispose(){for(const e of this.getZones())e.group.removeFromParent(),e.floorGeom.dispose(),e.floorMaterial.dispose(),e.stripeGeom.dispose(),e.stripeMaterial.dispose(),Hx(e.primaryMarker),Hx(e.secondaryMarker)}getTeamZones(e){return e?new Map([["back",this.blueBack],["forward",this.blueForward],["other",this.blueOther]]):new Map([["back",this.orangeBack],["forward",this.orangeForward],["other",this.orangeOther]])}getZones(){return[this.blueBack,this.blueForward,this.blueOther,this.orangeBack,this.orangeForward,this.orangeOther]}}function d4(n){return n==null||Number.isNaN(n)?null:n<0?"team-zero":"team-one"}class h4{group;teamZeroSide;teamOneSide;constructor(e,t){this.group=new Et,this.teamZeroSide=this.createHalfFieldSide(Ed),this.teamOneSide=this.createHalfFieldSide(Cd);const i=vc*t,s=5120*t;this.teamZeroSide.mesh.position.set(0,-s/2,Ux),this.teamZeroSide.mesh.scale.set(i*2,s,1),this.teamOneSide.mesh.position.set(0,s/2,Ux),this.teamOneSide.mesh.scale.set(i*2,s,1),this.group.add(this.teamZeroSide.mesh),this.group.add(this.teamOneSide.mesh),e.add(this.group)}update(e){const t=d4(e);this.teamZeroSide.material.opacity=t==="team-zero"?Fx:Rm,this.teamOneSide.material.opacity=t==="team-one"?Fx:Rm}dispose(){this.group.removeFromParent(),this.teamZeroSide.mesh.geometry.dispose(),this.teamZeroSide.material.dispose(),this.teamOneSide.mesh.geometry.dispose(),this.teamOneSide.material.dispose()}createHalfFieldSide(e){const t=new Nn(1,1),i=new je({color:e,transparent:!0,opacity:Rm,side:ut,depthWrite:!1,depthTest:!1}),s=new Se(t,i);return s.renderOrder=18,{mesh:s,material:i}}}function f4(n,e){const t=new Et,i=vc*2*e,s=(a,r,o)=>{const l=new Nn(i,r*e),c=new je({color:jV,transparent:!0,opacity:o,side:ut,depthWrite:!1,depthTest:!1}),u=new Se(l,c);return u.position.set(0,a,YV),u.renderOrder=24,u};for(const a of[-1,1]){const r=a*VV*e;t.add(s(r,JV,ZV))}return t.add(s(0,e4,QV)),n.add(t),t}function un(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function V_(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function Vi(n,e){return`
${n}${e}
`}function p4(n,e){return` + ${Vi("50s",un(n?.count))} + ${Vi("Blue wins",`${un(n?.wins)} (${V_(n?.wins,n?.count)})`)} + ${Vi("Orange wins",`${un(n?.losses)} (${V_(n?.losses,n?.count)})`)} + ${Vi("Neutral",un(n?.neutral_outcomes))} + ${Vi("Blue poss after",un(n?.possession_after_count))} + ${Vi("Orange poss after",un(n?.opponent_possession_after_count))} + ${Vi("Kickoff 50s",un(n?.kickoff_count))} + ${Vi("Blue kickoff wins",un(n?.kickoff_wins))} + ${Vi("Orange kickoff wins",un(n?.kickoff_losses))} + ${Vi("Blue kickoff poss",un(n?.kickoff_possession_after_count))} + ${Vi("Orange kickoff poss",un(n?.kickoff_opponent_possession_after_count))} + `}function Vx(n){return`
50s${un(n?.count)}
-
Wins${un(n?.wins)} (${O_(n?.wins,n?.count)})
+
Wins${un(n?.wins)} (${V_(n?.wins,n?.count)})
Losses${un(n?.losses)}
Neutral${un(n?.neutral_outcomes)}
Poss after${un(n?.possession_after_count)}
Kickoff 50s${un(n?.kickoff_count)}
Kickoff wins${un(n?.kickoff_wins)}
Kickoff poss${un(n?.kickoff_possession_after_count)}
- `}function OV(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function FV(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function Dx(n,e,t=1){if(n===void 0||Number.isNaN(n))return"?";const i=FV(n,e,t);return i==="?"?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${i})`}function Ox(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function F_(n,e){return`
${Ox(n)}${Ox(e)}
`}function NV(n){const e=new Set,t=[];for(const i of n??[])e.has(i)||(e.add(i),t.push(i));return t}function QE(n,e){return n==="neutral"?"Neutral":e.kind==="shared"?n==="own"?"Blue control":"Orange control":n==="own"?"Team control":"Opp control"}function N_(n){return n.kind==="shared"?["own","neutral","opponent"]:["own","neutral","opponent"]}function UV(n,e){return n==="neutral_third"?"Neutral third":e.kind==="shared"?n==="defensive_third"?"Blue third":"Orange third":n==="defensive_third"?"Own third":"Opp third"}function BV(n){return n.kind==="shared"?["defensive_third","neutral_third","offensive_third"]:["defensive_third","neutral_third","offensive_third"]}function zV(n,e){return n==="neutral"?"Neutral":e.kind==="shared"?n==="defensive_half"?"Blue half":"Orange half":n==="defensive_half"?"Own half":"Opp half"}function HV(n){return n.kind==="shared"?["defensive_half","neutral","offensive_half"]:["defensive_half","neutral","offensive_half"]}function VV(n,e,t,i){for(const s of t){const a=s==="possession_state"?N_(i):s==="field_third"?BV(i):HV(i),r=a.indexOf(n[s]),o=a.indexOf(e[s]),l=r===-1?Number.MAX_SAFE_INTEGER:r,c=o===-1?Number.MAX_SAFE_INTEGER:o;if(l!==c)return l-c}return 0}function GV(n,e,t){const i=(s,a)=>s==="possession_state"?QE(a,t):s==="field_third"?UV(a,t):zV(a,t);if(e.length===1){const s=e[0];return i(s,n[s])}return e.map(s=>i(s,n[s])).join(" / ")}function $V(n,e,t,i){if(e.length===0)return"";const s=new Map;if(n?.labeled_time?.entries?.length)for(const a of n.labeled_time.entries){const r=new Map(a.labels.map(d=>[d.key,d.value])),o={};let l=!0;for(const d of e){const h=r.get(d);if(h===void 0){l=!1;break}o[d]=h}if(!l)continue;const c=e.map(d=>`${d}:${o[d]}`).join("|"),u=s.get(c);u?u.total+=a.value:s.set(c,{values:o,total:a.value})}if(s.size===0&&e.length===1&&e[0]==="possession_state"){const a=new Map;return n&&(a.set("own",n.possession_time),a.set("neutral",n.neutral_time??0),a.set("opponent",n.opponent_possession_time)),N_(i).some(r=>(a.get(r)??0)>0)?N_(i).filter(r=>a.has(r)).map(r=>F_(QE(r,i),Dx(a.get(r),t))).join(""):""}return[...s.values()].sort((a,r)=>VV(a.values,r.values,e,i)).map(a=>F_(GV(a.values,e,i),Dx(a.total,t))).join("")}function Fx(n,e){const t=n?.tracked_time,i=NV(e.breakdownClasses),s=$V(n,i,t,e.labelPerspective);return` - ${F_("Tracked",OV(t,1,"s"))} + `}function m4(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function _4(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function Gx(n,e,t=1){if(n===void 0||Number.isNaN(n))return"?";const i=_4(n,e,t);return i==="?"?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${i})`}function $x(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function G_(n,e){return`
${$x(n)}${$x(e)}
`}function g4(n){const e=new Set,t=[];for(const i of n??[])e.has(i)||(e.add(i),t.push(i));return t}function u1(n,e){return n==="neutral"?"Neutral":e.kind==="shared"?n==="own"?"Blue control":"Orange control":n==="own"?"Team control":"Opp control"}function $_(n){return n.kind==="shared"?["own","neutral","opponent"]:["own","neutral","opponent"]}function y4(n,e){return n==="neutral_third"?"Neutral third":e.kind==="shared"?n==="defensive_third"?"Blue third":"Orange third":n==="defensive_third"?"Own third":"Opp third"}function v4(n){return n.kind==="shared"?["defensive_third","neutral_third","offensive_third"]:["defensive_third","neutral_third","offensive_third"]}function b4(n,e){return n==="neutral"?"Neutral":e.kind==="shared"?n==="defensive_half"?"Blue half":"Orange half":n==="defensive_half"?"Own half":"Opp half"}function x4(n){return n.kind==="shared"?["defensive_half","neutral","offensive_half"]:["defensive_half","neutral","offensive_half"]}function w4(n,e,t,i){for(const s of t){const a=s==="possession_state"?$_(i):s==="field_third"?v4(i):x4(i),r=a.indexOf(n[s]),o=a.indexOf(e[s]),l=r===-1?Number.MAX_SAFE_INTEGER:r,c=o===-1?Number.MAX_SAFE_INTEGER:o;if(l!==c)return l-c}return 0}function S4(n,e,t){const i=(s,a)=>s==="possession_state"?u1(a,t):s==="field_third"?y4(a,t):b4(a,t);if(e.length===1){const s=e[0];return i(s,n[s])}return e.map(s=>i(s,n[s])).join(" / ")}function T4(n,e,t,i){if(e.length===0)return"";const s=new Map;if(n?.labeled_time?.entries?.length)for(const a of n.labeled_time.entries){const r=new Map(a.labels.map(d=>[d.key,d.value])),o={};let l=!0;for(const d of e){const h=r.get(d);if(h===void 0){l=!1;break}o[d]=h}if(!l)continue;const c=e.map(d=>`${d}:${o[d]}`).join("|"),u=s.get(c);u?u.total+=a.value:s.set(c,{values:o,total:a.value})}if(s.size===0&&e.length===1&&e[0]==="possession_state"){const a=new Map;return n&&(a.set("own",n.possession_time),a.set("neutral",n.neutral_time??0),a.set("opponent",n.opponent_possession_time)),$_(i).some(r=>(a.get(r)??0)>0)?$_(i).filter(r=>a.has(r)).map(r=>G_(u1(r,i),Gx(a.get(r),t))).join(""):""}return[...s.values()].sort((a,r)=>w4(a.values,r.values,e,i)).map(a=>G_(S4(a.values,e,i),Gx(a.total,t))).join("")}function Wx(n,e){const t=n?.tracked_time,i=g4(e.breakdownClasses),s=T4(n,i,t,e.labelPerspective);return` + ${G_("Tracked",m4(t,1,"s"))} ${s} - `}function WV(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function XV(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function KV(n,e,t=1){if(n===void 0||Number.isNaN(n))return"?";const i=XV(n,e,t);return i==="?"?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${i})`}function Nx(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function e1(n,e){return`
${Nx(n)}${Nx(e)}
`}function qV(n,e){return n==="neutral"?"Neutral zone":e.kind==="shared"?n==="defensive_half"?"Blue side":"Orange side":n==="defensive_half"?"Own half":"Opp half"}function YV(n,e,t){const i=new Map;if(n&&(i.set("defensive_half",n.defensive_half_time),i.set("neutral",n.neutral_time??0),i.set("offensive_half",n.offensive_half_time)),n?.labeled_time?.entries?.length){i.clear();for(const a of n.labeled_time.entries){const r=a.labels.find(o=>o.key==="field_half")?.value;r&&i.set(r,(i.get(r)??0)+a.value)}}const s=["defensive_half","neutral","offensive_half"];return s.some(a=>(i.get(a)??0)>0)?s.filter(a=>i.has(a)).map(a=>e1(qV(a,t),KV(i.get(a),e))).join(""):""}function Ux(n,e){const t=n?.tracked_time,i=YV(n,t,e.labelPerspective);return` - ${i.length===0?e1("Tracked",WV(t,1,"s")):""} + `}function M4(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function E4(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function C4(n,e,t=1){if(n===void 0||Number.isNaN(n))return"?";const i=E4(n,e,t);return i==="?"?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${i})`}function Xx(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function d1(n,e){return`
${Xx(n)}${Xx(e)}
`}function A4(n,e){return n==="neutral"?"Neutral zone":e.kind==="shared"?n==="defensive_half"?"Blue side":"Orange side":n==="defensive_half"?"Own half":"Opp half"}function R4(n,e,t){const i=new Map;if(n&&(i.set("defensive_half",n.defensive_half_time),i.set("neutral",n.neutral_time??0),i.set("offensive_half",n.offensive_half_time)),n?.labeled_time?.entries?.length){i.clear();for(const a of n.labeled_time.entries){const r=a.labels.find(o=>o.key==="field_half")?.value;r&&i.set(r,(i.get(r)??0)+a.value)}}const s=["defensive_half","neutral","offensive_half"];return s.some(a=>(i.get(a)??0)>0)?s.filter(a=>i.has(a)).map(a=>d1(A4(a,t),C4(i.get(a),e))).join(""):""}function Kx(n,e){const t=n?.tracked_time,i=R4(n,t,e.labelPerspective);return` + ${i.length===0?d1("Tracked",M4(t,1,"s")):""} ${i} - `}function jV(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function ZV(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function JV(n,e,t=1){if(n===void 0||Number.isNaN(n))return"?";const i=ZV(n,e,t);return i==="?"?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${i})`}function Bx(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function t1(n,e){return`
${Bx(n)}${Bx(e)}
`}function QV(n,e){return n==="neutral_third"?"Neutral third":e.kind==="shared"?n==="defensive_third"?"Blue third":"Orange third":n==="defensive_third"?"Own third":"Opp third"}function e4(n,e,t){const i=new Map;if(n&&(i.set("defensive_third",n.defensive_third_time),i.set("neutral_third",n.neutral_third_time??0),i.set("offensive_third",n.offensive_third_time)),n?.labeled_time?.entries?.length){i.clear();for(const a of n.labeled_time.entries){const r=a.labels.find(o=>o.key==="field_third")?.value;r&&i.set(r,(i.get(r)??0)+a.value)}}const s=["defensive_third","neutral_third","offensive_third"];return s.some(a=>(i.get(a)??0)>0)?s.filter(a=>i.has(a)).map(a=>t1(QV(a,t),JV(i.get(a),e))).join(""):""}function zx(n,e){const t=n?.tracked_time,i=e4(n,t,e.labelPerspective);return` - ${i.length===0?t1("Tracked",jV(t,1,"s")):""} + `}function P4(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function I4(n,e,t=1){return n===void 0||e===void 0||Number.isNaN(n)||Number.isNaN(e)||e<=0?"?":`${(n*100/e).toFixed(t)}%`}function L4(n,e,t=1){if(n===void 0||Number.isNaN(n))return"?";const i=I4(n,e,t);return i==="?"?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${i})`}function qx(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function h1(n,e){return`
${qx(n)}${qx(e)}
`}function k4(n,e){return n==="neutral_third"?"Neutral third":e.kind==="shared"?n==="defensive_third"?"Blue third":"Orange third":n==="defensive_third"?"Own third":"Opp third"}function D4(n,e,t){const i=new Map;if(n&&(i.set("defensive_third",n.defensive_third_time),i.set("neutral_third",n.neutral_third_time??0),i.set("offensive_third",n.offensive_third_time)),n?.labeled_time?.entries?.length){i.clear();for(const a of n.labeled_time.entries){const r=a.labels.find(o=>o.key==="field_third")?.value;r&&i.set(r,(i.get(r)??0)+a.value)}}const s=["defensive_third","neutral_third","offensive_third"];return s.some(a=>(i.get(a)??0)>0)?s.filter(a=>i.has(a)).map(a=>h1(k4(a,t),L4(i.get(a),e))).join(""):""}function Yx(n,e){const t=n?.tracked_time,i=D4(n,t,e.labelPerspective);return` + ${i.length===0?h1("Tracked",P4(t,1,"s")):""} ${i} - `}function $a(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function Wa(n,e){return`
${n}${e}
`}function Tm(n){return` - ${Wa("Rushes",$a(n?.count))} - ${Wa("2v1",$a(n?.two_v_one_count))} - ${Wa("2v2",$a(n?.two_v_two_count))} - ${Wa("2v3",$a(n?.two_v_three_count))} - ${Wa("3v1",$a(n?.three_v_one_count))} - ${Wa("3v2",$a(n?.three_v_two_count))} - ${Wa("3v3",$a(n?.three_v_three_count))} - `}const Hx="subtr-actor-fifty-fifty-overlay-styles",t4=5882879,n4=16761180,i4=15988472,s4=180,a4=4;function U_(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function Vx(n,e){const t=U_(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function r4(n,e){const t=Vx(e,n.team_zero_player),i=Vx(e,n.team_one_player),s=n.is_kickoff?"Kickoff 50/50":"50/50",a=n.winning_team_is_team_0===void 0?null:n.winning_team_is_team_0,r=n.possession_team_is_team_0===void 0?null:n.possession_team_is_team_0,o=a===null?"neutral":a?"blue win":"orange win",l=r===null?"neutral poss":r?"blue poss":"orange poss",c=a===null?"sap-fifty-fifty-overlay-label-neutral":a?"sap-fifty-fifty-overlay-label-blue":"sap-fifty-fifty-overlay-label-orange";return{text:`${s}: ${t} vs ${i} | ${o} | ${l}`,className:c,winnerIsTeamZero:a}}function n1(n,e){return be(n,"fifty_fifty").map(t=>{const i=r4(t,e),s=new T(...t.team_zero_position),a=new T(...t.team_one_position),r=new T(...t.midpoint),o=e.frames[t.start_frame]?.time??t.start_time;return{id:`fifty-fifty:${t.start_frame}:${U_(t.team_zero_player)}:${U_(t.team_one_player)}`,time:o,frame:t.start_frame,label:i.text,labelClassName:i.className,axisStart:s,axisEnd:a,midpoint:r,winnerIsTeamZero:i.winnerIsTeamZero}})}function o4(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function l4(){if(document.getElementById(Hx))return;const n=document.createElement("style");n.id=Hx,n.textContent=` + `}function Wa(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function Xa(n,e){return`
${n}${e}
`}function Im(n){return` + ${Xa("Rushes",Wa(n?.count))} + ${Xa("2v1",Wa(n?.two_v_one_count))} + ${Xa("2v2",Wa(n?.two_v_two_count))} + ${Xa("2v3",Wa(n?.two_v_three_count))} + ${Xa("3v1",Wa(n?.three_v_one_count))} + ${Xa("3v2",Wa(n?.three_v_two_count))} + ${Xa("3v3",Wa(n?.three_v_three_count))} + `}const jx="subtr-actor-fifty-fifty-overlay-styles",O4=5882879,F4=16761180,N4=15988472,U4=180,B4=4;function W_(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function Zx(n,e){const t=W_(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function z4(n,e){const t=Zx(e,n.team_zero_player),i=Zx(e,n.team_one_player),s=n.is_kickoff?"Kickoff 50/50":"50/50",a=n.winning_team_is_team_0===void 0?null:n.winning_team_is_team_0,r=n.possession_team_is_team_0===void 0?null:n.possession_team_is_team_0,o=a===null?"neutral":a?"blue win":"orange win",l=r===null?"neutral poss":r?"blue poss":"orange poss",c=a===null?"sap-fifty-fifty-overlay-label-neutral":a?"sap-fifty-fifty-overlay-label-blue":"sap-fifty-fifty-overlay-label-orange";return{text:`${s}: ${t} vs ${i} | ${o} | ${l}`,className:c,winnerIsTeamZero:a}}function f1(n,e){return be(n,"fifty_fifty").map(t=>{const i=z4(t,e),s=new T(...t.team_zero_position),a=new T(...t.team_one_position),r=new T(...t.midpoint),o=e.frames[t.start_frame]?.time??t.start_time;return{id:`fifty-fifty:${t.start_frame}:${W_(t.team_zero_player)}:${W_(t.team_one_player)}`,time:o,frame:t.start_frame,label:i.text,labelClassName:i.className,axisStart:s,axisEnd:a,midpoint:r,winnerIsTeamZero:i.winnerIsTeamZero}})}function H4(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function V4(){if(document.getElementById(jx))return;const n=document.createElement("style");n.id=jx,n.textContent=` .sap-fifty-fifty-overlay-root { position: absolute; inset: 0; @@ -5584,7 +5649,7 @@ void main() { border-color: rgba(243, 246, 248, 0.4); background: rgba(34, 41, 47, 0.86); } - `,document.head.append(n)}function c4(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class u4{scene;container;group=new Et;labelRoot;projectedPosition=new T;worldPosition=new T;labelOffset=new T(0,0,s4);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=a4;constructor(e,t,i,s){l4(),this.scene=e,this.container=t,this.markers=n1(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="fifty-fifty-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-fifty-fifty-overlay-root",this.container.append(this.labelRoot)}update(e){const t=o4(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.line.removeFromParent(),a.line.geometry.dispose(),a.material.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.12+.78*r;o.material.opacity=l;const c=o.line.geometry.getAttribute("position");c.setXYZ(0,s.axisStart.x,s.axisStart.y,s.axisStart.z+24),c.setXYZ(1,s.axisEnd.x,s.axisEnd.y,s.axisEnd.z+24),c.needsUpdate=!0,this.worldPosition.copy(s.midpoint).add(this.labelOffset),this.scene.replayRoot.localToWorld(this.worldPosition),c4(this.worldPosition,this.scene.camera,this.container,this.projectedPosition)?(o.label.hidden=!1,o.label.style.opacity=`${.24+.76*r}`,o.label.style.transform=`translate(${this.projectedPosition.x.toFixed(1)}px, ${this.projectedPosition.y.toFixed(1)}px) translate(-50%, -100%)`):o.label.hidden=!0}}dispose(){for(const e of this.views.values())e.line.removeFromParent(),e.line.geometry.dispose(),e.material.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition,this.changedContainerPosition=!1)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=new $e().setFromPoints([e.axisStart,e.axisEnd]),s=new Pt({color:e.winnerIsTeamZero===null?i4:e.winnerIsTeamZero?t4:n4,transparent:!0,opacity:.9}),a=new On(i,s);a.renderOrder=3,this.group.add(a);const r=document.createElement("div");r.className=`sap-fifty-fifty-overlay-label ${e.labelClassName}`,r.textContent=e.label,this.labelRoot.append(r);const o={marker:e,line:a,material:s,label:r};return this.views.set(e.id,o),o}}const Gx="subtr-actor-ceiling-shot-overlay-styles",d4=5882879,h4=16761180,f4=16185075,p4=140,m4=215,_4=220,g4=4.5;function i1(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function y4(n,e){const t=i1(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function s1(n,e){return be(n,"ceiling_shot").map(t=>{const i=y4(e,t.player),s=i1(t.player),a=e.frames[t.frame]?.time??t.time,r=t.confidence;return{id:`ceiling-shot:${t.frame}:${s}:${Math.round(r*1e3)}`,time:a,frame:t.frame,isTeamZero:t.is_team_0,playerId:s,playerName:i,ceilingContactPosition:{x:t.ceiling_contact_position[0],y:t.ceiling_contact_position[1],z:t.ceiling_contact_position[2]},touchPosition:{x:t.touch_position[0],y:t.touch_position[1],z:t.touch_position[2]},quality:r,qualityLabel:`${Math.round(r*100)}%`}})}function v4(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function b4(){if(document.getElementById(Gx))return;const n=document.createElement("style");n.id=Gx,n.textContent=` + `,document.head.append(n)}function G4(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class $4{scene;container;group=new Et;labelRoot;projectedPosition=new T;worldPosition=new T;labelOffset=new T(0,0,U4);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=B4;constructor(e,t,i,s){V4(),this.scene=e,this.container=t,this.markers=f1(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="fifty-fifty-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-fifty-fifty-overlay-root",this.container.append(this.labelRoot)}update(e){const t=H4(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.line.removeFromParent(),a.line.geometry.dispose(),a.material.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.12+.78*r;o.material.opacity=l;const c=o.line.geometry.getAttribute("position");c.setXYZ(0,s.axisStart.x,s.axisStart.y,s.axisStart.z+24),c.setXYZ(1,s.axisEnd.x,s.axisEnd.y,s.axisEnd.z+24),c.needsUpdate=!0,this.worldPosition.copy(s.midpoint).add(this.labelOffset),this.scene.replayRoot.localToWorld(this.worldPosition),G4(this.worldPosition,this.scene.camera,this.container,this.projectedPosition)?(o.label.hidden=!1,o.label.style.opacity=`${.24+.76*r}`,o.label.style.transform=`translate(${this.projectedPosition.x.toFixed(1)}px, ${this.projectedPosition.y.toFixed(1)}px) translate(-50%, -100%)`):o.label.hidden=!0}}dispose(){for(const e of this.views.values())e.line.removeFromParent(),e.line.geometry.dispose(),e.material.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition,this.changedContainerPosition=!1)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=new $e().setFromPoints([e.axisStart,e.axisEnd]),s=new Pt({color:e.winnerIsTeamZero===null?N4:e.winnerIsTeamZero?O4:F4,transparent:!0,opacity:.9}),a=new On(i,s);a.renderOrder=3,this.group.add(a);const r=document.createElement("div");r.className=`sap-fifty-fifty-overlay-label ${e.labelClassName}`,r.textContent=e.label,this.labelRoot.append(r);const o={marker:e,line:a,material:s,label:r};return this.views.set(e.id,o),o}}const Jx="subtr-actor-ceiling-shot-overlay-styles",W4=5882879,X4=16761180,K4=16185075,q4=140,Y4=215,j4=220,Z4=4.5;function p1(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function J4(n,e){const t=p1(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function m1(n,e){return be(n,"ceiling_shot").map(t=>{const i=J4(e,t.player),s=p1(t.player),a=e.frames[t.frame]?.time??t.time,r=t.confidence;return{id:`ceiling-shot:${t.frame}:${s}:${Math.round(r*1e3)}`,time:a,frame:t.frame,isTeamZero:t.is_team_0,playerId:s,playerName:i,ceilingContactPosition:{x:t.ceiling_contact_position[0],y:t.ceiling_contact_position[1],z:t.ceiling_contact_position[2]},touchPosition:{x:t.touch_position[0],y:t.touch_position[1],z:t.touch_position[2]},quality:r,qualityLabel:`${Math.round(r*100)}%`}})}function Q4(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function eG(){if(document.getElementById(Jx))return;const n=document.createElement("style");n.id=Jx,n.textContent=` .sap-ceiling-shot-overlay-root { position: absolute; inset: 0; @@ -5621,13 +5686,13 @@ void main() { border-color: rgba(255, 193, 92, 0.5); background: rgba(76, 41, 7, 0.84); } - `,document.head.append(n)}function x4(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class w4{scene;container;group=new Et;labelRoot;projectedPosition=new T;worldPosition=new T;labelOffset=new T(0,0,_4);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=g4;constructor(e,t,i,s){b4(),this.scene=e,this.container=t,this.markers=s1(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="ceiling-shot-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-ceiling-shot-overlay-root",this.container.append(this.labelRoot)}update(e){const t=v4(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.ring.removeFromParent(),a.ring.geometry.dispose(),a.ringMaterial.dispose(),a.beam.removeFromParent(),a.beamGeometry.dispose(),a.beamMaterial.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.14+.6*r,c=.94+(1-r)*.18;o.ringMaterial.opacity=l,o.beamMaterial.opacity=.18+.55*r,o.ring.position.set(s.touchPosition.x,s.touchPosition.y,s.touchPosition.z+12),o.ring.scale.setScalar(c+s.quality*.08),this.worldPosition.set(s.touchPosition.x,s.touchPosition.y,s.touchPosition.z).add(this.labelOffset);const u=x4(this.worldPosition,this.scene.camera,this.container,this.projectedPosition);o.label.style.display=u?"block":"none",u&&(o.label.style.left=`${this.projectedPosition.x}px`,o.label.style.top=`${this.projectedPosition.y}px`,o.label.style.opacity=`${.42+.58*r}`)}}dispose(){for(const e of this.views.values())e.ring.removeFromParent(),e.ring.geometry.dispose(),e.ringMaterial.dispose(),e.beam.removeFromParent(),e.beamGeometry.dispose(),e.beamMaterial.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=e.quality>=.8?f4:e.isTeamZero?d4:h4,s=new je({color:i,transparent:!0,opacity:.8,side:ut,depthWrite:!1,depthTest:!1}),a=new oi(p4,m4,48),r=new Se(a,s);r.renderOrder=30,this.group.add(r);const o=new $e().setFromPoints([new T(e.ceilingContactPosition.x,e.ceilingContactPosition.y,e.ceilingContactPosition.z),new T(e.touchPosition.x,e.touchPosition.y,e.touchPosition.z)]),l=new Pt({color:i,transparent:!0,opacity:.7,depthWrite:!1,depthTest:!1}),c=new On(o,l);c.renderOrder=29,this.group.add(c);const u=document.createElement("div");u.className=`sap-ceiling-shot-overlay-label ${e.isTeamZero?"sap-ceiling-shot-overlay-label-blue":"sap-ceiling-shot-overlay-label-orange"}`,u.textContent=`${e.playerName} ceiling shot ${e.qualityLabel}`,this.labelRoot.append(u);const d={marker:e,ring:r,ringMaterial:s,beam:c,beamGeometry:o,beamMaterial:l,label:u};return this.views.set(e.id,d),d}}const S4="#d1d9e0",a1=new Set(["flick_goal","double_tap_goal","one_timer_goal","passing_goal","air_dribble_goal","flip_reset_goal","bump_goal","demo_goal","half_volley_goal"]);function my(n){return n.metadata.performer==="scorer"||n.metadata.modifiers?.includes("by_scorer")?"scorer":n.metadata.performer==="teammate"?"teammate":a1.has(n.kind)?"unknown":"scorer"}function T4(n){return my(n)==="scorer"}function M4(n){return my(n)==="teammate"}function r1(n){const e=my(n);return e==="unknown"?"performer unknown":a1.has(n.kind)?`by ${e}`:null}function is(n,e){return n.players.find(t=>t.id===e)?.name??e}function Un(n,e,t){return n.frames[e??-1]?.time??t}function E4(n){const e=n.kind;return e!=="forward"&&e!=="reverse"&&e!=="side"?"flick":`${n.direction==="left"||n.direction==="right"?`${n.direction} `:""}${e} flick`}function C4(n){const e=new Set(n),t=new Set(["goal"]);return e.has("core")&&(t.add("save"),t.add("shot"),t.add("assist")),e.has("demo")&&t.add("demo"),[...t]}function A4(n,e){const t=new Set(C4(e));return n.timelineEvents.filter(i=>t.has(i.kind))}function R4(n,e){return n1(n,e).map(t=>({id:t.id,time:t.time,frame:t.frame,kind:"fifty-fifty",label:t.label,shortLabel:t.label.startsWith("Kickoff 50/50")?"KO":"50",isTeamZero:t.winnerIsTeamZero,color:t.winnerIsTeamZero===null?S4:t.winnerIsTeamZero?tn:nn}))}function P4(n,e){return(be(n,"flick")??[]).map((t,i)=>{const s=Ct(t.player),a=is(e,s),r=E4(t);return{id:`flick:${t.frame}:${s}:${i+1}`,time:Un(e,t.frame,t.time),frame:t.frame,kind:"flick",label:`${a} ${r}`,shortLabel:"F",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function I4(n,e){return jE(n,e).map(t=>({id:t.id,time:t.time,frame:t.frame,kind:"touch",label:`${t.playerName} touch`,shortLabel:"T",playerId:t.playerId,playerName:t.playerName,isTeamZero:t.isTeamZero,color:t.isTeamZero?tn:nn}))}function L4(n,e){return be(n,"backboard").map((t,i)=>{const s=Ct(t.player),a=e.players.find(r=>r.id===s)?.name??s;return{id:`backboard:${t.frame}:${s}:${i}`,time:Un(e,t.frame,t.time),frame:t.frame,kind:"backboard",label:`${a} backboard`,shortLabel:"BB",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function k4(n,e){return s1(n,e).map(t=>({id:t.id,time:t.time,frame:t.frame,kind:"ceiling-shot",label:`${t.playerName} ceiling shot ${t.qualityLabel}`,shortLabel:"CS",playerId:t.playerId,playerName:t.playerName,isTeamZero:t.isTeamZero,color:t.isTeamZero?tn:nn}))}function D4(n,e){return be(n,"wall_aerial").map((t,i)=>{const s=Ct(t.player),a=is(e,s),r=Un(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Dn(t.wall).toLowerCase();return{id:`wall-aerial:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"wall-aerial",label:`${a} wall-to-air setup ${o}% | ${l} wall`,shortLabel:"W2A",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function O4(n,e){return be(n,"wall_aerial_shot").map((t,i)=>{const s=Ct(t.player),a=is(e,s),r=Un(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Dn(t.wall).toLowerCase();return{id:`wall-aerial-shot:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"wall-aerial-shot",label:`${a} wall shot ${o}% | ${l} wall`,shortLabel:"WS",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function F4(n,e){return be(n,"double_tap").map((t,i)=>{const s=Ct(t.player),a=is(e,s);return{id:`double-tap:${t.frame}:${s}:${i}`,time:Un(e,t.frame,t.time),frame:t.frame,kind:"double-tap",label:`${a} double tap`,shortLabel:"DT",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function N4(n,e){return be(n,"center").map((t,i)=>{const s=Ct(t.player),a=is(e,s),r=Un(e,t.frame,t.time),o=Math.round(t.lateral_centering_distance);return{id:`center:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"center",label:`${a} center | ${o}uu lateral`,shortLabel:"C",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function U4(n,e){return be(n,"one_timer").map((t,i)=>{const s=Ct(t.player),a=Ct(t.passer),r=is(e,s),o=is(e,a),l=Un(e,t.frame,t.time),c=Math.round(t.ball_speed);return{id:`one-timer:${t.frame}:${a}:${s}:${i}`,time:l,frame:t.frame,kind:"one-timer",label:`${r} one-timer from ${o} | ${c}uu/s`,shortLabel:"OT",playerId:s,playerName:r,secondaryPlayerId:a,secondaryPlayerName:o,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function B4(n){return Dn(n.replace(/_pass$/,""))}function z4(n,e){return be(n,"pass").map((t,i)=>{const s=Ct(t.passer),a=Ct(t.receiver),r=is(e,s),o=is(e,a),l=Un(e,t.frame,t.time),c=Math.round(t.ball_travel_distance),u=B4(t.pass_kind);return{id:`pass:${t.frame}:${s}:${a}:${i}`,time:l,frame:t.frame,kind:"pass",label:`${r} to ${o} ${u.toLowerCase()} pass | ${c}uu`,shortLabel:"P",playerId:s,playerName:r,secondaryPlayerId:a,secondaryPlayerName:o,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function H4(n,e){return be(n,"half_volley").map((t,i)=>{const s=Ct(t.player),a=is(e,s),r=Un(e,t.frame,t.time),o=Math.round(t.ball_speed);return{id:`half-volley:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"half-volley",label:`${a} half volley | ${o}uu/s`,shortLabel:"HV",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function V4(n,e){return be(n,"rush").map((t,i)=>{const s=Un(e,t.end_frame,t.end_time),a=`${t.attackers}v${t.defenders}`,r=t.is_team_0?"Blue":"Orange";return{id:`rush:${t.start_frame}:${t.end_frame}:${i}`,time:s,frame:t.end_frame,kind:"rush",label:`${r} rush ${a}`,shortLabel:"R",playerId:null,playerName:null,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function G4(n,e){return(be(n,"powerslide")??[]).filter(t=>t.active).map((t,i)=>{const s=Ct(t.player),a=is(e,s);return{id:`powerslide:${t.frame}:${s}:${i+1}`,time:Un(e,t.frame,t.time),frame:t.frame,kind:"powerslide",label:`${a} powerslide`,shortLabel:"PS",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function $4(n,e){return be(n,"speed_flip").map(t=>{const i=t.player?Ct(t.player):null,s=i?e.players.find(o=>o.id===i)?.name??i:"Unknown",a=e.frames[t.frame]?.time??t.time,r=Math.round(t.confidence*100);return{id:`speed-flip:${t.frame}:${i}:${Math.round(t.confidence*1e3)}`,time:a,frame:t.frame,kind:"speed-flip",label:`${s} speed flip ${r}%`,shortLabel:"SF",playerId:i,playerName:s,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function W4(n,e){return(be(n,"dodge")??[]).map((t,i)=>{const s=Ct(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=Un(e,t.frame,t.time),o=Math.round((t.dodge_impulse?.confidence??1)*100),l=(t.dodge_impulse?.direction_label??"dodge").replaceAll("_"," ");return{id:`dodge:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"dodge",label:`${a} flip impulse ${l} ${o}%`,shortLabel:"FI",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function X4(n,e){return be(n,"half_flip").map((t,i)=>{const s=Ct(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=Un(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Math.round(t.end_speed-t.start_speed);return{id:`half-flip:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"half-flip",label:`${a} half flip ${o}% | +${l}uu/s`,shortLabel:"HF",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function K4(n,e){return be(n,"wavedash").map((t,i)=>{const s=Ct(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=Un(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Math.round(t.horizontal_speed_gain);return{id:`wavedash:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"wavedash",label:`${a} wavedash ${o}% | +${l}uu/s`,shortLabel:"WD",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function q4(n,e){return be(n,"bump").map((t,i)=>{const s=Ct(t.initiator),a=Ct(t.victim),r=e.players.find(u=>u.id===s)?.name??s,o=e.players.find(u=>u.id===a)?.name??a,l=Un(e,t.frame,t.time),c=Math.round(t.confidence*100);return{id:`bump:${t.frame}:${s}:${a}:${i}`,time:l,frame:t.frame,kind:"bump",label:`${r} bumped ${o} ${c}%`,shortLabel:"B",playerId:s,playerName:r,isTeamZero:t.initiator_is_team_0,color:t.initiator_is_team_0?tn:nn}})}function Y4(n){return n.kind==="beaten_to_ball"?"BT":n.dodge_active?"DW":n.aerial?"AW":"W"}function j4(n){const e=[n.aerial?"aerial":"grounded"];return n.dodge_active&&e.push("dodge"),e.join(" ")}function Z4(n){return n.kind==="beaten_to_ball"?"beaten to ball":"whiff"}function J4(n,e){return be(n,"whiff").map((t,i)=>{const s=Ct(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=Un(e,t.frame,t.time),o=Math.round(t.closest_approach_distance),l=Math.round(t.approach_speed);return{id:`whiff:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"whiff",label:`${a} ${j4(t)} ${Z4(t)} | ${o}uu closest, ${l}uu/s`,shortLabel:Y4(t),playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}const o1={flick:P4,ceiling_shot:k4,wall_aerial:D4,wall_aerial_shot:O4,double_tap:F4,center:N4,one_timer:U4,pass:z4,half_flip:X4,half_volley:H4,speed_flip:$4},l1=Object.keys(o1),c1=.02,si=1e-4,Q4=200,u1=.08,B_={big:"rgba(245, 158, 11, 0.92)",small:"rgba(52, 211, 153, 0.86)"},$x={both:"rgba(52, 211, 153, 0.86)",inferred_only:"rgba(239, 68, 68, 0.9)",reported_only:"rgba(59, 130, 246, 0.9)"};function eG(n){const e=n.config?.ball_half_neutral_zone_half_width_y;return typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):Q4}function Th(n,e,t){return n?.frames?.[e??-1]?.time??t}function tG(n,e,t,i,s,a){const r=e?.ballFrames[n]?.position?.y;return typeof r=="number"&&Number.isFinite(r)&&Math.abs(r)<=t+si||a>si?"neutral":i>s+si?"team_zero_side":s>i+si?"team_one_side":null}function d1(n,e,t){if(n==="neutral")return{id:`half-control:neutral:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"half-control",laneLabel:"Half Control",label:"Neutral half control",color:"rgba(209, 217, 224, 0.7)",isTeamZero:null};const i=n==="team_zero_side";return{id:`half-control:${n}:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"half-control",laneLabel:"Half Control",label:i?"Blue half control":"Orange half control",color:Ef(i)??void 0,isTeamZero:i}}function Af(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function nG(n,e){const t=Af(be(n,"possession")),i=[];let s=0,a=!1,r="neutral",o=null;for(const l of n.frames){for(;s0)return nG(n,e);const t=[];let i=0,s=0,a=0,r=null;for(const o of n.frames){if(!Number.isFinite(o.time)||!Number.isFinite(o.dt)||o.dt<=0){r=o;continue}const l=o,c=l.team_zero?.possession?.possession_time??0,u=l.team_one?.possession?.possession_time??0,d=l.team_zero?.possession?.neutral_time??0,h=c-i,f=u-s,p=d-a;i=c,s=u,a=d;let g=null;const{startTime:_,endTime:m}=Er(o,r,e);h>f+si&&h>p+si?g={id:`possession:team_zero:${_.toFixed(3)}`,startTime:_,endTime:m,lane:"possession",laneLabel:"Possession",label:"Blue possession",color:"rgba(59, 130, 246, 0.88)",isTeamZero:!0}:f>h+si&&f>p+si&&(g={id:`possession:team_one:${_.toFixed(3)}`,startTime:_,endTime:m,lane:"possession",laneLabel:"Possession",label:"Orange possession",color:"rgba(245, 158, 11, 0.88)",isTeamZero:!1}),Zo(t,g),r=o}return t}function sG(n,e){const t=Af(be(n,"ball_half")),i=[];let s=0,a=!1,r="neutral",o=null;for(const l of n.frames){for(;s0)return sG(n,e);const t=[];let i=0,s=0,a=0;const r=eG(n);let o=null;for(const l of n.frames){if(!Number.isFinite(l.time)||!Number.isFinite(l.dt)||l.dt<=0){o=l;continue}const c=l,u=c.team_zero?.ball_half?.defensive_half_time??0,d=c.team_one?.ball_half?.defensive_half_time??0,h=c.team_zero?.ball_half?.neutral_time??0,f=u-i,p=d-s,g=h-a;i=u,s=d,a=h;const{startTime:_,endTime:m}=Er(l,o,e),v=tG(l.frame_number,e,r,f,p,g),y=v?d1(v,_,m):null;Zo(t,y),o=l}return t}function rG(n,e,t){return t>si?"neutral_third":n>e+si?"team_zero_third":e>n+si?"team_one_third":null}function h1(n,e,t){if(n==="neutral_third")return{id:`third-control:neutral_third:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"third-control",laneLabel:"Third Control",label:"Neutral third control",color:"rgba(209, 217, 224, 0.7)",isTeamZero:null};const i=n==="team_zero_third";return{id:`third-control:${n}:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"third-control",laneLabel:"Third Control",label:i?"Blue third control":"Orange third control",color:Ef(i)??void 0,isTeamZero:i}}function oG(n,e){const t=Af(be(n,"ball_third")),i=[];let s=0,a=!1,r="neutral_third",o=null;for(const l of n.frames){for(;s0)return oG(n,e);const t=[];let i=0,s=0,a=0,r=null;for(const o of n.frames){if(!Number.isFinite(o.time)||!Number.isFinite(o.dt)||o.dt<=0){r=o;continue}const l=o,c=l.team_zero?.ball_third?.defensive_third_time??0,u=l.team_one?.ball_third?.defensive_third_time??0,d=l.team_zero?.ball_third?.neutral_third_time??0,h=c-i,f=u-s,p=d-a;i=c,s=u,a=d;const{startTime:g,endTime:_}=Er(o,r,e),m=rG(h,f,p),v=m?h1(m,g,_):null;Zo(t,v),r=o}return t}function cG(n,e){return be(n,"fifty_fifty").map((t,i)=>{const s=Th(e,t.start_frame,t.start_time),a=Math.max(s,Th(e,t.resolve_frame,t.resolve_time)),r=t.winning_team_is_team_0==null?"Neutral":t.winning_team_is_team_0?"Blue win":"Orange win",o=t.is_kickoff?"kickoff ":"";return{id:`fifty-fifty:${t.start_frame}:${t.resolve_frame}:${i}`,startTime:s,endTime:a,lane:"fifty-fifty",laneLabel:"50/50",label:`${r} ${o}50/50`,shortLabel:t.is_kickoff?"KO":"50",color:t.winning_team_is_team_0==null?"rgba(209, 217, 224, 0.7)":t.winning_team_is_team_0?"rgba(59, 130, 246, 0.48)":"rgba(245, 158, 11, 0.48)",isTeamZero:t.winning_team_is_team_0}}).sort((t,i)=>t.startTime!==i.startTime?t.startTime-i.startTime:(t.id??"").localeCompare(i.id??""))}function uG(n,e){return be(n,"rush").map((t,i)=>{const s=e?.frames[t.start_frame]?.time??t.start_time,a=e?.frames[t.end_frame]?.time??t.end_time,r=`${t.attackers}v${t.defenders}`,o=t.is_team_0;return{id:`rush-range:${t.start_frame}:${t.end_frame}:${i}`,startTime:s,endTime:Math.max(s,a),lane:"rush",laneLabel:"Rush",label:`${o?"Blue":"Orange"} rush ${r}`,color:o?"rgba(59, 130, 246, 0.4)":"rgba(245, 158, 11, 0.4)",isTeamZero:o}})}function dG(n,e={}){const t=f1(e),i=new Set(e.detections??["both","inferred_only","reported_only"]),s=new Set(e.activities??["active","inactive","unknown"]),a=new Set(e.fieldHalves??["own","opponent","unknown"]),r=e.playerIds?new Set(e.playerIds):null;if(t.size===0||i.size===0||!s.has("unknown")||!a.has("unknown")||r?.size===0)return[];const o=new Map(n.players.map(c=>[c.id,c.isTeamZero])),l=[];for(const c of n.boostPads)if(t.has(c.size))for(let u=0;uc.startTime!==u.startTime?c.startTime-u.startTime:(c.id??"").localeCompare(u.id??""))}function f1(n){if(n.padTypes)return new Set(n.padTypes);if(n.sizes){const e=new Set(n.sizes),t=new Set;return e.has("big")&&t.add("big"),e.has("small")&&t.add("small"),e.has("big")&&e.has("small")&&t.add("ambiguous"),t}return new Set(["big","small","ambiguous"])}function Wx(n){const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function hG(n){return{big:"big",small:"small",ambiguous:"ambiguous"}[n]}function fG(n){return{both:"counted",inferred_only:"inferred",reported_only:"reported"}[n]}function pG(n,e){return n==="inferred_only"?"I":n==="reported_only"?"R":{big:"100",small:"12",ambiguous:"?"}[e]}function mG(n,e,t={}){const i=be(n,"boost_pickup");if(i.length===0&&e)return dG(e,t);const s=f1(t),a=new Set(t.detections??["both","inferred_only","reported_only"]),r=new Set(t.activities??["active","inactive","unknown"]),o=new Set(t.fieldHalves??["own","opponent","unknown"]),l=t.playerIds?new Set(t.playerIds):null;if(s.size===0||a.size===0||r.size===0||o.size===0||l?.size===0)return[];const c=new Map((e?.players??[]).map(u=>[u.id,u.name]));return i.filter(u=>{const d=Wx(u.player_id);return s.has(u.pad_type)&&a.has(u.detection)&&r.has(u.activity)&&o.has(u.field_half)&&(!l||l.has(d))}).map((u,d)=>{const h=Wx(u.player_id),f=c.get(h)??h,p=Math.max(0,Th(e,u.frame,u.time)),g=fG(u.detection),_=hG(u.pad_type);return{id:`boost-pickup:${u.detection}:${u.frame}:${h}:${d}`,startTime:p,endTime:Math.max(p+u1,p),lane:"boost-pickups",laneLabel:"Boost Pickups",label:`${f} ${g} ${_} boost pickup`,shortLabel:pG(u.detection,u.pad_type),color:Ef(u.is_team_0)??(u.detection==="both"?u.pad_type==="big"?B_.big:u.pad_type==="small"?B_.small:$x.both:$x[u.detection]),isTeamZero:u.is_team_0}}).sort((u,d)=>u.startTime!==d.startTime?u.startTime-d.startTime:(u.id??"").localeCompare(d.id??""))}const Sd=[{fieldName:"time_defensive_third",aliases:["time_defensive_zone"],label:"Def third",relativeColor:"own"},{fieldName:"time_neutral_third",aliases:["time_neutral_zone"],label:"Neutral third",relativeColor:"neutral"},{fieldName:"time_offensive_third",aliases:["time_offensive_zone"],label:"Off third",relativeColor:"opp"}];function p1(n,e){return n.relativeColor==="neutral"?"rgba(209, 217, 224, 0.68)":(n.relativeColor==="own"?e:!e)?"rgba(89, 195, 255, 0.74)":"rgba(255, 193, 92, 0.78)"}function _y(n){const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function _G(n,e){const t=n.positioning;if(!t)return 0;for(const i of[e.fieldName,...e.aliases??[]]){const s=t[i];if(typeof s=="number"&&Number.isFinite(s))return s}return 0}function gG(n){switch(n){case"defensive":return Sd[0];case"neutral":return Sd[1];case"offensive":return Sd[2]}}function yG(n){const e=new Map;for(const t of n.frames)for(const i of t.players){const s=_y(i.player_id);e.has(s)||e.set(s,i.name)}return e}function vG(n){const e=Af(be(n,"field_third")),t=[],i=new Map,s=yG(n);for(const a of e){if(!Number.isFinite(a.time)||!Number.isFinite(a.end_time)||a.end_time-a.time<=si)continue;const r=_y(a.player),o=gG(a.state);m1(t,i,{id:`time-in-zone:${r}:${o.fieldName}:${a.time.toFixed(3)}`,startTime:a.time,endTime:a.end_time,lane:`time-in-zone:${r}`,laneLabel:s.get(r)??r,label:o.label,color:p1(o,a.is_team_0),isTeamZero:a.is_team_0})}return t}function bG(n,e){if(be(n,"field_third").length>0)return vG(n);const t=new Map,i=[],s=new Map;let a=null;for(const r of n.frames){if(!Number.isFinite(r.time)||!Number.isFinite(r.dt)||r.dt<=0){a=r;continue}const{startTime:o,endTime:l}=Er(r,a,e);if(l-o<=si){a=r;continue}for(const c of r.players){const u=_y(c.player_id),d=t.get(u)??new Map;let h=null,f=0;for(const p of Sd){const g=_G(c,p),_=g-(d.get(p.fieldName)??0);_>f+si&&(f=_,h=p),d.set(p.fieldName,g)}t.set(u,d),h&&m1(i,s,{id:`time-in-zone:${u}:${h.fieldName}:${o.toFixed(3)}`,startTime:o,endTime:l,lane:`time-in-zone:${u}`,laneLabel:c.name,label:h.label,color:p1(h,c.is_team_0),isTeamZero:c.is_team_0})}a=r}return i}function Er(n,e,t){const i=t?.frames[n.frame_number]?.time??n.time,s=e?t?.frames[e.frame_number]?.time??e.time:Math.max(0,i-n.dt);return{startTime:Math.max(0,s),endTime:Math.max(s,i)}}function Zo(n,e){if(!e)return;const t=n[n.length-1];if(t&&t.lane===e.lane&&t.label===e.label&&Math.abs(t.endTime-e.startTime)<=c1){t.endTime=e.endTime;return}n.push(e)}function m1(n,e,t){if(!t)return;const i=t.lane??"",s=e.get(i);if(s&&s.label===t.label&&Math.abs(s.endTime-t.startTime)<=c1){s.endTime=t.endTime;return}n.push(t),e.set(i,t)}const Mm=236,_1="relative-positioning",xG={last:"Last",upfield:"Upfield",level:"Level",mid:"Mid"};function ca(n){return n?"team-blue":"team-orange"}function g1(n,e,t){return`
+ `,document.head.append(n)}function tG(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class nG{scene;container;group=new Et;labelRoot;projectedPosition=new T;worldPosition=new T;labelOffset=new T(0,0,j4);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=Z4;constructor(e,t,i,s){eG(),this.scene=e,this.container=t,this.markers=m1(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="ceiling-shot-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-ceiling-shot-overlay-root",this.container.append(this.labelRoot)}update(e){const t=Q4(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.ring.removeFromParent(),a.ring.geometry.dispose(),a.ringMaterial.dispose(),a.beam.removeFromParent(),a.beamGeometry.dispose(),a.beamMaterial.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.14+.6*r,c=.94+(1-r)*.18;o.ringMaterial.opacity=l,o.beamMaterial.opacity=.18+.55*r,o.ring.position.set(s.touchPosition.x,s.touchPosition.y,s.touchPosition.z+12),o.ring.scale.setScalar(c+s.quality*.08),this.worldPosition.set(s.touchPosition.x,s.touchPosition.y,s.touchPosition.z).add(this.labelOffset);const u=tG(this.worldPosition,this.scene.camera,this.container,this.projectedPosition);o.label.style.display=u?"block":"none",u&&(o.label.style.left=`${this.projectedPosition.x}px`,o.label.style.top=`${this.projectedPosition.y}px`,o.label.style.opacity=`${.42+.58*r}`)}}dispose(){for(const e of this.views.values())e.ring.removeFromParent(),e.ring.geometry.dispose(),e.ringMaterial.dispose(),e.beam.removeFromParent(),e.beamGeometry.dispose(),e.beamMaterial.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=e.quality>=.8?K4:e.isTeamZero?W4:X4,s=new je({color:i,transparent:!0,opacity:.8,side:ut,depthWrite:!1,depthTest:!1}),a=new oi(q4,Y4,48),r=new Se(a,s);r.renderOrder=30,this.group.add(r);const o=new $e().setFromPoints([new T(e.ceilingContactPosition.x,e.ceilingContactPosition.y,e.ceilingContactPosition.z),new T(e.touchPosition.x,e.touchPosition.y,e.touchPosition.z)]),l=new Pt({color:i,transparent:!0,opacity:.7,depthWrite:!1,depthTest:!1}),c=new On(o,l);c.renderOrder=29,this.group.add(c);const u=document.createElement("div");u.className=`sap-ceiling-shot-overlay-label ${e.isTeamZero?"sap-ceiling-shot-overlay-label-blue":"sap-ceiling-shot-overlay-label-orange"}`,u.textContent=`${e.playerName} ceiling shot ${e.qualityLabel}`,this.labelRoot.append(u);const d={marker:e,ring:r,ringMaterial:s,beam:c,beamGeometry:o,beamMaterial:l,label:u};return this.views.set(e.id,d),d}}const iG="#d1d9e0",_1=new Set(["flick_goal","double_tap_goal","one_timer_goal","passing_goal","air_dribble_goal","flip_reset_goal","bump_goal","demo_goal","half_volley_goal"]);function wy(n){return n.metadata.performer==="scorer"||n.metadata.modifiers?.includes("by_scorer")?"scorer":n.metadata.performer==="teammate"?"teammate":_1.has(n.kind)?"unknown":"scorer"}function sG(n){return wy(n)==="scorer"}function aG(n){return wy(n)==="teammate"}function g1(n){const e=wy(n);return e==="unknown"?"performer unknown":_1.has(n.kind)?`by ${e}`:null}function ss(n,e){return n.players.find(t=>t.id===e)?.name??e}function Un(n,e,t){return n.frames[e??-1]?.time??t}function rG(n){const e=n.kind;return e!=="forward"&&e!=="reverse"&&e!=="side"?"flick":`${n.direction==="left"||n.direction==="right"?`${n.direction} `:""}${e} flick`}function oG(n){const e=new Set(n),t=new Set(["goal"]);return e.has("core")&&(t.add("save"),t.add("shot"),t.add("assist")),e.has("demo")&&t.add("demo"),[...t]}function lG(n,e){const t=new Set(oG(e));return n.timelineEvents.filter(i=>t.has(i.kind))}function cG(n,e){return f1(n,e).map(t=>({id:t.id,time:t.time,frame:t.frame,kind:"fifty-fifty",label:t.label,shortLabel:t.label.startsWith("Kickoff 50/50")?"KO":"50",isTeamZero:t.winnerIsTeamZero,color:t.winnerIsTeamZero===null?iG:t.winnerIsTeamZero?tn:nn}))}function uG(n,e){return(be(n,"flick")??[]).map((t,i)=>{const s=Ct(t.player),a=ss(e,s),r=rG(t);return{id:`flick:${t.frame}:${s}:${i+1}`,time:Un(e,t.frame,t.time),frame:t.frame,kind:"flick",label:`${a} ${r}`,shortLabel:"F",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function dG(n,e){return o1(n,e).map(t=>({id:t.id,time:t.time,frame:t.frame,kind:"touch",label:`${t.playerName} touch`,shortLabel:"T",playerId:t.playerId,playerName:t.playerName,isTeamZero:t.isTeamZero,color:t.isTeamZero?tn:nn}))}function hG(n,e){return be(n,"backboard").map((t,i)=>{const s=Ct(t.player),a=e.players.find(r=>r.id===s)?.name??s;return{id:`backboard:${t.frame}:${s}:${i}`,time:Un(e,t.frame,t.time),frame:t.frame,kind:"backboard",label:`${a} backboard`,shortLabel:"BB",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function fG(n,e){return m1(n,e).map(t=>({id:t.id,time:t.time,frame:t.frame,kind:"ceiling-shot",label:`${t.playerName} ceiling shot ${t.qualityLabel}`,shortLabel:"CS",playerId:t.playerId,playerName:t.playerName,isTeamZero:t.isTeamZero,color:t.isTeamZero?tn:nn}))}function pG(n,e){return be(n,"wall_aerial").map((t,i)=>{const s=Ct(t.player),a=ss(e,s),r=Un(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Dn(t.wall).toLowerCase();return{id:`wall-aerial:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"wall-aerial",label:`${a} wall-to-air setup ${o}% | ${l} wall`,shortLabel:"W2A",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function mG(n,e){return be(n,"wall_aerial_shot").map((t,i)=>{const s=Ct(t.player),a=ss(e,s),r=Un(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Dn(t.wall).toLowerCase();return{id:`wall-aerial-shot:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"wall-aerial-shot",label:`${a} wall shot ${o}% | ${l} wall`,shortLabel:"WS",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function _G(n,e){return be(n,"double_tap").map((t,i)=>{const s=Ct(t.player),a=ss(e,s);return{id:`double-tap:${t.frame}:${s}:${i}`,time:Un(e,t.frame,t.time),frame:t.frame,kind:"double-tap",label:`${a} double tap`,shortLabel:"DT",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function gG(n,e){return be(n,"center").map((t,i)=>{const s=Ct(t.player),a=ss(e,s),r=Un(e,t.frame,t.time),o=Math.round(t.lateral_centering_distance);return{id:`center:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"center",label:`${a} center | ${o}uu lateral`,shortLabel:"C",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function yG(n,e){return be(n,"one_timer").map((t,i)=>{const s=Ct(t.player),a=Ct(t.passer),r=ss(e,s),o=ss(e,a),l=Un(e,t.frame,t.time),c=Math.round(t.ball_speed);return{id:`one-timer:${t.frame}:${a}:${s}:${i}`,time:l,frame:t.frame,kind:"one-timer",label:`${r} one-timer from ${o} | ${c}uu/s`,shortLabel:"OT",playerId:s,playerName:r,secondaryPlayerId:a,secondaryPlayerName:o,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function vG(n){return Dn(n.replace(/_pass$/,""))}function bG(n,e){return be(n,"pass").map((t,i)=>{const s=Ct(t.passer),a=Ct(t.receiver),r=ss(e,s),o=ss(e,a),l=Un(e,t.frame,t.time),c=Math.round(t.ball_travel_distance),u=vG(t.pass_kind);return{id:`pass:${t.frame}:${s}:${a}:${i}`,time:l,frame:t.frame,kind:"pass",label:`${r} to ${o} ${u.toLowerCase()} pass | ${c}uu`,shortLabel:"P",playerId:s,playerName:r,secondaryPlayerId:a,secondaryPlayerName:o,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function xG(n,e){return be(n,"half_volley").map((t,i)=>{const s=Ct(t.player),a=ss(e,s),r=Un(e,t.frame,t.time),o=Math.round(t.ball_speed);return{id:`half-volley:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"half-volley",label:`${a} half volley | ${o}uu/s`,shortLabel:"HV",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function wG(n,e){return be(n,"rush").map((t,i)=>{const s=Un(e,t.end_frame,t.end_time),a=`${t.attackers}v${t.defenders}`,r=t.is_team_0?"Blue":"Orange";return{id:`rush:${t.start_frame}:${t.end_frame}:${i}`,time:s,frame:t.end_frame,kind:"rush",label:`${r} rush ${a}`,shortLabel:"R",playerId:null,playerName:null,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function SG(n,e){return(be(n,"powerslide")??[]).filter(t=>t.active).map((t,i)=>{const s=Ct(t.player),a=ss(e,s);return{id:`powerslide:${t.frame}:${s}:${i+1}`,time:Un(e,t.frame,t.time),frame:t.frame,kind:"powerslide",label:`${a} powerslide`,shortLabel:"PS",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function TG(n,e){return be(n,"speed_flip").map(t=>{const i=t.player?Ct(t.player):null,s=i?e.players.find(o=>o.id===i)?.name??i:"Unknown",a=e.frames[t.frame]?.time??t.time,r=Math.round(t.confidence*100);return{id:`speed-flip:${t.frame}:${i}:${Math.round(t.confidence*1e3)}`,time:a,frame:t.frame,kind:"speed-flip",label:`${s} speed flip ${r}%`,shortLabel:"SF",playerId:i,playerName:s,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function MG(n,e){return(be(n,"dodge")??[]).map((t,i)=>{const s=Ct(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=Un(e,t.frame,t.time),o=Math.round((t.dodge_impulse?.confidence??1)*100),l=(t.dodge_impulse?.direction_label??"dodge").replaceAll("_"," ");return{id:`dodge:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"dodge",label:`${a} flip impulse ${l} ${o}%`,shortLabel:"FI",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function EG(n,e){return be(n,"half_flip").map((t,i)=>{const s=Ct(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=Un(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Math.round(t.end_speed-t.start_speed);return{id:`half-flip:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"half-flip",label:`${a} half flip ${o}% | +${l}uu/s`,shortLabel:"HF",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function CG(n,e){return be(n,"wavedash").map((t,i)=>{const s=Ct(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=Un(e,t.frame,t.time),o=Math.round(t.confidence*100),l=Math.round(t.horizontal_speed_gain);return{id:`wavedash:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"wavedash",label:`${a} wavedash ${o}% | +${l}uu/s`,shortLabel:"WD",playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}function AG(n,e){return be(n,"bump").map((t,i)=>{const s=Ct(t.initiator),a=Ct(t.victim),r=e.players.find(u=>u.id===s)?.name??s,o=e.players.find(u=>u.id===a)?.name??a,l=Un(e,t.frame,t.time),c=Math.round(t.confidence*100);return{id:`bump:${t.frame}:${s}:${a}:${i}`,time:l,frame:t.frame,kind:"bump",label:`${r} bumped ${o} ${c}%`,shortLabel:"B",playerId:s,playerName:r,isTeamZero:t.initiator_is_team_0,color:t.initiator_is_team_0?tn:nn}})}function RG(n){return n.kind==="beaten_to_ball"?"BT":n.dodge_active?"DW":n.aerial?"AW":"W"}function PG(n){const e=[n.aerial?"aerial":"grounded"];return n.dodge_active&&e.push("dodge"),e.join(" ")}function IG(n){return n.kind==="beaten_to_ball"?"beaten to ball":"whiff"}function LG(n,e){return be(n,"whiff").map((t,i)=>{const s=Ct(t.player),a=e.players.find(c=>c.id===s)?.name??s,r=Un(e,t.frame,t.time),o=Math.round(t.closest_approach_distance),l=Math.round(t.approach_speed);return{id:`whiff:${t.frame}:${s}:${i}`,time:r,frame:t.frame,kind:"whiff",label:`${a} ${PG(t)} ${IG(t)} | ${o}uu closest, ${l}uu/s`,shortLabel:RG(t),playerId:s,playerName:a,isTeamZero:t.is_team_0,color:t.is_team_0?tn:nn}})}const y1={flick:uG,ceiling_shot:fG,wall_aerial:pG,wall_aerial_shot:mG,double_tap:_G,center:gG,one_timer:yG,pass:bG,half_flip:EG,half_volley:xG,speed_flip:TG},v1=Object.keys(y1),b1=.02,si=1e-4,kG=200,x1=.08,X_={big:"rgba(245, 158, 11, 0.92)",small:"rgba(52, 211, 153, 0.86)"},Qx={both:"rgba(52, 211, 153, 0.86)",inferred_only:"rgba(239, 68, 68, 0.9)",reported_only:"rgba(59, 130, 246, 0.9)"};function DG(n){const e=n.config?.ball_half_neutral_zone_half_width_y;return typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):kG}function Ph(n,e,t){return n?.frames?.[e??-1]?.time??t}function OG(n,e,t,i,s,a){const r=e?.ballFrames[n]?.position?.y;return typeof r=="number"&&Number.isFinite(r)&&Math.abs(r)<=t+si||a>si?"neutral":i>s+si?"team_zero_side":s>i+si?"team_one_side":null}function w1(n,e,t){if(n==="neutral")return{id:`half-control:neutral:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"half-control",laneLabel:"Half Control",label:"Neutral half control",color:"rgba(209, 217, 224, 0.7)",isTeamZero:null};const i=n==="team_zero_side";return{id:`half-control:${n}:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"half-control",laneLabel:"Half Control",label:i?"Blue half control":"Orange half control",color:Lf(i)??void 0,isTeamZero:i}}function Df(n){return n.map((e,t)=>({event:e,index:t})).sort((e,t)=>e.event.frame!==t.event.frame?e.event.frame-t.event.frame:e.event.time!==t.event.time?e.event.time-t.event.time:e.index-t.index).map(({event:e})=>e)}function FG(n,e){const t=Df(be(n,"possession")),i=[];let s=0,a=!1,r="neutral",o=null;for(const l of n.frames){for(;s0)return FG(n,e);const t=[];let i=0,s=0,a=0,r=null;for(const o of n.frames){if(!Number.isFinite(o.time)||!Number.isFinite(o.dt)||o.dt<=0){r=o;continue}const l=o,c=l.team_zero?.possession?.possession_time??0,u=l.team_one?.possession?.possession_time??0,d=l.team_zero?.possession?.neutral_time??0,h=c-i,f=u-s,p=d-a;i=c,s=u,a=d;let g=null;const{startTime:_,endTime:m}=Cr(o,r,e);h>f+si&&h>p+si?g={id:`possession:team_zero:${_.toFixed(3)}`,startTime:_,endTime:m,lane:"possession",laneLabel:"Possession",label:"Blue possession",color:"rgba(59, 130, 246, 0.88)",isTeamZero:!0}:f>h+si&&f>p+si&&(g={id:`possession:team_one:${_.toFixed(3)}`,startTime:_,endTime:m,lane:"possession",laneLabel:"Possession",label:"Orange possession",color:"rgba(245, 158, 11, 0.88)",isTeamZero:!1}),el(t,g),r=o}return t}function UG(n,e){const t=Df(be(n,"ball_half")),i=[];let s=0,a=!1,r="neutral",o=null;for(const l of n.frames){for(;s0)return UG(n,e);const t=[];let i=0,s=0,a=0;const r=DG(n);let o=null;for(const l of n.frames){if(!Number.isFinite(l.time)||!Number.isFinite(l.dt)||l.dt<=0){o=l;continue}const c=l,u=c.team_zero?.ball_half?.defensive_half_time??0,d=c.team_one?.ball_half?.defensive_half_time??0,h=c.team_zero?.ball_half?.neutral_time??0,f=u-i,p=d-s,g=h-a;i=u,s=d,a=h;const{startTime:_,endTime:m}=Cr(l,o,e),v=OG(l.frame_number,e,r,f,p,g),y=v?w1(v,_,m):null;el(t,y),o=l}return t}function zG(n,e,t){return t>si?"neutral_third":n>e+si?"team_zero_third":e>n+si?"team_one_third":null}function S1(n,e,t){if(n==="neutral_third")return{id:`third-control:neutral_third:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"third-control",laneLabel:"Third Control",label:"Neutral third control",color:"rgba(209, 217, 224, 0.7)",isTeamZero:null};const i=n==="team_zero_third";return{id:`third-control:${n}:${e.toFixed(3)}`,startTime:e,endTime:t,lane:"third-control",laneLabel:"Third Control",label:i?"Blue third control":"Orange third control",color:Lf(i)??void 0,isTeamZero:i}}function HG(n,e){const t=Df(be(n,"ball_third")),i=[];let s=0,a=!1,r="neutral_third",o=null;for(const l of n.frames){for(;s0)return HG(n,e);const t=[];let i=0,s=0,a=0,r=null;for(const o of n.frames){if(!Number.isFinite(o.time)||!Number.isFinite(o.dt)||o.dt<=0){r=o;continue}const l=o,c=l.team_zero?.ball_third?.defensive_third_time??0,u=l.team_one?.ball_third?.defensive_third_time??0,d=l.team_zero?.ball_third?.neutral_third_time??0,h=c-i,f=u-s,p=d-a;i=c,s=u,a=d;const{startTime:g,endTime:_}=Cr(o,r,e),m=zG(h,f,p),v=m?S1(m,g,_):null;el(t,v),r=o}return t}function GG(n,e){return be(n,"fifty_fifty").map((t,i)=>{const s=Ph(e,t.start_frame,t.start_time),a=Math.max(s,Ph(e,t.resolve_frame,t.resolve_time)),r=t.winning_team_is_team_0==null?"Neutral":t.winning_team_is_team_0?"Blue win":"Orange win",o=t.is_kickoff?"kickoff ":"";return{id:`fifty-fifty:${t.start_frame}:${t.resolve_frame}:${i}`,startTime:s,endTime:a,lane:"fifty-fifty",laneLabel:"50/50",label:`${r} ${o}50/50`,shortLabel:t.is_kickoff?"KO":"50",color:t.winning_team_is_team_0==null?"rgba(209, 217, 224, 0.7)":t.winning_team_is_team_0?"rgba(59, 130, 246, 0.48)":"rgba(245, 158, 11, 0.48)",isTeamZero:t.winning_team_is_team_0}}).sort((t,i)=>t.startTime!==i.startTime?t.startTime-i.startTime:(t.id??"").localeCompare(i.id??""))}function $G(n,e){return be(n,"rush").map((t,i)=>{const s=e?.frames[t.start_frame]?.time??t.start_time,a=e?.frames[t.end_frame]?.time??t.end_time,r=`${t.attackers}v${t.defenders}`,o=t.is_team_0;return{id:`rush-range:${t.start_frame}:${t.end_frame}:${i}`,startTime:s,endTime:Math.max(s,a),lane:"rush",laneLabel:"Rush",label:`${o?"Blue":"Orange"} rush ${r}`,color:o?"rgba(59, 130, 246, 0.4)":"rgba(245, 158, 11, 0.4)",isTeamZero:o}})}function WG(n,e={}){const t=T1(e),i=new Set(e.detections??["both","inferred_only","reported_only"]),s=new Set(e.activities??["active","inactive","unknown"]),a=new Set(e.fieldHalves??["own","opponent","unknown"]),r=e.playerIds?new Set(e.playerIds):null;if(t.size===0||i.size===0||!s.has("unknown")||!a.has("unknown")||r?.size===0)return[];const o=new Map(n.players.map(c=>[c.id,c.isTeamZero])),l=[];for(const c of n.boostPads)if(t.has(c.size))for(let u=0;uc.startTime!==u.startTime?c.startTime-u.startTime:(c.id??"").localeCompare(u.id??""))}function T1(n){if(n.padTypes)return new Set(n.padTypes);if(n.sizes){const e=new Set(n.sizes),t=new Set;return e.has("big")&&t.add("big"),e.has("small")&&t.add("small"),e.has("big")&&e.has("small")&&t.add("ambiguous"),t}return new Set(["big","small","ambiguous"])}function ew(n){const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function XG(n){return{big:"big",small:"small",ambiguous:"ambiguous"}[n]}function KG(n){return{both:"counted",inferred_only:"inferred",reported_only:"reported"}[n]}function qG(n,e){return n==="inferred_only"?"I":n==="reported_only"?"R":{big:"100",small:"12",ambiguous:"?"}[e]}function YG(n,e,t={}){const i=be(n,"boost_pickup");if(i.length===0&&e)return WG(e,t);const s=T1(t),a=new Set(t.detections??["both","inferred_only","reported_only"]),r=new Set(t.activities??["active","inactive","unknown"]),o=new Set(t.fieldHalves??["own","opponent","unknown"]),l=t.playerIds?new Set(t.playerIds):null;if(s.size===0||a.size===0||r.size===0||o.size===0||l?.size===0)return[];const c=new Map((e?.players??[]).map(u=>[u.id,u.name]));return i.filter(u=>{const d=ew(u.player_id);return s.has(u.pad_type)&&a.has(u.detection)&&r.has(u.activity)&&o.has(u.field_half)&&(!l||l.has(d))}).map((u,d)=>{const h=ew(u.player_id),f=c.get(h)??h,p=Math.max(0,Ph(e,u.frame,u.time)),g=KG(u.detection),_=XG(u.pad_type);return{id:`boost-pickup:${u.detection}:${u.frame}:${h}:${d}`,startTime:p,endTime:Math.max(p+x1,p),lane:"boost-pickups",laneLabel:"Boost Pickups",label:`${f} ${g} ${_} boost pickup`,shortLabel:qG(u.detection,u.pad_type),color:Lf(u.is_team_0)??(u.detection==="both"?u.pad_type==="big"?X_.big:u.pad_type==="small"?X_.small:Qx.both:Qx[u.detection]),isTeamZero:u.is_team_0}}).sort((u,d)=>u.startTime!==d.startTime?u.startTime-d.startTime:(u.id??"").localeCompare(d.id??""))}const Ad=[{fieldName:"time_defensive_third",aliases:["time_defensive_zone"],label:"Def third",relativeColor:"own"},{fieldName:"time_neutral_third",aliases:["time_neutral_zone"],label:"Neutral third",relativeColor:"neutral"},{fieldName:"time_offensive_third",aliases:["time_offensive_zone"],label:"Off third",relativeColor:"opp"}];function M1(n,e){return n.relativeColor==="neutral"?"rgba(209, 217, 224, 0.68)":(n.relativeColor==="own"?e:!e)?"rgba(89, 195, 255, 0.74)":"rgba(255, 193, 92, 0.78)"}function Sy(n){const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function jG(n,e){const t=n.positioning;if(!t)return 0;for(const i of[e.fieldName,...e.aliases??[]]){const s=t[i];if(typeof s=="number"&&Number.isFinite(s))return s}return 0}function ZG(n){switch(n){case"defensive":return Ad[0];case"neutral":return Ad[1];case"offensive":return Ad[2]}}function JG(n){const e=new Map;for(const t of n.frames)for(const i of t.players){const s=Sy(i.player_id);e.has(s)||e.set(s,i.name)}return e}function QG(n){const e=Df(be(n,"field_third")),t=[],i=new Map,s=JG(n);for(const a of e){if(!Number.isFinite(a.time)||!Number.isFinite(a.end_time)||a.end_time-a.time<=si)continue;const r=Sy(a.player),o=ZG(a.state);E1(t,i,{id:`time-in-zone:${r}:${o.fieldName}:${a.time.toFixed(3)}`,startTime:a.time,endTime:a.end_time,lane:`time-in-zone:${r}`,laneLabel:s.get(r)??r,label:o.label,color:M1(o,a.is_team_0),isTeamZero:a.is_team_0})}return t}function e$(n,e){if(be(n,"field_third").length>0)return QG(n);const t=new Map,i=[],s=new Map;let a=null;for(const r of n.frames){if(!Number.isFinite(r.time)||!Number.isFinite(r.dt)||r.dt<=0){a=r;continue}const{startTime:o,endTime:l}=Cr(r,a,e);if(l-o<=si){a=r;continue}for(const c of r.players){const u=Sy(c.player_id),d=t.get(u)??new Map;let h=null,f=0;for(const p of Ad){const g=jG(c,p),_=g-(d.get(p.fieldName)??0);_>f+si&&(f=_,h=p),d.set(p.fieldName,g)}t.set(u,d),h&&E1(i,s,{id:`time-in-zone:${u}:${h.fieldName}:${o.toFixed(3)}`,startTime:o,endTime:l,lane:`time-in-zone:${u}`,laneLabel:c.name,label:h.label,color:M1(h,c.is_team_0),isTeamZero:c.is_team_0})}a=r}return i}function Cr(n,e,t){const i=t?.frames[n.frame_number]?.time??n.time,s=e?t?.frames[e.frame_number]?.time??e.time:Math.max(0,i-n.dt);return{startTime:Math.max(0,s),endTime:Math.max(s,i)}}function el(n,e){if(!e)return;const t=n[n.length-1];if(t&&t.lane===e.lane&&t.label===e.label&&Math.abs(t.endTime-e.startTime)<=b1){t.endTime=e.endTime;return}n.push(e)}function E1(n,e,t){if(!t)return;const i=t.lane??"",s=e.get(i);if(s&&s.label===t.label&&Math.abs(s.endTime-t.startTime)<=b1){s.endTime=t.endTime;return}n.push(t),e.set(i,t)}const Lm=236,C1="relative-positioning",t$={last:"Last",upfield:"Upfield",level:"Level",mid:"Mid"};function ua(n){return n?"team-blue":"team-orange"}function A1(n,e,t){return`
${n} ${t.metaHtml??""}
${e} -
`}function En(n,e,t,i=""){return g1(n,t,{metaHtml:i,tone:e?"blue":"orange"})}function ci(n,e){return`
${[!0,!1].map(t=>{const i=n.filter(a=>a.is_team_0===t);if(i.length===0)return"";const s=t?"Blue":"Orange";return`
+
`}function En(n,e,t,i=""){return A1(n,t,{metaHtml:i,tone:e?"blue":"orange"})}function ci(n,e){return`
${[!0,!1].map(t=>{const i=n.filter(a=>a.is_team_0===t);if(i.length===0)return"";const s=t?"Blue":"Orange";return`

${s} team

${i.length} player${i.length===1?"":"s"} @@ -5635,12 +5700,12 @@ void main() {
${i.map(e).join("")}
-
`}).join("")}
`}function Rf(n,e,t=""){return g1(n,e,{metaHtml:t,tone:"shared"})}function Sn(n,e,t){const i=Ht(n.statsFrameLookup,e);return i?i.players.find(s=>Ct(s.player_id)===t)??null:null}function wG(n,e,t){const i=n.players.find(p=>p.id===e);if(!i||!i.frames[t]?.position)return"mid";const a=i.isTeamZero,r=n.players.filter(p=>p.isTeamZero===a).length,o=[];let l=0;for(const p of n.players){if(p.isTeamZero!==a)continue;const g=p.frames[t];if(!g?.position)continue;const _=a?g.position.y:-g.position.y;o.push(_),p.id===e&&(l=_)}if(r<2||o.length!==r)return"mid";const c=Math.min(...o),u=Math.max(...o);if(u-c<=Mm)return"level";const h=l-c<=Mm,f=u-l<=Mm;return h&&!f?"last":f&&!h?"upfield":"mid"}function SG(n){let e=null,t=null;const i=new Set,s=["possession_state","field_half","field_third"];return{id:"possession",label:"Possession",setup(){a()},teardown(){},onBeforeRender(){},getTimelineRanges(o){return iG(o.statsTimeline,o.replay)},getConfig(){return{breakdownClasses:r()}},applyConfig(o){if(i.clear(),o&&typeof o=="object"&&!Array.isArray(o)){const l=o.breakdownClasses;if(Array.isArray(l))for(const c of l)s.includes(c)&&i.add(c)}a(),n.rerenderCurrentState()},renderStats(o,l){const u=Ht(l.statsFrameLookup,o)?.team_zero?.possession;return u?Rf("Control State",Fx(u,{labelPerspective:{kind:"shared"},breakdownClasses:r()})):""},renderFocusedPlayerStats(o,l,c){const u=Ht(c.statsFrameLookup,l),d=Sn(c,l,o),h=d?.is_team_0?u?.team_zero?.possession:u?.team_one?.possession;return!h||!d?"":Fx(h,{labelPerspective:{kind:"team"},breakdownClasses:r()})},renderSettings(){if(!e){e=document.createElement("div"),e.className="module-settings-card";const o=document.createElement("div");o.className="module-settings-header";const l=document.createElement("div"),c=document.createElement("p");c.className="module-settings-eyebrow",c.textContent="Stat display";const u=document.createElement("h3");u.textContent="Possession breakdown",l.append(c,u),t=document.createElement("strong"),t.className="metric-readout",o.append(l,t);const d=document.createElement("div");d.className="module-settings-options";const h=document.createElement("label");h.className="toggle";const f=document.createElement("input");f.type="checkbox",f.dataset.breakdownClass="possession_state",f.addEventListener("change",()=>{f.checked?i.add("possession_state"):i.delete("possession_state"),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const p=document.createElement("span");p.textContent="Control",h.append(f,p),d.append(h);const g=document.createElement("label");g.className="toggle";const _=document.createElement("input");_.type="checkbox",_.dataset.breakdownClass="field_third",_.addEventListener("change",()=>{_.checked?i.add("field_third"):i.delete("field_third"),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const m=document.createElement("span");m.textContent="Thirds",g.append(_,m),d.append(g);const v=document.createElement("label");v.className="toggle";const y=document.createElement("input");y.type="checkbox",y.dataset.breakdownClass="field_half",y.addEventListener("change",()=>{y.checked?i.add("field_half"):i.delete("field_half"),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const b=document.createElement("span");b.textContent="Halves",v.append(y,b),d.append(v),e.append(o,d)}return a(),e}};function a(){if(e){for(const o of e.querySelectorAll("input[data-breakdown-class]")){const l=o.dataset.breakdownClass;o.checked=l?i.has(l):!1}if(t){const o=s.filter(l=>i.has(l));t.textContent=o.length===0?"Total only":o.map(l=>l==="possession_state"?"Control":l==="field_half"?"Halves":"Thirds").join(" x ")}}}function r(){return s.filter(o=>i.has(o))}}function TG(){let n=null;return{id:"fifty-fifty",label:"50/50",setup(e){n=new u4(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},getTimelineEvents(e){return R4(e.statsTimeline,e.replay)},getTimelineRanges(e){return cG(e.statsTimeline,e.replay)},renderStats(e,t){const i=Ht(t.statsFrameLookup,e);if(!i)return"";const s=Rf("Challenge Summary",DV(i.team_zero?.fifty_fifty)),a=ci(i.players,r=>En(r.name,r.is_team_0,kx(r.fifty_fifty)));return s+a},renderFocusedPlayerStats(e,t,i){const s=Sn(i,t,e);return s?kx(s.fifty_fifty):""}}}function MG(){let n=null,e=null;return{id:"ball_half",label:"Half Control",setup(t){e=t.replay,n=new LV(t.player.sceneState.replayRoot,t.fieldScale)},teardown(){n?.dispose(),n=null,e=null},onBeforeRender(t){const i=e?.ballFrames[t.frameIndex];n?.update(i?.position?.y??null)},getTimelineRanges(t){return aG(t.statsTimeline,t.replay)},renderStats(t,i){const a=Ht(i.statsFrameLookup,t)?.team_zero?.ball_half;return a?Rf("Field State",Ux(a,{labelPerspective:{kind:"shared"}})):""},renderFocusedPlayerStats(t,i,s){const a=Ht(s.statsFrameLookup,i),r=Sn(s,i,t),o=r?.is_team_0?a?.team_zero?.ball_half:a?.team_one?.ball_half;return!o||!r?"":Ux(o,{labelPerspective:{kind:"team"}})}}}function EG(){return{id:"ball_third",label:"Third Control",setup(){},teardown(){},onBeforeRender(){},getTimelineRanges(n){return lG(n.statsTimeline,n.replay)},renderStats(n,e){const i=Ht(e.statsFrameLookup,n)?.team_zero?.ball_third;return i?Rf("Field State",zx(i,{labelPerspective:{kind:"shared"}})):""},renderFocusedPlayerStats(n,e,t){const i=Ht(t.statsFrameLookup,e),s=Sn(t,e,n),a=s?.is_team_0?i?.team_zero?.ball_third:i?.team_one?.ball_third;return!a||!s?"":zx(a,{labelPerspective:{kind:"team"}})}}}function CG(){return{id:"rush",label:"Rush",setup(){},teardown(){},onBeforeRender(){},getTimelineRanges(n){return uG(n.statsTimeline,n.replay)},getTimelineEvents(n){return V4(n.statsTimeline,n.replay)},renderStats(n,e){const t=Ht(e.statsFrameLookup,n),i=t?.team_zero?.rush,s=t?.team_one?.rush;return!i||!s?"":[En("Blue Team",!0,Tm(i)),En("Orange Team",!1,Tm(s))].join("")},renderFocusedPlayerStats(n,e,t){const i=Ht(t.statsFrameLookup,e),s=Sn(t,e,n),a=s?.is_team_0?i?.team_zero?.rush:i?.team_one?.rush;return!a||!s?"":Tm(a)}}}const z_={speed_band:{valueOrder:["slow","boost","supersonic"],formatValue:n=>({slow:"Slow",boost:"Boost",supersonic:"Supersonic"})[n]??n},height_band:{valueOrder:["ground","low_air","high_air"],formatValue:n=>({ground:"Ground",low_air:"Low air",high_air:"High air"})[n]??n}};function AG(n){const e=new Set,t=[];for(const i of n??[])e.has(i)||(e.add(i),t.push(i));return t}function Em(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function RG(n,e,t=1){return n===void 0||Number.isNaN(n)?"?":e===void 0||Number.isNaN(e)||e<=0?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${(n*100/e).toFixed(t)}%)`}function Xx(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Td(n,e){return`
${Xx(n)}${Xx(e)}
`}function PG(n,e,t){for(const i of t){const{valueOrder:s}=z_[i],a=s.indexOf(n[i]),r=s.indexOf(e[i]),o=a===-1?Number.MAX_SAFE_INTEGER:a,l=r===-1?Number.MAX_SAFE_INTEGER:r;if(o!==l)return o-l}return 0}function IG(n,e){if(e.length===1){const t=e[0];return z_[t].formatValue(n[t])}return e.map(t=>z_[t].formatValue(n[t])).join(" / ")}function LG(n,e,t){if(e.length===0||!n?.labeled_tracked_time?.entries?.length)return"";const i=new Map,s=n?.labeled_tracked_time?.entries??[];for(const a of s){const r=new Map(a.labels.map(d=>[d.key,d.value])),o={};let l=!0;for(const d of e){const h=r.get(d);if(h===void 0){l=!1;break}o[d]=h}if(!l)continue;const c=e.map(d=>`${d}:${o[d]}`).join("|"),u=i.get(c);u?u.total+=a.value:i.set(c,{values:o,total:a.value})}return[...i.values()].sort((a,r)=>PG(a.values,r.values,e)).map(a=>Td(IG(a.values,e),RG(a.total,t))).join("")}function Kx(n,e={}){const t=n?.tracked_time,i=n&&t&&t>0?n.speed_integral/t:t===0?0:void 0,s=AG(e.breakdownClasses),a=LG(n,s,t);return` - ${Td("Tracked",Em(t,1,"s"))} - ${Td("Distance",Em(n?.total_distance,0," uu"))} - ${Td("Avg speed",Em(i,0," uu/s"))} + `}).join("")}
`}function Of(n,e,t=""){return A1(n,e,{metaHtml:t,tone:"shared"})}function Sn(n,e,t){const i=Ht(n.statsFrameLookup,e);return i?i.players.find(s=>Ct(s.player_id)===t)??null:null}function n$(n,e,t){const i=n.players.find(p=>p.id===e);if(!i||!i.frames[t]?.position)return"mid";const a=i.isTeamZero,r=n.players.filter(p=>p.isTeamZero===a).length,o=[];let l=0;for(const p of n.players){if(p.isTeamZero!==a)continue;const g=p.frames[t];if(!g?.position)continue;const _=a?g.position.y:-g.position.y;o.push(_),p.id===e&&(l=_)}if(r<2||o.length!==r)return"mid";const c=Math.min(...o),u=Math.max(...o);if(u-c<=Lm)return"level";const h=l-c<=Lm,f=u-l<=Lm;return h&&!f?"last":f&&!h?"upfield":"mid"}function i$(n){let e=null,t=null;const i=new Set,s=["possession_state","field_half","field_third"];return{id:"possession",label:"Possession",setup(){a()},teardown(){},onBeforeRender(){},getTimelineRanges(o){return NG(o.statsTimeline,o.replay)},getConfig(){return{breakdownClasses:r()}},applyConfig(o){if(i.clear(),o&&typeof o=="object"&&!Array.isArray(o)){const l=o.breakdownClasses;if(Array.isArray(l))for(const c of l)s.includes(c)&&i.add(c)}a(),n.rerenderCurrentState()},renderStats(o,l){const u=Ht(l.statsFrameLookup,o)?.team_zero?.possession;return u?Of("Control State",Wx(u,{labelPerspective:{kind:"shared"},breakdownClasses:r()})):""},renderFocusedPlayerStats(o,l,c){const u=Ht(c.statsFrameLookup,l),d=Sn(c,l,o),h=d?.is_team_0?u?.team_zero?.possession:u?.team_one?.possession;return!h||!d?"":Wx(h,{labelPerspective:{kind:"team"},breakdownClasses:r()})},renderSettings(){if(!e){e=document.createElement("div"),e.className="module-settings-card";const o=document.createElement("div");o.className="module-settings-header";const l=document.createElement("div"),c=document.createElement("p");c.className="module-settings-eyebrow",c.textContent="Stat display";const u=document.createElement("h3");u.textContent="Possession breakdown",l.append(c,u),t=document.createElement("strong"),t.className="metric-readout",o.append(l,t);const d=document.createElement("div");d.className="module-settings-options";const h=document.createElement("label");h.className="toggle";const f=document.createElement("input");f.type="checkbox",f.dataset.breakdownClass="possession_state",f.addEventListener("change",()=>{f.checked?i.add("possession_state"):i.delete("possession_state"),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const p=document.createElement("span");p.textContent="Control",h.append(f,p),d.append(h);const g=document.createElement("label");g.className="toggle";const _=document.createElement("input");_.type="checkbox",_.dataset.breakdownClass="field_third",_.addEventListener("change",()=>{_.checked?i.add("field_third"):i.delete("field_third"),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const m=document.createElement("span");m.textContent="Thirds",g.append(_,m),d.append(g);const v=document.createElement("label");v.className="toggle";const y=document.createElement("input");y.type="checkbox",y.dataset.breakdownClass="field_half",y.addEventListener("change",()=>{y.checked?i.add("field_half"):i.delete("field_half"),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const b=document.createElement("span");b.textContent="Halves",v.append(y,b),d.append(v),e.append(o,d)}return a(),e}};function a(){if(e){for(const o of e.querySelectorAll("input[data-breakdown-class]")){const l=o.dataset.breakdownClass;o.checked=l?i.has(l):!1}if(t){const o=s.filter(l=>i.has(l));t.textContent=o.length===0?"Total only":o.map(l=>l==="possession_state"?"Control":l==="field_half"?"Halves":"Thirds").join(" x ")}}}function r(){return s.filter(o=>i.has(o))}}function s$(){let n=null;return{id:"fifty-fifty",label:"50/50",setup(e){n=new $4(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},getTimelineEvents(e){return cG(e.statsTimeline,e.replay)},getTimelineRanges(e){return GG(e.statsTimeline,e.replay)},renderStats(e,t){const i=Ht(t.statsFrameLookup,e);if(!i)return"";const s=Of("Challenge Summary",p4(i.team_zero?.fifty_fifty)),a=ci(i.players,r=>En(r.name,r.is_team_0,Vx(r.fifty_fifty)));return s+a},renderFocusedPlayerStats(e,t,i){const s=Sn(i,t,e);return s?Vx(s.fifty_fifty):""}}}function a$(){let n=null,e=null;return{id:"ball_half",label:"Half Control",setup(t){e=t.replay,n=new h4(t.player.sceneState.replayRoot,t.fieldScale)},teardown(){n?.dispose(),n=null,e=null},onBeforeRender(t){const i=e?.ballFrames[t.frameIndex];n?.update(i?.position?.y??null)},getTimelineRanges(t){return BG(t.statsTimeline,t.replay)},renderStats(t,i){const a=Ht(i.statsFrameLookup,t)?.team_zero?.ball_half;return a?Of("Field State",Kx(a,{labelPerspective:{kind:"shared"}})):""},renderFocusedPlayerStats(t,i,s){const a=Ht(s.statsFrameLookup,i),r=Sn(s,i,t),o=r?.is_team_0?a?.team_zero?.ball_half:a?.team_one?.ball_half;return!o||!r?"":Kx(o,{labelPerspective:{kind:"team"}})}}}function r$(){return{id:"ball_third",label:"Third Control",setup(){},teardown(){},onBeforeRender(){},getTimelineRanges(n){return VG(n.statsTimeline,n.replay)},renderStats(n,e){const i=Ht(e.statsFrameLookup,n)?.team_zero?.ball_third;return i?Of("Field State",Yx(i,{labelPerspective:{kind:"shared"}})):""},renderFocusedPlayerStats(n,e,t){const i=Ht(t.statsFrameLookup,e),s=Sn(t,e,n),a=s?.is_team_0?i?.team_zero?.ball_third:i?.team_one?.ball_third;return!a||!s?"":Yx(a,{labelPerspective:{kind:"team"}})}}}function o$(){return{id:"rush",label:"Rush",setup(){},teardown(){},onBeforeRender(){},getTimelineRanges(n){return $G(n.statsTimeline,n.replay)},getTimelineEvents(n){return wG(n.statsTimeline,n.replay)},renderStats(n,e){const t=Ht(e.statsFrameLookup,n),i=t?.team_zero?.rush,s=t?.team_one?.rush;return!i||!s?"":[En("Blue Team",!0,Im(i)),En("Orange Team",!1,Im(s))].join("")},renderFocusedPlayerStats(n,e,t){const i=Ht(t.statsFrameLookup,e),s=Sn(t,e,n),a=s?.is_team_0?i?.team_zero?.rush:i?.team_one?.rush;return!a||!s?"":Im(a)}}}const K_={speed_band:{valueOrder:["slow","boost","supersonic"],formatValue:n=>({slow:"Slow",boost:"Boost",supersonic:"Supersonic"})[n]??n},height_band:{valueOrder:["ground","low_air","high_air"],formatValue:n=>({ground:"Ground",low_air:"Low air",high_air:"High air"})[n]??n}};function l$(n){const e=new Set,t=[];for(const i of n??[])e.has(i)||(e.add(i),t.push(i));return t}function km(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function c$(n,e,t=1){return n===void 0||Number.isNaN(n)?"?":e===void 0||Number.isNaN(e)||e<=0?`${n.toFixed(t)}s`:`${n.toFixed(t)}s (${(n*100/e).toFixed(t)}%)`}function tw(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Rd(n,e){return`
${tw(n)}${tw(e)}
`}function u$(n,e,t){for(const i of t){const{valueOrder:s}=K_[i],a=s.indexOf(n[i]),r=s.indexOf(e[i]),o=a===-1?Number.MAX_SAFE_INTEGER:a,l=r===-1?Number.MAX_SAFE_INTEGER:r;if(o!==l)return o-l}return 0}function d$(n,e){if(e.length===1){const t=e[0];return K_[t].formatValue(n[t])}return e.map(t=>K_[t].formatValue(n[t])).join(" / ")}function h$(n,e,t){if(e.length===0||!n?.labeled_tracked_time?.entries?.length)return"";const i=new Map,s=n?.labeled_tracked_time?.entries??[];for(const a of s){const r=new Map(a.labels.map(d=>[d.key,d.value])),o={};let l=!0;for(const d of e){const h=r.get(d);if(h===void 0){l=!1;break}o[d]=h}if(!l)continue;const c=e.map(d=>`${d}:${o[d]}`).join("|"),u=i.get(c);u?u.total+=a.value:i.set(c,{values:o,total:a.value})}return[...i.values()].sort((a,r)=>u$(a.values,r.values,e)).map(a=>Rd(d$(a.values,e),c$(a.total,t))).join("")}function nw(n,e={}){const t=n?.tracked_time,i=n&&t&&t>0?n.speed_integral/t:t===0?0:void 0,s=l$(e.breakdownClasses),a=h$(n,s,t);return` + ${Rd("Tracked",km(t,1,"s"))} + ${Rd("Distance",km(n?.total_distance,0," uu"))} + ${Rd("Avg speed",km(i,0," uu/s"))} ${a} - `}const qx="subtr-actor-flip-impulse-overlay-styles",kG=5882879,DG=16761180,Cm=260,OG=760,FG=260,NG=2.5;function y1(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function UG(n,e){const t=y1(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function BG(n){return n.split("_").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function zG(n,e){return be(n,"dodge").flatMap((t,i)=>{const s=t.dodge_impulse;if(!s)return[];const a=UG(e,t.player),r=y1(t.player),o=e.frames[t.frame]?.time??t.time,l=new T(s.estimated_direction[0],s.estimated_direction[1],s.estimated_direction[2]);return l.lengthSq()<=Number.EPSILON&&l.set(1,0,0),l.normalize(),{id:`dodge-impulse:${t.frame}:${r}:${i}`,time:o,frame:t.frame,isTeamZero:t.is_team_0,playerId:r,playerName:a,position:new T(s.start_position[0],s.start_position[1],s.start_position[2]+44),direction:l,magnitude:s.estimated_impulse_magnitude,confidence:s.confidence,directionLabel:s.direction_label}})}function HG(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function VG(){if(document.getElementById(qx))return;const n=document.createElement("style");n.id=qx,n.textContent=` + `}const iw="subtr-actor-flip-impulse-overlay-styles",f$=5882879,p$=16761180,Dm=260,m$=760,_$=260,g$=2.5;function R1(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function y$(n,e){const t=R1(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function v$(n){return n.split("_").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function b$(n,e){return be(n,"dodge").flatMap((t,i)=>{const s=t.dodge_impulse;if(!s)return[];const a=y$(e,t.player),r=R1(t.player),o=e.frames[t.frame]?.time??t.time,l=new T(s.estimated_direction[0],s.estimated_direction[1],s.estimated_direction[2]);return l.lengthSq()<=Number.EPSILON&&l.set(1,0,0),l.normalize(),{id:`dodge-impulse:${t.frame}:${r}:${i}`,time:o,frame:t.frame,isTeamZero:t.is_team_0,playerId:r,playerName:a,position:new T(s.start_position[0],s.start_position[1],s.start_position[2]+44),direction:l,magnitude:s.estimated_impulse_magnitude,confidence:s.confidence,directionLabel:s.direction_label}})}function x$(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function w$(){if(document.getElementById(iw))return;const n=document.createElement("style");n.id=iw,n.textContent=` .sap-flip-impulse-overlay-root { position: absolute; inset: 0; @@ -5676,7 +5741,7 @@ void main() { border-color: rgba(255, 193, 92, 0.5); background: rgba(76, 41, 7, 0.84); } - `,document.head.append(n)}function GG(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class $G{scene;container;group=new Et;labelRoot;projectedPosition=new T;worldPosition=new T;labelOffset=new T(0,0,FG);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=NG;constructor(e,t,i,s){VG(),this.scene=e,this.container=t,this.markers=zG(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="flip-impulse-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-flip-impulse-overlay-root",this.container.append(this.labelRoot)}update(e){const t=HG(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.arrow.removeFromParent(),a.arrow.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.24+.72*r,c=Cm+Math.min(1,s.magnitude/450)*(OG-Cm);o.arrow.position.copy(s.position),o.arrow.setDirection(s.direction),o.arrow.setLength(c,70,38),o.arrow.cone.material.opacity=l,o.arrow.line.material.opacity=l,this.worldPosition.copy(s.position).add(this.labelOffset);const u=GG(this.worldPosition,this.scene.camera,this.container,this.projectedPosition);o.label.style.display=u?"block":"none",u&&(o.label.style.left=`${this.projectedPosition.x}px`,o.label.style.top=`${this.projectedPosition.y}px`,o.label.style.opacity=`${.42+.58*r}`)}}dispose(){for(const e of this.views.values())e.arrow.removeFromParent(),e.arrow.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=e.isTeamZero?kG:DG,s=new jg(e.direction,e.position,Cm,i);s.renderOrder=35,s.line.material=new Pt({color:i,transparent:!0,opacity:.9,depthWrite:!1,depthTest:!1}),s.cone.material=new je({color:i,transparent:!0,opacity:.9,depthWrite:!1,depthTest:!1}),this.group.add(s);const a=document.createElement("div");a.className=`sap-flip-impulse-overlay-label ${e.isTeamZero?"sap-flip-impulse-overlay-label-blue":"sap-flip-impulse-overlay-label-orange"}`,a.textContent=`${e.playerName} ${BG(e.directionLabel)} ${Math.round(e.confidence*100)}%`,this.labelRoot.append(a);const r={marker:e,arrow:s,label:a};return this.views.set(e.id,r),r}}const Yx="subtr-actor-speed-flip-overlay-styles",WG=5882879,XG=16761180,KG=16185075,qG=150,YG=230,jG=220,ZG=4;function v1(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function JG(n,e){const t=v1(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function QG(n,e){return be(n,"speed_flip").map(t=>{const i=JG(e,t.player),s=v1(t.player),a=e.frames[t.frame]?.time??t.time,r=t.confidence;return{id:`speed-flip:${t.frame}:${s}:${Math.round(r*1e3)}`,time:a,frame:t.frame,isTeamZero:t.is_team_0,playerId:s,playerName:i,position:{x:t.start_position[0],y:t.start_position[1],z:t.start_position[2]},quality:r,qualityLabel:`${Math.round(r*100)}%`}})}function e$(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function t$(){if(document.getElementById(Yx))return;const n=document.createElement("style");n.id=Yx,n.textContent=` + `,document.head.append(n)}function S$(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class T${scene;container;group=new Et;labelRoot;projectedPosition=new T;worldPosition=new T;labelOffset=new T(0,0,_$);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=g$;constructor(e,t,i,s){w$(),this.scene=e,this.container=t,this.markers=b$(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="flip-impulse-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-flip-impulse-overlay-root",this.container.append(this.labelRoot)}update(e){const t=x$(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.arrow.removeFromParent(),a.arrow.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.24+.72*r,c=Dm+Math.min(1,s.magnitude/450)*(m$-Dm);o.arrow.position.copy(s.position),o.arrow.setDirection(s.direction),o.arrow.setLength(c,70,38),o.arrow.cone.material.opacity=l,o.arrow.line.material.opacity=l,this.worldPosition.copy(s.position).add(this.labelOffset);const u=S$(this.worldPosition,this.scene.camera,this.container,this.projectedPosition);o.label.style.display=u?"block":"none",u&&(o.label.style.left=`${this.projectedPosition.x}px`,o.label.style.top=`${this.projectedPosition.y}px`,o.label.style.opacity=`${.42+.58*r}`)}}dispose(){for(const e of this.views.values())e.arrow.removeFromParent(),e.arrow.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=e.isTeamZero?f$:p$,s=new iy(e.direction,e.position,Dm,i);s.renderOrder=35,s.line.material=new Pt({color:i,transparent:!0,opacity:.9,depthWrite:!1,depthTest:!1}),s.cone.material=new je({color:i,transparent:!0,opacity:.9,depthWrite:!1,depthTest:!1}),this.group.add(s);const a=document.createElement("div");a.className=`sap-flip-impulse-overlay-label ${e.isTeamZero?"sap-flip-impulse-overlay-label-blue":"sap-flip-impulse-overlay-label-orange"}`,a.textContent=`${e.playerName} ${v$(e.directionLabel)} ${Math.round(e.confidence*100)}%`,this.labelRoot.append(a);const r={marker:e,arrow:s,label:a};return this.views.set(e.id,r),r}}const sw="subtr-actor-speed-flip-overlay-styles",M$=5882879,E$=16761180,C$=16185075,A$=150,R$=230,P$=220,I$=4;function P1(n){if(!n)return null;const[e,t]=Object.entries(n)[0]??["Unknown","unknown"],i=typeof t=="string"?t:JSON.stringify(t);return`${e}:${i}`}function L$(n,e){const t=P1(e);return t?n.players.find(i=>i.id===t)?.name??t:"Unknown"}function k$(n,e){return be(n,"speed_flip").map(t=>{const i=L$(e,t.player),s=P1(t.player),a=e.frames[t.frame]?.time??t.time,r=t.confidence;return{id:`speed-flip:${t.frame}:${s}:${Math.round(r*1e3)}`,time:a,frame:t.frame,isTeamZero:t.is_team_0,playerId:s,playerName:i,position:{x:t.start_position[0],y:t.start_position[1],z:t.start_position[2]},quality:r,qualityLabel:`${Math.round(r*100)}%`}})}function D$(n,e,t){const i=Math.max(.1,t);return n.filter(s=>{const a=e-s.time;return a>=0&&a<=i})}function O$(){if(document.getElementById(sw))return;const n=document.createElement("style");n.id=sw,n.textContent=` .sap-speed-flip-overlay-root { position: absolute; inset: 0; @@ -5713,7 +5778,7 @@ void main() { border-color: rgba(255, 193, 92, 0.5); background: rgba(76, 41, 7, 0.84); } - `,document.head.append(n)}function n$(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class i${scene;container;group=new Et;labelRoot;projectedPosition=new T;worldPosition=new T;labelOffset=new T(0,0,jG);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=ZG;constructor(e,t,i,s){t$(),this.scene=e,this.container=t,this.markers=QG(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="speed-flip-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-speed-flip-overlay-root",this.container.append(this.labelRoot)}update(e){const t=e$(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.ring.removeFromParent(),a.ring.geometry.dispose(),a.material.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.16+.56*r,c=.96+(1-r)*.22;o.material.opacity=l,o.ring.position.set(s.position.x,s.position.y,s.position.z+14),o.ring.scale.setScalar(c+s.quality*.08),this.worldPosition.set(s.position.x,s.position.y,s.position.z).add(this.labelOffset);const u=n$(this.worldPosition,this.scene.camera,this.container,this.projectedPosition);o.label.style.display=u?"block":"none",u&&(o.label.style.left=`${this.projectedPosition.x}px`,o.label.style.top=`${this.projectedPosition.y}px`,o.label.style.opacity=`${.42+.58*r}`)}}dispose(){for(const e of this.views.values())e.ring.removeFromParent(),e.ring.geometry.dispose(),e.material.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=new je({color:e.quality>=.75?KG:e.isTeamZero?WG:XG,transparent:!0,opacity:.8,side:ut,depthWrite:!1,depthTest:!1}),s=new oi(qG,YG,48),a=new Se(s,i);a.renderOrder=30,this.group.add(a);const r=document.createElement("div");r.className=`sap-speed-flip-overlay-label ${e.isTeamZero?"sap-speed-flip-overlay-label-blue":"sap-speed-flip-overlay-label-orange"}`,r.textContent=`${e.playerName} speed flip ${e.qualityLabel}`,this.labelRoot.append(r);const o={marker:e,ring:a,material:i,label:r};return this.views.set(e.id,o),o}}const Ju=[{value:"big",label:"Big pads"},{value:"small",label:"Small pads"},{value:"ambiguous",label:"Ambiguous pads"}],Am=[{value:"both",label:"Both detectors"},{value:"inferred_only",label:"Inferred only"},{value:"reported_only",label:"Reported only"}],Qu=[{value:"active",label:"Active play"},{value:"inactive",label:"Inactive play"},{value:"unknown",label:"Unknown activity"}],ed=[{value:"own",label:"Own half"},{value:"opponent",label:"Opponent half"},{value:"unknown",label:"Unknown half"}];function s$(n,e){return n===e||n==="ambiguous"}function a$(n,e){const t=e?r$(e,be(e,"boost_pickup")):[];return t.length===0?null:t.find(i=>Ct(i.player_id)===n.player.id&&i.detection!=="inferred_only"&&i.frame===n.event.frame&&s$(i.pad_type,n.pad.size))??null}function r$(n,e){if(e.length>0)return e;const t=n.events?.boost_pickups;return Array.isArray(t)?t:e}function b1(n={}){let e=null,t=null,i=null,s=null,a=null,r=null;const o=new Set(Ju.map(M=>M.value)),l=new Set(Am.map(M=>M.value)),c=new Set(Qu.map(M=>M.value)),u=new Set(ed.map(M=>M.value));let d=null,h=!1;function f(M,C,w,E){const R=document.createElement("div");R.className="boost-pickup-filter-group";const L=document.createElement("p");L.className="module-settings-group-title",L.textContent=M;const O=document.createElement("div");O.className="boost-pickup-filter-options";for(const D of C){const U=document.createElement("label");U.className="toggle";const F=document.createElement("input");F.type="checkbox",F.dataset.boostPickupFilter=E,F.dataset.boostPickupValue=D.value,F.addEventListener("change",()=>{F.checked?w.add(D.value):w.delete(D.value),_(a),n.refreshTimelineRanges?.(),n.rerenderCurrentState?.(),n.requestConfigSync?.()});const W=document.createElement("span");W.textContent=D.label,U.append(F,W),O.append(U)}return R.append(L,O),R}function p(){const M=document.createElement("div");M.className="boost-pickup-filter-group boost-pickup-filter-group-wide",i=M;const C=document.createElement("p");return C.className="module-settings-group-title",C.textContent="Player",s=document.createElement("div"),s.className="boost-pickup-filter-options",M.append(C,s),M}function g(M){if(s&&(s.replaceChildren(),i&&(i.hidden=!M||M.players.length===0),!!M))for(const C of M.players){const w=document.createElement("label");w.className="toggle";const E=document.createElement("input");E.type="checkbox",E.dataset.boostPickupPlayerId=C.id,E.addEventListener("change",()=>{d||(d=new Set(M.players.map(L=>L.id))),E.checked?d.add(C.id):d.delete(C.id),_(M),n.refreshTimelineRanges?.(),n.rerenderCurrentState?.(),n.requestConfigSync?.()});const R=document.createElement("span");R.textContent=`${C.name} (${C.isTeamZero?"Blue":"Orange"})`,w.append(E,R),s.append(w)}}function _(M){if(e){for(const C of e.querySelectorAll("input[data-boost-pickup-filter][data-boost-pickup-value]")){const w=C.dataset.boostPickupFilter,E=C.dataset.boostPickupValue;C.checked=m(w,E)}for(const C of e.querySelectorAll("input[data-boost-pickup-player-id]")){const w=C.dataset.boostPickupPlayerId;C.checked=w?d?.has(w)??!0:!1}t&&(t.textContent=v(M))}}function m(M,C){if(!C)return!1;switch(M){case"pad-type":return o.has(C);case"detection":return l.has(C);case"activity":return c.has(C);case"field-half":return u.has(C);default:return!1}}function v(M){const C=M?.players.length??0,w=d?d.size:C;if(o.size===0||l.size===0||c.size===0||u.size===0||d!==null&&d.size===0)return"Hidden";const R=[o.sizeR.value));for(const R of w)typeof R=="string"&&E.has(R)&&M.add(R)}function S(){return{padTypes:[...o],detections:[...l],activities:[...c],fieldHalves:[...u],playerIds:d?[...d]:null}}function x(M){if(!M||typeof M!="object"||Array.isArray(M))return;const C=M;b(o,Ju,C.padTypes),b(l,Am,C.detections),b(c,Qu,C.activities),b(u,ed,C.fieldHalves),d=Array.isArray(C.playerIds)?new Set(C.playerIds.filter(w=>typeof w=="string")):null,h=a===null&&d!==null,_(a),n.refreshTimelineRanges?.(),n.rerenderCurrentState?.(),n.requestConfigSync?.()}return{setup(M){a!==M.replay&&(a=M.replay,h?h=!1:d=null),r=M.statsTimeline,_(M.replay)},teardown(){},getConfig:S,applyConfig:x,getTimelineRangeOptions(){const M={padTypes:o,detections:l,activities:c,fieldHalves:u};return d&&(M.playerIds=d),M},includePickup:y,renderSettings(M,C){if(!e){e=document.createElement("div"),e.className="boost-pickup-filter-panel";const w=document.createElement("div");w.className="boost-pickup-filter-summary",t=document.createElement("strong"),t.className="metric-readout",w.append(t);const E=document.createElement("div");E.className="boost-pickup-filter-grid",E.append(f("Pad type",Ju,o,"pad-type"),f("Activity",Qu,c,"activity"),f("Field half",ed,u,"field-half"),p()),(C.showHeader??!1)&&e.append(w),e.append(E)}return g(M?.replay??null),_(M?.replay??null),e}}}function ui(n){return{id:n.id,label:n.label,setup(){},teardown(){},onBeforeRender(){},getTimelineEvents:n.getTimelineEvents,getTimelineRanges:n.getTimelineRanges,renderStats(e,t){const i=Ht(t.statsFrameLookup,e);return i?ci(i.players,s=>En(s.name,s.is_team_0,n.render(n.select(s),s))):""},renderFocusedPlayerStats(e,t,i){const s=Sn(i,t,e);return s?n.render(n.select(s),s):""}}}function $i(n){return n==null?"?":Ys(n).toFixed(0)}function o$(n,e){const t=$i(n);if(n==null||e==null)return t;const i=$i(n+e);return`${t} (${i})`}function Rm(n){n&&typeof n=="object"&&"dispose"in n&&typeof n.dispose=="function"&&n.dispose()}function l$(n){n&&(n.removeFromParent(),n.traverse(e=>{const t="geometry"in e?e.geometry:null;Rm(t);const i="material"in e?e.material:null;if(Array.isArray(i))for(const s of i)Rm(s);else Rm(i)}))}function c$(){let n=0,e=null;return{acquire(t){e||(e=kV(t.player.sceneState.replayRoot,t.fieldScale)),n+=1},release(){n<=0||(n-=1,n===0&&(l$(e),e=null))}}}const jx=c$();function it(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function ke(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function H_(n,e=0){return ke(n,e,"%")}function x1(n,e,t=1,i=0){if(n===void 0||Number.isNaN(n))return H_(e,i);const s=ke(n,t,"s");return e===void 0||Number.isNaN(e)?s:`${s} (${H_(e,i)})`}function qa(n,e,t=1,i=0){const s=n!==void 0&&e!==void 0&&!Number.isNaN(n)&&!Number.isNaN(e)&&e>0?n*100/e:void 0;return x1(n,s,t,i)}function xt(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function ys(n){const e=xt(n);return e===void 0?void 0:e*100}function w1(n){return xt(n?.tracked_time)}function u$(n,e,t){const i=xt(n?.[e]);if(i!==void 0)return i;const s=w1(n),a=xt(n?.[t]);if(!(s===void 0||s<=0||a===void 0))return a*100/s}function Pn(n,e,t){return x1(xt(n?.[t]),u$(n,e,t))}function Zx(n,e,t){const i=xt(n?.[e]);if(i!==void 0)return i;const s=w1(n),a=xt(n?.[t]);if(!(s===void 0||s<=0||a===void 0))return a/s}function Jx(n){return` + `,document.head.append(n)}function F$(n,e,t,i){if(i.copy(n).project(e),i.z<-1||i.z>1)return!1;const s=t.clientWidth||1,a=t.clientHeight||1;return i.x=(i.x+1)*s/2,i.y=(1-i.y)*a/2,!(i.x<-100||i.x>s+100||i.y<-100||i.y>a+100)}class N${scene;container;group=new Et;labelRoot;projectedPosition=new T;worldPosition=new T;labelOffset=new T(0,0,P$);markers;views=new Map;changedContainerPosition=!1;originalContainerPosition="";decaySeconds=I$;constructor(e,t,i,s){O$(),this.scene=e,this.container=t,this.markers=k$(s,i),getComputedStyle(t).position==="static"&&(this.changedContainerPosition=!0,this.originalContainerPosition=t.style.position,t.style.position="relative"),this.group.name="speed-flip-overlay",this.scene.replayRoot.add(this.group),this.labelRoot=document.createElement("div"),this.labelRoot.className="sap-speed-flip-overlay-root",this.container.append(this.labelRoot)}update(e){const t=D$(this.markers,e,this.decaySeconds),i=new Set(t.map(s=>s.id));for(const[s,a]of this.views.entries())i.has(s)||(a.ring.removeFromParent(),a.ring.geometry.dispose(),a.material.dispose(),a.label.remove(),this.views.delete(s));for(const s of t){const a=Math.max(0,e-s.time),r=Math.max(0,1-a/this.decaySeconds),o=this.ensureView(s),l=.16+.56*r,c=.96+(1-r)*.22;o.material.opacity=l,o.ring.position.set(s.position.x,s.position.y,s.position.z+14),o.ring.scale.setScalar(c+s.quality*.08),this.worldPosition.set(s.position.x,s.position.y,s.position.z).add(this.labelOffset);const u=F$(this.worldPosition,this.scene.camera,this.container,this.projectedPosition);o.label.style.display=u?"block":"none",u&&(o.label.style.left=`${this.projectedPosition.x}px`,o.label.style.top=`${this.projectedPosition.y}px`,o.label.style.opacity=`${.42+.58*r}`)}}dispose(){for(const e of this.views.values())e.ring.removeFromParent(),e.ring.geometry.dispose(),e.material.dispose(),e.label.remove();this.views.clear(),this.group.removeFromParent(),this.labelRoot.remove(),this.changedContainerPosition&&(this.container.style.position=this.originalContainerPosition)}ensureView(e){const t=this.views.get(e.id);if(t)return t;const i=new je({color:e.quality>=.75?C$:e.isTeamZero?M$:E$,transparent:!0,opacity:.8,side:ut,depthWrite:!1,depthTest:!1}),s=new oi(A$,R$,48),a=new Se(s,i);a.renderOrder=30,this.group.add(a);const r=document.createElement("div");r.className=`sap-speed-flip-overlay-label ${e.isTeamZero?"sap-speed-flip-overlay-label-blue":"sap-speed-flip-overlay-label-orange"}`,r.textContent=`${e.playerName} speed flip ${e.qualityLabel}`,this.labelRoot.append(r);const o={marker:e,ring:a,material:i,label:r};return this.views.set(e.id,o),o}}const nd=[{value:"big",label:"Big pads"},{value:"small",label:"Small pads"},{value:"ambiguous",label:"Ambiguous pads"}],Om=[{value:"both",label:"Both detectors"},{value:"inferred_only",label:"Inferred only"},{value:"reported_only",label:"Reported only"}],id=[{value:"active",label:"Active play"},{value:"inactive",label:"Inactive play"},{value:"unknown",label:"Unknown activity"}],sd=[{value:"own",label:"Own half"},{value:"opponent",label:"Opponent half"},{value:"unknown",label:"Unknown half"}];function U$(n,e){return n===e||n==="ambiguous"}function B$(n,e){const t=e?z$(e,be(e,"boost_pickup")):[];return t.length===0?null:t.find(i=>Ct(i.player_id)===n.player.id&&i.detection!=="inferred_only"&&i.frame===n.event.frame&&U$(i.pad_type,n.pad.size))??null}function z$(n,e){if(e.length>0)return e;const t=n.events?.boost_pickups;return Array.isArray(t)?t:e}function I1(n={}){let e=null,t=null,i=null,s=null,a=null,r=null;const o=new Set(nd.map(M=>M.value)),l=new Set(Om.map(M=>M.value)),c=new Set(id.map(M=>M.value)),u=new Set(sd.map(M=>M.value));let d=null,h=!1;function f(M,C,w,E){const R=document.createElement("div");R.className="boost-pickup-filter-group";const L=document.createElement("p");L.className="module-settings-group-title",L.textContent=M;const O=document.createElement("div");O.className="boost-pickup-filter-options";for(const D of C){const U=document.createElement("label");U.className="toggle";const F=document.createElement("input");F.type="checkbox",F.dataset.boostPickupFilter=E,F.dataset.boostPickupValue=D.value,F.addEventListener("change",()=>{F.checked?w.add(D.value):w.delete(D.value),_(a),n.refreshTimelineRanges?.(),n.rerenderCurrentState?.(),n.requestConfigSync?.()});const W=document.createElement("span");W.textContent=D.label,U.append(F,W),O.append(U)}return R.append(L,O),R}function p(){const M=document.createElement("div");M.className="boost-pickup-filter-group boost-pickup-filter-group-wide",i=M;const C=document.createElement("p");return C.className="module-settings-group-title",C.textContent="Player",s=document.createElement("div"),s.className="boost-pickup-filter-options",M.append(C,s),M}function g(M){if(s&&(s.replaceChildren(),i&&(i.hidden=!M||M.players.length===0),!!M))for(const C of M.players){const w=document.createElement("label");w.className="toggle";const E=document.createElement("input");E.type="checkbox",E.dataset.boostPickupPlayerId=C.id,E.addEventListener("change",()=>{d||(d=new Set(M.players.map(L=>L.id))),E.checked?d.add(C.id):d.delete(C.id),_(M),n.refreshTimelineRanges?.(),n.rerenderCurrentState?.(),n.requestConfigSync?.()});const R=document.createElement("span");R.textContent=`${C.name} (${C.isTeamZero?"Blue":"Orange"})`,w.append(E,R),s.append(w)}}function _(M){if(e){for(const C of e.querySelectorAll("input[data-boost-pickup-filter][data-boost-pickup-value]")){const w=C.dataset.boostPickupFilter,E=C.dataset.boostPickupValue;C.checked=m(w,E)}for(const C of e.querySelectorAll("input[data-boost-pickup-player-id]")){const w=C.dataset.boostPickupPlayerId;C.checked=w?d?.has(w)??!0:!1}t&&(t.textContent=v(M))}}function m(M,C){if(!C)return!1;switch(M){case"pad-type":return o.has(C);case"detection":return l.has(C);case"activity":return c.has(C);case"field-half":return u.has(C);default:return!1}}function v(M){const C=M?.players.length??0,w=d?d.size:C;if(o.size===0||l.size===0||c.size===0||u.size===0||d!==null&&d.size===0)return"Hidden";const R=[o.sizeR.value));for(const R of w)typeof R=="string"&&E.has(R)&&M.add(R)}function S(){return{padTypes:[...o],detections:[...l],activities:[...c],fieldHalves:[...u],playerIds:d?[...d]:null}}function x(M){if(!M||typeof M!="object"||Array.isArray(M))return;const C=M;b(o,nd,C.padTypes),b(l,Om,C.detections),b(c,id,C.activities),b(u,sd,C.fieldHalves),d=Array.isArray(C.playerIds)?new Set(C.playerIds.filter(w=>typeof w=="string")):null,h=a===null&&d!==null,_(a),n.refreshTimelineRanges?.(),n.rerenderCurrentState?.(),n.requestConfigSync?.()}return{setup(M){a!==M.replay&&(a=M.replay,h?h=!1:d=null),r=M.statsTimeline,_(M.replay)},teardown(){},getConfig:S,applyConfig:x,getTimelineRangeOptions(){const M={padTypes:o,detections:l,activities:c,fieldHalves:u};return d&&(M.playerIds=d),M},includePickup:y,renderSettings(M,C){if(!e){e=document.createElement("div"),e.className="boost-pickup-filter-panel";const w=document.createElement("div");w.className="boost-pickup-filter-summary",t=document.createElement("strong"),t.className="metric-readout",w.append(t);const E=document.createElement("div");E.className="boost-pickup-filter-grid",E.append(f("Pad type",nd,o,"pad-type"),f("Activity",id,c,"activity"),f("Field half",sd,u,"field-half"),p()),(C.showHeader??!1)&&e.append(w),e.append(E)}return g(M?.replay??null),_(M?.replay??null),e}}}function ui(n){return{id:n.id,label:n.label,setup(){},teardown(){},onBeforeRender(){},getTimelineEvents:n.getTimelineEvents,getTimelineRanges:n.getTimelineRanges,renderStats(e,t){const i=Ht(t.statsFrameLookup,e);return i?ci(i.players,s=>En(s.name,s.is_team_0,n.render(n.select(s),s))):""},renderFocusedPlayerStats(e,t,i){const s=Sn(i,t,e);return s?n.render(n.select(s),s):""}}}function Wi(n){return n==null?"?":Ys(n).toFixed(0)}function H$(n,e){const t=Wi(n);if(n==null||e==null)return t;const i=Wi(n+e);return`${t} (${i})`}function Fm(n){n&&typeof n=="object"&&"dispose"in n&&typeof n.dispose=="function"&&n.dispose()}function V$(n){n&&(n.removeFromParent(),n.traverse(e=>{const t="geometry"in e?e.geometry:null;Fm(t);const i="material"in e?e.material:null;if(Array.isArray(i))for(const s of i)Fm(s);else Fm(i)}))}function G$(){let n=0,e=null;return{acquire(t){e||(e=f4(t.player.sceneState.replayRoot,t.fieldScale)),n+=1},release(){n<=0||(n-=1,n===0&&(V$(e),e=null))}}}const aw=G$();function it(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function ke(n,e=1,t=""){return n===void 0||Number.isNaN(n)?"?":`${n.toFixed(e)}${t}`}function q_(n,e=0){return ke(n,e,"%")}function L1(n,e,t=1,i=0){if(n===void 0||Number.isNaN(n))return q_(e,i);const s=ke(n,t,"s");return e===void 0||Number.isNaN(e)?s:`${s} (${q_(e,i)})`}function Ya(n,e,t=1,i=0){const s=n!==void 0&&e!==void 0&&!Number.isNaN(n)&&!Number.isNaN(e)&&e>0?n*100/e:void 0;return L1(n,s,t,i)}function xt(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function ys(n){const e=xt(n);return e===void 0?void 0:e*100}function k1(n){return xt(n?.tracked_time)}function $$(n,e,t){const i=xt(n?.[e]);if(i!==void 0)return i;const s=k1(n),a=xt(n?.[t]);if(!(s===void 0||s<=0||a===void 0))return a*100/s}function Pn(n,e,t){return L1(xt(n?.[t]),$$(n,e,t))}function rw(n,e,t){const i=xt(n?.[e]);if(i!==void 0)return i;const s=k1(n),a=xt(n?.[t]);if(!(s===void 0||s<=0||a===void 0))return a/s}function ow(n){return`
Most back${Pn(n,"percent_most_back","time_most_back")}
Most forward${Pn(n,"percent_most_forward","time_most_forward")}
Mid role${Pn(n,"percent_mid_role","time_mid_role")}
@@ -5725,59 +5790,59 @@ void main() {
Behind ball${Pn(n,"percent_behind_ball","time_behind_ball")}
Level with ball${Pn(n,"percent_level_with_ball","time_level_with_ball")}
In front of ball${Pn(n,"percent_in_front_of_ball","time_in_front_of_ball")}
- `}function Qx(n){return` + `}function lw(n){return`
Defensive zone${Pn(n,"percent_defensive_third","time_defensive_third")}
Neutral zone${Pn(n,"percent_neutral_third","time_neutral_third")}
Offensive zone${Pn(n,"percent_offensive_third","time_offensive_third")}
Defensive half${Pn(n,"percent_defensive_half","time_defensive_half")}
Offensive half${Pn(n,"percent_offensive_half","time_offensive_half")}
-
To teammates${ke(Zx(n,"average_distance_to_teammates","sum_distance_to_teammates"),0)}
-
To ball${ke(Zx(n,"average_distance_to_ball","sum_distance_to_ball"),0)}
- `}function td(n,e){return qa(xt(n?.[e]),xt(n?.active_game_time))}function d$(n){return n?n.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "):"?"}function h$(n){const e=n&&n.first_man_stint_count>0?n.time_first_man/n.first_man_stint_count:void 0;return` -
Current role${d$(n?.current_role_state)}
-
First man${td(n,"time_first_man")}
+
To teammates${ke(rw(n,"average_distance_to_teammates","sum_distance_to_teammates"),0)}
+
To ball${ke(rw(n,"average_distance_to_ball","sum_distance_to_ball"),0)}
+ `}function ad(n,e){return Ya(xt(n?.[e]),xt(n?.active_game_time))}function W$(n){return n?n.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "):"?"}function X$(n){const e=n&&n.first_man_stint_count>0?n.time_first_man/n.first_man_stint_count:void 0;return` +
Current role${W$(n?.current_role_state)}
+
First man${ad(n,"time_first_man")}
First stints${it(n?.first_man_stint_count)}
Avg first stint${ke(e,2,"s")}
Longest first stint${ke(n?.longest_first_man_stint_time,2,"s")}
-
Second man${td(n,"time_second_man")}
-
Third man${td(n,"time_third_man")}
-
Ambiguous${td(n,"time_ambiguous_role")}
+
Second man${ad(n,"time_second_man")}
+
Third man${ad(n,"time_third_man")}
+
Ambiguous${ad(n,"time_ambiguous_role")}
Became first${it(n?.became_first_man_count)}
Lost first${it(n?.lost_first_man_count)}
- `}function f$(n){const e=n&&n.shots>0?n.goals*100/n.shots:void 0;return` + `}function K$(n){const e=n&&n.shots>0?n.goals*100/n.shots:void 0;return`
Score${it(n?.score)}
Goals${it(n?.goals)}
Assists${it(n?.assists)}
Saves${it(n?.saves)}
Shots${it(n?.shots)}
-
Shooting %${H_(e)}
- `}function p$(n){return` +
Shooting %${q_(e)}
+ `}function q$(n){return`
Hits${it(n?.count)}
Since last${ke(xt(n?.time_since_last_backboard),2,"s")}
- `}function m$(n){return` + `}function Y$(n){return`
Count${it(n?.count)}
Since last${ke(xt(n?.time_since_last_double_tap),2,"s")}
- `}function _$(n){const e=n&&n.completed_pass_count>0?n.total_pass_distance/n.completed_pass_count:void 0,t=n&&n.completed_pass_count>0?n.total_pass_advance/n.completed_pass_count:void 0;return` + `}function j$(n){const e=n&&n.completed_pass_count>0?n.total_pass_distance/n.completed_pass_count:void 0,t=n&&n.completed_pass_count>0?n.total_pass_advance/n.completed_pass_count:void 0;return`
Completed${it(n?.completed_pass_count)}
Received${it(n?.received_pass_count)}
Avg distance${ke(e,0)}
Avg advance${ke(t,0)}
Longest${ke(n?.longest_pass_distance,0)}
Since last${ke(xt(n?.time_since_last_completed_pass),2,"s")}
- `}function g$(n){const e=n&&n.count>0?n.total_ball_speed/n.count:void 0,t=n&&n.count>0?n.total_pass_distance/n.count:void 0;return` + `}function Z$(n){const e=n&&n.count>0?n.total_ball_speed/n.count:void 0,t=n&&n.count>0?n.total_pass_distance/n.count:void 0;return`
Attempts${it(n?.count)}
Avg speed${ke(e,0)}
Fastest${ke(n?.fastest_ball_speed,0)}
Avg pass distance${ke(t,0)}
Since last${ke(xt(n?.time_since_last_one_timer),2,"s")}
- `}function ew(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0;return` + `}function cw(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0;return`
Attempts${it(n?.count)}
High conf${it(n?.high_confidence_count)}
Last quality${ke(xt(n?.last_confidence),0,"%")}
Avg quality${ke(e,0,"%")}
Best quality${ke(xt(n?.best_confidence),0,"%")}
Since last${ke(xt(n?.time_since_last_ceiling_shot),2,"s")}
- `}function tw(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0,t=ys(e),i=n&&n.count>0?n.cumulative_setup_duration/n.count:void 0,s=n&&n.count>0?n.cumulative_takeoff_to_touch_time/n.count:void 0,a=n&&n.count>0?n.cumulative_touch_height/n.count:void 0;return` + `}function uw(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0,t=ys(e),i=n&&n.count>0?n.cumulative_setup_duration/n.count:void 0,s=n&&n.count>0?n.cumulative_takeoff_to_touch_time/n.count:void 0,a=n&&n.count>0?n.cumulative_touch_height/n.count:void 0;return`
Plays${it(n?.count)}
High conf${it(n?.high_confidence_count)}
Last quality${ke(ys(n?.last_confidence),0,"%")}
@@ -5786,7 +5851,7 @@ void main() {
Avg takeoff${ke(s,2,"s")}
Avg height${ke(a,0)}
Since last${ke(xt(n?.time_since_last_wall_aerial),2,"s")}
- `}function nw(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0,t=n&&n.count>0?n.cumulative_takeoff_to_shot_time/n.count:void 0,i=n&&n.count>0?n.cumulative_shot_height/n.count:void 0;return` + `}function dw(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0,t=n&&n.count>0?n.cumulative_takeoff_to_shot_time/n.count:void 0,i=n&&n.count>0?n.cumulative_shot_height/n.count:void 0;return`
Shots${it(n?.count)}
High conf${it(n?.high_confidence_count)}
Last quality${ke(ys(n?.last_confidence),0,"%")}
@@ -5794,13 +5859,13 @@ void main() {
Avg takeoff${ke(t,2,"s")}
Avg height${ke(i,0)}
Since last${ke(xt(n?.time_since_last_wall_aerial_shot),2,"s")}
- `}function y$(n){const e=n&&n.carry_count>0?n.average_horizontal_gap_sum/n.carry_count:void 0;return` + `}function J$(n){const e=n&&n.carry_count>0?n.average_horizontal_gap_sum/n.carry_count:void 0;return`
Carries${it(n?.carry_count)}
Total time${ke(n?.total_carry_time,1,"s")}
Longest${ke(n?.longest_carry_time,1,"s")}
Furthest${ke(n?.furthest_carry_distance,0)}
Avg gap${ke(e,0)}
- `}function v$(n){const e=n&&n.count>0?n.average_horizontal_gap_sum/n.count:void 0,t=n&&n.count>0?n.total_touch_count/n.count:void 0;return` + `}function Q$(n){const e=n&&n.count>0?n.average_horizontal_gap_sum/n.count:void 0,t=n&&n.count>0?n.total_touch_count/n.count:void 0;return`
Air dribbles${it(n?.count)}
Ground to air${it(n?.ground_to_air_count)}
Wall to air${it(n?.wall_to_air_count)}
@@ -5810,11 +5875,11 @@ void main() {
Longest${ke(n?.longest_time,1,"s")}
Furthest${ke(n?.furthest_distance,0)}
Avg gap${ke(e,0)}
- `}function b$(n){const e=n&&n.press_count>0?n.total_duration/n.press_count:void 0;return` + `}function eW(n){const e=n&&n.press_count>0?n.total_duration/n.press_count:void 0;return`
Presses${it(n?.press_count)}
Total time${ke(n?.total_duration,1,"s")}
Avg duration${ke(e,2,"s")}
- `}function x$(n){const e=n&&n.whiff_count>0?n.cumulative_closest_approach_distance/n.whiff_count:void 0;return` + `}function tW(n){const e=n&&n.whiff_count>0?n.cumulative_closest_approach_distance/n.whiff_count:void 0;return`
Whiffs${it(n?.whiff_count)}
Beaten to ball${it(n?.beaten_to_ball_count)}
Grounded${it(n?.grounded_whiff_count)}
@@ -5824,10 +5889,10 @@ void main() {
Best closest${ke(xt(n?.best_closest_approach_distance),0)}
Avg closest${ke(e,0)}
Since last${ke(xt(n?.time_since_last_whiff),2,"s")}
- `}function w$(n){return` + `}function nW(n){return`
Inflicted${it(n?.demos_inflicted)}
Taken${it(n?.demos_taken)}
- `}function S$(n){const e=n&&n.bumps_inflicted>0?n.cumulative_bump_strength/n.bumps_inflicted:void 0;return` + `}function iW(n){const e=n&&n.bumps_inflicted>0?n.cumulative_bump_strength/n.bumps_inflicted:void 0;return`
Inflicted${it(n?.bumps_inflicted)}
Taken${it(n?.bumps_taken)}
Team inflicted${it(n?.team_bumps_inflicted)}
@@ -5835,14 +5900,14 @@ void main() {
Last strength${ke(xt(n?.last_bump_strength),0)}
Max strength${ke(xt(n?.max_bump_strength),0)}
Avg strength${ke(e,0)}
- `}function T$(n){return` + `}function sW(n){return`
Refreshes${it(n?.count)}
On ball${it(n?.on_ball_count)}
- `}function M$(n){const e=n&&n.count>0?n.total_time_to_use/n.count:void 0;return` + `}function aW(n){const e=n&&n.count>0?n.total_time_to_use/n.count:void 0;return`
Confirmed${it(n?.count)}
Avg use${ke(e,2,"s")}
Fastest use${ke(xt(n?.min_time_to_use),2,"s")}
- `}function iw(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0,t=n&&n.count>0?n.cumulative_setup_duration/n.count:void 0,i=n&&n.count>0?n.cumulative_ball_speed_change/n.count:void 0;return` + `}function hw(n){const e=n&&n.count>0?n.cumulative_confidence/n.count:void 0,t=n&&n.count>0?n.cumulative_setup_duration/n.count:void 0,i=n&&n.count>0?n.cumulative_ball_speed_change/n.count:void 0;return`
Attempts${it(n?.count)}
High conf${it(n?.high_confidence_count)}
Last quality${ke(xt(n?.last_confidence),0,"%")}
@@ -5850,56 +5915,56 @@ void main() {
Avg setup${ke(t,2,"s")}
Avg impulse${ke(i,0,"uu/s")}
Since last${ke(xt(n?.time_since_last_flick),2,"s")}
- `}function sw(n){const e=n&&n.count>0?n.cumulative_quality/n.count:void 0;return` + `}function fw(n){const e=n&&n.count>0?n.cumulative_quality/n.count:void 0;return`
Attempts${it(n?.count)}
High conf${it(n?.high_confidence_count)}
Last quality${ke(xt(n?.last_quality),0,"%")}
Avg quality${ke(e,0,"%")}
Best quality${ke(xt(n?.best_quality),0,"%")}
Since last${ke(xt(n?.time_since_last_speed_flip),2,"s")}
- `}function aw(n){const e=n&&n.count>0?n.cumulative_quality/n.count:void 0,t=ys(n?.last_quality),i=ys(e),s=ys(n?.best_quality);return` + `}function pw(n){const e=n&&n.count>0?n.cumulative_quality/n.count:void 0,t=ys(n?.last_quality),i=ys(e),s=ys(n?.best_quality);return`
Attempts${it(n?.count)}
High conf${it(n?.high_confidence_count)}
Last quality${ke(t,0,"%")}
Avg quality${ke(i,0,"%")}
Best quality${ke(s,0,"%")}
Since last${ke(xt(n?.time_since_last_half_flip),2,"s")}
- `}function rw(n){const e=n&&n.count>0?n.cumulative_quality/n.count:void 0,t=ys(n?.last_quality),i=ys(e),s=ys(n?.best_quality);return` + `}function mw(n){const e=n&&n.count>0?n.cumulative_quality/n.count:void 0,t=ys(n?.last_quality),i=ys(e),s=ys(n?.best_quality);return`
Attempts${it(n?.count)}
High conf${it(n?.high_confidence_count)}
Last quality${ke(t,0,"%")}
Avg quality${ke(i,0,"%")}
Best quality${ke(s,0,"%")}
Since last${ke(xt(n?.time_since_last_wavedash),2,"s")}
- `}function ow(n){const e=n&&n.tracked_time>0?Ys(n.boost_integral/n.tracked_time).toFixed(0):"?",t=xt(n?.tracked_time);return` -
Collected${o$(n?.amount_collected,n?.amount_respawned)}
-
Inactive collected${$i(n?.amount_collected_inactive)}
-
Big pads amt${$i(n?.amount_collected_big)}
-
Small pads amt${$i(n?.amount_collected_small)}
-
Respawns${$i(n?.amount_respawned)}
-
Overfill${$i(n?.overfill_total)}
-
Used${$i(n?.amount_used)}
-
Used ground${$i(n?.amount_used_while_grounded)}
-
Used air${$i(n?.amount_used_while_airborne)}
+ `}function _w(n){const e=n&&n.tracked_time>0?Ys(n.boost_integral/n.tracked_time).toFixed(0):"?",t=xt(n?.tracked_time);return` +
Collected${H$(n?.amount_collected,n?.amount_respawned)}
+
Inactive collected${Wi(n?.amount_collected_inactive)}
+
Big pads amt${Wi(n?.amount_collected_big)}
+
Small pads amt${Wi(n?.amount_collected_small)}
+
Respawns${Wi(n?.amount_respawned)}
+
Overfill${Wi(n?.overfill_total)}
+
Used${Wi(n?.amount_used)}
+
Used ground${Wi(n?.amount_used_while_grounded)}
+
Used air${Wi(n?.amount_used_while_airborne)}
Big pads${n?.big_pads_collected??"?"}
Small pads${n?.small_pads_collected??"?"}
Inactive big pads${n?.big_pads_collected_inactive??"?"}
Inactive small pads${n?.small_pads_collected_inactive??"?"}
-
Stolen${$i(n?.amount_stolen)}
+
Stolen${Wi(n?.amount_stolen)}
Avg boost${e}
-
Time @ 0${qa(xt(n?.time_zero_boost),t)}
-
Time 0-25${qa(xt(n?.time_boost_0_25),t)}
-
Time 25-50${qa(xt(n?.time_boost_25_50),t)}
-
Time 50-75${qa(xt(n?.time_boost_50_75),t)}
-
Time 75-100${qa(xt(n?.time_boost_75_100),t)}
-
Time @ 100${qa(xt(n?.time_hundred_boost),t)}
- `}const V_={kind:{label:"Kind",valueOrder:["control","medium_hit","hard_hit"],formatValue:n=>({control:"Control",medium_hit:"Medium",hard_hit:"Hard"})[n]??n},height_band:{label:"Height",valueOrder:["ground","low_air","high_air"],formatValue:n=>({ground:"Ground",low_air:"Low air",high_air:"High air"})[n]??n},surface:{label:"Surface",valueOrder:["ground","air","wall"],formatValue:n=>({ground:"Ground",air:"Air",wall:"Wall"})[n]??n},dodge_state:{label:"Dodge",valueOrder:["no_dodge","dodge"],formatValue:n=>({no_dodge:"No dodge",dodge:"Dodge"})[n]??n}};function E$(n){const e=new Set,t=[];for(const i of n??[])e.has(i)||(e.add(i),t.push(i));return t}function oa(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function Pm(n,e=0,t=""){return n===void 0||!Number.isFinite(n)?"?":`${n.toFixed(e)}${t}`}function lw(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Ji(n,e){return`
${lw(n)}${lw(e)}
`}function C$(n,e,t){for(const i of t){const{valueOrder:s}=V_[i],a=s.indexOf(n[i]),r=s.indexOf(e[i]),o=a===-1?Number.MAX_SAFE_INTEGER:a,l=r===-1?Number.MAX_SAFE_INTEGER:r;if(o!==l)return o-l}return 0}function A$(n,e){if(e.length===1){const t=e[0];return V_[t].formatValue(n[t])}return e.map(t=>V_[t].formatValue(n[t])).join(" / ")}function R$(n){return(n?.labeled_touch_counts?.entries??[]).map(e=>({labels:e.labels,count:e.count}))}function P$(n,e){if(e.length===0||n.length===0)return"";const t=new Map;for(const i of n){const s=new Map(i.labels.map(c=>[c.key,c.value])),a={};let r=!0;for(const c of e){const u=s.get(c);if(u===void 0){r=!1;break}a[c]=u}if(!r)continue;const o=e.map(c=>`${c}:${a[c]}`).join("|"),l=t.get(o);l?l.count+=i.count:t.set(o,{values:a,count:i.count})}return[...t.values()].sort((i,s)=>C$(i.values,s.values,e)).map(i=>Ji(A$(i.values,e),oa(i.count))).join("")}function I$(n,e){if(!n||e.length!==1)return"";const[t]=e;if(t==="kind")return[Ji("Control",oa(n.control_touch_count)),Ji("Medium",oa(n.medium_hit_count)),Ji("Hard",oa(n.hard_hit_count))].join("");if(t==="height_band"){const i=n.high_aerial_touch_count??0,s=(n.aerial_touch_count??0)-i,a=(n.touch_count??0)-(n.aerial_touch_count??0);return[Ji("Ground",oa(a)),Ji("Low air",oa(s)),Ji("High air",oa(i))].join("")}return""}function cw(n,e={}){const t=E$(e.breakdownClasses),i=R$(n),s=P$(i,t)||I$(n,t);return` - ${Ji("Touches",oa(n?.touch_count))} - ${Ji("Ball advanced",Pm(n?.total_ball_advance_distance,0," uu"))} - ${Ji("Ball traveled",Pm(n?.total_ball_travel_distance,0," uu"))} - ${Ji("Ball retreated",Pm(n?.total_ball_retreat_distance,0," uu"))} +
Time @ 0${Ya(xt(n?.time_zero_boost),t)}
+
Time 0-25${Ya(xt(n?.time_boost_0_25),t)}
+
Time 25-50${Ya(xt(n?.time_boost_25_50),t)}
+
Time 50-75${Ya(xt(n?.time_boost_50_75),t)}
+
Time 75-100${Ya(xt(n?.time_boost_75_100),t)}
+
Time @ 100${Ya(xt(n?.time_hundred_boost),t)}
+ `}const Y_={kind:{label:"Kind",valueOrder:["control","medium_hit","hard_hit"],formatValue:n=>({control:"Control",medium_hit:"Medium",hard_hit:"Hard"})[n]??n},height_band:{label:"Height",valueOrder:["ground","low_air","high_air"],formatValue:n=>({ground:"Ground",low_air:"Low air",high_air:"High air"})[n]??n},surface:{label:"Surface",valueOrder:["ground","air","wall"],formatValue:n=>({ground:"Ground",air:"Air",wall:"Wall"})[n]??n},dodge_state:{label:"Dodge",valueOrder:["no_dodge","dodge"],formatValue:n=>({no_dodge:"No dodge",dodge:"Dodge"})[n]??n}};function rW(n){const e=new Set,t=[];for(const i of n??[])e.has(i)||(e.add(i),t.push(i));return t}function oa(n){return n===void 0||Number.isNaN(n)?"?":`${Math.round(n)}`}function Nm(n,e=0,t=""){return n===void 0||!Number.isFinite(n)?"?":`${n.toFixed(e)}${t}`}function gw(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Qi(n,e){return`
${gw(n)}${gw(e)}
`}function oW(n,e,t){for(const i of t){const{valueOrder:s}=Y_[i],a=s.indexOf(n[i]),r=s.indexOf(e[i]),o=a===-1?Number.MAX_SAFE_INTEGER:a,l=r===-1?Number.MAX_SAFE_INTEGER:r;if(o!==l)return o-l}return 0}function lW(n,e){if(e.length===1){const t=e[0];return Y_[t].formatValue(n[t])}return e.map(t=>Y_[t].formatValue(n[t])).join(" / ")}function cW(n){return(n?.labeled_touch_counts?.entries??[]).map(e=>({labels:e.labels,count:e.count}))}function uW(n,e){if(e.length===0||n.length===0)return"";const t=new Map;for(const i of n){const s=new Map(i.labels.map(c=>[c.key,c.value])),a={};let r=!0;for(const c of e){const u=s.get(c);if(u===void 0){r=!1;break}a[c]=u}if(!r)continue;const o=e.map(c=>`${c}:${a[c]}`).join("|"),l=t.get(o);l?l.count+=i.count:t.set(o,{values:a,count:i.count})}return[...t.values()].sort((i,s)=>oW(i.values,s.values,e)).map(i=>Qi(lW(i.values,e),oa(i.count))).join("")}function dW(n,e){if(!n||e.length!==1)return"";const[t]=e;if(t==="kind")return[Qi("Control",oa(n.control_touch_count)),Qi("Medium",oa(n.medium_hit_count)),Qi("Hard",oa(n.hard_hit_count))].join("");if(t==="height_band"){const i=n.high_aerial_touch_count??0,s=(n.aerial_touch_count??0)-i,a=(n.touch_count??0)-(n.aerial_touch_count??0);return[Qi("Ground",oa(a)),Qi("Low air",oa(s)),Qi("High air",oa(i))].join("")}return""}function yw(n,e={}){const t=rW(e.breakdownClasses),i=cW(n),s=uW(i,t)||dW(n,t);return` + ${Qi("Touches",oa(n?.touch_count))} + ${Qi("Ball advanced",Nm(n?.total_ball_advance_distance,0," uu"))} + ${Qi("Ball traveled",Nm(n?.total_ball_travel_distance,0," uu"))} + ${Qi("Ball retreated",Nm(n?.total_ball_retreat_distance,0," uu"))} ${s} - `}const G_="subtr-actor:touch-color-modes-change",L$=[{title:"Team",mode:"team"},{title:"Intention",mode:"intention"},{title:"Hit strength",mode:"kind"},{title:"Height",mode:"height_band"},{title:"Surface",mode:"surface"},{title:"Dodge",mode:"dodge_state"},{title:"Flags",mode:"flag"}];function k$(n){return L$.find(e=>e.title===n)?.mode??"team"}function D$(n){return`#${n.toString(16).padStart(6,"0")}`}function S1(n,e){n.replaceChildren();const t=So(e),i=new Set(t),s=document.createElement("div");s.className="touch-color-legend-explainer";const a=document.createElement("span");a.textContent="Toggle sections to add or remove rings";const r=document.createElement("span");r.textContent="The outermost enabled ring sets the label tint",s.append(a,r),n.append(s);for(const o of BH){const l=k$(o.title),c=i.has(l),u=document.createElement("section");u.className="touch-color-legend-group",u.dataset.active=c?"true":"false";const d=document.createElement("button");d.type="button",d.className="touch-color-legend-heading",d.dataset.colorMode=l,d.dataset.active=c?"true":"false",d.textContent=o.title,d.addEventListener("click",()=>{const f=new Set(i);f.has(l)?f.delete(l):f.add(l);const p=NH.filter(g=>f.has(g));n.dispatchEvent(new CustomEvent(G_,{bubbles:!0,detail:{colorModes:p}})),S1(n,p)});const h=document.createElement("div");h.className="touch-color-legend-list";for(const f of o.entries){const p=document.createElement("div");p.className="touch-color-legend-item";const g=document.createElement("span");g.className="touch-color-legend-swatch",g.style.background=D$(f.color);const _=document.createElement("span");_.textContent=f.label,p.append(g,_),h.append(p)}u.append(d,h),n.append(u)}}function O$(n){let e=null,t=5,i="advancement",s=["team"],a=null,r=null,o=null,l=null,c=null;const u=new Set,d=["kind","height_band","surface","dodge_state"];return{id:"touch",label:"Touch",setup(g){e=new ZH(g.player.sceneState,g.player.container,g.replay,g.statsTimeline,{mode:i,colorModes:s}),e.setDecaySeconds(t),c=_=>{if(!(_ instanceof CustomEvent))return;const m=_.detail?.colorModes;Array.isArray(m)&&p(m.filter(bd))},window.addEventListener(G_,c),h()},teardown(){c&&(window.removeEventListener(G_,c),c=null),e?.dispose(),e=null},onBeforeRender(g){e?.update(g.currentTime)},getTimelineEvents(g){return I4(g.statsTimeline,g.replay)},getConfig(){return{decaySeconds:t,overlayMode:i,overlayColorModes:s,breakdownClasses:f()}},applyConfig(g){if(g&&typeof g=="object"&&!Array.isArray(g)){const _=g;if(typeof _.decaySeconds=="number"&&Number.isFinite(_.decaySeconds)&&(t=Math.max(1,Math.min(10,_.decaySeconds)),e?.setDecaySeconds(t)),(_.overlayMode==="markers"||_.overlayMode==="advancement")&&(i=_.overlayMode,e?.setMode(i)),Array.isArray(_.overlayColorModes)?(s=So(_.overlayColorModes.filter(bd)),e?.setColorModes(s)):bd(_.overlayColorMode)&&(s=So(_.overlayColorMode),e?.setColorModes(s)),u.clear(),Array.isArray(_.breakdownClasses))for(const m of _.breakdownClasses)d.includes(m)&&u.add(m)}h(),n.rerenderCurrentState()},renderStats(g,_){const m=Ht(_.statsFrameLookup,g);return m?ci(m.players,v=>En(v.name,v.is_team_0,cw(v.touch,{breakdownClasses:f()}),v.touch?.is_last_touch?'Last Touch':"")):""},renderFocusedPlayerStats(g,_,m){const v=Sn(m,_,g);return v?cw(v.touch,{breakdownClasses:f()}):""},renderSettings(){if(!a){a=document.createElement("div"),a.className="module-settings-card";const g=document.createElement("div");g.className="module-settings-header";const _=document.createElement("div"),m=document.createElement("p");m.className="module-settings-eyebrow",m.textContent="Touch markers";const v=document.createElement("h3");v.textContent="Touch decay",_.append(m,v),r=document.createElement("strong"),r.className="metric-readout",g.append(_,r);const y=document.createElement("label"),b=document.createElement("span");b.className="label",b.textContent="Keep each marker visible after the touch";const S=document.createElement("input");S.type="range",S.min="1",S.max="10",S.step="0.5",S.value=`${t}`,S.addEventListener("input",()=>{const H=Number(S.value);t=Number.isFinite(H)?Math.max(1,Math.min(10,H)):t,e?.setDecaySeconds(t),h(t),n.requestConfigSync?.()}),y.append(b,S);const x=document.createElement("div");x.className="module-settings-subgroup";const M=document.createElement("div");M.className="module-settings-header";const C=document.createElement("div"),w=document.createElement("p");w.className="module-settings-eyebrow",w.textContent="Overlay";const E=document.createElement("h3");E.textContent="Touch mode",C.append(w,E),o=document.createElement("strong"),o.className="metric-readout",M.append(C,o);const R=document.createElement("div");R.className="module-settings-options";for(const H of[{mode:"markers",label:"Markers"},{mode:"advancement",label:"Advancement"}]){const ie=document.createElement("label");ie.className="toggle";const le=document.createElement("input");le.type="radio",le.name="touch-overlay-mode",le.dataset.overlayMode=H.mode,le.addEventListener("change",()=>{le.checked&&(i=H.mode,e?.setMode(i),h(),n.requestConfigSync?.())});const me=document.createElement("span");me.textContent=H.label,ie.append(le,me),R.append(ie)}x.append(M,R);const L=document.createElement("div");L.className="module-settings-subgroup";const O=document.createElement("div");O.className="module-settings-header";const D=document.createElement("div"),U=document.createElement("p");U.className="module-settings-eyebrow",U.textContent="Stat display";const F=document.createElement("h3");F.textContent="Touch breakdown",D.append(U,F),l=document.createElement("strong"),l.className="metric-readout",O.append(D,l);const W=document.createElement("div");W.className="module-settings-options";for(const H of[{className:"kind",label:"Kind"},{className:"height_band",label:"Height"},{className:"surface",label:"Surface"},{className:"dodge_state",label:"Dodge"}]){const ie=document.createElement("label");ie.className="toggle";const le=document.createElement("input");le.type="checkbox",le.dataset.breakdownClass=H.className,le.addEventListener("change",()=>{le.checked?u.add(H.className):u.delete(H.className),h(),n.rerenderCurrentState(),n.requestConfigSync?.()});const me=document.createElement("span");me.textContent=H.label,ie.append(le,me),W.append(ie)}L.append(O,W),a.append(g,y,x,L)}return h(),a}};function h(g){if(!a)return;const _=g??t,m=a.querySelector("input");m instanceof HTMLInputElement&&(m.value=`${_}`),r&&(r.textContent=`${_.toFixed(1)}s`);for(const v of a.querySelectorAll("input[data-overlay-mode]"))v.checked=v.dataset.overlayMode===i;o&&(o.textContent=i==="advancement"?"Advancement":"Markers");for(const v of a.querySelectorAll("input[data-breakdown-class]")){const y=v.dataset.breakdownClass;v.checked=y?u.has(y):!1}if(l){const v=f();l.textContent=v.length>0?v.map(y=>({kind:"Kind",height_band:"Height",surface:"Surface",dodge_state:"Dodge"})[y]).join(" + "):"Total only"}}function f(){return d.filter(g=>u.has(g))}function p(g){s=So(g),e?.setColorModes(s),h(),n.requestConfigSync?.()}}function F$(n,e=b1({refreshTimelineRanges:n.refreshTimelineRanges,rerenderCurrentState:n.rerenderCurrentState})){return{id:"boost",label:"Boost",setup(t){e.setup(t)},teardown(){e.teardown()},onBeforeRender(){},getTimelineRanges(t){return mG(t.statsTimeline,t.replay,e.getTimelineRangeOptions())},getConfig(){return e.getConfig()},applyConfig(t){e.applyConfig(t)},includeBoostPickupAnimationPickup(t){return e.includePickup(t)},renderStats(t,i){const s=Ht(i.statsFrameLookup,t);return s?ci(s.players,a=>En(a.name,a.is_team_0,ow(a.boost))):""},renderFocusedPlayerStats(t,i,s){const a=Sn(s,i,t);return a?ow(a.boost):""},renderSettings(t){return e.renderSettings(t,{showHeader:!0})}}}function N$(){return ui({id:"core",label:"Core",select:n=>n.core,render:n=>f$(n)})}function U$(){return ui({id:"backboard",label:"Backboard",select:n=>n.backboard,render:n=>p$(n),getTimelineEvents(n){return L4(n.statsTimeline,n.replay)}})}function B$(){let n=null;return{id:"ceiling-shot",label:"Ceiling Shot",setup(e){n=new w4(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},renderStats(e,t){const i=Ht(t.statsFrameLookup,e);return i?ci(i.players,s=>En(s.name,s.is_team_0,ew(s.ceiling_shot),s.ceiling_shot?.is_last_ceiling_shot?'Last Ceiling Shot':"")):""},renderFocusedPlayerStats(e,t,i){const s=Sn(i,t,e);return s?ew(s.ceiling_shot):""}}}function z$(){return{id:"wall-aerial",label:"Wall-to-Air Setup",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=Ht(e.statsFrameLookup,n);return t?ci(t.players,i=>En(i.name,i.is_team_0,tw(i.wall_aerial),i.wall_aerial?.is_last_wall_aerial?'Last Wall-to-Air Setup':"")):""},renderFocusedPlayerStats(n,e,t){const i=Sn(t,e,n);return i?tw(i.wall_aerial):""}}}function H$(){return{id:"wall-aerial-shot",label:"Wall Shot",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=Ht(e.statsFrameLookup,n);return t?ci(t.players,i=>En(i.name,i.is_team_0,nw(i.wall_aerial_shot),i.wall_aerial_shot?.is_last_wall_aerial_shot?'Last Wall Shot':"")):""},renderFocusedPlayerStats(n,e,t){const i=Sn(t,e,n);return i?nw(i.wall_aerial_shot):""}}}function V$(){return ui({id:"ball-carry",label:"Ball Carry",select:n=>n.ball_carry,render:n=>y$(n)})}function G$(){return ui({id:"air-dribble",label:"Air Dribble",select:n=>n.air_dribble,render:n=>v$(n)})}function $$(){return ui({id:"dodge-reset",label:"Dodge Refresh",select:n=>n.dodge_reset,render:n=>T$(n)})}function W$(){return ui({id:"flip-reset",label:"Flip Reset",select:n=>n.flip_reset,render:n=>M$(n)})}function X$(){return ui({id:"double-tap",label:"Double Tap",select:n=>n.double_tap,render:n=>m$(n)})}function K$(){return ui({id:"pass",label:"Pass",select:n=>n.pass,render:n=>_$(n)})}function q$(){return ui({id:"one-timer",label:"One-timer",select:n=>n.one_timer,render:n=>g$(n)})}function Y$(){return{id:"flick",label:"Flick",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=Ht(e.statsFrameLookup,n);return t?ci(t.players,i=>En(i.name,i.is_team_0,iw(i.flick),i.flick?.is_last_flick?'Last Flick':"")):""},renderFocusedPlayerStats(n,e,t){const i=Sn(t,e,n);return i?iw(i.flick):""}}}function j$(){let n=null;return{id:"speed-flip",label:"Speed Flip",setup(e){n=new i$(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},renderStats(e,t){const i=Ht(t.statsFrameLookup,e);return i?ci(i.players,s=>En(s.name,s.is_team_0,sw(s.speed_flip),s.speed_flip?.is_last_speed_flip?'Last Speed Flip':"")):""},renderFocusedPlayerStats(e,t,i){const s=Sn(i,t,e);return s?sw(s.speed_flip):""}}}function Z$(){let n=null;return{id:"dodge",label:"Dodge",setup(e){n=new $G(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},getTimelineEvents(e){return W4(e.statsTimeline,e.replay)},renderStats(e,t){const i=new Map;for(const a of t.replay.players)i.set(a.id,{name:a.name,isTeamZero:a.isTeamZero,count:0});for(const a of be(t.statsTimeline,"dodge")){const r=Ct(a.player),o=t.replay.players.find(c=>c.id===r)??null,l=i.get(r)??{name:o?.name??r,isTeamZero:a.is_team_0,count:0};l.count+=1,i.set(r,l)}const s=[...i.values()].filter(a=>a.count>0);return s.length===0?"":`
${[!0,!1].map(a=>{const r=s.filter(l=>l.isTeamZero===a);if(r.length===0)return"";const o=a?"Blue":"Orange";return`
+ `}const j_="subtr-actor:touch-color-modes-change",hW=[{title:"Team",mode:"team"},{title:"Intention",mode:"intention"},{title:"Hit strength",mode:"kind"},{title:"Height",mode:"height_band"},{title:"Surface",mode:"surface"},{title:"Dodge",mode:"dodge_state"},{title:"Flags",mode:"flag"}];function fW(n){return hW.find(e=>e.title===n)?.mode??"team"}function pW(n){return`#${n.toString(16).padStart(6,"0")}`}function D1(n,e){n.replaceChildren();const t=Mo(e),i=new Set(t),s=document.createElement("div");s.className="touch-color-legend-explainer";const a=document.createElement("span");a.textContent="Toggle sections to add or remove rings";const r=document.createElement("span");r.textContent="The outermost enabled ring sets the label tint",s.append(a,r),n.append(s);for(const o of vV){const l=fW(o.title),c=i.has(l),u=document.createElement("section");u.className="touch-color-legend-group",u.dataset.active=c?"true":"false";const d=document.createElement("button");d.type="button",d.className="touch-color-legend-heading",d.dataset.colorMode=l,d.dataset.active=c?"true":"false",d.textContent=o.title,d.addEventListener("click",()=>{const f=new Set(i);f.has(l)?f.delete(l):f.add(l);const p=gV.filter(g=>f.has(g));n.dispatchEvent(new CustomEvent(j_,{bubbles:!0,detail:{colorModes:p}})),D1(n,p)});const h=document.createElement("div");h.className="touch-color-legend-list";for(const f of o.entries){const p=document.createElement("div");p.className="touch-color-legend-item";const g=document.createElement("span");g.className="touch-color-legend-swatch",g.style.background=pW(f.color);const _=document.createElement("span");_.textContent=f.label,p.append(g,_),h.append(p)}u.append(d,h),n.append(u)}}function mW(n){let e=null,t=5,i="advancement",s=["team"],a=null,r=null,o=null,l=null,c=null;const u=new Set,d=["kind","height_band","surface","dodge_state"];return{id:"touch",label:"Touch",setup(g){e=new IV(g.player.sceneState,g.player.container,g.replay,g.statsTimeline,{mode:i,colorModes:s}),e.setDecaySeconds(t),c=_=>{if(!(_ instanceof CustomEvent))return;const m=_.detail?.colorModes;Array.isArray(m)&&p(m.filter(Md))},window.addEventListener(j_,c),h()},teardown(){c&&(window.removeEventListener(j_,c),c=null),e?.dispose(),e=null},onBeforeRender(g){e?.update(g.currentTime)},getTimelineEvents(g){return dG(g.statsTimeline,g.replay)},getConfig(){return{decaySeconds:t,overlayMode:i,overlayColorModes:s,breakdownClasses:f()}},applyConfig(g){if(g&&typeof g=="object"&&!Array.isArray(g)){const _=g;if(typeof _.decaySeconds=="number"&&Number.isFinite(_.decaySeconds)&&(t=Math.max(1,Math.min(10,_.decaySeconds)),e?.setDecaySeconds(t)),(_.overlayMode==="markers"||_.overlayMode==="advancement")&&(i=_.overlayMode,e?.setMode(i)),Array.isArray(_.overlayColorModes)?(s=Mo(_.overlayColorModes.filter(Md)),e?.setColorModes(s)):Md(_.overlayColorMode)&&(s=Mo(_.overlayColorMode),e?.setColorModes(s)),u.clear(),Array.isArray(_.breakdownClasses))for(const m of _.breakdownClasses)d.includes(m)&&u.add(m)}h(),n.rerenderCurrentState()},renderStats(g,_){const m=Ht(_.statsFrameLookup,g);return m?ci(m.players,v=>En(v.name,v.is_team_0,yw(v.touch,{breakdownClasses:f()}),v.touch?.is_last_touch?'Last Touch':"")):""},renderFocusedPlayerStats(g,_,m){const v=Sn(m,_,g);return v?yw(v.touch,{breakdownClasses:f()}):""},renderSettings(){if(!a){a=document.createElement("div"),a.className="module-settings-card";const g=document.createElement("div");g.className="module-settings-header";const _=document.createElement("div"),m=document.createElement("p");m.className="module-settings-eyebrow",m.textContent="Touch markers";const v=document.createElement("h3");v.textContent="Touch decay",_.append(m,v),r=document.createElement("strong"),r.className="metric-readout",g.append(_,r);const y=document.createElement("label"),b=document.createElement("span");b.className="label",b.textContent="Keep each marker visible after the touch";const S=document.createElement("input");S.type="range",S.min="1",S.max="10",S.step="0.5",S.value=`${t}`,S.addEventListener("input",()=>{const H=Number(S.value);t=Number.isFinite(H)?Math.max(1,Math.min(10,H)):t,e?.setDecaySeconds(t),h(t),n.requestConfigSync?.()}),y.append(b,S);const x=document.createElement("div");x.className="module-settings-subgroup";const M=document.createElement("div");M.className="module-settings-header";const C=document.createElement("div"),w=document.createElement("p");w.className="module-settings-eyebrow",w.textContent="Overlay";const E=document.createElement("h3");E.textContent="Touch mode",C.append(w,E),o=document.createElement("strong"),o.className="metric-readout",M.append(C,o);const R=document.createElement("div");R.className="module-settings-options";for(const H of[{mode:"markers",label:"Markers"},{mode:"advancement",label:"Advancement"}]){const ie=document.createElement("label");ie.className="toggle";const le=document.createElement("input");le.type="radio",le.name="touch-overlay-mode",le.dataset.overlayMode=H.mode,le.addEventListener("change",()=>{le.checked&&(i=H.mode,e?.setMode(i),h(),n.requestConfigSync?.())});const me=document.createElement("span");me.textContent=H.label,ie.append(le,me),R.append(ie)}x.append(M,R);const L=document.createElement("div");L.className="module-settings-subgroup";const O=document.createElement("div");O.className="module-settings-header";const D=document.createElement("div"),U=document.createElement("p");U.className="module-settings-eyebrow",U.textContent="Stat display";const F=document.createElement("h3");F.textContent="Touch breakdown",D.append(U,F),l=document.createElement("strong"),l.className="metric-readout",O.append(D,l);const W=document.createElement("div");W.className="module-settings-options";for(const H of[{className:"kind",label:"Kind"},{className:"height_band",label:"Height"},{className:"surface",label:"Surface"},{className:"dodge_state",label:"Dodge"}]){const ie=document.createElement("label");ie.className="toggle";const le=document.createElement("input");le.type="checkbox",le.dataset.breakdownClass=H.className,le.addEventListener("change",()=>{le.checked?u.add(H.className):u.delete(H.className),h(),n.rerenderCurrentState(),n.requestConfigSync?.()});const me=document.createElement("span");me.textContent=H.label,ie.append(le,me),W.append(ie)}L.append(O,W),a.append(g,y,x,L)}return h(),a}};function h(g){if(!a)return;const _=g??t,m=a.querySelector("input");m instanceof HTMLInputElement&&(m.value=`${_}`),r&&(r.textContent=`${_.toFixed(1)}s`);for(const v of a.querySelectorAll("input[data-overlay-mode]"))v.checked=v.dataset.overlayMode===i;o&&(o.textContent=i==="advancement"?"Advancement":"Markers");for(const v of a.querySelectorAll("input[data-breakdown-class]")){const y=v.dataset.breakdownClass;v.checked=y?u.has(y):!1}if(l){const v=f();l.textContent=v.length>0?v.map(y=>({kind:"Kind",height_band:"Height",surface:"Surface",dodge_state:"Dodge"})[y]).join(" + "):"Total only"}}function f(){return d.filter(g=>u.has(g))}function p(g){s=Mo(g),e?.setColorModes(s),h(),n.requestConfigSync?.()}}function _W(n,e=I1({refreshTimelineRanges:n.refreshTimelineRanges,rerenderCurrentState:n.rerenderCurrentState})){return{id:"boost",label:"Boost",setup(t){e.setup(t)},teardown(){e.teardown()},onBeforeRender(){},getTimelineRanges(t){return YG(t.statsTimeline,t.replay,e.getTimelineRangeOptions())},getConfig(){return e.getConfig()},applyConfig(t){e.applyConfig(t)},includeBoostPickupAnimationPickup(t){return e.includePickup(t)},renderStats(t,i){const s=Ht(i.statsFrameLookup,t);return s?ci(s.players,a=>En(a.name,a.is_team_0,_w(a.boost))):""},renderFocusedPlayerStats(t,i,s){const a=Sn(s,i,t);return a?_w(a.boost):""},renderSettings(t){return e.renderSettings(t,{showHeader:!0})}}}function gW(){return ui({id:"core",label:"Core",select:n=>n.core,render:n=>K$(n)})}function yW(){return ui({id:"backboard",label:"Backboard",select:n=>n.backboard,render:n=>q$(n),getTimelineEvents(n){return hG(n.statsTimeline,n.replay)}})}function vW(){let n=null;return{id:"ceiling-shot",label:"Ceiling Shot",setup(e){n=new nG(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},renderStats(e,t){const i=Ht(t.statsFrameLookup,e);return i?ci(i.players,s=>En(s.name,s.is_team_0,cw(s.ceiling_shot),s.ceiling_shot?.is_last_ceiling_shot?'Last Ceiling Shot':"")):""},renderFocusedPlayerStats(e,t,i){const s=Sn(i,t,e);return s?cw(s.ceiling_shot):""}}}function bW(){return{id:"wall-aerial",label:"Wall-to-Air Setup",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=Ht(e.statsFrameLookup,n);return t?ci(t.players,i=>En(i.name,i.is_team_0,uw(i.wall_aerial),i.wall_aerial?.is_last_wall_aerial?'Last Wall-to-Air Setup':"")):""},renderFocusedPlayerStats(n,e,t){const i=Sn(t,e,n);return i?uw(i.wall_aerial):""}}}function xW(){return{id:"wall-aerial-shot",label:"Wall Shot",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=Ht(e.statsFrameLookup,n);return t?ci(t.players,i=>En(i.name,i.is_team_0,dw(i.wall_aerial_shot),i.wall_aerial_shot?.is_last_wall_aerial_shot?'Last Wall Shot':"")):""},renderFocusedPlayerStats(n,e,t){const i=Sn(t,e,n);return i?dw(i.wall_aerial_shot):""}}}function wW(){return ui({id:"ball-carry",label:"Ball Carry",select:n=>n.ball_carry,render:n=>J$(n)})}function SW(){return ui({id:"air-dribble",label:"Air Dribble",select:n=>n.air_dribble,render:n=>Q$(n)})}function TW(){return ui({id:"dodge-reset",label:"Dodge Refresh",select:n=>n.dodge_reset,render:n=>sW(n)})}function MW(){return ui({id:"flip-reset",label:"Flip Reset",select:n=>n.flip_reset,render:n=>aW(n)})}function EW(){return ui({id:"double-tap",label:"Double Tap",select:n=>n.double_tap,render:n=>Y$(n)})}function CW(){return ui({id:"pass",label:"Pass",select:n=>n.pass,render:n=>j$(n)})}function AW(){return ui({id:"one-timer",label:"One-timer",select:n=>n.one_timer,render:n=>Z$(n)})}function RW(){return{id:"flick",label:"Flick",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=Ht(e.statsFrameLookup,n);return t?ci(t.players,i=>En(i.name,i.is_team_0,hw(i.flick),i.flick?.is_last_flick?'Last Flick':"")):""},renderFocusedPlayerStats(n,e,t){const i=Sn(t,e,n);return i?hw(i.flick):""}}}function PW(){let n=null;return{id:"speed-flip",label:"Speed Flip",setup(e){n=new N$(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},renderStats(e,t){const i=Ht(t.statsFrameLookup,e);return i?ci(i.players,s=>En(s.name,s.is_team_0,fw(s.speed_flip),s.speed_flip?.is_last_speed_flip?'Last Speed Flip':"")):""},renderFocusedPlayerStats(e,t,i){const s=Sn(i,t,e);return s?fw(s.speed_flip):""}}}function IW(){let n=null;return{id:"dodge",label:"Dodge",setup(e){n=new T$(e.player.sceneState,e.player.container,e.replay,e.statsTimeline)},teardown(){n?.dispose(),n=null},onBeforeRender(e){n?.update(e.currentTime)},getTimelineEvents(e){return MG(e.statsTimeline,e.replay)},renderStats(e,t){const i=new Map;for(const a of t.replay.players)i.set(a.id,{name:a.name,isTeamZero:a.isTeamZero,count:0});for(const a of be(t.statsTimeline,"dodge")){const r=Ct(a.player),o=t.replay.players.find(c=>c.id===r)??null,l=i.get(r)??{name:o?.name??r,isTeamZero:a.is_team_0,count:0};l.count+=1,i.set(r,l)}const s=[...i.values()].filter(a=>a.count>0);return s.length===0?"":`
${[!0,!1].map(a=>{const r=s.filter(l=>l.isTeamZero===a);if(r.length===0)return"";const o=a?"Blue":"Orange";return`

${o} team

${r.length} player${r.length===1?"":"s"} @@ -5907,7 +5972,7 @@ void main() {
${r.map(l=>En(l.name,l.isTeamZero,`
Events${l.count}
`)).join("")}
-
`}).join("")}
`},renderFocusedPlayerStats(e,t,i){return`
Events${be(i.statsTimeline,"dodge").filter(a=>Ct(a.player)===e).length}
`}}}function J$(){return{id:"half-flip",label:"Half Flip",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=Ht(e.statsFrameLookup,n);return t?ci(t.players,i=>En(i.name,i.is_team_0,aw(i.half_flip),i.half_flip?.is_last_half_flip?'Last Half Flip':"")):""},renderFocusedPlayerStats(n,e,t){const i=Sn(t,e,n);return i?aw(i.half_flip):""}}}function Q$(){return{id:"wavedash",label:"Wavedash",setup(){},teardown(){},onBeforeRender(){},getTimelineEvents(n){return K4(n.statsTimeline,n.replay)},renderStats(n,e){const t=Ht(e.statsFrameLookup,n);return t?ci(t.players,i=>En(i.name,i.is_team_0,rw(i.wavedash),i.wavedash?.is_last_wavedash?'Last Wavedash':"")):""},renderFocusedPlayerStats(n,e,t){const i=Sn(t,e,n);return i?rw(i.wavedash):""}}}function eW(){return ui({id:"whiff",label:"Whiff",select:n=>n.whiff,render:n=>x$(n),getTimelineEvents(n){return J4(n.statsTimeline,n.replay)}})}function tW(n){let e=null,t=null;const i=new Set,s=["speed_band","height_band"];return{id:"movement",label:"Movement",setup(){a()},teardown(){},onBeforeRender(){},getConfig(){return{breakdownClasses:r()}},applyConfig(o){if(i.clear(),o&&typeof o=="object"&&!Array.isArray(o)){const l=o.breakdownClasses;if(Array.isArray(l))for(const c of l)s.includes(c)&&i.add(c)}a(),n.rerenderCurrentState()},renderStats(o,l){const c=Ht(l.statsFrameLookup,o);return c?ci(c.players,u=>En(u.name,u.is_team_0,Kx(u.movement,{breakdownClasses:r()}))):""},renderFocusedPlayerStats(o,l,c){const u=Sn(c,l,o);return u?Kx(u.movement,{breakdownClasses:r()}):""},renderSettings(){if(!e){e=document.createElement("div"),e.className="module-settings-card";const o=document.createElement("div");o.className="module-settings-header";const l=document.createElement("div"),c=document.createElement("p");c.className="module-settings-eyebrow",c.textContent="Stat display";const u=document.createElement("h3");u.textContent="Movement breakdown",l.append(c,u),t=document.createElement("strong"),t.className="metric-readout",o.append(l,t);const d=document.createElement("div");d.className="module-settings-options";for(const h of[{className:"speed_band",label:"Speed band"},{className:"height_band",label:"Height band"}]){const f=document.createElement("label");f.className="toggle";const p=document.createElement("input");p.type="checkbox",p.dataset.breakdownClass=h.className,p.addEventListener("change",()=>{p.checked?i.add(h.className):i.delete(h.className),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const g=document.createElement("span");g.textContent=h.label,f.append(p,g),d.append(f)}e.append(o,d)}return a(),e}};function a(){if(e){for(const o of e.querySelectorAll("input[data-breakdown-class]")){const l=o.dataset.breakdownClass;o.checked=l?i.has(l):!1}if(t){const o=r();t.textContent=o.length>0?o.map(l=>({speed_band:"Speed band",height_band:"Height band"})[l]).join(" + "):"Total only"}}}function r(){return s.filter(o=>i.has(o))}}function nW(){return ui({id:"powerslide",label:"Powerslide",select:n=>n.powerslide,render:n=>b$(n),getTimelineEvents(n){return G4(n.statsTimeline,n.replay)}})}function iW(){return ui({id:"rotation",label:"Rotation",select:n=>n.rotation,render:n=>h$(n)})}function sW(){return ui({id:"demo",label:"Demo",select:n=>n.demo,render:n=>w$(n)})}function aW(){return ui({id:"bump",label:"Bump",select:n=>n.bump,render:n=>S$(n),getTimelineEvents(n){return q4(n.statsTimeline,n.replay)}})}function rW(){let n=null,e=1;return{id:_1,label:"Relative Positioning",setup(t){e=t.fieldScale,n=new PV(t.player.sceneState.replayRoot,t.replay,e)},teardown(){n?.dispose(),n=null},onBeforeRender(t){n?.update(t,e)},renderStats(t,i){const s=Ht(i.statsFrameLookup,t);return s?ci(s.players,a=>{const r=wG(i.replay,Ct(a.player_id),t),o=xG[r];return En(a.name,a.is_team_0,Jx(a.positioning),`${o}`)}):""},renderFocusedPlayerStats(t,i,s){const a=Sn(s,i,t);return a?Jx(a.positioning):""}}}function oW(){return{id:"absolute-positioning",label:"Absolute Positioning",setup(n){jx.acquire(n)},teardown(){jx.release()},onBeforeRender(){},getTimelineRanges(n){return bG(n.statsTimeline,n.replay)},renderStats(n,e){const t=Ht(e.statsFrameLookup,n);return t?ci(t.players,i=>En(i.name,i.is_team_0,Qx(i.positioning))):""},renderFocusedPlayerStats(n,e,t){const i=Sn(t,e,n);return i?Qx(i.positioning):""}}}function lW(n,e={}){return[N$(),U$(),B$(),z$(),H$(),X$(),q$(),K$(),SG(n),TG(),MG(),EG(),CG(),rW(),oW(),iW(),Z$(),j$(),J$(),Q$(),O$(n),eW(),Y$(),$$(),W$(),G$(),F$(n,e.boostPickupFilters),V$(),tW(n),nW(),sW(),aW()]}const cW=new Set(["player_id","name","is_team_0"]),uW=["is_last_","time_since_last_","frames_since_last_"];function dW(n){return n===null||typeof n=="number"||typeof n=="string"||typeof n=="boolean"||Array.isArray(n)}function hW(n,e){let t=n;for(const i of e){if(!t||typeof t!="object"||Array.isArray(t))return;t=t[i]}return t}function fW(n){return n==null?"--":typeof n=="number"?Number.isFinite(n)?Number.isInteger(n)?`${n}`:`${Number(n.toFixed(3))}`:"--":typeof n=="boolean"?n?"true":"false":Array.isArray(n)?n.length===0?"[]":JSON.stringify(n):`${n}`}function pW(n,e){if(uW.some(a=>n.startsWith(a)))return!0;const t=n.match(/^last_(.+)_time$/),i=n.match(/^last_(.+)_frame$/),s=t?.[1]??i?.[1];return s?`is_last_${s}`in e||`time_since_last_${s}`in e||`frames_since_last_${s}`in e:!1}function $_(n,e,t,i){if(!n||typeof n!="object"||Array.isArray(n))return;const s=n;for(const[a,r]of Object.entries(s)){if(e==="player"&&t.length===0&&cW.has(a)||pW(a,s))continue;const o=[...t,a];if(dW(r)){const l=`${e}:${o.join(".")}`;i.push({id:l,label:o.join("."),category:o[0]??e,scope:e,path:o,read(c){return hW(c,o)},format:fW});continue}$_(r,e,o,i)}}function mW(n){const e=new Set;return n.filter(t=>e.has(t.id)?!1:(e.add(t.id),!0))}function T1(n,e){const t=[];return n&&$_(n,"player",[],t),e&&$_(e,"team",[],t),mW(t).sort((i,s)=>i.label.localeCompare(s.label))}function _W(){return T1(cy(),Bo())}function zo(n){return n?T1(n.players[0]??cy(),n.team_zero??n.team_one??Bo()):_W()}function M1(n){return n.toLowerCase().replace(/[_/.-]+/g," ").replace(/\s+/g," ").trim()}function gW(n){return M1(n).split(" ").filter(Boolean)}function yW(n,e){const t=gW(e);if(t.length===0)return 0;const i=M1([n.scope,n.category,n.label,n.id,...n.path].join(" "));let s=0;for(const a of t){const r=i.indexOf(a);if(r<0)return null;s+=r}return s+i.length/1e3}function vW(n,e){return n.map((t,i)=>({definition:t,index:i,score:yW(t,e)})).filter(t=>t.score!==null).sort((t,i)=>t.score-i.score||t.index-i.index).map(t=>t.definition)}function ds(n){if(!Number.isFinite(n))return"--";const e=Math.floor(Math.max(0,n)/60),t=Math.max(0,n)-e*60;return`${e}:${t.toFixed(1).padStart(4,"0")}`}class bW{constructor(e){this.options=e}statsWindows=new Map;nextStatsWindowId=1;getConfigs(){return[...this.statsWindows.values()].map(e=>({id:e.id,kind:e.kind,placement:this.options.readWindowPlacement(e.element),playerId:e.playerId,team:e.team,entries:e.entries.map(t=>({statId:t.statId,targetId:t.targetId}))}))}clear(){for(const e of this.statsWindows.values())e.element.remove();this.statsWindows.clear(),this.nextStatsWindowId=1}replaceFromConfig(e){this.clear();for(const t of e)this.create(t.kind,t)}render(e=this.options.getReplayPlayer()?.getState().frameIndex??0,t={}){for(const i of this.statsWindows.values())t.preserveOpenPickers&&(i.pickerOpen||i.element.contains(document.activeElement))||this.renderStatsWindow(i,e)}create(e,t){const i=t?.id??`stats-${this.nextStatsWindowId++}`,s=Number.parseInt(i.replace(/^stats-/,""),10);Number.isFinite(s)&&(this.nextStatsWindowId=Math.max(this.nextStatsWindowId,s+1));const{x:a,y:r}=this.getStatsWindowDefaultPosition(),o=document.createElement("section");o.className="stats-window",o.dataset.windowId=i,o.style.setProperty("--window-x",`${a}px`),o.style.setProperty("--window-y",`${r}px`),t&&this.options.applyWindowPlacement(o,t.placement);const l=document.createElement("header");l.className="stats-window-header";const c=document.createElement("div");c.className="stats-window-actions";const u=document.createElement("button");if(u.type="button",u.className="stats-window-action",u.textContent="Hide",c.append(u),this.hasStatsWindowScopeSelector(e))l.classList.add("stats-window-header-actions-only"),l.append(c);else{const f=document.createElement("h2");f.textContent=this.getStatsWindowTitle(e),l.append(f,c)}const d=document.createElement("div");d.className="stats-window-body",o.append(l,d),this.options.layer.append(o);const h={id:i,kind:e,entries:t?.entries.map(f=>({key:`${i}:${f.statId}:${f.targetId??"scope"}`,statId:f.statId,targetId:f.targetId}))??[],playerId:t?.playerId??this.options.getReplayPlayer()?.replay.players[0]?.id??null,team:t?.team??"blue",pickerOpen:!1,query:"",element:o,body:d};return u.addEventListener("click",()=>{o.hidden=!0,this.options.requestConfigSync()}),this.statsWindows.set(i,h),t||this.options.bringWindowToFront(o),this.options.setLauncherOpen(!1),this.renderStatsWindow(h),this.options.requestConfigSync(),h}getStatById(e){return this.options.getStatRegistry().find(t=>t.id===e)??null}getCurrentStatsFrame(e){const t=this.options.getStatsFrameLookup();return t?Ht(t,e):null}getTeamSnapshot(e,t){return t==="blue"?e.team_zero??null:e.team_one??null}getTeamLabel(e){return e==="blue"?"Blue":"Orange"}getPlayerTeamClass(e){const t=this.options.getReplayPlayer()?.replay.players.find(i=>i.id===e);return t?ca(t.isTeamZero):null}getTeamScopeClass(e){return ca(e==="blue")}appendGroupedPlayerOptions(e,t){const i=this.options.getReplayPlayer()?.replay.players??[];for(const s of["blue","orange"]){const a=i.filter(o=>o.isTeamZero===(s==="blue"));if(a.length===0)continue;const r=document.createElement("optgroup");r.label=`${this.getTeamLabel(s)} team`;for(const o of a)r.append(new Option(o.name,o.id,o.id===t,o.id===t));e.append(r)}}getStatsWindowScopeTeamClass(e){return e.kind==="player"?this.getPlayerTeamClass(e.playerId):e.kind==="team"?this.getTeamScopeClass(e.team??"blue"):null}getStatTargetTeamClass(e,t){return e.scope==="player"?this.getPlayerTeamClass(t):this.getTeamScopeClass(t==="orange"?"orange":"blue")}getStatsWindowTitle(e){switch(e){case"player":return"Player stats";case"team":return"Team stats";case"all-players":return"All players stats";case"all-teams":return"All teams stats";case"kickoff-overview":return"Kickoff details";case"goals-overview":return"Goal labels";case"ad-hoc":return"Ad hoc stats"}}hasStatsWindowScopeSelector(e){return e==="player"||e==="team"}hasStatsWindowStatPicker(e){return e!=="goals-overview"&&e!=="kickoff-overview"}getStatsWindowAllowedScope(e){switch(e){case"player":case"all-players":return"player";case"team":case"all-teams":return"team";case"kickoff-overview":return null;case"goals-overview":return null;case"ad-hoc":return null}}getStatsWindowDefaultPosition(){const e=this.statsWindows.size*18;return{x:Math.max(12,Math.min(window.innerWidth-360,96+e)),y:Math.max(64,Math.min(window.innerHeight-240,96+e))}}renderStatsWindow(e,t=this.options.getReplayPlayer()?.getState().frameIndex??0){const i=document.activeElement,s=i instanceof HTMLInputElement&&i.dataset.statsWindowSearch===e.id,a=s?i.selectionStart:null,r=s?i.selectionEnd:null,o=s?i.selectionDirection:null;if(e.body.replaceChildren(),this.renderStatsWindowScope(e),this.hasStatsWindowStatPicker(e.kind)&&(this.renderStatsWindowAddControl(e),this.renderStatsWindowPicker(e)),this.renderStatsWindowEntries(e,t),s){const l=e.body.querySelector(`input[data-stats-window-search="${e.id}"]`);l?.focus({preventScroll:!0}),l&&a!==null&&r!==null&&l.setSelectionRange(a,r,o??"none")}}renderStatsWindowScope(e){if(e.kind!=="player"&&e.kind!=="team")return;const t=document.createElement("div");t.className="stats-window-scope-row";const i=document.createElement("select");i.className="stats-window-scope-select";const s=this.getStatsWindowScopeTeamClass(e);s&&i.classList.add(s),i.setAttribute("aria-label",e.kind==="player"?"Player stats target":"Team stats target"),e.kind==="player"?(this.appendGroupedPlayerOptions(i,e.playerId),i.value=e.playerId??"",i.addEventListener("change",()=>{e.playerId=i.value||null,this.renderStatsWindow(e),this.options.requestConfigSync()})):(i.append(new Option("Blue","blue",e.team==="blue",e.team==="blue"),new Option("Orange","orange",e.team==="orange",e.team==="orange")),i.value=e.team??"blue",i.addEventListener("change",()=>{e.team=i.value==="orange"?"orange":"blue",this.renderStatsWindow(e),this.options.requestConfigSync()})),t.append(i),e.body.append(t)}renderStatsWindowAddControl(e){const t=document.createElement("button");if(t.type="button",t.className="stats-window-add-button",t.textContent="+",t.title="Add stat",t.setAttribute("aria-label","Add stat"),t.setAttribute("aria-expanded",String(e.pickerOpen)),this.activateButton(t,()=>{e.pickerOpen=!e.pickerOpen,this.renderStatsWindow(e)}),this.hasStatsWindowScopeSelector(e.kind)){e.body.querySelector(".stats-window-scope-row")?.append(t);return}const i=document.createElement("div");i.className="stats-window-toolbar",i.append(t),e.body.append(i)}activateButton(e,t){let i=!1;e.addEventListener("pointerdown",s=>{e.disabled||(i=!0,s.preventDefault(),t())}),e.addEventListener("click",()=>{if(i){i=!1;return}e.disabled||t()})}renderStatsWindowPicker(e){const t=document.createElement("div");if(t.className="stats-window-picker",t.hidden=!e.pickerOpen,t.hidden){e.body.append(t);return}const i=this.getStatsWindowAllowedScope(e.kind),s=document.createElement("input");s.type="search",s.placeholder="Search stats",s.value=e.query,s.dataset.statsWindowSearch=e.id;const a=document.createElement("div");a.className="stats-window-picker-list",s.addEventListener("input",()=>{e.query=s.value,this.renderStatsWindowPickerList(e,a,i)}),this.renderStatsWindowPickerList(e,a,i),t.append(s,a),e.body.append(t)}renderStatsWindowPickerList(e,t,i){t.replaceChildren();const s=this.options.getStatRegistry(),a=i?s.filter(l=>l.scope===i):s,r=vW(a,e.query),o=new Map;for(const l of r){const c=o.get(l.category)??[];c.push(l),o.set(l.category,c)}for(const[l,c]of o){if(c.length<2)continue;const u=document.createElement("button");u.type="button",u.className="stats-window-picker-item",u.innerHTML=`Add all ${l}${c.length}`,this.activateButton(u,()=>{for(const d of c)this.addStatToWindow(e,d);this.renderStatsWindow(e),this.options.requestConfigSync()}),t.append(u)}for(const l of r){const c=document.createElement("button");c.type="button",c.className="stats-window-picker-item",c.innerHTML=`${l.label}${l.scope}`,c.disabled=e.kind!=="ad-hoc"&&e.entries.some(u=>u.statId===l.id),this.activateButton(c,()=>{this.addStatToWindow(e,l),this.renderStatsWindow(e),this.options.requestConfigSync()}),t.append(c)}if(r.length===0){const l=document.createElement("p");l.className="stat-window-empty",l.textContent=s.length===0?"No stats available.":"No matching stats.",t.append(l)}}addStatToWindow(e,t){const i=e.kind==="ad-hoc"?this.getDefaultAdHocTargetId(t):void 0;e.entries.some(s=>s.statId===t.id&&s.targetId===i)||e.entries.push({key:`${e.id}:${t.id}:${i??"scope"}`,statId:t.id,targetId:i})}getDefaultAdHocTargetId(e){return e.scope==="player"?this.options.getReplayPlayer()?.replay.players[0]?.id??"":"blue"}removeStatFromWindow(e,t){const i=e.entries.findIndex(s=>s.key===t);i>=0&&e.entries.splice(i,1)}renderStatsWindowEntries(e,t){if(e.kind==="goals-overview"){this.renderGoalLabelsOverview(e);return}if(e.kind==="kickoff-overview"){this.renderKickoffOverview(e,t);return}const i=this.getStatsWindowAllowedScope(e.kind),s=e.entries.map(r=>({entry:r,definition:this.getStatById(r.statId)})).filter(r=>r.definition!==null&&(!i||r.definition.scope===i));if(s.length===0){const r=document.createElement("p");r.className="stat-window-empty",r.textContent="No stats added.",e.body.append(r);return}const a=this.getCurrentStatsFrame(t);if(!a){const r=document.createElement("p");r.className="stat-window-empty",r.textContent="Load a replay to show stats.",e.body.append(r);return}if(e.kind==="all-players"){this.renderAllPlayersStats(e,a,s);return}if(e.kind==="all-teams"){this.renderAllTeamsStats(e,a,s);return}if(e.kind==="player"){const r=e.playerId?a.players.find(o=>Ct(o.player_id)===e.playerId)??null:null;this.renderScopedStatList(e,r,s);return}if(e.kind==="team"){this.renderScopedStatList(e,this.getTeamSnapshot(a,e.team??"blue"),s);return}e.kind==="ad-hoc"&&this.renderAdHocStats(e,a,s)}renderGoalLabelsOverview(e){const t=this.options.getStatsTimeline(),i=this.options.getReplayPlayer()?.replay??null;if(!t||!i){this.appendStatsWindowEmpty(e,"Load a replay to show goal labels.");return}const s=[...be(t,"goal_context")].sort((o,l)=>o.time-l.time),a=s.map((o,l)=>l);if(a.length===0){this.appendStatsWindowEmpty(e,"No goals loaded.");return}const r=document.createElement("div");r.className="goal-label-list";for(const o of a){const l=s[o]??null,c=[...l?.tags??[]].sort((M,C)=>M.kind.localeCompare(C.kind)||C.metadata.confidence-M.metadata.confidence),u=l?.time??0,d=l?.scorer??null,h=d?Ct(d):null,f=d?i.players.find(M=>M.id===h)?.name??h:"Unknown scorer",p=l?.scoring_team_is_team_0??null,g=document.createElement("section");g.className="goal-label-item",p!==null&&g.classList.add(ca(p));const _=document.createElement("header"),m=document.createElement("h3");m.textContent=`Goal ${o+1}`;const v=document.createElement("span");v.textContent=`${ds(u)} · ${f}`,_.append(m,v);const y=document.createElement("div");if(y.className="goal-label-tags",c.length===0){const M=document.createElement("span");M.className="goal-label-tag goal-label-tag-empty",M.textContent="Unlabeled",y.append(M)}else for(const M of c){const C=document.createElement("span");C.className="goal-label-tag";const w=r1(M);C.textContent=`${Dn(M.kind)} ${Math.round(M.metadata.confidence*100)}%${w?` - ${w}`:""}`,y.append(C)}const b=document.createElement("div");b.className="goal-label-actions";const S=document.createElement("button");S.type="button",S.className="goal-label-watch",S.textContent="Watch",S.addEventListener("click",()=>{this.options.watchGoalReplay(u,h)});const x=document.createElement("button");x.type="button",x.textContent="Cue",x.addEventListener("click",()=>{this.options.cueGoalReplay(u)}),b.append(S,x),g.append(_,y,b),r.append(g)}e.body.append(r)}renderKickoffOverview(e,t){const i=this.options.getStatsTimeline(),s=this.options.getReplayPlayer()?.replay??null;if(!i||!s){this.appendStatsWindowEmpty(e,"Load a replay to show kickoff details.");return}const a=this.getClosestKickoffEvent(i,t);if(!a){this.appendStatsWindowEmpty(e,"No kickoff events loaded.");return}const r=a.payload.payload,o=document.createElement("section");o.className="kickoff-overview";const l=document.createElement("header");l.className="kickoff-overview-hero";const c=document.createElement("div"),u=document.createElement("h3");u.textContent=this.formatKickoffTitle(a);const d=document.createElement("span");d.textContent=`Nearest kickoff · resolved at ${ds(r.end_time)}`,c.append(u,d);const h=document.createElement("strong"),f=this.teamClassFromNullable(r.winning_team_is_team_0);h.className="kickoff-overview-victor",f&&h.classList.add(f),h.textContent=this.formatOutcome(r),l.append(c,h);const p=document.createElement("div");p.className="kickoff-overview-summary",p.append(this.renderKickoffMetric("Win strength",`${this.formatNullableNumber(r.win_strength,2)} · ${this.formatKickoffLabelValue("kickoff_win_strength",r.win_strength_band)}`),this.renderKickoffMetric("First touch",this.formatFirstTouch(r)),this.renderKickoffMetric("Advantage",this.formatAdvantage(r)),this.renderKickoffMetric("Contested",this.formatContested(r)));const g=document.createElement("div");g.className="kickoff-detail-grid",g.append(this.renderKickoffDetail("Kickoff start",ds(r.start_time)),this.renderKickoffDetail("Movement start",ds(r.movement_start_time)),this.renderKickoffDetail("Live action",r.live_action_start_time===null?"--":ds(r.live_action_start_time)),this.renderKickoffDetail("First touch",r.first_touch_time===null?"--":ds(r.first_touch_time)),this.renderKickoffDetail("Resolution",ds(r.end_time)),this.renderKickoffDetail("After first touch",this.formatSeconds(r.advantage_seconds_after_first_touch)));const _=document.createElement("div");_.className="kickoff-strategy-list",_.append(this.renderKickoffTeamStrategy("Blue",r.team_zero_taker,r.team_zero_non_takers),this.renderKickoffTeamStrategy("Orange",r.team_one_taker,r.team_one_non_takers)),o.append(l,p,g,_),e.body.append(o)}getClosestKickoffEvent(e,t){return pc(e).filter(s=>s.payload.kind==="kickoff").sort((s,a)=>{const r=this.kickoffFrameDistance(s.payload.payload,t),o=this.kickoffFrameDistance(a.payload.payload,t);return r!==o?r-o:s.payload.payload.start_frame-a.payload.payload.start_frame})[0]??null}kickoffFrameDistance(e,t){return t>=e.start_frame&&t<=e.end_frame?0:Math.min(Math.abs(t-e.start_frame),Math.abs(t-e.end_frame))}renderKickoffMetric(e,t){const i=document.createElement("div");i.className="kickoff-metric";const s=document.createElement("span");s.textContent=e;const a=document.createElement("strong");return a.textContent=t,i.append(s,a),i}renderKickoffDetail(e,t){const i=document.createElement("div");i.className="kickoff-detail-row";const s=document.createElement("span");s.textContent=e;const a=document.createElement("strong");return a.textContent=t,i.append(s,a),i}renderKickoffTeamStrategy(e,t,i){const s=document.createElement("section");s.className=`kickoff-strategy-team ${e==="Blue"?"team-blue":"team-orange"}`;const a=document.createElement("h4");a.textContent=e,s.append(a);const r=document.createElement("p");if(r.className="kickoff-strategy-line",r.textContent=t?`${this.getPlayerName(t.player)}: ${this.formatKickoffLabelValue("kickoff_approach",t.approach)} from ${this.formatKickoffLabelValue("kickoff_spawn",t.spawn_position)} (${this.formatKickoffLabelValue("taker_outcome",t.outcome)}, ${this.formatSeconds(t.time_to_ball)})`:"No taker detected",s.append(r),i.length>0){const o=document.createElement("ul");o.className="kickoff-support-list";for(const l of i){const c=document.createElement("li");c.textContent=`${this.getPlayerName(l.player)}: ${this.formatKickoffLabelValue("support_behavior",l.support_behavior)} from ${this.formatKickoffLabelValue("kickoff_spawn",l.spawn_position)}`,o.append(c)}s.append(o)}return s}formatOutcome(e){return e.winning_team_is_team_0===!0?"Blue wins":e.winning_team_is_team_0===!1?"Orange wins":e.outcome==="neutral"?"Neutral":"Unknown"}formatFirstTouch(e){if(!e.first_touch_player)return"--";const t=e.first_touch_team_is_team_0===!0?"Blue":e.first_touch_team_is_team_0===!1?"Orange":"Unknown",i=e.first_touch_time===null?"--":ds(e.first_touch_time);return`${t} · ${this.getPlayerName(e.first_touch_player)} · ${i}`}formatAdvantage(e){if(e.advantage==="no_advantage")return"No advantage";const t=e.advantage_team_is_team_0===!0?"Blue":e.advantage_team_is_team_0===!1?"Orange":"Unknown",i=e.advantage.replace(/^team_(zero|one)_/,""),s=e.advantage_player?` · ${this.getPlayerName(e.advantage_player)}`:"",a=e.advantage_time===null?"":` · ${ds(e.advantage_time)}`;return`${t} ${this.formatKickoffLabelValue("kickoff_advantage",i)}${s}${a}`}formatContested(e){return e.kickoff_possession_outcome==="contested"?"Yes":e.kickoff_possession_team_is_team_0===!0?`No · Blue ${this.formatPossessionOutcome(e.kickoff_possession_outcome)}`:e.kickoff_possession_team_is_team_0===!1?`No · Orange ${this.formatPossessionOutcome(e.kickoff_possession_outcome)}`:`No · ${this.formatPossessionOutcome(e.kickoff_possession_outcome)}`}formatPossessionOutcome(e){return e.endsWith("_advantage")?"advantage":e.endsWith("_possession")?"possession":this.formatKickoffLabelValue("kickoff_possession_outcome",e)}formatKickoffType(e){return this.formatKickoffLabelValue("kickoff_type",e)}formatKickoffTitle(e){const t=e.payload.payload,i=this.formatKickoffDirection(t.kickoff_direction),s=[this.formatKickoffType(t.kickoff_type),i].filter(Boolean).join(" ");return[e.meta.label,s].filter(Boolean).join(" · ")}formatKickoffDirection(e){return e==="unknown"?"":`(${this.formatKickoffLabelValue("kickoff_direction",e)})`}formatNullableNumber(e,t){return e===null||!Number.isFinite(e)?"--":e.toFixed(t)}formatSeconds(e){return e===null||!Number.isFinite(e)?"--":`${e.toFixed(2)}s`}formatLabel(e){return e.replace(/^team_zero_/,"blue_").replace(/^team_one_/,"orange_").replaceAll("_"," ").replace(/\b\w/g,t=>t.toUpperCase())}formatKickoffLabelValue(e,t){const i=t.replace(/^team_zero_/,"blue_").replace(/^team_one_/,"orange_");return e==="kickoff_advantage"?this.formatLabel(i.replace(/^blue_/,"").replace(/^orange_/,"")):e==="kickoff_possession_outcome"?this.formatLabel(i.replace(/^blue_/,"Blue ").replace(/^orange_/,"Orange ")):this.formatLabel(i)}teamClassFromNullable(e){return e===null?null:ca(e)}getPlayerName(e){const t=Ct(e);return this.options.getReplayPlayer()?.replay.players.find(i=>i.id===t)?.name??t}appendStatsWindowEmpty(e,t){const i=document.createElement("p");i.className="stat-window-empty",i.textContent=t,e.body.append(i)}renderScopedStatList(e,t,i){const s=document.createElement("div");s.className="stats-window-stat-list";for(const{entry:a,definition:r}of i)s.append(this.renderStatRow(e,a,r,t?r.format(r.read(t)):"--"));e.body.append(s)}renderAllPlayersStats(e,t,i){const s=document.createElement("div");s.className="stats-window-team-list";for(const a of["blue","orange"]){const r=t.players.filter(h=>h.is_team_0===(a==="blue"));if(r.length===0)continue;const o=document.createElement("section");o.className=`stats-window-team-group ${this.getTeamScopeClass(a)}`;const l=document.createElement("header");l.className="stats-window-team-header";const c=document.createElement("h3");c.textContent=`${this.getTeamLabel(a)} team`;const u=document.createElement("span");u.textContent=`${r.length} player${r.length===1?"":"s"}`,l.append(c,u),o.append(l);const d=document.createElement("div");d.className="stats-window-entity-list";for(const h of r){const f=document.createElement("section");f.className=`stats-window-entity ${ca(h.is_team_0)}`;const p=document.createElement("h4");p.className="stats-window-entity-title",p.textContent=h.name,f.append(p);for(const{entry:g,definition:_}of i)f.append(this.renderStatRow(e,g,_,_.format(_.read(h))));d.append(f)}o.append(d),s.append(o)}e.body.append(s)}renderAllTeamsStats(e,t,i){const s=document.createElement("div");s.className="stats-window-entity-list";for(const a of["blue","orange"]){const r=this.getTeamSnapshot(t,a),o=document.createElement("section");o.className=`stats-window-entity ${this.getTeamScopeClass(a)}`;const l=document.createElement("h3");l.className="stats-window-entity-title",l.textContent=this.getTeamLabel(a),o.append(l);for(const{entry:c,definition:u}of i)o.append(this.renderStatRow(e,c,u,r?u.format(u.read(r)):"--"));s.append(o)}e.body.append(s)}renderAdHocStats(e,t,i){const s=document.createElement("div");s.className="stats-window-stat-list";for(const{entry:a,definition:r}of i){const o=this.getAdHocTarget(t,r,a.targetId);s.append(this.renderStatRow(e,a,r,o?r.format(r.read(o)):"--"))}e.body.append(s)}getAdHocTarget(e,t,i){return t.scope==="player"?e.players.find(s=>Ct(s.player_id)===i)??e.players[0]??null:this.getTeamSnapshot(e,i==="orange"?"orange":"blue")}renderStatRow(e,t,i,s){const a=document.createElement("div");a.className="stats-window-stat-row";const r=document.createElement("span");if(r.className="stats-window-stat-name",r.textContent=i.label,e.kind==="ad-hoc"){const c=document.createElement("select");c.className="stats-window-stat-target";const u=this.getStatTargetTeamClass(i,t.targetId);u&&c.classList.add(u),i.scope==="player"?this.appendGroupedPlayerOptions(c,t.targetId):c.append(new Option("Blue","blue",t.targetId==="blue",t.targetId==="blue"),new Option("Orange","orange",t.targetId==="orange",t.targetId==="orange")),c.value=t.targetId??"",c.addEventListener("change",()=>{const d=c.value;if(e.entries.some(f=>f!==t&&f.statId===t.statId&&f.targetId===d)){this.renderStatsWindow(e);return}const h=e.entries.findIndex(f=>f.key===t.key);h>=0&&(e.entries[h]={key:`${e.id}:${t.statId}:${d}`,statId:t.statId,targetId:d}),this.renderStatsWindow(e),this.options.requestConfigSync()}),r.append(" ",c)}const o=document.createElement("span");o.className="stats-window-stat-value",o.textContent=s;const l=document.createElement("button");return l.type="button",l.className="stats-window-stat-remove",l.textContent="x",l.addEventListener("click",()=>{this.removeStatFromWindow(e,t.key),this.renderStatsWindow(e),this.options.requestConfigSync()}),a.append(r,o,l),a}}function xW(n){return new bW(n)}const wW=new Set(["module:dodge","module:touch","module:powerslide"]),SW=["stats-stream:"],Mh=["#3b82f6","#06b6d4","#22c55e","#a855f7","#f97316","#ef4444","#f59e0b","#ec4899"],Pf="#d1d9e0",gy=Mh[0],yy=Mh[4],TW=[{id:"core",label:"Shots, saves, assists",buildEvents(n){return n.replay.timelineEvents.filter(e=>e.kind==="shot"||e.kind==="save"||e.kind==="assist")}},{id:"demo",label:"Demos",buildEvents(n){return n.replay.timelineEvents.filter(e=>e.kind==="demo")}}],MW=[];function E1(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function C1(n){if(typeof n=="string"&&n.length>0)return n;if(!E1(n))return null;const[e,t]=Object.entries(n)[0]??[];return!e||t==null?null:typeof t=="string"||typeof t=="number"?`${e}:${t}`:`${e}:${JSON.stringify(t)}`}function A1(n){return n.split(/[_-]+/).filter(e=>e.length>0).map(e=>e.slice(0,1).toUpperCase()).join("").slice(0,3)||"E"}function EW(n){if(typeof n!="number"||!Number.isFinite(n))return null;const e=Math.abs(n)<1?2:1;return`${n.toFixed(e).replace(/\.0+$/,"").replace(/(\.\d*[1-9])0+$/,"$1")}s`}function ji(n){return typeof n!="string"||n.length===0?null:n.split(/[_-]+/).filter(e=>e.length>0).map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1)}`).join(" ")}function CW(n){return n==="team_zero_side"?"Blue side":n==="team_one_side"?"Orange side":n==="neutral"?"Neutral zone":ji(n)}function AW(n){const e=ji(n);return e?`${e.toLowerCase()} third`:null}function RW(n){return n==="team_zero_third"?"Blue third":n==="team_one_third"?"Orange third":n==="neutral_third"?"Neutral third":ji(n)}function PW(n){return n==="team_zero"?"Blue":n==="team_one"?"Orange":n==="neutral"?"Neutral":ji(n)}function Md(n){return E1(n.payload.payload)?n.payload.payload:{}}function R1(n){return n===!0?gy:n===!1?yy:null}function IW(n){return n==="team_zero_side"?gy:n==="team_one_side"?yy:n==="neutral"?Pf:null}function LW(n){return n==="team_zero"?gy:n==="team_one"?yy:n==="neutral"?Pf:null}function kW(n){return typeof n=="boolean"?R1(n):null}const DW={ball_half(n){return IW(Md(n).field_half)},possession(n){return LW(Md(n).possession_state)},player_possession(n){return kW(Md(n).is_team_0)}};function P1(n,e,t){return DW[n]?.(e)??R1(t)??Pf}function mi(n){return n.filter(e=>!!e).join(" | ")}function OW({event:n,playerName:e,streamLabel:t,teamLabel:i}){const s=Md(n),a=EW(s.duration);if(n.payload.kind==="ball_half"){const r=CW(s.field_half),o=s.active===!1?"Ball half inactive":r?`Ball on ${r.toLowerCase()}`:null;return mi([o??t,a])}if(n.payload.kind==="ball_third"){const r=RW(s.field_third),o=s.active===!1?"Ball third inactive":r?`Ball in ${r.toLowerCase()}`:null;return mi([o??t,a])}if(n.payload.kind==="territorial_pressure"){const r=ji(s.end_reason),o=`${i??""} territorial pressure`.trim();return mi([r?`${o} ended: ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="possession"){const r=PW(s.possession_state),o=AW(s.field_third),l=r?`${r} possession`:t;return mi([l,o,a])}if(n.payload.kind==="controlled_play"){const r=e?`${e} controlled play`:t;return mi([r,a])}if(n.payload.kind==="ball_carry"){const r=e?`${e} ${t.toLowerCase()}`:t;return mi([r,a])}if(n.payload.kind==="player_activity"){const r=ji(s.state),o=e?`${e} positioning`:t;return mi([r?`${o} ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="field_third"){const r=ji(s.state),o=e?`${e} positioning`:t;return mi([r?`${o} in ${r.toLowerCase()} third`:o,a])}if(n.payload.kind==="field_half"){const r=ji(s.state),o=e?`${e} positioning`:t;return mi([r?`${o} in ${r.toLowerCase()} half`:o,a])}if(n.payload.kind==="ball_depth"){const r=ji(s.state),o=e?`${e} ball depth`:t;return mi([r?`${o}: ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="depth_role"){const r=ji(s.state),o=e?`${e} depth role`:t;return mi([r?`${o}: ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="shadow_defense"){const r=e?`${e} shadow defense`:t;return mi([r,a])}if(n.payload.kind==="rotation_role"){const r=ji(s.state),o=e?`${e} rotation`:t;return mi([r?`${o}: ${r.toLowerCase()}`:o,a])}return e?`${e} ${t.toLowerCase()}`:t}function FW(n,e,t){const i=Dn(e),s=new Map(n.replay.players.map(a=>[a.id,a.name]));return t.flatMap((a,r)=>{const o=a.meta.timing.type==="moment"?{time:a.meta.timing.time,frame:a.meta.timing.frame}:{time:a.meta.timing.end_time,frame:a.meta.timing.end_frame},l=C1(a.meta.primary_player),c=l?s.get(l)??l:null,u=a.meta.team_is_team_0??null,d=u==null?null:u?"Blue":"Orange",h=a.meta.id||`${e}:${o.frame??o.time}:${r}`,f=P1(e,a,u);return[{id:`stats-stream:${h}`,time:n.replay.frames[o.frame??-1]?.time??o.time,frame:o.frame,kind:e,label:OW({event:a,playerName:c,streamLabel:i,teamLabel:d}),shortLabel:A1(e),playerId:l,playerName:c,isTeamZero:u,color:f}]})}function NW(n,e,t){const i=Dn(e),s=new Map(n.replay.players.map(a=>[a.id,a.name]));return t.flatMap((a,r)=>{if(a.meta.timing.type!=="span")return[];const o={startTime:a.meta.timing.start_time,endTime:a.meta.timing.end_time,startFrame:a.meta.timing.start_frame,endFrame:a.meta.timing.end_frame},l=a.meta.team_is_team_0??null,c=l==null?null:l?"Blue":"Orange",u=C1(a.meta.primary_player),d=u?s.get(u)??u:null,h=P1(e,a,l),f=a.meta.id||`${e}:${o.startFrame??o.startTime}:${o.endFrame??o.endTime}:${r}`,p=d?`${d} ${i.toLowerCase()}`:c?`${c} ${i.toLowerCase()}`:i;let g=`stats-stream:${e}`,_=i;return a.meta.scope==="player"&&u?(g=`stats-stream:${e}:player:${u}`,_=d?`${d} ${i.toLowerCase()}`:i):a.meta.scope==="team"&&l!=null&&(g=`stats-stream:${e}:team:${l?"0":"1"}`,_=c?`${c} ${i.toLowerCase()}`:i),[{id:`stats-stream:${f}`,startTime:n.replay.frames[o.startFrame??-1]?.time??o.startTime,endTime:Math.max(n.replay.frames[o.startFrame??-1]?.time??o.startTime,n.replay.frames[o.endFrame??-1]?.time??o.endTime),lane:g,laneLabel:_,label:p,shortLabel:A1(e),isTeamZero:l,color:h}]}).sort((a,r)=>a.startTime!==r.startTime?a.startTime-r.startTime:(a.id??"").localeCompare(r.id??""))}function UW(n,e,t,i){return[...new Set([...gM,...pc(n.statsTimeline).map(a=>a.meta.stream)])].flatMap(a=>{const r=pc(n.statsTimeline).filter(u=>u.meta.stream===a);if(i.has(a)&&r.length>0)return[];const o=r.some(u=>u.meta.timing.type==="span"),l=o?NW(n,a,r):[],c=FW(n,a,r);return[{id:`stats-stream:${a}`,playlistId:`stats-stream:${a}`,timelineKey:`stats-stream:${a}`,timelineId:`stats-stream:${a}`,group:"Event streams",label:Dn(a),count:o?l.length:c.length,active:e.has(`stats-stream:${a}`),buildTimelineEvents(){return o?[]:c},buildPlaylistEvents(){return c},buildTimelineRanges:o?()=>l:void 0,setActive(u){t(`stats-stream:${a}`,u)}}]})}function BW(n){return new Set([...n.filter(e=>e.getTimelineEvents).map(e=>e.id),...l1])}function zW(){return[...l1].sort((n,e)=>Dn(n).localeCompare(Dn(e)))}function HW({ctx:n,modules:e,activeTimelineEventSourceIds:t,activeMechanicTimelineKinds:i,toggleEventSource:s,setMechanicTimelineKind:a}){if(!n)return[];const r=[];for(const o of TW){const l=o.buildEvents(n),c=l.length;r.push({id:o.id,playlistId:`replay:${o.id}`,timelineKey:`events:${o.id}`,timelineId:`events:${o.id}`,group:"Replay",label:o.label,count:c,active:t.has(o.id),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){s(o.id,u)}})}for(const o of e.filter(l=>l.getTimelineEvents)){const l=o.getTimelineEvents?.(n)??[],c=l.length;r.push({id:o.id,playlistId:`module:${o.id}`,timelineKey:`module:${o.id}`,timelineId:`module:${o.id}`,group:"Stats",label:o.label,count:c,active:t.has(o.id),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){s(o.id,u)}})}for(const o of MW){const l=o.buildEvents(n),c=l.length;r.push({id:o.id,playlistId:`extra:${o.id}`,timelineKey:`extra:${o.id}`,timelineId:`extra:${o.id}`,group:"Stats",label:o.label,count:c,active:t.has(o.id),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){s(o.id,u)}})}r.push(...UW(n,t,s,BW(e)));for(const o of zW()){const l=o1[o](n.statsTimeline,n.replay),c=l.length;r.push({id:`mechanic:${o}`,playlistId:`mechanic:${o}`,timelineKey:`mechanic:${o}`,timelineId:`mechanic:${o}`,group:"Event types",label:Dn(o),count:c,active:i.has(o),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){a(o,u)}})}return r.sort((o,l)=>o.label.localeCompare(l.label))}function VW(n,e){if(!n)return[];const t=[{id:"replay:goals",group:"Replay",label:"Goals",events:n.replay.timelineEvents.filter(s=>s.kind==="goal")}],i=e.map(s=>({id:s.playlistId,group:s.group,label:s.label,events:s.buildPlaylistEvents()}));return[...t,...i]}function W_(n,e){const t=n.map(i=>i.id);return e===null?new Set(t.filter(i=>!wW.has(i)&&!SW.some(s=>i.startsWith(s)))):new Set(t.filter(i=>e.has(i)))}function GW(n,e){const t=n.playerId??null,i=t?e.findIndex(s=>s.id===t):-1;return i>=0?Mh[i%Mh.length]:n.color??Pf}function $W({sources:n,activeSourceIds:e,replayPlayers:t}){const i=W_(n,e);return n.filter(s=>i.has(s.id)).flatMap(s=>s.events.map((a,r)=>({key:`${s.id}:${a.id??`${a.kind}:${a.time}:${r}`}`,sourceId:s.id,sourceLabel:s.label,event:a,color:GW(a,t)}))).sort((s,a)=>s.event.time!==a.event.time?s.event.time-a.event.time:(s.event.label??s.sourceLabel).localeCompare(a.event.label??a.sourceLabel))}class WW{constructor(e){this.options=e}getSources(e=this.options.getContext()){return HW({ctx:e,modules:this.options.modules,activeTimelineEventSourceIds:this.options.getActiveTimelineEventSourceIds(),activeMechanicTimelineKinds:this.options.getActiveMechanicTimelineKinds(),toggleEventSource:this.options.toggleEventSource,setMechanicTimelineKind:this.options.setMechanicTimelineKind})}countVisibleSources(e){return e.replay.timelineEvents.filter(i=>i.kind==="goal").length+this.getSources(e).filter(i=>i.active).reduce((i,s)=>i+s.count,0)}render(){const{body:e}=this.options;e.replaceChildren();const t=this.getSources();if(t.length===0){const d=document.createElement("p");d.className="stat-window-empty",d.textContent="No events loaded.",e.append(d);return}const i=document.createElement("div");i.className="mechanics-actions";const s=document.createElement("button");s.type="button",s.className="module-summary-item",s.addEventListener("click",()=>{for(const d of t)d.setActive(!0);this.options.setupActiveModules(),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.render(),this.options.renderModuleSummary(),this.options.renderModuleSettings(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()});const a=document.createElement("span");a.textContent="All events";const r=document.createElement("strong");r.textContent=`${t.length}`,s.append(a,r);const o=document.createElement("button");o.type="button",o.className="module-summary-item",o.addEventListener("click",()=>{for(const d of t)d.setActive(!1);this.options.setupActiveModules(),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.render(),this.options.renderModuleSummary(),this.options.renderModuleSettings(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()});const l=document.createElement("span");l.textContent="No events";const c=document.createElement("strong");c.textContent="Off",o.append(l,c),i.append(s,o),e.append(i);const u=this.renderSourceList(t);u&&e.append(u)}renderSourceList(e){if(e.length===0)return null;const t=document.createElement("div");t.className="module-list mechanics-list mechanics-event-list",t.style.setProperty("--event-source-columns",`${XW(e.length)}`);for(const i of e){const s=document.createElement("button");s.type="button",s.className="module-summary-item",s.dataset.active=i.active?"true":"false",s.setAttribute("aria-pressed",i.active?"true":"false"),s.addEventListener("click",()=>{i.setActive(!i.active),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.render(),this.options.renderTimelineEventCount()});const a=document.createElement("span");a.textContent=i.label;const r=document.createElement("strong");r.textContent=`${i.active?"On":"Off"} ${i.count}`,s.append(a,r),t.append(s)}return t}}function XW(n){return window.innerWidth<640?1:window.innerWidth<900?n>=7?2:1:n>=13?3:n>=7?2:1}function KW(n){return new WW(n)}const qW=new Set(["ceiling-shot","fifty-fifty","ball_half",_1,"absolute-positioning","dodge","speed-flip","touch"]),uw="touch";class YW{constructor(e){this.options=e}renderSummary(){const{summary:e}=this.options.elements;e.replaceChildren();const t=this.options.getTimelineSources(),i=t.map(o=>this.renderTimelineSourceToggle(o)),s=[],a=[],r=this.options.getContext();for(const o of this.options.modules){const l=qW.has(o.id);!o.getTimelineEvents&&!o.getTimelineRanges&&!l||(t.length===0&&o.getTimelineEvents&&i.push(this.renderCapabilityToggle(o.id,Lm(o,"events"),"events")),o.getTimelineRanges&&s.push(this.renderCapabilityToggle(o.id,Lm(o,"ranges"),"ranges",r?o.getTimelineRanges(r).length:void 0)),l&&a.push(this.renderCapabilityToggle(o.id,Lm(o,"effects"),"effects")))}a.push(this.renderBoostPickupAnimationToggle()),e.append(Im("Timeline markers",i),Im("Timeline ranges",s),Im("In-game visualizations",a))}renderSettings(){const{settings:e}=this.options.elements;e.replaceChildren();const t=this.options.getContext(),i=this.options.getActiveModules().filter(s=>s.id!=="boost"&&s.id!==uw).map(s=>s.renderSettings?.(t)??null).filter(s=>s instanceof HTMLElement);if(i.length===0){e.hidden=!0,this.renderBoostPickupFiltersWindow(),this.renderTouchControlsWindow();return}e.hidden=!1,e.append(...i),this.renderBoostPickupFiltersWindow(),this.renderTouchControlsWindow()}renderBoostPickupAnimationToggle(){const e=this.options.getBoostPickupAnimationEnabled(),t=document.createElement("button");t.type="button",t.className="module-summary-item",t.dataset.active=e?"true":"false",t.setAttribute("aria-pressed",e?"true":"false"),t.addEventListener("click",this.options.toggleBoostPickupAnimation);const i=document.createElement("span");i.textContent="Boost pickup animation";const s=document.createElement("strong");return s.textContent=e?"On":"Off",t.append(i,s),t}renderCapabilityToggle(e,t,i,s){const r=this.options.getActiveCapabilityIds(i).has(e),o=document.createElement("button");o.type="button",o.className="module-summary-item",o.dataset.active=r?"true":"false",o.setAttribute("aria-pressed",r?"true":"false"),o.addEventListener("click",()=>{this.options.toggleCapability(e,i,!this.options.getActiveCapabilityIds(i).has(e))});const l=document.createElement("span");l.textContent=t;const c=document.createElement("strong");return c.textContent=dw(r,s),o.append(l,c),o}renderTimelineSourceToggle(e){const t=document.createElement("button");t.type="button",t.className="module-summary-item",t.dataset.active=e.active?"true":"false",t.setAttribute("aria-pressed",e.active?"true":"false"),t.addEventListener("click",()=>{e.setActive(!e.active),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.options.renderTimelineEventCount(),this.options.requestConfigSync(),this.renderSummary()});const i=document.createElement("span");i.textContent=jW(e);const s=document.createElement("strong");return s.textContent=dw(e.active,e.count),t.append(i,s),t}renderBoostPickupFiltersWindow(){const e=this.options.getContext(),t=this.options.boostPickupFilters.renderSettings(e,{showHeader:!1});this.options.elements.boostPickupFilters.replaceChildren(t)}renderTouchControlsWindow(){const e=this.options.getContext(),i=this.options.modules.find(s=>s.id===uw)?.renderSettings?.(e)??null;this.options.elements.touchControls.replaceChildren(),i instanceof HTMLElement&&this.options.elements.touchControls.append(i)}}function Im(n,e){const t=document.createElement("section");t.className="module-summary-group";const i=document.createElement("h3");i.textContent=n;const s=document.createElement("div");return s.className="module-list",s.append(...e),t.append(i,s),t}function dw(n,e){const t=n?"On":"Off";return e==null?t:`${t} ${e}`}function jW(n){return n.group==="Replay"?n.label:`${n.label} events`}function Lm(n,e){const t={"absolute-positioning:ranges":"Position zones","backboard:events":"Backboard","ball-carry:events":"Ball carry","boost:ranges":"Boost pickup timeline","bump:events":"Bump","ceiling-shot:events":"Ceiling shot","demo:events":"Demo","dodge-reset:events":"Dodge refresh","double-tap:events":"Double tap","fifty-fifty:events":"50/50","fifty-fifty:ranges":"50/50","dodge:events":"Dodge","half-flip:events":"Half flip","possession:ranges":"Possession","powerslide:events":"Powerslide","powerslide:ranges":"Powerslide","ball_half:ranges":"Half control","ball_third:ranges":"Third control","rush:ranges":"Rush","speed-flip:events":"Speed flip","touch:events":"Touch","wavedash:events":"Wavedash"},i={"absolute-positioning":"Position zones","ceiling-shot":"Ceiling shot labels","fifty-fifty":"50/50 labels",dodge:"Dodge impulse arrows",ball_half:"Half control","relative-positioning":"Player roles","speed-flip":"Speed flip labels",touch:"Touch labels"};return e==="effects"?i[n.id]??n.label:t[`${n.id}:${e}`]??`${n.label} timeline`}function ZW(n){return new YW(n)}var yn=Uint8Array,vi=Uint16Array,vy=Int32Array,If=new yn([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Lf=new yn([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),X_=new yn([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),I1=function(n,e){for(var t=new vi(31),i=0;i<31;++i)t[i]=e+=1<>1|(Bt&21845)<<1;aa=(aa&52428)>>2|(aa&13107)<<2,aa=(aa&61680)>>4|(aa&3855)<<4,q_[Bt]=((aa&65280)>>8|(aa&255)<<8)>>1}var vs=(function(n,e,t){for(var i=n.length,s=0,a=new vi(e);s>l]=c}else for(o=new vi(i),s=0;s>15-n[s]);return o}),va=new yn(288);for(var Bt=0;Bt<144;++Bt)va[Bt]=8;for(var Bt=144;Bt<256;++Bt)va[Bt]=9;for(var Bt=256;Bt<280;++Bt)va[Bt]=7;for(var Bt=280;Bt<288;++Bt)va[Bt]=8;var _c=new yn(32);for(var Bt=0;Bt<32;++Bt)_c[Bt]=5;var QW=vs(va,9,0),e8=vs(va,9,1),t8=vs(_c,5,0),n8=vs(_c,5,1),km=function(n){for(var e=n[0],t=1;te&&(e=n[t]);return e},Vi=function(n,e,t){var i=e/8|0;return(n[i]|n[i+1]<<8)>>(e&7)&t},Dm=function(n,e){var t=e/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},by=function(n){return(n+7)/8|0},kf=function(n,e,t){return(e==null||e<0)&&(e=0),(t==null||t>n.length)&&(t=n.length),new yn(n.subarray(e,t))},i8=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],ps=function(n,e,t){var i=new Error(e||i8[n]);if(i.code=n,Error.captureStackTrace&&Error.captureStackTrace(i,ps),!t)throw i;return i},s8=function(n,e,t,i){var s=n.length,a=0;if(!s||e.f&&!e.l)return t||new yn(0);var r=!t,o=r||e.i!=2,l=e.i;r&&(t=new yn(s*3));var c=function(we){var Re=t.length;if(we>Re){var k=new yn(Math.max(Re*2,we));k.set(t),t=k}},u=e.f||0,d=e.p||0,h=e.b||0,f=e.l,p=e.d,g=e.m,_=e.n,m=s*8;do{if(!f){u=Vi(n,d,1);var v=Vi(n,d+1,3);if(d+=3,v)if(v==1)f=e8,p=n8,g=9,_=5;else if(v==2){var x=Vi(n,d,31)+257,M=Vi(n,d+10,15)+4,C=x+Vi(n,d+5,31)+1;d+=14;for(var w=new yn(C),E=new yn(19),R=0;R>4;if(y<16)w[R++]=y;else{var F=0,W=0;for(y==16?(W=3+Vi(n,d,3),d+=2,F=w[R-1]):y==17?(W=3+Vi(n,d,7),d+=3):y==18&&(W=11+Vi(n,d,127),d+=7);W--;)w[R++]=F}}var H=w.subarray(0,x),ie=w.subarray(x);g=km(H),_=km(ie),f=vs(H,g,1),p=vs(ie,_,1)}else ps(1);else{var y=by(d)+4,b=n[y-4]|n[y-3]<<8,S=y+b;if(S>s){l&&ps(0);break}o&&c(h+b),t.set(n.subarray(y,S),h),e.b=h+=b,e.p=d=S*8,e.f=u;continue}if(d>m){l&&ps(0);break}}o&&c(h+131072);for(var le=(1<>4;if(d+=F&15,d>m){l&&ps(0);break}if(F||ps(2),De<256)t[h++]=De;else if(De==256){Le=d,f=null;break}else{var Ke=De-254;if(De>264){var R=De-257,Oe=If[R];Ke=Vi(n,d,(1<>4;Z||ps(3),d+=Z&15;var ie=JW[ae];if(ae>3){var Oe=Lf[ae];ie+=Dm(n,d)&(1<m){l&&ps(0);break}o&&c(h+131072);var Te=h+Ke;if(h>8},wl=function(n,e,t){t<<=e&7;var i=e/8|0;n[i]|=t,n[i+1]|=t>>8,n[i+2]|=t>>16},Om=function(n,e){for(var t=[],i=0;ih&&(h=a[i].s);var f=new vi(h+1),p=Y_(t[u-1],f,0);if(p>e){var i=0,g=0,_=p-e,m=1<<_;for(a.sort(function(x,M){return f[M.s]-f[x.s]||x.f-M.f});ie)g+=m-(1<>=_;g>0;){var y=a[i].s;f[y]=0&&g;--i){var b=a[i].s;f[b]==e&&(--f[b],++g)}p=e}return{t:new yn(f),l:p}},Y_=function(n,e,t){return n.s==-1?Math.max(Y_(n.l,e,t+1),Y_(n.r,e,t+1)):e[n.s]=t},fw=function(n){for(var e=n.length;e&&!n[--e];);for(var t=new vi(++e),i=0,s=n[0],a=1,r=function(l){t[i++]=l},o=1;o<=e;++o)if(n[o]==s&&o!=e)++a;else{if(!s&&a>2){for(;a>138;a-=138)r(32754);a>2&&(r(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(r(s),--a;a>6;a-=6)r(8304);a>2&&(r(a-3<<5|8208),a=0)}for(;a--;)r(s);a=1,s=n[o]}return{c:t.subarray(0,i),n:e}},Sl=function(n,e){for(var t=0,i=0;i>8,n[s+2]=n[s]^255,n[s+3]=n[s+1]^255;for(var a=0;a4&&!E[X_[L-1]];--L);var O=c+5<<3,D=Sl(s,va)+Sl(a,_c)+r,U=Sl(s,h)+Sl(a,g)+r+14+3*L+Sl(M,E)+2*M[16]+3*M[17]+7*M[18];if(l>=0&&O<=D&&O<=U)return O1(e,u,n.subarray(l,l+c));var F,W,H,ie;if(ks(e,u,1+(U15&&(ks(e,u,De[C]>>5&127),u+=De[C]>>12)}}else F=QW,W=va,H=t8,ie=_c;for(var C=0;C255){var Ke=Oe>>18&31;wl(e,u,F[Ke+257]),u+=W[Ke+257],Ke>7&&(ks(e,u,Oe>>23&31),u+=If[Ke]);var Z=Oe&31;wl(e,u,H[Z]),u+=ie[Z],Z>3&&(wl(e,u,Oe>>5&8191),u+=Lf[Z])}else wl(e,u,F[Oe]),u+=W[Oe]}return wl(e,u,F[256]),u+W[256]},a8=new vy([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),F1=new yn(0),r8=function(n,e,t,i,s,a){var r=a.z||n.length,o=new yn(i+r+5*(1+Math.ceil(r/7e3))+s),l=o.subarray(i,o.length-s),c=a.l,u=(a.r||0)&7;if(e){u&&(l[0]=a.r>>3);for(var d=a8[e-1],h=d>>13,f=d&8191,p=(1<7e3||E>24576)&&(F>423||!c)){u=pw(n,l,0,b,S,x,C,E,L,w-L,u),E=M=C=0,L=w;for(var W=0;W<286;++W)S[W]=0;for(var W=0;W<30;++W)x[W]=0}var H=2,ie=0,le=f,me=D-U&32767;if(F>2&&O==y(w-me))for(var Le=Math.min(h,F)-1,De=Math.min(32767,w),Ke=Math.min(258,F);me<=De&&--le&&D!=U;){if(n[w+H]==n[w+H-me]){for(var Oe=0;OeH){if(H=Oe,ie=me,Oe>Le)break;for(var Z=Math.min(me,Oe-2),ae=0,W=0;Wae&&(ae=se,U=Te)}}}D=U,U=g[D],me+=D-U&32767}if(ie){b[E++]=268435456|K_[H]<<18|hw[ie];var we=K_[H]&31,Re=hw[ie]&31;C+=If[we]+Lf[Re],++S[257+we],++x[Re],R=w+H,++M}else b[E++]=n[w],++S[n[w]]}}for(w=Math.max(w,R);w=r&&(l[u/8|0]=c,k=r),u=O1(l,u+1,n.subarray(w,k))}a.i=r}return kf(o,0,i+by(u)+s)},o8=function(n,e,t,i,s){if(!s&&(s={l:1},e.dictionary)){var a=e.dictionary.subarray(-32768),r=new yn(a.length+n.length);r.set(a),r.set(n,a.length),n=r,s.w=a.length}return r8(n,e.level==null?6:e.level,e.mem==null?s.l?Math.ceil(Math.max(8,Math.min(13,Math.log(n.length)))*1.5):20:12+e.mem,t,i,s)};function l8(n,e){return o8(n,e||{},0,0)}function N1(n,e){return s8(n,{i:2},e,e)}var mw=typeof TextEncoder<"u"&&new TextEncoder,j_=typeof TextDecoder<"u"&&new TextDecoder,c8=0;try{j_.decode(F1,{stream:!0}),c8=1}catch{}var u8=function(n){for(var e="",t=0;;){var i=n[t++],s=(i>127)+(i>223)+(i>239);if(t+s>n.length)return{s:e,r:kf(n,t-1)};s?s==3?(i=((i&15)<<18|(n[t++]&63)<<12|(n[t++]&63)<<6|n[t++]&63)-65536,e+=String.fromCharCode(55296|i>>10,56320|i&1023)):s&1?e+=String.fromCharCode((i&31)<<6|n[t++]&63):e+=String.fromCharCode((i&15)<<12|(n[t++]&63)<<6|n[t++]&63):e+=String.fromCharCode(i)}};function d8(n,e){var t;if(mw)return mw.encode(n);for(var i=n.length,s=new yn(n.length+(n.length>>1)),a=0,r=function(c){s[a++]=c},t=0;ts.length){var o=new yn(a+8+(i-t<<1));o.set(s),s=o}var l=n.charCodeAt(t);l<128||e?r(l):l<2048?(r(192|l>>6),r(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|n.charCodeAt(++t)&1023,r(240|l>>18),r(128|l>>12&63),r(128|l>>6&63),r(128|l&63)):(r(224|l>>12),r(128|l>>6&63),r(128|l&63))}return kf(s,0,a)}function U1(n,e){var t;if(j_)return j_.decode(n);var i=u8(n),s=i.s,t=i.r;return t.length&&ps(8),s}const Eh=1,Z_="cfg",_w="cfgDebug";function h8(n){let e="";for(const t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function f8(n){const e=n.replaceAll("-","+").replaceAll("_","/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=atob(t),s=new Uint8Array(i.length);for(let a=0;a!Di(e)||!A8(e.id)?null:{id:e.id,placement:H1(e.placement)}).filter(e=>e!==null):[]}function E8(n){return Array.isArray(n)?n.map(e=>!Di(e)||typeof e.id!="string"||!R8(e.kind)?null:{id:e.id,kind:e.kind,placement:H1(e.placement),playerId:V1(e.playerId)??null,team:e.team==="orange"?"orange":e.team==="blue"?"blue":null,entries:C8(e.entries)}).filter(e=>e!==null):[]}function C8(n){return Array.isArray(n)?n.map(e=>!Di(e)||typeof e.statId!="string"?null:{statId:e.statId,targetId:typeof e.targetId=="string"?e.targetId:void 0}).filter(e=>e!==null):[]}function H1(n){const e=Di(n)?n:{},t=Di(e.viewport)?e.viewport:{};return{x:Ln(e.x)??8,y:Ln(e.y)??8,viewport:{width:Ch(t.width)??1,height:Ch(t.height)??1},zIndex:Ln(e.zIndex),visible:ti(e.visible)??!0}}function A8(n){return n==="camera"||n==="scoreboard"||n==="playback"||n==="recording"||n==="mechanics"||n==="event-playlist"||n==="mechanics-review"||n==="replay-loading"||n==="boost-pickups"||n==="touch-controls"||n==="touch-legend"||n==="shot-visualization"||n==="missed-events"}function R8(n){return n==="player"||n==="team"||n==="all-players"||n==="all-teams"||n==="kickoff-overview"||n==="goals-overview"||n==="ad-hoc"}function Di(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Ln(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Ch(n){const e=Ln(n);return e!==void 0&&e>0?e:void 0}function ti(n){return typeof n=="boolean"?n:void 0}function V1(n){return n===null?null:typeof n=="string"?n:void 0}function Tl(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"):[]}function gw(n,e,t){return Math.min(t,Math.max(e,n))}const P8=["camera","scoreboard","playback","recording","mechanics","event-playlist","mechanics-review","replay-loading","boost-pickups","touch-controls","touch-legend","shot-visualization","missed-events"];class I8{constructor(e){this.options=e}nextZIndex=30;reset(){this.nextZIndex=30}bringToFront(e){e.style.zIndex=`${this.nextZIndex++}`}show(e){const t=this.mustWindow(e);t.hidden=!1,this.bringToFront(t),this.options.requestConfigSync()}toggle(e){const t=this.mustWindow(e);t.hidden=!t.hidden,t.hidden||this.bringToFront(t),this.options.requestConfigSync()}hide(e){const t=this.mustWindow(e);t.hidden=!0,this.options.requestConfigSync()}readPlacement(e){const t=Number.parseInt(e.style.zIndex,10);return{x:this.readCoordinate(e,"--window-x"),y:this.readCoordinate(e,"--window-y"),viewport:yw(),zIndex:Number.isFinite(t)?t:void 0,visible:!e.hidden}}applyPlacement(e,t){const i=y8(t,yw());e.style.setProperty("--window-x",`${i.x}px`),e.style.setProperty("--window-y",`${i.y}px`),e.hidden=!t.visible,t.zIndex!==void 0&&(e.style.zIndex=`${t.zIndex}`,this.nextZIndex=Math.max(this.nextZIndex,t.zIndex+1))}getSingletonConfigs(){const e=[],t=this.options.getRoot();for(const i of P8){const s=t.querySelector(`[data-window-id="${i}"]`);s&&e.push({id:i,placement:this.readPlacement(s)})}return e}applySingletonConfigs(e){const t=this.options.getRoot();for(const i of e){const s=t.querySelector(`[data-window-id="${i.id}"]`);s&&this.applyPlacement(s,i.placement)}}installDragging(e,t){e.addEventListener("pointerdown",i=>{if(!(i.target instanceof HTMLElement)||L8(i.target))return;const s=i.target.closest("[data-window-id]");if(!s||s.hidden)return;this.bringToFront(s);const a=i.clientX,r=i.clientY,o=s.getBoundingClientRect(),l=i.pointerId;s.setPointerCapture(l),i.preventDefault();const c=d=>{const h=Math.max(8,Math.min(window.innerWidth-120,o.left+d.clientX-a)),f=Math.max(8,Math.min(window.innerHeight-100,o.top+d.clientY-r));s.style.setProperty("--window-x",`${h}px`),s.style.setProperty("--window-y",`${f}px`)},u=()=>{s.releasePointerCapture(l),s.removeEventListener("pointermove",c),s.removeEventListener("pointerup",u),s.removeEventListener("pointercancel",u),this.options.requestConfigSync()};s.addEventListener("pointermove",c),s.addEventListener("pointerup",u),s.addEventListener("pointercancel",u)},{signal:t})}mustWindow(e){const t=this.options.getRoot().querySelector(`[data-window-id="${e}"]`);if(!t)throw new Error(`Missing window for id: ${e}`);return t}readCoordinate(e,t){const i=e.style.getPropertyValue(t).trim(),s=getComputedStyle(e).getPropertyValue(t).trim(),a=i||s,r=Number.parseFloat(a);if(Number.isFinite(r))return r;const o=e.getBoundingClientRect();return t==="--window-y"?o.top:o.left}}function yw(){return{width:Math.max(1,window.innerWidth),height:Math.max(1,window.innerHeight)}}function L8(n){return n instanceof Element&&!!n.closest("button, input, select, textarea, option, label, a, [data-no-drag]")}function k8(n){return new I8(n)}class D8{constructor(e){this.options=e}activeSourceIds=null;autoFollow=!0;lastActiveKey=null;activeItem=null;renderedItems=[];reset(){this.activeSourceIds=null,this.lastActiveKey=null,this.activeItem=null,this.renderedItems=[]}render(){this.options.body.replaceChildren(),this.lastActiveKey=null,this.activeItem=null,this.renderedItems=[];const e=this.options.getSources();if(e.length===0){const _=document.createElement("p");_.className="stat-window-empty",_.textContent=this.options.getReplayPlayer()?"No events loaded.":"Load a replay to see events.",this.options.body.append(_);return}const t=W_(e,this.activeSourceIds),i=$W({sources:e,activeSourceIds:this.activeSourceIds,replayPlayers:this.options.getReplayPlayer()?.replay.players??[]}),s=document.createElement("div");s.className="event-playlist-toolbar";const a=document.createElement("details");a.className="event-playlist-filter",a.dataset.noDrag="true";const r=document.createElement("summary");r.textContent=`Filters ${t.size}/${e.length}`,a.append(r);const o=document.createElement("div");o.className="event-playlist-filter-panel";const l=document.createElement("div");l.className="event-playlist-filter-actions";const c=document.createElement("button");c.type="button",c.textContent="All",c.addEventListener("click",()=>{this.activeSourceIds=new Set(e.map(m=>m.id)),this.lastActiveKey=null,this.render();const _=this.options.getReplayPlayer()?.getState();_&&this.syncTimeline(_)});const u=document.createElement("button");u.type="button",u.textContent="None",u.addEventListener("click",()=>{this.activeSourceIds=new Set,this.lastActiveKey=null,this.render()}),l.append(c,u),o.append(l);const d=new Map;for(const _ of e){const m=d.get(_.group)??[];m.push(_),d.set(_.group,m)}for(const[_,m]of d){const v=document.createElement("section");v.className="event-playlist-filter-group";const y=document.createElement("h3");y.textContent=_,v.append(y);for(const b of m){const S=document.createElement("label");S.className="toggle event-playlist-filter-option";const x=document.createElement("input");x.type="checkbox",x.checked=t.has(b.id),x.addEventListener("change",()=>{this.setSourceSelection(e,C=>{x.checked?C.add(b.id):C.delete(b.id)})});const M=document.createElement("span");M.textContent=`${b.label} (${b.events.length})`,S.append(x,M),v.append(S)}o.append(v)}a.append(o);const h=document.createElement("label");h.className="toggle event-playlist-follow";const f=document.createElement("input");f.type="checkbox",f.checked=this.autoFollow,f.addEventListener("change",()=>{this.autoFollow=f.checked;const _=this.options.getReplayPlayer()?.getState();_&&this.syncTimeline(_,{forceScroll:!0})});const p=document.createElement("span");p.textContent="Auto-follow",h.append(f,p),s.append(a,h);const g=document.createElement("div");if(g.className="event-playlist-list",g.dataset.noDrag="true",i.length===0){const _=document.createElement("p");_.className="stat-window-empty",t.size===0?_.textContent="No event types selected.":_.textContent="No events in selected event types.",g.append(_)}else for(const _ of i){const m=document.createElement("button");m.type="button",m.className="event-playlist-item",m.dataset.eventKey=_.key,m.dataset.eventTime=`${_.event.time}`,m.style.setProperty("--event-color",_.color),Number.isFinite(_.event.time)&&this.renderedItems.push({key:_.key,time:_.event.time,element:m}),m.addEventListener("click",()=>{this.options.cueTimelineEvent(_.event)});const v=document.createElement("span");v.className="event-playlist-time",v.textContent=this.options.formatTime(_.event.time);const y=document.createElement("span");y.className="event-playlist-main";const b=document.createElement("strong");b.textContent=_.event.label??_.sourceLabel;const S=document.createElement("span");S.textContent=[_.event.playerName??null,_.event.frame!==void 0?`frame ${_.event.frame}`:null,_.sourceLabel].filter(x=>!!x).join(" · "),y.append(b,S),m.append(v,y),g.append(m)}this.options.body.append(s,g)}syncTimeline(e,t={}){if(!this.options.body.querySelector(".event-playlist-list"))return;const s=this.getActiveItem(e.currentTime),a=s?.dataset.eventKey??null;a===this.lastActiveKey&&!t.forceScroll||(this.activeItem?.isConnected?this.activeItem.dataset.active="false":this.activeItem&&(this.activeItem=null),s?(s.dataset.active="true",this.activeItem=s,(this.autoFollow||t.forceScroll)&&s.scrollIntoView({block:"nearest"})):this.activeItem=null,this.lastActiveKey=a)}setSourceSelection(e,t){const i=W_(e,this.activeSourceIds);t(i),this.activeSourceIds=i,this.lastActiveKey=null,this.render();const s=this.options.getReplayPlayer()?.getState();s&&this.syncTimeline(s)}getActiveItem(e){const t=this.renderedItems;if(t.length===0)return null;let i=0,s=t.length-1;for(;ie.getConfig||e.applyConfig).map(e=>{const t={id:e.id};return e.id==="boost"&&(t.aliases=["boost-pickup-animation"]),e.getConfig&&(t.getConfig=()=>e.getConfig?.()),e.applyConfig&&(t.applyConfig=i=>e.applyConfig?.(i)),t})}function W8(n){return B8($1(n))}function X8({replayPlayer:n,playbackRate:e,skipPostGoalTransitions:t,skipKickoffs:i}){const s=n?.getState();return{currentTime:s?.currentTime,playing:s?.playing,rate:s?.speed??Df(Number(e?.value??1)),skipPostGoalTransitions:n?s?.skipPostGoalTransitionsEnabled:t.checked,skipKickoffs:n?s?.skipKickoffsEnabled:i.checked}}function K8({replayPlayer:n,cameraControlsController:e}){const t=n?.getState(),i=t?UE(t):e?.ballCamMode;return{mode:t?.cameraViewMode,freePreset:e?.freeCameraPreset??null,attachedPlayerId:t?.attachedPlayerId,ballCam:i===void 0?void 0:i==="on",useReplayBallCam:i===void 0?void 0:i==="player",usePlayerCameraSettings:t?.customCameraSettings===null,autoPossession:e?.autoPossessionEnabled,customSettings:t?.customCameraSettings,nameplateLiftUu:e?.nameplateLiftUu}}function q8({playback:n,camera:e,activeTimelineEventSourceIds:t,activeTimelineRangeModuleIds:i,activeMechanicTimelineKinds:s,activeRenderEffectModuleIds:a,initialConfig:r,replayPlayer:o,boostPadOverlayEnabled:l,recording:c,singletonWindows:u,statsWindows:d,moduleConfigs:h}){return{version:Eh,playback:n,camera:e,overlays:{timelineEvents:[...t],timelineRanges:[...i],mechanics:[...s],renderEffects:[...a],...r?.overlays.pluginRenderEffects!==void 0?{pluginRenderEffects:[...r.overlays.pluginRenderEffects]}:{},...r?.overlays.pluginHudOverlay!==void 0?{pluginHudOverlay:r.overlays.pluginHudOverlay}:{},followedPlayerHud:!1,boostPads:l,boostPickupAnimation:o?.getState().boostPickupAnimationEnabled??!1,hitboxWireframes:o?.getState().hitboxWireframesEnabled??!1,hitboxOnlyMode:o?.getState().hitboxOnlyModeEnabled??!1},recording:c,singletonWindows:u,statsWindows:d,moduleConfigs:h}}function Y8(n,e,t){return{currentTime:n.currentTime,playing:n.playing,speed:n.rate,customCameraSettings:G1(e),cameraViewMode:e.mode,attachedPlayerId:e.attachedPlayerId,...yx(e)==="player"?{useReplayBallCam:!0}:{ballCamEnabled:yx(e)==="on"},boostPickupAnimationEnabled:t.overlays.boostPickupAnimation,hitboxWireframesEnabled:t.overlays.hitboxWireframes,hitboxOnlyModeEnabled:t.overlays.hitboxOnlyMode,skipPostGoalTransitionsEnabled:n.skipPostGoalTransitions,skipKickoffsEnabled:n.skipKickoffs}}function j8(n,e,t){console.groupCollapsed("[subtr-actor] stats player cfg load"),console.log("location.href",window.location.href),console.log("location.search",n.search||"(empty)"),console.log("location.hash",n.hash||"(empty)"),console.table([...n.searchParams.map(([i,s])=>({source:"search",name:i,value:s})),...n.hashParams.map(([i,s])=>({source:"hash",name:i,value:s}))]),console.log("cfg selected source",n.selectedSource??"(none)"),console.log("cfg selected raw text",n.selectedValue??"(none)"),console.log("cfg selected raw length",n.selectedValue?.length??0),console.log("cfg search values",n.searchValues),console.log("cfg hash values",n.hashValues),n.hashValues.length>0&&n.searchValues.length>0&&console.warn("Both hash and search contain cfg; hash cfg is used."),e&&(console.log("cfg normalized JSON",JSON.stringify(e,null,2)),console.log("cfg normalized object",e)),t&&console.error("cfg decode/apply error",t),console.groupEnd()}function vw(n,e){const{style:t}=n.renderer.domElement;t.visibility=e?"hidden":"",t.pointerEvents=e?"none":""}function bw(n,e={}){const t=e.destroyPlayer??!0,i=e.clearPlayerPluginHandles??!0,s=n.getUnsubscribe();s&&(s(),n.setUnsubscribe(null)),n.teardownActiveModules(),t&&(n.getReplayPlayer()?.destroy(),n.setReplayPlayer(null)),i&&(n.setCanvasRecorder(null),n.setTimelineOverlay(null)),n.setLoadedReplayName(null),n.setStatsTimeline(null),n.setStatsFrameLookup(null),n.setStatRegistry(zo(null)),n.clearTimelineEventSources(),n.clearTimelineRangeSources(),n.clearStandalonePlugins(),n.clearRenderCaches(),n.resetEventPlaylistWindow(),n.renderModuleSummary(),n.renderScoreboard(),n.renderTimelineEventCount(),n.renderMechanicsTimelineControls(),n.renderEventPlaylistWindow(),n.renderModuleSettings(),n.syncRecordingWindow()}async function Z8(n,e,t){const{elements:i}=t;let s=null;i.statusReadout.textContent=n.preparingStatus,i.fileInput.disabled=!0,t.getReplayLoadModal()?.show(n.name,n.preparingStatus),t.setTransportEnabled(!1),t.getCameraControlsController()?.syncAvailability(),i.emptyState.hidden=t.getReplayPlayer()!==null,t.getReplayPlayer()?.pause();try{i.statusReadout.textContent="Parsing replay...",t.getReplayLoadModal()?.show(n.name,"Parsing replay...");const a=await e,{replay:r}=a,o=t.getReplayPlayer();if(o){bw(t,{destroyPlayer:!1,clearPlayerPluginHandles:!1});const h=new nS(a.raw);await o.replaceReplay(h,r,{preservePlayback:!1}),t.setStatsTimeline(a.statsTimeline),t.setStatsFrameLookup(a.statsFrameLookup),t.setStatRegistry(zo(null)),t.setReplayPlayer(o),t.syncBoostPadOverlayPlugin(),t.setupActiveModules(),t.setUnsubscribe(o.subscribe(t.renderSnapshot));const f=t.getInitialConfig();if(f){t.setApplyingConfig(!0);try{t.applyConfigToReplayPlayer(f)}finally{t.setApplyingConfig(!1)}}t.getCameraControlsController()?.populateAttachedPlayerOptions(r.players),i.emptyState.hidden=!0,i.statusReadout.textContent=`Loaded ${n.name}`,t.setLoadedReplayName(n.name),i.playersReadout.textContent=r.players.map(p=>p.name).join(", "),i.framesReadout.textContent=`${r.frameCount}`,t.renderModuleSummary(),t.renderTimelineEventCount(),t.renderMechanicsTimelineControls(),t.resetEventPlaylistWindow(),t.renderEventPlaylistWindow(),t.setTransportEnabled(!0),t.getCameraControlsController()?.syncAvailability(o.getState()),t.renderSnapshot(o.getState()),t.renderStatsWindows(o.getState().frameIndex),t.renderScoreboard(o.getState().frameIndex),t.syncEventPlaylistTimeline(o.getState(),{forceScroll:!0}),t.renderModuleSettings(),t.syncRecordingWindow(),t.getReplayLoadModal()?.hide();return}const l=eU({replayEventsLabel:"Replay",replayEvents:h=>t.withTimelineEventSeekTimes(t.getReplayTimelineEvents(h.replay))}),c=O3({onStatusChange:t.syncRecordingWindow});t.setCanvasRecorder(c);const u=t.getInitialConfig(),d=tU(i.viewport,a,{initialPlaybackRate:u?.playback.rate,initialCustomCameraSettings:G1(u?.camera),initialAttachedPlayerId:u?.camera.attachedPlayerId??null,initialCameraViewMode:u?.camera.mode,initialBoostPickupAnimationEnabled:u?.overlays.boostPickupAnimation??!1,initialHitboxWireframesEnabled:u?.overlays.hitboxWireframes??i.hitboxWireframes.checked,initialHitboxOnlyModeEnabled:u?.overlays.hitboxOnlyMode??i.hitboxOnlyMode.checked,initialSkipPostGoalTransitionsEnabled:i.skipPostGoalTransitions.checked,initialSkipKickoffsEnabled:i.skipKickoffs.checked,plugins:[u3({onSample:({renderFps:h,replayFps:f})=>{const p=document.getElementById("render-fps-readout"),g=document.getElementById("replay-fps-readout");p&&(p.textContent=`${h.toFixed(0)} fps`),g&&(g.textContent=`${f.toFixed(0)} fps`)}}),Bu(dU({floatingLiftUu:()=>t.getCameraControlsController()?.nameplateLiftUu})),Bu(P3({includePickup:t.includeBoostPickupAnimationPickup})),Bu(c),Bu(l)]});if(s=d,vw(d,!0),await d.ready,bw(t),s=null,vw(d,!1),t.setStatsTimeline(a.statsTimeline),t.setStatsFrameLookup(a.statsFrameLookup),t.setStatRegistry(zo(null)),t.setTimelineOverlay(l),t.setReplayPlayer(d),t.syncBoostPadOverlayPlugin(),t.setupActiveModules(),t.setUnsubscribe(d.subscribe(t.renderSnapshot)),u){t.setApplyingConfig(!0);try{t.applyConfigToReplayPlayer(u)}finally{t.setApplyingConfig(!1)}}t.getCameraControlsController()?.populateAttachedPlayerOptions(r.players),i.emptyState.hidden=!0,i.statusReadout.textContent=`Loaded ${n.name}`,t.setLoadedReplayName(n.name),i.playersReadout.textContent=r.players.map(h=>h.name).join(", "),i.framesReadout.textContent=`${r.frameCount}`,t.renderModuleSummary(),t.renderTimelineEventCount(),t.renderMechanicsTimelineControls(),t.resetEventPlaylistWindow(),t.renderEventPlaylistWindow(),t.setTransportEnabled(!0),t.getCameraControlsController()?.syncAvailability(d.getState()),t.renderSnapshot(d.getState()),t.renderStatsWindows(d.getState().frameIndex),t.renderScoreboard(d.getState().frameIndex),t.syncEventPlaylistTimeline(d.getState(),{forceScroll:!0}),t.renderModuleSettings(),t.syncRecordingWindow(),t.getReplayLoadModal()?.hide()}catch(a){throw t.getReplayLoadModal()?.hide(),s?.destroy(),t.getReplayPlayer()||(i.emptyState.hidden=!1,t.setCanvasRecorder(null)),t.syncRecordingWindow(),a}finally{i.fileInput.disabled=!1}}function J8(n){if(n<=0)return"--";const e=["B","KB","MB","GB"];let t=n,i=0;for(;t>=1024&&i=10?1:2;return`${t.toFixed(s)} ${e[i]}`}function Q8(n){if(!n)return"No replay";if(n.error)return n.error;switch(n.state){case"idle":return"Idle";case"recording":return"Recording";case"stopping":return"Stopping";case"ready":return"Ready";case"error":return"Error"}}function e6({fpsValue:n,playbackRateValue:e}){const t=Number(n),i=Number(e);return{fps:Number.isFinite(t)?Math.max(1,Math.min(120,Math.trunc(t))):60,playbackRate:Number.isFinite(i)?Math.max(.1,i):1}}function t6(n,e=new Date){const i=(n?.replace(/\.replay$/i,"")||"replay").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,""),s=e.toISOString().replace(/[:.]/g,"-");return`${i||"replay"}-${s}.webm`}function n6(n,e){const t=URL.createObjectURL(n),i=document.createElement("a");i.href=t,i.download=e,document.body.append(i),i.click(),i.remove(),window.setTimeout(()=>URL.revokeObjectURL(t),0)}class i6{constructor(e){this.options=e}getConfigSnapshot(){const{elements:e}=this.options;return{fps:Number(e.fps.value),playbackRate:Number(e.playbackRate.value)}}applyConfig(e){const{elements:t}=this.options;e.fps!==void 0&&(t.fps.value=`${e.fps}`),e.playbackRate!==void 0&&(t.playbackRate.value=`${e.playbackRate}`)}sync(e=this.options.getCanvasRecorder()?.getStatus()??null){const{elements:t}=this.options,i=this.options.getCanvasRecorder()!==null&&this.options.getReplayPlayer()!==null,s=e?.state??"idle",a=s==="recording"||s==="stopping",r=(this.options.getCanvasRecorder()?.getRecording()??null)!==null;t.status.textContent=Q8(e),t.elapsed.textContent=`${(e?.elapsedSeconds??0).toFixed(1)}s`,t.size.textContent=J8(e?.sizeBytes??0),t.type.textContent=e?.mimeType||"WebM",t.start.disabled=!i||a,t.fullReplay.disabled=!i||a,t.stop.disabled=!i||!a,t.download.disabled=!r||a,t.clear.disabled=!r||a,t.fps.disabled=a,t.playbackRate.disabled=a}installEventListeners(e){const{elements:t}=this.options;t.start.addEventListener("click",()=>{const i=this.options.getCanvasRecorder();if(i)try{const{fps:s}=this.getRecordingOptions();i.start({fps:s}),this.sync()}catch(s){console.error("Failed to start recording:",s),this.options.setStatus(s instanceof Error?s.message:"Failed to start recording"),this.sync(i.getStatus())}},{signal:e}),t.fullReplay.addEventListener("click",()=>{const i=this.options.getCanvasRecorder();if(!i)return;const{fps:s,playbackRate:a}=this.getRecordingOptions();i.recordFullReplay({fps:s,playbackRate:a,restorePlaybackState:!0}).catch(r=>{console.error("Failed to record replay:",r),this.options.setStatus(r instanceof Error?r.message:"Failed to record replay"),this.sync(this.options.getCanvasRecorder()?.getStatus()??null)}),this.sync()},{signal:e}),t.stop.addEventListener("click",()=>{this.options.getCanvasRecorder()?.stop().catch(i=>{console.error("Failed to stop recording:",i),this.options.setStatus(i instanceof Error?i.message:"Failed to stop recording")}),this.sync()},{signal:e}),t.download.addEventListener("click",()=>{const i=this.options.getCanvasRecorder()?.getRecording();i&&n6(i,t6(this.options.getLoadedReplayName()))},{signal:e}),t.clear.addEventListener("click",()=>{try{this.options.getCanvasRecorder()?.clear(),this.sync()}catch(i){console.error("Failed to clear recording:",i)}},{signal:e}),t.fps.addEventListener("change",this.options.requestConfigSync,{signal:e}),t.playbackRate.addEventListener("change",this.options.requestConfigSync,{signal:e})}getRecordingOptions(){const{elements:e}=this.options;return e6({fpsValue:e.fps.value,playbackRateValue:e.playbackRate.value})}}function s6(n){return new i6(n)}class a6{constructor(e){this.options=e}render(e=this.options.getReplayPlayer()?.getState().frameIndex??0){const{body:t}=this.options;t.replaceChildren();const i=this.options.getStatsFrameLookup(),s=i?Ht(i,e):null,a=this.options.getReplayPlayer()?.replay??null;if(!s||!a){const o=document.createElement("p");o.className="scoreboard-empty",o.textContent="Load a replay to show the scoreboard.",t.append(o);return}const r=document.createElement("div");r.className="scoreboard-scoreline",r.append(xw(s.team_zero?.core.goals,!0),o6(),xw(s.team_one?.core.goals,!1)),t.append(r)}}function r6(n){return typeof n=="number"&&Number.isFinite(n)?`${Math.round(n)}`:"--"}function o6(){const n=document.createElement("span");return n.className="scoreboard-divider",n.textContent="-",n}function xw(n,e){const t=document.createElement("strong");return t.className=`scoreboard-goal-value ${ca(e)}`,t.textContent=r6(n),t}function l6(n){return new a6(n)}class c6{constructor(e){this.options=e}setTransportEnabled(e,t){const{elements:i}=this.options;i.togglePlayback.disabled=!e,i.previousFrame.disabled=!e,i.nextFrame.disabled=!e,i.playbackRate.disabled=!e,i.skipPostGoalTransitions.disabled=!e,i.skipKickoffs.disabled=!e,i.hitboxWireframes.disabled=!e,i.hitboxOnlyMode.disabled=!e,this.options.getCameraControlsController()?.setTransportEnabled(e,t)}renderSnapshot(e){const{elements:t}=this.options;t.timeReadout.textContent=`${e.currentTime.toFixed(2)}s`,t.frameReadout.textContent=`${e.frameIndex}`,t.durationReadout.textContent=`${e.duration.toFixed(2)}s`,t.playbackStatusReadout.textContent=e.playing?"Playing":"Paused",t.togglePlayback.textContent=e.playing?"Pause":"Play";const i=Math.max(0,this.options.getFrameCount()-1);t.previousFrame.disabled=e.frameIndex<=0,t.nextFrame.disabled=e.frameIndex>=i;const s=Df(e.speed);t.playbackRate.value=`${s}`,t.playbackRateReadout.textContent=wy(s),this.options.getCameraControlsController()?.syncState(e),t.skipPostGoalTransitions.checked=e.skipPostGoalTransitionsEnabled,t.skipKickoffs.checked=e.skipKickoffsEnabled,t.hitboxWireframes.checked=e.hitboxWireframesEnabled,t.hitboxOnlyMode.checked=e.hitboxOnlyModeEnabled,t.emptyState.hidden=!0}}function u6(n){return new c6(n)}function d6({elements:n,signal:e,setLauncherOpen:t,openReplayFilePicker:i,getElementWindowId:s,toggleWindow:a,hideWindow:r,createStatsWindow:o,loadReplayFile:l,togglePlayback:c,stepFrames:u,setPlaybackRate:d,setSkipPostGoalTransitionsEnabled:h,setSkipKickoffsEnabled:f,setHitboxWireframesEnabled:p,setHitboxOnlyModeEnabled:g}){n.launcherToggle.addEventListener("click",()=>{t(n.launcherMenu.hidden)},{signal:e}),n.root.addEventListener("click",m=>{m.target instanceof Element&&(m.target.closest(".top-chrome")||t(!1))},{signal:e}),n.loadReplayAction.addEventListener("click",i,{signal:e}),n.emptyLoadReplay.addEventListener("click",i,{signal:e}),n.root.querySelectorAll("[data-window-toggle]").forEach(m=>{m.addEventListener("click",()=>{const v=m.dataset.windowToggle;v&&(a(v),t(!1))},{signal:e})}),n.root.querySelectorAll("[data-window-hide]").forEach(m=>{m.addEventListener("click",()=>{const v=m.dataset.windowHide??s(m);v&&r(v)},{signal:e})}),n.root.querySelectorAll("[data-create-stats-window]").forEach(m=>{m.addEventListener("click",()=>{o(m.dataset.createStatsWindow)},{signal:e})}),n.fileInput.addEventListener("change",()=>{const m=n.fileInput.files?.[0];m&&l(m)},{signal:e}),n.togglePlayback.addEventListener("click",c,{signal:e}),n.previousFrame.addEventListener("click",()=>u(-1),{signal:e}),n.nextFrame.addEventListener("click",()=>u(1),{signal:e});const _=()=>{const m=Df(Number(n.playbackRate.value));n.playbackRate.value=`${m}`,n.playbackRateReadout.textContent=wy(m),d(m)};n.playbackRate.addEventListener("input",_,{signal:e}),n.playbackRate.addEventListener("change",_,{signal:e}),n.skipPostGoalTransitions.addEventListener("change",()=>{h(n.skipPostGoalTransitions.checked)},{signal:e}),n.skipKickoffs.addEventListener("change",()=>{f(n.skipKickoffs.checked)},{signal:e}),n.hitboxWireframes.addEventListener("change",()=>{p(n.hitboxWireframes.checked)},{signal:e}),n.hitboxOnlyMode.addEventListener("change",()=>{g(n.hitboxOnlyMode.checked)},{signal:e})}const h6=3500;function f6(){const n=document.activeElement;if(!(n instanceof HTMLElement))return!1;if(n.isContentEditable)return!0;const e=n.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"}function p6(n){const{getReplayPlayer:e,signal:t}=n,i={forward:!1,backward:!1,left:!1,right:!1,up:!1,down:!1},s=()=>{i.forward=!1,i.backward=!1,i.left=!1,i.right=!1,i.up=!1,i.down=!1},a=(g,_)=>{switch(g){case"KeyW":return i.forward=_,!0;case"KeyS":return i.backward=_,!0;case"KeyA":return i.left=_,!0;case"KeyD":return i.right=_,!0;case"Space":return i.up=_,!0;case"ShiftLeft":case"ShiftRight":return i.down=_,!0;default:return!1}},r=g=>{g.ctrlKey||g.metaKey||g.altKey||f6()||a(g.code,!0)&&g.preventDefault()},o=g=>{a(g.code,!1)};window.addEventListener("keydown",r,{signal:t}),window.addEventListener("keyup",o,{signal:t}),window.addEventListener("blur",s,{signal:t});const l=new T,c=new T,u=new T,d=new T(0,1,0);let h=null,f=0;const p=g=>{f=requestAnimationFrame(p);const _=h===null?0:Math.min(.1,(g-h)/1e3);h=g;const m=(i.forward?1:0)-(i.backward?1:0),v=(i.right?1:0)-(i.left?1:0),y=(i.up?1:0)-(i.down?1:0);if(_===0||m===0&&v===0&&y===0)return;const b=e();if(!b||b.getState().cameraViewMode!=="free")return;const S=b.camera,x=b.controls;S.getWorldDirection(l),c.set(1,0,0).applyQuaternion(S.quaternion),u.set(0,0,0).addScaledVector(l,m).addScaledVector(c,v).addScaledVector(d,y),u.lengthSq()!==0&&(u.normalize().multiplyScalar(h6*_),S.position.add(u),x.target.add(u))};f=requestAnimationFrame(p),t.addEventListener("abort",()=>{cancelAnimationFrame(f)})}function m6(n,e){const t=new URLSearchParams(n),s=(t.get("replayId")??t.get("replay-id")??e??"").trim();return s.length>0?s:null}function _6(){const n=new URLSearchParams(window.location.search),e=n.get("reviewToken")??n.get("token")??window.localStorage.getItem("rocket_sense_access_token");return e?{Authorization:`Bearer ${e}`}:{}}function g6(n){if(!n.replayId)return null;const e={replay_id:n.replayId,reviewed_mechanic:n.mechanic,reviewed_event_frame:n.frame,reviewed_event_time:n.time,confidence:n.confidence,status:"confirmed"};return n.subjectKind&&n.subjectId&&(e.reviewed_subject_kind=n.subjectKind,e.reviewed_subject_id=n.subjectId),n.startFrame!==null&&(e.reviewed_start_frame=n.startFrame),n.endFrame!==null&&(e.reviewed_end_frame=n.endFrame),n.notes&&n.notes.trim()&&(e.notes=n.notes.trim()),Object.keys(n.context).length>0&&(e.context=n.context),e}function y6(n,e){const t=n.getState(),i=Math.max(0,Math.round(t.frameIndex??0)),s=t.currentTime??0,a=t.attachedPlayerId??null,r=a?n.replay.players.find(o=>o.id===a)?.name??null:null;return{localId:e.localId,mechanic:e.mechanic,frame:i,time:s,subjectKind:a?"player":null,subjectId:a,playerName:r,startFrame:null,endFrame:null,notes:e.notes?.trim()?e.notes.trim():null,confidence:1,replayId:e.replayId,context:{capturedFrom:"stat-evaluation-player",attachedPlayerId:a,playerName:r,durationSeconds:n.replay.duration??null}}}async function v6(n,e="/api/v1/events/reviews"){const t=g6(n);if(!t)return{record:n,ok:!1,message:"No replay id — cannot upload (export JSON instead)."};try{const i=await fetch(e,{method:"POST",headers:{"content-type":"application/json",..._6()},credentials:"same-origin",body:JSON.stringify(t)});if(!i.ok){let s=`${i.status}${i.statusText?` ${i.statusText}`:""}`;try{const a=await i.json();typeof a.error=="string"&&(s=a.error)}catch{}return{record:n,ok:!1,message:s}}return{record:n,ok:!0,message:"uploaded"}}catch(i){return{record:n,ok:!1,message:i instanceof Error?i.message:String(i)}}}const b6=["flick","whiff","double_tap","ceiling_shot","wall_aerial","flip_reset","one_timer","speed_flip","half_flip","wavedash","demo"],x6="m";function w6(){const n=document.activeElement;if(!(n instanceof HTMLElement))return!1;if(n.isContentEditable)return!0;const e=n.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"}function S6(n,e){const t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),i=URL.createObjectURL(t),s=document.createElement("a");s.href=i,s.download=n,document.body.appendChild(s),s.click(),s.remove(),URL.revokeObjectURL(i)}class T6{constructor(e){this.options=e}records=[];localIdSeq=0;installEventListeners(e){const{elements:t}=this.options;for(const i of b6){const s=document.createElement("option");s.value=i,s.textContent=i.replaceAll("_"," "),t.mechanic.appendChild(s)}t.capture.addEventListener("click",()=>this.capture(),{signal:e}),t.export.addEventListener("click",()=>this.exportJson(),{signal:e}),t.upload.addEventListener("click",()=>{this.uploadAll()},{signal:e}),t.clear.addEventListener("click",()=>{this.records.length=0,this.render(),this.setStatus("Cleared.")},{signal:e}),window.addEventListener("keydown",i=>{i.key.toLowerCase()!==x6||i.repeat||i.metaKey||i.ctrlKey||i.altKey||w6()||(i.preventDefault(),this.capture())},{signal:e}),this.render()}capture(){const e=this.options.getReplayPlayer();if(!e){this.setStatus("No replay loaded.");return}this.localIdSeq+=1;const t=y6(e,{mechanic:this.options.elements.mechanic.value||"flick",replayId:this.resolveReplayId(),localId:`missed-${this.localIdSeq}`});this.records.push(t),this.options.showWindow(),this.render(),this.setStatus(`Captured ${t.mechanic} @ ${t.time.toFixed(2)}s`+(t.replayId?".":" (no replay id — export only)."))}exportJson(){if(this.records.length===0){this.setStatus("Nothing to export.");return}S6("missed-events.json",{capturedFrom:"stat-evaluation-player",replayId:this.resolveReplayId(),missedEvents:this.records}),this.setStatus(`Exported ${this.records.length}.`)}async uploadAll(){if(this.records.length===0){this.setStatus("Nothing to upload.");return}let e=0;const t=[];for(const i of[...this.records]){const s=await v6(i);if(s.ok){e+=1;const a=this.records.findIndex(r=>r.localId===i.localId);a>=0&&this.records.splice(a,1)}else t.push(`${i.mechanic}@${i.time.toFixed(1)}s: ${s.message}`)}this.render(),this.setStatus(t.length===0?`Uploaded ${e}.`:`Uploaded ${e}, ${t.length} failed — ${t[0]}`)}render(){const{list:e}=this.options.elements;e.replaceChildren();for(const t of this.records){const i=document.createElement("li"),s=t.playerName??t.subjectId??"no subject",a=document.createElement("span");a.className="missed-event-row",a.textContent=`${t.mechanic} @ ${t.time.toFixed(2)}s · f${t.frame} · ${s}`+(t.replayId?"":" · no replay id");const r=document.createElement("button");r.type="button",r.textContent="✕",r.title="Remove",r.addEventListener("click",()=>{const o=this.records.findIndex(l=>l.localId===t.localId);o>=0&&(this.records.splice(o,1),this.render())}),i.append(a,r),e.appendChild(i)}}setStatus(e){this.options.elements.status.textContent=e}resolveReplayId(){return m6(window.location.search,this.options.getReplayId?.()??null)}}function M6(n){return new T6(n)}class E6{constructor(e){this.options=e}activeModules=[];activeTimelineEventSourceIds=new Set;activeTimelineRangeModuleIds=new Set;activeMechanicTimelineKinds=new Set;activeRenderEffectModuleIds=new Set;removeRenderHook=null;timelineSourceRemovers=new Map;timelineRangeSourceRemovers=new Map;getActiveModules(){return this.activeModules}getActiveTimelineEventSourceIds(){return this.activeTimelineEventSourceIds}getActiveTimelineRangeModuleIds(){return this.activeTimelineRangeModuleIds}getActiveMechanicTimelineKinds(){return this.activeMechanicTimelineKinds}getActiveRenderEffectModuleIds(){return this.activeRenderEffectModuleIds}getActiveCapabilityIds(e){return e==="events"?this.activeTimelineEventSourceIds:e==="ranges"?this.activeTimelineRangeModuleIds:this.activeRenderEffectModuleIds}getBoostPadOverlayEnabled(){return!0}getTimelineEventSourceIds(){return[...this.activeTimelineEventSourceIds]}getTimelineRangeModuleIds(){return[...this.activeTimelineRangeModuleIds]}getMechanicTimelineKinds(){return[...this.activeMechanicTimelineKinds]}getRenderEffectModuleIds(){return[...this.activeRenderEffectModuleIds]}applyOverlayConfig({timelineEvents:e,timelineRanges:t,mechanics:i,renderEffects:s,boostPads:a}){this.activeTimelineEventSourceIds=new Set(e),this.activeTimelineRangeModuleIds=new Set(t),this.activeMechanicTimelineKinds=new Set(i),this.activeRenderEffectModuleIds=new Set(s)}reset(){this.teardownActiveModules(),this.clearStandalonePlugins(),this.activeModules=[],this.activeTimelineEventSourceIds=new Set,this.activeTimelineRangeModuleIds=new Set,this.activeMechanicTimelineKinds=new Set,this.activeRenderEffectModuleIds=new Set,this.removeRenderHook=null}setupActiveModules(){this.teardownActiveModules();const e=this.options.getContext();if(!e)return;const t=this.getActiveModuleIds();this.activeModules=this.options.modules.filter(i=>t.has(i.id)),this.options.boostPickupFilters.setup(e);for(const i of this.activeModules)i.setup(e);this.removeRenderHook=e.player.onBeforeRender(i=>{for(const s of this.activeModules)this.activeRenderEffectModuleIds.has(s.id)&&s.onBeforeRender(i)}),this.syncTimelineEvents(),this.syncTimelineRanges()}teardownActiveModules(){this.removeRenderHook?.(),this.removeRenderHook=null,this.clearTimelineEventSources(),this.clearTimelineRangeSources();for(const e of this.activeModules)e.teardown();this.activeModules=[]}toggleCapability(e,t,i){const s=this.getMutableActiveCapabilityIds(t);i?s.add(e):s.delete(e),this.setupActiveModules(),this.options.renderModuleSummary(),this.options.renderModuleSettings(),this.options.renderStatsWindows(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()}setMechanicTimelineKind(e,t){t?this.activeMechanicTimelineKinds.add(e):this.activeMechanicTimelineKinds.delete(e),this.options.requestConfigSync()}activateMechanicTimelineKind(e){this.activeMechanicTimelineKinds.add(e),this.syncTimelineEvents(),this.syncTimelineRanges(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()}clearTimelineEventSources(){for(const e of this.timelineSourceRemovers.values())e();this.timelineSourceRemovers.clear()}clearTimelineRangeSources(){for(const e of this.timelineRangeSourceRemovers.values())e();this.timelineRangeSourceRemovers.clear()}clearStandalonePlugins(){}syncBoostPadOverlayPlugin(){}toggleBoostPadOverlay(){this.options.renderModuleSummary(),this.options.requestConfigSync()}syncTimelineEvents(){this.clearTimelineEventSources();const e=this.options.getContext(),t=this.options.getTimelineOverlay();if(!(!t||!e)){for(const i of this.options.getEventTimelineSources(e)){if(!i.active)continue;const s=i.buildTimelineEvents();s.length!==0&&this.timelineSourceRemovers.set(i.timelineKey,t.addEventSource(this.options.withTimelineEventSeekTimes(s),{id:i.timelineId,label:i.label}))}t.refreshEvents()}}syncTimelineRanges(){this.clearTimelineRangeSources();const e=this.options.getContext(),t=this.options.getTimelineOverlay();if(!(!t||!e)){for(const i of this.activeModules)!this.activeTimelineRangeModuleIds.has(i.id)||!i.getTimelineRanges||this.timelineRangeSourceRemovers.set(i.id,t.addRangeSource(()=>i.getTimelineRanges?.(e)??[]));for(const i of this.options.getEventTimelineSources(e)){if(!i.active||!i.buildTimelineRanges)continue;const s=i.buildTimelineRanges();s.length!==0&&this.timelineRangeSourceRemovers.set(i.timelineKey,t.addRangeSource(s))}t.refreshRanges()}}getActiveModuleIds(){return new Set([...this.activeTimelineEventSourceIds,...this.activeTimelineRangeModuleIds,...this.activeRenderEffectModuleIds])}getMutableActiveCapabilityIds(e){return e==="events"?this.activeTimelineEventSourceIds:e==="ranges"?this.activeTimelineRangeModuleIds:this.activeRenderEffectModuleIds}}function C6(n){return new E6(n)}function ni(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function ww(n){return ni(n)&&(n.kind==="time"||n.kind==="frame")&&typeof n.value=="number"&&Number.isFinite(n.value)?{kind:n.kind,value:n.value}:null}function nd(n,e){if(n!=null){if(typeof n!="number"||!Number.isInteger(n)||!Number.isFinite(n)||n<0)throw new Error(`Review playlist page ${e} must be a non-negative integer.`);return n}}function Sw(n,e){if(n!=null){if(typeof n!="string")throw new Error(`Review playlist page ${e} must be a string.`);return n}}function A6(n){if(n!=null){if(!ni(n))throw new Error("Review playlist page must be an object.");return{next:Sw(n.next,"next"),previous:Sw(n.previous,"previous"),total:nd(n.total,"total"),count:nd(n.count,"count"),limit:nd(n.limit,"limit"),offset:nd(n.offset,"offset")}}}function R6(n){if(n!=null){if(!ni(n))throw new Error("Review playlist playback must be an object.");if(n.timeBase!==void 0&&n.timeBase!=="playback"&&n.timeBase!=="rawReplay")throw new Error('Review playlist playback timeBase must be "playback" or "rawReplay".');return{...n,timeBase:n.timeBase}}}function P6(n,e){if(n==null)return;if(!ni(n))throw new Error(`Review item ${e} perspective must be an object.`);if(n.kind!=="player")throw new Error(`Review item ${e} perspective kind must be "player".`);const t=typeof n.playerId=="string"&&n.playerId.trim()?n.playerId.trim():void 0,i=typeof n.playerName=="string"&&n.playerName.trim()?n.playerName.trim():void 0;if(!t&&!i)throw new Error(`Review item ${e} player perspective needs playerId or playerName.`);if(n.ballCam!==void 0&&n.ballCam!=="off"&&n.ballCam!=="on"&&n.ballCam!=="player")throw new Error(`Review item ${e} perspective ballCam must be off, on, or player.`);if(n.usePlayerCameraSettings!==void 0&&typeof n.usePlayerCameraSettings!="boolean")throw new Error(`Review item ${e} perspective usePlayerCameraSettings must be boolean.`);return{kind:"player",playerId:t,playerName:i,ballCam:n.ballCam,usePlayerCameraSettings:n.usePlayerCameraSettings}}function I6(n){if(!ni(n)||!Array.isArray(n.items))throw new Error("Review playlist must contain an items array.");const e=n.items.map((i,s)=>{if(!ni(i)||typeof i.replay!="string")throw new Error(`Invalid review item at index ${s}.`);const a=ww(i.start),r=ww(i.end);if(!a||!r)throw new Error(`Review item ${s+1} has invalid start or end.`);return{id:typeof i.id=="string"?i.id:void 0,replay:i.replay,start:a,end:r,label:typeof i.label=="string"?i.label:void 0,perspective:P6(i.perspective,s+1),meta:ni(i.meta)?i.meta:void 0}}),t=Array.isArray(n.replays)?n.replays.map(i=>!ni(i)||typeof i.id!="string"?null:{id:i.id,path:typeof i.path=="string"?i.path:void 0,label:typeof i.label=="string"?i.label:void 0,locator:ni(i.locator)?i.locator:void 0,meta:ni(i.meta)?i.meta:void 0}).filter(i=>i!==null):void 0;return{label:typeof n.label=="string"?n.label:void 0,replays:t,items:e,page:A6(n.page),playback:R6(n.playback),meta:n.meta}}function Tw(n){let e;try{e=JSON.parse(n)}catch(t){throw new Error(`Invalid review playlist JSON: ${t instanceof Error?t.message:String(t)}`)}return I6(e)}function L6(){const n=new URLSearchParams(window.location.search);return n.get("reviewPlaylist")?.trim()||n.get("review")?.trim()||n.get("playlist")?.trim()||n.get("playlistUrl")?.trim()||null}function k6(n){return/^\/(?:home|Users|tmp|var\/tmp|mnt|media|run\/user|nix\/store)\//.test(n)}function W1(n,e){const t=n.startsWith("path:")?n.slice(5):n;if(/^https?:\/\//i.test(t)||t.startsWith("/@fs/"))return t;if(t.startsWith("/")){if(k6(t))return`/@fs${t}`;if(e){const i=new URL(e,window.location.href);if(i.origin!==window.location.origin)return new URL(t,i.origin).href}return t}return e?new URL(t,e).href:t}function Ed(n,e){const t=e.replaysById.get(n.replay);if(t?.path)return t.path;if(ni(t?.locator)&&t.locator.kind==="path"&&typeof t.locator.path=="string")return t.locator.path;if(/^https?:\/\//i.test(n.replay)||n.replay.startsWith("/")||n.replay.startsWith("/@fs/")||n.replay.startsWith("path:"))return n.replay;throw new Error(`Review replay "${n.replay}" does not include a loadable path.`)}function Mw(n,e){const t=e.replaysById.get(n.replay),s=(t?.path??Ed(n,e)).replace(/^path:/,"").split("/").filter(Boolean).pop();return t?.label??s??"review replay"}function Cd(n){return typeof n=="number"&&Number.isFinite(n)?`${n.toFixed(2)}s`:"--"}function Ew(n){return n.kind==="time"?Cd(n.value):`frame ${Math.trunc(n.value)}`}function Qi(n,e){if(!ni(n.meta?.target))return null;const t=n.meta.target[e];return typeof t=="number"&&Number.isFinite(t)?t:null}function Ad(n,e){if(!ni(n.meta?.target))return null;const t=n.meta.target[e];return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):null}function D6(n,e){for(const[t,i]of[["eventTime","eventFrame"],["startTime","startFrame"],["endTime","endFrame"]]){const s=Qi(n,t),a=Ad(n,i),r=a===null?null:e.frames[a]?.time;if(s!==null&&typeof r=="number"&&Number.isFinite(r))return s-r}return 0}function X1(n,e,t){return t==="playback"?0:t==="rawReplay"&&typeof e.rawStartTime=="number"&&Number.isFinite(e.rawStartTime)?e.rawStartTime:D6(n,e)}function J_(n,e){return Math.min(Math.max(0,n),Math.max(0,e))}function O6(n,e,t,i){if(e.kind==="frame"){const a=Math.max(0,Math.trunc(e.value));return J_(t.frames[a]?.time??0,t.duration)}const s=X1(n,t,i);return J_(e.value-s,t.duration)}function F6(n,e,t){const i=V6(n);return i===null?null:J_(i-X1(n,e,t),e.duration)}function N6(n){const e=n.start.kind==="time"?n.start.value:null,t=n.end.kind==="time"?n.end.value:null,i=[`${Ew(n.start)} to ${Ew(n.end)}`];e!==null&&t!==null&&i.push(`${Math.max(0,t-e).toFixed(1)}s clip`);const s=Qi(n,"startTime")??Qi(n,"eventTime"),a=Qi(n,"endTime")??Qi(n,"eventTime");return e!==null&&s!==null&&i.push(`${Math.max(0,s-e).toFixed(1)}s preroll`),t!==null&&a!==null&&i.push(`${Math.max(0,t-a).toFixed(1)}s postroll`),i.join(" · ")}function U6(n){const e=Qi(n,"eventTime"),t=Qi(n,"startTime"),i=Qi(n,"endTime"),s=Ad(n,"eventFrame"),a=Ad(n,"startFrame"),r=Ad(n,"endFrame"),o=t!==null&&i!==null&&Math.abs(i-t)>.001?`${Cd(t)} to ${Cd(i)}`:Cd(e??t??i),l=a!==null&&r!==null&&r!==a?`frames ${a}-${r}`:s!==null?`frame ${s}`:a!==null?`frame ${a}`:null;return[o,l].filter(c=>c&&c!=="--").join(" · ")||"--"}function Fm(n,e){return n.label??n.meta?.eventTypeLabel??n.meta?.mechanicLabel??`Review item ${e+1}`}function B6(n){if(typeof n.meta?.playerName=="string"&&n.meta.playerName.trim())return n.meta.playerName.trim();if(ni(n.meta?.target)&&typeof n.meta.target.playerName=="string"){const e=n.meta.target.playerName.trim();return e||null}return null}function Cw(n,e){if(!n)return null;if(n.playerId){const i=e.find(s=>s.id===n.playerId);if(i)return i}const t=n.playerName?.toLowerCase();return t?e.find(i=>i.name.trim().toLowerCase()===t)??null:null}function Aw(n){if(typeof n.meta?.eventTypeLabel=="string"&&n.meta.eventTypeLabel.trim())return n.meta.eventTypeLabel;if(typeof n.meta?.mechanicLabel=="string"&&n.meta.mechanicLabel.trim())return n.meta.mechanicLabel;const e=n.meta?.eventType??n.meta?.mechanic;return typeof e=="string"?Dn(e):"--"}function z6(n){const e=n.meta?.eventCategory;return typeof e=="string"&&e.trim()?Dn(e.trim()):"--"}function H6(n){const e=n.meta?.eventType??n.meta?.mechanic;return typeof e=="string"&&e.trim()?e.trim().replaceAll("-","_"):null}function V6(n){return Qi(n,"eventTime")??Qi(n,"startTime")??Qi(n,"endTime")}class G6{constructor(e){this.options=e}createReplaySource(e,t,i){const s=Ed(e,t),a=W1(s,t.sourceUrl);return{name:Mw(e,t),preparingStatus:"Loading review replay...",async readBytes(){const r=await fetch(a,{signal:i});if(!r.ok){const o=r.statusText?` ${r.statusText}`:"";throw new Error(`Failed to fetch review replay from ${a} (${r.status}${o})`)}return new Uint8Array(await r.arrayBuffer())}}}initialize(e){const t=this.getReplayClipCounts(e);for(const[i,s]of this.getReplayItems(e)){let a="",r=i;try{a=Ed(s,e),r=Mw(s,e)}catch{r=e.replaysById.get(i)?.label??i}e.replayLoadStates.set(i,{replayId:i,label:r,path:a,clipCount:t.get(i)??0,status:"idle",progress:null,error:null})}}preload(e,t){if(e.preloading)return;const i=this.getNextReplayItems(e,t);i.length!==0&&(e.preloading=!0,(async()=>{try{for(const s of i){const a=s.replay,r=e.replayLoadStates.get(a);if(!(r?.status==="loaded"||r?.status==="loading"))try{await this.loadBundle(s,e)}catch{}}}finally{e.preloading=!1}})())}loadBundle(e,t){const i=t.replayLoadCache.get(e.replay);if(i)return i;const s=this.createReplaySource(e,t);this.updateLoadState(t,e.replay,{label:s.name,path:Ed(e,t),status:"loading",progress:null,error:null});const a=Promise.resolve().then(async()=>{const r=await s.readBytes();return Cf(r,{reportEveryNFrames:100,onProgress:o=>{this.updateLoadState(t,e.replay,{status:"loading",progress:o,error:null})}})}).then(r=>(this.updateLoadState(t,e.replay,{status:"loaded",progress:null,error:null}),r)).catch(r=>{throw t.replayLoadCache.delete(e.replay),this.updateLoadState(t,e.replay,{status:"error",error:r instanceof Error?r.message:String(r)}),r});return t.replayLoadCache.set(e.replay,a),a}render(e){const{reviewSummary:t,loadingSummary:i,loadingActive:s,loadingList:a}=this.options.elements,r=e?Array.from(e.replayLoadStates.values()):[],o=r.filter(h=>h.status==="loaded").length,l=r.filter(h=>h.status==="loading").length,c=r.filter(h=>h.status==="error").length,u=r.filter(h=>h.status==="idle").length,d=r.length===0?"0 replays":`${o}/${r.length} loaded${l>0?`, ${l} loading`:""}${c>0?`, ${c} failed`:""}`;if(t.textContent=d,i.textContent=d,s.textContent=r.length===0?"No playlist":l>0?`${l} active, ${u} pending`:c>0?`${c} failed`:e?.preloading?`Background queue, ${u} pending`:o===r.length?"Complete":`${u} pending`,a.replaceChildren(),!e||r.length===0){const h=document.createElement("p");h.className="stat-window-empty",h.textContent="No replay sources.",a.append(h);return}for(const h of r){const f=document.createElement("div");f.className=`mechanics-review-replay-load ${h.status}`;const p=document.createElement("div");p.className="mechanics-review-replay-load-main";const g=document.createElement("span");g.className="mechanics-review-replay-load-title",g.textContent=h.label;const _=document.createElement("span");_.className="mechanics-review-replay-load-meta",_.textContent=[h.replayId,`${h.clipCount} ${h.clipCount===1?"clip":"clips"}`,h.path].filter(Boolean).join(" · "),p.append(g,_);const m=document.createElement("strong");m.className="mechanics-review-replay-load-status",m.textContent=this.replayLoadStatusText(h);const v=document.createElement("div");v.className="mechanics-review-replay-load-progress";const y=document.createElement("span");y.style.width=`${Math.round(this.replayLoadProgressValue(h)*100)}%`,v.append(y),f.append(p,m,v),a.append(f)}}updateLoadState(e,t,i){const s=e.replayLoadStates.get(t)??{replayId:t,label:t,path:"",clipCount:0,status:"idle",progress:null,error:null};e.replayLoadStates.set(t,{...s,...i});const a=e.manifest.items[e.currentIndex];e.loading&&a?.replay===t&&i.progress&&this.options.onActiveLoadProgress(i.progress),this.options.isActiveReview(e)&&this.render(e)}getReplayItems(e){const t=new Map;for(const i of e.manifest.items)t.has(i.replay)||t.set(i.replay,i);return t}getReplayClipCounts(e){const t=new Map;for(const i of e.manifest.items)t.set(i.replay,(t.get(i.replay)??0)+1);return t}getNextReplayItems(e,t){const i=e.manifest.items[t]?.replay,s=new Set(i?[i]:[]),a=[];for(let r=t+1;r{const i=t.file.files?.[0];if(i)try{const s=Tw(await i.text());await this.loadPlaylist(s,null)}catch(s){console.error("Failed to load review playlist:",s),this.setStatus(s instanceof Error?s.message:"Failed to load review playlist")}finally{t.file.value=""}},{signal:e}),t.loadUrl.addEventListener("click",()=>{this.loadPlaylistFromUrl(t.url.value.trim()).catch(i=>{console.error("Failed to load review playlist URL:",i),this.setStatus(i instanceof Error?i.message:"Failed to load review playlist URL")})},{signal:e}),t.previous.addEventListener("click",()=>{const i=this.activeReview;i&&this.activateItem(Math.max(0,i.currentIndex-1))},{signal:e}),t.replay.addEventListener("click",()=>this.replayClip(),{signal:e}),t.next.addEventListener("click",()=>{const i=this.activeReview;i&&this.activateItem(Math.min(i.manifest.items.length-1,i.currentIndex+1))},{signal:e}),t.confirm.addEventListener("click",()=>{this.submitDecision("confirmed")},{signal:e}),t.reject.addEventListener("click",()=>{this.submitDecision("rejected")},{signal:e}),t.uncertain.addEventListener("click",()=>{this.submitDecision("uncertain")},{signal:e})}render(){const{elements:e}=this.options,t=this.activeReview,i=t?.manifest.items??[],s=t?i[t.currentIndex]??null:null,a=i.length>0;e.count.textContent=`${i.length} item${i.length===1?"":"s"}`,e.index.textContent=a&&t?`${t.currentIndex+1} / ${i.length}`:"0 / 0",e.title.textContent=s?Fm(s,t?.currentIndex??0):"No candidate selected",e.mechanic.textContent=s?Aw(s):"--",e.player.textContent=s?this.getPlayerName(s):"--",e.clip.textContent=s?N6(s):"--",e.event.textContent=s?U6(s):"--",e.reason.textContent=s?.meta?.reason??"--",e.previous.disabled=!t||t.loading||t.currentIndex<=0,e.replay.disabled=!t||t.loading||!t.currentClip,e.next.disabled=!t||t.loading||t.currentIndex>=i.length-1;const r=!t||t.loading||Rw(s)===null;if(e.confirm.disabled=r,e.reject.disabled=r,e.uncertain.disabled=r,this.options.replayLoads.render(t),e.list.replaceChildren(),!t||i.length===0){const o=document.createElement("p");o.className="stat-window-empty",o.textContent="No review playlist loaded.",e.list.append(o);return}i.forEach((o,l)=>{const c=document.createElement("button");c.type="button",c.className="mechanics-review-item",c.dataset.active=l===t.currentIndex?"true":"false",c.disabled=t.loading,c.addEventListener("click",()=>{this.activateItem(l)});const u=document.createElement("span");u.textContent=Fm(o,l);const d=document.createElement("strong");d.textContent=[z6(o),Aw(o),this.getPlayerName(o),Nm(o.meta?.reviewStatus)].filter(h=>h&&h!=="--").join(" · ")||"--",c.append(u,d),e.list.append(c)})}async loadPlaylist(e,t){const i=new Map;for(const s of e.replays??[])i.set(s.id,s);this.activeReview={manifest:e,sourceUrl:t,replaysById:i,replayLoadStates:new Map,replayLoadCache:new Map,currentIndex:0,loading:!1,preloading:!1,currentReplayId:null,currentClip:null},this.options.replayLoads.initialize(this.activeReview),this.options.showReplayLoadingWindow(),this.setStatus(e.label?`Loaded ${e.label}.`:"Loaded review playlist."),this.render(),e.items.length>0&&await this.activateItem(0)}async loadPlaylistFromUrl(e){if(!e){this.setStatus("Enter a review playlist URL.");return}const t=W1(e,window.location.href);this.setStatus("Loading review playlist...");const i=await fetch(t);if(!i.ok){const a=i.statusText?` ${i.statusText}`:"";throw new Error(`Failed to fetch review playlist from ${t} (${i.status}${a})`)}const s=Tw(await i.text());await this.loadPlaylist(s,i.url||t)}async activateItem(e){const t=this.activeReview,i=t?.manifest.items[e];if(!(!t||!i||t.loading)){t.loading=!0,t.currentIndex=e,this.render(),this.setStatus(`Loading ${Fm(i,e)}...`);try{if(!this.options.getReplayPlayer()||t.currentReplayId!==i.replay){const d=this.options.replayLoads.createReplaySource(i,t),h=this.options.replayLoads.loadBundle(i,t);await this.options.loadReplayBundleForDisplay(d,h),t.currentReplayId=i.replay}this.options.replayLoads.preload(t,e);const a=t.manifest.playback?.timeBase,r=Math.max(0,this.getBoundTime(i,i.start,a)),o=Math.min(this.options.getReplayPlayer()?.getState().duration??Number.POSITIVE_INFINITY,Math.max(r,this.getBoundTime(i,i.end,a)));if(!Number.isFinite(r)||!Number.isFinite(o)||o<=r)throw new Error("Review item has an empty playback range.");const l=this.options.getReplayPlayer(),c=l?Cw(i.perspective,l.replay.players):null;c&&this.options.applyClipPerspective({playerId:c.id,ballCam:i.perspective?.ballCam,usePlayerCameraSettings:i.perspective?.usePlayerCameraSettings}),this.options.resetReplayTransitionControls();const u=l===null?null:F6(i,l.replay,a);t.currentClip={startTime:r,endTime:o,targetTime:u},this.options.activateTimelineSource(i),this.options.getReplayPlayer()?.setState({currentTime:r,playing:!0,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),this.setStatus(u===null?`Playing ${r.toFixed(2)}s to ${o.toFixed(2)}s`:`Playing ${r.toFixed(2)}s to ${o.toFixed(2)}s; target ${u.toFixed(2)}s`)}catch(s){console.error("Failed to activate mechanics review item:",s),t.currentClip=null,this.setStatus(s instanceof Error?s.message:"Failed to load review item")}finally{t.loading=!1,this.render()}}}replayClip(){const e=this.activeReview?.currentClip,t=this.options.getReplayPlayer();!e||!t||t.setState({currentTime:e.startTime,playing:!0,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1})}async submitDecision(e){const t=this.activeReview,i=t?.manifest.items[t.currentIndex]??null,s=Rw(i);if(!t||!i||!s){this.setStatus("Current review item has no review endpoint.");return}this.setStatus(`Submitting ${Nm(e)}...`);const a=await fetch(s,{method:"POST",headers:{"content-type":"application/json",...X6()},credentials:"same-origin",body:JSON.stringify({status:e})});if(!a.ok){let r=`${a.status}${a.statusText?` ${a.statusText}`:""}`;try{const o=await a.json();typeof o.error=="string"&&(r=o.error)}catch{}this.setStatus(`Review failed: ${r}`);return}i.meta=i.meta??{},i.meta.reviewStatus=e,this.setStatus(`Marked ${Nm(e)}.`),this.render()}enforceClipBoundary(e){const t=this.activeReview?.currentClip,i=this.options.getReplayPlayer();if(!t||!i||this.boundaryGuard)return!1;const s=e.currentTime=t.endTime-.025;if(!s&&!a)return!1;this.boundaryGuard=!0;try{i.setState({currentTime:s?t.startTime:t.endTime,playing:!1,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),a&&this.setStatus(`Finished clip at ${t.endTime.toFixed(2)}s`)}finally{this.boundaryGuard=!1}return!0}getBoundTime(e,t,i){const s=this.options.getReplayPlayer();return s?O6(e,t,s.replay,i):t.kind==="time"?t.value:0}getPlayerName(e){const t=B6(e);if(t)return t;const i=this.options.getReplayPlayer()?.replay.players??[];return Cw(e.perspective,i)?.name??"--"}}function Nm(n){return typeof n=="string"&&n.trim()?n.replaceAll("_"," "):"unreviewed"}function Rw(n){if(!n)return null;if(typeof n.meta?.reviewEndpoint=="string"&&n.meta.reviewEndpoint)return n.meta.reviewEndpoint;const e=typeof n.meta?.eventId=="string"&&n.meta.eventId?n.meta.eventId:n.id;return e?`/api/v1/events/${encodeURIComponent(e)}/reviews`:null}function X6(){const n=new URLSearchParams(window.location.search),e=n.get("reviewToken")??n.get("token")??window.localStorage.getItem("rocket_sense_access_token");return e?{Authorization:`Bearer ${e}`}:{}}function K6(n){return new W6(n)}const q6=["replayUrl","replay_url","replay"],Y6=["r","replayUrlZ","replay_url_z"],j6=["ballchasing","ballchasingId","ballchasingUuid","ballchasingReplay"];function Z6(n){const e=n.replaceAll("-","+").replaceAll("_","/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=atob(t),s=new Uint8Array(i.length);for(let a=0;a{n.signal.aborted||(console.error("Failed to load replay URL:",t),n.statusReadout.textContent=t instanceof Error?t.message:"Failed to load replay URL")})}function i9(n){n.initialBundle?n.loadReplayBundleForDisplay({name:n.initialReplayName??"replay",preparingStatus:"Preparing replay...",async readBytes(){throw new Error("Replay bytes are not available for this preloaded replay")}},Promise.resolve(n.initialBundle)).catch(i=>{n.signal.aborted||(console.error("Failed to load preprocessed replay bundle:",i),n.statusReadout.textContent=i instanceof Error?i.message:"Failed to load preprocessed replay bundle")}):n.loadFromLocation!==!1&&n9(n);const e=L6();if(!e)return;const t=n.getMechanicsReviewController();t?.setUrl(e),n.showMechanicsReviewWindow(),t?.loadPlaylistFromUrl(e).catch(i=>{n.signal.aborted||(console.error("Failed to load mechanics review playlist from URL:",i),t?.setStatus(i instanceof Error?i.message:"Failed to load mechanics review playlist from URL"))})}function s9(n){const e=()=>{n.getSkipPostGoalTransitions().checked=!1,n.getSkipKickoffs().checked=!1},t=(i,s)=>{const a=n.getReplayPlayer();!a||!Number.isFinite(i)||(n.getMechanicsReviewController()?.clearCurrentClip(),e(),a.setState({currentTime:Math.max(0,i-n.goalWatchLeadSeconds),playing:s,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),n.scheduleConfigUrlUpdate())};return{watchGoalReplay(i,s){const a=n.getReplayPlayer();if(!a||!Number.isFinite(i))return;if(n.getMechanicsReviewController()?.clearCurrentClip(),s!==null&&a.replay.players.some(o=>o.id===s)){a.setAttachedPlayer(s),a.setCameraViewMode("follow");const o=n.getCameraControlsController();o&&(o.freeCameraPreset=null)}e(),a.setState({currentTime:Math.max(0,i-n.goalWatchLeadSeconds),playing:!0,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),n.scheduleConfigUrlUpdate()},cueGoalReplay(i){t(i,!1)},cueTimelineEvent(i){const s=n.getReplayPlayer();s&&(n.getMechanicsReviewController()?.clearCurrentClip(),e(),s.setState({currentTime:ny(i),skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),n.scheduleConfigUrlUpdate())},applyConfigToReplayPlayer(i){const s=n.getReplayPlayer();if(!s)return;s.setState(Y8(i.playback,i.camera,i));const a=n.getCameraControlsController();a&&(a.freeCameraPreset=i.camera.freePreset??null),i.camera.mode==="free"&&i.camera.freePreset&&s.setFreeCameraPreset(i.camera.freePreset),n.syncBoostPadOverlayPlugin(),n.setupActiveModules(),n.renderModuleSummary(),n.renderModuleSettings(),n.renderStatsWindows(s.getState().frameIndex)}}}function a9(n){let e=!1,t=null;const i=()=>n.getFloatingWindowController()?.getSingletonConfigs()??[],s=()=>n.getStatsWindowsController()?.getConfigs()??[],a=()=>{const o=n.getActiveModulesRuntime(),l=n.getReplayPlayer();return q8({playback:X8({replayPlayer:l,playbackRate:n.playbackRate,skipPostGoalTransitions:n.skipPostGoalTransitions,skipKickoffs:n.skipKickoffs}),camera:K8({replayPlayer:l,cameraControlsController:n.getCameraControlsController()}),activeTimelineEventSourceIds:o.getActiveTimelineEventSourceIds(),activeTimelineRangeModuleIds:o.getActiveTimelineRangeModuleIds(),activeMechanicTimelineKinds:o.getActiveMechanicTimelineKinds(),activeRenderEffectModuleIds:o.getActiveRenderEffectModuleIds(),initialConfig:n.getInitialConfig(),replayPlayer:l,boostPadOverlayEnabled:o.getBoostPadOverlayEnabled(),recording:n.getRecordingWindowController()?.getConfigSnapshot()??{},singletonWindows:i(),statsWindows:s(),moduleConfigs:W8(n.modules)})},r=o=>{z8($1(n.modules),o)};return{setApplyingConfig(o){e=o},reset(){t!==null&&(window.clearTimeout(t),t=null),e=!1},scheduleConfigUrlUpdate(){e||(t!==null&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null;const o=z1(new URL(window.location.href),a());window.history.replaceState(window.history.state,"",o)},150))},applyConfigToStaticControls(o){if(n.getActiveModulesRuntime().applyOverlayConfig(o.overlays),n.skipPostGoalTransitions.checked=o.playback.skipPostGoalTransitions??n.skipPostGoalTransitions.checked,n.skipKickoffs.checked=o.playback.skipKickoffs??n.skipKickoffs.checked,n.hitboxWireframes.checked=o.overlays.hitboxWireframes,n.hitboxOnlyMode.checked=o.overlays.hitboxOnlyMode,n.getCameraControlsController()?.applyNameplateLiftUu(o.camera.nameplateLiftUu),n.getCameraControlsController()?.setAutoPossessionEnabled(o.camera.autoPossession??!1,{requestConfigSync:!1}),o.playback.rate!==void 0){const l=Df(o.playback.rate);n.playbackRate.value=`${l}`,n.playbackRateReadout.textContent=wy(l)}n.getRecordingWindowController()?.applyConfig(o.recording),r(o.moduleConfigs),n.getFloatingWindowController()?.applySingletonConfigs(o.singletonWindows),n.getStatsWindowsController()?.replaceFromConfig(o.statsWindows),n.renderModuleSummary(),n.renderModuleSettings(),n.renderTimelineEventCount()}}}function r9(n){const e=t=>{const i=n.getLauncherToggle();n.getLauncherMenu().hidden=!t,i.setAttribute("aria-label",t?"Close menu":"Open menu"),i.setAttribute("aria-expanded",t?"true":"false")};return{bringWindowToFront(t){n.getFloatingWindowController()?.bringToFront(t)},showWindow(t){n.getFloatingWindowController()?.show(t)},toggleWindow(t){n.getFloatingWindowController()?.toggle(t)},hideWindow(t){n.getFloatingWindowController()?.hide(t)},setLauncherOpen:e,openReplayFilePicker(){n.getFileInput().click(),e(!1)},installWindowDragging(t,i){n.getFloatingWindowController()?.installDragging(t,i)},getElementWindowId(t){return t.closest("[data-window-id]")?.dataset.windowId??null}}}const Q_=4096,xr=5120,o9=893,l9=642,ts=1/105;class c9{constructor(e){this.options=e,this.options.body.innerHTML=` +
`}).join("")}
`},renderFocusedPlayerStats(e,t,i){return`
Events${be(i.statsTimeline,"dodge").filter(a=>Ct(a.player)===e).length}
`}}}function LW(){return{id:"half-flip",label:"Half Flip",setup(){},teardown(){},onBeforeRender(){},renderStats(n,e){const t=Ht(e.statsFrameLookup,n);return t?ci(t.players,i=>En(i.name,i.is_team_0,pw(i.half_flip),i.half_flip?.is_last_half_flip?'Last Half Flip':"")):""},renderFocusedPlayerStats(n,e,t){const i=Sn(t,e,n);return i?pw(i.half_flip):""}}}function kW(){return{id:"wavedash",label:"Wavedash",setup(){},teardown(){},onBeforeRender(){},getTimelineEvents(n){return CG(n.statsTimeline,n.replay)},renderStats(n,e){const t=Ht(e.statsFrameLookup,n);return t?ci(t.players,i=>En(i.name,i.is_team_0,mw(i.wavedash),i.wavedash?.is_last_wavedash?'Last Wavedash':"")):""},renderFocusedPlayerStats(n,e,t){const i=Sn(t,e,n);return i?mw(i.wavedash):""}}}function DW(){return ui({id:"whiff",label:"Whiff",select:n=>n.whiff,render:n=>tW(n),getTimelineEvents(n){return LG(n.statsTimeline,n.replay)}})}function OW(n){let e=null,t=null;const i=new Set,s=["speed_band","height_band"];return{id:"movement",label:"Movement",setup(){a()},teardown(){},onBeforeRender(){},getConfig(){return{breakdownClasses:r()}},applyConfig(o){if(i.clear(),o&&typeof o=="object"&&!Array.isArray(o)){const l=o.breakdownClasses;if(Array.isArray(l))for(const c of l)s.includes(c)&&i.add(c)}a(),n.rerenderCurrentState()},renderStats(o,l){const c=Ht(l.statsFrameLookup,o);return c?ci(c.players,u=>En(u.name,u.is_team_0,nw(u.movement,{breakdownClasses:r()}))):""},renderFocusedPlayerStats(o,l,c){const u=Sn(c,l,o);return u?nw(u.movement,{breakdownClasses:r()}):""},renderSettings(){if(!e){e=document.createElement("div"),e.className="module-settings-card";const o=document.createElement("div");o.className="module-settings-header";const l=document.createElement("div"),c=document.createElement("p");c.className="module-settings-eyebrow",c.textContent="Stat display";const u=document.createElement("h3");u.textContent="Movement breakdown",l.append(c,u),t=document.createElement("strong"),t.className="metric-readout",o.append(l,t);const d=document.createElement("div");d.className="module-settings-options";for(const h of[{className:"speed_band",label:"Speed band"},{className:"height_band",label:"Height band"}]){const f=document.createElement("label");f.className="toggle";const p=document.createElement("input");p.type="checkbox",p.dataset.breakdownClass=h.className,p.addEventListener("change",()=>{p.checked?i.add(h.className):i.delete(h.className),a(),n.rerenderCurrentState(),n.requestConfigSync?.()});const g=document.createElement("span");g.textContent=h.label,f.append(p,g),d.append(f)}e.append(o,d)}return a(),e}};function a(){if(e){for(const o of e.querySelectorAll("input[data-breakdown-class]")){const l=o.dataset.breakdownClass;o.checked=l?i.has(l):!1}if(t){const o=r();t.textContent=o.length>0?o.map(l=>({speed_band:"Speed band",height_band:"Height band"})[l]).join(" + "):"Total only"}}}function r(){return s.filter(o=>i.has(o))}}function FW(){return ui({id:"powerslide",label:"Powerslide",select:n=>n.powerslide,render:n=>eW(n),getTimelineEvents(n){return SG(n.statsTimeline,n.replay)}})}function NW(){return ui({id:"rotation",label:"Rotation",select:n=>n.rotation,render:n=>X$(n)})}function UW(){return ui({id:"demo",label:"Demo",select:n=>n.demo,render:n=>nW(n)})}function BW(){return ui({id:"bump",label:"Bump",select:n=>n.bump,render:n=>iW(n),getTimelineEvents(n){return AG(n.statsTimeline,n.replay)}})}function zW(){let n=null,e=1;return{id:C1,label:"Relative Positioning",setup(t){e=t.fieldScale,n=new u4(t.player.sceneState.replayRoot,t.replay,e)},teardown(){n?.dispose(),n=null},onBeforeRender(t){n?.update(t,e)},renderStats(t,i){const s=Ht(i.statsFrameLookup,t);return s?ci(s.players,a=>{const r=n$(i.replay,Ct(a.player_id),t),o=t$[r];return En(a.name,a.is_team_0,ow(a.positioning),`${o}`)}):""},renderFocusedPlayerStats(t,i,s){const a=Sn(s,i,t);return a?ow(a.positioning):""}}}function HW(){return{id:"absolute-positioning",label:"Absolute Positioning",setup(n){aw.acquire(n)},teardown(){aw.release()},onBeforeRender(){},getTimelineRanges(n){return e$(n.statsTimeline,n.replay)},renderStats(n,e){const t=Ht(e.statsFrameLookup,n);return t?ci(t.players,i=>En(i.name,i.is_team_0,lw(i.positioning))):""},renderFocusedPlayerStats(n,e,t){const i=Sn(t,e,n);return i?lw(i.positioning):""}}}function VW(n,e={}){return[gW(),yW(),vW(),bW(),xW(),EW(),AW(),CW(),i$(n),s$(),a$(),r$(),o$(),zW(),HW(),NW(),IW(),PW(),LW(),kW(),mW(n),DW(),RW(),TW(),MW(),SW(),_W(n,e.boostPickupFilters),wW(),OW(n),FW(),UW(),BW()]}const GW=new Set(["player_id","name","is_team_0"]),$W=["is_last_","time_since_last_","frames_since_last_"];function WW(n){return n===null||typeof n=="number"||typeof n=="string"||typeof n=="boolean"||Array.isArray(n)}function XW(n,e){let t=n;for(const i of e){if(!t||typeof t!="object"||Array.isArray(t))return;t=t[i]}return t}function KW(n){return n==null?"--":typeof n=="number"?Number.isFinite(n)?Number.isInteger(n)?`${n}`:`${Number(n.toFixed(3))}`:"--":typeof n=="boolean"?n?"true":"false":Array.isArray(n)?n.length===0?"[]":JSON.stringify(n):`${n}`}function qW(n,e){if($W.some(a=>n.startsWith(a)))return!0;const t=n.match(/^last_(.+)_time$/),i=n.match(/^last_(.+)_frame$/),s=t?.[1]??i?.[1];return s?`is_last_${s}`in e||`time_since_last_${s}`in e||`frames_since_last_${s}`in e:!1}function Z_(n,e,t,i){if(!n||typeof n!="object"||Array.isArray(n))return;const s=n;for(const[a,r]of Object.entries(s)){if(e==="player"&&t.length===0&&GW.has(a)||qW(a,s))continue;const o=[...t,a];if(WW(r)){const l=`${e}:${o.join(".")}`;i.push({id:l,label:o.join("."),category:o[0]??e,scope:e,path:o,read(c){return XW(c,o)},format:KW});continue}Z_(r,e,o,i)}}function YW(n){const e=new Set;return n.filter(t=>e.has(t.id)?!1:(e.add(t.id),!0))}function O1(n,e){const t=[];return n&&Z_(n,"player",[],t),e&&Z_(e,"team",[],t),YW(t).sort((i,s)=>i.label.localeCompare(s.label))}function jW(){return O1(_y(),Vo())}function Go(n){return n?O1(n.players[0]??_y(),n.team_zero??n.team_one??Vo()):jW()}function F1(n){return n.toLowerCase().replace(/[_/.-]+/g," ").replace(/\s+/g," ").trim()}function ZW(n){return F1(n).split(" ").filter(Boolean)}function JW(n,e){const t=ZW(e);if(t.length===0)return 0;const i=F1([n.scope,n.category,n.label,n.id,...n.path].join(" "));let s=0;for(const a of t){const r=i.indexOf(a);if(r<0)return null;s+=r}return s+i.length/1e3}function QW(n,e){return n.map((t,i)=>({definition:t,index:i,score:JW(t,e)})).filter(t=>t.score!==null).sort((t,i)=>t.score-i.score||t.index-i.index).map(t=>t.definition)}function Ai(n){if(!Number.isFinite(n))return"--";const e=Math.floor(Math.max(0,n)/60),t=Math.max(0,n)-e*60;return`${e}:${t.toFixed(1).padStart(4,"0")}`}class e8{constructor(e){this.options=e}statsWindows=new Map;nextStatsWindowId=1;getConfigs(){return[...this.statsWindows.values()].map(e=>({id:e.id,kind:e.kind,placement:this.options.readWindowPlacement(e.element),playerId:e.playerId,team:e.team,entries:e.entries.map(t=>({statId:t.statId,targetId:t.targetId}))}))}clear(){for(const e of this.statsWindows.values())e.element.remove();this.statsWindows.clear(),this.nextStatsWindowId=1}replaceFromConfig(e){this.clear();for(const t of e)this.create(t.kind,t)}render(e=this.options.getReplayPlayer()?.getState().frameIndex??0,t={}){for(const i of this.statsWindows.values())t.preserveOpenPickers&&(i.pickerOpen||i.element.contains(document.activeElement))||this.renderStatsWindow(i,e)}create(e,t){const i=t?.id??`stats-${this.nextStatsWindowId++}`,s=Number.parseInt(i.replace(/^stats-/,""),10);Number.isFinite(s)&&(this.nextStatsWindowId=Math.max(this.nextStatsWindowId,s+1));const{x:a,y:r}=this.getStatsWindowDefaultPosition(),o=document.createElement("section");o.className="stats-window",o.dataset.windowId=i,o.style.setProperty("--window-x",`${a}px`),o.style.setProperty("--window-y",`${r}px`),t&&this.options.applyWindowPlacement(o,t.placement);const l=document.createElement("header");l.className="stats-window-header";const c=document.createElement("div");c.className="stats-window-actions";const u=document.createElement("button");if(u.type="button",u.className="stats-window-action",u.textContent="Hide",c.append(u),this.hasStatsWindowScopeSelector(e))l.classList.add("stats-window-header-actions-only"),l.append(c);else{const f=document.createElement("h2");f.textContent=this.getStatsWindowTitle(e),l.append(f,c)}const d=document.createElement("div");d.className="stats-window-body",o.append(l,d),this.options.layer.append(o);const h={id:i,kind:e,entries:t?.entries.map(f=>({key:`${i}:${f.statId}:${f.targetId??"scope"}`,statId:f.statId,targetId:f.targetId}))??[],playerId:t?.playerId??this.options.getReplayPlayer()?.replay.players[0]?.id??null,team:t?.team??"blue",pickerOpen:!1,query:"",element:o,body:d};return u.addEventListener("click",()=>{o.hidden=!0,this.options.requestConfigSync()}),this.statsWindows.set(i,h),t||this.options.bringWindowToFront(o),this.options.setLauncherOpen(!1),this.renderStatsWindow(h),this.options.requestConfigSync(),h}getStatById(e){return this.options.getStatRegistry().find(t=>t.id===e)??null}getCurrentStatsFrame(e){const t=this.options.getStatsFrameLookup();return t?Ht(t,e):null}getTeamSnapshot(e,t){return t==="blue"?e.team_zero??null:e.team_one??null}getTeamLabel(e){return e==="blue"?"Blue":"Orange"}getPlayerTeamClass(e){const t=this.options.getReplayPlayer()?.replay.players.find(i=>i.id===e);return t?ua(t.isTeamZero):null}getTeamScopeClass(e){return ua(e==="blue")}appendGroupedPlayerOptions(e,t){const i=this.options.getReplayPlayer()?.replay.players??[];for(const s of["blue","orange"]){const a=i.filter(o=>o.isTeamZero===(s==="blue"));if(a.length===0)continue;const r=document.createElement("optgroup");r.label=`${this.getTeamLabel(s)} team`;for(const o of a)r.append(new Option(o.name,o.id,o.id===t,o.id===t));e.append(r)}}getStatsWindowScopeTeamClass(e){return e.kind==="player"?this.getPlayerTeamClass(e.playerId):e.kind==="team"?this.getTeamScopeClass(e.team??"blue"):null}getStatTargetTeamClass(e,t){return e.scope==="player"?this.getPlayerTeamClass(t):this.getTeamScopeClass(t==="orange"?"orange":"blue")}getStatsWindowTitle(e){switch(e){case"player":return"Player stats";case"team":return"Team stats";case"all-players":return"All players stats";case"all-teams":return"All teams stats";case"kickoff-overview":return"Kickoff details";case"goals-overview":return"Goal labels";case"ad-hoc":return"Ad hoc stats"}}hasStatsWindowScopeSelector(e){return e==="player"||e==="team"}hasStatsWindowStatPicker(e){return e!=="goals-overview"&&e!=="kickoff-overview"}getStatsWindowAllowedScope(e){switch(e){case"player":case"all-players":return"player";case"team":case"all-teams":return"team";case"kickoff-overview":return null;case"goals-overview":return null;case"ad-hoc":return null}}getStatsWindowDefaultPosition(){const e=this.statsWindows.size*18;return{x:Math.max(12,Math.min(window.innerWidth-360,96+e)),y:Math.max(64,Math.min(window.innerHeight-240,96+e))}}renderStatsWindow(e,t=this.options.getReplayPlayer()?.getState().frameIndex??0){const i=document.activeElement,s=i instanceof HTMLInputElement&&i.dataset.statsWindowSearch===e.id,a=s?i.selectionStart:null,r=s?i.selectionEnd:null,o=s?i.selectionDirection:null;if(e.body.replaceChildren(),this.renderStatsWindowScope(e),this.hasStatsWindowStatPicker(e.kind)&&(this.renderStatsWindowAddControl(e),this.renderStatsWindowPicker(e)),this.renderStatsWindowEntries(e,t),s){const l=e.body.querySelector(`input[data-stats-window-search="${e.id}"]`);l?.focus({preventScroll:!0}),l&&a!==null&&r!==null&&l.setSelectionRange(a,r,o??"none")}}renderStatsWindowScope(e){if(e.kind!=="player"&&e.kind!=="team")return;const t=document.createElement("div");t.className="stats-window-scope-row";const i=document.createElement("select");i.className="stats-window-scope-select";const s=this.getStatsWindowScopeTeamClass(e);s&&i.classList.add(s),i.setAttribute("aria-label",e.kind==="player"?"Player stats target":"Team stats target"),e.kind==="player"?(this.appendGroupedPlayerOptions(i,e.playerId),i.value=e.playerId??"",i.addEventListener("change",()=>{e.playerId=i.value||null,this.renderStatsWindow(e),this.options.requestConfigSync()})):(i.append(new Option("Blue","blue",e.team==="blue",e.team==="blue"),new Option("Orange","orange",e.team==="orange",e.team==="orange")),i.value=e.team??"blue",i.addEventListener("change",()=>{e.team=i.value==="orange"?"orange":"blue",this.renderStatsWindow(e),this.options.requestConfigSync()})),t.append(i),e.body.append(t)}renderStatsWindowAddControl(e){const t=document.createElement("button");if(t.type="button",t.className="stats-window-add-button",t.textContent="+",t.title="Add stat",t.setAttribute("aria-label","Add stat"),t.setAttribute("aria-expanded",String(e.pickerOpen)),this.activateButton(t,()=>{e.pickerOpen=!e.pickerOpen,this.renderStatsWindow(e)}),this.hasStatsWindowScopeSelector(e.kind)){e.body.querySelector(".stats-window-scope-row")?.append(t);return}const i=document.createElement("div");i.className="stats-window-toolbar",i.append(t),e.body.append(i)}activateButton(e,t){let i=!1;e.addEventListener("pointerdown",s=>{e.disabled||(i=!0,s.preventDefault(),t())}),e.addEventListener("click",()=>{if(i){i=!1;return}e.disabled||t()})}renderStatsWindowPicker(e){const t=document.createElement("div");if(t.className="stats-window-picker",t.hidden=!e.pickerOpen,t.hidden){e.body.append(t);return}const i=this.getStatsWindowAllowedScope(e.kind),s=document.createElement("input");s.type="search",s.placeholder="Search stats",s.value=e.query,s.dataset.statsWindowSearch=e.id;const a=document.createElement("div");a.className="stats-window-picker-list",s.addEventListener("input",()=>{e.query=s.value,this.renderStatsWindowPickerList(e,a,i)}),this.renderStatsWindowPickerList(e,a,i),t.append(s,a),e.body.append(t)}renderStatsWindowPickerList(e,t,i){t.replaceChildren();const s=this.options.getStatRegistry(),a=i?s.filter(l=>l.scope===i):s,r=QW(a,e.query),o=new Map;for(const l of r){const c=o.get(l.category)??[];c.push(l),o.set(l.category,c)}for(const[l,c]of o){if(c.length<2)continue;const u=document.createElement("button");u.type="button",u.className="stats-window-picker-item",u.innerHTML=`Add all ${l}${c.length}`,this.activateButton(u,()=>{for(const d of c)this.addStatToWindow(e,d);this.renderStatsWindow(e),this.options.requestConfigSync()}),t.append(u)}for(const l of r){const c=document.createElement("button");c.type="button",c.className="stats-window-picker-item",c.innerHTML=`${l.label}${l.scope}`,c.disabled=e.kind!=="ad-hoc"&&e.entries.some(u=>u.statId===l.id),this.activateButton(c,()=>{this.addStatToWindow(e,l),this.renderStatsWindow(e),this.options.requestConfigSync()}),t.append(c)}if(r.length===0){const l=document.createElement("p");l.className="stat-window-empty",l.textContent=s.length===0?"No stats available.":"No matching stats.",t.append(l)}}addStatToWindow(e,t){const i=e.kind==="ad-hoc"?this.getDefaultAdHocTargetId(t):void 0;e.entries.some(s=>s.statId===t.id&&s.targetId===i)||e.entries.push({key:`${e.id}:${t.id}:${i??"scope"}`,statId:t.id,targetId:i})}getDefaultAdHocTargetId(e){return e.scope==="player"?this.options.getReplayPlayer()?.replay.players[0]?.id??"":"blue"}removeStatFromWindow(e,t){const i=e.entries.findIndex(s=>s.key===t);i>=0&&e.entries.splice(i,1)}renderStatsWindowEntries(e,t){if(e.kind==="goals-overview"){this.renderGoalLabelsOverview(e);return}if(e.kind==="kickoff-overview"){this.renderKickoffOverview(e,t);return}const i=this.getStatsWindowAllowedScope(e.kind),s=e.entries.map(r=>({entry:r,definition:this.getStatById(r.statId)})).filter(r=>r.definition!==null&&(!i||r.definition.scope===i));if(s.length===0){const r=document.createElement("p");r.className="stat-window-empty",r.textContent="No stats added.",e.body.append(r);return}const a=this.getCurrentStatsFrame(t);if(!a){const r=document.createElement("p");r.className="stat-window-empty",r.textContent="Load a replay to show stats.",e.body.append(r);return}if(e.kind==="all-players"){this.renderAllPlayersStats(e,a,s);return}if(e.kind==="all-teams"){this.renderAllTeamsStats(e,a,s);return}if(e.kind==="player"){const r=e.playerId?a.players.find(o=>Ct(o.player_id)===e.playerId)??null:null;this.renderScopedStatList(e,r,s);return}if(e.kind==="team"){this.renderScopedStatList(e,this.getTeamSnapshot(a,e.team??"blue"),s);return}e.kind==="ad-hoc"&&this.renderAdHocStats(e,a,s)}renderGoalLabelsOverview(e){const t=this.options.getStatsTimeline(),i=this.options.getReplayPlayer()?.replay??null;if(!t||!i){this.appendStatsWindowEmpty(e,"Load a replay to show goal labels.");return}const s=[...be(t,"goal_context")].sort((o,l)=>o.time-l.time),a=s.map((o,l)=>l);if(a.length===0){this.appendStatsWindowEmpty(e,"No goals loaded.");return}const r=document.createElement("div");r.className="goal-label-list";for(const o of a){const l=s[o]??null,c=[...l?.tags??[]].sort((M,C)=>M.kind.localeCompare(C.kind)||C.metadata.confidence-M.metadata.confidence),u=l?.time??0,d=l?.scorer??null,h=d?Ct(d):null,f=d?i.players.find(M=>M.id===h)?.name??h:"Unknown scorer",p=l?.scoring_team_is_team_0??null,g=document.createElement("section");g.className="goal-label-item",p!==null&&g.classList.add(ua(p));const _=document.createElement("header"),m=document.createElement("h3");m.textContent=`Goal ${o+1}`;const v=document.createElement("span");v.textContent=`${Ai(u)} · ${f}`,_.append(m,v);const y=document.createElement("div");if(y.className="goal-label-tags",c.length===0){const M=document.createElement("span");M.className="goal-label-tag goal-label-tag-empty",M.textContent="Unlabeled",y.append(M)}else for(const M of c){const C=document.createElement("span");C.className="goal-label-tag";const w=g1(M);C.textContent=`${Dn(M.kind)} ${Math.round(M.metadata.confidence*100)}%${w?` - ${w}`:""}`,y.append(C)}const b=document.createElement("div");b.className="goal-label-actions";const S=document.createElement("button");S.type="button",S.className="goal-label-watch",S.textContent="Watch",S.addEventListener("click",()=>{this.options.watchGoalReplay(u,h)});const x=document.createElement("button");x.type="button",x.textContent="Cue",x.addEventListener("click",()=>{this.options.cueGoalReplay(u)}),b.append(S,x),g.append(_,y,b),r.append(g)}e.body.append(r)}renderKickoffOverview(e,t){const i=this.options.getStatsTimeline(),s=this.options.getReplayPlayer()?.replay??null;if(!i||!s){this.appendStatsWindowEmpty(e,"Load a replay to show kickoff details.");return}const a=this.getClosestKickoffEvent(i,t);if(!a){this.appendStatsWindowEmpty(e,"No kickoff events loaded.");return}const r=a.payload.payload,o=document.createElement("section");o.className="kickoff-overview";const l=document.createElement("header");l.className="kickoff-overview-hero";const c=document.createElement("div"),u=document.createElement("h3");u.textContent=this.formatKickoffTitle(a);const d=document.createElement("span");d.textContent=`Nearest kickoff · resolved at ${Ai(r.end_time)}`,c.append(u,d);const h=document.createElement("strong"),f=this.teamClassFromNullable(r.winning_team_is_team_0);h.className="kickoff-overview-victor",f&&h.classList.add(f),h.textContent=this.formatOutcome(r),l.append(c,h);const p=document.createElement("div");p.className="kickoff-overview-summary",p.append(this.renderKickoffMetric("Win strength",`${this.formatNullableNumber(r.win_strength,2)} · ${this.formatKickoffLabelValue("kickoff_win_strength",r.win_strength_band)}`),this.renderKickoffMetric("First touch",this.formatFirstTouch(r)),this.renderKickoffMetric("Advantage",this.formatAdvantage(r)),this.renderKickoffMetric("Contested",this.formatContested(r)));const g=document.createElement("div");g.className="kickoff-detail-grid",g.append(this.renderKickoffDetail("Kickoff start",Ai(r.start_time)),this.renderKickoffDetail("Movement start",Ai(r.movement_start_time)),this.renderKickoffDetail("Live action",r.live_action_start_time===null?"--":Ai(r.live_action_start_time)),this.renderKickoffDetail("First touch",r.first_touch_time===null?"--":Ai(r.first_touch_time)),this.renderKickoffDetail("Resolution",Ai(r.end_time)),this.renderKickoffDetail("After first touch",this.formatSeconds(r.advantage_seconds_after_first_touch)));const _=document.createElement("div");_.className="kickoff-strategy-list",_.append(this.renderKickoffTeamStrategy("Blue",r.team_zero_taker,r.team_zero_non_takers),this.renderKickoffTeamStrategy("Orange",r.team_one_taker,r.team_one_non_takers)),o.append(l,p,g,_),e.body.append(o)}getClosestKickoffEvent(e,t){return yc(e).filter(s=>s.payload.kind==="kickoff").sort((s,a)=>{const r=this.kickoffFrameDistance(s.payload.payload,t),o=this.kickoffFrameDistance(a.payload.payload,t);return r!==o?r-o:s.payload.payload.start_frame-a.payload.payload.start_frame})[0]??null}kickoffFrameDistance(e,t){return t>=e.start_frame&&t<=e.end_frame?0:Math.min(Math.abs(t-e.start_frame),Math.abs(t-e.end_frame))}renderKickoffMetric(e,t){const i=document.createElement("div");i.className="kickoff-metric";const s=document.createElement("span");s.textContent=e;const a=document.createElement("strong");return a.textContent=t,i.append(s,a),i}renderKickoffDetail(e,t){const i=document.createElement("div");i.className="kickoff-detail-row";const s=document.createElement("span");s.textContent=e;const a=document.createElement("strong");return a.textContent=t,i.append(s,a),i}renderKickoffTeamStrategy(e,t,i){const s=document.createElement("section");s.className=`kickoff-strategy-team ${e==="Blue"?"team-blue":"team-orange"}`;const a=document.createElement("h4");a.textContent=e,s.append(a);const r=document.createElement("p");if(r.className="kickoff-strategy-line",r.textContent=t?`${this.getPlayerName(t.player)}: ${this.formatKickoffLabelValue("kickoff_approach",t.approach)} from ${this.formatKickoffLabelValue("kickoff_spawn",t.spawn_position)} (${this.formatKickoffLabelValue("taker_outcome",t.outcome)}, ${this.formatSeconds(t.time_to_ball)})`:"No taker detected",s.append(r),i.length>0){const o=document.createElement("ul");o.className="kickoff-support-list";for(const l of i){const c=document.createElement("li");c.textContent=`${this.getPlayerName(l.player)}: ${this.formatKickoffLabelValue("support_behavior",l.support_behavior)} from ${this.formatKickoffLabelValue("kickoff_spawn",l.spawn_position)}`,o.append(c)}s.append(o)}return s}formatOutcome(e){return e.winning_team_is_team_0===!0?"Blue wins":e.winning_team_is_team_0===!1?"Orange wins":e.outcome==="neutral"?"Neutral":"Unknown"}formatFirstTouch(e){if(!e.first_touch_player)return"--";const t=e.first_touch_team_is_team_0===!0?"Blue":e.first_touch_team_is_team_0===!1?"Orange":"Unknown",i=e.first_touch_time===null?"--":Ai(e.first_touch_time);return`${t} · ${this.getPlayerName(e.first_touch_player)} · ${i}`}formatAdvantage(e){if(e.advantage==="no_advantage")return"No advantage";const t=e.advantage_team_is_team_0===!0?"Blue":e.advantage_team_is_team_0===!1?"Orange":"Unknown",i=e.advantage.replace(/^team_(zero|one)_/,""),s=e.advantage_player?` · ${this.getPlayerName(e.advantage_player)}`:"",a=e.advantage_time===null?"":` · ${Ai(e.advantage_time)}`;return`${t} ${this.formatKickoffLabelValue("kickoff_advantage",i)}${s}${a}`}formatContested(e){return e.kickoff_possession_outcome==="contested"?"Yes":e.kickoff_possession_team_is_team_0===!0?`No · Blue ${this.formatPossessionOutcome(e.kickoff_possession_outcome)}`:e.kickoff_possession_team_is_team_0===!1?`No · Orange ${this.formatPossessionOutcome(e.kickoff_possession_outcome)}`:`No · ${this.formatPossessionOutcome(e.kickoff_possession_outcome)}`}formatPossessionOutcome(e){return e.endsWith("_advantage")?"advantage":e.endsWith("_possession")?"possession":this.formatKickoffLabelValue("kickoff_possession_outcome",e)}formatKickoffType(e){return this.formatKickoffLabelValue("kickoff_type",e)}formatKickoffTitle(e){const t=e.payload.payload,i=this.formatKickoffDirection(t.kickoff_direction),s=[this.formatKickoffType(t.kickoff_type),i].filter(Boolean).join(" ");return[e.meta.label,s].filter(Boolean).join(" · ")}formatKickoffDirection(e){return e==="unknown"?"":`(${this.formatKickoffLabelValue("kickoff_direction",e)})`}formatNullableNumber(e,t){return e===null||!Number.isFinite(e)?"--":e.toFixed(t)}formatSeconds(e){return e===null||!Number.isFinite(e)?"--":`${e.toFixed(2)}s`}formatLabel(e){return e.replace(/^team_zero_/,"blue_").replace(/^team_one_/,"orange_").replaceAll("_"," ").replace(/\b\w/g,t=>t.toUpperCase())}formatKickoffLabelValue(e,t){const i=t.replace(/^team_zero_/,"blue_").replace(/^team_one_/,"orange_");return e==="kickoff_advantage"?this.formatLabel(i.replace(/^blue_/,"").replace(/^orange_/,"")):e==="kickoff_possession_outcome"?this.formatLabel(i.replace(/^blue_/,"Blue ").replace(/^orange_/,"Orange ")):this.formatLabel(i)}teamClassFromNullable(e){return e===null?null:ua(e)}getPlayerName(e){const t=Ct(e);return this.options.getReplayPlayer()?.replay.players.find(i=>i.id===t)?.name??t}appendStatsWindowEmpty(e,t){const i=document.createElement("p");i.className="stat-window-empty",i.textContent=t,e.body.append(i)}renderScopedStatList(e,t,i){const s=document.createElement("div");s.className="stats-window-stat-list";for(const{entry:a,definition:r}of i)s.append(this.renderStatRow(e,a,r,t?r.format(r.read(t)):"--"));e.body.append(s)}renderAllPlayersStats(e,t,i){const s=document.createElement("div");s.className="stats-window-team-list";for(const a of["blue","orange"]){const r=t.players.filter(h=>h.is_team_0===(a==="blue"));if(r.length===0)continue;const o=document.createElement("section");o.className=`stats-window-team-group ${this.getTeamScopeClass(a)}`;const l=document.createElement("header");l.className="stats-window-team-header";const c=document.createElement("h3");c.textContent=`${this.getTeamLabel(a)} team`;const u=document.createElement("span");u.textContent=`${r.length} player${r.length===1?"":"s"}`,l.append(c,u),o.append(l);const d=document.createElement("div");d.className="stats-window-entity-list";for(const h of r){const f=document.createElement("section");f.className=`stats-window-entity ${ua(h.is_team_0)}`;const p=document.createElement("h4");p.className="stats-window-entity-title",p.textContent=h.name,f.append(p);for(const{entry:g,definition:_}of i)f.append(this.renderStatRow(e,g,_,_.format(_.read(h))));d.append(f)}o.append(d),s.append(o)}e.body.append(s)}renderAllTeamsStats(e,t,i){const s=document.createElement("div");s.className="stats-window-entity-list";for(const a of["blue","orange"]){const r=this.getTeamSnapshot(t,a),o=document.createElement("section");o.className=`stats-window-entity ${this.getTeamScopeClass(a)}`;const l=document.createElement("h3");l.className="stats-window-entity-title",l.textContent=this.getTeamLabel(a),o.append(l);for(const{entry:c,definition:u}of i)o.append(this.renderStatRow(e,c,u,r?u.format(u.read(r)):"--"));s.append(o)}e.body.append(s)}renderAdHocStats(e,t,i){const s=document.createElement("div");s.className="stats-window-stat-list";for(const{entry:a,definition:r}of i){const o=this.getAdHocTarget(t,r,a.targetId);s.append(this.renderStatRow(e,a,r,o?r.format(r.read(o)):"--"))}e.body.append(s)}getAdHocTarget(e,t,i){return t.scope==="player"?e.players.find(s=>Ct(s.player_id)===i)??e.players[0]??null:this.getTeamSnapshot(e,i==="orange"?"orange":"blue")}renderStatRow(e,t,i,s){const a=document.createElement("div");a.className="stats-window-stat-row";const r=document.createElement("span");if(r.className="stats-window-stat-name",r.textContent=i.label,e.kind==="ad-hoc"){const c=document.createElement("select");c.className="stats-window-stat-target";const u=this.getStatTargetTeamClass(i,t.targetId);u&&c.classList.add(u),i.scope==="player"?this.appendGroupedPlayerOptions(c,t.targetId):c.append(new Option("Blue","blue",t.targetId==="blue",t.targetId==="blue"),new Option("Orange","orange",t.targetId==="orange",t.targetId==="orange")),c.value=t.targetId??"",c.addEventListener("change",()=>{const d=c.value;if(e.entries.some(f=>f!==t&&f.statId===t.statId&&f.targetId===d)){this.renderStatsWindow(e);return}const h=e.entries.findIndex(f=>f.key===t.key);h>=0&&(e.entries[h]={key:`${e.id}:${t.statId}:${d}`,statId:t.statId,targetId:d}),this.renderStatsWindow(e),this.options.requestConfigSync()}),r.append(" ",c)}const o=document.createElement("span");o.className="stats-window-stat-value",o.textContent=s;const l=document.createElement("button");return l.type="button",l.className="stats-window-stat-remove",l.textContent="x",l.addEventListener("click",()=>{this.removeStatFromWindow(e,t.key),this.renderStatsWindow(e),this.options.requestConfigSync()}),a.append(r,o,l),a}}function t8(n){return new e8(n)}const n8=new Set(["module:dodge","module:touch","module:powerslide"]),i8=["stats-stream:"],Ih=["#3b82f6","#06b6d4","#22c55e","#a855f7","#f97316","#ef4444","#f59e0b","#ec4899"],Ff="#d1d9e0",Ty=Ih[0],My=Ih[4],s8=[{id:"core",label:"Shots, saves, assists",buildEvents(n){return n.replay.timelineEvents.filter(e=>e.kind==="shot"||e.kind==="save"||e.kind==="assist")}},{id:"demo",label:"Demos",buildEvents(n){return n.replay.timelineEvents.filter(e=>e.kind==="demo")}}],a8=[];function N1(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function U1(n){if(typeof n=="string"&&n.length>0)return n;if(!N1(n))return null;const[e,t]=Object.entries(n)[0]??[];return!e||t==null?null:typeof t=="string"||typeof t=="number"?`${e}:${t}`:`${e}:${JSON.stringify(t)}`}function B1(n){return n.split(/[_-]+/).filter(e=>e.length>0).map(e=>e.slice(0,1).toUpperCase()).join("").slice(0,3)||"E"}function r8(n){if(typeof n!="number"||!Number.isFinite(n))return null;const e=Math.abs(n)<1?2:1;return`${n.toFixed(e).replace(/\.0+$/,"").replace(/(\.\d*[1-9])0+$/,"$1")}s`}function Zi(n){return typeof n!="string"||n.length===0?null:n.split(/[_-]+/).filter(e=>e.length>0).map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1)}`).join(" ")}function o8(n){return n==="team_zero_side"?"Blue side":n==="team_one_side"?"Orange side":n==="neutral"?"Neutral zone":Zi(n)}function l8(n){const e=Zi(n);return e?`${e.toLowerCase()} third`:null}function c8(n){return n==="team_zero_third"?"Blue third":n==="team_one_third"?"Orange third":n==="neutral_third"?"Neutral third":Zi(n)}function u8(n){return n==="team_zero"?"Blue":n==="team_one"?"Orange":n==="neutral"?"Neutral":Zi(n)}function Pd(n){return N1(n.payload.payload)?n.payload.payload:{}}function z1(n){return n===!0?Ty:n===!1?My:null}function d8(n){return n==="team_zero_side"?Ty:n==="team_one_side"?My:n==="neutral"?Ff:null}function h8(n){return n==="team_zero"?Ty:n==="team_one"?My:n==="neutral"?Ff:null}function f8(n){return typeof n=="boolean"?z1(n):null}const p8={ball_half(n){return d8(Pd(n).field_half)},possession(n){return h8(Pd(n).possession_state)},player_possession(n){return f8(Pd(n).is_team_0)}};function H1(n,e,t){return p8[n]?.(e)??z1(t)??Ff}function mi(n){return n.filter(e=>!!e).join(" | ")}function m8({event:n,playerName:e,streamLabel:t,teamLabel:i}){const s=Pd(n),a=r8(s.duration);if(n.payload.kind==="ball_half"){const r=o8(s.field_half),o=s.active===!1?"Ball half inactive":r?`Ball on ${r.toLowerCase()}`:null;return mi([o??t,a])}if(n.payload.kind==="ball_third"){const r=c8(s.field_third),o=s.active===!1?"Ball third inactive":r?`Ball in ${r.toLowerCase()}`:null;return mi([o??t,a])}if(n.payload.kind==="territorial_pressure"){const r=Zi(s.end_reason),o=`${i??""} territorial pressure`.trim();return mi([r?`${o} ended: ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="possession"){const r=u8(s.possession_state),o=l8(s.field_third),l=r?`${r} possession`:t;return mi([l,o,a])}if(n.payload.kind==="controlled_play"){const r=e?`${e} controlled play`:t;return mi([r,a])}if(n.payload.kind==="ball_carry"){const r=e?`${e} ${t.toLowerCase()}`:t;return mi([r,a])}if(n.payload.kind==="player_activity"){const r=Zi(s.state),o=e?`${e} positioning`:t;return mi([r?`${o} ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="field_third"){const r=Zi(s.state),o=e?`${e} positioning`:t;return mi([r?`${o} in ${r.toLowerCase()} third`:o,a])}if(n.payload.kind==="field_half"){const r=Zi(s.state),o=e?`${e} positioning`:t;return mi([r?`${o} in ${r.toLowerCase()} half`:o,a])}if(n.payload.kind==="ball_depth"){const r=Zi(s.state),o=e?`${e} ball depth`:t;return mi([r?`${o}: ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="depth_role"){const r=Zi(s.state),o=e?`${e} depth role`:t;return mi([r?`${o}: ${r.toLowerCase()}`:o,a])}if(n.payload.kind==="shadow_defense"){const r=e?`${e} shadow defense`:t;return mi([r,a])}if(n.payload.kind==="rotation_role"){const r=Zi(s.state),o=e?`${e} rotation`:t;return mi([r?`${o}: ${r.toLowerCase()}`:o,a])}return e?`${e} ${t.toLowerCase()}`:t}function _8(n,e,t){const i=Dn(e),s=new Map(n.replay.players.map(a=>[a.id,a.name]));return t.flatMap((a,r)=>{const o=a.meta.timing.type==="moment"?{time:a.meta.timing.time,frame:a.meta.timing.frame}:{time:a.meta.timing.end_time,frame:a.meta.timing.end_frame},l=U1(a.meta.primary_player),c=l?s.get(l)??l:null,u=a.meta.team_is_team_0??null,d=u==null?null:u?"Blue":"Orange",h=a.meta.id||`${e}:${o.frame??o.time}:${r}`,f=H1(e,a,u);return[{id:`stats-stream:${h}`,time:n.replay.frames[o.frame??-1]?.time??o.time,frame:o.frame,kind:e,label:m8({event:a,playerName:c,streamLabel:i,teamLabel:d}),shortLabel:B1(e),playerId:l,playerName:c,isTeamZero:u,color:f}]})}function g8(n,e,t){const i=Dn(e),s=new Map(n.replay.players.map(a=>[a.id,a.name]));return t.flatMap((a,r)=>{if(a.meta.timing.type!=="span")return[];const o={startTime:a.meta.timing.start_time,endTime:a.meta.timing.end_time,startFrame:a.meta.timing.start_frame,endFrame:a.meta.timing.end_frame},l=a.meta.team_is_team_0??null,c=l==null?null:l?"Blue":"Orange",u=U1(a.meta.primary_player),d=u?s.get(u)??u:null,h=H1(e,a,l),f=a.meta.id||`${e}:${o.startFrame??o.startTime}:${o.endFrame??o.endTime}:${r}`,p=d?`${d} ${i.toLowerCase()}`:c?`${c} ${i.toLowerCase()}`:i;let g=`stats-stream:${e}`,_=i;return a.meta.scope==="player"&&u?(g=`stats-stream:${e}:player:${u}`,_=d?`${d} ${i.toLowerCase()}`:i):a.meta.scope==="team"&&l!=null&&(g=`stats-stream:${e}:team:${l?"0":"1"}`,_=c?`${c} ${i.toLowerCase()}`:i),[{id:`stats-stream:${f}`,startTime:n.replay.frames[o.startFrame??-1]?.time??o.startTime,endTime:Math.max(n.replay.frames[o.startFrame??-1]?.time??o.startTime,n.replay.frames[o.endFrame??-1]?.time??o.endTime),lane:g,laneLabel:_,label:p,shortLabel:B1(e),isTeamZero:l,color:h}]}).sort((a,r)=>a.startTime!==r.startTime?a.startTime-r.startTime:(a.id??"").localeCompare(r.id??""))}function y8(n,e,t,i){return[...new Set([...AM,...yc(n.statsTimeline).map(a=>a.meta.stream)])].flatMap(a=>{const r=yc(n.statsTimeline).filter(u=>u.meta.stream===a);if(i.has(a)&&r.length>0)return[];const o=r.some(u=>u.meta.timing.type==="span"),l=o?g8(n,a,r):[],c=_8(n,a,r);return[{id:`stats-stream:${a}`,playlistId:`stats-stream:${a}`,timelineKey:`stats-stream:${a}`,timelineId:`stats-stream:${a}`,group:"Event streams",label:Dn(a),count:o?l.length:c.length,active:e.has(`stats-stream:${a}`),buildTimelineEvents(){return o?[]:c},buildPlaylistEvents(){return c},buildTimelineRanges:o?()=>l:void 0,setActive(u){t(`stats-stream:${a}`,u)}}]})}function v8(n){return new Set([...n.filter(e=>e.getTimelineEvents).map(e=>e.id),...v1])}function b8(){return[...v1].sort((n,e)=>Dn(n).localeCompare(Dn(e)))}function x8({ctx:n,modules:e,activeTimelineEventSourceIds:t,activeMechanicTimelineKinds:i,toggleEventSource:s,setMechanicTimelineKind:a}){if(!n)return[];const r=[];for(const o of s8){const l=o.buildEvents(n),c=l.length;r.push({id:o.id,playlistId:`replay:${o.id}`,timelineKey:`events:${o.id}`,timelineId:`events:${o.id}`,group:"Replay",label:o.label,count:c,active:t.has(o.id),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){s(o.id,u)}})}for(const o of e.filter(l=>l.getTimelineEvents)){const l=o.getTimelineEvents?.(n)??[],c=l.length;r.push({id:o.id,playlistId:`module:${o.id}`,timelineKey:`module:${o.id}`,timelineId:`module:${o.id}`,group:"Stats",label:o.label,count:c,active:t.has(o.id),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){s(o.id,u)}})}for(const o of a8){const l=o.buildEvents(n),c=l.length;r.push({id:o.id,playlistId:`extra:${o.id}`,timelineKey:`extra:${o.id}`,timelineId:`extra:${o.id}`,group:"Stats",label:o.label,count:c,active:t.has(o.id),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){s(o.id,u)}})}r.push(...y8(n,t,s,v8(e)));for(const o of b8()){const l=y1[o](n.statsTimeline,n.replay),c=l.length;r.push({id:`mechanic:${o}`,playlistId:`mechanic:${o}`,timelineKey:`mechanic:${o}`,timelineId:`mechanic:${o}`,group:"Event types",label:Dn(o),count:c,active:i.has(o),buildTimelineEvents(){return l},buildPlaylistEvents(){return l},setActive(u){a(o,u)}})}return r.sort((o,l)=>o.label.localeCompare(l.label))}function w8(n,e){if(!n)return[];const t=[{id:"replay:goals",group:"Replay",label:"Goals",events:n.replay.timelineEvents.filter(s=>s.kind==="goal")}],i=e.map(s=>({id:s.playlistId,group:s.group,label:s.label,events:s.buildPlaylistEvents()}));return[...t,...i]}function J_(n,e){const t=n.map(i=>i.id);return e===null?new Set(t.filter(i=>!n8.has(i)&&!i8.some(s=>i.startsWith(s)))):new Set(t.filter(i=>e.has(i)))}function S8(n,e){const t=n.playerId??null,i=t?e.findIndex(s=>s.id===t):-1;return i>=0?Ih[i%Ih.length]:n.color??Ff}function T8({sources:n,activeSourceIds:e,replayPlayers:t}){const i=J_(n,e);return n.filter(s=>i.has(s.id)).flatMap(s=>s.events.map((a,r)=>({key:`${s.id}:${a.id??`${a.kind}:${a.time}:${r}`}`,sourceId:s.id,sourceLabel:s.label,event:a,color:S8(a,t)}))).sort((s,a)=>s.event.time!==a.event.time?s.event.time-a.event.time:(s.event.label??s.sourceLabel).localeCompare(a.event.label??a.sourceLabel))}class M8{constructor(e){this.options=e}getSources(e=this.options.getContext()){return x8({ctx:e,modules:this.options.modules,activeTimelineEventSourceIds:this.options.getActiveTimelineEventSourceIds(),activeMechanicTimelineKinds:this.options.getActiveMechanicTimelineKinds(),toggleEventSource:this.options.toggleEventSource,setMechanicTimelineKind:this.options.setMechanicTimelineKind})}countVisibleSources(e){return e.replay.timelineEvents.filter(i=>i.kind==="goal").length+this.getSources(e).filter(i=>i.active).reduce((i,s)=>i+s.count,0)}render(){const{body:e}=this.options;e.replaceChildren();const t=this.getSources();if(t.length===0){const d=document.createElement("p");d.className="stat-window-empty",d.textContent="No events loaded.",e.append(d);return}const i=document.createElement("div");i.className="mechanics-actions";const s=document.createElement("button");s.type="button",s.className="module-summary-item",s.addEventListener("click",()=>{for(const d of t)d.setActive(!0);this.options.setupActiveModules(),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.render(),this.options.renderModuleSummary(),this.options.renderModuleSettings(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()});const a=document.createElement("span");a.textContent="All events";const r=document.createElement("strong");r.textContent=`${t.length}`,s.append(a,r);const o=document.createElement("button");o.type="button",o.className="module-summary-item",o.addEventListener("click",()=>{for(const d of t)d.setActive(!1);this.options.setupActiveModules(),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.render(),this.options.renderModuleSummary(),this.options.renderModuleSettings(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()});const l=document.createElement("span");l.textContent="No events";const c=document.createElement("strong");c.textContent="Off",o.append(l,c),i.append(s,o),e.append(i);const u=this.renderSourceList(t);u&&e.append(u)}renderSourceList(e){if(e.length===0)return null;const t=document.createElement("div");t.className="module-list mechanics-list mechanics-event-list",t.style.setProperty("--event-source-columns",`${E8(e.length)}`);for(const i of e){const s=document.createElement("button");s.type="button",s.className="module-summary-item",s.dataset.active=i.active?"true":"false",s.setAttribute("aria-pressed",i.active?"true":"false"),s.addEventListener("click",()=>{i.setActive(!i.active),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.render(),this.options.renderTimelineEventCount()});const a=document.createElement("span");a.textContent=i.label;const r=document.createElement("strong");r.textContent=`${i.active?"On":"Off"} ${i.count}`,s.append(a,r),t.append(s)}return t}}function E8(n){return window.innerWidth<640?1:window.innerWidth<900?n>=7?2:1:n>=13?3:n>=7?2:1}function C8(n){return new M8(n)}const A8=new Set(["ceiling-shot","fifty-fifty","ball_half",C1,"absolute-positioning","dodge","speed-flip","touch"]),vw="touch";class R8{constructor(e){this.options=e}renderSummary(){const{summary:e}=this.options.elements;e.replaceChildren();const t=this.options.getTimelineSources(),i=t.map(o=>this.renderTimelineSourceToggle(o)),s=[],a=[],r=this.options.getContext();for(const o of this.options.modules){const l=A8.has(o.id);!o.getTimelineEvents&&!o.getTimelineRanges&&!l||(t.length===0&&o.getTimelineEvents&&i.push(this.renderCapabilityToggle(o.id,Bm(o,"events"),"events")),o.getTimelineRanges&&s.push(this.renderCapabilityToggle(o.id,Bm(o,"ranges"),"ranges",r?o.getTimelineRanges(r).length:void 0)),l&&a.push(this.renderCapabilityToggle(o.id,Bm(o,"effects"),"effects")))}a.push(this.renderBoostPickupAnimationToggle()),e.append(Um("Timeline markers",i),Um("Timeline ranges",s),Um("In-game visualizations",a))}renderSettings(){const{settings:e}=this.options.elements;e.replaceChildren();const t=this.options.getContext(),i=this.options.getActiveModules().filter(s=>s.id!=="boost"&&s.id!==vw).map(s=>s.renderSettings?.(t)??null).filter(s=>s instanceof HTMLElement);if(i.length===0){e.hidden=!0,this.renderBoostPickupFiltersWindow(),this.renderTouchControlsWindow();return}e.hidden=!1,e.append(...i),this.renderBoostPickupFiltersWindow(),this.renderTouchControlsWindow()}renderBoostPickupAnimationToggle(){const e=this.options.getBoostPickupAnimationEnabled(),t=document.createElement("button");t.type="button",t.className="module-summary-item",t.dataset.active=e?"true":"false",t.setAttribute("aria-pressed",e?"true":"false"),t.addEventListener("click",this.options.toggleBoostPickupAnimation);const i=document.createElement("span");i.textContent="Boost pickup animation";const s=document.createElement("strong");return s.textContent=e?"On":"Off",t.append(i,s),t}renderCapabilityToggle(e,t,i,s){const r=this.options.getActiveCapabilityIds(i).has(e),o=document.createElement("button");o.type="button",o.className="module-summary-item",o.dataset.active=r?"true":"false",o.setAttribute("aria-pressed",r?"true":"false"),o.addEventListener("click",()=>{this.options.toggleCapability(e,i,!this.options.getActiveCapabilityIds(i).has(e))});const l=document.createElement("span");l.textContent=t;const c=document.createElement("strong");return c.textContent=bw(r,s),o.append(l,c),o}renderTimelineSourceToggle(e){const t=document.createElement("button");t.type="button",t.className="module-summary-item",t.dataset.active=e.active?"true":"false",t.setAttribute("aria-pressed",e.active?"true":"false"),t.addEventListener("click",()=>{e.setActive(!e.active),this.options.syncTimelineEvents(),this.options.syncTimelineRanges(),this.options.renderTimelineEventCount(),this.options.requestConfigSync(),this.renderSummary()});const i=document.createElement("span");i.textContent=P8(e);const s=document.createElement("strong");return s.textContent=bw(e.active,e.count),t.append(i,s),t}renderBoostPickupFiltersWindow(){const e=this.options.getContext(),t=this.options.boostPickupFilters.renderSettings(e,{showHeader:!1});this.options.elements.boostPickupFilters.replaceChildren(t)}renderTouchControlsWindow(){const e=this.options.getContext(),i=this.options.modules.find(s=>s.id===vw)?.renderSettings?.(e)??null;this.options.elements.touchControls.replaceChildren(),i instanceof HTMLElement&&this.options.elements.touchControls.append(i)}}function Um(n,e){const t=document.createElement("section");t.className="module-summary-group";const i=document.createElement("h3");i.textContent=n;const s=document.createElement("div");return s.className="module-list",s.append(...e),t.append(i,s),t}function bw(n,e){const t=n?"On":"Off";return e==null?t:`${t} ${e}`}function P8(n){return n.group==="Replay"?n.label:`${n.label} events`}function Bm(n,e){const t={"absolute-positioning:ranges":"Position zones","backboard:events":"Backboard","ball-carry:events":"Ball carry","boost:ranges":"Boost pickup timeline","bump:events":"Bump","ceiling-shot:events":"Ceiling shot","demo:events":"Demo","dodge-reset:events":"Dodge refresh","double-tap:events":"Double tap","fifty-fifty:events":"50/50","fifty-fifty:ranges":"50/50","dodge:events":"Dodge","half-flip:events":"Half flip","possession:ranges":"Possession","powerslide:events":"Powerslide","powerslide:ranges":"Powerslide","ball_half:ranges":"Half control","ball_third:ranges":"Third control","rush:ranges":"Rush","speed-flip:events":"Speed flip","touch:events":"Touch","wavedash:events":"Wavedash"},i={"absolute-positioning":"Position zones","ceiling-shot":"Ceiling shot labels","fifty-fifty":"50/50 labels",dodge:"Dodge impulse arrows",ball_half:"Half control","relative-positioning":"Player roles","speed-flip":"Speed flip labels",touch:"Touch labels"};return e==="effects"?i[n.id]??n.label:t[`${n.id}:${e}`]??`${n.label} timeline`}function I8(n){return new R8(n)}var yn=Uint8Array,vi=Uint16Array,Ey=Int32Array,Nf=new yn([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Uf=new yn([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Q_=new yn([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),V1=function(n,e){for(var t=new vi(31),i=0;i<31;++i)t[i]=e+=1<>1|(Bt&21845)<<1;aa=(aa&52428)>>2|(aa&13107)<<2,aa=(aa&61680)>>4|(aa&3855)<<4,tg[Bt]=((aa&65280)>>8|(aa&255)<<8)>>1}var vs=(function(n,e,t){for(var i=n.length,s=0,a=new vi(e);s>l]=c}else for(o=new vi(i),s=0;s>15-n[s]);return o}),ba=new yn(288);for(var Bt=0;Bt<144;++Bt)ba[Bt]=8;for(var Bt=144;Bt<256;++Bt)ba[Bt]=9;for(var Bt=256;Bt<280;++Bt)ba[Bt]=7;for(var Bt=280;Bt<288;++Bt)ba[Bt]=8;var bc=new yn(32);for(var Bt=0;Bt<32;++Bt)bc[Bt]=5;var k8=vs(ba,9,0),D8=vs(ba,9,1),O8=vs(bc,5,0),F8=vs(bc,5,1),zm=function(n){for(var e=n[0],t=1;te&&(e=n[t]);return e},Gi=function(n,e,t){var i=e/8|0;return(n[i]|n[i+1]<<8)>>(e&7)&t},Hm=function(n,e){var t=e/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},Cy=function(n){return(n+7)/8|0},Bf=function(n,e,t){return(e==null||e<0)&&(e=0),(t==null||t>n.length)&&(t=n.length),new yn(n.subarray(e,t))},N8=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],ps=function(n,e,t){var i=new Error(e||N8[n]);if(i.code=n,Error.captureStackTrace&&Error.captureStackTrace(i,ps),!t)throw i;return i},U8=function(n,e,t,i){var s=n.length,a=0;if(!s||e.f&&!e.l)return t||new yn(0);var r=!t,o=r||e.i!=2,l=e.i;r&&(t=new yn(s*3));var c=function(we){var Re=t.length;if(we>Re){var k=new yn(Math.max(Re*2,we));k.set(t),t=k}},u=e.f||0,d=e.p||0,h=e.b||0,f=e.l,p=e.d,g=e.m,_=e.n,m=s*8;do{if(!f){u=Gi(n,d,1);var v=Gi(n,d+1,3);if(d+=3,v)if(v==1)f=D8,p=F8,g=9,_=5;else if(v==2){var x=Gi(n,d,31)+257,M=Gi(n,d+10,15)+4,C=x+Gi(n,d+5,31)+1;d+=14;for(var w=new yn(C),E=new yn(19),R=0;R>4;if(y<16)w[R++]=y;else{var F=0,W=0;for(y==16?(W=3+Gi(n,d,3),d+=2,F=w[R-1]):y==17?(W=3+Gi(n,d,7),d+=3):y==18&&(W=11+Gi(n,d,127),d+=7);W--;)w[R++]=F}}var H=w.subarray(0,x),ie=w.subarray(x);g=zm(H),_=zm(ie),f=vs(H,g,1),p=vs(ie,_,1)}else ps(1);else{var y=Cy(d)+4,b=n[y-4]|n[y-3]<<8,S=y+b;if(S>s){l&&ps(0);break}o&&c(h+b),t.set(n.subarray(y,S),h),e.b=h+=b,e.p=d=S*8,e.f=u;continue}if(d>m){l&&ps(0);break}}o&&c(h+131072);for(var le=(1<>4;if(d+=F&15,d>m){l&&ps(0);break}if(F||ps(2),De<256)t[h++]=De;else if(De==256){Le=d,f=null;break}else{var Ke=De-254;if(De>264){var R=De-257,Oe=Nf[R];Ke=Gi(n,d,(1<>4;Z||ps(3),d+=Z&15;var ie=L8[re];if(re>3){var Oe=Uf[re];ie+=Hm(n,d)&(1<m){l&&ps(0);break}o&&c(h+131072);var Te=h+Ke;if(h>8},Ml=function(n,e,t){t<<=e&7;var i=e/8|0;n[i]|=t,n[i+1]|=t>>8,n[i+2]|=t>>16},Vm=function(n,e){for(var t=[],i=0;ih&&(h=a[i].s);var f=new vi(h+1),p=ng(t[u-1],f,0);if(p>e){var i=0,g=0,_=p-e,m=1<<_;for(a.sort(function(x,M){return f[M.s]-f[x.s]||x.f-M.f});ie)g+=m-(1<>=_;g>0;){var y=a[i].s;f[y]=0&&g;--i){var b=a[i].s;f[b]==e&&(--f[b],++g)}p=e}return{t:new yn(f),l:p}},ng=function(n,e,t){return n.s==-1?Math.max(ng(n.l,e,t+1),ng(n.r,e,t+1)):e[n.s]=t},ww=function(n){for(var e=n.length;e&&!n[--e];);for(var t=new vi(++e),i=0,s=n[0],a=1,r=function(l){t[i++]=l},o=1;o<=e;++o)if(n[o]==s&&o!=e)++a;else{if(!s&&a>2){for(;a>138;a-=138)r(32754);a>2&&(r(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(r(s),--a;a>6;a-=6)r(8304);a>2&&(r(a-3<<5|8208),a=0)}for(;a--;)r(s);a=1,s=n[o]}return{c:t.subarray(0,i),n:e}},El=function(n,e){for(var t=0,i=0;i>8,n[s+2]=n[s]^255,n[s+3]=n[s+1]^255;for(var a=0;a4&&!E[Q_[L-1]];--L);var O=c+5<<3,D=El(s,ba)+El(a,bc)+r,U=El(s,h)+El(a,g)+r+14+3*L+El(M,E)+2*M[16]+3*M[17]+7*M[18];if(l>=0&&O<=D&&O<=U)return X1(e,u,n.subarray(l,l+c));var F,W,H,ie;if(ks(e,u,1+(U15&&(ks(e,u,De[C]>>5&127),u+=De[C]>>12)}}else F=k8,W=ba,H=O8,ie=bc;for(var C=0;C255){var Ke=Oe>>18&31;Ml(e,u,F[Ke+257]),u+=W[Ke+257],Ke>7&&(ks(e,u,Oe>>23&31),u+=Nf[Ke]);var Z=Oe&31;Ml(e,u,H[Z]),u+=ie[Z],Z>3&&(Ml(e,u,Oe>>5&8191),u+=Uf[Z])}else Ml(e,u,F[Oe]),u+=W[Oe]}return Ml(e,u,F[256]),u+W[256]},B8=new Ey([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),K1=new yn(0),z8=function(n,e,t,i,s,a){var r=a.z||n.length,o=new yn(i+r+5*(1+Math.ceil(r/7e3))+s),l=o.subarray(i,o.length-s),c=a.l,u=(a.r||0)&7;if(e){u&&(l[0]=a.r>>3);for(var d=B8[e-1],h=d>>13,f=d&8191,p=(1<7e3||E>24576)&&(F>423||!c)){u=Sw(n,l,0,b,S,x,C,E,L,w-L,u),E=M=C=0,L=w;for(var W=0;W<286;++W)S[W]=0;for(var W=0;W<30;++W)x[W]=0}var H=2,ie=0,le=f,me=D-U&32767;if(F>2&&O==y(w-me))for(var Le=Math.min(h,F)-1,De=Math.min(32767,w),Ke=Math.min(258,F);me<=De&&--le&&D!=U;){if(n[w+H]==n[w+H-me]){for(var Oe=0;OeH){if(H=Oe,ie=me,Oe>Le)break;for(var Z=Math.min(me,Oe-2),re=0,W=0;Wre&&(re=se,U=Te)}}}D=U,U=g[D],me+=D-U&32767}if(ie){b[E++]=268435456|eg[H]<<18|xw[ie];var we=eg[H]&31,Re=xw[ie]&31;C+=Nf[we]+Uf[Re],++S[257+we],++x[Re],R=w+H,++M}else b[E++]=n[w],++S[n[w]]}}for(w=Math.max(w,R);w=r&&(l[u/8|0]=c,k=r),u=X1(l,u+1,n.subarray(w,k))}a.i=r}return Bf(o,0,i+Cy(u)+s)},H8=function(n,e,t,i,s){if(!s&&(s={l:1},e.dictionary)){var a=e.dictionary.subarray(-32768),r=new yn(a.length+n.length);r.set(a),r.set(n,a.length),n=r,s.w=a.length}return z8(n,e.level==null?6:e.level,e.mem==null?s.l?Math.ceil(Math.max(8,Math.min(13,Math.log(n.length)))*1.5):20:12+e.mem,t,i,s)};function V8(n,e){return H8(n,e||{},0,0)}function q1(n,e){return U8(n,{i:2},e,e)}var Tw=typeof TextEncoder<"u"&&new TextEncoder,ig=typeof TextDecoder<"u"&&new TextDecoder,G8=0;try{ig.decode(K1,{stream:!0}),G8=1}catch{}var $8=function(n){for(var e="",t=0;;){var i=n[t++],s=(i>127)+(i>223)+(i>239);if(t+s>n.length)return{s:e,r:Bf(n,t-1)};s?s==3?(i=((i&15)<<18|(n[t++]&63)<<12|(n[t++]&63)<<6|n[t++]&63)-65536,e+=String.fromCharCode(55296|i>>10,56320|i&1023)):s&1?e+=String.fromCharCode((i&31)<<6|n[t++]&63):e+=String.fromCharCode((i&15)<<12|(n[t++]&63)<<6|n[t++]&63):e+=String.fromCharCode(i)}};function W8(n,e){var t;if(Tw)return Tw.encode(n);for(var i=n.length,s=new yn(n.length+(n.length>>1)),a=0,r=function(c){s[a++]=c},t=0;ts.length){var o=new yn(a+8+(i-t<<1));o.set(s),s=o}var l=n.charCodeAt(t);l<128||e?r(l):l<2048?(r(192|l>>6),r(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|n.charCodeAt(++t)&1023,r(240|l>>18),r(128|l>>12&63),r(128|l>>6&63),r(128|l&63)):(r(224|l>>12),r(128|l>>6&63),r(128|l&63))}return Bf(s,0,a)}function Y1(n,e){var t;if(ig)return ig.decode(n);var i=$8(n),s=i.s,t=i.r;return t.length&&ps(8),s}const Lh=1,sg="cfg",Mw="cfgDebug";function X8(n){let e="";for(const t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function K8(n){const e=n.replaceAll("-","+").replaceAll("_","/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=atob(t),s=new Uint8Array(i.length);for(let a=0;a!Oi(e)||!l6(e.id)?null:{id:e.id,placement:J1(e.placement)}).filter(e=>e!==null):[]}function r6(n){return Array.isArray(n)?n.map(e=>!Oi(e)||typeof e.id!="string"||!c6(e.kind)?null:{id:e.id,kind:e.kind,placement:J1(e.placement),playerId:Q1(e.playerId)??null,team:e.team==="orange"?"orange":e.team==="blue"?"blue":null,entries:o6(e.entries)}).filter(e=>e!==null):[]}function o6(n){return Array.isArray(n)?n.map(e=>!Oi(e)||typeof e.statId!="string"?null:{statId:e.statId,targetId:typeof e.targetId=="string"?e.targetId:void 0}).filter(e=>e!==null):[]}function J1(n){const e=Oi(n)?n:{},t=Oi(e.viewport)?e.viewport:{};return{x:Ln(e.x)??8,y:Ln(e.y)??8,viewport:{width:kh(t.width)??1,height:kh(t.height)??1},zIndex:Ln(e.zIndex),visible:ti(e.visible)??!0}}function l6(n){return n==="camera"||n==="scoreboard"||n==="playback"||n==="recording"||n==="training-pack"||n==="mechanics"||n==="event-playlist"||n==="mechanics-review"||n==="replay-loading"||n==="boost-pickups"||n==="touch-controls"||n==="touch-legend"||n==="shot-visualization"||n==="missed-events"}function c6(n){return n==="player"||n==="team"||n==="all-players"||n==="all-teams"||n==="kickoff-overview"||n==="goals-overview"||n==="ad-hoc"}function Oi(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Ln(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function kh(n){const e=Ln(n);return e!==void 0&&e>0?e:void 0}function ti(n){return typeof n=="boolean"?n:void 0}function Q1(n){return n===null?null:typeof n=="string"?n:void 0}function Cl(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"):[]}function Ew(n,e,t){return Math.min(t,Math.max(e,n))}const u6=["camera","scoreboard","playback","recording","training-pack","mechanics","event-playlist","mechanics-review","replay-loading","boost-pickups","touch-controls","touch-legend","shot-visualization","missed-events"];class d6{constructor(e){this.options=e}nextZIndex=30;reset(){this.nextZIndex=30}bringToFront(e){e.style.zIndex=`${this.nextZIndex++}`}show(e){const t=this.mustWindow(e);t.hidden=!1,this.bringToFront(t),this.options.requestConfigSync()}toggle(e){const t=this.mustWindow(e);t.hidden=!t.hidden,t.hidden||this.bringToFront(t),this.options.requestConfigSync()}hide(e){const t=this.mustWindow(e);t.hidden=!0,this.options.requestConfigSync()}readPlacement(e){const t=Number.parseInt(e.style.zIndex,10);return{x:this.readCoordinate(e,"--window-x"),y:this.readCoordinate(e,"--window-y"),viewport:Cw(),zIndex:Number.isFinite(t)?t:void 0,visible:!e.hidden}}applyPlacement(e,t){const i=J8(t,Cw());e.style.setProperty("--window-x",`${i.x}px`),e.style.setProperty("--window-y",`${i.y}px`),e.hidden=!t.visible,t.zIndex!==void 0&&(e.style.zIndex=`${t.zIndex}`,this.nextZIndex=Math.max(this.nextZIndex,t.zIndex+1))}getSingletonConfigs(){const e=[],t=this.options.getRoot();for(const i of u6){const s=t.querySelector(`[data-window-id="${i}"]`);s&&e.push({id:i,placement:this.readPlacement(s)})}return e}applySingletonConfigs(e){const t=this.options.getRoot();for(const i of e){const s=t.querySelector(`[data-window-id="${i.id}"]`);s&&this.applyPlacement(s,i.placement)}}installDragging(e,t){e.addEventListener("pointerdown",i=>{if(!(i.target instanceof HTMLElement)||h6(i.target))return;const s=i.target.closest("[data-window-id]");if(!s||s.hidden)return;this.bringToFront(s);const a=i.clientX,r=i.clientY,o=s.getBoundingClientRect(),l=i.pointerId;s.setPointerCapture(l),i.preventDefault();const c=d=>{const h=Math.max(8,Math.min(window.innerWidth-120,o.left+d.clientX-a)),f=Math.max(8,Math.min(window.innerHeight-100,o.top+d.clientY-r));s.style.setProperty("--window-x",`${h}px`),s.style.setProperty("--window-y",`${f}px`)},u=()=>{s.releasePointerCapture(l),s.removeEventListener("pointermove",c),s.removeEventListener("pointerup",u),s.removeEventListener("pointercancel",u),this.options.requestConfigSync()};s.addEventListener("pointermove",c),s.addEventListener("pointerup",u),s.addEventListener("pointercancel",u)},{signal:t})}mustWindow(e){const t=this.options.getRoot().querySelector(`[data-window-id="${e}"]`);if(!t)throw new Error(`Missing window for id: ${e}`);return t}readCoordinate(e,t){const i=e.style.getPropertyValue(t).trim(),s=getComputedStyle(e).getPropertyValue(t).trim(),a=i||s,r=Number.parseFloat(a);if(Number.isFinite(r))return r;const o=e.getBoundingClientRect();return t==="--window-y"?o.top:o.left}}function Cw(){return{width:Math.max(1,window.innerWidth),height:Math.max(1,window.innerHeight)}}function h6(n){return n instanceof Element&&!!n.closest("button, input, select, textarea, option, label, a, [data-no-drag]")}function f6(n){return new d6(n)}class p6{constructor(e){this.options=e}activeSourceIds=null;autoFollow=!0;lastActiveKey=null;activeItem=null;renderedItems=[];reset(){this.activeSourceIds=null,this.lastActiveKey=null,this.activeItem=null,this.renderedItems=[]}render(){this.options.body.replaceChildren(),this.lastActiveKey=null,this.activeItem=null,this.renderedItems=[];const e=this.options.getSources();if(e.length===0){const _=document.createElement("p");_.className="stat-window-empty",_.textContent=this.options.getReplayPlayer()?"No events loaded.":"Load a replay to see events.",this.options.body.append(_);return}const t=J_(e,this.activeSourceIds),i=T8({sources:e,activeSourceIds:this.activeSourceIds,replayPlayers:this.options.getReplayPlayer()?.replay.players??[]}),s=document.createElement("div");s.className="event-playlist-toolbar";const a=document.createElement("details");a.className="event-playlist-filter",a.dataset.noDrag="true";const r=document.createElement("summary");r.textContent=`Filters ${t.size}/${e.length}`,a.append(r);const o=document.createElement("div");o.className="event-playlist-filter-panel";const l=document.createElement("div");l.className="event-playlist-filter-actions";const c=document.createElement("button");c.type="button",c.textContent="All",c.addEventListener("click",()=>{this.activeSourceIds=new Set(e.map(m=>m.id)),this.lastActiveKey=null,this.render();const _=this.options.getReplayPlayer()?.getState();_&&this.syncTimeline(_)});const u=document.createElement("button");u.type="button",u.textContent="None",u.addEventListener("click",()=>{this.activeSourceIds=new Set,this.lastActiveKey=null,this.render()}),l.append(c,u),o.append(l);const d=new Map;for(const _ of e){const m=d.get(_.group)??[];m.push(_),d.set(_.group,m)}for(const[_,m]of d){const v=document.createElement("section");v.className="event-playlist-filter-group";const y=document.createElement("h3");y.textContent=_,v.append(y);for(const b of m){const S=document.createElement("label");S.className="toggle event-playlist-filter-option";const x=document.createElement("input");x.type="checkbox",x.checked=t.has(b.id),x.addEventListener("change",()=>{this.setSourceSelection(e,C=>{x.checked?C.add(b.id):C.delete(b.id)})});const M=document.createElement("span");M.textContent=`${b.label} (${b.events.length})`,S.append(x,M),v.append(S)}o.append(v)}a.append(o);const h=document.createElement("label");h.className="toggle event-playlist-follow";const f=document.createElement("input");f.type="checkbox",f.checked=this.autoFollow,f.addEventListener("change",()=>{this.autoFollow=f.checked;const _=this.options.getReplayPlayer()?.getState();_&&this.syncTimeline(_,{forceScroll:!0})});const p=document.createElement("span");p.textContent="Auto-follow",h.append(f,p),s.append(a,h);const g=document.createElement("div");if(g.className="event-playlist-list",g.dataset.noDrag="true",i.length===0){const _=document.createElement("p");_.className="stat-window-empty",t.size===0?_.textContent="No event types selected.":_.textContent="No events in selected event types.",g.append(_)}else for(const _ of i){const m=document.createElement("button");m.type="button",m.className="event-playlist-item",m.dataset.eventKey=_.key,m.dataset.eventTime=`${_.event.time}`,m.style.setProperty("--event-color",_.color),Number.isFinite(_.event.time)&&this.renderedItems.push({key:_.key,time:_.event.time,element:m}),m.addEventListener("click",()=>{this.options.cueTimelineEvent(_.event)});const v=document.createElement("span");v.className="event-playlist-time",v.textContent=this.options.formatTime(_.event.time);const y=document.createElement("span");y.className="event-playlist-main";const b=document.createElement("strong");b.textContent=_.event.label??_.sourceLabel;const S=document.createElement("span");S.textContent=[_.event.playerName??null,_.event.frame!==void 0?`frame ${_.event.frame}`:null,_.sourceLabel].filter(x=>!!x).join(" · "),y.append(b,S),m.append(v,y),g.append(m)}this.options.body.append(s,g)}syncTimeline(e,t={}){if(!this.options.body.querySelector(".event-playlist-list"))return;const s=this.getActiveItem(e.currentTime),a=s?.dataset.eventKey??null;a===this.lastActiveKey&&!t.forceScroll||(this.activeItem?.isConnected?this.activeItem.dataset.active="false":this.activeItem&&(this.activeItem=null),s?(s.dataset.active="true",this.activeItem=s,(this.autoFollow||t.forceScroll)&&s.scrollIntoView({block:"nearest"})):this.activeItem=null,this.lastActiveKey=a)}setSourceSelection(e,t){const i=J_(e,this.activeSourceIds);t(i),this.activeSourceIds=i,this.lastActiveKey=null,this.render();const s=this.options.getReplayPlayer()?.getState();s&&this.syncTimeline(s)}getActiveItem(e){const t=this.renderedItems;if(t.length===0)return null;let i=0,s=t.length-1;for(;ie.getConfig||e.applyConfig).map(e=>{const t={id:e.id};return e.id==="boost"&&(t.aliases=["boost-pickup-animation"]),e.getConfig&&(t.getConfig=()=>e.getConfig?.()),e.applyConfig&&(t.applyConfig=i=>e.applyConfig?.(i)),t})}function M6(n){return v6(tC(n))}function E6({replayPlayer:n,playbackRate:e,skipPostGoalTransitions:t,skipKickoffs:i}){const s=n?.getState();return{currentTime:s?.currentTime,playing:s?.playing,rate:s?.speed??zf(Number(e?.value??1)),skipPostGoalTransitions:n?s?.skipPostGoalTransitionsEnabled:t.checked,skipKickoffs:n?s?.skipKickoffsEnabled:i.checked}}function C6({replayPlayer:n,cameraControlsController:e}){const t=n?.getState(),i=t?YE(t):e?.ballCamMode;return{mode:t?.cameraViewMode,freePreset:e?.freeCameraPreset??null,attachedPlayerId:t?.attachedPlayerId,ballCam:i===void 0?void 0:i==="on",useReplayBallCam:i===void 0?void 0:i==="player",usePlayerCameraSettings:t?.customCameraSettings===null,autoPossession:e?.autoPossessionEnabled,customSettings:t?.customCameraSettings,nameplateLiftUu:e?.nameplateLiftUu}}function A6({playback:n,camera:e,activeTimelineEventSourceIds:t,activeTimelineRangeModuleIds:i,activeMechanicTimelineKinds:s,activeRenderEffectModuleIds:a,initialConfig:r,replayPlayer:o,boostPadOverlayEnabled:l,recording:c,singletonWindows:u,statsWindows:d,moduleConfigs:h}){return{version:Lh,playback:n,camera:e,overlays:{timelineEvents:[...t],timelineRanges:[...i],mechanics:[...s],renderEffects:[...a],...r?.overlays.pluginRenderEffects!==void 0?{pluginRenderEffects:[...r.overlays.pluginRenderEffects]}:{},...r?.overlays.pluginHudOverlay!==void 0?{pluginHudOverlay:r.overlays.pluginHudOverlay}:{},followedPlayerHud:!1,boostPads:l,boostPickupAnimation:o?.getState().boostPickupAnimationEnabled??!1,hitboxWireframes:o?.getState().hitboxWireframesEnabled??!1,hitboxOnlyMode:o?.getState().hitboxOnlyModeEnabled??!1},recording:c,singletonWindows:u,statsWindows:d,moduleConfigs:h}}function R6(n,e,t){return{currentTime:n.currentTime,playing:n.playing,speed:n.rate,customCameraSettings:eC(e),cameraViewMode:e.mode,attachedPlayerId:e.attachedPlayerId,...Cx(e)==="player"?{useReplayBallCam:!0}:{ballCamEnabled:Cx(e)==="on"},boostPickupAnimationEnabled:t.overlays.boostPickupAnimation,hitboxWireframesEnabled:t.overlays.hitboxWireframes,hitboxOnlyModeEnabled:t.overlays.hitboxOnlyMode,skipPostGoalTransitionsEnabled:n.skipPostGoalTransitions,skipKickoffsEnabled:n.skipKickoffs}}function P6(n,e,t){console.groupCollapsed("[subtr-actor] stats player cfg load"),console.log("location.href",window.location.href),console.log("location.search",n.search||"(empty)"),console.log("location.hash",n.hash||"(empty)"),console.table([...n.searchParams.map(([i,s])=>({source:"search",name:i,value:s})),...n.hashParams.map(([i,s])=>({source:"hash",name:i,value:s}))]),console.log("cfg selected source",n.selectedSource??"(none)"),console.log("cfg selected raw text",n.selectedValue??"(none)"),console.log("cfg selected raw length",n.selectedValue?.length??0),console.log("cfg search values",n.searchValues),console.log("cfg hash values",n.hashValues),n.hashValues.length>0&&n.searchValues.length>0&&console.warn("Both hash and search contain cfg; hash cfg is used."),e&&(console.log("cfg normalized JSON",JSON.stringify(e,null,2)),console.log("cfg normalized object",e)),t&&console.error("cfg decode/apply error",t),console.groupEnd()}function Aw(n,e){const{style:t}=n.renderer.domElement;t.visibility=e?"hidden":"",t.pointerEvents=e?"none":""}function Rw(n,e={}){const t=e.destroyPlayer??!0,i=e.clearPlayerPluginHandles??!0,s=n.getUnsubscribe();s&&(s(),n.setUnsubscribe(null)),n.teardownActiveModules(),t&&(n.getReplayPlayer()?.destroy(),n.setReplayPlayer(null)),i&&(n.setCanvasRecorder(null),n.setTimelineOverlay(null)),n.setLoadedReplayName(null),n.setStatsTimeline(null),n.setStatsFrameLookup(null),n.setStatRegistry(Go(null)),n.clearTimelineEventSources(),n.clearTimelineRangeSources(),n.clearStandalonePlugins(),n.clearRenderCaches(),n.resetEventPlaylistWindow(),n.renderModuleSummary(),n.renderScoreboard(),n.renderTimelineEventCount(),n.renderMechanicsTimelineControls(),n.renderEventPlaylistWindow(),n.renderModuleSettings(),n.syncRecordingWindow()}async function I6(n,e,t){const{elements:i}=t;let s=null;i.statusReadout.textContent=n.preparingStatus,i.fileInput.disabled=!0,t.getReplayLoadModal()?.show(n.name,n.preparingStatus),t.setTransportEnabled(!1),t.getCameraControlsController()?.syncAvailability(),i.emptyState.hidden=t.getReplayPlayer()!==null,t.getReplayPlayer()?.pause();try{i.statusReadout.textContent="Parsing replay...",t.getReplayLoadModal()?.show(n.name,"Parsing replay...");const a=await e,{replay:r}=a,o=t.getReplayPlayer();if(o){Rw(t,{destroyPlayer:!1,clearPlayerPluginHandles:!1});const h=new dS(a.raw);await o.replaceReplay(h,r,{preservePlayback:!1}),t.setStatsTimeline(a.statsTimeline),t.setStatsFrameLookup(a.statsFrameLookup),t.setStatRegistry(Go(null)),t.setReplayPlayer(o),t.syncBoostPadOverlayPlugin(),t.setupActiveModules(),t.setUnsubscribe(o.subscribe(t.renderSnapshot));const f=t.getInitialConfig();if(f){t.setApplyingConfig(!0);try{t.applyConfigToReplayPlayer(f)}finally{t.setApplyingConfig(!1)}}t.getCameraControlsController()?.populateAttachedPlayerOptions(r.players),i.emptyState.hidden=!0,i.statusReadout.textContent=`Loaded ${n.name}`,t.setLoadedReplayName(n.name),i.playersReadout.textContent=r.players.map(p=>p.name).join(", "),i.framesReadout.textContent=`${r.frameCount}`,t.renderModuleSummary(),t.renderTimelineEventCount(),t.renderMechanicsTimelineControls(),t.resetEventPlaylistWindow(),t.renderEventPlaylistWindow(),t.setTransportEnabled(!0),t.getCameraControlsController()?.syncAvailability(o.getState()),t.renderSnapshot(o.getState()),t.renderStatsWindows(o.getState().frameIndex),t.renderScoreboard(o.getState().frameIndex),t.syncEventPlaylistTimeline(o.getState(),{forceScroll:!0}),t.renderModuleSettings(),t.syncRecordingWindow(),t.getReplayLoadModal()?.hide();return}const l=d3({replayEventsLabel:"Replay",replayEvents:h=>t.withTimelineEventSeekTimes(t.getReplayTimelineEvents(h.replay))}),c=XU({onStatusChange:t.syncRecordingWindow});t.setCanvasRecorder(c);const u=t.getInitialConfig(),d=h3(i.viewport,a,{initialPlaybackRate:u?.playback.rate,initialCustomCameraSettings:eC(u?.camera),initialAttachedPlayerId:u?.camera.attachedPlayerId??null,initialCameraViewMode:u?.camera.mode,initialBoostPickupAnimationEnabled:u?.overlays.boostPickupAnimation??!1,initialHitboxWireframesEnabled:u?.overlays.hitboxWireframes??i.hitboxWireframes.checked,initialHitboxOnlyModeEnabled:u?.overlays.hitboxOnlyMode??i.hitboxOnlyMode.checked,initialSkipPostGoalTransitionsEnabled:i.skipPostGoalTransitions.checked,initialSkipKickoffsEnabled:i.skipKickoffs.checked,plugins:[xU({onSample:({renderFps:h,replayFps:f})=>{const p=document.getElementById("render-fps-readout"),g=document.getElementById("replay-fps-readout");p&&(p.textContent=`${h.toFixed(0)} fps`),g&&(g.textContent=`${f.toFixed(0)} fps`)}}),Gu(w3({floatingLiftUu:()=>t.getCameraControlsController()?.nameplateLiftUu})),Gu(HU({includePickup:t.includeBoostPickupAnimationPickup})),Gu(c),Gu(l)]});if(s=d,Aw(d,!0),await d.ready,Rw(t),s=null,Aw(d,!1),t.setStatsTimeline(a.statsTimeline),t.setStatsFrameLookup(a.statsFrameLookup),t.setStatRegistry(Go(null)),t.setTimelineOverlay(l),t.setReplayPlayer(d),t.syncBoostPadOverlayPlugin(),t.setupActiveModules(),t.setUnsubscribe(d.subscribe(t.renderSnapshot)),u){t.setApplyingConfig(!0);try{t.applyConfigToReplayPlayer(u)}finally{t.setApplyingConfig(!1)}}t.getCameraControlsController()?.populateAttachedPlayerOptions(r.players),i.emptyState.hidden=!0,i.statusReadout.textContent=`Loaded ${n.name}`,t.setLoadedReplayName(n.name),i.playersReadout.textContent=r.players.map(h=>h.name).join(", "),i.framesReadout.textContent=`${r.frameCount}`,t.renderModuleSummary(),t.renderTimelineEventCount(),t.renderMechanicsTimelineControls(),t.resetEventPlaylistWindow(),t.renderEventPlaylistWindow(),t.setTransportEnabled(!0),t.getCameraControlsController()?.syncAvailability(d.getState()),t.renderSnapshot(d.getState()),t.renderStatsWindows(d.getState().frameIndex),t.renderScoreboard(d.getState().frameIndex),t.syncEventPlaylistTimeline(d.getState(),{forceScroll:!0}),t.renderModuleSettings(),t.syncRecordingWindow(),t.getReplayLoadModal()?.hide()}catch(a){throw t.getReplayLoadModal()?.hide(),s?.destroy(),t.getReplayPlayer()||(i.emptyState.hidden=!1,t.setCanvasRecorder(null)),t.syncRecordingWindow(),a}finally{i.fileInput.disabled=!1}}function L6(n){if(n<=0)return"--";const e=["B","KB","MB","GB"];let t=n,i=0;for(;t>=1024&&i=10?1:2;return`${t.toFixed(s)} ${e[i]}`}function k6(n){if(!n)return"No replay";if(n.error)return n.error;switch(n.state){case"idle":return"Idle";case"recording":return"Recording";case"stopping":return"Stopping";case"ready":return"Ready";case"error":return"Error"}}function D6({fpsValue:n,playbackRateValue:e}){const t=Number(n),i=Number(e);return{fps:Number.isFinite(t)?Math.max(1,Math.min(120,Math.trunc(t))):60,playbackRate:Number.isFinite(i)?Math.max(.1,i):1}}function O6(n,e=new Date){const i=(n?.replace(/\.replay$/i,"")||"replay").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,""),s=e.toISOString().replace(/[:.]/g,"-");return`${i||"replay"}-${s}.webm`}function F6(n,e){const t=URL.createObjectURL(n),i=document.createElement("a");i.href=t,i.download=e,document.body.append(i),i.click(),i.remove(),window.setTimeout(()=>URL.revokeObjectURL(t),0)}class N6{constructor(e){this.options=e}getConfigSnapshot(){const{elements:e}=this.options;return{fps:Number(e.fps.value),playbackRate:Number(e.playbackRate.value)}}applyConfig(e){const{elements:t}=this.options;e.fps!==void 0&&(t.fps.value=`${e.fps}`),e.playbackRate!==void 0&&(t.playbackRate.value=`${e.playbackRate}`)}sync(e=this.options.getCanvasRecorder()?.getStatus()??null){const{elements:t}=this.options,i=this.options.getCanvasRecorder()!==null&&this.options.getReplayPlayer()!==null,s=e?.state??"idle",a=s==="recording"||s==="stopping",r=(this.options.getCanvasRecorder()?.getRecording()??null)!==null;t.status.textContent=k6(e),t.elapsed.textContent=`${(e?.elapsedSeconds??0).toFixed(1)}s`,t.size.textContent=L6(e?.sizeBytes??0),t.type.textContent=e?.mimeType||"WebM",t.start.disabled=!i||a,t.fullReplay.disabled=!i||a,t.stop.disabled=!i||!a,t.download.disabled=!r||a,t.clear.disabled=!r||a,t.fps.disabled=a,t.playbackRate.disabled=a}installEventListeners(e){const{elements:t}=this.options;t.start.addEventListener("click",()=>{const i=this.options.getCanvasRecorder();if(i)try{const{fps:s}=this.getRecordingOptions();i.start({fps:s}),this.sync()}catch(s){console.error("Failed to start recording:",s),this.options.setStatus(s instanceof Error?s.message:"Failed to start recording"),this.sync(i.getStatus())}},{signal:e}),t.fullReplay.addEventListener("click",()=>{const i=this.options.getCanvasRecorder();if(!i)return;const{fps:s,playbackRate:a}=this.getRecordingOptions();i.recordFullReplay({fps:s,playbackRate:a,restorePlaybackState:!0}).catch(r=>{console.error("Failed to record replay:",r),this.options.setStatus(r instanceof Error?r.message:"Failed to record replay"),this.sync(this.options.getCanvasRecorder()?.getStatus()??null)}),this.sync()},{signal:e}),t.stop.addEventListener("click",()=>{this.options.getCanvasRecorder()?.stop().catch(i=>{console.error("Failed to stop recording:",i),this.options.setStatus(i instanceof Error?i.message:"Failed to stop recording")}),this.sync()},{signal:e}),t.download.addEventListener("click",()=>{const i=this.options.getCanvasRecorder()?.getRecording();i&&F6(i,O6(this.options.getLoadedReplayName()))},{signal:e}),t.clear.addEventListener("click",()=>{try{this.options.getCanvasRecorder()?.clear(),this.sync()}catch(i){console.error("Failed to clear recording:",i)}},{signal:e}),t.fps.addEventListener("change",this.options.requestConfigSync,{signal:e}),t.playbackRate.addEventListener("change",this.options.requestConfigSync,{signal:e})}getRecordingOptions(){const{elements:e}=this.options;return D6({fpsValue:e.fps.value,playbackRateValue:e.playbackRate.value})}}function U6(n){return new N6(n)}class B6{constructor(e){this.options=e}render(e=this.options.getReplayPlayer()?.getState().frameIndex??0){const{body:t}=this.options;t.replaceChildren();const i=this.options.getStatsFrameLookup(),s=i?Ht(i,e):null,a=this.options.getReplayPlayer()?.replay??null;if(!s||!a){const o=document.createElement("p");o.className="scoreboard-empty",o.textContent="Load a replay to show the scoreboard.",t.append(o);return}const r=document.createElement("div");r.className="scoreboard-scoreline",r.append(Pw(s.team_zero?.core.goals,!0),H6(),Pw(s.team_one?.core.goals,!1)),t.append(r)}}function z6(n){return typeof n=="number"&&Number.isFinite(n)?`${Math.round(n)}`:"--"}function H6(){const n=document.createElement("span");return n.className="scoreboard-divider",n.textContent="-",n}function Pw(n,e){const t=document.createElement("strong");return t.className=`scoreboard-goal-value ${ua(e)}`,t.textContent=z6(n),t}function V6(n){return new B6(n)}class G6{constructor(e){this.options=e}setTransportEnabled(e,t){const{elements:i}=this.options;i.togglePlayback.disabled=!e,i.previousFrame.disabled=!e,i.nextFrame.disabled=!e,i.playbackRate.disabled=!e,i.skipPostGoalTransitions.disabled=!e,i.skipKickoffs.disabled=!e,i.hitboxWireframes.disabled=!e,i.hitboxOnlyMode.disabled=!e,this.options.getCameraControlsController()?.setTransportEnabled(e,t)}renderSnapshot(e){const{elements:t}=this.options;t.timeReadout.textContent=`${e.currentTime.toFixed(2)}s`,t.frameReadout.textContent=`${e.frameIndex}`,t.durationReadout.textContent=`${e.duration.toFixed(2)}s`,t.playbackStatusReadout.textContent=e.playing?"Playing":"Paused",t.togglePlayback.textContent=e.playing?"Pause":"Play";const i=Math.max(0,this.options.getFrameCount()-1);t.previousFrame.disabled=e.frameIndex<=0,t.nextFrame.disabled=e.frameIndex>=i;const s=zf(e.speed);t.playbackRate.value=`${s}`,t.playbackRateReadout.textContent=Ry(s),this.options.getCameraControlsController()?.syncState(e),t.skipPostGoalTransitions.checked=e.skipPostGoalTransitionsEnabled,t.skipKickoffs.checked=e.skipKickoffsEnabled,t.hitboxWireframes.checked=e.hitboxWireframesEnabled,t.hitboxOnlyMode.checked=e.hitboxOnlyModeEnabled,t.emptyState.hidden=!0}}function $6(n){return new G6(n)}function W6({elements:n,signal:e,setLauncherOpen:t,openReplayFilePicker:i,getElementWindowId:s,toggleWindow:a,hideWindow:r,createStatsWindow:o,loadReplayFile:l,togglePlayback:c,stepFrames:u,setPlaybackRate:d,setSkipPostGoalTransitionsEnabled:h,setSkipKickoffsEnabled:f,setHitboxWireframesEnabled:p,setHitboxOnlyModeEnabled:g}){n.launcherToggle.addEventListener("click",()=>{t(n.launcherMenu.hidden)},{signal:e}),n.root.addEventListener("click",m=>{m.target instanceof Element&&(m.target.closest(".top-chrome")||t(!1))},{signal:e}),n.loadReplayAction.addEventListener("click",i,{signal:e}),n.emptyLoadReplay.addEventListener("click",i,{signal:e}),n.root.querySelectorAll("[data-window-toggle]").forEach(m=>{m.addEventListener("click",()=>{const v=m.dataset.windowToggle;v&&(a(v),t(!1))},{signal:e})}),n.root.querySelectorAll("[data-window-hide]").forEach(m=>{m.addEventListener("click",()=>{const v=m.dataset.windowHide??s(m);v&&r(v)},{signal:e})}),n.root.querySelectorAll("[data-create-stats-window]").forEach(m=>{m.addEventListener("click",()=>{o(m.dataset.createStatsWindow)},{signal:e})}),n.fileInput.addEventListener("change",()=>{const m=n.fileInput.files?.[0];m&&l(m)},{signal:e}),n.togglePlayback.addEventListener("click",c,{signal:e}),n.previousFrame.addEventListener("click",()=>u(-1),{signal:e}),n.nextFrame.addEventListener("click",()=>u(1),{signal:e});const _=()=>{const m=zf(Number(n.playbackRate.value));n.playbackRate.value=`${m}`,n.playbackRateReadout.textContent=Ry(m),d(m)};n.playbackRate.addEventListener("input",_,{signal:e}),n.playbackRate.addEventListener("change",_,{signal:e}),n.skipPostGoalTransitions.addEventListener("change",()=>{h(n.skipPostGoalTransitions.checked)},{signal:e}),n.skipKickoffs.addEventListener("change",()=>{f(n.skipKickoffs.checked)},{signal:e}),n.hitboxWireframes.addEventListener("change",()=>{p(n.hitboxWireframes.checked)},{signal:e}),n.hitboxOnlyMode.addEventListener("change",()=>{g(n.hitboxOnlyMode.checked)},{signal:e})}const X6=3500;function K6(){const n=document.activeElement;if(!(n instanceof HTMLElement))return!1;if(n.isContentEditable)return!0;const e=n.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"}function q6(n){const{getReplayPlayer:e,signal:t}=n,i={forward:!1,backward:!1,left:!1,right:!1,up:!1,down:!1},s=()=>{i.forward=!1,i.backward=!1,i.left=!1,i.right=!1,i.up=!1,i.down=!1},a=(g,_)=>{switch(g){case"KeyW":return i.forward=_,!0;case"KeyS":return i.backward=_,!0;case"KeyA":return i.left=_,!0;case"KeyD":return i.right=_,!0;case"Space":return i.up=_,!0;case"ShiftLeft":case"ShiftRight":return i.down=_,!0;default:return!1}},r=g=>{g.ctrlKey||g.metaKey||g.altKey||K6()||a(g.code,!0)&&g.preventDefault()},o=g=>{a(g.code,!1)};window.addEventListener("keydown",r,{signal:t}),window.addEventListener("keyup",o,{signal:t}),window.addEventListener("blur",s,{signal:t});const l=new T,c=new T,u=new T,d=new T(0,1,0);let h=null,f=0;const p=g=>{f=requestAnimationFrame(p);const _=h===null?0:Math.min(.1,(g-h)/1e3);h=g;const m=(i.forward?1:0)-(i.backward?1:0),v=(i.right?1:0)-(i.left?1:0),y=(i.up?1:0)-(i.down?1:0);if(_===0||m===0&&v===0&&y===0)return;const b=e();if(!b||b.getState().cameraViewMode!=="free")return;const S=b.camera,x=b.controls;S.getWorldDirection(l),c.set(1,0,0).applyQuaternion(S.quaternion),u.set(0,0,0).addScaledVector(l,m).addScaledVector(c,v).addScaledVector(d,y),u.lengthSq()!==0&&(u.normalize().multiplyScalar(X6*_),S.position.add(u),x.target.add(u))};f=requestAnimationFrame(p),t.addEventListener("abort",()=>{cancelAnimationFrame(f)})}function Y6(n,e){const t=new URLSearchParams(n),s=(t.get("replayId")??t.get("replay-id")??e??"").trim();return s.length>0?s:null}function j6(){const n=new URLSearchParams(window.location.search),e=n.get("reviewToken")??n.get("token")??window.localStorage.getItem("rocket_sense_access_token");return e?{Authorization:`Bearer ${e}`}:{}}function Z6(n){if(!n.replayId)return null;const e={replay_id:n.replayId,reviewed_mechanic:n.mechanic,reviewed_event_frame:n.frame,reviewed_event_time:n.time,confidence:n.confidence,status:"confirmed"};return n.subjectKind&&n.subjectId&&(e.reviewed_subject_kind=n.subjectKind,e.reviewed_subject_id=n.subjectId),n.startFrame!==null&&(e.reviewed_start_frame=n.startFrame),n.endFrame!==null&&(e.reviewed_end_frame=n.endFrame),n.notes&&n.notes.trim()&&(e.notes=n.notes.trim()),Object.keys(n.context).length>0&&(e.context=n.context),e}function J6(n,e){const t=n.getState(),i=Math.max(0,Math.round(t.frameIndex??0)),s=t.currentTime??0,a=t.attachedPlayerId??null,r=a?n.replay.players.find(o=>o.id===a)?.name??null:null;return{localId:e.localId,mechanic:e.mechanic,frame:i,time:s,subjectKind:a?"player":null,subjectId:a,playerName:r,startFrame:null,endFrame:null,notes:e.notes?.trim()?e.notes.trim():null,confidence:1,replayId:e.replayId,context:{capturedFrom:"stat-evaluation-player",attachedPlayerId:a,playerName:r,durationSeconds:n.replay.duration??null}}}async function Q6(n,e="/api/v1/events/reviews"){const t=Z6(n);if(!t)return{record:n,ok:!1,message:"No replay id — cannot upload (export JSON instead)."};try{const i=await fetch(e,{method:"POST",headers:{"content-type":"application/json",...j6()},credentials:"same-origin",body:JSON.stringify(t)});if(!i.ok){let s=`${i.status}${i.statusText?` ${i.statusText}`:""}`;try{const a=await i.json();typeof a.error=="string"&&(s=a.error)}catch{}return{record:n,ok:!1,message:s}}return{record:n,ok:!0,message:"uploaded"}}catch(i){return{record:n,ok:!1,message:i instanceof Error?i.message:String(i)}}}const e9=["flick","whiff","double_tap","ceiling_shot","wall_aerial","flip_reset","one_timer","speed_flip","half_flip","wavedash","demo"],t9="m";function n9(){const n=document.activeElement;if(!(n instanceof HTMLElement))return!1;if(n.isContentEditable)return!0;const e=n.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"}function i9(n,e){const t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),i=URL.createObjectURL(t),s=document.createElement("a");s.href=i,s.download=n,document.body.appendChild(s),s.click(),s.remove(),URL.revokeObjectURL(i)}class s9{constructor(e){this.options=e}records=[];localIdSeq=0;installEventListeners(e){const{elements:t}=this.options;for(const i of e9){const s=document.createElement("option");s.value=i,s.textContent=i.replaceAll("_"," "),t.mechanic.appendChild(s)}t.capture.addEventListener("click",()=>this.capture(),{signal:e}),t.export.addEventListener("click",()=>this.exportJson(),{signal:e}),t.upload.addEventListener("click",()=>{this.uploadAll()},{signal:e}),t.clear.addEventListener("click",()=>{this.records.length=0,this.render(),this.setStatus("Cleared.")},{signal:e}),window.addEventListener("keydown",i=>{i.key.toLowerCase()!==t9||i.repeat||i.metaKey||i.ctrlKey||i.altKey||n9()||(i.preventDefault(),this.capture())},{signal:e}),this.render()}capture(){const e=this.options.getReplayPlayer();if(!e){this.setStatus("No replay loaded.");return}this.localIdSeq+=1;const t=J6(e,{mechanic:this.options.elements.mechanic.value||"flick",replayId:this.resolveReplayId(),localId:`missed-${this.localIdSeq}`});this.records.push(t),this.options.showWindow(),this.render(),this.setStatus(`Captured ${t.mechanic} @ ${t.time.toFixed(2)}s`+(t.replayId?".":" (no replay id — export only)."))}exportJson(){if(this.records.length===0){this.setStatus("Nothing to export.");return}i9("missed-events.json",{capturedFrom:"stat-evaluation-player",replayId:this.resolveReplayId(),missedEvents:this.records}),this.setStatus(`Exported ${this.records.length}.`)}async uploadAll(){if(this.records.length===0){this.setStatus("Nothing to upload.");return}let e=0;const t=[];for(const i of[...this.records]){const s=await Q6(i);if(s.ok){e+=1;const a=this.records.findIndex(r=>r.localId===i.localId);a>=0&&this.records.splice(a,1)}else t.push(`${i.mechanic}@${i.time.toFixed(1)}s: ${s.message}`)}this.render(),this.setStatus(t.length===0?`Uploaded ${e}.`:`Uploaded ${e}, ${t.length} failed — ${t[0]}`)}render(){const{list:e}=this.options.elements;e.replaceChildren();for(const t of this.records){const i=document.createElement("li"),s=t.playerName??t.subjectId??"no subject",a=document.createElement("span");a.className="missed-event-row",a.textContent=`${t.mechanic} @ ${t.time.toFixed(2)}s · f${t.frame} · ${s}`+(t.replayId?"":" · no replay id");const r=document.createElement("button");r.type="button",r.textContent="✕",r.title="Remove",r.addEventListener("click",()=>{const o=this.records.findIndex(l=>l.localId===t.localId);o>=0&&(this.records.splice(o,1),this.render())}),i.append(a,r),e.appendChild(i)}}setStatus(e){this.options.elements.status.textContent=e}resolveReplayId(){return Y6(window.location.search,this.options.getReplayId?.()??null)}}function a9(n){return new s9(n)}class Eo{constructor(e,t){this.file=e,this.sourceTimes=t}sourceTimes;dirty=!1;static async createNew(e){const t=await ca.create(W3(),e);return new Eo(t,[])}static async loadFromBytes(e,t){const i=await ca.load(e,t);return new Eo(i,new Array(i.roundCount).fill(null))}get shotCount(){return this.file.roundCount}get hasUnsavedShots(){return this.dirty}shots(){return this.file.rounds.map((e,t)=>({index:t,timeLimit:e.time_limit,sourceReplayTime:this.sourceTimes[t]??null}))}captureShot(e,t=null){const i=H3(this.file,e);return this.sourceTimes[i]=t,this.dirty=!0,i}removeShot(e){this.file.removeRound(e),this.sourceTimes.splice(e,1),this.dirty=!0}setShotTimeLimit(e,t){this.file.setRoundTimeLimit(e,t),this.dirty=!0}downloadFileName(){return $3(this.file.guid)}toBytes(e=Math.floor(Date.now()/1e3)){this.file.updateMetadata({updated_at:BigInt(e)});const t=this.file.toBytes();return this.dirty=!1,t}}function r9(n,e,t,i){const s=`Captured shot ${n} (${e} at ${t})`;return i===null?`${s}.`:`${s}; warning: ${i}.`}function o9(n,e){const t=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),i=new Blob([t],{type:"application/octet-stream"}),s=URL.createObjectURL(i),a=document.createElement("a");a.href=s,a.download=e,document.body.appendChild(a),a.click(),a.remove(),window.setTimeout(()=>URL.revokeObjectURL(s),0)}class l9{constructor(e){this.options=e}session=null;sessionPromise=null;installEventListeners(e){const{elements:t}=this.options;t.capture.addEventListener("click",()=>{this.captureShot()},{signal:e}),t.newPack.addEventListener("click",()=>{this.newPack()},{signal:e}),t.download.addEventListener("click",()=>{this.download()},{signal:e}),t.load.addEventListener("click",()=>t.loadInput.click(),{signal:e}),t.loadInput.addEventListener("change",()=>{const i=t.loadInput.files?.[0]??null;t.loadInput.value="",i&&this.loadPackFile(i)},{signal:e}),t.name.addEventListener("change",()=>this.session?.file.setName(t.name.value||null),{signal:e}),t.creator.addEventListener("change",()=>this.session?.file.setCreatorName(t.creator.value||null),{signal:e}),t.description.addEventListener("change",()=>this.session?.file.setDescription(t.description.value||null),{signal:e}),t.difficulty.addEventListener("change",()=>this.session?.file.setDifficulty(t.difficulty.value),{signal:e}),this.sync()}sync(){const{elements:e}=this.options,t=this.options.getReplayPlayer();e.capture.disabled=!t,e.shooter.disabled=!t,this.populateShooterOptions(t),this.renderShotList()}populateShooterOptions(e){const{shooter:t}=this.options.elements,i=t.value;t.replaceChildren(),t.append(new Option("Followed player (camera)",""));for(const s of e?.replay.players??[])t.append(new Option(s.name,s.id));[...t.options].some(s=>s.value===i)&&(t.value=i)}async ensureSession(){if(this.session)return this.session;this.sessionPromise??=Eo.createNew();const e=await this.sessionPromise;return this.session||this.adoptSession(e),this.session??e}adoptSession(e){this.session=e,this.sessionPromise=null;const{elements:t}=this.options;t.name.value=e.file.name??"",t.creator.value=e.file.creatorName??"",t.description.value=e.file.description??"";const i=e.file.difficulty;[...t.difficulty.options].some(s=>s.value===i)&&(t.difficulty.value=i),this.renderShotList()}resolveShooter(e,t){const i=this.options.elements.shooter.value||null,s=e.getState().attachedPlayerId,a=e.replay.players,r=[...a.filter(o=>o.id===(i??s)),...a];for(const o of r){const l=o.frames[t];if(l?.position)return i&&o.id!==i?null:{track:o,sample:l}}return null}timeLimitSeconds(){const e=Number(this.options.elements.timeLimit.value);return!Number.isFinite(e)||e<0?EM:e}async captureShot(){const e=this.options.getReplayPlayer();if(!e){this.setStatus("No replay loaded.");return}const t=e.getState(),i=e.replay.ballFrames[t.frameIndex];if(!i?.position){this.setStatus("No ball state on the current frame.");return}const s=this.resolveShooter(e,t.frameIndex);if(!s){this.setStatus("Selected shooter has no car state on the current frame.");return}const a=await this.ensureSession(),r={position:s.sample.position,rotation:s.sample.rotation,linearVelocity:s.sample.linearVelocity},o=a.captureShot({ball:{position:i.position,linearVelocity:i.linearVelocity},shooter:r,timeLimit:this.timeLimitSeconds()},t.currentTime);this.renderShotList(),this.setStatus(r9(o+1,s.track.name,Ai(t.currentTime),N3(r)))}async loadPackFile(e){if(!(this.session?.hasUnsavedShots&&!window.confirm("Discard unsaved captured shots and open this pack?")))try{const t=await Eo.loadFromBytes(await e.arrayBuffer());this.adoptSession(t),this.setStatus(`Opened ${e.name} (${t.shotCount} shot${t.shotCount===1?"":"s"}); captures will append.`)}catch(t){console.error("Failed to load training pack:",t),this.setStatus(t instanceof Error?t.message:"Failed to load training pack.")}}async newPack(){if(!(this.session?.hasUnsavedShots&&!window.confirm("Discard unsaved captured shots and start a new pack?")))try{this.adoptSession(await Eo.createNew()),this.setStatus("Started a new pack.")}catch(e){console.error("Failed to create training pack:",e),this.setStatus(e instanceof Error?e.message:"Failed to create training pack.")}}async download(){const e=await this.ensureSession();if(e.shotCount===0){this.setStatus("No shots to download; capture one first.");return}try{o9(e.toBytes(),e.downloadFileName()),this.setStatus(`Downloaded ${e.downloadFileName()}.`)}catch(t){console.error("Failed to serialize training pack:",t),this.setStatus(t instanceof Error?t.message:"Failed to serialize pack.")}}renderShotList(){const{shotList:e}=this.options.elements;e.replaceChildren();const t=this.session;if(t)for(const i of t.shots()){const s=document.createElement("li"),a=document.createElement("span"),r=i.sourceReplayTime===null?"loaded":`at ${Ai(i.sourceReplayTime)}`,o=i.timeLimit===0?"no limit":`${i.timeLimit}s`;a.textContent=`Shot ${i.index+1} — ${r} — ${o}`;const l=document.createElement("button");l.type="button",l.textContent="Remove",l.addEventListener("click",()=>{t.removeShot(i.index),this.renderShotList(),this.setStatus(`Removed shot ${i.index+1}.`)}),s.append(a,l),e.appendChild(s)}}setStatus(e){this.options.elements.status.textContent=e}}function c9(n){return new l9(n)}class u9{constructor(e){this.options=e}activeModules=[];activeTimelineEventSourceIds=new Set;activeTimelineRangeModuleIds=new Set;activeMechanicTimelineKinds=new Set;activeRenderEffectModuleIds=new Set;removeRenderHook=null;timelineSourceRemovers=new Map;timelineRangeSourceRemovers=new Map;getActiveModules(){return this.activeModules}getActiveTimelineEventSourceIds(){return this.activeTimelineEventSourceIds}getActiveTimelineRangeModuleIds(){return this.activeTimelineRangeModuleIds}getActiveMechanicTimelineKinds(){return this.activeMechanicTimelineKinds}getActiveRenderEffectModuleIds(){return this.activeRenderEffectModuleIds}getActiveCapabilityIds(e){return e==="events"?this.activeTimelineEventSourceIds:e==="ranges"?this.activeTimelineRangeModuleIds:this.activeRenderEffectModuleIds}getBoostPadOverlayEnabled(){return!0}getTimelineEventSourceIds(){return[...this.activeTimelineEventSourceIds]}getTimelineRangeModuleIds(){return[...this.activeTimelineRangeModuleIds]}getMechanicTimelineKinds(){return[...this.activeMechanicTimelineKinds]}getRenderEffectModuleIds(){return[...this.activeRenderEffectModuleIds]}applyOverlayConfig({timelineEvents:e,timelineRanges:t,mechanics:i,renderEffects:s,boostPads:a}){this.activeTimelineEventSourceIds=new Set(e),this.activeTimelineRangeModuleIds=new Set(t),this.activeMechanicTimelineKinds=new Set(i),this.activeRenderEffectModuleIds=new Set(s)}reset(){this.teardownActiveModules(),this.clearStandalonePlugins(),this.activeModules=[],this.activeTimelineEventSourceIds=new Set,this.activeTimelineRangeModuleIds=new Set,this.activeMechanicTimelineKinds=new Set,this.activeRenderEffectModuleIds=new Set,this.removeRenderHook=null}setupActiveModules(){this.teardownActiveModules();const e=this.options.getContext();if(!e)return;const t=this.getActiveModuleIds();this.activeModules=this.options.modules.filter(i=>t.has(i.id)),this.options.boostPickupFilters.setup(e);for(const i of this.activeModules)i.setup(e);this.removeRenderHook=e.player.onBeforeRender(i=>{for(const s of this.activeModules)this.activeRenderEffectModuleIds.has(s.id)&&s.onBeforeRender(i)}),this.syncTimelineEvents(),this.syncTimelineRanges()}teardownActiveModules(){this.removeRenderHook?.(),this.removeRenderHook=null,this.clearTimelineEventSources(),this.clearTimelineRangeSources();for(const e of this.activeModules)e.teardown();this.activeModules=[]}toggleCapability(e,t,i){const s=this.getMutableActiveCapabilityIds(t);i?s.add(e):s.delete(e),this.setupActiveModules(),this.options.renderModuleSummary(),this.options.renderModuleSettings(),this.options.renderStatsWindows(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()}setMechanicTimelineKind(e,t){t?this.activeMechanicTimelineKinds.add(e):this.activeMechanicTimelineKinds.delete(e),this.options.requestConfigSync()}activateMechanicTimelineKind(e){this.activeMechanicTimelineKinds.add(e),this.syncTimelineEvents(),this.syncTimelineRanges(),this.options.renderTimelineEventCount(),this.options.requestConfigSync()}clearTimelineEventSources(){for(const e of this.timelineSourceRemovers.values())e();this.timelineSourceRemovers.clear()}clearTimelineRangeSources(){for(const e of this.timelineRangeSourceRemovers.values())e();this.timelineRangeSourceRemovers.clear()}clearStandalonePlugins(){}syncBoostPadOverlayPlugin(){}toggleBoostPadOverlay(){this.options.renderModuleSummary(),this.options.requestConfigSync()}syncTimelineEvents(){this.clearTimelineEventSources();const e=this.options.getContext(),t=this.options.getTimelineOverlay();if(!(!t||!e)){for(const i of this.options.getEventTimelineSources(e)){if(!i.active)continue;const s=i.buildTimelineEvents();s.length!==0&&this.timelineSourceRemovers.set(i.timelineKey,t.addEventSource(this.options.withTimelineEventSeekTimes(s),{id:i.timelineId,label:i.label}))}t.refreshEvents()}}syncTimelineRanges(){this.clearTimelineRangeSources();const e=this.options.getContext(),t=this.options.getTimelineOverlay();if(!(!t||!e)){for(const i of this.activeModules)!this.activeTimelineRangeModuleIds.has(i.id)||!i.getTimelineRanges||this.timelineRangeSourceRemovers.set(i.id,t.addRangeSource(()=>i.getTimelineRanges?.(e)??[]));for(const i of this.options.getEventTimelineSources(e)){if(!i.active||!i.buildTimelineRanges)continue;const s=i.buildTimelineRanges();s.length!==0&&this.timelineRangeSourceRemovers.set(i.timelineKey,t.addRangeSource(s))}t.refreshRanges()}}getActiveModuleIds(){return new Set([...this.activeTimelineEventSourceIds,...this.activeTimelineRangeModuleIds,...this.activeRenderEffectModuleIds])}getMutableActiveCapabilityIds(e){return e==="events"?this.activeTimelineEventSourceIds:e==="ranges"?this.activeTimelineRangeModuleIds:this.activeRenderEffectModuleIds}}function d9(n){return new u9(n)}function ni(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Iw(n){return ni(n)&&(n.kind==="time"||n.kind==="frame")&&typeof n.value=="number"&&Number.isFinite(n.value)?{kind:n.kind,value:n.value}:null}function rd(n,e){if(n!=null){if(typeof n!="number"||!Number.isInteger(n)||!Number.isFinite(n)||n<0)throw new Error(`Review playlist page ${e} must be a non-negative integer.`);return n}}function Lw(n,e){if(n!=null){if(typeof n!="string")throw new Error(`Review playlist page ${e} must be a string.`);return n}}function h9(n){if(n!=null){if(!ni(n))throw new Error("Review playlist page must be an object.");return{next:Lw(n.next,"next"),previous:Lw(n.previous,"previous"),total:rd(n.total,"total"),count:rd(n.count,"count"),limit:rd(n.limit,"limit"),offset:rd(n.offset,"offset")}}}function f9(n){if(n!=null){if(!ni(n))throw new Error("Review playlist playback must be an object.");if(n.timeBase!==void 0&&n.timeBase!=="playback"&&n.timeBase!=="rawReplay")throw new Error('Review playlist playback timeBase must be "playback" or "rawReplay".');return{...n,timeBase:n.timeBase}}}function p9(n,e){if(n==null)return;if(!ni(n))throw new Error(`Review item ${e} perspective must be an object.`);if(n.kind!=="player")throw new Error(`Review item ${e} perspective kind must be "player".`);const t=typeof n.playerId=="string"&&n.playerId.trim()?n.playerId.trim():void 0,i=typeof n.playerName=="string"&&n.playerName.trim()?n.playerName.trim():void 0;if(!t&&!i)throw new Error(`Review item ${e} player perspective needs playerId or playerName.`);if(n.ballCam!==void 0&&n.ballCam!=="off"&&n.ballCam!=="on"&&n.ballCam!=="player")throw new Error(`Review item ${e} perspective ballCam must be off, on, or player.`);if(n.usePlayerCameraSettings!==void 0&&typeof n.usePlayerCameraSettings!="boolean")throw new Error(`Review item ${e} perspective usePlayerCameraSettings must be boolean.`);return{kind:"player",playerId:t,playerName:i,ballCam:n.ballCam,usePlayerCameraSettings:n.usePlayerCameraSettings}}function m9(n){if(!ni(n)||!Array.isArray(n.items))throw new Error("Review playlist must contain an items array.");const e=n.items.map((i,s)=>{if(!ni(i)||typeof i.replay!="string")throw new Error(`Invalid review item at index ${s}.`);const a=Iw(i.start),r=Iw(i.end);if(!a||!r)throw new Error(`Review item ${s+1} has invalid start or end.`);return{id:typeof i.id=="string"?i.id:void 0,replay:i.replay,start:a,end:r,label:typeof i.label=="string"?i.label:void 0,perspective:p9(i.perspective,s+1),meta:ni(i.meta)?i.meta:void 0}}),t=Array.isArray(n.replays)?n.replays.map(i=>!ni(i)||typeof i.id!="string"?null:{id:i.id,path:typeof i.path=="string"?i.path:void 0,label:typeof i.label=="string"?i.label:void 0,locator:ni(i.locator)?i.locator:void 0,meta:ni(i.meta)?i.meta:void 0}).filter(i=>i!==null):void 0;return{label:typeof n.label=="string"?n.label:void 0,replays:t,items:e,page:h9(n.page),playback:f9(n.playback),meta:n.meta}}function kw(n){let e;try{e=JSON.parse(n)}catch(t){throw new Error(`Invalid review playlist JSON: ${t instanceof Error?t.message:String(t)}`)}return m9(e)}function _9(){const n=new URLSearchParams(window.location.search);return n.get("reviewPlaylist")?.trim()||n.get("review")?.trim()||n.get("playlist")?.trim()||n.get("playlistUrl")?.trim()||null}function g9(n){return/^\/(?:home|Users|tmp|var\/tmp|mnt|media|run\/user|nix\/store)\//.test(n)}function nC(n,e){const t=n.startsWith("path:")?n.slice(5):n;if(/^https?:\/\//i.test(t)||t.startsWith("/@fs/"))return t;if(t.startsWith("/")){if(g9(t))return`/@fs${t}`;if(e){const i=new URL(e,window.location.href);if(i.origin!==window.location.origin)return new URL(t,i.origin).href}return t}return e?new URL(t,e).href:t}function Id(n,e){const t=e.replaysById.get(n.replay);if(t?.path)return t.path;if(ni(t?.locator)&&t.locator.kind==="path"&&typeof t.locator.path=="string")return t.locator.path;if(/^https?:\/\//i.test(n.replay)||n.replay.startsWith("/")||n.replay.startsWith("/@fs/")||n.replay.startsWith("path:"))return n.replay;throw new Error(`Review replay "${n.replay}" does not include a loadable path.`)}function Dw(n,e){const t=e.replaysById.get(n.replay),s=(t?.path??Id(n,e)).replace(/^path:/,"").split("/").filter(Boolean).pop();return t?.label??s??"review replay"}function Ld(n){return typeof n=="number"&&Number.isFinite(n)?`${n.toFixed(2)}s`:"--"}function Ow(n){return n.kind==="time"?Ld(n.value):`frame ${Math.trunc(n.value)}`}function es(n,e){if(!ni(n.meta?.target))return null;const t=n.meta.target[e];return typeof t=="number"&&Number.isFinite(t)?t:null}function kd(n,e){if(!ni(n.meta?.target))return null;const t=n.meta.target[e];return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):null}function y9(n,e){for(const[t,i]of[["eventTime","eventFrame"],["startTime","startFrame"],["endTime","endFrame"]]){const s=es(n,t),a=kd(n,i),r=a===null?null:e.frames[a]?.time;if(s!==null&&typeof r=="number"&&Number.isFinite(r))return s-r}return 0}function iC(n,e,t){return t==="playback"?0:t==="rawReplay"&&typeof e.rawStartTime=="number"&&Number.isFinite(e.rawStartTime)?e.rawStartTime:y9(n,e)}function ag(n,e){return Math.min(Math.max(0,n),Math.max(0,e))}function v9(n,e,t,i){if(e.kind==="frame"){const a=Math.max(0,Math.trunc(e.value));return ag(t.frames[a]?.time??0,t.duration)}const s=iC(n,t,i);return ag(e.value-s,t.duration)}function b9(n,e,t){const i=E9(n);return i===null?null:ag(i-iC(n,e,t),e.duration)}function x9(n){const e=n.start.kind==="time"?n.start.value:null,t=n.end.kind==="time"?n.end.value:null,i=[`${Ow(n.start)} to ${Ow(n.end)}`];e!==null&&t!==null&&i.push(`${Math.max(0,t-e).toFixed(1)}s clip`);const s=es(n,"startTime")??es(n,"eventTime"),a=es(n,"endTime")??es(n,"eventTime");return e!==null&&s!==null&&i.push(`${Math.max(0,s-e).toFixed(1)}s preroll`),t!==null&&a!==null&&i.push(`${Math.max(0,t-a).toFixed(1)}s postroll`),i.join(" · ")}function w9(n){const e=es(n,"eventTime"),t=es(n,"startTime"),i=es(n,"endTime"),s=kd(n,"eventFrame"),a=kd(n,"startFrame"),r=kd(n,"endFrame"),o=t!==null&&i!==null&&Math.abs(i-t)>.001?`${Ld(t)} to ${Ld(i)}`:Ld(e??t??i),l=a!==null&&r!==null&&r!==a?`frames ${a}-${r}`:s!==null?`frame ${s}`:a!==null?`frame ${a}`:null;return[o,l].filter(c=>c&&c!=="--").join(" · ")||"--"}function Gm(n,e){return n.label??n.meta?.eventTypeLabel??n.meta?.mechanicLabel??`Review item ${e+1}`}function S9(n){if(typeof n.meta?.playerName=="string"&&n.meta.playerName.trim())return n.meta.playerName.trim();if(ni(n.meta?.target)&&typeof n.meta.target.playerName=="string"){const e=n.meta.target.playerName.trim();return e||null}return null}function Fw(n,e){if(!n)return null;if(n.playerId){const i=e.find(s=>s.id===n.playerId);if(i)return i}const t=n.playerName?.toLowerCase();return t?e.find(i=>i.name.trim().toLowerCase()===t)??null:null}function Nw(n){if(typeof n.meta?.eventTypeLabel=="string"&&n.meta.eventTypeLabel.trim())return n.meta.eventTypeLabel;if(typeof n.meta?.mechanicLabel=="string"&&n.meta.mechanicLabel.trim())return n.meta.mechanicLabel;const e=n.meta?.eventType??n.meta?.mechanic;return typeof e=="string"?Dn(e):"--"}function T9(n){const e=n.meta?.eventCategory;return typeof e=="string"&&e.trim()?Dn(e.trim()):"--"}function M9(n){const e=n.meta?.eventType??n.meta?.mechanic;return typeof e=="string"&&e.trim()?e.trim().replaceAll("-","_"):null}function E9(n){return es(n,"eventTime")??es(n,"startTime")??es(n,"endTime")}class C9{constructor(e){this.options=e}createReplaySource(e,t,i){const s=Id(e,t),a=nC(s,t.sourceUrl);return{name:Dw(e,t),preparingStatus:"Loading review replay...",async readBytes(){const r=await fetch(a,{signal:i});if(!r.ok){const o=r.statusText?` ${r.statusText}`:"";throw new Error(`Failed to fetch review replay from ${a} (${r.status}${o})`)}return new Uint8Array(await r.arrayBuffer())}}}initialize(e){const t=this.getReplayClipCounts(e);for(const[i,s]of this.getReplayItems(e)){let a="",r=i;try{a=Id(s,e),r=Dw(s,e)}catch{r=e.replaysById.get(i)?.label??i}e.replayLoadStates.set(i,{replayId:i,label:r,path:a,clipCount:t.get(i)??0,status:"idle",progress:null,error:null})}}preload(e,t){if(e.preloading)return;const i=this.getNextReplayItems(e,t);i.length!==0&&(e.preloading=!0,(async()=>{try{for(const s of i){const a=s.replay,r=e.replayLoadStates.get(a);if(!(r?.status==="loaded"||r?.status==="loading"))try{await this.loadBundle(s,e)}catch{}}}finally{e.preloading=!1}})())}loadBundle(e,t){const i=t.replayLoadCache.get(e.replay);if(i)return i;const s=this.createReplaySource(e,t);this.updateLoadState(t,e.replay,{label:s.name,path:Id(e,t),status:"loading",progress:null,error:null});const a=Promise.resolve().then(async()=>{const r=await s.readBytes();return kf(r,{reportEveryNFrames:100,onProgress:o=>{this.updateLoadState(t,e.replay,{status:"loading",progress:o,error:null})}})}).then(r=>(this.updateLoadState(t,e.replay,{status:"loaded",progress:null,error:null}),r)).catch(r=>{throw t.replayLoadCache.delete(e.replay),this.updateLoadState(t,e.replay,{status:"error",error:r instanceof Error?r.message:String(r)}),r});return t.replayLoadCache.set(e.replay,a),a}render(e){const{reviewSummary:t,loadingSummary:i,loadingActive:s,loadingList:a}=this.options.elements,r=e?Array.from(e.replayLoadStates.values()):[],o=r.filter(h=>h.status==="loaded").length,l=r.filter(h=>h.status==="loading").length,c=r.filter(h=>h.status==="error").length,u=r.filter(h=>h.status==="idle").length,d=r.length===0?"0 replays":`${o}/${r.length} loaded${l>0?`, ${l} loading`:""}${c>0?`, ${c} failed`:""}`;if(t.textContent=d,i.textContent=d,s.textContent=r.length===0?"No playlist":l>0?`${l} active, ${u} pending`:c>0?`${c} failed`:e?.preloading?`Background queue, ${u} pending`:o===r.length?"Complete":`${u} pending`,a.replaceChildren(),!e||r.length===0){const h=document.createElement("p");h.className="stat-window-empty",h.textContent="No replay sources.",a.append(h);return}for(const h of r){const f=document.createElement("div");f.className=`mechanics-review-replay-load ${h.status}`;const p=document.createElement("div");p.className="mechanics-review-replay-load-main";const g=document.createElement("span");g.className="mechanics-review-replay-load-title",g.textContent=h.label;const _=document.createElement("span");_.className="mechanics-review-replay-load-meta",_.textContent=[h.replayId,`${h.clipCount} ${h.clipCount===1?"clip":"clips"}`,h.path].filter(Boolean).join(" · "),p.append(g,_);const m=document.createElement("strong");m.className="mechanics-review-replay-load-status",m.textContent=this.replayLoadStatusText(h);const v=document.createElement("div");v.className="mechanics-review-replay-load-progress";const y=document.createElement("span");y.style.width=`${Math.round(this.replayLoadProgressValue(h)*100)}%`,v.append(y),f.append(p,m,v),a.append(f)}}updateLoadState(e,t,i){const s=e.replayLoadStates.get(t)??{replayId:t,label:t,path:"",clipCount:0,status:"idle",progress:null,error:null};e.replayLoadStates.set(t,{...s,...i});const a=e.manifest.items[e.currentIndex];e.loading&&a?.replay===t&&i.progress&&this.options.onActiveLoadProgress(i.progress),this.options.isActiveReview(e)&&this.render(e)}getReplayItems(e){const t=new Map;for(const i of e.manifest.items)t.has(i.replay)||t.set(i.replay,i);return t}getReplayClipCounts(e){const t=new Map;for(const i of e.manifest.items)t.set(i.replay,(t.get(i.replay)??0)+1);return t}getNextReplayItems(e,t){const i=e.manifest.items[t]?.replay,s=new Set(i?[i]:[]),a=[];for(let r=t+1;r{const i=t.file.files?.[0];if(i)try{const s=kw(await i.text());await this.loadPlaylist(s,null)}catch(s){console.error("Failed to load review playlist:",s),this.setStatus(s instanceof Error?s.message:"Failed to load review playlist")}finally{t.file.value=""}},{signal:e}),t.loadUrl.addEventListener("click",()=>{this.loadPlaylistFromUrl(t.url.value.trim()).catch(i=>{console.error("Failed to load review playlist URL:",i),this.setStatus(i instanceof Error?i.message:"Failed to load review playlist URL")})},{signal:e}),t.previous.addEventListener("click",()=>{const i=this.activeReview;i&&this.activateItem(Math.max(0,i.currentIndex-1))},{signal:e}),t.replay.addEventListener("click",()=>this.replayClip(),{signal:e}),t.next.addEventListener("click",()=>{const i=this.activeReview;i&&this.activateItem(Math.min(i.manifest.items.length-1,i.currentIndex+1))},{signal:e}),t.confirm.addEventListener("click",()=>{this.submitDecision("confirmed")},{signal:e}),t.reject.addEventListener("click",()=>{this.submitDecision("rejected")},{signal:e}),t.uncertain.addEventListener("click",()=>{this.submitDecision("uncertain")},{signal:e})}render(){const{elements:e}=this.options,t=this.activeReview,i=t?.manifest.items??[],s=t?i[t.currentIndex]??null:null,a=i.length>0;e.count.textContent=`${i.length} item${i.length===1?"":"s"}`,e.index.textContent=a&&t?`${t.currentIndex+1} / ${i.length}`:"0 / 0",e.title.textContent=s?Gm(s,t?.currentIndex??0):"No candidate selected",e.mechanic.textContent=s?Nw(s):"--",e.player.textContent=s?this.getPlayerName(s):"--",e.clip.textContent=s?x9(s):"--",e.event.textContent=s?w9(s):"--",e.reason.textContent=s?.meta?.reason??"--",e.previous.disabled=!t||t.loading||t.currentIndex<=0,e.replay.disabled=!t||t.loading||!t.currentClip,e.next.disabled=!t||t.loading||t.currentIndex>=i.length-1;const r=!t||t.loading||Uw(s)===null;if(e.confirm.disabled=r,e.reject.disabled=r,e.uncertain.disabled=r,this.options.replayLoads.render(t),e.list.replaceChildren(),!t||i.length===0){const o=document.createElement("p");o.className="stat-window-empty",o.textContent="No review playlist loaded.",e.list.append(o);return}i.forEach((o,l)=>{const c=document.createElement("button");c.type="button",c.className="mechanics-review-item",c.dataset.active=l===t.currentIndex?"true":"false",c.disabled=t.loading,c.addEventListener("click",()=>{this.activateItem(l)});const u=document.createElement("span");u.textContent=Gm(o,l);const d=document.createElement("strong");d.textContent=[T9(o),Nw(o),this.getPlayerName(o),$m(o.meta?.reviewStatus)].filter(h=>h&&h!=="--").join(" · ")||"--",c.append(u,d),e.list.append(c)})}async loadPlaylist(e,t){const i=new Map;for(const s of e.replays??[])i.set(s.id,s);this.activeReview={manifest:e,sourceUrl:t,replaysById:i,replayLoadStates:new Map,replayLoadCache:new Map,currentIndex:0,loading:!1,preloading:!1,currentReplayId:null,currentClip:null},this.options.replayLoads.initialize(this.activeReview),this.options.showReplayLoadingWindow(),this.setStatus(e.label?`Loaded ${e.label}.`:"Loaded review playlist."),this.render(),e.items.length>0&&await this.activateItem(0)}async loadPlaylistFromUrl(e){if(!e){this.setStatus("Enter a review playlist URL.");return}const t=nC(e,window.location.href);this.setStatus("Loading review playlist...");const i=await fetch(t);if(!i.ok){const a=i.statusText?` ${i.statusText}`:"";throw new Error(`Failed to fetch review playlist from ${t} (${i.status}${a})`)}const s=kw(await i.text());await this.loadPlaylist(s,i.url||t)}async activateItem(e){const t=this.activeReview,i=t?.manifest.items[e];if(!(!t||!i||t.loading)){t.loading=!0,t.currentIndex=e,this.render(),this.setStatus(`Loading ${Gm(i,e)}...`);try{if(!this.options.getReplayPlayer()||t.currentReplayId!==i.replay){const d=this.options.replayLoads.createReplaySource(i,t),h=this.options.replayLoads.loadBundle(i,t);await this.options.loadReplayBundleForDisplay(d,h),t.currentReplayId=i.replay}this.options.replayLoads.preload(t,e);const a=t.manifest.playback?.timeBase,r=Math.max(0,this.getBoundTime(i,i.start,a)),o=Math.min(this.options.getReplayPlayer()?.getState().duration??Number.POSITIVE_INFINITY,Math.max(r,this.getBoundTime(i,i.end,a)));if(!Number.isFinite(r)||!Number.isFinite(o)||o<=r)throw new Error("Review item has an empty playback range.");const l=this.options.getReplayPlayer(),c=l?Fw(i.perspective,l.replay.players):null;c&&this.options.applyClipPerspective({playerId:c.id,ballCam:i.perspective?.ballCam,usePlayerCameraSettings:i.perspective?.usePlayerCameraSettings}),this.options.resetReplayTransitionControls();const u=l===null?null:b9(i,l.replay,a);t.currentClip={startTime:r,endTime:o,targetTime:u},this.options.activateTimelineSource(i),this.options.getReplayPlayer()?.setState({currentTime:r,playing:!0,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),this.setStatus(u===null?`Playing ${r.toFixed(2)}s to ${o.toFixed(2)}s`:`Playing ${r.toFixed(2)}s to ${o.toFixed(2)}s; target ${u.toFixed(2)}s`)}catch(s){console.error("Failed to activate mechanics review item:",s),t.currentClip=null,this.setStatus(s instanceof Error?s.message:"Failed to load review item")}finally{t.loading=!1,this.render()}}}replayClip(){const e=this.activeReview?.currentClip,t=this.options.getReplayPlayer();!e||!t||t.setState({currentTime:e.startTime,playing:!0,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1})}async submitDecision(e){const t=this.activeReview,i=t?.manifest.items[t.currentIndex]??null,s=Uw(i);if(!t||!i||!s){this.setStatus("Current review item has no review endpoint.");return}this.setStatus(`Submitting ${$m(e)}...`);const a=await fetch(s,{method:"POST",headers:{"content-type":"application/json",...P9()},credentials:"same-origin",body:JSON.stringify({status:e})});if(!a.ok){let r=`${a.status}${a.statusText?` ${a.statusText}`:""}`;try{const o=await a.json();typeof o.error=="string"&&(r=o.error)}catch{}this.setStatus(`Review failed: ${r}`);return}i.meta=i.meta??{},i.meta.reviewStatus=e,this.setStatus(`Marked ${$m(e)}.`),this.render()}enforceClipBoundary(e){const t=this.activeReview?.currentClip,i=this.options.getReplayPlayer();if(!t||!i||this.boundaryGuard)return!1;const s=e.currentTime=t.endTime-.025;if(!s&&!a)return!1;this.boundaryGuard=!0;try{i.setState({currentTime:s?t.startTime:t.endTime,playing:!1,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),a&&this.setStatus(`Finished clip at ${t.endTime.toFixed(2)}s`)}finally{this.boundaryGuard=!1}return!0}getBoundTime(e,t,i){const s=this.options.getReplayPlayer();return s?v9(e,t,s.replay,i):t.kind==="time"?t.value:0}getPlayerName(e){const t=S9(e);if(t)return t;const i=this.options.getReplayPlayer()?.replay.players??[];return Fw(e.perspective,i)?.name??"--"}}function $m(n){return typeof n=="string"&&n.trim()?n.replaceAll("_"," "):"unreviewed"}function Uw(n){if(!n)return null;if(typeof n.meta?.reviewEndpoint=="string"&&n.meta.reviewEndpoint)return n.meta.reviewEndpoint;const e=typeof n.meta?.eventId=="string"&&n.meta.eventId?n.meta.eventId:n.id;return e?`/api/v1/events/${encodeURIComponent(e)}/reviews`:null}function P9(){const n=new URLSearchParams(window.location.search),e=n.get("reviewToken")??n.get("token")??window.localStorage.getItem("rocket_sense_access_token");return e?{Authorization:`Bearer ${e}`}:{}}function I9(n){return new R9(n)}const L9=["replayUrl","replay_url","replay"],k9=["r","replayUrlZ","replay_url_z"],D9=["ballchasing","ballchasingId","ballchasingUuid","ballchasingReplay"];function O9(n){const e=n.replaceAll("-","+").replaceAll("_","/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=atob(t),s=new Uint8Array(i.length);for(let a=0;a{n.signal.aborted||(console.error("Failed to load replay URL:",t),n.statusReadout.textContent=t instanceof Error?t.message:"Failed to load replay URL")})}function H9(n){n.initialBundle?n.loadReplayBundleForDisplay({name:n.initialReplayName??"replay",preparingStatus:"Preparing replay...",async readBytes(){throw new Error("Replay bytes are not available for this preloaded replay")}},Promise.resolve(n.initialBundle)).catch(i=>{n.signal.aborted||(console.error("Failed to load preprocessed replay bundle:",i),n.statusReadout.textContent=i instanceof Error?i.message:"Failed to load preprocessed replay bundle")}):n.loadFromLocation!==!1&&z9(n);const e=_9();if(!e)return;const t=n.getMechanicsReviewController();t?.setUrl(e),n.showMechanicsReviewWindow(),t?.loadPlaylistFromUrl(e).catch(i=>{n.signal.aborted||(console.error("Failed to load mechanics review playlist from URL:",i),t?.setStatus(i instanceof Error?i.message:"Failed to load mechanics review playlist from URL"))})}function V9(n){const e=()=>{n.getSkipPostGoalTransitions().checked=!1,n.getSkipKickoffs().checked=!1},t=(i,s)=>{const a=n.getReplayPlayer();!a||!Number.isFinite(i)||(n.getMechanicsReviewController()?.clearCurrentClip(),e(),a.setState({currentTime:Math.max(0,i-n.goalWatchLeadSeconds),playing:s,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),n.scheduleConfigUrlUpdate())};return{watchGoalReplay(i,s){const a=n.getReplayPlayer();if(!a||!Number.isFinite(i))return;if(n.getMechanicsReviewController()?.clearCurrentClip(),s!==null&&a.replay.players.some(o=>o.id===s)){a.setAttachedPlayer(s),a.setCameraViewMode("follow");const o=n.getCameraControlsController();o&&(o.freeCameraPreset=null)}e(),a.setState({currentTime:Math.max(0,i-n.goalWatchLeadSeconds),playing:!0,skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),n.scheduleConfigUrlUpdate()},cueGoalReplay(i){t(i,!1)},cueTimelineEvent(i){const s=n.getReplayPlayer();s&&(n.getMechanicsReviewController()?.clearCurrentClip(),e(),s.setState({currentTime:cy(i),skipPostGoalTransitionsEnabled:!1,skipKickoffsEnabled:!1}),n.scheduleConfigUrlUpdate())},applyConfigToReplayPlayer(i){const s=n.getReplayPlayer();if(!s)return;s.setState(R6(i.playback,i.camera,i));const a=n.getCameraControlsController();a&&(a.freeCameraPreset=i.camera.freePreset??null),i.camera.mode==="free"&&i.camera.freePreset&&s.setFreeCameraPreset(i.camera.freePreset),n.syncBoostPadOverlayPlugin(),n.setupActiveModules(),n.renderModuleSummary(),n.renderModuleSettings(),n.renderStatsWindows(s.getState().frameIndex)}}}function G9(n){let e=!1,t=null;const i=()=>n.getFloatingWindowController()?.getSingletonConfigs()??[],s=()=>n.getStatsWindowsController()?.getConfigs()??[],a=()=>{const o=n.getActiveModulesRuntime(),l=n.getReplayPlayer();return A6({playback:E6({replayPlayer:l,playbackRate:n.playbackRate,skipPostGoalTransitions:n.skipPostGoalTransitions,skipKickoffs:n.skipKickoffs}),camera:C6({replayPlayer:l,cameraControlsController:n.getCameraControlsController()}),activeTimelineEventSourceIds:o.getActiveTimelineEventSourceIds(),activeTimelineRangeModuleIds:o.getActiveTimelineRangeModuleIds(),activeMechanicTimelineKinds:o.getActiveMechanicTimelineKinds(),activeRenderEffectModuleIds:o.getActiveRenderEffectModuleIds(),initialConfig:n.getInitialConfig(),replayPlayer:l,boostPadOverlayEnabled:o.getBoostPadOverlayEnabled(),recording:n.getRecordingWindowController()?.getConfigSnapshot()??{},singletonWindows:i(),statsWindows:s(),moduleConfigs:M6(n.modules)})},r=o=>{b6(tC(n.modules),o)};return{setApplyingConfig(o){e=o},reset(){t!==null&&(window.clearTimeout(t),t=null),e=!1},scheduleConfigUrlUpdate(){e||(t!==null&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null;const o=Z1(new URL(window.location.href),a());window.history.replaceState(window.history.state,"",o)},150))},applyConfigToStaticControls(o){if(n.getActiveModulesRuntime().applyOverlayConfig(o.overlays),n.skipPostGoalTransitions.checked=o.playback.skipPostGoalTransitions??n.skipPostGoalTransitions.checked,n.skipKickoffs.checked=o.playback.skipKickoffs??n.skipKickoffs.checked,n.hitboxWireframes.checked=o.overlays.hitboxWireframes,n.hitboxOnlyMode.checked=o.overlays.hitboxOnlyMode,n.getCameraControlsController()?.applyNameplateLiftUu(o.camera.nameplateLiftUu),n.getCameraControlsController()?.setAutoPossessionEnabled(o.camera.autoPossession??!1,{requestConfigSync:!1}),o.playback.rate!==void 0){const l=zf(o.playback.rate);n.playbackRate.value=`${l}`,n.playbackRateReadout.textContent=Ry(l)}n.getRecordingWindowController()?.applyConfig(o.recording),r(o.moduleConfigs),n.getFloatingWindowController()?.applySingletonConfigs(o.singletonWindows),n.getStatsWindowsController()?.replaceFromConfig(o.statsWindows),n.renderModuleSummary(),n.renderModuleSettings(),n.renderTimelineEventCount()}}}function $9(n){const e=t=>{const i=n.getLauncherToggle();n.getLauncherMenu().hidden=!t,i.setAttribute("aria-label",t?"Close menu":"Open menu"),i.setAttribute("aria-expanded",t?"true":"false")};return{bringWindowToFront(t){n.getFloatingWindowController()?.bringToFront(t)},showWindow(t){n.getFloatingWindowController()?.show(t)},toggleWindow(t){n.getFloatingWindowController()?.toggle(t)},hideWindow(t){n.getFloatingWindowController()?.hide(t)},setLauncherOpen:e,openReplayFilePicker(){n.getFileInput().click(),e(!1)},installWindowDragging(t,i){n.getFloatingWindowController()?.installDragging(t,i)},getElementWindowId(t){return t.closest("[data-window-id]")?.dataset.windowId??null}}}const rg=4096,wr=5120,W9=893,X9=642,ns=1/105;class K9{constructor(e){this.options=e,this.options.body.innerHTML=`
@@ -5920,4 +5985,4 @@ void main() {

Load a replay with shot events.

- `,this.chartCanvas=this.mustElement("#shot-chart-canvas"),this.shotList=this.mustElement("#shot-list"),this.summary=this.mustElement("#shot-visualization-summary"),this.details=this.mustElement("#shot-details"),this.sceneRoot=this.mustElement("#shot-demo-scene"),this.emptyState=this.mustElement("#shot-visualization-empty"),this.chartCanvas.addEventListener("click",t=>this.handleChartClick(t))}chartCanvas;shotList;summary;details;sceneRoot;emptyState;renderer=null;scene=null;camera=null;resizeObserver=null;selectedShotId=null;cachedReplay=null;cachedShots=[];lastShotsSignature="";lastListSelectionKey=null;lastSelectedShotKey=null;shotButtons=new Map;destroy(){this.resizeObserver?.disconnect(),this.renderer?.dispose(),this.renderer=null,this.scene=null,this.camera=null}render(e=this.options.getReplayPlayer()?.getState()??null){const t=this.shotEvents(),i=e?.currentTime??null;this.findSelectedShot(t)||(this.selectedShotId=t[0]?this.shotKey(t[0],0):null);const s=this.findSelectedShot(t),a=s?.key??null,r=this.shotsSignature(t),o=r!==this.lastShotsSignature;this.emptyState.hidden=t.length>0,o&&(this.summary.textContent=this.summaryText(t)),o||a!==this.lastListSelectionKey?(this.renderShotList(t,i,a),this.lastListSelectionKey=a):this.updateShotListActiveState(t,i),this.renderChart(t,i),(o||a!==this.lastSelectedShotKey)&&(this.renderSelectedShot(s?.shot??null),this.lastSelectedShotKey=a),this.lastShotsSignature=r}shotEvents(){const e=this.options.getReplayPlayer()?.replay;return e?e===this.cachedReplay?this.cachedShots:(this.cachedReplay=e,this.cachedShots=e.timelineEvents.filter(u9),this.cachedShots):(this.cachedReplay=null,this.cachedShots=[],[])}summaryText(e){if(e.length===0)return"No shots";const t=e.filter(a=>a.shot.resulting_save).length,i=e.map(a=>a.shot.ball_speed).filter(a=>Number.isFinite(a)),s=i.length===0?null:i.reduce((a,r)=>a+r,0)/i.length;return`${e.length} shots | ${t} saved | avg ${id(s)}`}renderShotList(e,t,i){this.shotButtons.clear(),this.shotList.replaceChildren(...e.map((s,a)=>{const r=this.shotKey(s,a),o=document.createElement("button");o.type="button",o.className="shot-list-item",o.dataset.selected=String(r===i),o.dataset.active=String(Um(s,t)),o.addEventListener("click",()=>{this.selectedShotId=r,this.options.cueTimelineEvent(s),this.render()});const l=document.createElement("span");l.className="shot-list-title",l.textContent=s.playerName??s.playerId??`Shot ${a+1}`;const c=document.createElement("span");return c.className="shot-list-meta",c.textContent=`${Lw(s.time)} | ${id(s.shot.ball_speed)} | ${s.shot.resulting_save?"saved":"unsaved"}`,o.append(l,c),this.shotButtons.set(r,o),o}))}updateShotListActiveState(e,t){e.forEach((i,s)=>{const a=this.shotButtons.get(this.shotKey(i,s));a&&(a.dataset.active=String(Um(i,t)))})}renderChart(e,t){const i=this.chartCanvas.getContext("2d");if(!i)return;const s=window.devicePixelRatio||1,a=this.chartCanvas.getBoundingClientRect(),r=Math.max(320,Math.round(a.width*s)),o=Math.max(220,Math.round(a.height*s));(this.chartCanvas.width!==r||this.chartCanvas.height!==o)&&(this.chartCanvas.width=r,this.chartCanvas.height=o),i.setTransform(s,0,0,s,0,0);const l=r/s,c=o/s;i.clearRect(0,0,l,c),d9(i,l,c),e.forEach((u,d)=>{const h=u.shot.shot_touch_position??u.shot.ball_position,f=Ah(h,l,c),p=!!u.shot.resulting_save,g=Um(u,t),_=this.shotKey(u,d)===this.selectedShotId,m=_?6:g?5:4;i.beginPath(),i.arc(f.x,f.y,m,0,Math.PI*2),i.fillStyle=p?"#f2c14e":"#62d2a2",i.fill(),i.lineWidth=_?2.5:1.25,i.strokeStyle=_?"#f8fafc":g?"#e11d48":"rgba(4, 12, 20, 0.85)",i.stroke()})}renderSelectedShot(e){if(!e){this.details.replaceChildren(),this.clearThreeScene();return}this.details.replaceChildren(Ml("Player",e.playerName??e.playerId??"--"),Ml("Speed",id(e.shot.ball_speed)),Ml("Toward goal",id(e.shot.ball_speed_toward_goal)),Ml("Touch",f9(e.shot.shot_touch_position??e.shot.ball_position)),Ml("Save",e.shot.resulting_save?Lw(e.shot.resulting_save.time):"--")),this.renderThreeScene(e)}renderThreeScene(e){const t=this.ensureRenderer(),i=this.scene,s=this.camera;i.clear(),i.add(new Pc(16777215,1.2));const a=new Ko(16777215,1.7);a.position.set(18,28,22),i.add(a);const r=new Se(new Nn(Q_*2*ts,xr*2*ts),new je({color:1520422,side:ut}));r.rotation.x=-Math.PI/2,i.add(r);const o=new Pt({color:14280674,transparent:!0,opacity:.55});i.add(new Fn(new hf(r.geometry),o)),i.add(Pw(!0)),i.add(Pw(!1));const l=Iw(e.shot.shot_touch_position??e.shot.ball_position),c=Iw(e.shot.target_goal_position),u=e.shot.ball_velocity,d=u?l.clone().add(h9(u).normalize().multiplyScalar(22)):c.clone(),h=new Pg([l,l.clone().lerp(d,.45).setY(Math.max(l.y,d.y)+2.8),d]),f=new $e().setFromPoints(h.getPoints(36));i.add(new On(f,new Pt({color:e.shot.resulting_save?15909198:6476450,linewidth:2})));const p=new Se(new vn(.9,24,16),new kn({color:16317180,roughness:.36}));p.position.copy(l),i.add(p);const g=new Se(new oi(1.05,1.45,32),new je({color:8892372,side:ut}));g.position.copy(c),g.rotation.y=Math.PI/2,i.add(g),s.position.set(0,54,72),s.lookAt(0,0,0),t.render(i,s)}ensureRenderer(){if(this.renderer&&this.scene&&this.camera)return this.resizeThreeScene(),this.renderer;const e=new Jg({antialias:!0,alpha:!0,preserveDrawingBuffer:!0});return e.setPixelRatio(window.devicePixelRatio||1),this.sceneRoot.replaceChildren(e.domElement),this.renderer=e,this.scene=new Tc,this.scene.background=new de(463132),this.camera=new Qt(42,1,.1,500),this.resizeObserver=new ResizeObserver(()=>{this.resizeThreeScene();const t=this.shotEvents().find(i=>i.id===this.selectedShotId)??null;t&&this.renderThreeScene(t)}),this.resizeObserver.observe(this.sceneRoot),this.resizeThreeScene(),e}resizeThreeScene(){if(!this.renderer||!this.camera)return;const e=this.sceneRoot.getBoundingClientRect(),t=Math.max(240,Math.round(e.width)),i=Math.max(170,Math.round(e.height));this.camera.aspect=t/i,this.camera.updateProjectionMatrix(),this.renderer.setSize(t,i,!1)}clearThreeScene(){this.sceneRoot.replaceChildren(),this.renderer?.dispose(),this.renderer=null,this.scene=null,this.camera=null}handleChartClick(e){const t=this.shotEvents(),i=this.chartCanvas.getBoundingClientRect(),s={x:e.clientX-i.left,y:e.clientY-i.top};let a=null,r=Number.POSITIVE_INFINITY;for(const o of t){const l=Ah(o.shot.shot_touch_position??o.shot.ball_position,i.width,i.height),c=Math.hypot(l.x-s.x,l.y-s.y);c`${this.shotKey(t,i)}:${t.time}:${t.shot.ball_speed}`).join("|")}}function u9(n){return n.kind==="shot"&&!!n.shot}function Um(n,e){return e!==null&&Math.abs(e-n.time)<1.5}function d9(n,e,t){n.fillStyle="#0f2b24",n.fillRect(0,0,e,t),n.strokeStyle="rgba(226, 241, 236, 0.74)",n.lineWidth=1.2,n.strokeRect(18,18,e-36,t-36),n.beginPath(),n.moveTo(18,t/2),n.lineTo(e-18,t/2),n.stroke(),n.beginPath(),n.arc(e/2,t/2,34,0,Math.PI*2),n.stroke();const s=Ah({x:0,y:-xr},e,t),a=Ah({x:0,y:xr},e,t);n.fillStyle="#4fa3ff",n.fillRect(s.x-28,s.y-4,56,8),n.fillStyle="#ff8a4c",n.fillRect(a.x-28,a.y-4,56,8)}function Ah(n,e,t){const s=e-36,a=t-36;return{x:18+(n.x+Q_)/(Q_*2)*s,y:18+(1-(n.y+xr)/(xr*2))*a}}function Pw(n){const e=new Et,t=new Pt({color:n?16747084:5219327}),i=(n?xr:-xr)*ts,s=o9*ts,a=l9*ts,r=[new T(-s,0,i),new T(-s,a,i),new T(s,a,i),new T(s,0,i)];return e.add(new On(new $e().setFromPoints(r),t)),e}function Iw(n){return new T(n.x*ts,n.z*ts,n.y*ts)}function h9(n){return new T(n.x*ts,n.z*ts,n.y*ts)}function Ml(n,e){const t=document.createElement("div"),i=document.createElement("dt");i.textContent=n;const s=document.createElement("dd");return s.textContent=e,t.append(i,s),t}function Lw(n){return Number.isFinite(n)?`${n.toFixed(2)}s`:"--"}function id(n){return Number.isFinite(n)?`${Math.round(n)} uu/s`:"--"}function f9(n){return n?`${Math.round(n.x)}, ${Math.round(n.y)}, ${Math.round(n.z)}`:"--"}const p9=4,m9=100;let lt=null,Sy=null,Rh=null,To=null,Mo=null,Ph=null,kw=0,ja=null;const Of=b1({refreshTimelineRanges(){Oh()},rerenderCurrentState(){lt&<.setBoostPickupAnimationEnabled(lt.getState().boostPickupAnimationEnabled)},requestConfigSync(){_n()}}),Rd=lW({rerenderCurrentState(){if(!lt)return;const n=lt.getState();kc(n.frameIndex)},refreshTimelineRanges(){Oh()},requestConfigSync(){_n()}},{boostPickupFilters:Of}),gn=C6({modules:Rd,boostPickupFilters:Of,getContext:Co,getReplayPlayer:()=>lt,getTimelineOverlay:()=>Sy,getEventTimelineSources:Ty,withTimelineEventSeekTimes:Q1,renderModuleSummary:rr,renderModuleSettings:or,renderStatsWindows(){lt&&kc(lt.getState().frameIndex)},renderTimelineEventCount:uo,requestConfigSync:_n}),Fl=s9({goalWatchLeadSeconds:p9,getReplayPlayer:()=>lt,getCameraControlsController:()=>Wi,getMechanicsReviewController:()=>Xi,getSkipPostGoalTransitions:()=>Za,getSkipKickoffs:()=>Ja,syncBoostPadOverlayPlugin:J1,setupActiveModules:Dh,renderModuleSummary:rr,renderModuleSettings:or,renderStatsWindows(n){kc(n)},scheduleConfigUrlUpdate:_n}),Ei=r9({getFloatingWindowController:()=>fa,getLauncherMenu:()=>ng,getLauncherToggle:()=>tg,getFileInput:()=>Ih});let Nl=null,Ih,q1,eg,Dw,tg,ng,Ow,Fw,Nw,Uw,Bw,zw,Bm,zm,Hm,Vm,sd,ad,Hw,Vw,Gw,$w,la,Y1,j1,ig,Za,co=null,Ja,Ul,Bl,rd=null,sg=zo(null),Wi=null,zl=null,Ww=null,Eo=null,gc=null,yc=null,Lh=null,Xi=null,fa=null,ag=null,kh=null,Pd=null,ua=null,rg=null,Os=null;function _9(n){return gn.getActiveCapabilityIds(n)}function g9(){}function Co(){return!lt||!To||!Mo?null:{player:lt,replay:lt.replay,statsTimeline:To,statsFrameLookup:Mo,fieldScale:1}}function Dh(){gn.setupActiveModules()}function Z1(){gn.teardownActiveModules()}function Xw(n,e,t){gn.toggleCapability(n,e,t)}function y9(){gn.clearTimelineEventSources()}function v9(){gn.clearTimelineRangeSources()}function b9(){gn.clearStandalonePlugins()}function J1(){gn.syncBoostPadOverlayPlugin()}function Kw(){gn.syncTimelineEvents()}function Oh(){gn.syncTimelineRanges()}function uo(){const n=Co();if(!n){ig.textContent="--";return}ig.textContent=`${x9(n)}`}function x9(n){return yc?.countVisibleSources(n)??0}function re(n,e){const t=n.querySelector(e);if(!(t instanceof HTMLElement))throw new Error(`Missing element for selector: ${e}`);return t}function w9(n){if(!fa)throw new Error("Floating windows are not initialized.");return fa.readPlacement(n)}function S9(n,e){fa?.applyPlacement(n,e)}function kc(n=lt?.getState().frameIndex??0,e={}){Eo?.render(n,e)}function T9(n){Eo?.create(n)}function M9(){Eo?.clear()}function _n(){ua?.scheduleConfigUrlUpdate()}function E9(n){ua?.applyConfigToStaticControls(n)}function Q1(n){return n.map(e=>({...e,seekTime:ny(e)}))}function rr(){Lh?.renderSummary()}function eC(){yc?.render()}function Ty(n){return yc?.getSources(n)??[]}function C9(){const n=Co();return VW(n,Ty(n))}function My(){gc?.render()}function Ey(n){const e=Nl?.querySelector(`[data-window-id="${n}"]`);return!!(e&&!e.hidden)}function Cy(n,e={}){!e.forceScroll&&!Ey("event-playlist")||gc?.syncTimeline(n,e)}function tC(){gc?.reset()}function A9(n){const e=H6(n);e&&(gn.activateMechanicTimelineKind(e),eC())}function R9(n){return Xi?.enforceClipBoundary(n)??!1}function or(){Lh?.renderSettings()}function Ay(n=lt?.getState().frameIndex??0){ag?.render(n)}function nC(n=lt?.getState()??null){Ey("shot-visualization")&&Pd?.render(n)}function P9(n){if(Ei.toggleWindow(n),!!Ey(n)){if(n==="event-playlist"){My();const e=lt?.getState();e&&Cy(e,{forceScroll:!0})}n==="shot-visualization"&&nC(lt?.getState()??null)}}function I9(n){kh?.setTransportEnabled(n,lt?.getState())}function iC(n=Rh?.getStatus()??null){zl?.sync(n)}function L9(n){if(R9(n))return;const e=performance.now();n.playing&&e-kwU8(n,e=>{la.textContent=jo(e),co?.update(e)})))}async function og(n,e){await Z8(n,e,{elements:{fileInput:Ih,viewport:q1,emptyState:eg,statusReadout:la,playersReadout:Y1,framesReadout:j1,skipPostGoalTransitions:Za,skipKickoffs:Ja,hitboxWireframes:Ul,hitboxOnlyMode:Bl},getReplayLoadModal:()=>co,getReplayPlayer:()=>lt,setReplayPlayer(t){lt=t,ja?.syncSource()},getUnsubscribe:()=>Ph,setUnsubscribe(t){Ph=t},setCanvasRecorder(t){Rh=t},setLoadedReplayName(t){rg=t},setTimelineOverlay(t){Sy=t},setStatsTimeline(t){To=t,ja?.syncSource()},setStatsFrameLookup(t){Mo=t},setStatRegistry(t){sg=t},getInitialConfig:()=>Os,setApplyingConfig(t){ua?.setApplyingConfig(t)},getReplayTimelineEvents(t){return A4(t,gn.getActiveTimelineEventSourceIds())},withTimelineEventSeekTimes:Q1,includeBoostPickupAnimationPickup:k9,syncRecordingWindow:iC,setTransportEnabled:I9,teardownActiveModules:Z1,clearTimelineEventSources:y9,clearTimelineRangeSources:v9,clearStandalonePlugins:b9,clearRenderCaches:g9,resetEventPlaylistWindow:tC,renderModuleSummary:rr,renderScoreboard:Ay,renderTimelineEventCount:uo,renderMechanicsTimelineControls:eC,renderEventPlaylistWindow:My,renderModuleSettings:or,syncBoostPadOverlayPlugin:J1,setupActiveModules:Dh,renderSnapshot:L9,applyConfigToReplayPlayer:Fl.applyConfigToReplayPlayer,renderStatsWindows:kc,syncEventPlaylistTimeline:Cy,getCameraControlsController:()=>Wi})}function D9(n,e={}){rd?.(),n.innerHTML=hU(),Nl=n,co=IH(n),fa=k8({getRoot:()=>Nl??document,requestConfigSync:_n}),Ih=re(n,"#replay-file"),q1=re(n,"#viewport"),eg=re(n,"#empty-state"),Dw=re(n,"#empty-load-replay"),tg=re(n,"#launcher-toggle"),ng=re(n,"#launcher-menu"),Ow=re(n,"#load-replay-action"),Fw=re(n,"#floating-window-layer"),ag=l6({body:re(n,"#scoreboard-window-body"),getReplayPlayer:()=>lt,getStatsFrameLookup:()=>Mo});const t=re(n,"#mechanics-timeline-window-body");yc=KW({body:t,modules:Rd,getContext:Co,getActiveTimelineEventSourceIds:()=>gn.getActiveTimelineEventSourceIds(),getActiveMechanicTimelineKinds:()=>gn.getActiveMechanicTimelineKinds(),toggleEventSource(d,h){Xw(d,"events",h)},setMechanicTimelineKind(d,h){gn.setMechanicTimelineKind(d,h)},setupActiveModules:Dh,syncTimelineEvents:Kw,syncTimelineRanges:Oh,renderModuleSummary:rr,renderModuleSettings:or,renderTimelineEventCount:uo,requestConfigSync:_n}),Nw=re(n,"#event-playlist-window-body"),gc=O8({body:Nw,getReplayPlayer:()=>lt,getSources:C9,cueTimelineEvent:Fl.cueTimelineEvent,formatTime:ds}),Pd=new c9({body:re(n,"#shot-visualization-window-body"),getReplayPlayer:()=>lt,cueTimelineEvent:Fl.cueTimelineEvent}),Uw=re(n,"#replay-loading-summary"),Bw=re(n,"#replay-loading-active"),zw=re(n,"#replay-loading-list");const i=$6({elements:{reviewSummary:re(n,"#mechanics-review-replay-load-summary"),loadingSummary:Uw,loadingActive:Bw,loadingList:zw},isActiveReview(d){return Xi?.review===d},onActiveLoadProgress(d){la.textContent=jo(d),co?.update(d)}});Xi=K6({elements:{file:re(n,"#mechanics-review-file"),url:re(n,"#mechanics-review-url"),loadUrl:re(n,"#mechanics-review-load-url"),status:re(n,"#mechanics-review-status"),index:re(n,"#mechanics-review-index"),title:re(n,"#mechanics-review-title"),mechanic:re(n,"#mechanics-review-mechanic"),player:re(n,"#mechanics-review-player"),clip:re(n,"#mechanics-review-clip"),event:re(n,"#mechanics-review-event"),reason:re(n,"#mechanics-review-reason"),previous:re(n,"#mechanics-review-prev"),replay:re(n,"#mechanics-review-replay"),next:re(n,"#mechanics-review-next"),confirm:re(n,"#mechanics-review-confirm"),reject:re(n,"#mechanics-review-reject"),uncertain:re(n,"#mechanics-review-uncertain"),count:re(n,"#mechanics-review-count"),list:re(n,"#mechanics-review-list")},replayLoads:i,getReplayPlayer:()=>lt,resetReplayTransitionControls(){Za.checked=!1,Ja.checked=!1},activateTimelineSource:A9,loadReplayBundleForDisplay:og,applyClipPerspective(d){Wi?.followPlayerWithReplayCamera(d.playerId,{ballCam:d.ballCam,usePlayerCameraSettings:d.usePlayerCameraSettings})},showReplayLoadingWindow(){Ei.showWindow("replay-loading")}});const s=re(n,"#boost-pickup-filters-window-body"),a=re(n,"#touch-controls-window-body");Bm=re(n,"#stats-window-layer"),Eo=xW({layer:Bm,getReplayPlayer:()=>lt,getStatsTimeline:()=>To,getStatsFrameLookup:()=>Mo,getStatRegistry:()=>sg,readWindowPlacement:w9,applyWindowPlacement:S9,bringWindowToFront:Ei.bringWindowToFront,setLauncherOpen:Ei.setLauncherOpen,requestConfigSync:_n,watchGoalReplay:Fl.watchGoalReplay,cueGoalReplay:Fl.cueGoalReplay}),zm=re(n,"#toggle-playback"),Hm=re(n,"#previous-frame"),Vm=re(n,"#next-frame"),sd=re(n,"#playback-rate"),Wi=kH({elements:{attachedPlayer:re(n,"#attached-player"),cameraViewFreeButton:re(n,"#camera-view-free"),cameraViewFollowButton:re(n,"#camera-view-follow"),cameraViewAutoPossession:re(n,"#camera-view-auto-possession"),cameraViewOverheadButton:re(n,"#camera-view-overhead"),cameraViewSideButton:re(n,"#camera-view-side"),usePlayerCameraSettings:re(n,"#use-player-camera-settings"),cameraSettingsControls:re(n,"#camera-settings-controls"),customCameraFov:re(n,"#custom-camera-fov"),customCameraHeight:re(n,"#custom-camera-height"),customCameraPitch:re(n,"#custom-camera-pitch"),customCameraDistance:re(n,"#custom-camera-distance"),customCameraStiffness:re(n,"#custom-camera-stiffness"),customCameraSwivelSpeed:re(n,"#custom-camera-swivel-speed"),customCameraTransitionSpeed:re(n,"#custom-camera-transition-speed"),customCameraFovReadout:re(n,"#custom-camera-fov-readout"),customCameraHeightReadout:re(n,"#custom-camera-height-readout"),customCameraPitchReadout:re(n,"#custom-camera-pitch-readout"),customCameraDistanceReadout:re(n,"#custom-camera-distance-readout"),customCameraStiffnessReadout:re(n,"#custom-camera-stiffness-readout"),customCameraSwivelSpeedReadout:re(n,"#custom-camera-swivel-speed-readout"),customCameraTransitionSpeedReadout:re(n,"#custom-camera-transition-speed-readout"),ballCamOffButton:re(n,"#ball-cam-off"),ballCamOnButton:re(n,"#ball-cam-on"),ballCamPlayerButton:re(n,"#ball-cam-player"),nameplateLift:re(n,"#custom-nameplate-lift"),nameplateLiftReadout:re(n,"#custom-nameplate-lift-readout"),cameraProfileReadout:re(n,"#camera-profile-readout"),cameraFovReadout:re(n,"#camera-fov-readout"),cameraHeightReadout:re(n,"#camera-height-readout"),cameraPitchReadout:re(n,"#camera-pitch-readout"),cameraBaseDistanceReadout:re(n,"#camera-base-distance-readout"),cameraStiffnessReadout:re(n,"#camera-stiffness-readout")},getReplayPlayer:()=>lt,requestConfigSync:_n,onAutoPossessionChange(d){ja?.syncSource(),d&&ja?.syncCurrentFrame()}}),ja=rV({getReplayPlayer:()=>lt,getStatsTimeline:()=>To,getCameraControlsController:()=>Wi}),S1(re(n,"#touch-color-legend-body"),["team"]),Lh=ZW({elements:{summary:re(n,"#module-summary"),settings:re(n,"#module-settings"),boostPickupFilters:s,touchControls:a},modules:Rd,boostPickupFilters:Of,getContext:Co,getTimelineSources:()=>Ty(Co()),getActiveModules:()=>gn.getActiveModules(),getActiveCapabilityIds:_9,getBoostPickupAnimationEnabled:()=>lt?.getState().boostPickupAnimationEnabled??!1,toggleCapability:Xw,toggleBoostPickupAnimation(){const d=!(lt?.getState().boostPickupAnimationEnabled??!1);lt?.setBoostPickupAnimationEnabled(d),Dh(),rr(),or(),_n()},syncTimelineEvents:Kw,syncTimelineRanges:Oh,renderTimelineEventCount:uo,requestConfigSync:_n}),Hw=re(n,"#time-readout"),Vw=re(n,"#frame-readout"),Gw=re(n,"#duration-readout"),$w=re(n,"#playback-status-readout"),la=re(n,"#status-readout"),Y1=re(n,"#players-readout"),j1=re(n,"#frames-readout"),ig=re(n,"#events-readout"),ad=re(n,"#playback-rate-readout"),Za=re(n,"#skip-post-goal-transitions"),Ja=re(n,"#skip-kickoffs"),Ul=re(n,"#hitbox-wireframes"),Bl=re(n,"#hitbox-only-mode"),kh=u6({elements:{togglePlayback:zm,previousFrame:Hm,nextFrame:Vm,playbackRate:sd,playbackRateReadout:ad,skipPostGoalTransitions:Za,skipKickoffs:Ja,hitboxWireframes:Ul,hitboxOnlyMode:Bl,emptyState:eg,timeReadout:Hw,frameReadout:Vw,durationReadout:Gw,playbackStatusReadout:$w},getFrameCount:()=>lt?.replay.frameCount??0,getCameraControlsController:()=>Wi}),zl=s6({elements:{fps:re(n,"#recording-fps"),playbackRate:re(n,"#recording-playback-rate"),start:re(n,"#recording-start"),fullReplay:re(n,"#recording-full-replay"),stop:re(n,"#recording-stop"),download:re(n,"#recording-download"),clear:re(n,"#recording-clear"),status:re(n,"#recording-status"),elapsed:re(n,"#recording-elapsed"),size:re(n,"#recording-size"),type:re(n,"#recording-type")},getCanvasRecorder:()=>Rh,getReplayPlayer:()=>lt,getLoadedReplayName:()=>rg,setStatus(d){la.textContent=d},requestConfigSync:_n}),Ww=M6({elements:{mechanic:re(n,"#missed-event-mechanic"),capture:re(n,"#missed-event-capture"),list:re(n,"#missed-event-list"),export:re(n,"#missed-event-export"),upload:re(n,"#missed-event-upload"),clear:re(n,"#missed-event-clear"),status:re(n,"#missed-event-status")},getReplayPlayer:()=>lt,showWindow:()=>Ei.showWindow("missed-events")}),ua=a9({modules:Rd,playbackRate:sd,playbackRateReadout:ad,skipPostGoalTransitions:Za,skipKickoffs:Ja,hitboxWireframes:Ul,hitboxOnlyMode:Bl,getReplayPlayer:()=>lt,getCameraControlsController:()=>Wi,getRecordingWindowController:()=>zl,getFloatingWindowController:()=>fa,getStatsWindowsController:()=>Eo,getActiveModulesRuntime:()=>gn,getInitialConfig:()=>Os,renderModuleSummary:rr,renderModuleSettings:or,renderTimelineEventCount:uo});const r=B1(window.location),o=g8(window.location);let l=null;if(e.initialConfig!==void 0)Os=e.initialConfig;else{try{Os=_8(window.location)}catch(d){l=d,console.error("Invalid stats player config:",d),la.textContent=d instanceof Error?d.message:"Invalid stats player config",Os=null}o&&j8(r,Os,l)}const c=new AbortController;Ei.installWindowDragging(Fw,c.signal),Ei.installWindowDragging(Bm,c.signal);const u=()=>{c.abort(),Ph?.(),Ph=null,Z1(),lt?.destroy(),lt=null,Rh=null,Sy=null,To=null,Mo=null,sg=zo(null),M9(),Eo=null,gn.reset(),co?.destroy(),co=null,tC(),yc=null,gc=null,Xi?.reset(),Xi=null,rg=null,ja?.reset(),ja=null,Wi=null,zl=null,Lh=null,ag=null,kh=null,Pd?.destroy(),Pd=null,Os=null,ua?.reset(),ua=null,fa?.reset(),fa=null,Nl===n&&(Nl=null,n.replaceChildren()),rd===u&&(rd=null)};if(rd=u,Os){ua?.setApplyingConfig(!0);try{E9(Os)}finally{ua?.setApplyingConfig(!1)}}return d6({elements:{root:n,launcherToggle:tg,launcherMenu:ng,loadReplayAction:Ow,emptyLoadReplay:Dw,fileInput:Ih,togglePlayback:zm,previousFrame:Hm,nextFrame:Vm,playbackRate:sd,playbackRateReadout:ad,skipPostGoalTransitions:Za,skipKickoffs:Ja,hitboxWireframes:Ul,hitboxOnlyMode:Bl},signal:c.signal,setLauncherOpen:Ei.setLauncherOpen,openReplayFilePicker:Ei.openReplayFilePicker,getElementWindowId:Ei.getElementWindowId,toggleWindow:P9,hideWindow:Ei.hideWindow,createStatsWindow:T9,async loadReplayFile(d){try{Xi?.clearCurrentClip({resetReplayId:!0,render:!0}),await qw(F8(d))}catch(h){console.error("Failed to load replay:",h),la.textContent=h instanceof Error?h.message:"Failed to load replay"}},togglePlayback(){lt?.togglePlayback(),_n()},stepFrames(d){lt?.stepFrames(d),_n()},setPlaybackRate(d){lt?.setPlaybackRate(d),_n()},setSkipPostGoalTransitionsEnabled(d){lt?.setSkipPostGoalTransitionsEnabled(d),_n()},setSkipKickoffsEnabled(d){lt?.setSkipKickoffsEnabled(d),_n()},setHitboxWireframesEnabled(d){lt?.setHitboxWireframesEnabled(d),_n()},setHitboxOnlyModeEnabled(d){lt?.setHitboxOnlyModeEnabled(d),_n()}}),Xi?.installEventListeners(c.signal),zl?.installEventListeners(c.signal),Ww?.installEventListeners(c.signal),Wi?.installEventListeners(c.signal),p6({getReplayPlayer:()=>lt,signal:c.signal}),window.addEventListener("message",d=>{if(d.origin!==window.location.origin)return;const h=d.data;!h||typeof h!="object"||h.source!=="rocket-sense"||h.type==="activateReviewItem"&&typeof h.index=="number"&&Number.isInteger(h.index)&&Xi?.activateItem(h.index)},{signal:c.signal}),rr(),or(),Ay(),Wi?.renderProfile(),Wi?.syncModeButtons(),iC(),uo(),Xi?.render(),My(),i9({signal:c.signal,location:window.location,statusReadout:la,initialBundle:e.initialBundle,initialReplayName:e.initialReplayName,loadFromLocation:e.loadFromLocation,loadReplay:qw,loadReplayBundleForDisplay:og,getMechanicsReviewController:()=>Xi,showMechanicsReviewWindow(){Ei.showWindow("mechanics-review")}}),{root:n,destroy:u}}const In=["#58a6ff","#f39a37"],Yw=["#58a6ff","#f39a37","#65d6ad","#d2a8ff","#ff7b72","#f2cc60","#79c0ff","#ffa657"],El={zero:"#ff7b72",low:"#f39a37",midLow:"#f2cc60",midHigh:"#65d6ad",high:"#58a6ff"},jw={big:"#f39a37",small:"#65d6ad"},sC=[{id:"overview",label:"Overview"},{id:"goals",label:"Goals"},{id:"boost",label:"Boost"},{id:"territory",label:"Possession & territory"},{id:"involvement",label:"Player involvement"},{id:"dump",label:"All stats"}],O9=[{statId:"player:core.score",kind:"bar",title:"Score by player"},{statId:"player:core.shots",kind:"bar",title:"Shots by player"},{statId:"player:touch.touch_count",kind:"bar",title:"Touches by player"},{statId:"team:core.shots",kind:"pie",title:"Shot share"},{statId:"team:possession.possession_time",kind:"pie",title:"Possession share"},{statId:"team:ball_half.offensive_pressure_time",kind:"bar",title:"Offensive pressure"}],F9=[{statId:"player:touch.touch_count",kind:"bar",title:"Touches"},{statId:"player:touch.control_touch_count",kind:"bar",title:"Control touches"},{statId:"player:touch.hard_hit_count",kind:"bar",title:"Hard hits"},{statId:"player:demo.demos_inflicted",kind:"bar",title:"Demos inflicted"},{statId:"player:fifty_fifty.wins",kind:"bar",title:"50/50 wins"},{statId:"player:powerslide.total_duration",kind:"bar",title:"Powerslide time"}];function te(n,e={}){const t=document.createElement(n);return e.className&&(t.className=e.className),e.id&&(t.id=e.id),e.text!==void 0&&(t.textContent=e.text),t}function aC(n,e,t){return e==="player"?n.name||`Player ${t+1}`:t===0?"Blue":"Orange"}function Fh(n){return n?Ct(n):null}function ao(n,e){const t=Fh(e);return t?n.players.find(i=>Fh(i.player_id)===t)?.name??t:"--"}function lg(n){return n===!0?"Blue":n===!1?"Orange":"--"}function rC(n,e){return e==="player"?n.players:[n.team_zero,n.team_one]}function oC(n){return n.is_team_0?In[0]:In[1]}function N9(n,e,t){return e==="player"?oC(n):In[t%In.length]}function U9(n,e){const t=n.frames.at(-1);return t?e.get(t.frame_number)??null:null}function B9(n,e){const t=n.read(e);return typeof t=="number"&&Number.isFinite(t)?t:null}function wr(n){return n==null||!Number.isFinite(n)?"--":`${Number(n.toFixed(1))}s`}function z9(n){return n==null||!Number.isFinite(n)?"--":`${Number(n.toFixed(1))}%`}function Ai(n,e){return e>0?`${wr(n)} (${z9(n/e*100)})`:"--"}function Id(n){return n?`x ${Math.round(n.x)}, y ${Math.round(n.y)}, z ${Math.round(n.z)}`:"--"}function es(n){return n==null||!Number.isFinite(n)?"--":`${Number(Ys(n).toFixed(0))}`}function Jl(n){if(n==null||!Number.isFinite(n))return"--";const e=Math.max(0,n),t=Math.floor(e/60),i=e-t*60;return`${t}:${i.toFixed(1).padStart(4,"0")}`}function H9(n,e,t){if(!n||e==null||!Number.isFinite(e))return null;const i=Fh(t),s=new URL("../",window.location.href);return s.searchParams.set("replayUrl",n.href),z1(s,lC(e,i)).href}function V9(n,e,t){if(e==null||!Number.isFinite(e))return null;const i=Fh(t);return{config:lC(e,i),href:H9(n,e,t),goalTime:e,playerId:i}}function lC(n,e){return{version:Eh,playback:{currentTime:Math.max(0,n-4),playing:!0,rate:1,skipPostGoalTransitions:!1,skipKickoffs:!1},camera:e?{mode:"follow",attachedPlayerId:e,ballCam:!0}:{mode:"free"},overlays:{timelineEvents:["core"],timelineRanges:[],mechanics:[],renderEffects:[],followedPlayerHud:!1,boostPads:!0,boostPickupAnimation:!1,hitboxWireframes:!1,hitboxOnlyMode:!1},recording:{},singletonWindows:[],statsWindows:[],moduleConfigs:{}}}function cC(n,e){return e>0?`${Number((Ys(n)/e*60).toFixed(1))}/min`:"--"}function G9(n){const e=new Map;for(const t of n){const i=`${t.scope}:${t.category}`,s=e.get(i);s?s.push(t):e.set(i,[t])}return new Map([...e].sort(([t],[i])=>t.localeCompare(i)))}function uC(n){const[e,t]=n.split(":"),i=(t??"").replace(/_/g," ").replace(/\b\w/g,s=>s.toUpperCase());return`${e==="player"?"Player":"Team"} ${i}`}function dC(n){return`stats-${n.replace(/[^a-z0-9]+/gi,"-").toLowerCase()}`}function $9(n){return n.path.slice(1).join(".")||n.label}function W9(n){return!n.path.includes("entries")}function Tn(n,e,t){const i=te("section",{className:"stats-report-summary-card"});return i.append(te("span",{text:n}),te("strong",{text:e})),t&&i.append(te("small",{text:t})),i}function X9(n,e){const t=te("section",{className:"stats-report-summary"}),i=e.time>0?wr(e.time):"--";return t.append(Tn("Replay",n.fileName),Tn("Frames",n.statsTimeline.frames.length.toLocaleString()),Tn("Duration",i),Tn("Players",e.players.length.toLocaleString())),t}function Jo(n,e){const t=te("section",{className:"stats-report-page-intro"});return t.append(te("h2",{text:n}),te("p",{text:e})),t}function K9(n,e,t){const i=e[0]?.scope??"player",s=rC(t,i),a=te("section",{className:"stats-report-section",id:dC(n)}),r=te("header");r.append(te("h2",{text:uC(n)}),te("span",{text:`${e.length} stats`}));const o=te("div",{className:"stats-report-table-wrap"}),l=te("table",{className:"stats-report-table"}),c=te("thead"),u=te("tr");u.append(te("th",{text:"Statistic"})),s.forEach((h,f)=>{u.append(te("th",{text:aC(h,i,f)}))}),c.append(u);const d=te("tbody");return e.forEach(h=>{const f=te("tr");f.append(te("td",{text:$9(h)})),s.forEach(p=>{f.append(te("td",{text:h.format(h.read(p))}))}),d.append(f)}),l.append(c,d),o.append(l),a.append(r,o),a}function Ry(n,e){return rC(e,n.scope).map((t,i)=>({label:aC(t,n.scope,i),value:B9(n,t)??0,color:N9(t,n.scope,i)})).filter(t=>t.value>0)}function Ql(n,e){const t=Math.max(...n.map(s=>s.value),1),i=te("div",{className:"stats-report-bar-chart"});return n.forEach(s=>{const a=te("div",{className:"stats-report-bar-row"});a.style.setProperty("--bar-color",s.color),a.style.setProperty("--bar-width",`${Math.max(2,s.value/t*100)}%`),a.append(te("span",{className:"stats-report-bar-label",text:s.label}),te("span",{className:"stats-report-bar-track"}),te("strong",{text:s.formatted??e(s.value)})),i.append(a)}),i}function hC(n,e){const t=n.path.join(".");return n.category==="boost"&&(t.includes("amount_")||t.includes("overfill")||t.includes("boost_integral"))?es(e):t.endsWith("_time")||t.startsWith("time_")||t.includes(".time_")||t.endsWith("_duration")||t==="active_game_time"||t==="tracked_time"?wr(e):n.format(e)}function q9(n,e){return Ql(Ry(n,e),t=>hC(n,t))}function Y9(n){const e=n.reduce((i,s)=>i+s.value,0);if(e<=0)return"conic-gradient(rgba(255,255,255,0.12) 0 360deg)";let t=0;return`conic-gradient(${n.map(i=>{const s=t;return t+=i.value/e*360,`${i.color} ${s}deg ${t}deg`}).join(", ")})`}function Nh(n,e){const t=n.reduce((r,o)=>r+o.value,0),i=te("div",{className:"stats-report-pie-chart"}),s=te("div",{className:"stats-report-pie"});s.style.background=Y9(n);const a=te("div",{className:"stats-report-pie-legend"});return n.forEach(r=>{const o=te("div");o.style.setProperty("--legend-color",r.color);const l=t>0?`${Math.round(r.value/t*100)}%`:"--";o.append(te("span",{text:r.label}),te("strong",{text:`${r.formatted??e(r.value)} (${l})`})),a.append(o)}),i.append(s,a),i}function j9(n,e){return Nh(Ry(n,e),t=>hC(n,t))}function fC(n,e="Territory share"){return ai(e,Nh([{label:"Blue half",value:n.team_zero.ball_half.defensive_half_time,color:In[0]},{label:"Neutral",value:n.team_zero.ball_half.neutral_time,color:"#65d6ad"},{label:"Orange half",value:n.team_zero.ball_half.offensive_half_time,color:In[1]}],wr))}function ai(n,e,t){const i=te("section",{className:"stats-report-chart-card"});return i.append(te("h3",{text:n})),i.append(e),i}function pC(n,e,t){return Ry(e,t).length===0?null:ai(n.title,n.kind==="pie"?j9(e,t):q9(e,t))}function mC(n,e,t){const i=new Map(n.map(a=>[a.id,a])),s=te("section",{className:"stats-report-charts"});return t.forEach(a=>{const r=i.get(a.statId);if(!r)return;const o=pC(a,r,e);o&&s.append(o)}),s.childElementCount>0?s:null}function Ho(n,e){const t=te("div",{className:"stats-report-stacked-chart"});return n.forEach(i=>{const s=i.segments.reduce((l,c)=>l+Math.max(0,c.value),0),a=te("div",{className:"stats-report-stacked-row"}),r=te("div",{className:"stats-report-stacked-track"});i.segments.forEach(l=>{const c=te("span");c.style.setProperty("--segment-color",l.color),c.style.setProperty("--segment-width",`${s>0?Math.max(1.5,l.value/s*100):0}%`),c.title=`${l.label}: ${e(l.value,s)}`,r.append(c)});const o=te("div",{className:"stats-report-stacked-legend"});i.segments.forEach(l=>{const c=te("span",{text:`${l.label}: ${e(l.value,s)}`});c.style.setProperty("--legend-color",l.color),o.append(c)}),a.append(te("strong",{text:i.label}),r,o),t.append(a)}),t}function Ff(n){const e=te("section",{className:"stats-report-metric-grid"});return e.append(...n),e}function lr(n,e,t){const i=[...n].sort((a,r)=>e(r)-e(a))[0],s=i?e(i):0;return Tn(i?.name??"--",t(s))}function Z9(n,e){const t=te("div",{className:"stats-report-page"});t.append(Jo("All stats dump","Everything emitted by the current stats timeline, including experimental mechanic counters and low-level breakdowns."));const i=te("nav",{className:"stats-report-jump-nav"});for(const a of n.keys()){const r=te("a",{text:uC(a)});r.setAttribute("href",`#${dC(a)}`),i.append(r)}t.append(i);const s=te("div",{className:"stats-report-grid"});for(const[a,r]of n)s.append(K9(a,r,e));return t.append(s),t}let Ld=null,vc={};function J9(n,e,t){const i=te("div",{className:"stats-report-page"});i.append(X9(n,e)),i.append(Jo("Featured stats","A shorter readout of stable scoreboard, touch, boost, possession, and pressure signals. The raw export remains available in All stats."));const s=`${e.team_zero.core.goals}-${e.team_one.core.goals}`;i.append(Ff([Tn("Final score",s,"Blue - Orange"),lr(e.players,r=>r.touch.touch_count,r=>`${r} touches`),lr(e.players,r=>r.boost.tracked_time>0?Ys(r.boost.boost_integral/r.boost.tracked_time):0,r=>`${Number(r.toFixed(0))} avg boost`),lr(e.players,r=>r.core.score,r=>`${r} score`)]));const a=mC(t,e,O9)??te("section",{className:"stats-report-charts"});return a.append(fC(e)),i.append(a),i}function Q9(n){return[...n??[]].sort((e,t)=>e.kind.localeCompare(t.kind)||t.metadata.confidence-e.metadata.confidence)}function Zw(n){const e=new Map;for(const t of n)e.set(t.kind,(e.get(t.kind)??0)+1);return[...e.entries()].sort(([t,i],[s,a])=>a-i||Dn(t).localeCompare(Dn(s))).map(([t,i],s)=>({label:Dn(t),value:i,color:Yw[s%Yw.length],formatted:i.toLocaleString()}))}function e7(n){const e=te("dl",{className:"stats-report-detail-list"});for(const t of n){const i=te("div",{className:"stats-report-detail-item"});i.append(te("dt",{text:t.label}),te("dd",{text:t.value})),e.append(i)}return e}function t7(n){const e=te("div",{className:"stats-report-goal-tags"});if(n.length===0)return e.append(te("span",{className:"stats-report-goal-tag stats-report-goal-tag-empty",text:"Unlabeled"})),e;for(const t of n){const i=t.metadata,s=r1(t),a=s?` - ${s}`:"";e.append(te("span",{className:"stats-report-goal-tag",text:`${Dn(t.kind)} ${Math.round(i.confidence*100)}%${a}`}))}return e}function n7(n,e){if(e.length===0)return null;const t=te("div",{className:"stats-report-goal-subsection"});t.append(te("h3",{text:"Player context"}));const i=te("div",{className:"stats-report-table-wrap"}),s=te("table",{className:"stats-report-table"}),a=te("thead"),r=te("tr");["Player","Team","Boost","Leadup avg","Leadup min","Role","Position"].forEach(l=>{r.append(te("th",{text:l}))}),a.append(r);const o=te("tbody");for(const l of e){const c=te("tr");c.append(te("td",{text:ao(n,l.player)}),te("td",{text:lg(l.is_team_0)}),te("td",{text:es(l.boost_amount)}),te("td",{text:es(l.average_boost_in_leadup)}),te("td",{text:es(l.min_boost_in_leadup)}),te("td",{text:l.is_most_back?"Most back":"--"}),te("td",{text:Id(l.position)})),o.append(c)}return s.append(a,o),i.append(s),t.append(i),t}function i7(n,e,t,i,s){const a=i?.scoring_team_is_team_0??null,r=i?.scorer??null,o=i?.time??null,l=i?.frame??null,c=V9(e,o,r),u=te("section",{className:"stats-report-goal-card"});a!==null&&(u.dataset.team=a?"blue":"orange");const d=te("header"),h=te("div",{className:"stats-report-goal-heading"});if(h.append(te("h2",{text:`Goal ${t+1}`}),te("span",{text:`${lg(a)} - ${ao(n,r)} - ${Jl(o)}`})),d.append(h),c){if(vc.onWatchGoal){const g=te("button",{className:"stats-report-goal-watch",text:"Watch"});g.type="button",g.addEventListener("click",()=>{vc.onWatchGoal?.(c)}),d.append(g)}else if(c.href){const g=te("a",{className:"stats-report-goal-watch",text:"Watch"});g.setAttribute("href",c.href),g.setAttribute("target","_blank"),g.setAttribute("rel","noreferrer"),d.append(g)}}u.append(d),u.append(t7(s));const f=[{label:"Scoring team",value:lg(a)},{label:"Scorer",value:ao(n,r)},{label:"Time",value:Jl(o)},{label:"Frame",value:l==null?"--":l.toLocaleString()},{label:"Scorer last touch",value:i?.scorer_last_touch?`${ao(n,i.scorer_last_touch.player)} at ${Jl(i.scorer_last_touch.time)}`:"--"},{label:"Scoring most back",value:ao(n,i?.scoring_team_most_back_player)},{label:"Defending most back",value:ao(n,i?.defending_team_most_back_player)},{label:"Ball position",value:Id(i?.ball_position)},{label:"Last touch ball",value:Id(i?.scorer_last_touch?.ball_position)},{label:"Last touch player",value:Id(i?.scorer_last_touch?.player_position)}];u.append(e7(f));const p=n7(n,i?.players??[]);return p&&u.append(p),u}function s7(n,e){const t=te("div",{className:"stats-report-page"});t.append(Jo("Goal metadata","Goal-by-goal scorer, timing, context, tag confidence, and lead-up player state from the stats timeline event stream."));const i=[...be(n.statsTimeline,"goal_context")].sort((p,g)=>p.time-g.time),s=i.flatMap(p=>p.tags??[]),a=s.filter(T4),r=s.filter(M4),o=i.map((p,g)=>g),l=i.filter(p=>(p.tags??[]).length>0).length,c=Zw(a),u=Zw(r),d=c[0];if(t.append(Ff([Tn("Goals found",o.length.toLocaleString()),Tn("Tagged goals",l.toLocaleString()),Tn("Scorer goal tags",a.length.toLocaleString()),Tn("Assist goal tags",r.length.toLocaleString()),Tn("Top tag",d?`${d.label} (${d.value})`:"--")])),o.length===0)return t.append(te("section",{className:"stats-report-empty",text:"No goal metadata was emitted for this replay."})),t;const h=te("section",{className:"stats-report-charts"});h.append(ai("Scorer goal tags by type",c.length>0?Ql(c,p=>p.toLocaleString()):te("p",{className:"stats-report-note",text:"No scorer goal tags emitted."})),ai("Assist goal tags by type",u.length>0?Ql(u,p=>p.toLocaleString()):te("p",{className:"stats-report-note",text:"No assist goal tags emitted."})),ai("Goal timing",Ql(o.map(p=>{const g=i[p]??null,_=g?.time??0,m=g?.scoring_team_is_team_0??!0;return{label:`Goal ${p+1}`,value:_,color:m?In[0]:In[1],formatted:Jl(_)}}),Jl))),t.append(h);const f=te("div",{className:"stats-report-goal-list"});for(const p of o)f.append(i7(e,n.replayUrl,p,i[p]??null,Q9(i[p]?.tags)));return t.append(f),t}function a7(n,e){const t=te("div",{className:"stats-report-page"});t.append(Jo("Boost economy","A focused view of boost usage, collection, pad mix, starvation, and waste. Values are shown in normal 0-100 boost units.")),t.append(Ff([lr(n.players,a=>a.boost.amount_used,a=>`${es(a)} used`),lr(n.players,a=>a.boost.amount_stolen,a=>`${es(a)} stolen`),lr(n.players,a=>a.boost.overfill_total,a=>`${es(a)} overfill`),lr(n.players,a=>a.boost.time_zero_boost,a=>`${wr(a)} at zero`)]));const i=te("section",{className:"stats-report-charts"});i.append(ai("Boost used per minute",Ql(n.players.map((a,r)=>({label:a.name||`Player ${r+1}`,value:a.boost.tracked_time>0?Ys(a.boost.amount_used)/a.boost.tracked_time*60:0,color:oC(a),formatted:cC(a.boost.amount_used,a.boost.tracked_time)})),a=>`${Number(a.toFixed(1))}/min`)),ai("Pad collection mix",Ho(n.players.map((a,r)=>({label:a.name||`Player ${r+1}`,segments:[{label:"Big",value:a.boost.amount_collected_big,color:jw.big},{label:"Small",value:a.boost.amount_collected_small,color:jw.small}]})),a=>es(a))),ai("Boost tank time",Ho(n.players.map((a,r)=>({label:a.name||`Player ${r+1}`,segments:[{label:"0",value:a.boost.time_zero_boost,color:El.zero},{label:"0-25",value:a.boost.time_boost_0_25,color:El.low},{label:"25-50",value:a.boost.time_boost_25_50,color:El.midLow},{label:"50-75",value:a.boost.time_boost_50_75,color:El.midHigh},{label:"75-100",value:a.boost.time_boost_75_100+a.boost.time_hundred_boost,color:El.high}]})),Ai)));const s=new Map(e.map(a=>[a.id,a]));for(const a of[{statId:"player:boost.amount_used",kind:"bar",title:"Total boost used"},{statId:"player:boost.overfill_total",kind:"bar",title:"Boost overfill"},{statId:"player:boost.amount_stolen",kind:"bar",title:"Stolen boost"}]){const r=s.get(a.statId),o=r?pC(a,r,n):null;o&&i.append(o)}return t.append(i),t.append(r7(n)),t}function r7(n){const e=te("section",{className:"stats-report-section"}),t=te("header");t.append(te("h2",{text:"Boost scorecard"}),te("span",{text:"display units"}));const i=[{label:"Average boost",read(c){return c.boost.tracked_time>0?`${Number(Ys(c.boost.boost_integral/c.boost.tracked_time).toFixed(0))}`:"--"}},{label:"Used per minute",read(c){return cC(c.boost.amount_used,c.boost.tracked_time)}},{label:"Collected",read(c){return es(c.boost.amount_collected)}},{label:"Stolen",read(c){return es(c.boost.amount_stolen)}},{label:"Overfill",read(c){return es(c.boost.overfill_total)}},{label:"Big pads",read(c){return`${c.boost.big_pads_collected}`}},{label:"Small pads",read(c){return`${c.boost.small_pads_collected}`}},{label:"Time at zero",read(c){return Ai(c.boost.time_zero_boost,c.boost.tracked_time)}}],s=te("div",{className:"stats-report-table-wrap"}),a=te("table",{className:"stats-report-table"}),r=te("thead"),o=te("tr");o.append(te("th",{text:"Metric"})),n.players.forEach((c,u)=>{o.append(te("th",{text:c.name||`Player ${u+1}`}))}),r.append(o);const l=te("tbody");return i.forEach(c=>{const u=te("tr");u.append(te("td",{text:c.label})),n.players.forEach(d=>{u.append(te("td",{text:c.read(d)}))}),l.append(u)}),a.append(r,l),s.append(a),e.append(t,s),e}function o7(n){const e=te("div",{className:"stats-report-page"});e.append(Jo("Possession & territory","Team control, field-half pressure, and where each player spent time relative to the field and the ball."));const t=n.team_zero.possession.tracked_time,i=n.team_zero.ball_half.tracked_time,s=n.team_zero.ball_third.tracked_time;e.append(Ff([Tn("Blue possession",Ai(n.team_zero.possession.possession_time,t)),Tn("Orange possession",Ai(n.team_zero.possession.opponent_possession_time,t)),Tn("Blue pressure",Ai(n.team_zero.ball_half.offensive_half_time,i),"Time in Orange half"),Tn("Orange pressure",Ai(n.team_zero.ball_half.defensive_half_time,i),"Time in Blue half"),Tn("Blue final third",Ai(n.team_zero.ball_third.offensive_third_time,s),"Time in Orange third"),Tn("Orange final third",Ai(n.team_zero.ball_third.defensive_third_time,s),"Time in Blue third")]));const a=te("section",{className:"stats-report-charts"});return a.append(ai("Possession split",Nh([{label:"Blue control",value:n.team_zero.possession.possession_time,color:In[0]},{label:"Neutral",value:n.team_zero.possession.neutral_time,color:"#65d6ad"},{label:"Orange control",value:n.team_zero.possession.opponent_possession_time,color:In[1]}],wr)),fC(n,"Field half pressure"),ai("Ball third control",Nh([{label:"Blue third",value:n.team_zero.ball_third.defensive_third_time,color:In[0]},{label:"Neutral third",value:n.team_zero.ball_third.neutral_third_time,color:"#65d6ad"},{label:"Orange third",value:n.team_zero.ball_third.offensive_third_time,color:In[1]}],wr)),ai("Player field thirds",Ho(n.players.map((r,o)=>({label:r.name||`Player ${o+1}`,segments:[{label:"Def",value:r.positioning.time_defensive_third,color:r.is_team_0?In[0]:In[1]},{label:"Mid",value:r.positioning.time_neutral_third,color:"#65d6ad"},{label:"Off",value:r.positioning.time_offensive_third,color:r.is_team_0?In[1]:In[0]}]})),Ai)),ai("Role time",Ho(n.players.map((r,o)=>({label:r.name||`Player ${o+1}`,segments:[{label:"Most back",value:r.positioning.time_most_back,color:"#58a6ff"},{label:"Mid",value:r.positioning.time_mid_role,color:"#65d6ad"},{label:"Most forward",value:r.positioning.time_most_forward,color:"#f39a37"},{label:"Other",value:r.positioning.time_other_role,color:"rgba(255,255,255,0.22)"}]})),Ai))),e.append(a),e}function l7(n,e){const t=te("div",{className:"stats-report-page"});t.append(Jo("Player involvement","Interaction stats that are usually easier to trust at a glance: touches, hits, demos, 50/50 outcomes, movement, and powerslide usage."));const i=mC(e,n,F9);i&&t.append(i);const s=te("section",{className:"stats-report-charts"});return s.append(ai("Speed bands",Ho(n.players.map((a,r)=>({label:a.name||`Player ${r+1}`,segments:[{label:"Slow",value:a.movement.time_slow_speed,color:"#58a6ff"},{label:"Boost",value:a.movement.time_boost_speed,color:"#f2cc60"},{label:"Supersonic",value:a.movement.time_supersonic_speed,color:"#f39a37"}]})),Ai)),ai("Aerial profile",Ho(n.players.map((a,r)=>({label:a.name||`Player ${r+1}`,segments:[{label:"Ground",value:a.movement.time_on_ground,color:"#65d6ad"},{label:"Low air",value:a.movement.time_low_air,color:"#58a6ff"},{label:"High air",value:a.movement.time_high_air,color:"#d2a8ff"}]})),Ai))),t.append(s),t.append(te("p",{className:"stats-report-note",text:"Experimental event detectors such as speed flips, dodge refreshes, and ceiling shots are kept in All stats until their precision is stronger."})),t}function _C(){const n=window.location.hash.replace(/^#/,"");return sC.some(e=>e.id===n)?n:"overview"}function c7(n,e,t){const i=te("nav",{className:"stats-report-tabs"});return sC.forEach(s=>{const a=te("button",{text:s.label});a.type="button",a.dataset.active=s.id===n?"true":"false",a.addEventListener("click",()=>{_C()!==s.id&&window.history.replaceState(null,"",`#${s.id}`),Uh(e,t)}),i.append(a)}),i}function Py(n){const e=te("header",{className:"stats-report-header"}),t=te("div",{className:"stats-report-title"});if(t.append(te("h1",{text:"Replay Stats"}),te("p",{text:n??"Load a Rocket League replay to review curated stats pages, comparison graphs, and the complete raw stat dump."})),vc.showStandaloneActions!==!1){const i=te("div",{className:"stats-report-actions"}),s=te("label",{className:"stats-report-file-label",text:"Load replay"}),a=te("input");a.type="file",a.accept=".replay",a.addEventListener("change",async()=>{const o=a.files?.[0],l=Ld;o&&l instanceof HTMLElement&&await u7(l,o)}),s.append(a);const r=te("a",{className:"stats-report-link",text:"Open player"});r.setAttribute("href","../"),i.append(s,r),e.append(t,i)}else e.append(t);return e}function Uh(n,e){const t=U9(e.statsTimeline,e.statsFrameLookup);if(!t){n.replaceChildren(te("main",{className:"stats-report-empty",text:"The replay did not produce any stats frames."}));return}const i=zo(t).filter(W9),s=G9(i),a=_C(),r=te("main",{className:"stats-report"});r.append(Py()),r.append(c7(a,n,e)),a==="goals"?r.append(s7(e,t)):a==="boost"?r.append(a7(t,i)):a==="territory"?r.append(o7(t)):a==="involvement"?r.append(l7(t,i)):a==="dump"?r.append(Z9(s,t)):r.append(J9(e,t,i)),n.replaceChildren(r)}function Jw(n){return{...n,statsFrameLookup:n.statsFrameLookup??OE(n.statsTimeline)}}function bc(n,e){const t=te("main",{className:"stats-report"});t.append(Py(e)),t.append(te("p",{className:"stats-report-status",text:e})),n.replaceChildren(t)}async function gC(n,e,t,i){bc(n,`Loading ${t}...`);const s=await Cf(e,{onProgress(a){bc(n,jo(a))}});Uh(n,{fileName:t,replayUrl:i,statsTimeline:s.statsTimeline,statsFrameLookup:s.statsFrameLookup})}async function u7(n,e){try{await gC(n,new Uint8Array(await e.arrayBuffer()),e.name,null)}catch(t){bc(n,t instanceof Error?t.message:String(t))}}async function d7(n,e){try{bc(n,`Fetching ${e}...`);const t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch replay: ${t.status} ${t.statusText}`);const i=new URL(e,window.location.href).pathname,s=decodeURIComponent(i.split("/").pop()||"remote replay");await gC(n,new Uint8Array(await t.arrayBuffer()),s,t.url?new URL(t.url):new URL(e,window.location.href))}catch(t){bc(n,t instanceof Error?t.message:String(t))}}function h7(n,e={}){if(Ld=n,vc=e,e.initialData)Uh(n,Jw(e.initialData));else{const i=te("main",{className:"stats-report"});i.append(Py()),i.append(te("section",{className:"stats-report-empty",text:"Load a replay to generate the stats report."})),n.replaceChildren(i)}const t=new URL(window.location.href).searchParams.get("replayUrl");return!e.initialData&&t&&d7(n,t),{root:n,render(i){Uh(n,Jw(i))},destroy(){Ld===n&&(Ld=null,vc={}),n.replaceChildren()}}}const od="replay-review-document",Qw="replay-review-root";function _i(n,e={}){const t=document.createElement(n);return e.className&&(t.className=e.className),e.id&&(t.id=e.id),e.text!==void 0&&(t.textContent=e.text),t}function yC(n,e={}){let t=null;const i=async()=>n instanceof Uint8Array?n:await n(),s=a=>(t||(t=i().then(r=>Cf(r,{reportEveryNFrames:100,onProgress:a}))),t);return{replayName:e.replayName,replayUrl:e.replayUrl??null,async getStatsTimeline(a){return(await s(a)).statsTimeline},getReplayBundle:s}}function f7(n=window.location){const e=K1(n.search,n.href);return e?yC(async()=>{const t=await fetch(e.url,e.fetchInit);if(!t.ok){const i=t.statusText?` ${t.statusText}`:"";throw new Error(`Failed to fetch replay: ${t.status}${i}`)}return new Uint8Array(await t.arrayBuffer())},{replayName:e.name,replayUrl:e.url}):null}function p7(n){return n||(new URL(window.location.href).searchParams.get("mode")==="viewer"?"viewer":"report")}function m7(n){const e=new URL(window.location.href);n==="report"?e.searchParams.delete("mode"):e.searchParams.set("mode",n),window.history.replaceState(null,"",e)}function _7(n,e={}){document.documentElement.classList.add(od),document.body.classList.add(od),n.classList.add(Qw);let t=e.provider??null,i=p7(e.initialMode),s=null,a=null,r=null,o=null,l=null,c=!1;const u=_i("main",{className:"replay-review-shell"}),d=_i("div",{className:"replay-review-toolbar"}),h=_i("div",{className:"replay-review-status"}),f=_i("button",{text:"Stats"}),p=_i("button",{text:"Viewer"}),g=_i("label",{className:"replay-review-file",text:"Load replay"}),_=_i("input"),m=_i("section",{className:"replay-review-pane"}),v=_i("section",{className:"replay-review-pane"});_.type="file",_.accept=".replay",g.append(_),d.append(h,g,f,p),u.append(d,m,v),n.replaceChildren(u);const y=L=>{h.textContent=L},b=L=>{y(jo(L))},S=()=>{s?.destroy(),s=null,a?.destroy(),a=null,r=null,o=null,l=null},x=()=>t?.getReplayBundle?(o||(o=t.getReplayBundle(b)),o):null,M=()=>t?(r||(r=t.getStatsTimeline?t.getStatsTimeline(b):x()?.then(L=>L.statsTimeline)??null),r):null,C=()=>{m.replaceChildren(_i("section",{className:"replay-review-empty",text:"Load a replay to review stats and playback."}))},w=async()=>{if(s)return;const L=M(),O=x();if(!L&&!O){C(),y("No replay loaded");return}m.replaceChildren(_i("section",{className:"replay-review-empty",text:"Loading stats..."}));const D=await O,U=D?.statsTimeline??(L?await L:null);if(!U){C(),y("No replay loaded");return}const F={fileName:t?.replayName??"replay",replayUrl:t?.replayUrl??null,statsTimeline:U,statsFrameLookup:D?.statsFrameLookup};c||(s=h7(m,{initialData:F,showStandaloneActions:!1,onWatchGoal(W){l=W.config,a?.destroy(),a=null,i="viewer",R()}}),y(`Loaded ${F.fileName}`))},E=async()=>{if(a)return;const L=x();if(!L){v.replaceChildren(_i("section",{className:"replay-review-empty",text:"Replay playback is not available for this data source."})),y("Viewer unavailable");return}v.replaceChildren(_i("section",{className:"replay-review-empty",text:"Loading viewer..."}));const O=await L;c||(a=D9(v,{initialBundle:O,initialConfig:l,initialReplayName:t?.replayName,loadFromLocation:!1}),l=null,y(`Loaded ${t?.replayName??"replay"}`))},R=()=>{f.dataset.active=String(i==="report"),p.dataset.active=String(i==="viewer"),m.hidden=i!=="report",v.hidden=i!=="viewer",m7(i),(i==="report"?w():E()).catch(L=>{console.error("Failed to render replay review mode:",L),y(L instanceof Error?L.message:"Failed to load replay review")})};return f.addEventListener("click",()=>{i="report",R()}),p.addEventListener("click",()=>{i="viewer",R()}),_.addEventListener("change",()=>{const L=_.files?.[0];L&&(t=yC(async()=>new Uint8Array(await L.arrayBuffer()),{replayName:L.name,replayUrl:null}),S(),R())}),R(),{root:n,setMode(L){i=L,R()},setProvider(L,O={}){t=L,O.mode&&(i=O.mode),S(),R()},destroy(){c=!0,S(),n.classList.remove(Qw),document.documentElement.classList.remove(od),document.body.classList.remove(od),n.replaceChildren()}}}const vC=document.querySelector("#app");if(!(vC instanceof HTMLElement))throw new Error("Missing #app mount element");let bC=null;try{bC=f7(window.location)}catch(n){console.error("Invalid replay URL:",n)}_7(vC,{provider:bC}); + `,this.chartCanvas=this.mustElement("#shot-chart-canvas"),this.shotList=this.mustElement("#shot-list"),this.summary=this.mustElement("#shot-visualization-summary"),this.details=this.mustElement("#shot-details"),this.sceneRoot=this.mustElement("#shot-demo-scene"),this.emptyState=this.mustElement("#shot-visualization-empty"),this.chartCanvas.addEventListener("click",t=>this.handleChartClick(t))}chartCanvas;shotList;summary;details;sceneRoot;emptyState;renderer=null;scene=null;camera=null;resizeObserver=null;selectedShotId=null;cachedReplay=null;cachedShots=[];lastShotsSignature="";lastListSelectionKey=null;lastSelectedShotKey=null;shotButtons=new Map;destroy(){this.resizeObserver?.disconnect(),this.renderer?.dispose(),this.renderer=null,this.scene=null,this.camera=null}render(e=this.options.getReplayPlayer()?.getState()??null){const t=this.shotEvents(),i=e?.currentTime??null;this.findSelectedShot(t)||(this.selectedShotId=t[0]?this.shotKey(t[0],0):null);const s=this.findSelectedShot(t),a=s?.key??null,r=this.shotsSignature(t),o=r!==this.lastShotsSignature;this.emptyState.hidden=t.length>0,o&&(this.summary.textContent=this.summaryText(t)),o||a!==this.lastListSelectionKey?(this.renderShotList(t,i,a),this.lastListSelectionKey=a):this.updateShotListActiveState(t,i),this.renderChart(t,i),(o||a!==this.lastSelectedShotKey)&&(this.renderSelectedShot(s?.shot??null),this.lastSelectedShotKey=a),this.lastShotsSignature=r}shotEvents(){const e=this.options.getReplayPlayer()?.replay;return e?e===this.cachedReplay?this.cachedShots:(this.cachedReplay=e,this.cachedShots=e.timelineEvents.filter(q9),this.cachedShots):(this.cachedReplay=null,this.cachedShots=[],[])}summaryText(e){if(e.length===0)return"No shots";const t=e.filter(a=>a.shot.resulting_save).length,i=e.map(a=>a.shot.ball_speed).filter(a=>Number.isFinite(a)),s=i.length===0?null:i.reduce((a,r)=>a+r,0)/i.length;return`${e.length} shots | ${t} saved | avg ${od(s)}`}renderShotList(e,t,i){this.shotButtons.clear(),this.shotList.replaceChildren(...e.map((s,a)=>{const r=this.shotKey(s,a),o=document.createElement("button");o.type="button",o.className="shot-list-item",o.dataset.selected=String(r===i),o.dataset.active=String(Wm(s,t)),o.addEventListener("click",()=>{this.selectedShotId=r,this.options.cueTimelineEvent(s),this.render()});const l=document.createElement("span");l.className="shot-list-title",l.textContent=s.playerName??s.playerId??`Shot ${a+1}`;const c=document.createElement("span");return c.className="shot-list-meta",c.textContent=`${Hw(s.time)} | ${od(s.shot.ball_speed)} | ${s.shot.resulting_save?"saved":"unsaved"}`,o.append(l,c),this.shotButtons.set(r,o),o}))}updateShotListActiveState(e,t){e.forEach((i,s)=>{const a=this.shotButtons.get(this.shotKey(i,s));a&&(a.dataset.active=String(Wm(i,t)))})}renderChart(e,t){const i=this.chartCanvas.getContext("2d");if(!i)return;const s=window.devicePixelRatio||1,a=this.chartCanvas.getBoundingClientRect(),r=Math.max(320,Math.round(a.width*s)),o=Math.max(220,Math.round(a.height*s));(this.chartCanvas.width!==r||this.chartCanvas.height!==o)&&(this.chartCanvas.width=r,this.chartCanvas.height=o),i.setTransform(s,0,0,s,0,0);const l=r/s,c=o/s;i.clearRect(0,0,l,c),Y9(i,l,c),e.forEach((u,d)=>{const h=u.shot.shot_touch_position??u.shot.ball_position,f=Dh(h,l,c),p=!!u.shot.resulting_save,g=Wm(u,t),_=this.shotKey(u,d)===this.selectedShotId,m=_?6:g?5:4;i.beginPath(),i.arc(f.x,f.y,m,0,Math.PI*2),i.fillStyle=p?"#f2c14e":"#62d2a2",i.fill(),i.lineWidth=_?2.5:1.25,i.strokeStyle=_?"#f8fafc":g?"#e11d48":"rgba(4, 12, 20, 0.85)",i.stroke()})}renderSelectedShot(e){if(!e){this.details.replaceChildren(),this.clearThreeScene();return}this.details.replaceChildren(Al("Player",e.playerName??e.playerId??"--"),Al("Speed",od(e.shot.ball_speed)),Al("Toward goal",od(e.shot.ball_speed_toward_goal)),Al("Touch",Z9(e.shot.shot_touch_position??e.shot.ball_position)),Al("Save",e.shot.resulting_save?Hw(e.shot.resulting_save.time):"--")),this.renderThreeScene(e)}renderThreeScene(e){const t=this.ensureRenderer(),i=this.scene,s=this.camera;i.clear(),i.add(new Dc(16777215,1.2));const a=new jo(16777215,1.7);a.position.set(18,28,22),i.add(a);const r=new Se(new Nn(rg*2*ns,wr*2*ns),new je({color:1520422,side:ut}));r.rotation.x=-Math.PI/2,i.add(r);const o=new Pt({color:14280674,transparent:!0,opacity:.55});i.add(new Fn(new yf(r.geometry),o)),i.add(Bw(!0)),i.add(Bw(!1));const l=zw(e.shot.shot_touch_position??e.shot.ball_position),c=zw(e.shot.target_goal_position),u=e.shot.ball_velocity,d=u?l.clone().add(j9(u).normalize().multiplyScalar(22)):c.clone(),h=new Ng([l,l.clone().lerp(d,.45).setY(Math.max(l.y,d.y)+2.8),d]),f=new $e().setFromPoints(h.getPoints(36));i.add(new On(f,new Pt({color:e.shot.resulting_save?15909198:6476450,linewidth:2})));const p=new Se(new vn(.9,24,16),new kn({color:16317180,roughness:.36}));p.position.copy(l),i.add(p);const g=new Se(new oi(1.05,1.45,32),new je({color:8892372,side:ut}));g.position.copy(c),g.rotation.y=Math.PI/2,i.add(g),s.position.set(0,54,72),s.lookAt(0,0,0),t.render(i,s)}ensureRenderer(){if(this.renderer&&this.scene&&this.camera)return this.resizeThreeScene(),this.renderer;const e=new ay({antialias:!0,alpha:!0,preserveDrawingBuffer:!0});return e.setPixelRatio(window.devicePixelRatio||1),this.sceneRoot.replaceChildren(e.domElement),this.renderer=e,this.scene=new Ac,this.scene.background=new de(463132),this.camera=new Qt(42,1,.1,500),this.resizeObserver=new ResizeObserver(()=>{this.resizeThreeScene();const t=this.shotEvents().find(i=>i.id===this.selectedShotId)??null;t&&this.renderThreeScene(t)}),this.resizeObserver.observe(this.sceneRoot),this.resizeThreeScene(),e}resizeThreeScene(){if(!this.renderer||!this.camera)return;const e=this.sceneRoot.getBoundingClientRect(),t=Math.max(240,Math.round(e.width)),i=Math.max(170,Math.round(e.height));this.camera.aspect=t/i,this.camera.updateProjectionMatrix(),this.renderer.setSize(t,i,!1)}clearThreeScene(){this.sceneRoot.replaceChildren(),this.renderer?.dispose(),this.renderer=null,this.scene=null,this.camera=null}handleChartClick(e){const t=this.shotEvents(),i=this.chartCanvas.getBoundingClientRect(),s={x:e.clientX-i.left,y:e.clientY-i.top};let a=null,r=Number.POSITIVE_INFINITY;for(const o of t){const l=Dh(o.shot.shot_touch_position??o.shot.ball_position,i.width,i.height),c=Math.hypot(l.x-s.x,l.y-s.y);c`${this.shotKey(t,i)}:${t.time}:${t.shot.ball_speed}`).join("|")}}function q9(n){return n.kind==="shot"&&!!n.shot}function Wm(n,e){return e!==null&&Math.abs(e-n.time)<1.5}function Y9(n,e,t){n.fillStyle="#0f2b24",n.fillRect(0,0,e,t),n.strokeStyle="rgba(226, 241, 236, 0.74)",n.lineWidth=1.2,n.strokeRect(18,18,e-36,t-36),n.beginPath(),n.moveTo(18,t/2),n.lineTo(e-18,t/2),n.stroke(),n.beginPath(),n.arc(e/2,t/2,34,0,Math.PI*2),n.stroke();const s=Dh({x:0,y:-wr},e,t),a=Dh({x:0,y:wr},e,t);n.fillStyle="#4fa3ff",n.fillRect(s.x-28,s.y-4,56,8),n.fillStyle="#ff8a4c",n.fillRect(a.x-28,a.y-4,56,8)}function Dh(n,e,t){const s=e-36,a=t-36;return{x:18+(n.x+rg)/(rg*2)*s,y:18+(1-(n.y+wr)/(wr*2))*a}}function Bw(n){const e=new Et,t=new Pt({color:n?16747084:5219327}),i=(n?wr:-wr)*ns,s=W9*ns,a=X9*ns,r=[new T(-s,0,i),new T(-s,a,i),new T(s,a,i),new T(s,0,i)];return e.add(new On(new $e().setFromPoints(r),t)),e}function zw(n){return new T(n.x*ns,n.z*ns,n.y*ns)}function j9(n){return new T(n.x*ns,n.z*ns,n.y*ns)}function Al(n,e){const t=document.createElement("div"),i=document.createElement("dt");i.textContent=n;const s=document.createElement("dd");return s.textContent=e,t.append(i,s),t}function Hw(n){return Number.isFinite(n)?`${n.toFixed(2)}s`:"--"}function od(n){return Number.isFinite(n)?`${Math.round(n)} uu/s`:"--"}function Z9(n){return n?`${Math.round(n.x)}, ${Math.round(n.y)}, ${Math.round(n.z)}`:"--"}const J9=4,Q9=100;let at=null,Py=null,Oh=null,Co=null,Ao=null,Fh=null,Vw=0,Za=null;const Hf=I1({refreshTimelineRanges(){Hh()},rerenderCurrentState(){at&&at.setBoostPickupAnimationEnabled(at.getState().boostPickupAnimationEnabled)},requestConfigSync(){_n()}}),Dd=VW({rerenderCurrentState(){if(!at)return;const n=at.getState();Nc(n.frameIndex)},refreshTimelineRanges(){Hh()},requestConfigSync(){_n()}},{boostPickupFilters:Hf}),gn=d9({modules:Dd,boostPickupFilters:Hf,getContext:Po,getReplayPlayer:()=>at,getTimelineOverlay:()=>Py,getEventTimelineSources:Iy,withTimelineEventSeekTimes:uC,renderModuleSummary:or,renderModuleSettings:lr,renderStatsWindows(){at&&Nc(at.getState().frameIndex)},renderTimelineEventCount:fo,requestConfigSync:_n}),Bl=V9({goalWatchLeadSeconds:J9,getReplayPlayer:()=>at,getCameraControlsController:()=>Xi,getMechanicsReviewController:()=>Ki,getSkipPostGoalTransitions:()=>Ja,getSkipKickoffs:()=>Qa,syncBoostPadOverlayPlugin:cC,setupActiveModules:zh,renderModuleSummary:or,renderModuleSettings:lr,renderStatsWindows(n){Nc(n)},scheduleConfigUrlUpdate:_n}),Ei=$9({getFloatingWindowController:()=>pa,getLauncherMenu:()=>cg,getLauncherToggle:()=>lg,getFileInput:()=>Nh});let zl=null,Nh,aC,og,Gw,lg,cg,$w,Ww,Xw,Kw,qw,Yw,Xm,Km,qm,Ym,ld,cd,jw,Zw,Jw,Qw,la,rC,oC,ug,Ja,ho=null,Qa,Hl,Vl,ud=null,dg=Go(null),Xi=null,Gl=null,eS=null,Od=null,Ro=null,xc=null,wc=null,Uh=null,Ki=null,pa=null,hg=null,Bh=null,Fd=null,da=null,fg=null,Os=null;function e7(n){return gn.getActiveCapabilityIds(n)}function t7(){}function Po(){return!at||!Co||!Ao?null:{player:at,replay:at.replay,statsTimeline:Co,statsFrameLookup:Ao,fieldScale:1}}function zh(){gn.setupActiveModules()}function lC(){gn.teardownActiveModules()}function tS(n,e,t){gn.toggleCapability(n,e,t)}function n7(){gn.clearTimelineEventSources()}function i7(){gn.clearTimelineRangeSources()}function s7(){gn.clearStandalonePlugins()}function cC(){gn.syncBoostPadOverlayPlugin()}function nS(){gn.syncTimelineEvents()}function Hh(){gn.syncTimelineRanges()}function fo(){const n=Po();if(!n){ug.textContent="--";return}ug.textContent=`${a7(n)}`}function a7(n){return wc?.countVisibleSources(n)??0}function ae(n,e){const t=n.querySelector(e);if(!(t instanceof HTMLElement))throw new Error(`Missing element for selector: ${e}`);return t}function r7(n){if(!pa)throw new Error("Floating windows are not initialized.");return pa.readPlacement(n)}function o7(n,e){pa?.applyPlacement(n,e)}function Nc(n=at?.getState().frameIndex??0,e={}){Ro?.render(n,e)}function l7(n){Ro?.create(n)}function c7(){Ro?.clear()}function _n(){da?.scheduleConfigUrlUpdate()}function u7(n){da?.applyConfigToStaticControls(n)}function uC(n){return n.map(e=>({...e,seekTime:cy(e)}))}function or(){Uh?.renderSummary()}function dC(){wc?.render()}function Iy(n){return wc?.getSources(n)??[]}function d7(){const n=Po();return w8(n,Iy(n))}function Ly(){xc?.render()}function ky(n){const e=zl?.querySelector(`[data-window-id="${n}"]`);return!!(e&&!e.hidden)}function Dy(n,e={}){!e.forceScroll&&!ky("event-playlist")||xc?.syncTimeline(n,e)}function hC(){xc?.reset()}function h7(n){const e=M9(n);e&&(gn.activateMechanicTimelineKind(e),dC())}function f7(n){return Ki?.enforceClipBoundary(n)??!1}function lr(){Uh?.renderSettings()}function Oy(n=at?.getState().frameIndex??0){hg?.render(n)}function fC(n=at?.getState()??null){ky("shot-visualization")&&Fd?.render(n)}function p7(n){if(Ei.toggleWindow(n),!!ky(n)){if(n==="event-playlist"){Ly();const e=at?.getState();e&&Dy(e,{forceScroll:!0})}n==="shot-visualization"&&fC(at?.getState()??null)}}function m7(n){Bh?.setTransportEnabled(n,at?.getState())}function pC(n=Oh?.getStatus()??null){Gl?.sync(n),Od?.sync()}function _7(n){if(f7(n))return;const e=performance.now();n.playing&&e-Vwy6(n,e=>{la.textContent=Qo(e),ho?.update(e)})))}async function pg(n,e){await I6(n,e,{elements:{fileInput:Nh,viewport:aC,emptyState:og,statusReadout:la,playersReadout:rC,framesReadout:oC,skipPostGoalTransitions:Ja,skipKickoffs:Qa,hitboxWireframes:Hl,hitboxOnlyMode:Vl},getReplayLoadModal:()=>ho,getReplayPlayer:()=>at,setReplayPlayer(t){at=t,Za?.syncSource()},getUnsubscribe:()=>Fh,setUnsubscribe(t){Fh=t},setCanvasRecorder(t){Oh=t},setLoadedReplayName(t){fg=t},setTimelineOverlay(t){Py=t},setStatsTimeline(t){Co=t,Za?.syncSource()},setStatsFrameLookup(t){Ao=t},setStatRegistry(t){dg=t},getInitialConfig:()=>Os,setApplyingConfig(t){da?.setApplyingConfig(t)},getReplayTimelineEvents(t){return lG(t,gn.getActiveTimelineEventSourceIds())},withTimelineEventSeekTimes:uC,includeBoostPickupAnimationPickup:g7,syncRecordingWindow:pC,setTransportEnabled:m7,teardownActiveModules:lC,clearTimelineEventSources:n7,clearTimelineRangeSources:i7,clearStandalonePlugins:s7,clearRenderCaches:t7,resetEventPlaylistWindow:hC,renderModuleSummary:or,renderScoreboard:Oy,renderTimelineEventCount:fo,renderMechanicsTimelineControls:dC,renderEventPlaylistWindow:Ly,renderModuleSettings:lr,syncBoostPadOverlayPlugin:cC,setupActiveModules:zh,renderSnapshot:_7,applyConfigToReplayPlayer:Bl.applyConfigToReplayPlayer,renderStatsWindows:Nc,syncEventPlaylistTimeline:Dy,getCameraControlsController:()=>Xi})}function y7(n,e={}){ud?.(),n.innerHTML=X3(),zl=n,ho=dV(n),pa=f6({getRoot:()=>zl??document,requestConfigSync:_n}),Nh=ae(n,"#replay-file"),aC=ae(n,"#viewport"),og=ae(n,"#empty-state"),Gw=ae(n,"#empty-load-replay"),lg=ae(n,"#launcher-toggle"),cg=ae(n,"#launcher-menu"),$w=ae(n,"#load-replay-action"),Ww=ae(n,"#floating-window-layer"),hg=V6({body:ae(n,"#scoreboard-window-body"),getReplayPlayer:()=>at,getStatsFrameLookup:()=>Ao});const t=ae(n,"#mechanics-timeline-window-body");wc=C8({body:t,modules:Dd,getContext:Po,getActiveTimelineEventSourceIds:()=>gn.getActiveTimelineEventSourceIds(),getActiveMechanicTimelineKinds:()=>gn.getActiveMechanicTimelineKinds(),toggleEventSource(d,h){tS(d,"events",h)},setMechanicTimelineKind(d,h){gn.setMechanicTimelineKind(d,h)},setupActiveModules:zh,syncTimelineEvents:nS,syncTimelineRanges:Hh,renderModuleSummary:or,renderModuleSettings:lr,renderTimelineEventCount:fo,requestConfigSync:_n}),Xw=ae(n,"#event-playlist-window-body"),xc=m6({body:Xw,getReplayPlayer:()=>at,getSources:d7,cueTimelineEvent:Bl.cueTimelineEvent,formatTime:Ai}),Fd=new K9({body:ae(n,"#shot-visualization-window-body"),getReplayPlayer:()=>at,cueTimelineEvent:Bl.cueTimelineEvent}),Kw=ae(n,"#replay-loading-summary"),qw=ae(n,"#replay-loading-active"),Yw=ae(n,"#replay-loading-list");const i=A9({elements:{reviewSummary:ae(n,"#mechanics-review-replay-load-summary"),loadingSummary:Kw,loadingActive:qw,loadingList:Yw},isActiveReview(d){return Ki?.review===d},onActiveLoadProgress(d){la.textContent=Qo(d),ho?.update(d)}});Ki=I9({elements:{file:ae(n,"#mechanics-review-file"),url:ae(n,"#mechanics-review-url"),loadUrl:ae(n,"#mechanics-review-load-url"),status:ae(n,"#mechanics-review-status"),index:ae(n,"#mechanics-review-index"),title:ae(n,"#mechanics-review-title"),mechanic:ae(n,"#mechanics-review-mechanic"),player:ae(n,"#mechanics-review-player"),clip:ae(n,"#mechanics-review-clip"),event:ae(n,"#mechanics-review-event"),reason:ae(n,"#mechanics-review-reason"),previous:ae(n,"#mechanics-review-prev"),replay:ae(n,"#mechanics-review-replay"),next:ae(n,"#mechanics-review-next"),confirm:ae(n,"#mechanics-review-confirm"),reject:ae(n,"#mechanics-review-reject"),uncertain:ae(n,"#mechanics-review-uncertain"),count:ae(n,"#mechanics-review-count"),list:ae(n,"#mechanics-review-list")},replayLoads:i,getReplayPlayer:()=>at,resetReplayTransitionControls(){Ja.checked=!1,Qa.checked=!1},activateTimelineSource:h7,loadReplayBundleForDisplay:pg,applyClipPerspective(d){Xi?.followPlayerWithReplayCamera(d.playerId,{ballCam:d.ballCam,usePlayerCameraSettings:d.usePlayerCameraSettings})},showReplayLoadingWindow(){Ei.showWindow("replay-loading")}});const s=ae(n,"#boost-pickup-filters-window-body"),a=ae(n,"#touch-controls-window-body");Xm=ae(n,"#stats-window-layer"),Ro=t8({layer:Xm,getReplayPlayer:()=>at,getStatsTimeline:()=>Co,getStatsFrameLookup:()=>Ao,getStatRegistry:()=>dg,readWindowPlacement:r7,applyWindowPlacement:o7,bringWindowToFront:Ei.bringWindowToFront,setLauncherOpen:Ei.setLauncherOpen,requestConfigSync:_n,watchGoalReplay:Bl.watchGoalReplay,cueGoalReplay:Bl.cueGoalReplay}),Km=ae(n,"#toggle-playback"),qm=ae(n,"#previous-frame"),Ym=ae(n,"#next-frame"),ld=ae(n,"#playback-rate"),Xi=fV({elements:{attachedPlayer:ae(n,"#attached-player"),cameraViewFreeButton:ae(n,"#camera-view-free"),cameraViewFollowButton:ae(n,"#camera-view-follow"),cameraViewAutoPossession:ae(n,"#camera-view-auto-possession"),cameraViewOverheadButton:ae(n,"#camera-view-overhead"),cameraViewSideButton:ae(n,"#camera-view-side"),usePlayerCameraSettings:ae(n,"#use-player-camera-settings"),cameraSettingsControls:ae(n,"#camera-settings-controls"),customCameraFov:ae(n,"#custom-camera-fov"),customCameraHeight:ae(n,"#custom-camera-height"),customCameraPitch:ae(n,"#custom-camera-pitch"),customCameraDistance:ae(n,"#custom-camera-distance"),customCameraStiffness:ae(n,"#custom-camera-stiffness"),customCameraSwivelSpeed:ae(n,"#custom-camera-swivel-speed"),customCameraTransitionSpeed:ae(n,"#custom-camera-transition-speed"),customCameraFovReadout:ae(n,"#custom-camera-fov-readout"),customCameraHeightReadout:ae(n,"#custom-camera-height-readout"),customCameraPitchReadout:ae(n,"#custom-camera-pitch-readout"),customCameraDistanceReadout:ae(n,"#custom-camera-distance-readout"),customCameraStiffnessReadout:ae(n,"#custom-camera-stiffness-readout"),customCameraSwivelSpeedReadout:ae(n,"#custom-camera-swivel-speed-readout"),customCameraTransitionSpeedReadout:ae(n,"#custom-camera-transition-speed-readout"),ballCamOffButton:ae(n,"#ball-cam-off"),ballCamOnButton:ae(n,"#ball-cam-on"),ballCamPlayerButton:ae(n,"#ball-cam-player"),nameplateLift:ae(n,"#custom-nameplate-lift"),nameplateLiftReadout:ae(n,"#custom-nameplate-lift-readout"),cameraProfileReadout:ae(n,"#camera-profile-readout"),cameraFovReadout:ae(n,"#camera-fov-readout"),cameraHeightReadout:ae(n,"#camera-height-readout"),cameraPitchReadout:ae(n,"#camera-pitch-readout"),cameraBaseDistanceReadout:ae(n,"#camera-base-distance-readout"),cameraStiffnessReadout:ae(n,"#camera-stiffness-readout")},getReplayPlayer:()=>at,requestConfigSync:_n,onAutoPossessionChange(d){Za?.syncSource(),d&&Za?.syncCurrentFrame()}}),Za=zV({getReplayPlayer:()=>at,getStatsTimeline:()=>Co,getCameraControlsController:()=>Xi}),D1(ae(n,"#touch-color-legend-body"),["team"]),Uh=I8({elements:{summary:ae(n,"#module-summary"),settings:ae(n,"#module-settings"),boostPickupFilters:s,touchControls:a},modules:Dd,boostPickupFilters:Hf,getContext:Po,getTimelineSources:()=>Iy(Po()),getActiveModules:()=>gn.getActiveModules(),getActiveCapabilityIds:e7,getBoostPickupAnimationEnabled:()=>at?.getState().boostPickupAnimationEnabled??!1,toggleCapability:tS,toggleBoostPickupAnimation(){const d=!(at?.getState().boostPickupAnimationEnabled??!1);at?.setBoostPickupAnimationEnabled(d),zh(),or(),lr(),_n()},syncTimelineEvents:nS,syncTimelineRanges:Hh,renderTimelineEventCount:fo,requestConfigSync:_n}),jw=ae(n,"#time-readout"),Zw=ae(n,"#frame-readout"),Jw=ae(n,"#duration-readout"),Qw=ae(n,"#playback-status-readout"),la=ae(n,"#status-readout"),rC=ae(n,"#players-readout"),oC=ae(n,"#frames-readout"),ug=ae(n,"#events-readout"),cd=ae(n,"#playback-rate-readout"),Ja=ae(n,"#skip-post-goal-transitions"),Qa=ae(n,"#skip-kickoffs"),Hl=ae(n,"#hitbox-wireframes"),Vl=ae(n,"#hitbox-only-mode"),Bh=$6({elements:{togglePlayback:Km,previousFrame:qm,nextFrame:Ym,playbackRate:ld,playbackRateReadout:cd,skipPostGoalTransitions:Ja,skipKickoffs:Qa,hitboxWireframes:Hl,hitboxOnlyMode:Vl,emptyState:og,timeReadout:jw,frameReadout:Zw,durationReadout:Jw,playbackStatusReadout:Qw},getFrameCount:()=>at?.replay.frameCount??0,getCameraControlsController:()=>Xi}),Gl=U6({elements:{fps:ae(n,"#recording-fps"),playbackRate:ae(n,"#recording-playback-rate"),start:ae(n,"#recording-start"),fullReplay:ae(n,"#recording-full-replay"),stop:ae(n,"#recording-stop"),download:ae(n,"#recording-download"),clear:ae(n,"#recording-clear"),status:ae(n,"#recording-status"),elapsed:ae(n,"#recording-elapsed"),size:ae(n,"#recording-size"),type:ae(n,"#recording-type")},getCanvasRecorder:()=>Oh,getReplayPlayer:()=>at,getLoadedReplayName:()=>fg,setStatus(d){la.textContent=d},requestConfigSync:_n}),eS=a9({elements:{mechanic:ae(n,"#missed-event-mechanic"),capture:ae(n,"#missed-event-capture"),list:ae(n,"#missed-event-list"),export:ae(n,"#missed-event-export"),upload:ae(n,"#missed-event-upload"),clear:ae(n,"#missed-event-clear"),status:ae(n,"#missed-event-status")},getReplayPlayer:()=>at,showWindow:()=>Ei.showWindow("missed-events")}),Od=c9({elements:{name:ae(n,"#training-pack-name"),creator:ae(n,"#training-pack-creator"),description:ae(n,"#training-pack-description"),difficulty:ae(n,"#training-pack-difficulty"),shooter:ae(n,"#training-pack-shooter"),timeLimit:ae(n,"#training-pack-time-limit"),capture:ae(n,"#training-pack-capture"),load:ae(n,"#training-pack-load"),loadInput:ae(n,"#training-pack-load-input"),newPack:ae(n,"#training-pack-new"),download:ae(n,"#training-pack-download"),shotList:ae(n,"#training-pack-shots"),status:ae(n,"#training-pack-status")},getReplayPlayer:()=>at}),da=G9({modules:Dd,playbackRate:ld,playbackRateReadout:cd,skipPostGoalTransitions:Ja,skipKickoffs:Qa,hitboxWireframes:Hl,hitboxOnlyMode:Vl,getReplayPlayer:()=>at,getCameraControlsController:()=>Xi,getRecordingWindowController:()=>Gl,getFloatingWindowController:()=>pa,getStatsWindowsController:()=>Ro,getActiveModulesRuntime:()=>gn,getInitialConfig:()=>Os,renderModuleSummary:or,renderModuleSettings:lr,renderTimelineEventCount:fo});const r=j1(window.location),o=Z8(window.location);let l=null;if(e.initialConfig!==void 0)Os=e.initialConfig;else{try{Os=j8(window.location)}catch(d){l=d,console.error("Invalid stats player config:",d),la.textContent=d instanceof Error?d.message:"Invalid stats player config",Os=null}o&&P6(r,Os,l)}const c=new AbortController;Ei.installWindowDragging(Ww,c.signal),Ei.installWindowDragging(Xm,c.signal);const u=()=>{c.abort(),Fh?.(),Fh=null,lC(),at?.destroy(),at=null,Oh=null,Py=null,Co=null,Ao=null,dg=Go(null),c7(),Ro=null,gn.reset(),ho?.destroy(),ho=null,hC(),wc=null,xc=null,Ki?.reset(),Ki=null,fg=null,Za?.reset(),Za=null,Xi=null,Gl=null,Od=null,Uh=null,hg=null,Bh=null,Fd?.destroy(),Fd=null,Os=null,da?.reset(),da=null,pa?.reset(),pa=null,zl===n&&(zl=null,n.replaceChildren()),ud===u&&(ud=null)};if(ud=u,Os){da?.setApplyingConfig(!0);try{u7(Os)}finally{da?.setApplyingConfig(!1)}}return W6({elements:{root:n,launcherToggle:lg,launcherMenu:cg,loadReplayAction:$w,emptyLoadReplay:Gw,fileInput:Nh,togglePlayback:Km,previousFrame:qm,nextFrame:Ym,playbackRate:ld,playbackRateReadout:cd,skipPostGoalTransitions:Ja,skipKickoffs:Qa,hitboxWireframes:Hl,hitboxOnlyMode:Vl},signal:c.signal,setLauncherOpen:Ei.setLauncherOpen,openReplayFilePicker:Ei.openReplayFilePicker,getElementWindowId:Ei.getElementWindowId,toggleWindow:p7,hideWindow:Ei.hideWindow,createStatsWindow:l7,async loadReplayFile(d){try{Ki?.clearCurrentClip({resetReplayId:!0,render:!0}),await iS(_6(d))}catch(h){console.error("Failed to load replay:",h),la.textContent=h instanceof Error?h.message:"Failed to load replay"}},togglePlayback(){at?.togglePlayback(),_n()},stepFrames(d){at?.stepFrames(d),_n()},setPlaybackRate(d){at?.setPlaybackRate(d),_n()},setSkipPostGoalTransitionsEnabled(d){at?.setSkipPostGoalTransitionsEnabled(d),_n()},setSkipKickoffsEnabled(d){at?.setSkipKickoffsEnabled(d),_n()},setHitboxWireframesEnabled(d){at?.setHitboxWireframesEnabled(d),_n()},setHitboxOnlyModeEnabled(d){at?.setHitboxOnlyModeEnabled(d),_n()}}),Ki?.installEventListeners(c.signal),Gl?.installEventListeners(c.signal),eS?.installEventListeners(c.signal),Od?.installEventListeners(c.signal),Xi?.installEventListeners(c.signal),q6({getReplayPlayer:()=>at,signal:c.signal}),window.addEventListener("message",d=>{if(d.origin!==window.location.origin)return;const h=d.data;!h||typeof h!="object"||h.source!=="rocket-sense"||h.type==="activateReviewItem"&&typeof h.index=="number"&&Number.isInteger(h.index)&&Ki?.activateItem(h.index)},{signal:c.signal}),or(),lr(),Oy(),Xi?.renderProfile(),Xi?.syncModeButtons(),pC(),fo(),Ki?.render(),Ly(),H9({signal:c.signal,location:window.location,statusReadout:la,initialBundle:e.initialBundle,initialReplayName:e.initialReplayName,loadFromLocation:e.loadFromLocation,loadReplay:iS,loadReplayBundleForDisplay:pg,getMechanicsReviewController:()=>Ki,showMechanicsReviewWindow(){Ei.showWindow("mechanics-review")}}),{root:n,destroy:u}}const In=["#58a6ff","#f39a37"],sS=["#58a6ff","#f39a37","#65d6ad","#d2a8ff","#ff7b72","#f2cc60","#79c0ff","#ffa657"],Rl={zero:"#ff7b72",low:"#f39a37",midLow:"#f2cc60",midHigh:"#65d6ad",high:"#58a6ff"},aS={big:"#f39a37",small:"#65d6ad"},mC=[{id:"overview",label:"Overview"},{id:"goals",label:"Goals"},{id:"boost",label:"Boost"},{id:"territory",label:"Possession & territory"},{id:"involvement",label:"Player involvement"},{id:"dump",label:"All stats"}],v7=[{statId:"player:core.score",kind:"bar",title:"Score by player"},{statId:"player:core.shots",kind:"bar",title:"Shots by player"},{statId:"player:touch.touch_count",kind:"bar",title:"Touches by player"},{statId:"team:core.shots",kind:"pie",title:"Shot share"},{statId:"team:possession.possession_time",kind:"pie",title:"Possession share"},{statId:"team:ball_half.offensive_pressure_time",kind:"bar",title:"Offensive pressure"}],b7=[{statId:"player:touch.touch_count",kind:"bar",title:"Touches"},{statId:"player:touch.control_touch_count",kind:"bar",title:"Control touches"},{statId:"player:touch.hard_hit_count",kind:"bar",title:"Hard hits"},{statId:"player:demo.demos_inflicted",kind:"bar",title:"Demos inflicted"},{statId:"player:fifty_fifty.wins",kind:"bar",title:"50/50 wins"},{statId:"player:powerslide.total_duration",kind:"bar",title:"Powerslide time"}];function te(n,e={}){const t=document.createElement(n);return e.className&&(t.className=e.className),e.id&&(t.id=e.id),e.text!==void 0&&(t.textContent=e.text),t}function _C(n,e,t){return e==="player"?n.name||`Player ${t+1}`:t===0?"Blue":"Orange"}function Vh(n){return n?Ct(n):null}function oo(n,e){const t=Vh(e);return t?n.players.find(i=>Vh(i.player_id)===t)?.name??t:"--"}function mg(n){return n===!0?"Blue":n===!1?"Orange":"--"}function gC(n,e){return e==="player"?n.players:[n.team_zero,n.team_one]}function yC(n){return n.is_team_0?In[0]:In[1]}function x7(n,e,t){return e==="player"?yC(n):In[t%In.length]}function w7(n,e){const t=n.frames.at(-1);return t?e.get(t.frame_number)??null:null}function S7(n,e){const t=n.read(e);return typeof t=="number"&&Number.isFinite(t)?t:null}function Sr(n){return n==null||!Number.isFinite(n)?"--":`${Number(n.toFixed(1))}s`}function T7(n){return n==null||!Number.isFinite(n)?"--":`${Number(n.toFixed(1))}%`}function Ri(n,e){return e>0?`${Sr(n)} (${T7(n/e*100)})`:"--"}function Nd(n){return n?`x ${Math.round(n.x)}, y ${Math.round(n.y)}, z ${Math.round(n.z)}`:"--"}function ts(n){return n==null||!Number.isFinite(n)?"--":`${Number(Ys(n).toFixed(0))}`}function nc(n){if(n==null||!Number.isFinite(n))return"--";const e=Math.max(0,n),t=Math.floor(e/60),i=e-t*60;return`${t}:${i.toFixed(1).padStart(4,"0")}`}function M7(n,e,t){if(!n||e==null||!Number.isFinite(e))return null;const i=Vh(t),s=new URL("../",window.location.href);return s.searchParams.set("replayUrl",n.href),Z1(s,vC(e,i)).href}function E7(n,e,t){if(e==null||!Number.isFinite(e))return null;const i=Vh(t);return{config:vC(e,i),href:M7(n,e,t),goalTime:e,playerId:i}}function vC(n,e){return{version:Lh,playback:{currentTime:Math.max(0,n-4),playing:!0,rate:1,skipPostGoalTransitions:!1,skipKickoffs:!1},camera:e?{mode:"follow",attachedPlayerId:e,ballCam:!0}:{mode:"free"},overlays:{timelineEvents:["core"],timelineRanges:[],mechanics:[],renderEffects:[],followedPlayerHud:!1,boostPads:!0,boostPickupAnimation:!1,hitboxWireframes:!1,hitboxOnlyMode:!1},recording:{},singletonWindows:[],statsWindows:[],moduleConfigs:{}}}function bC(n,e){return e>0?`${Number((Ys(n)/e*60).toFixed(1))}/min`:"--"}function C7(n){const e=new Map;for(const t of n){const i=`${t.scope}:${t.category}`,s=e.get(i);s?s.push(t):e.set(i,[t])}return new Map([...e].sort(([t],[i])=>t.localeCompare(i)))}function xC(n){const[e,t]=n.split(":"),i=(t??"").replace(/_/g," ").replace(/\b\w/g,s=>s.toUpperCase());return`${e==="player"?"Player":"Team"} ${i}`}function wC(n){return`stats-${n.replace(/[^a-z0-9]+/gi,"-").toLowerCase()}`}function A7(n){return n.path.slice(1).join(".")||n.label}function R7(n){return!n.path.includes("entries")}function Tn(n,e,t){const i=te("section",{className:"stats-report-summary-card"});return i.append(te("span",{text:n}),te("strong",{text:e})),t&&i.append(te("small",{text:t})),i}function P7(n,e){const t=te("section",{className:"stats-report-summary"}),i=e.time>0?Sr(e.time):"--";return t.append(Tn("Replay",n.fileName),Tn("Frames",n.statsTimeline.frames.length.toLocaleString()),Tn("Duration",i),Tn("Players",e.players.length.toLocaleString())),t}function tl(n,e){const t=te("section",{className:"stats-report-page-intro"});return t.append(te("h2",{text:n}),te("p",{text:e})),t}function I7(n,e,t){const i=e[0]?.scope??"player",s=gC(t,i),a=te("section",{className:"stats-report-section",id:wC(n)}),r=te("header");r.append(te("h2",{text:xC(n)}),te("span",{text:`${e.length} stats`}));const o=te("div",{className:"stats-report-table-wrap"}),l=te("table",{className:"stats-report-table"}),c=te("thead"),u=te("tr");u.append(te("th",{text:"Statistic"})),s.forEach((h,f)=>{u.append(te("th",{text:_C(h,i,f)}))}),c.append(u);const d=te("tbody");return e.forEach(h=>{const f=te("tr");f.append(te("td",{text:A7(h)})),s.forEach(p=>{f.append(te("td",{text:h.format(h.read(p))}))}),d.append(f)}),l.append(c,d),o.append(l),a.append(r,o),a}function Fy(n,e){return gC(e,n.scope).map((t,i)=>({label:_C(t,n.scope,i),value:S7(n,t)??0,color:x7(t,n.scope,i)})).filter(t=>t.value>0)}function ic(n,e){const t=Math.max(...n.map(s=>s.value),1),i=te("div",{className:"stats-report-bar-chart"});return n.forEach(s=>{const a=te("div",{className:"stats-report-bar-row"});a.style.setProperty("--bar-color",s.color),a.style.setProperty("--bar-width",`${Math.max(2,s.value/t*100)}%`),a.append(te("span",{className:"stats-report-bar-label",text:s.label}),te("span",{className:"stats-report-bar-track"}),te("strong",{text:s.formatted??e(s.value)})),i.append(a)}),i}function SC(n,e){const t=n.path.join(".");return n.category==="boost"&&(t.includes("amount_")||t.includes("overfill")||t.includes("boost_integral"))?ts(e):t.endsWith("_time")||t.startsWith("time_")||t.includes(".time_")||t.endsWith("_duration")||t==="active_game_time"||t==="tracked_time"?Sr(e):n.format(e)}function L7(n,e){return ic(Fy(n,e),t=>SC(n,t))}function k7(n){const e=n.reduce((i,s)=>i+s.value,0);if(e<=0)return"conic-gradient(rgba(255,255,255,0.12) 0 360deg)";let t=0;return`conic-gradient(${n.map(i=>{const s=t;return t+=i.value/e*360,`${i.color} ${s}deg ${t}deg`}).join(", ")})`}function Gh(n,e){const t=n.reduce((r,o)=>r+o.value,0),i=te("div",{className:"stats-report-pie-chart"}),s=te("div",{className:"stats-report-pie"});s.style.background=k7(n);const a=te("div",{className:"stats-report-pie-legend"});return n.forEach(r=>{const o=te("div");o.style.setProperty("--legend-color",r.color);const l=t>0?`${Math.round(r.value/t*100)}%`:"--";o.append(te("span",{text:r.label}),te("strong",{text:`${r.formatted??e(r.value)} (${l})`})),a.append(o)}),i.append(s,a),i}function D7(n,e){return Gh(Fy(n,e),t=>SC(n,t))}function TC(n,e="Territory share"){return ai(e,Gh([{label:"Blue half",value:n.team_zero.ball_half.defensive_half_time,color:In[0]},{label:"Neutral",value:n.team_zero.ball_half.neutral_time,color:"#65d6ad"},{label:"Orange half",value:n.team_zero.ball_half.offensive_half_time,color:In[1]}],Sr))}function ai(n,e,t){const i=te("section",{className:"stats-report-chart-card"});return i.append(te("h3",{text:n})),i.append(e),i}function MC(n,e,t){return Fy(e,t).length===0?null:ai(n.title,n.kind==="pie"?D7(e,t):L7(e,t))}function EC(n,e,t){const i=new Map(n.map(a=>[a.id,a])),s=te("section",{className:"stats-report-charts"});return t.forEach(a=>{const r=i.get(a.statId);if(!r)return;const o=MC(a,r,e);o&&s.append(o)}),s.childElementCount>0?s:null}function $o(n,e){const t=te("div",{className:"stats-report-stacked-chart"});return n.forEach(i=>{const s=i.segments.reduce((l,c)=>l+Math.max(0,c.value),0),a=te("div",{className:"stats-report-stacked-row"}),r=te("div",{className:"stats-report-stacked-track"});i.segments.forEach(l=>{const c=te("span");c.style.setProperty("--segment-color",l.color),c.style.setProperty("--segment-width",`${s>0?Math.max(1.5,l.value/s*100):0}%`),c.title=`${l.label}: ${e(l.value,s)}`,r.append(c)});const o=te("div",{className:"stats-report-stacked-legend"});i.segments.forEach(l=>{const c=te("span",{text:`${l.label}: ${e(l.value,s)}`});c.style.setProperty("--legend-color",l.color),o.append(c)}),a.append(te("strong",{text:i.label}),r,o),t.append(a)}),t}function Vf(n){const e=te("section",{className:"stats-report-metric-grid"});return e.append(...n),e}function cr(n,e,t){const i=[...n].sort((a,r)=>e(r)-e(a))[0],s=i?e(i):0;return Tn(i?.name??"--",t(s))}function O7(n,e){const t=te("div",{className:"stats-report-page"});t.append(tl("All stats dump","Everything emitted by the current stats timeline, including experimental mechanic counters and low-level breakdowns."));const i=te("nav",{className:"stats-report-jump-nav"});for(const a of n.keys()){const r=te("a",{text:xC(a)});r.setAttribute("href",`#${wC(a)}`),i.append(r)}t.append(i);const s=te("div",{className:"stats-report-grid"});for(const[a,r]of n)s.append(I7(a,r,e));return t.append(s),t}let Ud=null,Sc={};function F7(n,e,t){const i=te("div",{className:"stats-report-page"});i.append(P7(n,e)),i.append(tl("Featured stats","A shorter readout of stable scoreboard, touch, boost, possession, and pressure signals. The raw export remains available in All stats."));const s=`${e.team_zero.core.goals}-${e.team_one.core.goals}`;i.append(Vf([Tn("Final score",s,"Blue - Orange"),cr(e.players,r=>r.touch.touch_count,r=>`${r} touches`),cr(e.players,r=>r.boost.tracked_time>0?Ys(r.boost.boost_integral/r.boost.tracked_time):0,r=>`${Number(r.toFixed(0))} avg boost`),cr(e.players,r=>r.core.score,r=>`${r} score`)]));const a=EC(t,e,v7)??te("section",{className:"stats-report-charts"});return a.append(TC(e)),i.append(a),i}function N7(n){return[...n??[]].sort((e,t)=>e.kind.localeCompare(t.kind)||t.metadata.confidence-e.metadata.confidence)}function rS(n){const e=new Map;for(const t of n)e.set(t.kind,(e.get(t.kind)??0)+1);return[...e.entries()].sort(([t,i],[s,a])=>a-i||Dn(t).localeCompare(Dn(s))).map(([t,i],s)=>({label:Dn(t),value:i,color:sS[s%sS.length],formatted:i.toLocaleString()}))}function U7(n){const e=te("dl",{className:"stats-report-detail-list"});for(const t of n){const i=te("div",{className:"stats-report-detail-item"});i.append(te("dt",{text:t.label}),te("dd",{text:t.value})),e.append(i)}return e}function B7(n){const e=te("div",{className:"stats-report-goal-tags"});if(n.length===0)return e.append(te("span",{className:"stats-report-goal-tag stats-report-goal-tag-empty",text:"Unlabeled"})),e;for(const t of n){const i=t.metadata,s=g1(t),a=s?` - ${s}`:"";e.append(te("span",{className:"stats-report-goal-tag",text:`${Dn(t.kind)} ${Math.round(i.confidence*100)}%${a}`}))}return e}function z7(n,e){if(e.length===0)return null;const t=te("div",{className:"stats-report-goal-subsection"});t.append(te("h3",{text:"Player context"}));const i=te("div",{className:"stats-report-table-wrap"}),s=te("table",{className:"stats-report-table"}),a=te("thead"),r=te("tr");["Player","Team","Boost","Leadup avg","Leadup min","Role","Position"].forEach(l=>{r.append(te("th",{text:l}))}),a.append(r);const o=te("tbody");for(const l of e){const c=te("tr");c.append(te("td",{text:oo(n,l.player)}),te("td",{text:mg(l.is_team_0)}),te("td",{text:ts(l.boost_amount)}),te("td",{text:ts(l.average_boost_in_leadup)}),te("td",{text:ts(l.min_boost_in_leadup)}),te("td",{text:l.is_most_back?"Most back":"--"}),te("td",{text:Nd(l.position)})),o.append(c)}return s.append(a,o),i.append(s),t.append(i),t}function H7(n,e,t,i,s){const a=i?.scoring_team_is_team_0??null,r=i?.scorer??null,o=i?.time??null,l=i?.frame??null,c=E7(e,o,r),u=te("section",{className:"stats-report-goal-card"});a!==null&&(u.dataset.team=a?"blue":"orange");const d=te("header"),h=te("div",{className:"stats-report-goal-heading"});if(h.append(te("h2",{text:`Goal ${t+1}`}),te("span",{text:`${mg(a)} - ${oo(n,r)} - ${nc(o)}`})),d.append(h),c){if(Sc.onWatchGoal){const g=te("button",{className:"stats-report-goal-watch",text:"Watch"});g.type="button",g.addEventListener("click",()=>{Sc.onWatchGoal?.(c)}),d.append(g)}else if(c.href){const g=te("a",{className:"stats-report-goal-watch",text:"Watch"});g.setAttribute("href",c.href),g.setAttribute("target","_blank"),g.setAttribute("rel","noreferrer"),d.append(g)}}u.append(d),u.append(B7(s));const f=[{label:"Scoring team",value:mg(a)},{label:"Scorer",value:oo(n,r)},{label:"Time",value:nc(o)},{label:"Frame",value:l==null?"--":l.toLocaleString()},{label:"Scorer last touch",value:i?.scorer_last_touch?`${oo(n,i.scorer_last_touch.player)} at ${nc(i.scorer_last_touch.time)}`:"--"},{label:"Scoring most back",value:oo(n,i?.scoring_team_most_back_player)},{label:"Defending most back",value:oo(n,i?.defending_team_most_back_player)},{label:"Ball position",value:Nd(i?.ball_position)},{label:"Last touch ball",value:Nd(i?.scorer_last_touch?.ball_position)},{label:"Last touch player",value:Nd(i?.scorer_last_touch?.player_position)}];u.append(U7(f));const p=z7(n,i?.players??[]);return p&&u.append(p),u}function V7(n,e){const t=te("div",{className:"stats-report-page"});t.append(tl("Goal metadata","Goal-by-goal scorer, timing, context, tag confidence, and lead-up player state from the stats timeline event stream."));const i=[...be(n.statsTimeline,"goal_context")].sort((p,g)=>p.time-g.time),s=i.flatMap(p=>p.tags??[]),a=s.filter(sG),r=s.filter(aG),o=i.map((p,g)=>g),l=i.filter(p=>(p.tags??[]).length>0).length,c=rS(a),u=rS(r),d=c[0];if(t.append(Vf([Tn("Goals found",o.length.toLocaleString()),Tn("Tagged goals",l.toLocaleString()),Tn("Scorer goal tags",a.length.toLocaleString()),Tn("Assist goal tags",r.length.toLocaleString()),Tn("Top tag",d?`${d.label} (${d.value})`:"--")])),o.length===0)return t.append(te("section",{className:"stats-report-empty",text:"No goal metadata was emitted for this replay."})),t;const h=te("section",{className:"stats-report-charts"});h.append(ai("Scorer goal tags by type",c.length>0?ic(c,p=>p.toLocaleString()):te("p",{className:"stats-report-note",text:"No scorer goal tags emitted."})),ai("Assist goal tags by type",u.length>0?ic(u,p=>p.toLocaleString()):te("p",{className:"stats-report-note",text:"No assist goal tags emitted."})),ai("Goal timing",ic(o.map(p=>{const g=i[p]??null,_=g?.time??0,m=g?.scoring_team_is_team_0??!0;return{label:`Goal ${p+1}`,value:_,color:m?In[0]:In[1],formatted:nc(_)}}),nc))),t.append(h);const f=te("div",{className:"stats-report-goal-list"});for(const p of o)f.append(H7(e,n.replayUrl,p,i[p]??null,N7(i[p]?.tags)));return t.append(f),t}function G7(n,e){const t=te("div",{className:"stats-report-page"});t.append(tl("Boost economy","A focused view of boost usage, collection, pad mix, starvation, and waste. Values are shown in normal 0-100 boost units.")),t.append(Vf([cr(n.players,a=>a.boost.amount_used,a=>`${ts(a)} used`),cr(n.players,a=>a.boost.amount_stolen,a=>`${ts(a)} stolen`),cr(n.players,a=>a.boost.overfill_total,a=>`${ts(a)} overfill`),cr(n.players,a=>a.boost.time_zero_boost,a=>`${Sr(a)} at zero`)]));const i=te("section",{className:"stats-report-charts"});i.append(ai("Boost used per minute",ic(n.players.map((a,r)=>({label:a.name||`Player ${r+1}`,value:a.boost.tracked_time>0?Ys(a.boost.amount_used)/a.boost.tracked_time*60:0,color:yC(a),formatted:bC(a.boost.amount_used,a.boost.tracked_time)})),a=>`${Number(a.toFixed(1))}/min`)),ai("Pad collection mix",$o(n.players.map((a,r)=>({label:a.name||`Player ${r+1}`,segments:[{label:"Big",value:a.boost.amount_collected_big,color:aS.big},{label:"Small",value:a.boost.amount_collected_small,color:aS.small}]})),a=>ts(a))),ai("Boost tank time",$o(n.players.map((a,r)=>({label:a.name||`Player ${r+1}`,segments:[{label:"0",value:a.boost.time_zero_boost,color:Rl.zero},{label:"0-25",value:a.boost.time_boost_0_25,color:Rl.low},{label:"25-50",value:a.boost.time_boost_25_50,color:Rl.midLow},{label:"50-75",value:a.boost.time_boost_50_75,color:Rl.midHigh},{label:"75-100",value:a.boost.time_boost_75_100+a.boost.time_hundred_boost,color:Rl.high}]})),Ri)));const s=new Map(e.map(a=>[a.id,a]));for(const a of[{statId:"player:boost.amount_used",kind:"bar",title:"Total boost used"},{statId:"player:boost.overfill_total",kind:"bar",title:"Boost overfill"},{statId:"player:boost.amount_stolen",kind:"bar",title:"Stolen boost"}]){const r=s.get(a.statId),o=r?MC(a,r,n):null;o&&i.append(o)}return t.append(i),t.append($7(n)),t}function $7(n){const e=te("section",{className:"stats-report-section"}),t=te("header");t.append(te("h2",{text:"Boost scorecard"}),te("span",{text:"display units"}));const i=[{label:"Average boost",read(c){return c.boost.tracked_time>0?`${Number(Ys(c.boost.boost_integral/c.boost.tracked_time).toFixed(0))}`:"--"}},{label:"Used per minute",read(c){return bC(c.boost.amount_used,c.boost.tracked_time)}},{label:"Collected",read(c){return ts(c.boost.amount_collected)}},{label:"Stolen",read(c){return ts(c.boost.amount_stolen)}},{label:"Overfill",read(c){return ts(c.boost.overfill_total)}},{label:"Big pads",read(c){return`${c.boost.big_pads_collected}`}},{label:"Small pads",read(c){return`${c.boost.small_pads_collected}`}},{label:"Time at zero",read(c){return Ri(c.boost.time_zero_boost,c.boost.tracked_time)}}],s=te("div",{className:"stats-report-table-wrap"}),a=te("table",{className:"stats-report-table"}),r=te("thead"),o=te("tr");o.append(te("th",{text:"Metric"})),n.players.forEach((c,u)=>{o.append(te("th",{text:c.name||`Player ${u+1}`}))}),r.append(o);const l=te("tbody");return i.forEach(c=>{const u=te("tr");u.append(te("td",{text:c.label})),n.players.forEach(d=>{u.append(te("td",{text:c.read(d)}))}),l.append(u)}),a.append(r,l),s.append(a),e.append(t,s),e}function W7(n){const e=te("div",{className:"stats-report-page"});e.append(tl("Possession & territory","Team control, field-half pressure, and where each player spent time relative to the field and the ball."));const t=n.team_zero.possession.tracked_time,i=n.team_zero.ball_half.tracked_time,s=n.team_zero.ball_third.tracked_time;e.append(Vf([Tn("Blue possession",Ri(n.team_zero.possession.possession_time,t)),Tn("Orange possession",Ri(n.team_zero.possession.opponent_possession_time,t)),Tn("Blue pressure",Ri(n.team_zero.ball_half.offensive_half_time,i),"Time in Orange half"),Tn("Orange pressure",Ri(n.team_zero.ball_half.defensive_half_time,i),"Time in Blue half"),Tn("Blue final third",Ri(n.team_zero.ball_third.offensive_third_time,s),"Time in Orange third"),Tn("Orange final third",Ri(n.team_zero.ball_third.defensive_third_time,s),"Time in Blue third")]));const a=te("section",{className:"stats-report-charts"});return a.append(ai("Possession split",Gh([{label:"Blue control",value:n.team_zero.possession.possession_time,color:In[0]},{label:"Neutral",value:n.team_zero.possession.neutral_time,color:"#65d6ad"},{label:"Orange control",value:n.team_zero.possession.opponent_possession_time,color:In[1]}],Sr)),TC(n,"Field half pressure"),ai("Ball third control",Gh([{label:"Blue third",value:n.team_zero.ball_third.defensive_third_time,color:In[0]},{label:"Neutral third",value:n.team_zero.ball_third.neutral_third_time,color:"#65d6ad"},{label:"Orange third",value:n.team_zero.ball_third.offensive_third_time,color:In[1]}],Sr)),ai("Player field thirds",$o(n.players.map((r,o)=>({label:r.name||`Player ${o+1}`,segments:[{label:"Def",value:r.positioning.time_defensive_third,color:r.is_team_0?In[0]:In[1]},{label:"Mid",value:r.positioning.time_neutral_third,color:"#65d6ad"},{label:"Off",value:r.positioning.time_offensive_third,color:r.is_team_0?In[1]:In[0]}]})),Ri)),ai("Role time",$o(n.players.map((r,o)=>({label:r.name||`Player ${o+1}`,segments:[{label:"Most back",value:r.positioning.time_most_back,color:"#58a6ff"},{label:"Mid",value:r.positioning.time_mid_role,color:"#65d6ad"},{label:"Most forward",value:r.positioning.time_most_forward,color:"#f39a37"},{label:"Other",value:r.positioning.time_other_role,color:"rgba(255,255,255,0.22)"}]})),Ri))),e.append(a),e}function X7(n,e){const t=te("div",{className:"stats-report-page"});t.append(tl("Player involvement","Interaction stats that are usually easier to trust at a glance: touches, hits, demos, 50/50 outcomes, movement, and powerslide usage."));const i=EC(e,n,b7);i&&t.append(i);const s=te("section",{className:"stats-report-charts"});return s.append(ai("Speed bands",$o(n.players.map((a,r)=>({label:a.name||`Player ${r+1}`,segments:[{label:"Slow",value:a.movement.time_slow_speed,color:"#58a6ff"},{label:"Boost",value:a.movement.time_boost_speed,color:"#f2cc60"},{label:"Supersonic",value:a.movement.time_supersonic_speed,color:"#f39a37"}]})),Ri)),ai("Aerial profile",$o(n.players.map((a,r)=>({label:a.name||`Player ${r+1}`,segments:[{label:"Ground",value:a.movement.time_on_ground,color:"#65d6ad"},{label:"Low air",value:a.movement.time_low_air,color:"#58a6ff"},{label:"High air",value:a.movement.time_high_air,color:"#d2a8ff"}]})),Ri))),t.append(s),t.append(te("p",{className:"stats-report-note",text:"Experimental event detectors such as speed flips, dodge refreshes, and ceiling shots are kept in All stats until their precision is stronger."})),t}function CC(){const n=window.location.hash.replace(/^#/,"");return mC.some(e=>e.id===n)?n:"overview"}function K7(n,e,t){const i=te("nav",{className:"stats-report-tabs"});return mC.forEach(s=>{const a=te("button",{text:s.label});a.type="button",a.dataset.active=s.id===n?"true":"false",a.addEventListener("click",()=>{CC()!==s.id&&window.history.replaceState(null,"",`#${s.id}`),$h(e,t)}),i.append(a)}),i}function Ny(n){const e=te("header",{className:"stats-report-header"}),t=te("div",{className:"stats-report-title"});if(t.append(te("h1",{text:"Replay Stats"}),te("p",{text:n??"Load a Rocket League replay to review curated stats pages, comparison graphs, and the complete raw stat dump."})),Sc.showStandaloneActions!==!1){const i=te("div",{className:"stats-report-actions"}),s=te("label",{className:"stats-report-file-label",text:"Load replay"}),a=te("input");a.type="file",a.accept=".replay",a.addEventListener("change",async()=>{const o=a.files?.[0],l=Ud;o&&l instanceof HTMLElement&&await q7(l,o)}),s.append(a);const r=te("a",{className:"stats-report-link",text:"Open player"});r.setAttribute("href","../"),i.append(s,r),e.append(t,i)}else e.append(t);return e}function $h(n,e){const t=w7(e.statsTimeline,e.statsFrameLookup);if(!t){n.replaceChildren(te("main",{className:"stats-report-empty",text:"The replay did not produce any stats frames."}));return}const i=Go(t).filter(R7),s=C7(i),a=CC(),r=te("main",{className:"stats-report"});r.append(Ny()),r.append(K7(a,n,e)),a==="goals"?r.append(V7(e,t)):a==="boost"?r.append(G7(t,i)):a==="territory"?r.append(W7(t)):a==="involvement"?r.append(X7(t,i)):a==="dump"?r.append(O7(s,t)):r.append(F7(e,t,i)),n.replaceChildren(r)}function oS(n){return{...n,statsFrameLookup:n.statsFrameLookup??XE(n.statsTimeline)}}function Tc(n,e){const t=te("main",{className:"stats-report"});t.append(Ny(e)),t.append(te("p",{className:"stats-report-status",text:e})),n.replaceChildren(t)}async function AC(n,e,t,i){Tc(n,`Loading ${t}...`);const s=await kf(e,{onProgress(a){Tc(n,Qo(a))}});$h(n,{fileName:t,replayUrl:i,statsTimeline:s.statsTimeline,statsFrameLookup:s.statsFrameLookup})}async function q7(n,e){try{await AC(n,new Uint8Array(await e.arrayBuffer()),e.name,null)}catch(t){Tc(n,t instanceof Error?t.message:String(t))}}async function Y7(n,e){try{Tc(n,`Fetching ${e}...`);const t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch replay: ${t.status} ${t.statusText}`);const i=new URL(e,window.location.href).pathname,s=decodeURIComponent(i.split("/").pop()||"remote replay");await AC(n,new Uint8Array(await t.arrayBuffer()),s,t.url?new URL(t.url):new URL(e,window.location.href))}catch(t){Tc(n,t instanceof Error?t.message:String(t))}}function j7(n,e={}){if(Ud=n,Sc=e,e.initialData)$h(n,oS(e.initialData));else{const i=te("main",{className:"stats-report"});i.append(Ny()),i.append(te("section",{className:"stats-report-empty",text:"Load a replay to generate the stats report."})),n.replaceChildren(i)}const t=new URL(window.location.href).searchParams.get("replayUrl");return!e.initialData&&t&&Y7(n,t),{root:n,render(i){$h(n,oS(i))},destroy(){Ud===n&&(Ud=null,Sc={}),n.replaceChildren()}}}const dd="replay-review-document",lS="replay-review-root";function _i(n,e={}){const t=document.createElement(n);return e.className&&(t.className=e.className),e.id&&(t.id=e.id),e.text!==void 0&&(t.textContent=e.text),t}function RC(n,e={}){let t=null;const i=async()=>n instanceof Uint8Array?n:await n(),s=a=>(t||(t=i().then(r=>kf(r,{reportEveryNFrames:100,onProgress:a}))),t);return{replayName:e.replayName,replayUrl:e.replayUrl??null,async getStatsTimeline(a){return(await s(a)).statsTimeline},getReplayBundle:s}}function Z7(n=window.location){const e=sC(n.search,n.href);return e?RC(async()=>{const t=await fetch(e.url,e.fetchInit);if(!t.ok){const i=t.statusText?` ${t.statusText}`:"";throw new Error(`Failed to fetch replay: ${t.status}${i}`)}return new Uint8Array(await t.arrayBuffer())},{replayName:e.name,replayUrl:e.url}):null}function J7(n){return n||(new URL(window.location.href).searchParams.get("mode")==="viewer"?"viewer":"report")}function Q7(n){const e=new URL(window.location.href);n==="report"?e.searchParams.delete("mode"):e.searchParams.set("mode",n),window.history.replaceState(null,"",e)}function eX(n,e={}){document.documentElement.classList.add(dd),document.body.classList.add(dd),n.classList.add(lS);let t=e.provider??null,i=J7(e.initialMode),s=null,a=null,r=null,o=null,l=null,c=!1;const u=_i("main",{className:"replay-review-shell"}),d=_i("div",{className:"replay-review-toolbar"}),h=_i("div",{className:"replay-review-status"}),f=_i("button",{text:"Stats"}),p=_i("button",{text:"Viewer"}),g=_i("label",{className:"replay-review-file",text:"Load replay"}),_=_i("input"),m=_i("section",{className:"replay-review-pane"}),v=_i("section",{className:"replay-review-pane"});_.type="file",_.accept=".replay",g.append(_),d.append(h,g,f,p),u.append(d,m,v),n.replaceChildren(u);const y=L=>{h.textContent=L},b=L=>{y(Qo(L))},S=()=>{s?.destroy(),s=null,a?.destroy(),a=null,r=null,o=null,l=null},x=()=>t?.getReplayBundle?(o||(o=t.getReplayBundle(b)),o):null,M=()=>t?(r||(r=t.getStatsTimeline?t.getStatsTimeline(b):x()?.then(L=>L.statsTimeline)??null),r):null,C=()=>{m.replaceChildren(_i("section",{className:"replay-review-empty",text:"Load a replay to review stats and playback."}))},w=async()=>{if(s)return;const L=M(),O=x();if(!L&&!O){C(),y("No replay loaded");return}m.replaceChildren(_i("section",{className:"replay-review-empty",text:"Loading stats..."}));const D=await O,U=D?.statsTimeline??(L?await L:null);if(!U){C(),y("No replay loaded");return}const F={fileName:t?.replayName??"replay",replayUrl:t?.replayUrl??null,statsTimeline:U,statsFrameLookup:D?.statsFrameLookup};c||(s=j7(m,{initialData:F,showStandaloneActions:!1,onWatchGoal(W){l=W.config,a?.destroy(),a=null,i="viewer",R()}}),y(`Loaded ${F.fileName}`))},E=async()=>{if(a)return;const L=x();if(!L){v.replaceChildren(_i("section",{className:"replay-review-empty",text:"Replay playback is not available for this data source."})),y("Viewer unavailable");return}v.replaceChildren(_i("section",{className:"replay-review-empty",text:"Loading viewer..."}));const O=await L;c||(a=y7(v,{initialBundle:O,initialConfig:l,initialReplayName:t?.replayName,loadFromLocation:!1}),l=null,y(`Loaded ${t?.replayName??"replay"}`))},R=()=>{f.dataset.active=String(i==="report"),p.dataset.active=String(i==="viewer"),m.hidden=i!=="report",v.hidden=i!=="viewer",Q7(i),(i==="report"?w():E()).catch(L=>{console.error("Failed to render replay review mode:",L),y(L instanceof Error?L.message:"Failed to load replay review")})};return f.addEventListener("click",()=>{i="report",R()}),p.addEventListener("click",()=>{i="viewer",R()}),_.addEventListener("change",()=>{const L=_.files?.[0];L&&(t=RC(async()=>new Uint8Array(await L.arrayBuffer()),{replayName:L.name,replayUrl:null}),S(),R())}),R(),{root:n,setMode(L){i=L,R()},setProvider(L,O={}){t=L,O.mode&&(i=O.mode),S(),R()},destroy(){c=!0,S(),n.classList.remove(lS),document.documentElement.classList.remove(dd),document.body.classList.remove(dd),n.replaceChildren()}}}const PC=document.querySelector("#app");if(!(PC instanceof HTMLElement))throw new Error("Missing #app mount element");let IC=null;try{IC=Z7(window.location)}catch(n){console.error("Invalid replay URL:",n)}eX(PC,{provider:IC}); diff --git a/crates/rocket-sense-server/static/subtr-actor/stats/assets/replayLoader.worker-BOmyAjmY.js b/crates/rocket-sense-server/static/subtr-actor/stats/assets/replayLoader.worker-BOmyAjmY.js new file mode 100644 index 00000000..34a9e71b --- /dev/null +++ b/crates/rocket-sense-server/static/subtr-actor/stats/assets/replayLoader.worker-BOmyAjmY.js @@ -0,0 +1,2 @@ +(function(){"use strict";function be(e,t,n,r){const o=pe(e,u.__wbindgen_malloc),i=x,a=u.get_replay_bundle_json_parts_with_progress(o,i,t,k(n)?4294967297:n>>>0,k(r)?4294967297:r>>>0);if(a[2])throw G(a[1]);return G(a[0])}function ge(){return{__proto__:null,"./rl_replay_subtr_actor_bg.js":{__proto__:null,__wbg_Error_8c4e43fe74559d73:function(t,n){return Error(P(t,n))},__wbg_Number_04624de7d0e8332d:function(t){return Number(t)},__wbg_String_8f0eb39a4a4c2f66:function(t,n){const r=String(n),o=F(r,u.__wbindgen_malloc,u.__wbindgen_realloc),i=x;y().setInt32(t+4,i,!0),y().setInt32(t+0,o,!0)},__wbg___wbindgen_bigint_get_as_i64_8fcf4ce7f1ca72a2:function(t,n){const r=n,o=typeof r=="bigint"?r:void 0;y().setBigInt64(t+8,k(o)?BigInt(0):o,!0),y().setInt32(t+0,!k(o),!0)},__wbg___wbindgen_boolean_get_bbbb1c18aa2f5e25:function(t){const n=t,r=typeof n=="boolean"?n:void 0;return k(r)?16777215:r?1:0},__wbg___wbindgen_debug_string_0bc8482c6e3508ae:function(t,n){const r=U(n),o=F(r,u.__wbindgen_malloc,u.__wbindgen_realloc),i=x;y().setInt32(t+4,i,!0),y().setInt32(t+0,o,!0)},__wbg___wbindgen_in_47fa6863be6f2f25:function(t,n){return t in n},__wbg___wbindgen_is_bigint_31b12575b56f32fc:function(t){return typeof t=="bigint"},__wbg___wbindgen_is_function_0095a73b8b156f76:function(t){return typeof t=="function"},__wbg___wbindgen_is_object_5ae8e5880f2c1fbd:function(t){const n=t;return typeof n=="object"&&n!==null},__wbg___wbindgen_is_string_cd444516edc5b180:function(t){return typeof t=="string"},__wbg___wbindgen_is_undefined_9e4d92534c42d778:function(t){return t===void 0},__wbg___wbindgen_jsval_eq_11888390b0186270:function(t,n){return t===n},__wbg___wbindgen_jsval_loose_eq_9dd77d8cd6671811:function(t,n){return t==n},__wbg___wbindgen_number_get_8ff4255516ccad3e:function(t,n){const r=n,o=typeof r=="number"?r:void 0;y().setFloat64(t+8,k(o)?0:o,!0),y().setInt32(t+0,!k(o),!0)},__wbg___wbindgen_string_get_72fb696202c56729:function(t,n){const r=n,o=typeof r=="string"?r:void 0;var i=k(o)?0:F(o,u.__wbindgen_malloc,u.__wbindgen_realloc),a=x;y().setInt32(t+4,a,!0),y().setInt32(t+0,i,!0)},__wbg___wbindgen_throw_be289d5034ed271b:function(t,n){throw new Error(P(t,n))},__wbg_call_389efe28435a9388:function(){return E(function(t,n){return t.call(n)},arguments)},__wbg_call_4708e0c13bdc8e95:function(){return E(function(t,n,r){return t.call(n,r)},arguments)},__wbg_done_57b39ecd9addfe81:function(t){return t.done},__wbg_entries_58c7934c745daac7:function(t){return Object.entries(t)},__wbg_error_7534b8e9a36f1ab4:function(t,n){let r,o;try{r=t,o=n,console.error(P(t,n))}finally{u.__wbindgen_free(r,o,1)}},__wbg_get_9b94d73e6221f75c:function(t,n){return t[n>>>0]},__wbg_get_b3ed3ad4be2bc8ac:function(){return E(function(t,n){return Reflect.get(t,n)},arguments)},__wbg_get_with_ref_key_1dc361bd10053bfe:function(t,n){return t[n]},__wbg_instanceof_ArrayBuffer_c367199e2fa2aa04:function(t){let n;try{n=t instanceof ArrayBuffer}catch{n=!1}return n},__wbg_instanceof_Map_53af74335dec57f4:function(t){let n;try{n=t instanceof Map}catch{n=!1}return n},__wbg_instanceof_Uint8Array_9b9075935c74707c:function(t){let n;try{n=t instanceof Uint8Array}catch{n=!1}return n},__wbg_isArray_d314bb98fcf08331:function(t){return Array.isArray(t)},__wbg_isSafeInteger_bfbc7332a9768d2a:function(t){return Number.isSafeInteger(t)},__wbg_iterator_6ff6560ca1568e55:function(){return Symbol.iterator},__wbg_length_32ed9a279acd054c:function(t){return t.length},__wbg_length_35a7bace40f36eac:function(t){return t.length},__wbg_log_f1a1b5cd3f9c7822:function(t,n){console.log(P(t,n))},__wbg_new_361308b2356cecd0:function(){return new Object},__wbg_new_3eb36ae241fe6f44:function(){return new Array},__wbg_new_8a6f238a6ece86ea:function(){return new Error},__wbg_new_dca287b076112a51:function(){return new Map},__wbg_new_dd2b680c8bf6ae29:function(t){return new Uint8Array(t)},__wbg_new_from_slice_a3d2629dc1826784:function(t,n){return new Uint8Array(Z(t,n))},__wbg_next_3482f54c49e8af19:function(){return E(function(t){return t.next()},arguments)},__wbg_next_418f80d8f5303233:function(t){return t.next},__wbg_prototypesetcall_bdcdcc5842e4d77d:function(t,n,r){Uint8Array.prototype.set.call(Z(t,n),r)},__wbg_push_8ffdcb2063340ba5:function(t,n){return t.push(n)},__wbg_set_1eb0999cf5d27fc8:function(t,n,r){return t.set(n,r)},__wbg_set_3f1d0b984ed272ed:function(t,n,r){t[n]=r},__wbg_set_6cb8631f80447a67:function(){return E(function(t,n,r){return Reflect.set(t,n,r)},arguments)},__wbg_set_f43e577aea94465b:function(t,n,r){t[n>>>0]=r},__wbg_stack_0ed75d68575b0f3c:function(t,n){const r=n.stack,o=F(r,u.__wbindgen_malloc,u.__wbindgen_realloc),i=x;y().setInt32(t+4,i,!0),y().setInt32(t+0,o,!0)},__wbg_value_0546255b415e96c1:function(t){return t.value},__wbindgen_cast_0000000000000001:function(t){return t},__wbindgen_cast_0000000000000002:function(t){return t},__wbindgen_cast_0000000000000003:function(t,n){return P(t,n)},__wbindgen_cast_0000000000000004:function(t){return BigInt.asUintN(64,t)},__wbindgen_init_externref_table:function(){const t=u.__wbindgen_externrefs,n=t.grow(4);t.set(0,void 0),t.set(n+0,void 0),t.set(n+1,null),t.set(n+2,!0),t.set(n+3,!1)}}}}function ye(e){const t=u.__externref_table_alloc();return u.__wbindgen_externrefs.set(t,e),t}function U(e){const t=typeof e;if(t=="number"||t=="boolean"||e==null)return`${e}`;if(t=="string")return`"${e}"`;if(t=="symbol"){const o=e.description;return o==null?"Symbol":`Symbol(${o})`}if(t=="function"){const o=e.name;return typeof o=="string"&&o.length>0?`Function(${o})`:"Function"}if(Array.isArray(e)){const o=e.length;let i="[";o>0&&(i+=U(e[0]));for(let a=1;a1)r=n[1];else return toString.call(e);if(r=="Object")try{return"Object("+JSON.stringify(e)+")"}catch{return"Object"}return e instanceof Error?`${e.name}: ${e.message} +${e.stack}`:r}function Z(e,t){return e=e>>>0,O().subarray(e/1,e/1+t)}let T=null;function y(){return(T===null||T.buffer.detached===!0||T.buffer.detached===void 0&&T.buffer!==u.memory.buffer)&&(T=new DataView(u.memory.buffer)),T}function P(e,t){return e=e>>>0,we(e,t)}let B=null;function O(){return(B===null||B.byteLength===0)&&(B=new Uint8Array(u.memory.buffer)),B}function E(e,t){try{return e.apply(this,t)}catch(n){const r=ye(n);u.__wbindgen_exn_store(r)}}function k(e){return e==null}function pe(e,t){const n=t(e.length*1,1)>>>0;return O().set(e,n/1),x=e.length,n}function F(e,t,n){if(n===void 0){const s=D.encode(e),l=t(s.length,1)>>>0;return O().subarray(l,l+s.length).set(s),x=s.length,l}let r=e.length,o=t(r,1)>>>0;const i=O();let a=0;for(;a127)break;i[o+a]=s}if(a!==r){a!==0&&(e=e.slice(a)),o=n(o,r,r=a+e.length*3,1)>>>0;const s=O().subarray(o+a,o+r),l=D.encodeInto(e,s);a+=l.written,o=n(o,r,a,1)>>>0}return x=a,o}function G(e){const t=u.__wbindgen_externrefs.get(e);return u.__externref_table_dealloc(e),t}let z=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});z.decode();const he=2146435072;let H=0;function we(e,t){return H+=t,H>=he&&(z=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),z.decode(),H=t),z.decode(O().subarray(e,e+t))}const D=new TextEncoder;"encodeInto"in D||(D.encodeInto=function(e,t){const n=D.encode(e);return t.set(n),{read:e.length,written:n.length}});let x=0,u;function ke(e,t){return u=e.exports,T=null,B=null,u.__wbindgen_start(),u}async function xe(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(o){if(e.ok&&n(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",o);else throw o}const r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{const r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}async function Ae(e){if(u!==void 0)return u;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0&&(e=new URL(""+new URL("rl_replay_subtr_actor_bg-BjSK7HJ9.wasm",self.location.href).href,self.location.href));const t=ge();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));const{instance:n,module:r}=await xe(await e,t);return ke(n)}const q="octane",Te={breakout:{kind:"breakout",label:"Breakout",length:131.4924,width:80.521,height:30.3,slopeDegrees:-.9795,groundHeightFront:43.8976,groundHeightBack:46.1454,offset:13.88,elevation:17.05},dominus:{kind:"dominus",label:"Dominus",length:127.9268,width:83.27995,height:31.3,slopeDegrees:-.9635,groundHeightFront:47.2238,groundHeightBack:49.3749,offset:13.88,elevation:17.05},hybrid:{kind:"hybrid",label:"Hybrid",length:127.0192,width:82.18787,height:34.15907,slopeDegrees:-.5499,groundHeightFront:54.0982,groundHeightBack:55.3173,offset:13.88,elevation:17.05},merc:{kind:"merc",label:"Merc",length:120.72,width:76.71,height:41.66,slopeDegrees:.28,groundHeightFront:60.76,groundHeightBack:61.35,offset:13.88,elevation:17.05},octane:{kind:"octane",label:"Octane",length:118.0074,width:84.19941,height:36.15907,slopeDegrees:-.5518,groundHeightFront:55.1449,groundHeightBack:56.2814,offset:13.88,elevation:17.05},plank:{kind:"plank",label:"Plank",length:128.8198,width:84.67036,height:29.3944,slopeDegrees:-.3447,groundHeightFront:44.998,groundHeightBack:45.773,offset:13.88,elevation:17.05}},Se={"16batmobile":"plank","70dodgechargerrt":"dominus","89batmobile":"dominus","99nissanskylinegtrr34":"hybrid",aftershock:"dominus",animusgp:"breakout",artemis:"plank",artemisg1:"plank",artemisgxt:"plank",astonmartinvalhalla:"breakout",backfire:"octane",backtothefuturetimemachine:"dominus",batmobile1989:"dominus",battlebus:"merc",breakout:"breakout",breakouttypes:"breakout",centio:"plank",centiov17:"plank",cyclone:"breakout",deloreantimemachine:"dominus",diestro:"dominus",dominus:"dominus",dominusgt:"dominus",endo:"hybrid",esper:"hybrid",fast4wd:"octane",fennec:"octane",gazellagt:"dominus",gizmo:"octane",grog:"octane",guardian:"dominus",guardiang1:"dominus",guardiangxt:"dominus",hotshot:"dominus",icecharger:"dominus",imperatordt5:"dominus",jager619rs:"hybrid",jurassicjeepwrangler:"octane",mantis:"plank",marauder:"octane",masamune:"dominus",maverick:"dominus",maverickg1:"dominus",maverickgxt:"dominus",mclaren570s:"dominus",merc:"merc",mr11:"dominus",nimbus:"hybrid",octane:"octane",octanezsr:"octane",paladin:"plank",proteus:"octane",ripper:"dominus",roadhog:"octane",roadhogxl:"octane",samurai:"breakout",scarab:"octane",takumi:"octane",takumirxt:"octane",thedarkknightstumbler:"octane",thedarkknightrisestumbler:"octane",triton:"octane",twinmilliii:"plank",twinzer:"octane",venom:"hybrid",vulcan:"octane",werewolf:"dominus",xdevil:"hybrid",xdevilmk2:"hybrid",zippy:"octane","1966cadillacdeville":"breakout",ace:"breakout",admiral:"dominus",azura:"breakout",behemoth:"merc",beskar:"hybrid",bmwm3e30:"dominus",bmwm2racing:"dominus",bmwm4gt3evo:"dominus",bmw1series:"octane",bmw1seriesrle:"octane",bmwm240i:"dominus",bugatticentodieci:"plank",bumblebee:"dominus",bumblebeecar:"dominus",chevroletastro:"merc",chevroletcorvettestingray:"breakout",chevroletcorvettezr1:"breakout",chryslerpacifica:"hybrid",corlay:"octane",cyberpunkquadra:"breakout",defenderd7xr:"merc",diesel:"breakout",dodgechargerdaytonascatpack:"dominus",dodgerchargerdaytonascatpack:"dominus",dominusneon:"dominus",emperor:"breakout",emperorii:"breakout",emperoriifrozen:"breakout",emperoriiscorched:"breakout",fastfuriousdodgecharger:"dominus",fastandfuriousdodgecharger:"dominus",fastandfuriousdodgechargersrthellcat:"dominus",fastfuriousmazdarx7:"breakout",fastandfuriousmazdarx7:"breakout",fastfuriousnissanskyline:"hybrid",fastandfuriousnissanskyline:"hybrid",fastfuriouspontiacfiero:"hybrid",fastandfuriouspontiacfiero:"hybrid",fenneczrf:"octane",ferrari296gtb:"dominus",ferrarif40:"breakout",fordbroncoraptorrle:"merc",fordf150rle:"octane",fordmustanggtd:"dominus",fordmustangshelbygt500:"dominus",fordmustangmacherle:"octane",fordmustangshelbygt350rrle:"dominus",formula12021:"plank",formula12022:"plank",fuse:"breakout",havoc:"breakout",hearse:"hybrid",homerscar:"dominus",hondacivictyper:"octane",hondacivictyperle:"octane",jackal:"octane",jeepwranglerrubicon:"octane",kitt:"dominus",knightindustries2000:"dominus",komodo:"breakout",lamborghinicountachlpi8004:"dominus",lamborghinihuracansto:"dominus",lamborghiniurus:"hybrid",lamborghiniurusse:"hybrid",lightningmcqueen:"dominus",lightningmcqueencar:"dominus",lockjaw:"dominus",luiginsr:"octane",maestro:"dominus",magnifique:"dominus",magnifiquegxt:"dominus",mako:"breakout",mamba:"dominus",mario:"octane",marionsr:"octane",maven:"dominus",mclaren765lt:"dominus",mclarenp1:"dominus",mclarensenna:"breakout",megastar:"breakout",mercedesamggt63s:"dominus",mercedesbenzcla:"dominus",mudcat:"octane",mudcatg1:"octane",mudcatgxt:"octane",nissan350z:"dominus",nissanfairladyz:"dominus",nissanfairladyzrle:"dominus",nissansilvia:"hybrid",nissansilviarle:"hybrid",nissanskylinegtr:"hybrid",nissanskylinegtrr32:"hybrid",nissanzperformance:"dominus",nissanzperformancecar:"dominus",outlaw:"octane",outlawgxt:"octane",pattywagon:"octane",pizzaplanetdeliverytruck:"merc",pontiacfirebird:"breakout",porsche918spyder:"breakout",porsche911gt3rs:"dominus",porsche911turbo:"dominus",porsche911turborle:"dominus",primo:"hybrid",psyclops:"octane",quadraturbor:"breakout",ram1500rho:"hybrid",recoilav:"merc",redline:"breakout",revolver:"breakout",rivianr1s:"hybrid",scorpion:"dominus",shokunin:"octane",shokuningxt:"octane",stampede:"merc",teslacybertruck:"hybrid",themysterymachine:"merc",theincredibile:"breakout",turtlevan:"merc",voidburn:"hybrid",volkswagengolfgti:"octane",volkswagengolfgtirle:"octane",xentari:"octane",zefira:"dominus",breakoutx:"breakout",nexus:"breakout",nexussc:"breakout",whiplash:"breakout","007sastonmartindbs":"dominus","007sastonmartinvalhalla":"dominus",batmobile2022:"dominus",chikara:"dominus",chikarag1:"dominus",chikaragxt:"dominus",ecto1:"dominus",ecto1ghostbusters:"dominus",fastfuriousdodgechargersrthellcat:"dominus",gazellagthotwheels:"dominus",kittknightrider:"dominus",lamborghinihuracnsto:"dominus",mr11hotwheels:"dominus",nascarchevroletcamaro:"dominus",nascarfordmustang:"dominus",nascartoyotacamry:"dominus",nascarnextgenchevroletcamaro:"dominus",nascarnextgenchevroletcamaro2022:"dominus",nascarnextgenfordmustang:"dominus",nascarnextgenfordmustang2022:"dominus",nascarnextgentoyotacamry:"dominus",nascarnextgentoyotacamry2022:"dominus",nemesis:"dominus",peregrinett:"dominus",perigrinett:"dominus",ronin:"dominus",roning1:"dominus",roningxt:"dominus",samusgunship:"dominus",samusgunshipnintendoexclusive:"dominus",tyranno:"dominus",tyrannogxt:"dominus",insidio:"hybrid",jager619:"hybrid",jger619:"hybrid",jger619rs:"hybrid",r3mx:"hybrid",r3mxgxt:"hybrid",tygris:"hybrid",nomad:"merc",nomadgxt:"merc","007sastonmartindb5":"octane",armadillo:"octane",armadilloxboxexclusive:"octane",boneshaker:"octane",dingo:"octane",fast4wdhotwheels:"octane",harbinger:"octane",harbingergxt:"octane",hogsticker:"octane",hogstickerxboxexclusive:"octane",sweettooth:"octane",sweettoothplaystationexclusive:"octane",thedarkknighttumbler:"octane",batmobile2016:"plank",sentinel:"plank"};function ve(e){const t={};for(const[n,r]of e)for(const o of n)t[o]=r;return t}const Oe=ve([[[22,1416,1894,1932,3031,3311,6243,6489,7651,7696,7890,7901,8006,8360,8361,8565,8566,8669,9357,10697,10698,10817,10822,11038,11394,11505,11677,11800,11933,11949,12173,12315,12361,12484],"breakout"],[[29,403,597,600,1018,1171,1286,1675,1689,1883,2070,2268,2666,2950,2951,3155,3156,3157,3265,3426,3875,3879,3880,4014,4155,4367,4472,4473,4745,4770,4781,4861,4864,5709,5773,5823,5858,5964,5979,6122,6244,6247,6260,6836,7211,7337,7338,7341,7343,7415,7512,7532,7593,7772,8454,9053,9088,9089,9140,9388,9894,10094,10440,10441,10694,10695,11016,11095,11315,11336,11534,11941,11996,12106,12142,12262,12286,12325,12382,12563,12669],"dominus"],[[28,31,1159,1317,1624,1856,2269,3451,3582,3702,5470,5488,5879,7012,9084,9085,9427,10044,10805,11138,11141,11379,11932,12569,12652],"hybrid"],[[30,4780,7336,7477,7815,7979,10689,11098,11736,11905,11950,12318,12335],"merc"],[[21,23,25,26,27,402,404,523,607,625,723,1172,1295,1300,1475,1478,1533,1568,1623,2665,2853,2919,2949,4284,4318,4319,4320,4782,4906,5020,5039,5188,5361,5547,5713,5837,5951,6939,7947,7948,8383,8806,8807,10896,10897,10900,10901,11314,11603,12104,12105],"octane"],[[24,803,1603,1691,1919,3594,3614,3622,4268,5265,7052,8524],"plank"]]);function J(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function Q(e){if(!e)return null;switch(J(e)){case"breakout":return"breakout";case"dominus":return"dominus";case"hybrid":return"hybrid";case"merc":return"merc";case"octane":return"octane";case"batmobile":case"plank":return"plank";default:return null}}function ee(e){return e?Se[J(e)]??null:null}function Ie(e){return Q(e)??ee(e)}function Pe(e){return Te[e]}function Y(e,t){if(!(!e||typeof e!="object")){if("Str"in e&&typeof e.Str=="string"){t.push(e.Str);return}if("Name"in e&&typeof e.Name=="string"){t.push(e.Name);return}if("Byte"in e&&e.Byte&&typeof e.Byte=="object"){const n=e.Byte;typeof n.kind=="string"&&t.push(n.kind),typeof n.value=="string"&&t.push(n.value);return}if("Struct"in e&&e.Struct&&typeof e.Struct=="object"){const n=e.Struct;if(typeof n.name=="string"&&t.push(n.name),Array.isArray(n.fields))for(const r of n.fields)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),Y(r[1],t));return}if("Array"in e&&Array.isArray(e.Array)){for(const n of e.Array)if(Array.isArray(n))for(const r of n)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),Y(r[1],t))}}}function Be(e){const t=Q(e?.car_hitbox_family);if(t)return t;const n=e?.car_body_id;if(typeof n=="number"){const a=Oe[n];if(a)return a}const r=ee(e?.car_body_name);if(r)return r;const o=e?.stats;if(!o)return q;const i=[];for(const[a,s]of Object.entries(o))i.push(a),Y(s,i);for(const a of i){const s=Ie(a);if(s)return s}return q}function A(e){const[t,n]=Object.entries(e)[0]??["Unknown","unknown"];return typeof n=="string"||typeof n=="number"?`${t}:${n}`:n&&typeof n=="object"?`${t}:${JSON.stringify(n)}`:`${t}:${JSON.stringify(n)}`}function N(e,t){return Math.max(0,e-t)}function te(e){return new Map(e.map(t=>[t.id,t]))}const p=70,ne=73,Ee=3072,De=4096,Ne=1792,Me=4184,Re=940,Fe=3308,ze=2816,re=3584,Ce=2484,je=1788,Le=2300,Ve=2048,Ue=1036,He=1024,Ye=1024,$e=4240,oe=34;function C(e,t,n,r,o){e.push({index:e.length,padId:null,size:o,position:{x:t,y:n,z:r},events:[]})}function j(e,t,n,r,o){C(e,-t,n,r,o),C(e,t,n,r,o)}function $(e,t,n,r,o){C(e,t,-n,r,o),C(e,t,n,r,o)}function I(e,t,n,r,o){j(e,t,-n,r,o),j(e,t,n,r,o)}function Xe(){const e=[];return $(e,0,$e,p,"small"),I(e,Ne,Me,p,"small"),I(e,Ee,De,ne,"big"),I(e,Re,Fe,p,"small"),$(e,0,ze,p,"small"),I(e,re,Ce,p,"small"),I(e,je,Le,p,"small"),I(e,Ve,Ue,p,"small"),$(e,0,Ye,p,"small"),j(e,re,0,ne,"big"),j(e,He,0,p,"small"),e}function X(e){if(e==="Available")return!0;if(e&&typeof e=="object"){if("Available"in e)return!0;if("PickedUp"in e)return!1;const t=e.kind;if(t==="Available")return!0;if(t==="PickedUp")return!1}return null}function We(e){return e==="big"||e==="Big"?"big":e==="small"||e==="Small"?"small":null}function Ke(e){let t=null;for(const n of e){const r=X(n.kind);if(r===!1){t=n.time;continue}if(r===!0&&t!==null)return n.time-t>=7?"big":"small"}return null}function Ze(e,t,n,r){const o=te(t),i=new Map;for(const c of e.boost_pad_events??[]){if(X(c.kind)===null){r?.advance();continue}const d=i.get(c.pad_id);d?d.push(c):i.set(c.pad_id,[c]),r?.advance()}const a=e.boost_pads;if(!a||a.length===0)return r?.advance(oe),Xe();const s=[...a].sort((c,f)=>c.index-f.index),l=new Array(s.length);for(let c=0;c=72?"big":"small"),h=g.sort((_,w)=>_.time-w.time),m=new Array(h.length);for(let _=0;_=0?e.frame:null}function Ge(e,t){if(typeof e.time=="number"&&Number.isFinite(e.time))return e.time;const n=W(e);if(n===null)return null;const r=t.frame_data.metadata_frames[n]?.time;return typeof r=="number"&&Number.isFinite(r)?r:null}function qe(e,t){return`bookmark:${W(e)??"unknown"}:${e.description||"tick-mark"}:${t}`}function Je(e,t,n){return(e.replay_tick_marks??[]).flatMap((r,o)=>{n?.advance();const i=Ge(r,e);return i===null?[]:[{id:qe(r,o),description:r.description,frame:W(r),time:N(i,t)}]})}function Qe(e){const t=e.description.trim()||"Replay bookmark";return{id:e.id,time:e.time,seekTime:e.time,frame:e.frame??void 0,kind:"bookmark",label:t,shortLabel:"BM",iconName:"bookmark"}}const S={distance:270,height:100,pitch:-4,fov:110},et=.005,tt=Number.POSITIVE_INFINITY,nt=!0,rt=.15,ot=10,at=.1,it=10;function ae(e){const t=Math.hypot(e.x,e.y,e.z);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t}}function ie(e){const t=Math.hypot(e.x,e.y,e.z,e.w);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t,w:e.w/t}}function se(e,t){return{w:e.w*t.w-e.x*t.x-e.y*t.y-e.z*t.z,x:e.w*t.x+e.x*t.w+e.y*t.z-e.z*t.y,y:e.w*t.y-e.x*t.z+e.y*t.w+e.z*t.x,z:e.w*t.z+e.x*t.y-e.y*t.x+e.z*t.w}}function ce(e,t){const n=se(se(t,{x:e.x,y:e.y,z:e.z,w:0}),{x:-t.x,y:-t.y,z:-t.z,w:t.w});return{x:n.x,y:n.y,z:n.z}}function st(e){if(e==="Empty")return{position:null,linearVelocity:null,angularVelocity:null,rotation:null};const t=e.Data.rigid_body;return{position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:ie(t.rotation)}}function ue(e){return e==null?null:Math.max(-1,Math.min(1,(e-128)/128))}function le(e){return e==null?null:(e>127?e-256:e)*Math.PI/128}function de(e){return e?{x:e[0],y:e[1],z:e[2]}:null}const ct={cameraPitch:null,cameraYaw:null,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null};function ut(e){if(e==="Empty")return{isPresent:!1,position:null,linearVelocity:null,angularVelocity:null,rotation:null,forward:null,up:null,boostAmount:0,boostFraction:0,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,...ct};const t=e.Data.rigid_body,n=ie(t.rotation),r=n?ae(ce({x:1,y:0,z:0},n)):null,o=n?ae(ce({x:0,y:0,z:1},n)):null,i=e.Data.camera,a=e.Data.input;return{isPresent:!0,position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:n,forward:r,up:o,boostAmount:e.Data.boost_amount,boostFraction:Math.max(0,Math.min(1,e.Data.boost_amount/255)),boostActive:e.Data.boost_active,powerslideActive:e.Data.powerslide_active,jumpActive:e.Data.jump_active,doubleJumpActive:e.Data.double_jump_active,dodgeActive:e.Data.dodge_active,cameraPitch:le(i?.pitch),cameraYaw:le(i?.yaw),throttle:ue(a?.throttle),steer:ue(a?.steer),dodgeImpulse:de(a?.dodge_impulse),dodgeTorque:de(a?.dodge_torque)}}function lt(e){return e.position!==null}function dt(e){return{...e,isPresent:!1,linearVelocity:null,angularVelocity:null,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null}}function ft(e){let t=null,n=null;for(let r=0;r=t.length-1)return;let o=M(t[r].position);for(let i=r+1;iat){o=M(s.position);continue}if(mt(o,s.position)>it){o=M(s.position);continue}const d={x:(a.linearVelocity.x+s.linearVelocity.x)/2,y:(a.linearVelocity.y+s.linearVelocity.y)/2,z:(a.linearVelocity.z+s.linearVelocity.z)/2},g={x:o.x+d.x*f,y:o.y+d.y*f,z:o.z+d.z*f},b=(i-r)%n.smoothingAnchorInterval===0?.5:n.smoothingBlendFactor;o={x:g.x*(1-b)+s.position.x*b,y:g.y*(1-b)+s.position.y*b,z:g.z*(1-b)+s.position.z*b},s.position=M(o)}}function _t(e){return{motionSmoothing:e.motionSmoothing??nt,smoothingBlendFactor:e.smoothingBlendFactor??rt,smoothingAnchorInterval:Math.max(1,e.smoothingAnchorInterval??ot)}}function _e(){return typeof performance>"u"?Date.now():performance.now()}function bt(e){const t=e.meta.team_zero.length+e.meta.team_one.length,n=e.frame_data.players.reduce((a,[,s])=>a+s.frames.length,0),r=e.boost_pads?.length??oe,o=e.boost_pad_events?.length??0,i=(e.goal_events?.length??0)+(e.player_stat_events?.length??0)+(e.demolish_infos?.length??0)+(e.replay_tick_marks?.length??0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,n),Math.max(1,e.frame_data.ball_data.frames.length),Math.max(1,r+o),Math.max(1,i)].reduce((a,s)=>a+s,0)}function gt(e){const t=e.frame_data.players.reduce((n,[,r])=>n+r.frames.length,0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,e.frame_data.ball_data.frames.length)].reduce((n,r)=>n+r,0)}function yt(e,t,n={}){const r=bt(e),o=gt(e);let i=0,a=0,s=-1,l=-1,c=_e();const f=n.yieldEveryMs??Number.POSITIVE_INFINITY,d=n.progressReportMinDelta??et,g=Math.max(1,n.progressReportFrameInterval??tt),b=()=>{if(!t)return!1;const m=Math.max(0,Math.min(1,i/r));if(m<=s)return!1;const w=a-l>=g;return m>=1||m-s>=d||w?(s=m,l=a,t(m,{progress:m,processedFrames:Math.min(a,o),totalFrames:o,processedUnits:i,totalUnits:r}),!0):!1},h=(m=!1)=>{const _=_e();return!m&&_-cr===t)?.[1];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function kt(e){const t=wt(e?.stats);return{fov:v(t,"CameraFOV")??S.fov,height:v(t,"CameraHeight")??S.height,pitch:v(t,"CameraPitch")??S.pitch,distance:v(t,"CameraDistance")??S.distance,stiffness:v(t,"CameraStiffness")??S.stiffness,swivelSpeed:v(t,"CameraSwivelSpeed")??S.swivelSpeed,transitionSpeed:v(t,"CameraTransitionSpeed")??S.transitionSpeed}}function xt(e,t){const n=new Map,r=new Map,o=[...e.meta.team_zero,...e.meta.team_one];if(o.length===0)return t?.advance(),{byId:n,byName:r};for(const i of o)r.set(i.name,i),i.remote_id&&n.set(A(i.remote_id),i),t?.advance();return{byId:n,byName:r}}function At(e){const t=new Map;for(const[n,r]of e.player_camera_events??[])t.set(A(n),r.map(o=>({frame:o.frame,ballCamActive:o.ball_cam_active,behindViewActive:o.behind_view_active,driving:o.driving})));return t}function Tt(e,t){const n=new Set(e.meta.team_zero.map(l=>l.name)),r=new Set(e.meta.team_one.map(l=>l.name)),o=xt(e,t),i=At(e),a=[];let s=0;for(const[l,c]of e.frame_data.players){const f=new Array(c.frames.length);let d;for(let m=0;mt.time!==n.time?t.time-n.time:(t.frame??0)-(n.frame??0))}function Ot(e,t,n){const r=e.player?A(e.player):null,o=r?t.get(r)?.name??r:null,i=o?`${o} scored`:"Goal";return{id:K("goal",e.frame,r??"team"),time:N(e.time,n),frame:e.frame,kind:"goal",label:i,shortLabel:"G",playerId:r,playerName:o,isTeamZero:e.scoring_team_is_team_0}}function It(e,t,n){const r=A(e.player),o=t.get(r)?.name??r,i=e.kind.toLowerCase(),a=e.kind==="Shot"?"shot":e.kind==="Save"?"save":"assist",s=e.kind==="Shot"?"SH":e.kind==="Save"?"SV":"A";return{id:K(i,e.frame,r),time:N(e.time,n),frame:e.frame,kind:i,label:`${o} ${a}`,shortLabel:s,playerId:r,playerName:o,location:e.shot?.shot_touch_position??e.shot?.ball_position??null,shot:e.shot??null,isTeamZero:e.is_team_0}}function Pt(e,t,n){const r=A(e.attacker),o=A(e.victim),i=t.get(r),a=t.get(o);return{id:K("demo",e.frame,`${r}:${o}`),time:N(e.time,n),frame:e.frame,kind:"demo",label:`${i?.name??r} demoed ${a?.name??o}`,shortLabel:"D",playerId:r,playerName:i?.name??r,secondaryPlayerId:o,secondaryPlayerName:a?.name??o,location:e.victim_location,isTeamZero:i?.isTeamZero??null}}function Bt(e,t,n,r,o){const i=te(t),a=[];for(const s of e.goal_events??[])a.push(Ot(s,i,r)),o?.advance();for(const s of e.player_stat_events??[])a.push(It(s,i,r)),o?.advance();for(const s of e.demolish_infos??[])a.push(Pt(s,i,r)),o?.advance();for(const s of n)a.push(Qe(s));return a.length===0&&o?.advance(),vt(a)}function Et(e,t={}){const n=yt(e,t.onProgress,{progressReportMinDelta:t.progressReportMinDelta,progressReportFrameInterval:t.progressReportFrameInterval}),r=e.frame_data.metadata_frames[0]?.time??0,o=pt(e,n),i=Tt(e,n),a=St(e,n),s=_t(t);me(o,a,s);for(const d of i)me(o,d.frames,s);const l=Ze(e,i,r,n),c=Je(e,r,n),f=Bt(e,i,c,r,n);return n.finish(),{frameCount:o.length,duration:o.at(-1)?.time??0,rawStartTime:r,frames:o,ballFrames:a,boostPads:l,players:i,tickMarks:c,timelineEvents:f,teamZeroNames:e.meta.team_zero.map(d=>d.name),teamOneNames:e.meta.team_one.map(d=>d.name)}}function L(e){if(e instanceof Map)return Object.fromEntries(Array.from(e.entries()).map(([t,n])=>[t,L(n)]));if(Array.isArray(e))return e.map(t=>L(t));if(e&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=L(r);return t}return e}async function Dt(){const e=Ae;typeof e=="function"&&await e()}function R(e){self.postMessage(e)}self.onmessage=async e=>{if(e.data.type==="load-replay")try{await Dt();const t=new Uint8Array(e.data.bytes);R({type:"progress",progress:{stage:"validating",progress:0}});const n=be(t,c=>{R({type:"progress",progress:L(c)})},e.data.reportEveryNFrames,32*1024*1024);R({type:"progress",progress:{stage:"normalizing",progress:0}});const r=JSON.parse(new TextDecoder().decode(n.rawReplayData)),o=Et(r,{progressReportFrameInterval:e.data.reportEveryNFrames,onProgress(c){R({type:"progress",progress:{stage:"normalizing",progress:c}})}}),i=new TextEncoder().encode(JSON.stringify(o)),a=n.rawReplayData,s=a.byteOffset===0&&a.byteLength===a.buffer.byteLength?a.buffer:a.slice().buffer,l=Array.from(n.statsTimelineParts.frameChunks,c=>c.buffer);self.postMessage({type:"done",replayBuffer:i.buffer,rawReplayBuffer:s,statsTimelineParts:{configBuffer:n.statsTimelineParts.config.buffer,replayMetaBuffer:n.statsTimelineParts.replayMeta.buffer,eventsBuffer:n.statsTimelineParts.events.buffer,activitySummaryBuffer:n.statsTimelineParts.activitySummary.buffer,positioningSummaryBuffer:n.statsTimelineParts.positioningSummary.buffer,accumulationTracksBuffer:n.statsTimelineParts.accumulationTracks.buffer,frameChunkBuffers:l}},[i.buffer,s,n.statsTimelineParts.config.buffer,n.statsTimelineParts.replayMeta.buffer,n.statsTimelineParts.events.buffer,n.statsTimelineParts.activitySummary.buffer,n.statsTimelineParts.positioningSummary.buffer,n.statsTimelineParts.accumulationTracks.buffer,...l])}catch(t){R({type:"error",error:t instanceof Error?t.message:String(t)})}}})(); diff --git a/crates/rocket-sense-server/static/subtr-actor/stats/assets/replayLoader.worker-D3pjMe81.js b/crates/rocket-sense-server/static/subtr-actor/stats/assets/replayLoader.worker-D3pjMe81.js deleted file mode 100644 index 1217437e..00000000 --- a/crates/rocket-sense-server/static/subtr-actor/stats/assets/replayLoader.worker-D3pjMe81.js +++ /dev/null @@ -1 +0,0 @@ -(function(){"use strict";function fe(e,t,n,r){const o=ge(e,m.__wbindgen_malloc),i=x,a=m.get_replay_bundle_json_parts_with_progress(o,i,t,L(n)?4294967297:n>>>0,L(r)?4294967297:r>>>0);if(a[2])throw K(a[1]);return K(a[0])}function be(){return{__proto__:null,"./rl_replay_subtr_actor_bg.js":{__proto__:null,__wbg_Error_8c4e43fe74559d73:function(t,n){return Error(I(t,n))},__wbg_String_8f0eb39a4a4c2f66:function(t,n){const r=String(n),o=V(r,m.__wbindgen_malloc,m.__wbindgen_realloc),i=x;T().setInt32(t+4,i,!0),T().setInt32(t+0,o,!0)},__wbg___wbindgen_is_string_cd444516edc5b180:function(t){return typeof t=="string"},__wbg___wbindgen_string_get_72fb696202c56729:function(t,n){const r=n,o=typeof r=="string"?r:void 0;var i=L(o)?0:V(o,m.__wbindgen_malloc,m.__wbindgen_realloc),a=x;T().setInt32(t+4,a,!0),T().setInt32(t+0,i,!0)},__wbg___wbindgen_throw_be289d5034ed271b:function(t,n){throw new Error(I(t,n))},__wbg_call_4708e0c13bdc8e95:function(){return W(function(t,n,r){return t.call(n,r)},arguments)},__wbg_error_7534b8e9a36f1ab4:function(t,n){let r,o;try{r=t,o=n,console.error(I(t,n))}finally{m.__wbindgen_free(r,o,1)}},__wbg_log_d095c16a726a937c:function(t,n){console.log(I(t,n))},__wbg_new_361308b2356cecd0:function(){return new Object},__wbg_new_3eb36ae241fe6f44:function(){return new Array},__wbg_new_8a6f238a6ece86ea:function(){return new Error},__wbg_new_dca287b076112a51:function(){return new Map},__wbg_new_from_slice_a3d2629dc1826784:function(t,n){return new Uint8Array(ye(t,n))},__wbg_push_8ffdcb2063340ba5:function(t,n){return t.push(n)},__wbg_set_1eb0999cf5d27fc8:function(t,n,r){return t.set(n,r)},__wbg_set_3f1d0b984ed272ed:function(t,n,r){t[n]=r},__wbg_set_6cb8631f80447a67:function(){return W(function(t,n,r){return Reflect.set(t,n,r)},arguments)},__wbg_set_f43e577aea94465b:function(t,n,r){t[n>>>0]=r},__wbg_stack_0ed75d68575b0f3c:function(t,n){const r=n.stack,o=V(r,m.__wbindgen_malloc,m.__wbindgen_realloc),i=x;T().setInt32(t+4,i,!0),T().setInt32(t+0,o,!0)},__wbindgen_cast_0000000000000001:function(t){return t},__wbindgen_cast_0000000000000002:function(t){return t},__wbindgen_cast_0000000000000003:function(t,n){return I(t,n)},__wbindgen_cast_0000000000000004:function(t){return BigInt.asUintN(64,t)},__wbindgen_init_externref_table:function(){const t=m.__wbindgen_externrefs,n=t.grow(4);t.set(0,void 0),t.set(n+0,void 0),t.set(n+1,null),t.set(n+2,!0),t.set(n+3,!1)}}}}function _e(e){const t=m.__externref_table_alloc();return m.__wbindgen_externrefs.set(t,e),t}function ye(e,t){return e=e>>>0,S().subarray(e/1,e/1+t)}let w=null;function T(){return(w===null||w.buffer.detached===!0||w.buffer.detached===void 0&&w.buffer!==m.memory.buffer)&&(w=new DataView(m.memory.buffer)),w}function I(e,t){return e=e>>>0,he(e,t)}let P=null;function S(){return(P===null||P.byteLength===0)&&(P=new Uint8Array(m.memory.buffer)),P}function W(e,t){try{return e.apply(this,t)}catch(n){const r=_e(n);m.__wbindgen_exn_store(r)}}function L(e){return e==null}function ge(e,t){const n=t(e.length*1,1)>>>0;return S().set(e,n/1),x=e.length,n}function V(e,t,n){if(n===void 0){const s=B.encode(e),l=t(s.length,1)>>>0;return S().subarray(l,l+s.length).set(s),x=s.length,l}let r=e.length,o=t(r,1)>>>0;const i=S();let a=0;for(;a127)break;i[o+a]=s}if(a!==r){a!==0&&(e=e.slice(a)),o=n(o,r,r=a+e.length*3,1)>>>0;const s=S().subarray(o+a,o+r),l=B.encodeInto(e,s);a+=l.written,o=n(o,r,a,1)>>>0}return x=a,o}function K(e){const t=m.__wbindgen_externrefs.get(e);return m.__externref_table_dealloc(e),t}let M=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});M.decode();const pe=2146435072;let j=0;function he(e,t){return j+=t,j>=pe&&(M=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),M.decode(),j=t),M.decode(S().subarray(e,e+t))}const B=new TextEncoder;"encodeInto"in B||(B.encodeInto=function(e,t){const n=B.encode(e);return t.set(n),{read:e.length,written:n.length}});let x=0,m;function ke(e,t){return m=e.exports,w=null,P=null,m.__wbindgen_start(),m}async function we(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(o){if(e.ok&&n(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",o);else throw o}const r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{const r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}async function xe(e){if(m!==void 0)return m;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0&&(e=new URL(""+new URL("rl_replay_subtr_actor_bg-Xy9_Ya42.wasm",self.location.href).href,self.location.href));const t=be();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));const{instance:n,module:r}=await we(await e,t);return ke(n)}const Z="octane",Ae={breakout:{kind:"breakout",label:"Breakout",length:131.4924,width:80.521,height:30.3,slopeDegrees:-.9795,groundHeightFront:43.8976,groundHeightBack:46.1454,offset:13.88,elevation:17.05},dominus:{kind:"dominus",label:"Dominus",length:127.9268,width:83.27995,height:31.3,slopeDegrees:-.9635,groundHeightFront:47.2238,groundHeightBack:49.3749,offset:13.88,elevation:17.05},hybrid:{kind:"hybrid",label:"Hybrid",length:127.0192,width:82.18787,height:34.15907,slopeDegrees:-.5499,groundHeightFront:54.0982,groundHeightBack:55.3173,offset:13.88,elevation:17.05},merc:{kind:"merc",label:"Merc",length:120.72,width:76.71,height:41.66,slopeDegrees:.28,groundHeightFront:60.76,groundHeightBack:61.35,offset:13.88,elevation:17.05},octane:{kind:"octane",label:"Octane",length:118.0074,width:84.19941,height:36.15907,slopeDegrees:-.5518,groundHeightFront:55.1449,groundHeightBack:56.2814,offset:13.88,elevation:17.05},plank:{kind:"plank",label:"Plank",length:128.8198,width:84.67036,height:29.3944,slopeDegrees:-.3447,groundHeightFront:44.998,groundHeightBack:45.773,offset:13.88,elevation:17.05}},ve={"16batmobile":"plank","70dodgechargerrt":"dominus","89batmobile":"dominus","99nissanskylinegtrr34":"hybrid",aftershock:"dominus",animusgp:"breakout",artemis:"plank",artemisg1:"plank",artemisgxt:"plank",astonmartinvalhalla:"breakout",backfire:"octane",backtothefuturetimemachine:"dominus",batmobile1989:"dominus",battlebus:"merc",breakout:"breakout",breakouttypes:"breakout",centio:"plank",centiov17:"plank",cyclone:"breakout",deloreantimemachine:"dominus",diestro:"dominus",dominus:"dominus",dominusgt:"dominus",endo:"hybrid",esper:"hybrid",fast4wd:"octane",fennec:"octane",gazellagt:"dominus",gizmo:"octane",grog:"octane",guardian:"dominus",guardiang1:"dominus",guardiangxt:"dominus",hotshot:"dominus",icecharger:"dominus",imperatordt5:"dominus",jager619rs:"hybrid",jurassicjeepwrangler:"octane",mantis:"plank",marauder:"octane",masamune:"dominus",maverick:"dominus",maverickg1:"dominus",maverickgxt:"dominus",mclaren570s:"dominus",merc:"merc",mr11:"dominus",nimbus:"hybrid",octane:"octane",octanezsr:"octane",paladin:"plank",proteus:"octane",ripper:"dominus",roadhog:"octane",roadhogxl:"octane",samurai:"breakout",scarab:"octane",takumi:"octane",takumirxt:"octane",thedarkknightstumbler:"octane",thedarkknightrisestumbler:"octane",triton:"octane",twinmilliii:"plank",twinzer:"octane",venom:"hybrid",vulcan:"octane",werewolf:"dominus",xdevil:"hybrid",xdevilmk2:"hybrid",zippy:"octane","1966cadillacdeville":"breakout",ace:"breakout",admiral:"dominus",azura:"breakout",behemoth:"merc",beskar:"hybrid",bmwm3e30:"dominus",bmwm2racing:"dominus",bmwm4gt3evo:"dominus",bmw1series:"octane",bmw1seriesrle:"octane",bmwm240i:"dominus",bugatticentodieci:"plank",bumblebee:"dominus",bumblebeecar:"dominus",chevroletastro:"merc",chevroletcorvettestingray:"breakout",chevroletcorvettezr1:"breakout",chryslerpacifica:"hybrid",corlay:"octane",cyberpunkquadra:"breakout",defenderd7xr:"merc",diesel:"breakout",dodgechargerdaytonascatpack:"dominus",dodgerchargerdaytonascatpack:"dominus",dominusneon:"dominus",emperor:"breakout",emperorii:"breakout",emperoriifrozen:"breakout",emperoriiscorched:"breakout",fastfuriousdodgecharger:"dominus",fastandfuriousdodgecharger:"dominus",fastandfuriousdodgechargersrthellcat:"dominus",fastfuriousmazdarx7:"breakout",fastandfuriousmazdarx7:"breakout",fastfuriousnissanskyline:"hybrid",fastandfuriousnissanskyline:"hybrid",fastfuriouspontiacfiero:"hybrid",fastandfuriouspontiacfiero:"hybrid",fenneczrf:"octane",ferrari296gtb:"dominus",ferrarif40:"breakout",fordbroncoraptorrle:"merc",fordf150rle:"octane",fordmustanggtd:"dominus",fordmustangshelbygt500:"dominus",fordmustangmacherle:"octane",fordmustangshelbygt350rrle:"dominus",formula12021:"plank",formula12022:"plank",fuse:"breakout",havoc:"breakout",hearse:"hybrid",homerscar:"dominus",hondacivictyper:"octane",hondacivictyperle:"octane",jackal:"octane",jeepwranglerrubicon:"octane",kitt:"dominus",knightindustries2000:"dominus",komodo:"breakout",lamborghinicountachlpi8004:"dominus",lamborghinihuracansto:"dominus",lamborghiniurus:"hybrid",lamborghiniurusse:"hybrid",lightningmcqueen:"dominus",lightningmcqueencar:"dominus",lockjaw:"dominus",luiginsr:"octane",maestro:"dominus",magnifique:"dominus",magnifiquegxt:"dominus",mako:"breakout",mamba:"dominus",mario:"octane",marionsr:"octane",maven:"dominus",mclaren765lt:"dominus",mclarenp1:"dominus",mclarensenna:"breakout",megastar:"breakout",mercedesamggt63s:"dominus",mercedesbenzcla:"dominus",mudcat:"octane",mudcatg1:"octane",mudcatgxt:"octane",nissan350z:"dominus",nissanfairladyz:"dominus",nissanfairladyzrle:"dominus",nissansilvia:"hybrid",nissansilviarle:"hybrid",nissanskylinegtr:"hybrid",nissanskylinegtrr32:"hybrid",nissanzperformance:"dominus",nissanzperformancecar:"dominus",outlaw:"octane",outlawgxt:"octane",pattywagon:"octane",pizzaplanetdeliverytruck:"merc",pontiacfirebird:"breakout",porsche918spyder:"breakout",porsche911gt3rs:"dominus",porsche911turbo:"dominus",porsche911turborle:"dominus",primo:"hybrid",psyclops:"octane",quadraturbor:"breakout",ram1500rho:"hybrid",recoilav:"merc",redline:"breakout",revolver:"breakout",rivianr1s:"hybrid",scorpion:"dominus",shokunin:"octane",shokuningxt:"octane",stampede:"merc",teslacybertruck:"hybrid",themysterymachine:"merc",theincredibile:"breakout",turtlevan:"merc",voidburn:"hybrid",volkswagengolfgti:"octane",volkswagengolfgtirle:"octane",xentari:"octane",zefira:"dominus",breakoutx:"breakout",nexus:"breakout",nexussc:"breakout",whiplash:"breakout","007sastonmartindbs":"dominus","007sastonmartinvalhalla":"dominus",batmobile2022:"dominus",chikara:"dominus",chikarag1:"dominus",chikaragxt:"dominus",ecto1:"dominus",ecto1ghostbusters:"dominus",fastfuriousdodgechargersrthellcat:"dominus",gazellagthotwheels:"dominus",kittknightrider:"dominus",lamborghinihuracnsto:"dominus",mr11hotwheels:"dominus",nascarchevroletcamaro:"dominus",nascarfordmustang:"dominus",nascartoyotacamry:"dominus",nascarnextgenchevroletcamaro:"dominus",nascarnextgenchevroletcamaro2022:"dominus",nascarnextgenfordmustang:"dominus",nascarnextgenfordmustang2022:"dominus",nascarnextgentoyotacamry:"dominus",nascarnextgentoyotacamry2022:"dominus",nemesis:"dominus",peregrinett:"dominus",perigrinett:"dominus",ronin:"dominus",roning1:"dominus",roningxt:"dominus",samusgunship:"dominus",samusgunshipnintendoexclusive:"dominus",tyranno:"dominus",tyrannogxt:"dominus",insidio:"hybrid",jager619:"hybrid",jger619:"hybrid",jger619rs:"hybrid",r3mx:"hybrid",r3mxgxt:"hybrid",tygris:"hybrid",nomad:"merc",nomadgxt:"merc","007sastonmartindb5":"octane",armadillo:"octane",armadilloxboxexclusive:"octane",boneshaker:"octane",dingo:"octane",fast4wdhotwheels:"octane",harbinger:"octane",harbingergxt:"octane",hogsticker:"octane",hogstickerxboxexclusive:"octane",sweettooth:"octane",sweettoothplaystationexclusive:"octane",thedarkknighttumbler:"octane",batmobile2016:"plank",sentinel:"plank"};function Te(e){const t={};for(const[n,r]of e)for(const o of n)t[o]=r;return t}const Se=Te([[[22,1416,1894,1932,3031,3311,6243,6489,7651,7696,7890,7901,8006,8360,8361,8565,8566,8669,9357,10697,10698,10817,10822,11038,11394,11505,11677,11800,11933,11949,12173,12315,12361,12484],"breakout"],[[29,403,597,600,1018,1171,1286,1675,1689,1883,2070,2268,2666,2950,2951,3155,3156,3157,3265,3426,3875,3879,3880,4014,4155,4367,4472,4473,4745,4770,4781,4861,4864,5709,5773,5823,5858,5964,5979,6122,6244,6247,6260,6836,7211,7337,7338,7341,7343,7415,7512,7532,7593,7772,8454,9053,9088,9089,9140,9388,9894,10094,10440,10441,10694,10695,11016,11095,11315,11336,11534,11941,11996,12106,12142,12262,12286,12325,12382,12563,12669],"dominus"],[[28,31,1159,1317,1624,1856,2269,3451,3582,3702,5470,5488,5879,7012,9084,9085,9427,10044,10805,11138,11141,11379,11932,12569,12652],"hybrid"],[[30,4780,7336,7477,7815,7979,10689,11098,11736,11905,11950,12318,12335],"merc"],[[21,23,25,26,27,402,404,523,607,625,723,1172,1295,1300,1475,1478,1533,1568,1623,2665,2853,2919,2949,4284,4318,4319,4320,4782,4906,5020,5039,5188,5361,5547,5713,5837,5951,6939,7947,7948,8383,8806,8807,10896,10897,10900,10901,11314,11603,12104,12105],"octane"],[[24,803,1603,1691,1919,3594,3614,3622,4268,5265,7052,8524],"plank"]]);function G(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function q(e){if(!e)return null;switch(G(e)){case"breakout":return"breakout";case"dominus":return"dominus";case"hybrid":return"hybrid";case"merc":return"merc";case"octane":return"octane";case"batmobile":case"plank":return"plank";default:return null}}function J(e){return e?ve[G(e)]??null:null}function Oe(e){return q(e)??J(e)}function Ie(e){return Ae[e]}function H(e,t){if(!(!e||typeof e!="object")){if("Str"in e&&typeof e.Str=="string"){t.push(e.Str);return}if("Name"in e&&typeof e.Name=="string"){t.push(e.Name);return}if("Byte"in e&&e.Byte&&typeof e.Byte=="object"){const n=e.Byte;typeof n.kind=="string"&&t.push(n.kind),typeof n.value=="string"&&t.push(n.value);return}if("Struct"in e&&e.Struct&&typeof e.Struct=="object"){const n=e.Struct;if(typeof n.name=="string"&&t.push(n.name),Array.isArray(n.fields))for(const r of n.fields)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),H(r[1],t));return}if("Array"in e&&Array.isArray(e.Array)){for(const n of e.Array)if(Array.isArray(n))for(const r of n)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),H(r[1],t))}}}function Pe(e){const t=q(e?.car_hitbox_family);if(t)return t;const n=e?.car_body_id;if(typeof n=="number"){const a=Se[n];if(a)return a}const r=J(e?.car_body_name);if(r)return r;const o=e?.stats;if(!o)return Z;const i=[];for(const[a,s]of Object.entries(o))i.push(a),H(s,i);for(const a of i){const s=Oe(a);if(s)return s}return Z}function k(e){const[t,n]=Object.entries(e)[0]??["Unknown","unknown"];return typeof n=="string"||typeof n=="number"?`${t}:${n}`:n&&typeof n=="object"?`${t}:${JSON.stringify(n)}`:`${t}:${JSON.stringify(n)}`}function E(e,t){return Math.max(0,e-t)}function Q(e){return new Map(e.map(t=>[t.id,t]))}const g=70,ee=73,Be=3072,Ee=4096,De=1792,Re=4184,Me=940,Ne=3308,ze=2816,te=3584,Fe=2484,Ce=1788,Le=2300,Ve=2048,je=1036,He=1024,Ue=1024,Ye=4240,ne=34;function N(e,t,n,r,o){e.push({index:e.length,padId:null,size:o,position:{x:t,y:n,z:r},events:[]})}function z(e,t,n,r,o){N(e,-t,n,r,o),N(e,t,n,r,o)}function U(e,t,n,r,o){N(e,t,-n,r,o),N(e,t,n,r,o)}function O(e,t,n,r,o){z(e,t,-n,r,o),z(e,t,n,r,o)}function $e(){const e=[];return U(e,0,Ye,g,"small"),O(e,De,Re,g,"small"),O(e,Be,Ee,ee,"big"),O(e,Me,Ne,g,"small"),U(e,0,ze,g,"small"),O(e,te,Fe,g,"small"),O(e,Ce,Le,g,"small"),O(e,Ve,je,g,"small"),U(e,0,Ue,g,"small"),z(e,te,0,ee,"big"),z(e,He,0,g,"small"),e}function Y(e){if(e==="Available")return!0;if(e&&typeof e=="object"){if("Available"in e)return!0;if("PickedUp"in e)return!1;const t=e.kind;if(t==="Available")return!0;if(t==="PickedUp")return!1}return null}function Xe(e){return e==="big"||e==="Big"?"big":e==="small"||e==="Small"?"small":null}function We(e){let t=null;for(const n of e){const r=Y(n.kind);if(r===!1){t=n.time;continue}if(r===!0&&t!==null)return n.time-t>=7?"big":"small"}return null}function Ke(e,t,n,r){const o=Q(t),i=new Map;for(const c of e.boost_pad_events??[]){if(Y(c.kind)===null){r?.advance();continue}const u=i.get(c.pad_id);u?u.push(c):i.set(c.pad_id,[c]),r?.advance()}const a=e.boost_pads;if(!a||a.length===0)return r?.advance(ne),$e();const s=[...a].sort((c,d)=>c.index-d.index),l=new Array(s.length);for(let c=0;c=72?"big":"small"),p=y.sort((b,h)=>b.time-h.time),f=new Array(p.length);for(let b=0;b=0?e.frame:null}function Ze(e,t){if(typeof e.time=="number"&&Number.isFinite(e.time))return e.time;const n=$(e);if(n===null)return null;const r=t.frame_data.metadata_frames[n]?.time;return typeof r=="number"&&Number.isFinite(r)?r:null}function Ge(e,t){return`bookmark:${$(e)??"unknown"}:${e.description||"tick-mark"}:${t}`}function qe(e,t,n){return(e.replay_tick_marks??[]).flatMap((r,o)=>{n?.advance();const i=Ze(r,e);return i===null?[]:[{id:Ge(r,o),description:r.description,frame:$(r),time:E(i,t)}]})}function Je(e){const t=e.description.trim()||"Replay bookmark";return{id:e.id,time:e.time,seekTime:e.time,frame:e.frame??void 0,kind:"bookmark",label:t,shortLabel:"BM",iconName:"bookmark"}}const A={distance:270,height:100,pitch:-4,fov:110},Qe=.005,et=Number.POSITIVE_INFINITY,tt=!0,nt=.15,rt=10,ot=.1,at=10;function re(e){const t=Math.hypot(e.x,e.y,e.z);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t}}function oe(e){const t=Math.hypot(e.x,e.y,e.z,e.w);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t,w:e.w/t}}function ae(e,t){return{w:e.w*t.w-e.x*t.x-e.y*t.y-e.z*t.z,x:e.w*t.x+e.x*t.w+e.y*t.z-e.z*t.y,y:e.w*t.y-e.x*t.z+e.y*t.w+e.z*t.x,z:e.w*t.z+e.x*t.y-e.y*t.x+e.z*t.w}}function ie(e,t){const n=ae(ae(t,{x:e.x,y:e.y,z:e.z,w:0}),{x:-t.x,y:-t.y,z:-t.z,w:t.w});return{x:n.x,y:n.y,z:n.z}}function it(e){if(e==="Empty")return{position:null,linearVelocity:null,angularVelocity:null,rotation:null};const t=e.Data.rigid_body;return{position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:oe(t.rotation)}}function se(e){return e==null?null:Math.max(-1,Math.min(1,(e-128)/128))}function ce(e){return e==null?null:(e>127?e-256:e)*Math.PI/128}function le(e){return e?{x:e[0],y:e[1],z:e[2]}:null}const st={cameraPitch:null,cameraYaw:null,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null};function ct(e){if(e==="Empty")return{isPresent:!1,position:null,linearVelocity:null,angularVelocity:null,rotation:null,forward:null,up:null,boostAmount:0,boostFraction:0,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,...st};const t=e.Data.rigid_body,n=oe(t.rotation),r=n?re(ie({x:1,y:0,z:0},n)):null,o=n?re(ie({x:0,y:0,z:1},n)):null,i=e.Data.camera,a=e.Data.input;return{isPresent:!0,position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:n,forward:r,up:o,boostAmount:e.Data.boost_amount,boostFraction:Math.max(0,Math.min(1,e.Data.boost_amount/255)),boostActive:e.Data.boost_active,powerslideActive:e.Data.powerslide_active,jumpActive:e.Data.jump_active,doubleJumpActive:e.Data.double_jump_active,dodgeActive:e.Data.dodge_active,cameraPitch:ce(i?.pitch),cameraYaw:ce(i?.yaw),throttle:se(a?.throttle),steer:se(a?.steer),dodgeImpulse:le(a?.dodge_impulse),dodgeTorque:le(a?.dodge_torque)}}function lt(e){return e.position!==null}function ut(e){return{...e,isPresent:!1,linearVelocity:null,angularVelocity:null,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null}}function mt(e){let t=null,n=null;for(let r=0;r=t.length-1)return;let o=D(t[r].position);for(let i=r+1;iot){o=D(s.position);continue}if(dt(o,s.position)>at){o=D(s.position);continue}const u={x:(a.linearVelocity.x+s.linearVelocity.x)/2,y:(a.linearVelocity.y+s.linearVelocity.y)/2,z:(a.linearVelocity.z+s.linearVelocity.z)/2},y={x:o.x+u.x*d,y:o.y+u.y*d,z:o.z+u.z*d},_=(i-r)%n.smoothingAnchorInterval===0?.5:n.smoothingBlendFactor;o={x:y.x*(1-_)+s.position.x*_,y:y.y*(1-_)+s.position.y*_,z:y.z*(1-_)+s.position.z*_},s.position=D(o)}}function ft(e){return{motionSmoothing:e.motionSmoothing??tt,smoothingBlendFactor:e.smoothingBlendFactor??nt,smoothingAnchorInterval:Math.max(1,e.smoothingAnchorInterval??rt)}}function de(){return typeof performance>"u"?Date.now():performance.now()}function bt(e){const t=e.meta.team_zero.length+e.meta.team_one.length,n=e.frame_data.players.reduce((a,[,s])=>a+s.frames.length,0),r=e.boost_pads?.length??ne,o=e.boost_pad_events?.length??0,i=(e.goal_events?.length??0)+(e.player_stat_events?.length??0)+(e.demolish_infos?.length??0)+(e.replay_tick_marks?.length??0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,n),Math.max(1,e.frame_data.ball_data.frames.length),Math.max(1,r+o),Math.max(1,i)].reduce((a,s)=>a+s,0)}function _t(e){const t=e.frame_data.players.reduce((n,[,r])=>n+r.frames.length,0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,e.frame_data.ball_data.frames.length)].reduce((n,r)=>n+r,0)}function yt(e,t,n={}){const r=bt(e),o=_t(e);let i=0,a=0,s=-1,l=-1,c=de();const d=n.yieldEveryMs??Number.POSITIVE_INFINITY,u=n.progressReportMinDelta??Qe,y=Math.max(1,n.progressReportFrameInterval??et),_=()=>{if(!t)return!1;const f=Math.max(0,Math.min(1,i/r));if(f<=s)return!1;const h=a-l>=y;return f>=1||f-s>=u||h?(s=f,l=a,t(f,{progress:f,processedFrames:Math.min(a,o),totalFrames:o,processedUnits:i,totalUnits:r}),!0):!1},p=(f=!1)=>{const b=de();return!f&&b-cr===t)?.[1];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function kt(e){const t=ht(e?.stats);return{fov:v(t,"CameraFOV")??A.fov,height:v(t,"CameraHeight")??A.height,pitch:v(t,"CameraPitch")??A.pitch,distance:v(t,"CameraDistance")??A.distance,stiffness:v(t,"CameraStiffness")??A.stiffness,swivelSpeed:v(t,"CameraSwivelSpeed")??A.swivelSpeed,transitionSpeed:v(t,"CameraTransitionSpeed")??A.transitionSpeed}}function wt(e,t){const n=new Map,r=new Map,o=[...e.meta.team_zero,...e.meta.team_one];if(o.length===0)return t?.advance(),{byId:n,byName:r};for(const i of o)r.set(i.name,i),i.remote_id&&n.set(k(i.remote_id),i),t?.advance();return{byId:n,byName:r}}function xt(e){const t=new Map;for(const[n,r]of e.player_camera_events??[])t.set(k(n),r.map(o=>({frame:o.frame,ballCamActive:o.ball_cam_active,behindViewActive:o.behind_view_active,driving:o.driving})));return t}function At(e,t){const n=new Set(e.meta.team_zero.map(l=>l.name)),r=new Set(e.meta.team_one.map(l=>l.name)),o=wt(e,t),i=xt(e),a=[];let s=0;for(const[l,c]of e.frame_data.players){const d=new Array(c.frames.length);let u;for(let f=0;ft.time!==n.time?t.time-n.time:(t.frame??0)-(n.frame??0))}function St(e,t,n){const r=e.player?k(e.player):null,o=r?t.get(r)?.name??r:null,i=o?`${o} scored`:"Goal";return{id:X("goal",e.frame,r??"team"),time:E(e.time,n),frame:e.frame,kind:"goal",label:i,shortLabel:"G",playerId:r,playerName:o,isTeamZero:e.scoring_team_is_team_0}}function Ot(e,t,n){const r=k(e.player),o=t.get(r)?.name??r,i=e.kind.toLowerCase(),a=e.kind==="Shot"?"shot":e.kind==="Save"?"save":"assist",s=e.kind==="Shot"?"SH":e.kind==="Save"?"SV":"A";return{id:X(i,e.frame,r),time:E(e.time,n),frame:e.frame,kind:i,label:`${o} ${a}`,shortLabel:s,playerId:r,playerName:o,location:e.shot?.shot_touch_position??e.shot?.ball_position??null,shot:e.shot??null,isTeamZero:e.is_team_0}}function It(e,t,n){const r=k(e.attacker),o=k(e.victim),i=t.get(r),a=t.get(o);return{id:X("demo",e.frame,`${r}:${o}`),time:E(e.time,n),frame:e.frame,kind:"demo",label:`${i?.name??r} demoed ${a?.name??o}`,shortLabel:"D",playerId:r,playerName:i?.name??r,secondaryPlayerId:o,secondaryPlayerName:a?.name??o,location:e.victim_location,isTeamZero:i?.isTeamZero??null}}function Pt(e,t,n,r,o){const i=Q(t),a=[];for(const s of e.goal_events??[])a.push(St(s,i,r)),o?.advance();for(const s of e.player_stat_events??[])a.push(Ot(s,i,r)),o?.advance();for(const s of e.demolish_infos??[])a.push(It(s,i,r)),o?.advance();for(const s of n)a.push(Je(s));return a.length===0&&o?.advance(),Tt(a)}function Bt(e,t={}){const n=yt(e,t.onProgress,{progressReportMinDelta:t.progressReportMinDelta,progressReportFrameInterval:t.progressReportFrameInterval}),r=e.frame_data.metadata_frames[0]?.time??0,o=gt(e,n),i=At(e,n),a=vt(e,n),s=ft(t);me(o,a,s);for(const u of i)me(o,u.frames,s);const l=Ke(e,i,r,n),c=qe(e,r,n),d=Pt(e,i,c,r,n);return n.finish(),{frameCount:o.length,duration:o.at(-1)?.time??0,rawStartTime:r,frames:o,ballFrames:a,boostPads:l,players:i,tickMarks:c,timelineEvents:d,teamZeroNames:e.meta.team_zero.map(u=>u.name),teamOneNames:e.meta.team_one.map(u=>u.name)}}function F(e){if(e instanceof Map)return Object.fromEntries(Array.from(e.entries()).map(([t,n])=>[t,F(n)]));if(Array.isArray(e))return e.map(t=>F(t));if(e&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=F(r);return t}return e}async function Et(){const e=xe;typeof e=="function"&&await e()}function R(e){self.postMessage(e)}self.onmessage=async e=>{if(e.data.type==="load-replay")try{await Et();const t=new Uint8Array(e.data.bytes);R({type:"progress",progress:{stage:"validating",progress:0}});const n=fe(t,c=>{R({type:"progress",progress:F(c)})},e.data.reportEveryNFrames,32*1024*1024);R({type:"progress",progress:{stage:"normalizing",progress:0}});const r=JSON.parse(new TextDecoder().decode(n.rawReplayData)),o=Bt(r,{progressReportFrameInterval:e.data.reportEveryNFrames,onProgress(c){R({type:"progress",progress:{stage:"normalizing",progress:c}})}}),i=new TextEncoder().encode(JSON.stringify(o)),a=n.rawReplayData,s=a.byteOffset===0&&a.byteLength===a.buffer.byteLength?a.buffer:a.slice().buffer,l=Array.from(n.statsTimelineParts.frameChunks,c=>c.buffer);self.postMessage({type:"done",replayBuffer:i.buffer,rawReplayBuffer:s,statsTimelineParts:{configBuffer:n.statsTimelineParts.config.buffer,replayMetaBuffer:n.statsTimelineParts.replayMeta.buffer,eventsBuffer:n.statsTimelineParts.events.buffer,activitySummaryBuffer:n.statsTimelineParts.activitySummary.buffer,positioningSummaryBuffer:n.statsTimelineParts.positioningSummary.buffer,accumulationTracksBuffer:n.statsTimelineParts.accumulationTracks.buffer,frameChunkBuffers:l}},[i.buffer,s,n.statsTimelineParts.config.buffer,n.statsTimelineParts.replayMeta.buffer,n.statsTimelineParts.events.buffer,n.statsTimelineParts.activitySummary.buffer,n.statsTimelineParts.positioningSummary.buffer,n.statsTimelineParts.accumulationTracks.buffer,...l])}catch(t){R({type:"error",error:t instanceof Error?t.message:String(t)})}}})(); diff --git a/crates/rocket-sense-server/static/subtr-actor/stats/assets/rl_replay_subtr_actor-Cnltgw4Z.js b/crates/rocket-sense-server/static/subtr-actor/stats/assets/rl_replay_subtr_actor-Cnltgw4Z.js new file mode 100644 index 00000000..d2cb4f7d --- /dev/null +++ b/crates/rocket-sense-server/static/subtr-actor/stats/assets/rl_replay_subtr_actor-Cnltgw4Z.js @@ -0,0 +1,2 @@ +function U(r,n){var e=g(r)?0:k(r,_.__wbindgen_malloc),t=a,i=g(n)?0:k(n,_.__wbindgen_malloc),c=a;const o=_.get_column_headers(e,t,i,c);if(o[2])throw s(o[1]);return s(o[0])}function B(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.get_legacy_stats_timeline_json(n,e);if(t[3])throw s(t[2]);var i=v(t[0],t[1]).slice();return _.__wbindgen_free(t[0],t[1]*1,1),i}function D(r,n,e,t){const i=w(r,_.__wbindgen_malloc),c=a;var o=g(n)?0:k(n,_.__wbindgen_malloc),l=a,f=g(e)?0:k(e,_.__wbindgen_malloc),u=a;const p=_.get_ndarray_with_info(i,c,o,l,f,u,g(t)?4294967297:Math.fround(t));if(p[2])throw s(p[1]);return s(p[0])}function N(r,n,e,t){const i=w(r,_.__wbindgen_malloc),c=a,o=_.get_replay_bundle_json_parts_with_progress(i,c,n,g(e)?4294967297:e>>>0,g(t)?4294967297:t>>>0);if(o[2])throw s(o[1]);return s(o[0])}function L(r,n,e){const t=w(r,_.__wbindgen_malloc),i=a,c=_.get_replay_bundle_json_with_progress(t,i,n,g(e)?4294967297:e>>>0);if(c[2])throw s(c[1]);return s(c[0])}function $(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.get_replay_frames_data(n,e);if(t[2])throw s(t[1]);return s(t[0])}function V(r,n,e){const t=w(r,_.__wbindgen_malloc),i=a,c=_.get_replay_frames_data_json_with_progress(t,i,n,g(e)?4294967297:e>>>0);if(c[3])throw s(c[2]);var o=v(c[0],c[1]).slice();return _.__wbindgen_free(c[0],c[1]*1,1),o}function q(r,n,e){const t=w(r,_.__wbindgen_malloc),i=a,c=_.get_replay_frames_data_with_progress(t,i,n,g(e)?4294967297:e>>>0);if(c[2])throw s(c[1]);return s(c[0])}function z(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.get_replay_info(n,e);if(t[2])throw s(t[1]);return s(t[0])}function C(r,n,e){const t=w(r,_.__wbindgen_malloc),i=a;var c=g(n)?0:k(n,_.__wbindgen_malloc),o=a,l=g(e)?0:k(e,_.__wbindgen_malloc),f=a;const u=_.get_replay_meta(t,i,c,o,l,f);if(u[2])throw s(u[1]);return s(u[0])}function J(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.get_stats_timeline(n,e);if(t[2])throw s(t[1]);return s(t[0])}function P(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.get_stats_timeline_json(n,e);if(t[3])throw s(t[2]);var i=v(t[0],t[1]).slice();return _.__wbindgen_free(t[0],t[1]*1,1),i}function H(r,n){const e=w(r,_.__wbindgen_malloc),t=a,i=_.get_stats_timeline_json_parts(e,t,g(n)?4294967297:n>>>0);if(i[2])throw s(i[1]);return s(i[0])}function K(){_.main()}function X(r){let n,e;try{const c=_.new_training_pack(r);var t=c[0],i=c[1];if(c[3])throw t=0,i=0,s(c[2]);return n=t,e=i,b(t,i)}finally{_.__wbindgen_free(n,e,1)}}function Y(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.parse_replay(n,e);if(t[2])throw s(t[1]);return s(t[0])}function G(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.parse_training_pack(n,e);if(t[2])throw s(t[1]);return s(t[0])}function Q(r){let n,e;try{const c=w(r,_.__wbindgen_malloc),o=a,l=_.parse_training_pack_lossless(c,o);var t=l[0],i=l[1];if(l[3])throw t=0,i=0,s(l[2]);return n=t,e=i,b(t,i)}finally{_.__wbindgen_free(n,e,1)}}function Z(r){const n=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),e=a,t=_.serialize_training_pack(n,e);if(t[3])throw s(t[2]);var i=v(t[0],t[1]).slice();return _.__wbindgen_free(t[0],t[1]*1,1),i}function nn(r,n){let e,t;try{const o=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),l=a,f=_.training_pack_add_round(o,l,n);var i=f[0],c=f[1];if(f[3])throw i=0,c=0,s(f[2]);return e=i,t=c,b(i,c)}finally{_.__wbindgen_free(e,t,1)}}function en(r,n,e){let t,i;try{const l=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),f=a,u=_.training_pack_add_round_archetype(l,f,n,e);var c=u[0],o=u[1];if(u[3])throw c=0,o=0,s(u[2]);return t=c,i=o,b(c,o)}finally{_.__wbindgen_free(t,i,1)}}function tn(r,n){let e,t;try{const o=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),l=a,f=d(n,_.__wbindgen_malloc,_.__wbindgen_realloc),u=a,p=_.training_pack_append_rounds(o,l,f,u);var i=p[0],c=p[1];if(p[3])throw i=0,c=0,s(p[2]);return e=i,t=c,b(i,c)}finally{_.__wbindgen_free(e,t,1)}}function rn(r,n){let e,t;try{const o=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),l=a,f=_.training_pack_duplicate_round(o,l,n);var i=f[0],c=f[1];if(f[3])throw i=0,c=0,s(f[2]);return e=i,t=c,b(i,c)}finally{_.__wbindgen_free(e,t,1)}}function _n(r){const n=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),e=a,t=_.training_pack_from_lossless(n,e);if(t[2])throw s(t[1]);return s(t[0])}function cn(r,n,e){let t,i;try{const l=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),f=a,u=_.training_pack_insert_round(l,f,n,e);var c=u[0],o=u[1];if(u[3])throw c=0,o=0,s(u[2]);return t=c,i=o,b(c,o)}finally{_.__wbindgen_free(t,i,1)}}function on(r,n,e){let t,i;try{const l=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),f=a,u=_.training_pack_move_round(l,f,n,e);var c=u[0],o=u[1];if(u[3])throw c=0,o=0,s(u[2]);return t=c,i=o,b(c,o)}finally{_.__wbindgen_free(t,i,1)}}function sn(r,n){let e,t;try{const o=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),l=a,f=_.training_pack_remove_round(o,l,n);var i=f[0],c=f[1];if(f[3])throw i=0,c=0,s(f[2]);return e=i,t=c,b(i,c)}finally{_.__wbindgen_free(e,t,1)}}function an(r,n,e){let t,i;try{const l=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),f=a,u=_.training_pack_remove_round_archetype(l,f,n,e);var c=u[0],o=u[1];if(u[3])throw c=0,o=0,s(u[2]);return t=c,i=o,b(c,o)}finally{_.__wbindgen_free(t,i,1)}}function fn(r,n){const e=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),t=a,i=_.training_pack_round_archetypes(e,t,n);if(i[2])throw s(i[1]);return s(i[0])}function ln(r,n,e,t){let i,c;try{const f=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),u=a,p=_.training_pack_set_round_archetype(f,u,n,e,t);var o=p[0],l=p[1];if(p[3])throw o=0,l=0,s(p[2]);return i=o,c=l,b(o,l)}finally{_.__wbindgen_free(i,c,1)}}function un(r,n,e){let t,i;try{const l=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),f=a,u=_.training_pack_set_round_ball(l,f,n,e);var c=u[0],o=u[1];if(u[3])throw c=0,o=0,s(u[2]);return t=c,i=o,b(c,o)}finally{_.__wbindgen_free(t,i,1)}}function dn(r,n,e){let t,i;try{const l=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),f=a,u=_.training_pack_set_round_time_limit(l,f,n,e);var c=u[0],o=u[1];if(u[3])throw c=0,o=0,s(u[2]);return t=c,i=o,b(c,o)}finally{_.__wbindgen_free(t,i,1)}}function gn(r,n){let e,t;try{const o=d(r,_.__wbindgen_malloc,_.__wbindgen_realloc),l=a,f=_.update_training_pack_metadata(o,l,n);var i=f[0],c=f[1];if(f[3])throw i=0,c=0,s(f[2]);return e=i,t=c,b(i,c)}finally{_.__wbindgen_free(e,t,1)}}function bn(r){const n=w(r,_.__wbindgen_malloc),e=a,t=_.validate_replay(n,e);if(t[2])throw s(t[1]);return s(t[0])}function O(){return{__proto__:null,"./rl_replay_subtr_actor_bg.js":{__proto__:null,__wbg_Error_8c4e43fe74559d73:function(n,e){return Error(b(n,e))},__wbg_Number_04624de7d0e8332d:function(n){return Number(n)},__wbg_String_8f0eb39a4a4c2f66:function(n,e){const t=String(e),i=d(t,_.__wbindgen_malloc,_.__wbindgen_realloc),c=a;y().setInt32(n+4,c,!0),y().setInt32(n+0,i,!0)},__wbg___wbindgen_bigint_get_as_i64_8fcf4ce7f1ca72a2:function(n,e){const t=e,i=typeof t=="bigint"?t:void 0;y().setBigInt64(n+8,g(i)?BigInt(0):i,!0),y().setInt32(n+0,!g(i),!0)},__wbg___wbindgen_boolean_get_bbbb1c18aa2f5e25:function(n){const e=n,t=typeof e=="boolean"?e:void 0;return g(t)?16777215:t?1:0},__wbg___wbindgen_debug_string_0bc8482c6e3508ae:function(n,e){const t=M(e),i=d(t,_.__wbindgen_malloc,_.__wbindgen_realloc),c=a;y().setInt32(n+4,c,!0),y().setInt32(n+0,i,!0)},__wbg___wbindgen_in_47fa6863be6f2f25:function(n,e){return n in e},__wbg___wbindgen_is_bigint_31b12575b56f32fc:function(n){return typeof n=="bigint"},__wbg___wbindgen_is_function_0095a73b8b156f76:function(n){return typeof n=="function"},__wbg___wbindgen_is_object_5ae8e5880f2c1fbd:function(n){const e=n;return typeof e=="object"&&e!==null},__wbg___wbindgen_is_string_cd444516edc5b180:function(n){return typeof n=="string"},__wbg___wbindgen_is_undefined_9e4d92534c42d778:function(n){return n===void 0},__wbg___wbindgen_jsval_eq_11888390b0186270:function(n,e){return n===e},__wbg___wbindgen_jsval_loose_eq_9dd77d8cd6671811:function(n,e){return n==e},__wbg___wbindgen_number_get_8ff4255516ccad3e:function(n,e){const t=e,i=typeof t=="number"?t:void 0;y().setFloat64(n+8,g(i)?0:i,!0),y().setInt32(n+0,!g(i),!0)},__wbg___wbindgen_string_get_72fb696202c56729:function(n,e){const t=e,i=typeof t=="string"?t:void 0;var c=g(i)?0:d(i,_.__wbindgen_malloc,_.__wbindgen_realloc),o=a;y().setInt32(n+4,o,!0),y().setInt32(n+0,c,!0)},__wbg___wbindgen_throw_be289d5034ed271b:function(n,e){throw new Error(b(n,e))},__wbg_call_389efe28435a9388:function(){return A(function(n,e){return n.call(e)},arguments)},__wbg_call_4708e0c13bdc8e95:function(){return A(function(n,e,t){return n.call(e,t)},arguments)},__wbg_done_57b39ecd9addfe81:function(n){return n.done},__wbg_entries_58c7934c745daac7:function(n){return Object.entries(n)},__wbg_error_7534b8e9a36f1ab4:function(n,e){let t,i;try{t=n,i=e,console.error(b(n,e))}finally{_.__wbindgen_free(t,i,1)}},__wbg_get_9b94d73e6221f75c:function(n,e){return n[e>>>0]},__wbg_get_b3ed3ad4be2bc8ac:function(){return A(function(n,e){return Reflect.get(n,e)},arguments)},__wbg_get_with_ref_key_1dc361bd10053bfe:function(n,e){return n[e]},__wbg_instanceof_ArrayBuffer_c367199e2fa2aa04:function(n){let e;try{e=n instanceof ArrayBuffer}catch{e=!1}return e},__wbg_instanceof_Map_53af74335dec57f4:function(n){let e;try{e=n instanceof Map}catch{e=!1}return e},__wbg_instanceof_Uint8Array_9b9075935c74707c:function(n){let e;try{e=n instanceof Uint8Array}catch{e=!1}return e},__wbg_isArray_d314bb98fcf08331:function(n){return Array.isArray(n)},__wbg_isSafeInteger_bfbc7332a9768d2a:function(n){return Number.isSafeInteger(n)},__wbg_iterator_6ff6560ca1568e55:function(){return Symbol.iterator},__wbg_length_32ed9a279acd054c:function(n){return n.length},__wbg_length_35a7bace40f36eac:function(n){return n.length},__wbg_log_f1a1b5cd3f9c7822:function(n,e){console.log(b(n,e))},__wbg_new_361308b2356cecd0:function(){return new Object},__wbg_new_3eb36ae241fe6f44:function(){return new Array},__wbg_new_8a6f238a6ece86ea:function(){return new Error},__wbg_new_dca287b076112a51:function(){return new Map},__wbg_new_dd2b680c8bf6ae29:function(n){return new Uint8Array(n)},__wbg_new_from_slice_a3d2629dc1826784:function(n,e){return new Uint8Array(v(n,e))},__wbg_next_3482f54c49e8af19:function(){return A(function(n){return n.next()},arguments)},__wbg_next_418f80d8f5303233:function(n){return n.next},__wbg_prototypesetcall_bdcdcc5842e4d77d:function(n,e,t){Uint8Array.prototype.set.call(v(n,e),t)},__wbg_push_8ffdcb2063340ba5:function(n,e){return n.push(e)},__wbg_set_1eb0999cf5d27fc8:function(n,e,t){return n.set(e,t)},__wbg_set_3f1d0b984ed272ed:function(n,e,t){n[e]=t},__wbg_set_6cb8631f80447a67:function(){return A(function(n,e,t){return Reflect.set(n,e,t)},arguments)},__wbg_set_f43e577aea94465b:function(n,e,t){n[e>>>0]=t},__wbg_stack_0ed75d68575b0f3c:function(n,e){const t=e.stack,i=d(t,_.__wbindgen_malloc,_.__wbindgen_realloc),c=a;y().setInt32(n+4,c,!0),y().setInt32(n+0,i,!0)},__wbg_value_0546255b415e96c1:function(n){return n.value},__wbindgen_cast_0000000000000001:function(n){return n},__wbindgen_cast_0000000000000002:function(n){return n},__wbindgen_cast_0000000000000003:function(n,e){return b(n,e)},__wbindgen_cast_0000000000000004:function(n){return BigInt.asUintN(64,n)},__wbindgen_init_externref_table:function(){const n=_.__wbindgen_externrefs,e=n.grow(4);n.set(0,void 0),n.set(e+0,void 0),n.set(e+1,null),n.set(e+2,!0),n.set(e+3,!1)}}}}function W(r){const n=_.__externref_table_alloc();return _.__wbindgen_externrefs.set(n,r),n}function M(r){const n=typeof r;if(n=="number"||n=="boolean"||r==null)return`${r}`;if(n=="string")return`"${r}"`;if(n=="symbol"){const i=r.description;return i==null?"Symbol":`Symbol(${i})`}if(n=="function"){const i=r.name;return typeof i=="string"&&i.length>0?`Function(${i})`:"Function"}if(Array.isArray(r)){const i=r.length;let c="[";i>0&&(c+=M(r[0]));for(let o=1;o1)t=e[1];else return toString.call(r);if(t=="Object")try{return"Object("+JSON.stringify(r)+")"}catch{return"Object"}return r instanceof Error?`${r.name}: ${r.message} +${r.stack}`:t}function v(r,n){return r=r>>>0,h().subarray(r/1,r/1+n)}let m=null;function y(){return(m===null||m.buffer.detached===!0||m.buffer.detached===void 0&&m.buffer!==_.memory.buffer)&&(m=new DataView(_.memory.buffer)),m}function b(r,n){return r=r>>>0,F(r,n)}let j=null;function h(){return(j===null||j.byteLength===0)&&(j=new Uint8Array(_.memory.buffer)),j}function A(r,n){try{return r.apply(this,n)}catch(e){const t=W(e);_.__wbindgen_exn_store(t)}}function g(r){return r==null}function w(r,n){const e=n(r.length*1,1)>>>0;return h().set(r,e/1),a=r.length,e}function k(r,n){const e=n(r.length*4,4)>>>0;for(let t=0;t>>0;return h().subarray(f,f+l.length).set(l),a=l.length,f}let t=r.length,i=n(t,1)>>>0;const c=h();let o=0;for(;o127)break;c[i+o]=l}if(o!==t){o!==0&&(r=r.slice(o)),i=e(i,t,t=o+r.length*3,1)>>>0;const l=h().subarray(i+o,i+t),f=x.encodeInto(r,l);o+=f.written,i=e(i,t,o,1)>>>0}return a=o,i}function s(r){const n=_.__wbindgen_externrefs.get(r);return _.__externref_table_dealloc(r),n}let I=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});I.decode();const T=2146435072;let S=0;function F(r,n){return S+=n,S>=T&&(I=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),I.decode(),S=n),I.decode(h().subarray(r,r+n))}const x=new TextEncoder;"encodeInto"in x||(x.encodeInto=function(r,n){const e=x.encode(r);return n.set(e),{read:r.length,written:e.length}});let a=0,_;function E(r,n){return _=r.exports,m=null,j=null,_.__wbindgen_start(),_}async function R(r,n){if(typeof Response=="function"&&r instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(r,n)}catch(i){if(r.ok&&e(r.type)&&r.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",i);else throw i}const t=await r.arrayBuffer();return await WebAssembly.instantiate(t,n)}else{const t=await WebAssembly.instantiate(r,n);return t instanceof WebAssembly.Instance?{instance:t,module:r}:t}function e(t){switch(t){case"basic":case"cors":case"default":return!0}return!1}}function wn(r){if(_!==void 0)return _;r!==void 0&&(Object.getPrototypeOf(r)===Object.prototype?{module:r}=r:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));const n=O();r instanceof WebAssembly.Module||(r=new WebAssembly.Module(r));const e=new WebAssembly.Instance(r,n);return E(e)}async function pn(r){if(_!==void 0)return _;r!==void 0&&(Object.getPrototypeOf(r)===Object.prototype?{module_or_path:r}=r:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),r===void 0&&(r=new URL(""+new URL("rl_replay_subtr_actor_bg-BjSK7HJ9.wasm",import.meta.url).href,import.meta.url));const n=O();(typeof r=="string"||typeof Request=="function"&&r instanceof Request||typeof URL=="function"&&r instanceof URL)&&(r=fetch(r));const{instance:e,module:t}=await R(await r,n);return E(e)}export{pn as default,U as get_column_headers,B as get_legacy_stats_timeline_json,D as get_ndarray_with_info,N as get_replay_bundle_json_parts_with_progress,L as get_replay_bundle_json_with_progress,$ as get_replay_frames_data,V as get_replay_frames_data_json_with_progress,q as get_replay_frames_data_with_progress,z as get_replay_info,C as get_replay_meta,J as get_stats_timeline,P as get_stats_timeline_json,H as get_stats_timeline_json_parts,wn as initSync,K as main,X as new_training_pack,Y as parse_replay,G as parse_training_pack,Q as parse_training_pack_lossless,Z as serialize_training_pack,nn as training_pack_add_round,en as training_pack_add_round_archetype,tn as training_pack_append_rounds,rn as training_pack_duplicate_round,_n as training_pack_from_lossless,cn as training_pack_insert_round,on as training_pack_move_round,sn as training_pack_remove_round,an as training_pack_remove_round_archetype,fn as training_pack_round_archetypes,ln as training_pack_set_round_archetype,un as training_pack_set_round_ball,dn as training_pack_set_round_time_limit,gn as update_training_pack_metadata,bn as validate_replay}; diff --git a/crates/rocket-sense-server/static/subtr-actor/stats/assets/rl_replay_subtr_actor_bg-Xy9_Ya42.wasm b/crates/rocket-sense-server/static/subtr-actor/stats/assets/rl_replay_subtr_actor_bg-BjSK7HJ9.wasm similarity index 50% rename from crates/rocket-sense-server/static/subtr-actor/stats/assets/rl_replay_subtr_actor_bg-Xy9_Ya42.wasm rename to crates/rocket-sense-server/static/subtr-actor/stats/assets/rl_replay_subtr_actor_bg-BjSK7HJ9.wasm index 28187c21..140cd489 100644 Binary files a/crates/rocket-sense-server/static/subtr-actor/stats/assets/rl_replay_subtr_actor_bg-Xy9_Ya42.wasm and b/crates/rocket-sense-server/static/subtr-actor/stats/assets/rl_replay_subtr_actor_bg-BjSK7HJ9.wasm differ diff --git a/crates/rocket-sense-server/static/subtr-actor/stats/assets/wasm.worker-Bj4v8ZR2.js b/crates/rocket-sense-server/static/subtr-actor/stats/assets/wasm.worker-Bj4v8ZR2.js deleted file mode 100644 index 5e7d7d50..00000000 --- a/crates/rocket-sense-server/static/subtr-actor/stats/assets/wasm.worker-Bj4v8ZR2.js +++ /dev/null @@ -1 +0,0 @@ -(function(){"use strict";function ge(e,t,n){const r=G(e,c.__wbindgen_malloc),o=w,a=c.get_replay_frames_data_json_with_progress(r,o,t,Z(n)?4294967297:n>>>0);if(a[3])throw V(a[2]);var i=W(a[0],a[1]).slice();return c.__wbindgen_free(a[0],a[1]*1,1),i}function be(e){const t=G(e,c.__wbindgen_malloc),n=w,r=c.validate_replay(t,n);if(r[2])throw V(r[1]);return V(r[0])}function ye(){return{__proto__:null,"./rl_replay_subtr_actor_bg.js":{__proto__:null,__wbg_Error_8c4e43fe74559d73:function(t,n){return Error(I(t,n))},__wbg_String_8f0eb39a4a4c2f66:function(t,n){const r=String(n),o=L(r,c.__wbindgen_malloc,c.__wbindgen_realloc),a=w;O().setInt32(t+4,a,!0),O().setInt32(t+0,o,!0)},__wbg___wbindgen_is_string_cd444516edc5b180:function(t){return typeof t=="string"},__wbg___wbindgen_string_get_72fb696202c56729:function(t,n){const r=n,o=typeof r=="string"?r:void 0;var a=Z(o)?0:L(o,c.__wbindgen_malloc,c.__wbindgen_realloc),i=w;O().setInt32(t+4,i,!0),O().setInt32(t+0,a,!0)},__wbg___wbindgen_throw_be289d5034ed271b:function(t,n){throw new Error(I(t,n))},__wbg_call_4708e0c13bdc8e95:function(){return K(function(t,n,r){return t.call(n,r)},arguments)},__wbg_error_7534b8e9a36f1ab4:function(t,n){let r,o;try{r=t,o=n,console.error(I(t,n))}finally{c.__wbindgen_free(r,o,1)}},__wbg_log_d095c16a726a937c:function(t,n){console.log(I(t,n))},__wbg_new_361308b2356cecd0:function(){return new Object},__wbg_new_3eb36ae241fe6f44:function(){return new Array},__wbg_new_8a6f238a6ece86ea:function(){return new Error},__wbg_new_dca287b076112a51:function(){return new Map},__wbg_new_from_slice_a3d2629dc1826784:function(t,n){return new Uint8Array(W(t,n))},__wbg_push_8ffdcb2063340ba5:function(t,n){return t.push(n)},__wbg_set_1eb0999cf5d27fc8:function(t,n,r){return t.set(n,r)},__wbg_set_3f1d0b984ed272ed:function(t,n,r){t[n]=r},__wbg_set_6cb8631f80447a67:function(){return K(function(t,n,r){return Reflect.set(t,n,r)},arguments)},__wbg_set_f43e577aea94465b:function(t,n,r){t[n>>>0]=r},__wbg_stack_0ed75d68575b0f3c:function(t,n){const r=n.stack,o=L(r,c.__wbindgen_malloc,c.__wbindgen_realloc),a=w;O().setInt32(t+4,a,!0),O().setInt32(t+0,o,!0)},__wbindgen_cast_0000000000000001:function(t){return t},__wbindgen_cast_0000000000000002:function(t){return t},__wbindgen_cast_0000000000000003:function(t,n){return I(t,n)},__wbindgen_cast_0000000000000004:function(t){return BigInt.asUintN(64,t)},__wbindgen_init_externref_table:function(){const t=c.__wbindgen_externrefs,n=t.grow(4);t.set(0,void 0),t.set(n+0,void 0),t.set(n+1,null),t.set(n+2,!0),t.set(n+3,!1)}}}}function pe(e){const t=c.__externref_table_alloc();return c.__wbindgen_externrefs.set(t,e),t}function W(e,t){return e=e>>>0,S().subarray(e/1,e/1+t)}let x=null;function O(){return(x===null||x.buffer.detached===!0||x.buffer.detached===void 0&&x.buffer!==c.memory.buffer)&&(x=new DataView(c.memory.buffer)),x}function I(e,t){return e=e>>>0,we(e,t)}let E=null;function S(){return(E===null||E.byteLength===0)&&(E=new Uint8Array(c.memory.buffer)),E}function K(e,t){try{return e.apply(this,t)}catch(n){const r=pe(n);c.__wbindgen_exn_store(r)}}function Z(e){return e==null}function G(e,t){const n=t(e.length*1,1)>>>0;return S().set(e,n/1),w=e.length,n}function L(e,t,n){if(n===void 0){const s=D.encode(e),f=t(s.length,1)>>>0;return S().subarray(f,f+s.length).set(s),w=s.length,f}let r=e.length,o=t(r,1)>>>0;const a=S();let i=0;for(;i127)break;a[o+i]=s}if(i!==r){i!==0&&(e=e.slice(i)),o=n(o,r,r=i+e.length*3,1)>>>0;const s=S().subarray(o+i,o+r),f=D.encodeInto(e,s);i+=f.written,o=n(o,r,i,1)>>>0}return w=i,o}function V(e){const t=c.__wbindgen_externrefs.get(e);return c.__externref_table_dealloc(e),t}let R=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});R.decode();const he=2146435072;let j=0;function we(e,t){return j+=t,j>=he&&(R=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),R.decode(),j=t),R.decode(S().subarray(e,e+t))}const D=new TextEncoder;"encodeInto"in D||(D.encodeInto=function(e,t){const n=D.encode(e);return t.set(n),{read:e.length,written:n.length}});let w=0,c;function ke(e,t){return c=e.exports,x=null,E=null,c.__wbindgen_start(),c}async function xe(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(o){if(e.ok&&n(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",o);else throw o}const r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{const r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}async function Ae(e){if(c!==void 0)return c;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0&&(e=new URL(""+new URL("rl_replay_subtr_actor_bg-Xy9_Ya42.wasm",self.location.href).href,self.location.href));const t=ye();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));const{instance:n,module:r}=await xe(await e,t);return ke(n)}const q="octane",ve={breakout:{kind:"breakout",label:"Breakout",length:131.4924,width:80.521,height:30.3,slopeDegrees:-.9795,groundHeightFront:43.8976,groundHeightBack:46.1454,offset:13.88,elevation:17.05},dominus:{kind:"dominus",label:"Dominus",length:127.9268,width:83.27995,height:31.3,slopeDegrees:-.9635,groundHeightFront:47.2238,groundHeightBack:49.3749,offset:13.88,elevation:17.05},hybrid:{kind:"hybrid",label:"Hybrid",length:127.0192,width:82.18787,height:34.15907,slopeDegrees:-.5499,groundHeightFront:54.0982,groundHeightBack:55.3173,offset:13.88,elevation:17.05},merc:{kind:"merc",label:"Merc",length:120.72,width:76.71,height:41.66,slopeDegrees:.28,groundHeightFront:60.76,groundHeightBack:61.35,offset:13.88,elevation:17.05},octane:{kind:"octane",label:"Octane",length:118.0074,width:84.19941,height:36.15907,slopeDegrees:-.5518,groundHeightFront:55.1449,groundHeightBack:56.2814,offset:13.88,elevation:17.05},plank:{kind:"plank",label:"Plank",length:128.8198,width:84.67036,height:29.3944,slopeDegrees:-.3447,groundHeightFront:44.998,groundHeightBack:45.773,offset:13.88,elevation:17.05}},Oe={"16batmobile":"plank","70dodgechargerrt":"dominus","89batmobile":"dominus","99nissanskylinegtrr34":"hybrid",aftershock:"dominus",animusgp:"breakout",artemis:"plank",artemisg1:"plank",artemisgxt:"plank",astonmartinvalhalla:"breakout",backfire:"octane",backtothefuturetimemachine:"dominus",batmobile1989:"dominus",battlebus:"merc",breakout:"breakout",breakouttypes:"breakout",centio:"plank",centiov17:"plank",cyclone:"breakout",deloreantimemachine:"dominus",diestro:"dominus",dominus:"dominus",dominusgt:"dominus",endo:"hybrid",esper:"hybrid",fast4wd:"octane",fennec:"octane",gazellagt:"dominus",gizmo:"octane",grog:"octane",guardian:"dominus",guardiang1:"dominus",guardiangxt:"dominus",hotshot:"dominus",icecharger:"dominus",imperatordt5:"dominus",jager619rs:"hybrid",jurassicjeepwrangler:"octane",mantis:"plank",marauder:"octane",masamune:"dominus",maverick:"dominus",maverickg1:"dominus",maverickgxt:"dominus",mclaren570s:"dominus",merc:"merc",mr11:"dominus",nimbus:"hybrid",octane:"octane",octanezsr:"octane",paladin:"plank",proteus:"octane",ripper:"dominus",roadhog:"octane",roadhogxl:"octane",samurai:"breakout",scarab:"octane",takumi:"octane",takumirxt:"octane",thedarkknightstumbler:"octane",thedarkknightrisestumbler:"octane",triton:"octane",twinmilliii:"plank",twinzer:"octane",venom:"hybrid",vulcan:"octane",werewolf:"dominus",xdevil:"hybrid",xdevilmk2:"hybrid",zippy:"octane","1966cadillacdeville":"breakout",ace:"breakout",admiral:"dominus",azura:"breakout",behemoth:"merc",beskar:"hybrid",bmwm3e30:"dominus",bmwm2racing:"dominus",bmwm4gt3evo:"dominus",bmw1series:"octane",bmw1seriesrle:"octane",bmwm240i:"dominus",bugatticentodieci:"plank",bumblebee:"dominus",bumblebeecar:"dominus",chevroletastro:"merc",chevroletcorvettestingray:"breakout",chevroletcorvettezr1:"breakout",chryslerpacifica:"hybrid",corlay:"octane",cyberpunkquadra:"breakout",defenderd7xr:"merc",diesel:"breakout",dodgechargerdaytonascatpack:"dominus",dodgerchargerdaytonascatpack:"dominus",dominusneon:"dominus",emperor:"breakout",emperorii:"breakout",emperoriifrozen:"breakout",emperoriiscorched:"breakout",fastfuriousdodgecharger:"dominus",fastandfuriousdodgecharger:"dominus",fastandfuriousdodgechargersrthellcat:"dominus",fastfuriousmazdarx7:"breakout",fastandfuriousmazdarx7:"breakout",fastfuriousnissanskyline:"hybrid",fastandfuriousnissanskyline:"hybrid",fastfuriouspontiacfiero:"hybrid",fastandfuriouspontiacfiero:"hybrid",fenneczrf:"octane",ferrari296gtb:"dominus",ferrarif40:"breakout",fordbroncoraptorrle:"merc",fordf150rle:"octane",fordmustanggtd:"dominus",fordmustangshelbygt500:"dominus",fordmustangmacherle:"octane",fordmustangshelbygt350rrle:"dominus",formula12021:"plank",formula12022:"plank",fuse:"breakout",havoc:"breakout",hearse:"hybrid",homerscar:"dominus",hondacivictyper:"octane",hondacivictyperle:"octane",jackal:"octane",jeepwranglerrubicon:"octane",kitt:"dominus",knightindustries2000:"dominus",komodo:"breakout",lamborghinicountachlpi8004:"dominus",lamborghinihuracansto:"dominus",lamborghiniurus:"hybrid",lamborghiniurusse:"hybrid",lightningmcqueen:"dominus",lightningmcqueencar:"dominus",lockjaw:"dominus",luiginsr:"octane",maestro:"dominus",magnifique:"dominus",magnifiquegxt:"dominus",mako:"breakout",mamba:"dominus",mario:"octane",marionsr:"octane",maven:"dominus",mclaren765lt:"dominus",mclarenp1:"dominus",mclarensenna:"breakout",megastar:"breakout",mercedesamggt63s:"dominus",mercedesbenzcla:"dominus",mudcat:"octane",mudcatg1:"octane",mudcatgxt:"octane",nissan350z:"dominus",nissanfairladyz:"dominus",nissanfairladyzrle:"dominus",nissansilvia:"hybrid",nissansilviarle:"hybrid",nissanskylinegtr:"hybrid",nissanskylinegtrr32:"hybrid",nissanzperformance:"dominus",nissanzperformancecar:"dominus",outlaw:"octane",outlawgxt:"octane",pattywagon:"octane",pizzaplanetdeliverytruck:"merc",pontiacfirebird:"breakout",porsche918spyder:"breakout",porsche911gt3rs:"dominus",porsche911turbo:"dominus",porsche911turborle:"dominus",primo:"hybrid",psyclops:"octane",quadraturbor:"breakout",ram1500rho:"hybrid",recoilav:"merc",redline:"breakout",revolver:"breakout",rivianr1s:"hybrid",scorpion:"dominus",shokunin:"octane",shokuningxt:"octane",stampede:"merc",teslacybertruck:"hybrid",themysterymachine:"merc",theincredibile:"breakout",turtlevan:"merc",voidburn:"hybrid",volkswagengolfgti:"octane",volkswagengolfgtirle:"octane",xentari:"octane",zefira:"dominus",breakoutx:"breakout",nexus:"breakout",nexussc:"breakout",whiplash:"breakout","007sastonmartindbs":"dominus","007sastonmartinvalhalla":"dominus",batmobile2022:"dominus",chikara:"dominus",chikarag1:"dominus",chikaragxt:"dominus",ecto1:"dominus",ecto1ghostbusters:"dominus",fastfuriousdodgechargersrthellcat:"dominus",gazellagthotwheels:"dominus",kittknightrider:"dominus",lamborghinihuracnsto:"dominus",mr11hotwheels:"dominus",nascarchevroletcamaro:"dominus",nascarfordmustang:"dominus",nascartoyotacamry:"dominus",nascarnextgenchevroletcamaro:"dominus",nascarnextgenchevroletcamaro2022:"dominus",nascarnextgenfordmustang:"dominus",nascarnextgenfordmustang2022:"dominus",nascarnextgentoyotacamry:"dominus",nascarnextgentoyotacamry2022:"dominus",nemesis:"dominus",peregrinett:"dominus",perigrinett:"dominus",ronin:"dominus",roning1:"dominus",roningxt:"dominus",samusgunship:"dominus",samusgunshipnintendoexclusive:"dominus",tyranno:"dominus",tyrannogxt:"dominus",insidio:"hybrid",jager619:"hybrid",jger619:"hybrid",jger619rs:"hybrid",r3mx:"hybrid",r3mxgxt:"hybrid",tygris:"hybrid",nomad:"merc",nomadgxt:"merc","007sastonmartindb5":"octane",armadillo:"octane",armadilloxboxexclusive:"octane",boneshaker:"octane",dingo:"octane",fast4wdhotwheels:"octane",harbinger:"octane",harbingergxt:"octane",hogsticker:"octane",hogstickerxboxexclusive:"octane",sweettooth:"octane",sweettoothplaystationexclusive:"octane",thedarkknighttumbler:"octane",batmobile2016:"plank",sentinel:"plank"};function Se(e){const t={};for(const[n,r]of e)for(const o of n)t[o]=r;return t}const Te=Se([[[22,1416,1894,1932,3031,3311,6243,6489,7651,7696,7890,7901,8006,8360,8361,8565,8566,8669,9357,10697,10698,10817,10822,11038,11394,11505,11677,11800,11933,11949,12173,12315,12361,12484],"breakout"],[[29,403,597,600,1018,1171,1286,1675,1689,1883,2070,2268,2666,2950,2951,3155,3156,3157,3265,3426,3875,3879,3880,4014,4155,4367,4472,4473,4745,4770,4781,4861,4864,5709,5773,5823,5858,5964,5979,6122,6244,6247,6260,6836,7211,7337,7338,7341,7343,7415,7512,7532,7593,7772,8454,9053,9088,9089,9140,9388,9894,10094,10440,10441,10694,10695,11016,11095,11315,11336,11534,11941,11996,12106,12142,12262,12286,12325,12382,12563,12669],"dominus"],[[28,31,1159,1317,1624,1856,2269,3451,3582,3702,5470,5488,5879,7012,9084,9085,9427,10044,10805,11138,11141,11379,11932,12569,12652],"hybrid"],[[30,4780,7336,7477,7815,7979,10689,11098,11736,11905,11950,12318,12335],"merc"],[[21,23,25,26,27,402,404,523,607,625,723,1172,1295,1300,1475,1478,1533,1568,1623,2665,2853,2919,2949,4284,4318,4319,4320,4782,4906,5020,5039,5188,5361,5547,5713,5837,5951,6939,7947,7948,8383,8806,8807,10896,10897,10900,10901,11314,11603,12104,12105],"octane"],[[24,803,1603,1691,1919,3594,3614,3622,4268,5265,7052,8524],"plank"]]);function J(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function Q(e){if(!e)return null;switch(J(e)){case"breakout":return"breakout";case"dominus":return"dominus";case"hybrid":return"hybrid";case"merc":return"merc";case"octane":return"octane";case"batmobile":case"plank":return"plank";default:return null}}function ee(e){return e?Oe[J(e)]??null:null}function Ie(e){return Q(e)??ee(e)}function Ee(e){return ve[e]}function H(e,t){if(!(!e||typeof e!="object")){if("Str"in e&&typeof e.Str=="string"){t.push(e.Str);return}if("Name"in e&&typeof e.Name=="string"){t.push(e.Name);return}if("Byte"in e&&e.Byte&&typeof e.Byte=="object"){const n=e.Byte;typeof n.kind=="string"&&t.push(n.kind),typeof n.value=="string"&&t.push(n.value);return}if("Struct"in e&&e.Struct&&typeof e.Struct=="object"){const n=e.Struct;if(typeof n.name=="string"&&t.push(n.name),Array.isArray(n.fields))for(const r of n.fields)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),H(r[1],t));return}if("Array"in e&&Array.isArray(e.Array)){for(const n of e.Array)if(Array.isArray(n))for(const r of n)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),H(r[1],t))}}}function De(e){const t=Q(e?.car_hitbox_family);if(t)return t;const n=e?.car_body_id;if(typeof n=="number"){const i=Te[n];if(i)return i}const r=ee(e?.car_body_name);if(r)return r;const o=e?.stats;if(!o)return q;const a=[];for(const[i,s]of Object.entries(o))a.push(i),H(s,a);for(const i of a){const s=Ie(i);if(s)return s}return q}function k(e){const[t,n]=Object.entries(e)[0]??["Unknown","unknown"];return typeof n=="string"||typeof n=="number"?`${t}:${n}`:n&&typeof n=="object"?`${t}:${JSON.stringify(n)}`:`${t}:${JSON.stringify(n)}`}function B(e,t){return Math.max(0,e-t)}function te(e){return new Map(e.map(t=>[t.id,t]))}const y=70,ne=73,Be=3072,Pe=4096,Ne=1792,Re=4184,ze=940,Me=3308,Fe=2816,re=3584,Ce=2484,Le=1788,Ve=2300,je=2048,He=1036,Ue=1024,Ye=1024,$e=4240,oe=34;function z(e,t,n,r,o){e.push({index:e.length,padId:null,size:o,position:{x:t,y:n,z:r},events:[]})}function M(e,t,n,r,o){z(e,-t,n,r,o),z(e,t,n,r,o)}function U(e,t,n,r,o){z(e,t,-n,r,o),z(e,t,n,r,o)}function T(e,t,n,r,o){M(e,t,-n,r,o),M(e,t,n,r,o)}function Xe(){const e=[];return U(e,0,$e,y,"small"),T(e,Ne,Re,y,"small"),T(e,Be,Pe,ne,"big"),T(e,ze,Me,y,"small"),U(e,0,Fe,y,"small"),T(e,re,Ce,y,"small"),T(e,Le,Ve,y,"small"),T(e,je,He,y,"small"),U(e,0,Ye,y,"small"),M(e,re,0,ne,"big"),M(e,Ue,0,y,"small"),e}function Y(e){if(e==="Available")return!0;if(e&&typeof e=="object"){if("Available"in e)return!0;if("PickedUp"in e)return!1;const t=e.kind;if(t==="Available")return!0;if(t==="PickedUp")return!1}return null}function We(e){return e==="big"||e==="Big"?"big":e==="small"||e==="Small"?"small":null}function Ke(e){let t=null;for(const n of e){const r=Y(n.kind);if(r===!1){t=n.time;continue}if(r===!0&&t!==null)return n.time-t>=7?"big":"small"}return null}function Ze(e,t,n,r){const o=te(t),a=new Map;for(const l of e.boost_pad_events??[]){if(Y(l.kind)===null){r?.advance();continue}const u=a.get(l.pad_id);u?u.push(l):a.set(l.pad_id,[l]),r?.advance()}const i=e.boost_pads;if(!i||i.length===0)return r?.advance(oe),Xe();const s=[...i].sort((l,d)=>l.index-d.index),f=new Array(s.length);for(let l=0;l=72?"big":"small"),p=b.sort((_,h)=>_.time-h.time),m=new Array(p.length);for(let _=0;_=0?e.frame:null}function Ge(e,t){if(typeof e.time=="number"&&Number.isFinite(e.time))return e.time;const n=$(e);if(n===null)return null;const r=t.frame_data.metadata_frames[n]?.time;return typeof r=="number"&&Number.isFinite(r)?r:null}function qe(e,t){return`bookmark:${$(e)??"unknown"}:${e.description||"tick-mark"}:${t}`}function Je(e,t,n){return(e.replay_tick_marks??[]).flatMap((r,o)=>{n?.advance();const a=Ge(r,e);return a===null?[]:[{id:qe(r,o),description:r.description,frame:$(r),time:B(a,t)}]})}function Qe(e){const t=e.description.trim()||"Replay bookmark";return{id:e.id,time:e.time,seekTime:e.time,frame:e.frame??void 0,kind:"bookmark",label:t,shortLabel:"BM",iconName:"bookmark"}}const A={distance:270,height:100,pitch:-4,fov:110},et=.005,tt=Number.POSITIVE_INFINITY,nt=!0,rt=.15,ot=10,at=.1,it=10;function ae(e){const t=Math.hypot(e.x,e.y,e.z);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t}}function ie(e){const t=Math.hypot(e.x,e.y,e.z,e.w);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t,w:e.w/t}}function se(e,t){return{w:e.w*t.w-e.x*t.x-e.y*t.y-e.z*t.z,x:e.w*t.x+e.x*t.w+e.y*t.z-e.z*t.y,y:e.w*t.y-e.x*t.z+e.y*t.w+e.z*t.x,z:e.w*t.z+e.x*t.y-e.y*t.x+e.z*t.w}}function ce(e,t){const n=se(se(t,{x:e.x,y:e.y,z:e.z,w:0}),{x:-t.x,y:-t.y,z:-t.z,w:t.w});return{x:n.x,y:n.y,z:n.z}}function st(e){if(e==="Empty")return{position:null,linearVelocity:null,angularVelocity:null,rotation:null};const t=e.Data.rigid_body;return{position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:ie(t.rotation)}}function le(e){return e==null?null:Math.max(-1,Math.min(1,(e-128)/128))}function ue(e){return e==null?null:(e>127?e-256:e)*Math.PI/128}function de(e){return e?{x:e[0],y:e[1],z:e[2]}:null}const ct={cameraPitch:null,cameraYaw:null,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null};function lt(e){if(e==="Empty")return{isPresent:!1,position:null,linearVelocity:null,angularVelocity:null,rotation:null,forward:null,up:null,boostAmount:0,boostFraction:0,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,...ct};const t=e.Data.rigid_body,n=ie(t.rotation),r=n?ae(ce({x:1,y:0,z:0},n)):null,o=n?ae(ce({x:0,y:0,z:1},n)):null,a=e.Data.camera,i=e.Data.input;return{isPresent:!0,position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:n,forward:r,up:o,boostAmount:e.Data.boost_amount,boostFraction:Math.max(0,Math.min(1,e.Data.boost_amount/255)),boostActive:e.Data.boost_active,powerslideActive:e.Data.powerslide_active,jumpActive:e.Data.jump_active,doubleJumpActive:e.Data.double_jump_active,dodgeActive:e.Data.dodge_active,cameraPitch:ue(a?.pitch),cameraYaw:ue(a?.yaw),throttle:le(i?.throttle),steer:le(i?.steer),dodgeImpulse:de(i?.dodge_impulse),dodgeTorque:de(i?.dodge_torque)}}function ut(e){return e.position!==null}function dt(e){return{...e,isPresent:!1,linearVelocity:null,angularVelocity:null,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null}}function mt(e){let t=null,n=null;for(let r=0;r=t.length-1)return;let o=P(t[r].position);for(let a=r+1;aat){o=P(s.position);continue}if(ft(o,s.position)>it){o=P(s.position);continue}const u={x:(i.linearVelocity.x+s.linearVelocity.x)/2,y:(i.linearVelocity.y+s.linearVelocity.y)/2,z:(i.linearVelocity.z+s.linearVelocity.z)/2},b={x:o.x+u.x*d,y:o.y+u.y*d,z:o.z+u.z*d},g=(a-r)%n.smoothingAnchorInterval===0?.5:n.smoothingBlendFactor;o={x:b.x*(1-g)+s.position.x*g,y:b.y*(1-g)+s.position.y*g,z:b.z*(1-g)+s.position.z*g},s.position=P(o)}}function _t(e){return{motionSmoothing:e.motionSmoothing??nt,smoothingBlendFactor:e.smoothingBlendFactor??rt,smoothingAnchorInterval:Math.max(1,e.smoothingAnchorInterval??ot)}}function _e(){return typeof performance>"u"?Date.now():performance.now()}function gt(e){const t=e.meta.team_zero.length+e.meta.team_one.length,n=e.frame_data.players.reduce((i,[,s])=>i+s.frames.length,0),r=e.boost_pads?.length??oe,o=e.boost_pad_events?.length??0,a=(e.goal_events?.length??0)+(e.player_stat_events?.length??0)+(e.demolish_infos?.length??0)+(e.replay_tick_marks?.length??0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,n),Math.max(1,e.frame_data.ball_data.frames.length),Math.max(1,r+o),Math.max(1,a)].reduce((i,s)=>i+s,0)}function bt(e){const t=e.frame_data.players.reduce((n,[,r])=>n+r.frames.length,0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,e.frame_data.ball_data.frames.length)].reduce((n,r)=>n+r,0)}function yt(e,t,n={}){const r=gt(e),o=bt(e);let a=0,i=0,s=-1,f=-1,l=_e();const d=n.yieldEveryMs??Number.POSITIVE_INFINITY,u=n.progressReportMinDelta??et,b=Math.max(1,n.progressReportFrameInterval??tt),g=()=>{if(!t)return!1;const m=Math.max(0,Math.min(1,a/r));if(m<=s)return!1;const h=i-f>=b;return m>=1||m-s>=u||h?(s=m,f=i,t(m,{progress:m,processedFrames:Math.min(i,o),totalFrames:o,processedUnits:a,totalUnits:r}),!0):!1},p=(m=!1)=>{const _=_e();return!m&&_-lr===t)?.[1];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function kt(e){const t=wt(e?.stats);return{fov:v(t,"CameraFOV")??A.fov,height:v(t,"CameraHeight")??A.height,pitch:v(t,"CameraPitch")??A.pitch,distance:v(t,"CameraDistance")??A.distance,stiffness:v(t,"CameraStiffness")??A.stiffness,swivelSpeed:v(t,"CameraSwivelSpeed")??A.swivelSpeed,transitionSpeed:v(t,"CameraTransitionSpeed")??A.transitionSpeed}}function xt(e,t){const n=new Map,r=new Map,o=[...e.meta.team_zero,...e.meta.team_one];if(o.length===0)return t?.advance(),{byId:n,byName:r};for(const a of o)r.set(a.name,a),a.remote_id&&n.set(k(a.remote_id),a),t?.advance();return{byId:n,byName:r}}function At(e){const t=new Map;for(const[n,r]of e.player_camera_events??[])t.set(k(n),r.map(o=>({frame:o.frame,ballCamActive:o.ball_cam_active,behindViewActive:o.behind_view_active,driving:o.driving})));return t}function vt(e,t){const n=new Set(e.meta.team_zero.map(f=>f.name)),r=new Set(e.meta.team_one.map(f=>f.name)),o=xt(e,t),a=At(e),i=[];let s=0;for(const[f,l]of e.frame_data.players){const d=new Array(l.frames.length);let u;for(let m=0;mt.time!==n.time?t.time-n.time:(t.frame??0)-(n.frame??0))}function Tt(e,t,n){const r=e.player?k(e.player):null,o=r?t.get(r)?.name??r:null,a=o?`${o} scored`:"Goal";return{id:X("goal",e.frame,r??"team"),time:B(e.time,n),frame:e.frame,kind:"goal",label:a,shortLabel:"G",playerId:r,playerName:o,isTeamZero:e.scoring_team_is_team_0}}function It(e,t,n){const r=k(e.player),o=t.get(r)?.name??r,a=e.kind.toLowerCase(),i=e.kind==="Shot"?"shot":e.kind==="Save"?"save":"assist",s=e.kind==="Shot"?"SH":e.kind==="Save"?"SV":"A";return{id:X(a,e.frame,r),time:B(e.time,n),frame:e.frame,kind:a,label:`${o} ${i}`,shortLabel:s,playerId:r,playerName:o,location:e.shot?.shot_touch_position??e.shot?.ball_position??null,shot:e.shot??null,isTeamZero:e.is_team_0}}function Et(e,t,n){const r=k(e.attacker),o=k(e.victim),a=t.get(r),i=t.get(o);return{id:X("demo",e.frame,`${r}:${o}`),time:B(e.time,n),frame:e.frame,kind:"demo",label:`${a?.name??r} demoed ${i?.name??o}`,shortLabel:"D",playerId:r,playerName:a?.name??r,secondaryPlayerId:o,secondaryPlayerName:i?.name??o,location:e.victim_location,isTeamZero:a?.isTeamZero??null}}function Dt(e,t,n,r,o){const a=te(t),i=[];for(const s of e.goal_events??[])i.push(Tt(s,a,r)),o?.advance();for(const s of e.player_stat_events??[])i.push(It(s,a,r)),o?.advance();for(const s of e.demolish_infos??[])i.push(Et(s,a,r)),o?.advance();for(const s of n)i.push(Qe(s));return i.length===0&&o?.advance(),St(i)}function Bt(e,t={}){const n=yt(e,t.onProgress,{progressReportMinDelta:t.progressReportMinDelta,progressReportFrameInterval:t.progressReportFrameInterval}),r=e.frame_data.metadata_frames[0]?.time??0,o=pt(e,n),a=vt(e,n),i=Ot(e,n),s=_t(t);fe(o,i,s);for(const u of a)fe(o,u.frames,s);const f=Ze(e,a,r,n),l=Je(e,r,n),d=Dt(e,a,l,r,n);return n.finish(),{frameCount:o.length,duration:o.at(-1)?.time??0,rawStartTime:r,frames:o,ballFrames:i,boostPads:f,players:a,tickMarks:l,timelineEvents:d,teamZeroNames:e.meta.team_zero.map(u=>u.name),teamOneNames:e.meta.team_one.map(u=>u.name)}}function F(e){if(e instanceof Map)return Object.fromEntries(Array.from(e.entries()).map(([t,n])=>[t,F(n)]));if(Array.isArray(e))return e.map(t=>F(t));if(e&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=F(r);return t}return e}async function Pt(){const e=Ae;typeof e=="function"&&await e()}function N(e){self.postMessage(e)}self.onmessage=async e=>{if(e.data.type==="load-replay")try{await Pt();const t=new Uint8Array(e.data.bytes);N({type:"progress",progress:{stage:"validating",progress:0}});const n=F(be(t));if(!n.valid)throw new Error(n.error??"Replay validation failed");const r=ge(t,s=>{N({type:"progress",progress:s})},e.data.reportEveryNFrames);N({type:"progress",progress:{stage:"normalizing",progress:0}});const o=JSON.parse(new TextDecoder().decode(r)),a=Bt(o,{motionSmoothing:e.data.motionSmoothing,smoothingBlendFactor:e.data.smoothingBlendFactor,smoothingAnchorInterval:e.data.smoothingAnchorInterval,progressReportFrameInterval:e.data.reportEveryNFrames,onProgress(s){N({type:"progress",progress:{stage:"normalizing",progress:s}})}}),i=new TextEncoder().encode(JSON.stringify(a));self.postMessage({type:"done",rawBuffer:r.buffer,replayBuffer:i.buffer},[r.buffer,i.buffer])}catch(t){N({type:"error",error:t instanceof Error?t.message:String(t)})}}})(); diff --git a/crates/rocket-sense-server/static/subtr-actor/stats/assets/wasm.worker-zm5sJFWS.js b/crates/rocket-sense-server/static/subtr-actor/stats/assets/wasm.worker-zm5sJFWS.js new file mode 100644 index 00000000..1f671e38 --- /dev/null +++ b/crates/rocket-sense-server/static/subtr-actor/stats/assets/wasm.worker-zm5sJFWS.js @@ -0,0 +1,2 @@ +(function(){"use strict";function ge(e,t,n){const r=q(e,c.__wbindgen_malloc),o=p,a=c.get_replay_frames_data_json_with_progress(r,o,t,v(n)?4294967297:n>>>0);if(a[3])throw Y(a[2]);var i=H(a[0],a[1]).slice();return c.__wbindgen_free(a[0],a[1]*1,1),i}function ye(e){const t=q(e,c.__wbindgen_malloc),n=p,r=c.validate_replay(t,n);if(r[2])throw Y(r[1]);return Y(r[0])}function pe(){return{__proto__:null,"./rl_replay_subtr_actor_bg.js":{__proto__:null,__wbg_Error_8c4e43fe74559d73:function(t,n){return Error(E(t,n))},__wbg_Number_04624de7d0e8332d:function(t){return Number(t)},__wbg_String_8f0eb39a4a4c2f66:function(t,n){const r=String(n),o=M(r,c.__wbindgen_malloc,c.__wbindgen_realloc),a=p;y().setInt32(t+4,a,!0),y().setInt32(t+0,o,!0)},__wbg___wbindgen_bigint_get_as_i64_8fcf4ce7f1ca72a2:function(t,n){const r=n,o=typeof r=="bigint"?r:void 0;y().setBigInt64(t+8,v(o)?BigInt(0):o,!0),y().setInt32(t+0,!v(o),!0)},__wbg___wbindgen_boolean_get_bbbb1c18aa2f5e25:function(t){const n=t,r=typeof n=="boolean"?n:void 0;return v(r)?16777215:r?1:0},__wbg___wbindgen_debug_string_0bc8482c6e3508ae:function(t,n){const r=U(n),o=M(r,c.__wbindgen_malloc,c.__wbindgen_realloc),a=p;y().setInt32(t+4,a,!0),y().setInt32(t+0,o,!0)},__wbg___wbindgen_in_47fa6863be6f2f25:function(t,n){return t in n},__wbg___wbindgen_is_bigint_31b12575b56f32fc:function(t){return typeof t=="bigint"},__wbg___wbindgen_is_function_0095a73b8b156f76:function(t){return typeof t=="function"},__wbg___wbindgen_is_object_5ae8e5880f2c1fbd:function(t){const n=t;return typeof n=="object"&&n!==null},__wbg___wbindgen_is_string_cd444516edc5b180:function(t){return typeof t=="string"},__wbg___wbindgen_is_undefined_9e4d92534c42d778:function(t){return t===void 0},__wbg___wbindgen_jsval_eq_11888390b0186270:function(t,n){return t===n},__wbg___wbindgen_jsval_loose_eq_9dd77d8cd6671811:function(t,n){return t==n},__wbg___wbindgen_number_get_8ff4255516ccad3e:function(t,n){const r=n,o=typeof r=="number"?r:void 0;y().setFloat64(t+8,v(o)?0:o,!0),y().setInt32(t+0,!v(o),!0)},__wbg___wbindgen_string_get_72fb696202c56729:function(t,n){const r=n,o=typeof r=="string"?r:void 0;var a=v(o)?0:M(o,c.__wbindgen_malloc,c.__wbindgen_realloc),i=p;y().setInt32(t+4,i,!0),y().setInt32(t+0,a,!0)},__wbg___wbindgen_throw_be289d5034ed271b:function(t,n){throw new Error(E(t,n))},__wbg_call_389efe28435a9388:function(){return D(function(t,n){return t.call(n)},arguments)},__wbg_call_4708e0c13bdc8e95:function(){return D(function(t,n,r){return t.call(n,r)},arguments)},__wbg_done_57b39ecd9addfe81:function(t){return t.done},__wbg_entries_58c7934c745daac7:function(t){return Object.entries(t)},__wbg_error_7534b8e9a36f1ab4:function(t,n){let r,o;try{r=t,o=n,console.error(E(t,n))}finally{c.__wbindgen_free(r,o,1)}},__wbg_get_9b94d73e6221f75c:function(t,n){return t[n>>>0]},__wbg_get_b3ed3ad4be2bc8ac:function(){return D(function(t,n){return Reflect.get(t,n)},arguments)},__wbg_get_with_ref_key_1dc361bd10053bfe:function(t,n){return t[n]},__wbg_instanceof_ArrayBuffer_c367199e2fa2aa04:function(t){let n;try{n=t instanceof ArrayBuffer}catch{n=!1}return n},__wbg_instanceof_Map_53af74335dec57f4:function(t){let n;try{n=t instanceof Map}catch{n=!1}return n},__wbg_instanceof_Uint8Array_9b9075935c74707c:function(t){let n;try{n=t instanceof Uint8Array}catch{n=!1}return n},__wbg_isArray_d314bb98fcf08331:function(t){return Array.isArray(t)},__wbg_isSafeInteger_bfbc7332a9768d2a:function(t){return Number.isSafeInteger(t)},__wbg_iterator_6ff6560ca1568e55:function(){return Symbol.iterator},__wbg_length_32ed9a279acd054c:function(t){return t.length},__wbg_length_35a7bace40f36eac:function(t){return t.length},__wbg_log_f1a1b5cd3f9c7822:function(t,n){console.log(E(t,n))},__wbg_new_361308b2356cecd0:function(){return new Object},__wbg_new_3eb36ae241fe6f44:function(){return new Array},__wbg_new_8a6f238a6ece86ea:function(){return new Error},__wbg_new_dca287b076112a51:function(){return new Map},__wbg_new_dd2b680c8bf6ae29:function(t){return new Uint8Array(t)},__wbg_new_from_slice_a3d2629dc1826784:function(t,n){return new Uint8Array(H(t,n))},__wbg_next_3482f54c49e8af19:function(){return D(function(t){return t.next()},arguments)},__wbg_next_418f80d8f5303233:function(t){return t.next},__wbg_prototypesetcall_bdcdcc5842e4d77d:function(t,n,r){Uint8Array.prototype.set.call(H(t,n),r)},__wbg_push_8ffdcb2063340ba5:function(t,n){return t.push(n)},__wbg_set_1eb0999cf5d27fc8:function(t,n,r){return t.set(n,r)},__wbg_set_3f1d0b984ed272ed:function(t,n,r){t[n]=r},__wbg_set_6cb8631f80447a67:function(){return D(function(t,n,r){return Reflect.set(t,n,r)},arguments)},__wbg_set_f43e577aea94465b:function(t,n,r){t[n>>>0]=r},__wbg_stack_0ed75d68575b0f3c:function(t,n){const r=n.stack,o=M(r,c.__wbindgen_malloc,c.__wbindgen_realloc),a=p;y().setInt32(t+4,a,!0),y().setInt32(t+0,o,!0)},__wbg_value_0546255b415e96c1:function(t){return t.value},__wbindgen_cast_0000000000000001:function(t){return t},__wbindgen_cast_0000000000000002:function(t){return t},__wbindgen_cast_0000000000000003:function(t,n){return E(t,n)},__wbindgen_cast_0000000000000004:function(t){return BigInt.asUintN(64,t)},__wbindgen_init_externref_table:function(){const t=c.__wbindgen_externrefs,n=t.grow(4);t.set(0,void 0),t.set(n+0,void 0),t.set(n+1,null),t.set(n+2,!0),t.set(n+3,!1)}}}}function he(e){const t=c.__externref_table_alloc();return c.__wbindgen_externrefs.set(t,e),t}function U(e){const t=typeof e;if(t=="number"||t=="boolean"||e==null)return`${e}`;if(t=="string")return`"${e}"`;if(t=="symbol"){const o=e.description;return o==null?"Symbol":`Symbol(${o})`}if(t=="function"){const o=e.name;return typeof o=="string"&&o.length>0?`Function(${o})`:"Function"}if(Array.isArray(e)){const o=e.length;let a="[";o>0&&(a+=U(e[0]));for(let i=1;i1)r=n[1];else return toString.call(e);if(r=="Object")try{return"Object("+JSON.stringify(e)+")"}catch{return"Object"}return e instanceof Error?`${e.name}: ${e.message} +${e.stack}`:r}function H(e,t){return e=e>>>0,I().subarray(e/1,e/1+t)}let A=null;function y(){return(A===null||A.buffer.detached===!0||A.buffer.detached===void 0&&A.buffer!==c.memory.buffer)&&(A=new DataView(c.memory.buffer)),A}function E(e,t){return e=e>>>0,ke(e,t)}let B=null;function I(){return(B===null||B.byteLength===0)&&(B=new Uint8Array(c.memory.buffer)),B}function D(e,t){try{return e.apply(this,t)}catch(n){const r=he(n);c.__wbindgen_exn_store(r)}}function v(e){return e==null}function q(e,t){const n=t(e.length*1,1)>>>0;return I().set(e,n/1),p=e.length,n}function M(e,t,n){if(n===void 0){const s=N.encode(e),m=t(s.length,1)>>>0;return I().subarray(m,m+s.length).set(s),p=s.length,m}let r=e.length,o=t(r,1)>>>0;const a=I();let i=0;for(;i127)break;a[o+i]=s}if(i!==r){i!==0&&(e=e.slice(i)),o=n(o,r,r=i+e.length*3,1)>>>0;const s=I().subarray(o+i,o+r),m=N.encodeInto(e,s);i+=m.written,o=n(o,r,i,1)>>>0}return p=i,o}function Y(e){const t=c.__wbindgen_externrefs.get(e);return c.__externref_table_dealloc(e),t}let z=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});z.decode();const we=2146435072;let $=0;function ke(e,t){return $+=t,$>=we&&(z=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),z.decode(),$=t),z.decode(I().subarray(e,e+t))}const N=new TextEncoder;"encodeInto"in N||(N.encodeInto=function(e,t){const n=N.encode(e);return t.set(n),{read:e.length,written:n.length}});let p=0,c;function xe(e,t){return c=e.exports,A=null,B=null,c.__wbindgen_start(),c}async function Ae(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(o){if(e.ok&&n(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",o);else throw o}const r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{const r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}async function ve(e){if(c!==void 0)return c;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0&&(e=new URL(""+new URL("rl_replay_subtr_actor_bg-BjSK7HJ9.wasm",self.location.href).href,self.location.href));const t=pe();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));const{instance:n,module:r}=await Ae(await e,t);return xe(n)}const J="octane",Se={breakout:{kind:"breakout",label:"Breakout",length:131.4924,width:80.521,height:30.3,slopeDegrees:-.9795,groundHeightFront:43.8976,groundHeightBack:46.1454,offset:13.88,elevation:17.05},dominus:{kind:"dominus",label:"Dominus",length:127.9268,width:83.27995,height:31.3,slopeDegrees:-.9635,groundHeightFront:47.2238,groundHeightBack:49.3749,offset:13.88,elevation:17.05},hybrid:{kind:"hybrid",label:"Hybrid",length:127.0192,width:82.18787,height:34.15907,slopeDegrees:-.5499,groundHeightFront:54.0982,groundHeightBack:55.3173,offset:13.88,elevation:17.05},merc:{kind:"merc",label:"Merc",length:120.72,width:76.71,height:41.66,slopeDegrees:.28,groundHeightFront:60.76,groundHeightBack:61.35,offset:13.88,elevation:17.05},octane:{kind:"octane",label:"Octane",length:118.0074,width:84.19941,height:36.15907,slopeDegrees:-.5518,groundHeightFront:55.1449,groundHeightBack:56.2814,offset:13.88,elevation:17.05},plank:{kind:"plank",label:"Plank",length:128.8198,width:84.67036,height:29.3944,slopeDegrees:-.3447,groundHeightFront:44.998,groundHeightBack:45.773,offset:13.88,elevation:17.05}},Oe={"16batmobile":"plank","70dodgechargerrt":"dominus","89batmobile":"dominus","99nissanskylinegtrr34":"hybrid",aftershock:"dominus",animusgp:"breakout",artemis:"plank",artemisg1:"plank",artemisgxt:"plank",astonmartinvalhalla:"breakout",backfire:"octane",backtothefuturetimemachine:"dominus",batmobile1989:"dominus",battlebus:"merc",breakout:"breakout",breakouttypes:"breakout",centio:"plank",centiov17:"plank",cyclone:"breakout",deloreantimemachine:"dominus",diestro:"dominus",dominus:"dominus",dominusgt:"dominus",endo:"hybrid",esper:"hybrid",fast4wd:"octane",fennec:"octane",gazellagt:"dominus",gizmo:"octane",grog:"octane",guardian:"dominus",guardiang1:"dominus",guardiangxt:"dominus",hotshot:"dominus",icecharger:"dominus",imperatordt5:"dominus",jager619rs:"hybrid",jurassicjeepwrangler:"octane",mantis:"plank",marauder:"octane",masamune:"dominus",maverick:"dominus",maverickg1:"dominus",maverickgxt:"dominus",mclaren570s:"dominus",merc:"merc",mr11:"dominus",nimbus:"hybrid",octane:"octane",octanezsr:"octane",paladin:"plank",proteus:"octane",ripper:"dominus",roadhog:"octane",roadhogxl:"octane",samurai:"breakout",scarab:"octane",takumi:"octane",takumirxt:"octane",thedarkknightstumbler:"octane",thedarkknightrisestumbler:"octane",triton:"octane",twinmilliii:"plank",twinzer:"octane",venom:"hybrid",vulcan:"octane",werewolf:"dominus",xdevil:"hybrid",xdevilmk2:"hybrid",zippy:"octane","1966cadillacdeville":"breakout",ace:"breakout",admiral:"dominus",azura:"breakout",behemoth:"merc",beskar:"hybrid",bmwm3e30:"dominus",bmwm2racing:"dominus",bmwm4gt3evo:"dominus",bmw1series:"octane",bmw1seriesrle:"octane",bmwm240i:"dominus",bugatticentodieci:"plank",bumblebee:"dominus",bumblebeecar:"dominus",chevroletastro:"merc",chevroletcorvettestingray:"breakout",chevroletcorvettezr1:"breakout",chryslerpacifica:"hybrid",corlay:"octane",cyberpunkquadra:"breakout",defenderd7xr:"merc",diesel:"breakout",dodgechargerdaytonascatpack:"dominus",dodgerchargerdaytonascatpack:"dominus",dominusneon:"dominus",emperor:"breakout",emperorii:"breakout",emperoriifrozen:"breakout",emperoriiscorched:"breakout",fastfuriousdodgecharger:"dominus",fastandfuriousdodgecharger:"dominus",fastandfuriousdodgechargersrthellcat:"dominus",fastfuriousmazdarx7:"breakout",fastandfuriousmazdarx7:"breakout",fastfuriousnissanskyline:"hybrid",fastandfuriousnissanskyline:"hybrid",fastfuriouspontiacfiero:"hybrid",fastandfuriouspontiacfiero:"hybrid",fenneczrf:"octane",ferrari296gtb:"dominus",ferrarif40:"breakout",fordbroncoraptorrle:"merc",fordf150rle:"octane",fordmustanggtd:"dominus",fordmustangshelbygt500:"dominus",fordmustangmacherle:"octane",fordmustangshelbygt350rrle:"dominus",formula12021:"plank",formula12022:"plank",fuse:"breakout",havoc:"breakout",hearse:"hybrid",homerscar:"dominus",hondacivictyper:"octane",hondacivictyperle:"octane",jackal:"octane",jeepwranglerrubicon:"octane",kitt:"dominus",knightindustries2000:"dominus",komodo:"breakout",lamborghinicountachlpi8004:"dominus",lamborghinihuracansto:"dominus",lamborghiniurus:"hybrid",lamborghiniurusse:"hybrid",lightningmcqueen:"dominus",lightningmcqueencar:"dominus",lockjaw:"dominus",luiginsr:"octane",maestro:"dominus",magnifique:"dominus",magnifiquegxt:"dominus",mako:"breakout",mamba:"dominus",mario:"octane",marionsr:"octane",maven:"dominus",mclaren765lt:"dominus",mclarenp1:"dominus",mclarensenna:"breakout",megastar:"breakout",mercedesamggt63s:"dominus",mercedesbenzcla:"dominus",mudcat:"octane",mudcatg1:"octane",mudcatgxt:"octane",nissan350z:"dominus",nissanfairladyz:"dominus",nissanfairladyzrle:"dominus",nissansilvia:"hybrid",nissansilviarle:"hybrid",nissanskylinegtr:"hybrid",nissanskylinegtrr32:"hybrid",nissanzperformance:"dominus",nissanzperformancecar:"dominus",outlaw:"octane",outlawgxt:"octane",pattywagon:"octane",pizzaplanetdeliverytruck:"merc",pontiacfirebird:"breakout",porsche918spyder:"breakout",porsche911gt3rs:"dominus",porsche911turbo:"dominus",porsche911turborle:"dominus",primo:"hybrid",psyclops:"octane",quadraturbor:"breakout",ram1500rho:"hybrid",recoilav:"merc",redline:"breakout",revolver:"breakout",rivianr1s:"hybrid",scorpion:"dominus",shokunin:"octane",shokuningxt:"octane",stampede:"merc",teslacybertruck:"hybrid",themysterymachine:"merc",theincredibile:"breakout",turtlevan:"merc",voidburn:"hybrid",volkswagengolfgti:"octane",volkswagengolfgtirle:"octane",xentari:"octane",zefira:"dominus",breakoutx:"breakout",nexus:"breakout",nexussc:"breakout",whiplash:"breakout","007sastonmartindbs":"dominus","007sastonmartinvalhalla":"dominus",batmobile2022:"dominus",chikara:"dominus",chikarag1:"dominus",chikaragxt:"dominus",ecto1:"dominus",ecto1ghostbusters:"dominus",fastfuriousdodgechargersrthellcat:"dominus",gazellagthotwheels:"dominus",kittknightrider:"dominus",lamborghinihuracnsto:"dominus",mr11hotwheels:"dominus",nascarchevroletcamaro:"dominus",nascarfordmustang:"dominus",nascartoyotacamry:"dominus",nascarnextgenchevroletcamaro:"dominus",nascarnextgenchevroletcamaro2022:"dominus",nascarnextgenfordmustang:"dominus",nascarnextgenfordmustang2022:"dominus",nascarnextgentoyotacamry:"dominus",nascarnextgentoyotacamry2022:"dominus",nemesis:"dominus",peregrinett:"dominus",perigrinett:"dominus",ronin:"dominus",roning1:"dominus",roningxt:"dominus",samusgunship:"dominus",samusgunshipnintendoexclusive:"dominus",tyranno:"dominus",tyrannogxt:"dominus",insidio:"hybrid",jager619:"hybrid",jger619:"hybrid",jger619rs:"hybrid",r3mx:"hybrid",r3mxgxt:"hybrid",tygris:"hybrid",nomad:"merc",nomadgxt:"merc","007sastonmartindb5":"octane",armadillo:"octane",armadilloxboxexclusive:"octane",boneshaker:"octane",dingo:"octane",fast4wdhotwheels:"octane",harbinger:"octane",harbingergxt:"octane",hogsticker:"octane",hogstickerxboxexclusive:"octane",sweettooth:"octane",sweettoothplaystationexclusive:"octane",thedarkknighttumbler:"octane",batmobile2016:"plank",sentinel:"plank"};function Ie(e){const t={};for(const[n,r]of e)for(const o of n)t[o]=r;return t}const Te=Ie([[[22,1416,1894,1932,3031,3311,6243,6489,7651,7696,7890,7901,8006,8360,8361,8565,8566,8669,9357,10697,10698,10817,10822,11038,11394,11505,11677,11800,11933,11949,12173,12315,12361,12484],"breakout"],[[29,403,597,600,1018,1171,1286,1675,1689,1883,2070,2268,2666,2950,2951,3155,3156,3157,3265,3426,3875,3879,3880,4014,4155,4367,4472,4473,4745,4770,4781,4861,4864,5709,5773,5823,5858,5964,5979,6122,6244,6247,6260,6836,7211,7337,7338,7341,7343,7415,7512,7532,7593,7772,8454,9053,9088,9089,9140,9388,9894,10094,10440,10441,10694,10695,11016,11095,11315,11336,11534,11941,11996,12106,12142,12262,12286,12325,12382,12563,12669],"dominus"],[[28,31,1159,1317,1624,1856,2269,3451,3582,3702,5470,5488,5879,7012,9084,9085,9427,10044,10805,11138,11141,11379,11932,12569,12652],"hybrid"],[[30,4780,7336,7477,7815,7979,10689,11098,11736,11905,11950,12318,12335],"merc"],[[21,23,25,26,27,402,404,523,607,625,723,1172,1295,1300,1475,1478,1533,1568,1623,2665,2853,2919,2949,4284,4318,4319,4320,4782,4906,5020,5039,5188,5361,5547,5713,5837,5951,6939,7947,7948,8383,8806,8807,10896,10897,10900,10901,11314,11603,12104,12105],"octane"],[[24,803,1603,1691,1919,3594,3614,3622,4268,5265,7052,8524],"plank"]]);function Q(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function ee(e){if(!e)return null;switch(Q(e)){case"breakout":return"breakout";case"dominus":return"dominus";case"hybrid":return"hybrid";case"merc":return"merc";case"octane":return"octane";case"batmobile":case"plank":return"plank";default:return null}}function te(e){return e?Oe[Q(e)]??null:null}function Ee(e){return ee(e)??te(e)}function Be(e){return Se[e]}function X(e,t){if(!(!e||typeof e!="object")){if("Str"in e&&typeof e.Str=="string"){t.push(e.Str);return}if("Name"in e&&typeof e.Name=="string"){t.push(e.Name);return}if("Byte"in e&&e.Byte&&typeof e.Byte=="object"){const n=e.Byte;typeof n.kind=="string"&&t.push(n.kind),typeof n.value=="string"&&t.push(n.value);return}if("Struct"in e&&e.Struct&&typeof e.Struct=="object"){const n=e.Struct;if(typeof n.name=="string"&&t.push(n.name),Array.isArray(n.fields))for(const r of n.fields)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),X(r[1],t));return}if("Array"in e&&Array.isArray(e.Array)){for(const n of e.Array)if(Array.isArray(n))for(const r of n)Array.isArray(r)&&(typeof r[0]=="string"&&t.push(r[0]),X(r[1],t))}}}function De(e){const t=ee(e?.car_hitbox_family);if(t)return t;const n=e?.car_body_id;if(typeof n=="number"){const i=Te[n];if(i)return i}const r=te(e?.car_body_name);if(r)return r;const o=e?.stats;if(!o)return J;const a=[];for(const[i,s]of Object.entries(o))a.push(i),X(s,a);for(const i of a){const s=Ee(i);if(s)return s}return J}function x(e){const[t,n]=Object.entries(e)[0]??["Unknown","unknown"];return typeof n=="string"||typeof n=="number"?`${t}:${n}`:n&&typeof n=="object"?`${t}:${JSON.stringify(n)}`:`${t}:${JSON.stringify(n)}`}function P(e,t){return Math.max(0,e-t)}function ne(e){return new Map(e.map(t=>[t.id,t]))}const h=70,re=73,Ne=3072,Pe=4096,Fe=1792,Re=4184,Me=940,ze=3308,Ce=2816,oe=3584,je=2484,Le=1788,Ve=2300,Ue=2048,He=1036,Ye=1024,$e=1024,Xe=4240,ae=34;function C(e,t,n,r,o){e.push({index:e.length,padId:null,size:o,position:{x:t,y:n,z:r},events:[]})}function j(e,t,n,r,o){C(e,-t,n,r,o),C(e,t,n,r,o)}function W(e,t,n,r,o){C(e,t,-n,r,o),C(e,t,n,r,o)}function T(e,t,n,r,o){j(e,t,-n,r,o),j(e,t,n,r,o)}function We(){const e=[];return W(e,0,Xe,h,"small"),T(e,Fe,Re,h,"small"),T(e,Ne,Pe,re,"big"),T(e,Me,ze,h,"small"),W(e,0,Ce,h,"small"),T(e,oe,je,h,"small"),T(e,Le,Ve,h,"small"),T(e,Ue,He,h,"small"),W(e,0,$e,h,"small"),j(e,oe,0,re,"big"),j(e,Ye,0,h,"small"),e}function K(e){if(e==="Available")return!0;if(e&&typeof e=="object"){if("Available"in e)return!0;if("PickedUp"in e)return!1;const t=e.kind;if(t==="Available")return!0;if(t==="PickedUp")return!1}return null}function Ke(e){return e==="big"||e==="Big"?"big":e==="small"||e==="Small"?"small":null}function Ze(e){let t=null;for(const n of e){const r=K(n.kind);if(r===!1){t=n.time;continue}if(r===!0&&t!==null)return n.time-t>=7?"big":"small"}return null}function Ge(e,t,n,r){const o=ne(t),a=new Map;for(const u of e.boost_pad_events??[]){if(K(u.kind)===null){r?.advance();continue}const l=a.get(u.pad_id);l?l.push(u):a.set(u.pad_id,[u]),r?.advance()}const i=e.boost_pads;if(!i||i.length===0)return r?.advance(ae),We();const s=[...i].sort((u,d)=>u.index-d.index),m=new Array(s.length);for(let u=0;u=72?"big":"small"),w=g.sort((_,k)=>_.time-k.time),f=new Array(w.length);for(let _=0;_=0?e.frame:null}function qe(e,t){if(typeof e.time=="number"&&Number.isFinite(e.time))return e.time;const n=Z(e);if(n===null)return null;const r=t.frame_data.metadata_frames[n]?.time;return typeof r=="number"&&Number.isFinite(r)?r:null}function Je(e,t){return`bookmark:${Z(e)??"unknown"}:${e.description||"tick-mark"}:${t}`}function Qe(e,t,n){return(e.replay_tick_marks??[]).flatMap((r,o)=>{n?.advance();const a=qe(r,e);return a===null?[]:[{id:Je(r,o),description:r.description,frame:Z(r),time:P(a,t)}]})}function et(e){const t=e.description.trim()||"Replay bookmark";return{id:e.id,time:e.time,seekTime:e.time,frame:e.frame??void 0,kind:"bookmark",label:t,shortLabel:"BM",iconName:"bookmark"}}const S={distance:270,height:100,pitch:-4,fov:110},tt=.005,nt=Number.POSITIVE_INFINITY,rt=!0,ot=.15,at=10,it=.1,st=10;function ie(e){const t=Math.hypot(e.x,e.y,e.z);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t}}function se(e){const t=Math.hypot(e.x,e.y,e.z,e.w);return t<1e-6?null:{x:e.x/t,y:e.y/t,z:e.z/t,w:e.w/t}}function ce(e,t){return{w:e.w*t.w-e.x*t.x-e.y*t.y-e.z*t.z,x:e.w*t.x+e.x*t.w+e.y*t.z-e.z*t.y,y:e.w*t.y-e.x*t.z+e.y*t.w+e.z*t.x,z:e.w*t.z+e.x*t.y-e.y*t.x+e.z*t.w}}function ue(e,t){const n=ce(ce(t,{x:e.x,y:e.y,z:e.z,w:0}),{x:-t.x,y:-t.y,z:-t.z,w:t.w});return{x:n.x,y:n.y,z:n.z}}function ct(e){if(e==="Empty")return{position:null,linearVelocity:null,angularVelocity:null,rotation:null};const t=e.Data.rigid_body;return{position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:se(t.rotation)}}function le(e){return e==null?null:Math.max(-1,Math.min(1,(e-128)/128))}function de(e){return e==null?null:(e>127?e-256:e)*Math.PI/128}function fe(e){return e?{x:e[0],y:e[1],z:e[2]}:null}const ut={cameraPitch:null,cameraYaw:null,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null};function lt(e){if(e==="Empty")return{isPresent:!1,position:null,linearVelocity:null,angularVelocity:null,rotation:null,forward:null,up:null,boostAmount:0,boostFraction:0,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,...ut};const t=e.Data.rigid_body,n=se(t.rotation),r=n?ie(ue({x:1,y:0,z:0},n)):null,o=n?ie(ue({x:0,y:0,z:1},n)):null,a=e.Data.camera,i=e.Data.input;return{isPresent:!0,position:t.location,linearVelocity:t.linear_velocity??null,angularVelocity:t.angular_velocity??null,rotation:n,forward:r,up:o,boostAmount:e.Data.boost_amount,boostFraction:Math.max(0,Math.min(1,e.Data.boost_amount/255)),boostActive:e.Data.boost_active,powerslideActive:e.Data.powerslide_active,jumpActive:e.Data.jump_active,doubleJumpActive:e.Data.double_jump_active,dodgeActive:e.Data.dodge_active,cameraPitch:de(a?.pitch),cameraYaw:de(a?.yaw),throttle:le(i?.throttle),steer:le(i?.steer),dodgeImpulse:fe(i?.dodge_impulse),dodgeTorque:fe(i?.dodge_torque)}}function dt(e){return e.position!==null}function ft(e){return{...e,isPresent:!1,linearVelocity:null,angularVelocity:null,boostActive:!1,powerslideActive:!1,jumpActive:!1,doubleJumpActive:!1,dodgeActive:!1,throttle:null,steer:null,dodgeImpulse:null,dodgeTorque:null}}function mt(e){let t=null,n=null;for(let r=0;r=t.length-1)return;let o=F(t[r].position);for(let a=r+1;ait){o=F(s.position);continue}if(_t(o,s.position)>st){o=F(s.position);continue}const l={x:(i.linearVelocity.x+s.linearVelocity.x)/2,y:(i.linearVelocity.y+s.linearVelocity.y)/2,z:(i.linearVelocity.z+s.linearVelocity.z)/2},g={x:o.x+l.x*d,y:o.y+l.y*d,z:o.z+l.z*d},b=(a-r)%n.smoothingAnchorInterval===0?.5:n.smoothingBlendFactor;o={x:g.x*(1-b)+s.position.x*b,y:g.y*(1-b)+s.position.y*b,z:g.z*(1-b)+s.position.z*b},s.position=F(o)}}function bt(e){return{motionSmoothing:e.motionSmoothing??rt,smoothingBlendFactor:e.smoothingBlendFactor??ot,smoothingAnchorInterval:Math.max(1,e.smoothingAnchorInterval??at)}}function be(){return typeof performance>"u"?Date.now():performance.now()}function gt(e){const t=e.meta.team_zero.length+e.meta.team_one.length,n=e.frame_data.players.reduce((i,[,s])=>i+s.frames.length,0),r=e.boost_pads?.length??ae,o=e.boost_pad_events?.length??0,a=(e.goal_events?.length??0)+(e.player_stat_events?.length??0)+(e.demolish_infos?.length??0)+(e.replay_tick_marks?.length??0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,n),Math.max(1,e.frame_data.ball_data.frames.length),Math.max(1,r+o),Math.max(1,a)].reduce((i,s)=>i+s,0)}function yt(e){const t=e.frame_data.players.reduce((n,[,r])=>n+r.frames.length,0);return[Math.max(1,e.frame_data.metadata_frames.length),Math.max(1,t),Math.max(1,e.frame_data.ball_data.frames.length)].reduce((n,r)=>n+r,0)}function pt(e,t,n={}){const r=gt(e),o=yt(e);let a=0,i=0,s=-1,m=-1,u=be();const d=n.yieldEveryMs??Number.POSITIVE_INFINITY,l=n.progressReportMinDelta??tt,g=Math.max(1,n.progressReportFrameInterval??nt),b=()=>{if(!t)return!1;const f=Math.max(0,Math.min(1,a/r));if(f<=s)return!1;const k=i-m>=g;return f>=1||f-s>=l||k?(s=f,m=i,t(f,{progress:f,processedFrames:Math.min(i,o),totalFrames:o,processedUnits:a,totalUnits:r}),!0):!1},w=(f=!1)=>{const _=be();return!f&&_-ur===t)?.[1];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function xt(e){const t=kt(e?.stats);return{fov:O(t,"CameraFOV")??S.fov,height:O(t,"CameraHeight")??S.height,pitch:O(t,"CameraPitch")??S.pitch,distance:O(t,"CameraDistance")??S.distance,stiffness:O(t,"CameraStiffness")??S.stiffness,swivelSpeed:O(t,"CameraSwivelSpeed")??S.swivelSpeed,transitionSpeed:O(t,"CameraTransitionSpeed")??S.transitionSpeed}}function At(e,t){const n=new Map,r=new Map,o=[...e.meta.team_zero,...e.meta.team_one];if(o.length===0)return t?.advance(),{byId:n,byName:r};for(const a of o)r.set(a.name,a),a.remote_id&&n.set(x(a.remote_id),a),t?.advance();return{byId:n,byName:r}}function vt(e){const t=new Map;for(const[n,r]of e.player_camera_events??[])t.set(x(n),r.map(o=>({frame:o.frame,ballCamActive:o.ball_cam_active,behindViewActive:o.behind_view_active,driving:o.driving})));return t}function St(e,t){const n=new Set(e.meta.team_zero.map(m=>m.name)),r=new Set(e.meta.team_one.map(m=>m.name)),o=At(e,t),a=vt(e),i=[];let s=0;for(const[m,u]of e.frame_data.players){const d=new Array(u.frames.length);let l;for(let f=0;ft.time!==n.time?t.time-n.time:(t.frame??0)-(n.frame??0))}function Tt(e,t,n){const r=e.player?x(e.player):null,o=r?t.get(r)?.name??r:null,a=o?`${o} scored`:"Goal";return{id:G("goal",e.frame,r??"team"),time:P(e.time,n),frame:e.frame,kind:"goal",label:a,shortLabel:"G",playerId:r,playerName:o,isTeamZero:e.scoring_team_is_team_0}}function Et(e,t,n){const r=x(e.player),o=t.get(r)?.name??r,a=e.kind.toLowerCase(),i=e.kind==="Shot"?"shot":e.kind==="Save"?"save":"assist",s=e.kind==="Shot"?"SH":e.kind==="Save"?"SV":"A";return{id:G(a,e.frame,r),time:P(e.time,n),frame:e.frame,kind:a,label:`${o} ${i}`,shortLabel:s,playerId:r,playerName:o,location:e.shot?.shot_touch_position??e.shot?.ball_position??null,shot:e.shot??null,isTeamZero:e.is_team_0}}function Bt(e,t,n){const r=x(e.attacker),o=x(e.victim),a=t.get(r),i=t.get(o);return{id:G("demo",e.frame,`${r}:${o}`),time:P(e.time,n),frame:e.frame,kind:"demo",label:`${a?.name??r} demoed ${i?.name??o}`,shortLabel:"D",playerId:r,playerName:a?.name??r,secondaryPlayerId:o,secondaryPlayerName:i?.name??o,location:e.victim_location,isTeamZero:a?.isTeamZero??null}}function Dt(e,t,n,r,o){const a=ne(t),i=[];for(const s of e.goal_events??[])i.push(Tt(s,a,r)),o?.advance();for(const s of e.player_stat_events??[])i.push(Et(s,a,r)),o?.advance();for(const s of e.demolish_infos??[])i.push(Bt(s,a,r)),o?.advance();for(const s of n)i.push(et(s));return i.length===0&&o?.advance(),It(i)}function Nt(e,t={}){const n=pt(e,t.onProgress,{progressReportMinDelta:t.progressReportMinDelta,progressReportFrameInterval:t.progressReportFrameInterval}),r=e.frame_data.metadata_frames[0]?.time??0,o=ht(e,n),a=St(e,n),i=Ot(e,n),s=bt(t);_e(o,i,s);for(const l of a)_e(o,l.frames,s);const m=Ge(e,a,r,n),u=Qe(e,r,n),d=Dt(e,a,u,r,n);return n.finish(),{frameCount:o.length,duration:o.at(-1)?.time??0,rawStartTime:r,frames:o,ballFrames:i,boostPads:m,players:a,tickMarks:u,timelineEvents:d,teamZeroNames:e.meta.team_zero.map(l=>l.name),teamOneNames:e.meta.team_one.map(l=>l.name)}}function L(e){if(e instanceof Map)return Object.fromEntries(Array.from(e.entries()).map(([t,n])=>[t,L(n)]));if(Array.isArray(e))return e.map(t=>L(t));if(e&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=L(r);return t}return e}async function Pt(){const e=ve;typeof e=="function"&&await e()}function R(e){self.postMessage(e)}self.onmessage=async e=>{if(e.data.type==="load-replay")try{await Pt();const t=new Uint8Array(e.data.bytes);R({type:"progress",progress:{stage:"validating",progress:0}});const n=L(ye(t));if(!n.valid)throw new Error(n.error??"Replay validation failed");const r=ge(t,s=>{R({type:"progress",progress:s})},e.data.reportEveryNFrames);R({type:"progress",progress:{stage:"normalizing",progress:0}});const o=JSON.parse(new TextDecoder().decode(r)),a=Nt(o,{motionSmoothing:e.data.motionSmoothing,smoothingBlendFactor:e.data.smoothingBlendFactor,smoothingAnchorInterval:e.data.smoothingAnchorInterval,progressReportFrameInterval:e.data.reportEveryNFrames,onProgress(s){R({type:"progress",progress:{stage:"normalizing",progress:s}})}}),i=new TextEncoder().encode(JSON.stringify(a));self.postMessage({type:"done",rawBuffer:r.buffer,replayBuffer:i.buffer},[r.buffer,i.buffer])}catch(t){R({type:"error",error:t instanceof Error?t.message:String(t)})}}})(); diff --git a/crates/rocket-sense-server/static/subtr-actor/stats/index.html b/crates/rocket-sense-server/static/subtr-actor/stats/index.html index 056c1e7c..8c5b99d5 100644 --- a/crates/rocket-sense-server/static/subtr-actor/stats/index.html +++ b/crates/rocket-sense-server/static/subtr-actor/stats/index.html @@ -5,8 +5,8 @@ subtr-actor stats report - - + +
diff --git a/flake.lock b/flake.lock index 9f2e2db2..c7d81eeb 100644 --- a/flake.lock +++ b/flake.lock @@ -314,10 +314,10 @@ "uv2nix": "uv2nix" }, "locked": { - "lastModified": 1783320330, - "narHash": "sha256-gjP5C28tzPvOsfGcKLQFl7r7EXAXb1t928vdazfKiFE=", - "rev": "20eb0589911ea98e72fcaf55866b909e2af96a1c", - "revCount": 1859, + "lastModified": 1783582235, + "narHash": "sha256-Wamx7YkeTbpHOKVJ+Bi0VhUlEbQVktddW6ejJEMa58s=", + "rev": "db683e302b9028e5add304e449cb89d1f80702af", + "revCount": 1880, "type": "git", "url": "file:./vendor/subtr-actor" }, diff --git a/migrations/0089_leaderboard_player_window_cache.sql b/migrations/0089_leaderboard_player_window_cache.sql new file mode 100644 index 00000000..0e6cffd1 --- /dev/null +++ b/migrations/0089_leaderboard_player_window_cache.sql @@ -0,0 +1,131 @@ +-- Disposable read models for cross-player leaderboards. +-- +-- IMPORTANT: these tables are caches, not sources of truth. Canonical replay +-- metadata plus the per-replay/player fact tables remain authoritative. The +-- refresh job intentionally deletes and rebuilds these rows often; callers and +-- future migrations must never rely on cache rows surviving a refresh. + +CREATE TABLE leaderboard_cache_windows ( + window_key text PRIMARY KEY, + window_kind text NOT NULL, + season text, + window_start timestamptz, + window_end timestamptz, + is_current boolean NOT NULL DEFAULT false, + refreshed_at timestamptz NOT NULL DEFAULT now(), + CHECK (window_key <> ''), + CHECK (window_kind IN ('daily', 'trailing-7d', 'season')), + CHECK ((window_kind = 'season') = (season IS NOT NULL)) +); + +COMMENT ON TABLE leaderboard_cache_windows IS + 'Disposable leaderboard refresh metadata; canonical replay data is authoritative and this table is rebuilt often.'; + +-- One row per player and fully materialized scope. `*` / 0 mean that dimension +-- is unfiltered. Refresh uses a CUBE over the three dimensions, so normal UI +-- reads never need to GROUP BY the population before ordering it. +CREATE TABLE leaderboard_player_window_totals ( + window_key text NOT NULL REFERENCES leaderboard_cache_windows(window_key) ON DELETE CASCADE, + scope_game_type text NOT NULL, + scope_team_size smallint NOT NULL, + scope_playlist text NOT NULL, + platform text NOT NULL, + platform_player_id text NOT NULL, + replay_count bigint NOT NULL, + active_time_seconds double precision NOT NULL, + refreshed_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY ( + window_key, + scope_game_type, + scope_team_size, + scope_playlist, + platform, + platform_player_id + ), + CHECK (platform <> ''), + CHECK (platform_player_id <> ''), + CHECK (replay_count > 0), + CHECK (active_time_seconds >= 0.0) +); + +COMMENT ON TABLE leaderboard_player_window_totals IS + 'Disposable player/window leaderboard cache rebuilt from canonical replay appearances; never a source of truth.'; + +CREATE INDEX leaderboard_player_window_totals_rank_idx + ON leaderboard_player_window_totals ( + window_key, + scope_game_type, + scope_team_size, + scope_playlist, + replay_count DESC, + platform, + platform_player_id + ); + +-- Metric rows carry their already-matched appearance/time denominators. This +-- duplicates a little data deliberately: total and per-5-minute leaderboards +-- become bounded ordered-index reads rather than population-wide aggregates. +CREATE TABLE leaderboard_player_window_metrics ( + window_key text NOT NULL REFERENCES leaderboard_cache_windows(window_key) ON DELETE CASCADE, + scope_game_type text NOT NULL, + scope_team_size smallint NOT NULL, + scope_playlist text NOT NULL, + platform text NOT NULL, + platform_player_id text NOT NULL, + metric_kind text NOT NULL, + metric_key text NOT NULL, + total_value double precision NOT NULL, + replay_count bigint NOT NULL, + active_time_seconds double precision NOT NULL, + value_per_5_minutes double precision, + sample_count bigint, + average_value double precision, + refreshed_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY ( + window_key, + scope_game_type, + scope_team_size, + scope_playlist, + platform, + platform_player_id, + metric_kind, + metric_key + ), + CHECK (metric_kind IN ('event', 'stat')), + CHECK (metric_key <> ''), + CHECK (total_value >= 0.0), + CHECK (replay_count > 0), + CHECK (active_time_seconds >= 0.0), + CHECK (sample_count IS NULL OR sample_count >= 0) +); + +COMMENT ON TABLE leaderboard_player_window_metrics IS + 'Disposable player/window metric cache rebuilt often from canonical per-replay facts; never a source of truth.'; + +CREATE INDEX leaderboard_player_window_metrics_total_rank_idx + ON leaderboard_player_window_metrics ( + window_key, + metric_kind, + metric_key, + scope_game_type, + scope_team_size, + scope_playlist, + total_value DESC, + platform, + platform_player_id + ); + +CREATE INDEX leaderboard_player_window_metrics_rate_rank_idx + ON leaderboard_player_window_metrics ( + window_key, + metric_kind, + metric_key, + scope_game_type, + scope_team_size, + scope_playlist, + value_per_5_minutes DESC, + total_value DESC, + platform, + platform_player_id + ) + WHERE value_per_5_minutes IS NOT NULL; diff --git a/vendor/subtr-actor b/vendor/subtr-actor index 20eb0589..db683e30 160000 --- a/vendor/subtr-actor +++ b/vendor/subtr-actor @@ -1 +1 @@ -Subproject commit 20eb0589911ea98e72fcaf55866b909e2af96a1c +Subproject commit db683e302b9028e5add304e449cb89d1f80702af diff --git a/web/package-lock.json b/web/package-lock.json index b8b854a2..0962de84 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -3047,10 +3047,10 @@ } }, "vendor/@rlrml/player": { - "version": "1.1.0", + "version": "1.2.0", "license": "MIT", "dependencies": { - "@rlrml/subtr-actor": "1.1.0", + "@rlrml/subtr-actor": "1.2.0", "camera-controls": "^2.10.1" }, "peerDependencies": { @@ -3058,7 +3058,7 @@ } }, "vendor/@rlrml/subtr-actor": { - "version": "1.1.0", + "version": "1.2.0", "license": "MIT" }, "vendor/@rlrml/viewer": { diff --git a/web/src/stats/leaderboards.tsx b/web/src/stats/leaderboards.tsx index ef96b31d..956ac19a 100644 --- a/web/src/stats/leaderboards.tsx +++ b/web/src/stats/leaderboards.tsx @@ -22,16 +22,33 @@ import { StatPlayerLabel } from "./shared"; type MetricKind = "appearances" | "uploads" | "event" | "stat"; type Aggregation = "total" | "per-game" | "per-minute" | "share" | "average"; +type LeaderboardWindow = "daily" | "trailing-7d" | "season"; const PAGE_SIZE = 50; const RATE_WINDOW_MINUTES = 5; -const DEFAULT_MIN_GAMES = "10"; const DEFAULT_BOARD = "event:goal"; -const EVENT_AGGREGATIONS: Aggregation[] = ["total", "per-game", "per-minute"]; -const STAT_AGGREGATIONS: Aggregation[] = ["total", "per-game", "per-minute", "share"]; +const EVENT_AGGREGATIONS: Aggregation[] = ["total", "per-minute"]; +const STAT_AGGREGATIONS: Aggregation[] = ["total", "per-minute"]; const AVERAGE_STAT_AGGREGATIONS: Aggregation[] = ["average"]; +const windowOptions: Array<{ value: LeaderboardWindow; label: string }> = [ + { value: "daily", label: "Today" }, + { value: "trailing-7d", label: "Last 7 days" }, + { value: "season", label: "Season" }, +]; + +function defaultMinGames(window: LeaderboardWindow): string { + switch (window) { + case "daily": + return "3"; + case "trailing-7d": + return "10"; + case "season": + return "25"; + } +} + // A leaderboard is one METRIC ranked by an AGGREGATION within a SCOPE. Every // rankable thing — counted events, accumulated stats, plain activity counts — // is described by a single CatalogMetric, so the picker, the URL, and the table @@ -148,7 +165,7 @@ const statOptions: Array<{ label: "Ball advance", category: "possession", unit: "uu", - aggregations: ["total", "per-game", "per-minute"], + aggregations: STAT_AGGREGATIONS, description: "Distance the player advanced the ball during possessions.", }, { @@ -172,7 +189,7 @@ const statOptions: Array<{ label: "High aerial touches", category: "mechanic", unit: "count", - aggregations: ["total", "per-game", "per-minute"], + aggregations: STAT_AGGREGATIONS, description: "Touches classified as high aerial contacts.", }, { @@ -180,7 +197,7 @@ const statOptions: Array<{ label: "Control touches", category: "possession", unit: "count", - aggregations: ["total", "per-game", "per-minute"], + aggregations: STAT_AGGREGATIONS, description: "Touches classified as controlled contacts.", }, { @@ -188,7 +205,7 @@ const statOptions: Array<{ label: "Big boost pad count", category: "boost", unit: "count", - aggregations: ["total", "per-game", "per-minute"], + aggregations: STAT_AGGREGATIONS, description: "Big boost pads collected by the player.", }, { @@ -196,7 +213,7 @@ const statOptions: Array<{ label: "Small boost pad count", category: "boost", unit: "count", - aggregations: ["total", "per-game", "per-minute"], + aggregations: STAT_AGGREGATIONS, description: "Small boost pads collected by the player.", }, { @@ -204,7 +221,7 @@ const statOptions: Array<{ label: "Boost from big pads", category: "boost", unit: "boost", - aggregations: ["total", "per-game", "per-minute"], + aggregations: STAT_AGGREGATIONS, description: "Boost amount collected from big pads.", }, { @@ -212,7 +229,7 @@ const statOptions: Array<{ label: "Boost from small pads", category: "boost", unit: "boost", - aggregations: ["total", "per-game", "per-minute"], + aggregations: STAT_AGGREGATIONS, description: "Boost amount collected from small pads.", }, ]; @@ -248,16 +265,18 @@ function defaultAggregation(metric: CatalogMetric): Aggregation | null { // Build the full metric catalog: static activity + stat metrics, plus one entry // per countable event type from the live registry. function buildCatalog(eventTypes: EventTypeResponse[]): CatalogMetric[] { - const statMetrics: CatalogMetric[] = statOptions.map((option) => ({ - id: `stat:${option.value}`, - kind: "stat", - label: option.label, - category: option.category, - param: option.value, - unit: option.unit, - aggregations: option.aggregations, - description: option.description, - })); + const statMetrics: CatalogMetric[] = statOptions + .filter((option) => !isAverageStat(option.value)) + .map((option) => ({ + id: `stat:${option.value}`, + kind: "stat", + label: option.label, + category: option.category, + param: option.value, + unit: option.unit, + aggregations: option.aggregations, + description: option.description, + })); const eventMetrics: CatalogMetric[] = eventTypes.map((eventType) => ({ id: `event:${eventType.key}`, kind: "event", @@ -309,14 +328,6 @@ function formatRate(value: number | null): string { return value == null ? "-" : value.toLocaleString(undefined, { maximumFractionDigits: 2 }); } -function formatPercent(value: number | null): string { - if (value == null || !Number.isFinite(value)) return "-"; - return value.toLocaleString(undefined, { - maximumFractionDigits: 1, - style: "percent", - }); -} - function formatDurationCompact(value: number | null): string { if (value == null || !Number.isFinite(value)) return "-"; const totalSeconds = Math.max(0, Math.round(value)); @@ -405,19 +416,7 @@ const playlistOptions = [ { value: "tournament", label: "Tournament" }, ]; -const seasonOptions = buildSeasonOptions("Any season", { newestFirst: true }); - -function dateInputFromParam(value: string | null): string { - if (!value) return ""; - const date = new Date(value); - if (Number.isNaN(date.getTime())) return ""; - return date.toISOString().slice(0, 10); -} - -function replayDateParam(value: string, edge: "start" | "end"): string { - const suffix = edge === "start" ? "T00:00:00" : "T23:59:59.999"; - return new Date(`${value}${suffix}`).toISOString(); -} +const seasonOptions = buildSeasonOptions("Current season", { newestFirst: true }); // Read the selected board id, migrating the legacy metric/event-type/stat params // so old links and bookmarks still resolve. @@ -688,7 +687,6 @@ function EventLeaderboard({ Rank Total Games - Per game {rateColumnLabel} @@ -716,7 +714,6 @@ function EventLeaderboard({ {row.event_count.toLocaleString()} {row.replay_count.toLocaleString()} - {formatRate(row.count_per_game)} {formatRate(perRateWindow(row.per_active_minute, rateWindowMinutes))} ); @@ -750,7 +747,6 @@ function StatLeaderboard({ useLeaderboard(getStatLeaderboard, filterKey); const rateColumnLabel = rateWindowMinutes === 1 ? "Per min" : `Per ${rateWindowMinutes} min`; const averageStat = isAverageStat(statKey); - const showShare = unit === "seconds" && !averageStat; if (loading) return
Loading leaderboard…
; if (error) return
Failed to load leaderboard: {error}
; @@ -810,9 +806,7 @@ function StatLeaderboard({ Player Rank Total - {showShare ? Share : null} Games - Per game {rateColumnLabel} @@ -839,9 +833,7 @@ function StatLeaderboard({ /> {formatStatValue(row.value, unit)} - {showShare ? {formatPercent(row.share_of_active_time)} : null} {row.replay_count.toLocaleString()} - {formatStatValue(row.value_per_game, unit)} {perStatWindow(row.value_per_active_minute, rateWindowMinutes, unit)} ); @@ -1072,9 +1064,10 @@ export function LeaderboardsPage() { const gameType = params.get("game-type") ?? ""; const playlist = params.get("playlist") ?? ""; const season = params.get("season") ?? ""; - const replayDateAfter = dateInputFromParam(params.get("replay-date-after")); - const replayDateBefore = dateInputFromParam(params.get("replay-date-before")); - const minGames = params.get("min-games") ?? DEFAULT_MIN_GAMES; + const windowParam = params.get("window"); + const window: LeaderboardWindow = + windowParam === "daily" || windowParam === "season" ? windowParam : "trailing-7d"; + const minGames = params.get("min-games") ?? defaultMinGames(window); const selectedEventType = metric.kind === "event" ? eventTypes.find((option) => option.key === metric.param) : undefined; @@ -1087,7 +1080,8 @@ export function LeaderboardsPage() { : metric.aggregations.includes(sortParam as Aggregation) ? (sortParam as Aggregation) : defaultAggregation(metric); - const showMinGames = metric.kind === "event" || metric.kind === "stat"; + const showMinGames = + activeSort === "per-minute" && (metric.kind === "event" || metric.kind === "stat"); const setParam = useCallback( (key: string, value: string) => { @@ -1103,20 +1097,6 @@ export function LeaderboardsPage() { [location.pathname, location.search, navigate], ); - const setReplayDateParam = useCallback( - (key: "replay-date-after" | "replay-date-before", value: string, edge: "start" | "end") => { - const next = new URLSearchParams(location.search); - if (value) { - next.set(key, replayDateParam(value, edge)); - } else { - next.delete(key); - } - const query = next.toString(); - navigate(query ? `${location.pathname}?${query}` : location.pathname, { replace: true }); - }, - [location.pathname, location.search, navigate], - ); - const selectBoard = useCallback( (id: string) => { const next = new URLSearchParams(location.search); @@ -1141,44 +1121,45 @@ export function LeaderboardsPage() { // own metric param, ranking, and min-games threshold on top. const replayFilterKey = useMemo(() => { const filters = new URLSearchParams(); + filters.set("window", window); if (teamSize) filters.set("team-size", teamSize); if (gameType) filters.set("game-type", gameType); if (playlist) filters.set("playlist", playlist); - if (season) { + if (window === "season" && season) { filters.set("season", season); - // Production leaderboards already support season ranges. Keep the exact - // `season` param for replay-list links, and encode the same choice as a - // one-season range for leaderboard API reads. - filters.set("min-season", season); - filters.set("max-season", season); } - const rawReplayDateAfter = params.get("replay-date-after"); - const rawReplayDateBefore = params.get("replay-date-before"); - if (rawReplayDateAfter) filters.set("replay-date-after", rawReplayDateAfter); - if (rawReplayDateBefore) filters.set("replay-date-before", rawReplayDateBefore); return filters.toString(); - }, [gameType, params, playlist, season, teamSize]); + }, [gameType, playlist, season, teamSize, window]); const boardFilterKey = useMemo(() => { const filters = new URLSearchParams(replayFilterKey); if (metric.kind === "event") { if (metric.param) filters.set("event-type", metric.param); if (activeSort && activeSort !== "total") filters.set("sort", activeSort); - if (minGames) filters.set("min-games", minGames); + if (activeSort === "per-minute" && minGames) filters.set("min-games", minGames); } else if (metric.kind === "stat") { if (metric.param) filters.set("stat", metric.param); if (activeSort) filters.set("sort", activeSort); - if (minGames) filters.set("min-games", minGames); + if (activeSort === "per-minute" && minGames) filters.set("min-games", minGames); } return filters.toString(); }, [activeSort, metric.kind, metric.param, minGames, replayFilterKey]); const replayBrowseFilterKey = useMemo(() => { const filters = new URLSearchParams(replayFilterKey); - filters.delete("min-season"); - filters.delete("max-season"); + filters.delete("window"); + if (window === "daily") { + const start = new Date(); + start.setUTCHours(0, 0, 0, 0); + filters.set("replay-date-after", start.toISOString()); + } else if (window === "trailing-7d") { + filters.set( + "replay-date-after", + new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(), + ); + } return filters.toString(); - }, [replayFilterKey]); + }, [replayFilterKey, window]); return (
@@ -1192,6 +1173,13 @@ export function LeaderboardsPage() {
+ setParam("window", value)} + /> - - - + {window === "season" ? ( + + ) : null} {showMinGames ? (