Initial commit: the FS25 Lua mod (live.json data export), the FS25-WebDashboard project (Node/web dashboard + PySide6 desktop variant), and FarmHUD (standalone PySide6 companion app with Discord Rich Presence, settings, and installer).
954 lines
38 KiB
JavaScript
954 lines
38 KiB
JavaScript
(() => {
|
||
'use strict';
|
||
|
||
const POLL_INTERVAL_MS = 500;
|
||
const GAUGE_ARC_LENGTH = Math.PI * 80; // pi * radius(80) - matches the arc path in index.html exactly
|
||
const SPEED_HISTORY_WINDOW_MS = 60000;
|
||
|
||
const WEATHER_ICONS = {
|
||
SUN: '☀️',
|
||
PARTIALLY_CLOUDY: '🌤️',
|
||
CLOUDY: '☁️',
|
||
RAIN: '🌧️',
|
||
SNOW: '❄️',
|
||
HAIL: '🧊',
|
||
TWISTER: '🌪️',
|
||
THUNDER: '⛈️',
|
||
};
|
||
|
||
const WEATHER_LABELS_DE = {
|
||
SUN: 'Sonnig',
|
||
PARTIALLY_CLOUDY: 'Teils bewölkt',
|
||
CLOUDY: 'Bewölkt',
|
||
RAIN: 'Regen',
|
||
SNOW: 'Schnee',
|
||
HAIL: 'Hagel',
|
||
TWISTER: 'Tornado',
|
||
THUNDER: 'Gewitter',
|
||
};
|
||
|
||
/** @type {{selectedVehicleId: any, speedHistory: {t:number, v:number}[], lastData: any}} */
|
||
const state = {
|
||
selectedVehicleId: null,
|
||
followMyVehicle: true, // true = panel always shows the vehicle you're currently driving
|
||
speedHistory: [],
|
||
lastData: null,
|
||
};
|
||
|
||
// ---------------------------------------------------------------------
|
||
// DOM refs
|
||
// ---------------------------------------------------------------------
|
||
const el = (id) => document.getElementById(id);
|
||
const statusDot = el('statusDot');
|
||
const statusText = el('statusText');
|
||
const vehicleCountEl = el('vehicleCount');
|
||
const vehicleNameEl = el('vehicleName');
|
||
const vehicleTypeEl = el('vehicleType');
|
||
const followMyVehicleBtn = el('followMyVehicleBtn');
|
||
const manualSelectHintEl = el('manualSelectHint');
|
||
const speedValueEl = el('speedValue');
|
||
const speedGaugeFill = el('speedGaugeFill');
|
||
const rpmValueEl = el('rpmValue');
|
||
const rpmGaugeFill = el('rpmGaugeFill');
|
||
const cruiseValueEl = el('cruiseValue');
|
||
const cruiseChip = el('cruiseChip');
|
||
const motorValueEl = el('motorValue');
|
||
const loadValueEl = el('loadValue');
|
||
const fuelTextEl = el('fuelText');
|
||
const fuelBarEl = el('fuelBar');
|
||
const damageTextEl = el('damageText');
|
||
const damageBarEl = el('damageBar');
|
||
const dirtTextEl = el('dirtText');
|
||
const dirtBarEl = el('dirtBar');
|
||
const ownFillUnitsListEl = el('ownFillUnitsList');
|
||
const implementsListEl = el('implementsList');
|
||
const hoursValueEl = el('hoursValue');
|
||
const priceValueEl = el('priceValue');
|
||
const sellPriceValueEl = el('sellPriceValue');
|
||
const positionValueEl = el('positionValue');
|
||
const headingValueEl = el('headingValue');
|
||
const mapIdTextEl = el('mapIdText');
|
||
const speedHistoryCanvas = el('speedHistory');
|
||
const speedHistoryCtx = speedHistoryCanvas.getContext('2d');
|
||
const clockText = el('clockText');
|
||
const dayText = el('dayText');
|
||
const seasonText = el('seasonText');
|
||
const periodTextEl = el('periodText');
|
||
const scaleText = el('scaleText');
|
||
const weatherIcon = el('weatherIcon');
|
||
const weatherType = el('weatherType');
|
||
const weatherTemp = el('weatherTemp');
|
||
const weatherBadgesEl = el('weatherBadges');
|
||
const weatherExtraEl = el('weatherExtra');
|
||
const forecastStrip = el('forecastStrip');
|
||
const farmName = el('farmName');
|
||
const farmMoney = el('farmMoney');
|
||
const farmlandCountEl = el('farmlandCount');
|
||
const farmlandValueEl = el('farmlandValue');
|
||
const playerStatusValueEl = el('playerStatusValue');
|
||
const otherFarmsHeadEl = el('otherFarmsHead');
|
||
const otherFarmsListEl = el('otherFarmsList');
|
||
const farmlandListEl = el('farmlandList');
|
||
const siloListEl = el('siloList');
|
||
const husbandryListEl = el('husbandryList');
|
||
const productionListEl = el('productionList');
|
||
const vehicleTableBody = el('vehicleTableBody');
|
||
|
||
// ---------------------------------------------------------------------
|
||
// Theme + fullscreen
|
||
// ---------------------------------------------------------------------
|
||
const THEME_KEY = 'fs25dash.theme';
|
||
function applyStoredTheme() {
|
||
try {
|
||
const saved = localStorage.getItem(THEME_KEY);
|
||
if (saved) document.documentElement.setAttribute('data-theme', saved);
|
||
} catch (e) { /* localStorage may be unavailable, ignore */ }
|
||
}
|
||
applyStoredTheme();
|
||
|
||
el('themeToggle').addEventListener('click', () => {
|
||
const current = document.documentElement.getAttribute('data-theme') === 'light' ? 'light' : 'dark';
|
||
const next = current === 'light' ? 'dark' : 'light';
|
||
document.documentElement.setAttribute('data-theme', next);
|
||
try { localStorage.setItem(THEME_KEY, next); } catch (e) { /* ignore */ }
|
||
});
|
||
|
||
el('fullscreenBtn').addEventListener('click', () => {
|
||
if (!document.fullscreenElement) {
|
||
document.documentElement.requestFullscreen().catch(() => {});
|
||
} else {
|
||
document.exitFullscreen().catch(() => {});
|
||
}
|
||
});
|
||
|
||
// ---------------------------------------------------------------------
|
||
// Collapsible panels (state remembered per panel across reloads)
|
||
// ---------------------------------------------------------------------
|
||
const COLLAPSE_KEY_PREFIX = 'fs25dash.collapsed.';
|
||
document.querySelectorAll('.panel[data-panel-id]').forEach((panel) => {
|
||
const id = panel.dataset.panelId;
|
||
let collapsed = false;
|
||
try { collapsed = localStorage.getItem(COLLAPSE_KEY_PREFIX + id) === '1'; } catch (e) { /* ignore */ }
|
||
panel.classList.toggle('collapsed', collapsed);
|
||
|
||
const toggleBtn = panel.querySelector(':scope > .panel-header > .panel-toggle');
|
||
if (toggleBtn) {
|
||
toggleBtn.addEventListener('click', () => {
|
||
const nowCollapsed = panel.classList.toggle('collapsed');
|
||
try { localStorage.setItem(COLLAPSE_KEY_PREFIX + id, nowCollapsed ? '1' : '0'); } catch (e) { /* ignore */ }
|
||
// A panel that was hidden (display:none) had a 0x0 canvas inside it -
|
||
// force a fresh render once it's visible again so the map/sparkline
|
||
// pick up their real size immediately instead of waiting for the
|
||
// next poll.
|
||
if (!nowCollapsed && state.lastData) onData(state.lastData);
|
||
});
|
||
}
|
||
});
|
||
|
||
// ---------------------------------------------------------------------
|
||
// Polling
|
||
// ---------------------------------------------------------------------
|
||
async function pollOnce() {
|
||
try {
|
||
const res = await fetch('/api/live', { cache: 'no-store' });
|
||
const data = await res.json();
|
||
state.lastData = data;
|
||
onData(data);
|
||
setStatus(data.connected !== false, data);
|
||
} catch (err) {
|
||
setStatus(false, null);
|
||
}
|
||
}
|
||
|
||
function setStatus(live, data) {
|
||
statusDot.classList.toggle('live', !!live);
|
||
if (live) {
|
||
statusText.textContent = 'Live';
|
||
} else if (data && data.error) {
|
||
statusText.textContent = 'Warte auf Spiel…';
|
||
} else {
|
||
statusText.textContent = 'Keine Verbindung zum Server';
|
||
}
|
||
}
|
||
|
||
setInterval(pollOnce, POLL_INTERVAL_MS);
|
||
pollOnce();
|
||
|
||
// ---------------------------------------------------------------------
|
||
// Main render dispatch
|
||
// ---------------------------------------------------------------------
|
||
function onData(data) {
|
||
if (!data) return;
|
||
|
||
const vehicles = Array.isArray(data.vehicles) ? data.vehicles : [];
|
||
vehicleCountEl.textContent = vehicles.length + (vehicles.length === 1 ? ' Fahrzeug' : ' Fahrzeuge');
|
||
mapIdTextEl.textContent = data.mission && data.mission.mapId ? ('· ' + data.mission.mapId) : '';
|
||
|
||
ensureSelection(vehicles, data.controlledVehicleId);
|
||
|
||
renderVehicleTable(vehicles);
|
||
renderSelectedVehicle(vehicles);
|
||
renderTime(data.time);
|
||
renderWeather(data.weather, data.time);
|
||
renderFarm(data.mission, data.farmlands, data.farms);
|
||
renderStorage(data.silos, data.husbandries, data.productions, data.farms);
|
||
renderPlayerStatus(data.player);
|
||
}
|
||
|
||
function renderPlayerStatus(player) {
|
||
if (!player) {
|
||
playerStatusValueEl.textContent = '–';
|
||
return;
|
||
}
|
||
if (player.isControllingVehicle) {
|
||
playerStatusValueEl.textContent = 'im Fahrzeug';
|
||
} else if (typeof player.x === 'number' && typeof player.z === 'number') {
|
||
playerStatusValueEl.textContent = 'zu Fuß (' + Math.round(player.x) + ', ' + Math.round(player.z) + ')';
|
||
} else {
|
||
playerStatusValueEl.textContent = 'zu Fuß';
|
||
}
|
||
}
|
||
|
||
function ensureSelection(vehicles, controlledVehicleId) {
|
||
// "Follow me" (default): always show whatever you're currently sitting
|
||
// in, even if something else was clicked earlier - as long as you ARE
|
||
// in a vehicle. Getting out doesn't cancel follow mode, it just has
|
||
// nothing to jump to yet (falls through to the manual/fallback logic
|
||
// below) until you get back in.
|
||
if (state.followMyVehicle && controlledVehicleId != null && vehicles.some((v) => v.id === controlledVehicleId)) {
|
||
selectVehicle(controlledVehicleId, { manual: false });
|
||
return;
|
||
}
|
||
|
||
if (state.selectedVehicleId != null && vehicles.some((v) => v.id === state.selectedVehicleId)) {
|
||
return;
|
||
}
|
||
if (controlledVehicleId != null && vehicles.some((v) => v.id === controlledVehicleId)) {
|
||
selectVehicle(controlledVehicleId, { manual: false });
|
||
return;
|
||
}
|
||
if (vehicles.length > 0) {
|
||
selectVehicle(vehicles[0].id, { manual: false });
|
||
} else {
|
||
state.selectedVehicleId = null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* @param {*} id vehicle id to show in the main panel / highlight
|
||
* @param {{manual?: boolean}} [opts] pass {manual: true} for an explicit
|
||
* user click - this turns follow-mode off so the pick sticks even while
|
||
* driving. Internal/automatic selections omit this (or pass false).
|
||
*/
|
||
function selectVehicle(id, opts) {
|
||
if (state.selectedVehicleId !== id) {
|
||
state.speedHistory = [];
|
||
}
|
||
state.selectedVehicleId = id;
|
||
if (opts && opts.manual) {
|
||
state.followMyVehicle = false;
|
||
}
|
||
}
|
||
|
||
function followMyVehicleNow() {
|
||
state.followMyVehicle = true;
|
||
if (state.lastData) onData(state.lastData);
|
||
}
|
||
el('followMyVehicleBtn').addEventListener('click', followMyVehicleNow);
|
||
|
||
// ---------------------------------------------------------------------
|
||
// Canvas helpers (still used by the speed sparkline below)
|
||
// ---------------------------------------------------------------------
|
||
function resizeCanvasToDisplaySize(canvas) {
|
||
const ratio = window.devicePixelRatio || 1;
|
||
const rect = canvas.getBoundingClientRect();
|
||
const width = Math.max(1, Math.round(rect.width * ratio));
|
||
const height = Math.max(1, Math.round(rect.height * ratio));
|
||
if (canvas.width !== width || canvas.height !== height) {
|
||
canvas.width = width;
|
||
canvas.height = height;
|
||
}
|
||
return ratio;
|
||
}
|
||
|
||
function getCssVar(name) {
|
||
return getComputedStyle(document.documentElement).getPropertyValue(name).trim() || '#888';
|
||
}
|
||
|
||
// ---------------------------------------------------------------------
|
||
// Vehicle table
|
||
// ---------------------------------------------------------------------
|
||
function renderVehicleTable(vehicles) {
|
||
vehicleTableBody.innerHTML = '';
|
||
const sorted = [...vehicles].sort((a, b) => (a.name || '').localeCompare(b.name || '', 'de'));
|
||
|
||
for (const v of sorted) {
|
||
const tr = document.createElement('tr');
|
||
if (v.id === state.selectedVehicleId) tr.classList.add('selected');
|
||
tr.addEventListener('click', () => { selectVehicle(v.id, { manual: true }); if (state.lastData) onData(state.lastData); });
|
||
|
||
tr.appendChild(cell(v.name || 'Unbenannt'));
|
||
tr.appendChild(cell(isDrivable(v) ? formatNumber(v.speedKmh, 0) : '–'));
|
||
tr.appendChild(cell(formatNumber(v.rpm, 0)));
|
||
tr.appendChild(cell(v.cruiseControlActive ? `an (${formatNumber(v.cruiseControlSpeed, 0)})` : '–'));
|
||
tr.appendChild(cell(formatFuel(v)));
|
||
|
||
const damageCell = cell(typeof v.damagePercent === 'number' ? Math.round(Math.max(0, v.damagePercent)) + '%' : '–');
|
||
if (typeof v.damagePercent === 'number' && v.damagePercent >= 50) {
|
||
damageCell.style.color = 'var(--danger)';
|
||
damageCell.style.fontWeight = '600';
|
||
}
|
||
tr.appendChild(damageCell);
|
||
|
||
vehicleTableBody.appendChild(tr);
|
||
}
|
||
|
||
if (sorted.length === 0) {
|
||
const tr = document.createElement('tr');
|
||
const td = document.createElement('td');
|
||
td.colSpan = 6;
|
||
td.textContent = 'Keine Fahrzeuge geladen – starte das Spiel mit dem WebDashboard-Mod und lade einen Spielstand.';
|
||
td.style.color = 'var(--text-dim)';
|
||
tr.appendChild(td);
|
||
vehicleTableBody.appendChild(tr);
|
||
}
|
||
}
|
||
|
||
function cell(text) {
|
||
const td = document.createElement('td');
|
||
td.textContent = text;
|
||
return td;
|
||
}
|
||
|
||
// A plain implement (trailer, plow, seed drill, ...) has neither an
|
||
// engine (Motorized) nor its own steering/cruise control (Drivable) - its
|
||
// "speed" is just whatever's towing it, so showing a km/h number for it
|
||
// is noise rather than information.
|
||
function isDrivable(v) {
|
||
return typeof v.motorStarted === 'boolean' || typeof v.cruiseControlActive === 'boolean';
|
||
}
|
||
|
||
function formatFuel(v) {
|
||
if (typeof v.fuelLevel !== 'number' || typeof v.fuelCapacity !== 'number' || v.fuelCapacity <= 0) {
|
||
return '–';
|
||
}
|
||
return Math.round((v.fuelLevel / v.fuelCapacity) * 100) + '%';
|
||
}
|
||
|
||
// ---------------------------------------------------------------------
|
||
// Selected vehicle panel
|
||
// ---------------------------------------------------------------------
|
||
function renderSelectedVehicle(vehicles) {
|
||
manualSelectHintEl.hidden = state.followMyVehicle;
|
||
followMyVehicleBtn.classList.toggle('active', state.followMyVehicle);
|
||
|
||
const v = vehicles.find((x) => x.id === state.selectedVehicleId);
|
||
if (!v) {
|
||
vehicleNameEl.textContent = 'Kein Fahrzeug ausgewählt';
|
||
vehicleTypeEl.textContent = '';
|
||
setGauge(speedGaugeFill, 0);
|
||
setGauge(rpmGaugeFill, 0);
|
||
speedValueEl.textContent = '0';
|
||
rpmValueEl.textContent = '0';
|
||
cruiseValueEl.textContent = 'aus';
|
||
motorValueEl.textContent = '–';
|
||
loadValueEl.textContent = '–';
|
||
fuelTextEl.textContent = '–';
|
||
fuelBarEl.style.width = '0%';
|
||
damageTextEl.textContent = '–';
|
||
damageBarEl.style.width = '0%';
|
||
dirtTextEl.textContent = '–';
|
||
dirtBarEl.style.width = '0%';
|
||
hoursValueEl.textContent = '–';
|
||
priceValueEl.textContent = '–';
|
||
sellPriceValueEl.textContent = '–';
|
||
positionValueEl.textContent = '–';
|
||
headingValueEl.textContent = '–';
|
||
renderOwnFillUnits(null);
|
||
renderImplements(null, vehicles);
|
||
return;
|
||
}
|
||
|
||
vehicleNameEl.textContent = v.name || 'Unbenannt';
|
||
vehicleTypeEl.textContent = v.typeName || '';
|
||
|
||
const vehicleIsDrivable = isDrivable(v);
|
||
const speed = (vehicleIsDrivable && typeof v.speedKmh === 'number') ? Math.max(0, v.speedKmh) : 0;
|
||
const speedMax = Math.max(60, Math.ceil(speed / 20) * 20);
|
||
setGauge(speedGaugeFill, speed / speedMax);
|
||
speedValueEl.textContent = vehicleIsDrivable ? formatNumber(speed, 0) : '–';
|
||
|
||
const rpmFraction = typeof v.rpmPercent === 'number' ? v.rpmPercent / 100 : 0;
|
||
setGauge(rpmGaugeFill, rpmFraction);
|
||
rpmValueEl.textContent = formatNumber(v.rpm, 0);
|
||
|
||
if (v.cruiseControlActive) {
|
||
const maxText = typeof v.cruiseControlMaxSpeed === 'number' ? ' (max ' + formatNumber(v.cruiseControlMaxSpeed, 0) + ')' : '';
|
||
cruiseValueEl.textContent = 'an · ' + formatNumber(v.cruiseControlSpeed, 0) + ' km/h' + maxText;
|
||
cruiseValueEl.classList.add('active');
|
||
} else {
|
||
cruiseValueEl.textContent = 'aus';
|
||
cruiseValueEl.classList.remove('active');
|
||
}
|
||
|
||
if (typeof v.motorStarted === 'boolean') {
|
||
motorValueEl.textContent = v.motorStarted ? 'läuft' : 'aus';
|
||
} else {
|
||
motorValueEl.textContent = '–';
|
||
}
|
||
|
||
loadValueEl.textContent = typeof v.motorLoadPercent === 'number' ? Math.round(v.motorLoadPercent) + '%' : '–';
|
||
|
||
if (typeof v.fuelLevel === 'number' && typeof v.fuelCapacity === 'number' && v.fuelCapacity > 0) {
|
||
const pct = (v.fuelLevel / v.fuelCapacity) * 100;
|
||
const fuelUnit = Array.isArray(v.fillUnits) ? v.fillUnits.find((fu) => fu.fillTypeId === v.fuelType) : null;
|
||
const fuelName = fuelUnit && fuelUnit.fillTypeName ? fuelUnit.fillTypeName + ': ' : '';
|
||
fuelTextEl.textContent = fuelName + Math.round(v.fuelLevel) + ' / ' + Math.round(v.fuelCapacity) + ' l (' + Math.round(pct) + '%)';
|
||
fuelBarEl.style.width = Math.min(100, Math.max(0, pct)) + '%';
|
||
} else {
|
||
fuelTextEl.textContent = '–';
|
||
fuelBarEl.style.width = '0%';
|
||
}
|
||
|
||
if (typeof v.damagePercent === 'number') {
|
||
const pct = Math.min(100, Math.max(0, v.damagePercent));
|
||
damageTextEl.textContent = Math.round(pct) + '%';
|
||
damageBarEl.style.width = pct + '%';
|
||
} else {
|
||
damageTextEl.textContent = '–';
|
||
damageBarEl.style.width = '0%';
|
||
}
|
||
|
||
if (typeof v.dirtPercent === 'number') {
|
||
const pct = Math.min(100, Math.max(0, v.dirtPercent));
|
||
dirtTextEl.textContent = Math.round(pct) + '%';
|
||
dirtBarEl.style.width = pct + '%';
|
||
} else {
|
||
dirtTextEl.textContent = '–';
|
||
dirtBarEl.style.width = '0%';
|
||
}
|
||
|
||
hoursValueEl.textContent = typeof v.operatingHours === 'number' ? formatNumber(v.operatingHours, 1) + ' h' : '–';
|
||
priceValueEl.textContent = typeof v.price === 'number' ? formatEuro(v.price) : '–';
|
||
sellPriceValueEl.textContent = typeof v.sellPrice === 'number' ? formatEuro(v.sellPrice) : '–';
|
||
|
||
positionValueEl.textContent = (typeof v.x === 'number' && typeof v.z === 'number')
|
||
? Math.round(v.x) + ', ' + Math.round(v.z)
|
||
: '–';
|
||
headingValueEl.textContent = typeof v.headingRad === 'number'
|
||
? Math.round(((v.headingRad * 180 / Math.PI) % 360 + 360) % 360) + '°'
|
||
: '–';
|
||
|
||
renderOwnFillUnits(v);
|
||
renderImplements(v, vehicles);
|
||
|
||
pushSpeedHistory(speed);
|
||
renderSpeedHistory();
|
||
}
|
||
|
||
/**
|
||
* The selected vehicle's OWN tanks/hoppers (e.g. a combine's grain tank, a
|
||
* sprayer's own liquid tank) - separate from the "Tank" bar above, which is
|
||
* specifically the fuel/energy fillUnit. The fuel unit is excluded here so
|
||
* it isn't shown twice.
|
||
*/
|
||
function renderOwnFillUnits(v) {
|
||
ownFillUnitsListEl.innerHTML = '';
|
||
const fillUnits = (v && Array.isArray(v.fillUnits)) ? v.fillUnits : [];
|
||
const relevant = fillUnits.filter((fu) => {
|
||
if (typeof fu.capacity !== 'number' || fu.capacity <= 0) return false;
|
||
if (v && v.fuelType != null && fu.fillTypeId === v.fuelType) return false;
|
||
return true;
|
||
});
|
||
|
||
if (relevant.length === 0) {
|
||
const empty = document.createElement('div');
|
||
empty.className = 'implements-empty';
|
||
empty.textContent = '– keine –';
|
||
ownFillUnitsListEl.appendChild(empty);
|
||
return;
|
||
}
|
||
|
||
for (const fu of relevant) {
|
||
const level = typeof fu.fillLevel === 'number' ? fu.fillLevel : 0;
|
||
const pct = Math.min(100, Math.max(0, (level / fu.capacity) * 100));
|
||
|
||
const row = document.createElement('div');
|
||
row.className = 'implement-fill';
|
||
|
||
const label = document.createElement('div');
|
||
label.className = 'bar-label';
|
||
label.innerHTML = `<span>${fu.fillTypeName || 'Unbekannt'}</span><span>${Math.round(level)} / ${Math.round(fu.capacity)} l (${Math.round(pct)}%)</span>`;
|
||
row.appendChild(label);
|
||
|
||
const track = document.createElement('div');
|
||
track.className = 'bar-track';
|
||
const fill = document.createElement('div');
|
||
fill.className = 'bar-fill';
|
||
fill.style.width = pct + '%';
|
||
fill.style.background = 'var(--accent)';
|
||
track.appendChild(fill);
|
||
row.appendChild(track);
|
||
|
||
ownFillUnitsListEl.appendChild(row);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Shows the FULL attachment train behind the given vehicle - not just what's
|
||
* directly hitched, but also whatever's hitched behind THAT (a tractor
|
||
* pulling a dolly pulling a trailer, etc.). The mod only sends one level of
|
||
* attachedImplementIds per vehicle, so this walks that chain recursively,
|
||
* looking up each linked vehicle (and its own attachments) from the full
|
||
* vehicles list every render. A visited-set guards against a cycle ever
|
||
* causing an infinite loop (shouldn't happen, but cheap to be safe).
|
||
*/
|
||
function renderImplements(vehicle, vehicles) {
|
||
implementsListEl.innerHTML = '';
|
||
|
||
const rootIds = (vehicle && Array.isArray(vehicle.attachedImplementIds)) ? vehicle.attachedImplementIds : [];
|
||
if (rootIds.length === 0) {
|
||
const empty = document.createElement('div');
|
||
empty.className = 'implements-empty';
|
||
empty.textContent = '– keine –';
|
||
implementsListEl.appendChild(empty);
|
||
return;
|
||
}
|
||
|
||
const visited = new Set(vehicle ? [vehicle.id] : []);
|
||
for (const rootId of rootIds) {
|
||
appendImplementChain(rootId, vehicles, implementsListEl, 0, visited);
|
||
}
|
||
}
|
||
|
||
function appendImplementChain(implementId, vehicles, container, depth, visited) {
|
||
if (visited.has(implementId)) return;
|
||
visited.add(implementId);
|
||
|
||
const implement = vehicles.find((x) => x.id === implementId);
|
||
|
||
const card = document.createElement('div');
|
||
card.className = 'implement-card';
|
||
if (depth > 0) {
|
||
card.classList.add('implement-chained');
|
||
card.style.marginLeft = (depth * 16) + 'px';
|
||
}
|
||
|
||
const nameEl = document.createElement('div');
|
||
nameEl.className = 'implement-name';
|
||
nameEl.textContent = (depth > 0 ? '↳ ' : '') + (implement ? (implement.name || 'Unbenannt') : 'Unbekanntes Gerät');
|
||
card.appendChild(nameEl);
|
||
|
||
const fillUnits = (implement && Array.isArray(implement.fillUnits)) ? implement.fillUnits : [];
|
||
const relevant = fillUnits.filter((fu) => typeof fu.capacity === 'number' && fu.capacity > 0);
|
||
|
||
if (relevant.length === 0) {
|
||
const none = document.createElement('div');
|
||
none.className = 'implement-empty-tank';
|
||
none.textContent = 'kein Tank';
|
||
card.appendChild(none);
|
||
} else {
|
||
for (const fu of relevant) {
|
||
const level = typeof fu.fillLevel === 'number' ? fu.fillLevel : 0;
|
||
const pct = Math.min(100, Math.max(0, (level / fu.capacity) * 100));
|
||
|
||
const row = document.createElement('div');
|
||
row.className = 'implement-fill';
|
||
|
||
const label = document.createElement('div');
|
||
label.className = 'bar-label';
|
||
label.innerHTML = `<span>${fu.fillTypeName || 'Unbekannt'}</span><span>${Math.round(level)} / ${Math.round(fu.capacity)} l (${Math.round(pct)}%)</span>`;
|
||
row.appendChild(label);
|
||
|
||
const track = document.createElement('div');
|
||
track.className = 'bar-track';
|
||
const fill = document.createElement('div');
|
||
fill.className = 'bar-fill';
|
||
fill.style.width = pct + '%';
|
||
fill.style.background = 'var(--accent)';
|
||
track.appendChild(fill);
|
||
row.appendChild(track);
|
||
|
||
card.appendChild(row);
|
||
}
|
||
}
|
||
|
||
container.appendChild(card);
|
||
|
||
const childIds = (implement && Array.isArray(implement.attachedImplementIds)) ? implement.attachedImplementIds : [];
|
||
for (const childId of childIds) {
|
||
appendImplementChain(childId, vehicles, container, depth + 1, visited);
|
||
}
|
||
}
|
||
|
||
function setGauge(fillEl, fraction) {
|
||
const clamped = Math.max(0, Math.min(1, fraction || 0));
|
||
fillEl.style.strokeDashoffset = String(GAUGE_ARC_LENGTH * (1 - clamped));
|
||
// Real telemetry is never exactly 0 (physics jitter gives e.g. 0.0004 km/h),
|
||
// so comparing to 0 doesn't catch it - a small threshold does.
|
||
fillEl.classList.toggle('has-value', clamped > 0.01);
|
||
}
|
||
|
||
function pushSpeedHistory(speed) {
|
||
const now = Date.now();
|
||
state.speedHistory.push({ t: now, v: speed });
|
||
const cutoff = now - SPEED_HISTORY_WINDOW_MS;
|
||
while (state.speedHistory.length > 0 && state.speedHistory[0].t < cutoff) {
|
||
state.speedHistory.shift();
|
||
}
|
||
}
|
||
|
||
function renderSpeedHistory() {
|
||
const ratio = resizeCanvasToDisplaySize(speedHistoryCanvas);
|
||
const w = speedHistoryCanvas.width;
|
||
const h = speedHistoryCanvas.height;
|
||
speedHistoryCtx.clearRect(0, 0, w, h);
|
||
|
||
const points = state.speedHistory;
|
||
if (points.length < 2) return;
|
||
|
||
const now = Date.now();
|
||
const maxV = Math.max(20, ...points.map((p) => p.v));
|
||
|
||
speedHistoryCtx.beginPath();
|
||
points.forEach((p, i) => {
|
||
const fx = 1 - (now - p.t) / SPEED_HISTORY_WINDOW_MS;
|
||
const x = fx * w;
|
||
const y = h - (p.v / maxV) * (h - 4) - 2;
|
||
if (i === 0) speedHistoryCtx.moveTo(x, y); else speedHistoryCtx.lineTo(x, y);
|
||
});
|
||
speedHistoryCtx.strokeStyle = getCssVar('--accent');
|
||
speedHistoryCtx.lineWidth = 2 * ratio;
|
||
speedHistoryCtx.stroke();
|
||
}
|
||
|
||
// ---------------------------------------------------------------------
|
||
// Time
|
||
// ---------------------------------------------------------------------
|
||
function renderTime(time) {
|
||
if (!time) {
|
||
clockText.textContent = '--:--';
|
||
dayText.textContent = 'Tag –';
|
||
seasonText.textContent = '';
|
||
periodTextEl.textContent = '';
|
||
scaleText.textContent = '';
|
||
return;
|
||
}
|
||
|
||
// dayTimeMinutes first: it's the precise, continuously-updating clock
|
||
// (observed as milliseconds since midnight, e.g. 33359013 ms = ~9.27h).
|
||
// currentHour was preferred before, but it's only ever a whole number in
|
||
// practice, so the displayed time never showed minutes - only use it as
|
||
// a fallback if dayTimeMinutes isn't available at all.
|
||
let minutes = null;
|
||
if (typeof time.dayTimeMinutes === 'number') {
|
||
minutes = time.dayTimeMinutes > 1440 ? time.dayTimeMinutes / 60000 : time.dayTimeMinutes;
|
||
} else if (typeof time.currentHour === 'number') {
|
||
minutes = time.currentHour * 60;
|
||
}
|
||
|
||
if (minutes != null) {
|
||
minutes = ((minutes % 1440) + 1440) % 1440;
|
||
const hh = Math.floor(minutes / 60);
|
||
const mm = Math.floor(minutes % 60);
|
||
clockText.textContent = String(hh).padStart(2, '0') + ':' + String(mm).padStart(2, '0');
|
||
} else {
|
||
clockText.textContent = '--:--';
|
||
}
|
||
|
||
dayText.textContent = typeof time.currentDay === 'number' ? ('Tag ' + time.currentDay) : 'Tag –';
|
||
seasonText.textContent = time.currentSeason != null ? ('Saison ' + time.currentSeason) : '';
|
||
periodTextEl.textContent = typeof time.daysPerPeriod === 'number' ? ('(' + time.daysPerPeriod + ' Tage/Saison)') : '';
|
||
scaleText.textContent = typeof time.timeScale === 'number' ? (time.timeScale + '× Zeitraffer') : '';
|
||
}
|
||
|
||
// ---------------------------------------------------------------------
|
||
// Weather
|
||
// ---------------------------------------------------------------------
|
||
function renderWeather(weather, time) {
|
||
if (!weather) {
|
||
weatherIcon.textContent = '❓';
|
||
weatherType.textContent = 'Unbekannt';
|
||
weatherTemp.textContent = '';
|
||
weatherBadgesEl.innerHTML = '';
|
||
weatherExtraEl.innerHTML = '';
|
||
forecastStrip.innerHTML = '<div class="forecast-empty">Keine Wetterdaten vom Spiel verfügbar.</div>';
|
||
return;
|
||
}
|
||
|
||
const name = weather.currentTypeName;
|
||
weatherIcon.textContent = WEATHER_ICONS[name] || '❓';
|
||
weatherType.textContent = (name && WEATHER_LABELS_DE[name]) || 'Unbekannt';
|
||
weatherTemp.textContent = typeof weather.temperatureCelsius === 'number'
|
||
? Math.round(weather.temperatureCelsius) + ' °C'
|
||
: '';
|
||
|
||
weatherBadgesEl.innerHTML = '';
|
||
const badges = [];
|
||
if (weather.isRaining) badges.push('🌧️ Regen');
|
||
if (weather.isSnowing) badges.push('❄️ Schnee');
|
||
if (time && time.isNight) badges.push('🌙 Nacht');
|
||
for (const text of badges) {
|
||
const b = document.createElement('span');
|
||
b.className = 'weather-badge active';
|
||
b.textContent = text;
|
||
weatherBadgesEl.appendChild(b);
|
||
}
|
||
|
||
weatherExtraEl.innerHTML = '';
|
||
if (weather.isRaining && typeof weather.rainFallScale === 'number') {
|
||
const span = document.createElement('span');
|
||
span.textContent = 'Regenintensität: ' + Math.round(weather.rainFallScale * 100) + '%';
|
||
weatherExtraEl.appendChild(span);
|
||
}
|
||
if (typeof weather.snowHeight === 'number' && weather.snowHeight > 0.001) {
|
||
const span = document.createElement('span');
|
||
span.textContent = 'Schneehöhe: ' + weather.snowHeight.toFixed(2) + ' m';
|
||
weatherExtraEl.appendChild(span);
|
||
}
|
||
|
||
const forecast = Array.isArray(weather.forecast) ? weather.forecast : [];
|
||
if (forecast.length === 0) {
|
||
forecastStrip.innerHTML = '<div class="forecast-empty">Keine Vorhersagedaten vom Spiel verfügbar.</div>';
|
||
return;
|
||
}
|
||
|
||
forecastStrip.innerHTML = '';
|
||
for (const f of forecast) {
|
||
const day = document.createElement('div');
|
||
day.className = 'forecast-day';
|
||
|
||
const label = document.createElement('div');
|
||
label.className = 'fc-label';
|
||
label.textContent = '+' + f.dayOffset + ' Tag';
|
||
|
||
const icon = document.createElement('div');
|
||
icon.className = 'fc-icon';
|
||
icon.textContent = WEATHER_ICONS[f.typeName] || '❓';
|
||
|
||
const temp = document.createElement('div');
|
||
temp.className = 'fc-temp';
|
||
if (typeof f.minTemperatureCelsius === 'number' && typeof f.maxTemperatureCelsius === 'number') {
|
||
temp.textContent = Math.round(f.minTemperatureCelsius) + '° / ' + Math.round(f.maxTemperatureCelsius) + '°';
|
||
}
|
||
|
||
day.appendChild(label);
|
||
day.appendChild(icon);
|
||
day.appendChild(temp);
|
||
forecastStrip.appendChild(day);
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------------
|
||
// Farm
|
||
// ---------------------------------------------------------------------
|
||
function renderFarm(mission, farmlands, farms) {
|
||
if (!mission) {
|
||
farmName.textContent = '–';
|
||
farmMoney.textContent = '–';
|
||
farmlandCountEl.textContent = '–';
|
||
farmlandValueEl.textContent = '–';
|
||
otherFarmsHeadEl.hidden = true;
|
||
otherFarmsListEl.innerHTML = '';
|
||
farmlandListEl.innerHTML = '<div class="storage-empty">– keine –</div>';
|
||
return;
|
||
}
|
||
|
||
const farmArr = Array.isArray(farms) ? farms : [];
|
||
let name = mission.farmName || ('Betrieb #' + (mission.farmId != null ? mission.farmId : '–'));
|
||
if (farmArr.length > 1) {
|
||
name += ` (von ${farmArr.length} Betrieben)`;
|
||
}
|
||
farmName.textContent = name;
|
||
farmMoney.textContent = formatEuro(mission.money);
|
||
|
||
const owned = (Array.isArray(farmlands) ? farmlands : []).filter((f) => f.isOwned && f.farmId === mission.farmId);
|
||
farmlandCountEl.textContent = owned.length > 0 ? String(owned.length) : '–';
|
||
const totalValue = owned.reduce((sum, f) => sum + (typeof f.price === 'number' ? f.price : 0), 0);
|
||
farmlandValueEl.textContent = owned.length > 0 ? formatEuro(totalValue) : '–';
|
||
|
||
// Every other farm the mod knows about (i.e. owns at least one farmland) -
|
||
// useful on shared/multiplayer savegames to see who else is playing.
|
||
const others = farmArr.filter((f) => f.id !== mission.farmId);
|
||
otherFarmsHeadEl.hidden = others.length === 0;
|
||
otherFarmsListEl.innerHTML = '';
|
||
for (const f of others) {
|
||
const row = document.createElement('div');
|
||
row.className = 'storage-fill-row';
|
||
row.innerHTML = `<span>${f.name || ('Betrieb #' + f.id)}</span><span>${typeof f.money === 'number' ? formatEuro(f.money) : '–'}</span>`;
|
||
otherFarmsListEl.appendChild(row);
|
||
}
|
||
|
||
// Individual owned farmland plots (name + price) - the stat chips above
|
||
// only show the aggregate count/value.
|
||
farmlandListEl.innerHTML = '';
|
||
if (owned.length === 0) {
|
||
farmlandListEl.innerHTML = '<div class="storage-empty">– keine –</div>';
|
||
} else {
|
||
for (const f of owned) {
|
||
const row = document.createElement('div');
|
||
row.className = 'storage-fill-row';
|
||
row.innerHTML = `<span>${f.name || ('Grundstück #' + f.id)}</span><span>${typeof f.price === 'number' ? formatEuro(f.price) : '–'}</span>`;
|
||
farmlandListEl.appendChild(row);
|
||
}
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------------
|
||
// Storage (silos) & animal husbandries
|
||
// ---------------------------------------------------------------------
|
||
// Best-effort translation - the real ProductionPoint.PROD_STATUS enum
|
||
// wasn't fully enumerable from the shipped source (only MISSING_INPUTS was
|
||
// confirmed via an actual usage), so unrecognized status names just show
|
||
// as-is rather than disappearing.
|
||
const PRODUCTION_STATUS_LABELS = {
|
||
RUNNING: 'läuft',
|
||
ACTIVE: 'läuft',
|
||
STOPPED: 'gestoppt',
|
||
DISABLED: 'deaktiviert',
|
||
PAUSED: 'pausiert',
|
||
MISSING_INPUTS: 'Rohstoffe fehlen',
|
||
MISSING_OUTPUT_CAPACITY: 'Lager voll',
|
||
NO_INPUT_CAPACITY: 'Lager voll',
|
||
};
|
||
function productionStatusClass(name) {
|
||
if (name === 'RUNNING' || name === 'ACTIVE') return 'ok';
|
||
if (!name) return '';
|
||
return 'warn';
|
||
}
|
||
|
||
function renderStorage(silos, husbandries, productions, farms) {
|
||
const showFarmBadge = Array.isArray(farms) && farms.length > 1;
|
||
|
||
siloListEl.innerHTML = '';
|
||
const filledSilos = (Array.isArray(silos) ? silos : []).filter((s) => Array.isArray(s.fillTypes) && s.fillTypes.length > 0);
|
||
if (filledSilos.length === 0) {
|
||
siloListEl.innerHTML = '<div class="storage-empty">– keine befüllten Silos –</div>';
|
||
} else {
|
||
for (const silo of filledSilos) {
|
||
const card = document.createElement('div');
|
||
card.className = 'storage-item';
|
||
|
||
const nameEl = document.createElement('div');
|
||
nameEl.className = 'storage-item-name';
|
||
nameEl.textContent = (silo.name || 'Unbenannt') + farmSuffix(silo.ownerFarmId, showFarmBadge);
|
||
card.appendChild(nameEl);
|
||
|
||
for (const ft of silo.fillTypes) {
|
||
const row = document.createElement('div');
|
||
row.className = 'storage-fill-row';
|
||
const level = typeof ft.fillLevel === 'number' ? Math.round(ft.fillLevel) : 0;
|
||
row.innerHTML = `<span>${ft.fillTypeName || 'Unbekannt'}</span><span>${level.toLocaleString('de-DE')} l</span>`;
|
||
card.appendChild(row);
|
||
}
|
||
siloListEl.appendChild(card);
|
||
}
|
||
}
|
||
|
||
husbandryListEl.innerHTML = '';
|
||
const husbandryArr = Array.isArray(husbandries) ? husbandries : [];
|
||
if (husbandryArr.length === 0) {
|
||
husbandryListEl.innerHTML = '<div class="storage-empty">– keine –</div>';
|
||
} else {
|
||
for (const h of husbandryArr) {
|
||
const card = document.createElement('div');
|
||
card.className = 'storage-item';
|
||
|
||
const nameEl = document.createElement('div');
|
||
nameEl.className = 'storage-item-name';
|
||
nameEl.textContent = (h.name || 'Unbenannt') + farmSuffix(h.ownerFarmId, showFarmBadge);
|
||
card.appendChild(nameEl);
|
||
|
||
const countEl = document.createElement('div');
|
||
countEl.className = 'storage-animal-count';
|
||
const count = typeof h.numAnimals === 'number' ? h.numAnimals : '–';
|
||
const max = typeof h.maxNumAnimals === 'number' ? ' / ' + h.maxNumAnimals : '';
|
||
countEl.textContent = count + max;
|
||
card.appendChild(countEl);
|
||
|
||
const subEl = document.createElement('div');
|
||
subEl.className = 'storage-animal-sub';
|
||
subEl.textContent = 'Tiere';
|
||
card.appendChild(subEl);
|
||
|
||
husbandryListEl.appendChild(card);
|
||
}
|
||
}
|
||
|
||
productionListEl.innerHTML = '';
|
||
const productionArr = Array.isArray(productions) ? productions : [];
|
||
if (productionArr.length === 0) {
|
||
productionListEl.innerHTML = '<div class="storage-empty">– keine –</div>';
|
||
} else {
|
||
for (const p of productionArr) {
|
||
const card = document.createElement('div');
|
||
card.className = 'storage-item';
|
||
|
||
const nameEl = document.createElement('div');
|
||
nameEl.className = 'storage-item-name';
|
||
nameEl.textContent = (p.name || 'Unbenannt') + farmSuffix(p.ownerFarmId, showFarmBadge);
|
||
card.appendChild(nameEl);
|
||
|
||
for (const r of (Array.isArray(p.recipes) ? p.recipes : [])) {
|
||
const head = document.createElement('div');
|
||
head.className = 'production-recipe-head';
|
||
const statusLabel = PRODUCTION_STATUS_LABELS[r.statusName] || r.statusName || '';
|
||
head.innerHTML = `<span>${r.name || 'Rezept'}</span>`
|
||
+ (statusLabel ? `<span class="production-status ${productionStatusClass(r.statusName)}">${statusLabel}</span>` : '');
|
||
card.appendChild(head);
|
||
|
||
const inputsText = (Array.isArray(r.inputs) ? r.inputs : [])
|
||
.map((i) => (i.fillTypeName || '?') + (typeof i.amount === 'number' ? ` (${i.amount})` : ''))
|
||
.join(' + ') || '–';
|
||
const outputsText = (Array.isArray(r.outputs) ? r.outputs : [])
|
||
.map((o) => (o.fillTypeName || '?') + (typeof o.amount === 'number' ? ` (${o.amount})` : ''))
|
||
.join(' + ') || '–';
|
||
const flow = document.createElement('div');
|
||
flow.className = 'production-flow';
|
||
flow.textContent = inputsText + ' → ' + outputsText;
|
||
card.appendChild(flow);
|
||
}
|
||
|
||
const contents = Array.isArray(p.contents) ? p.contents : [];
|
||
if (contents.length > 0) {
|
||
const contentHead = document.createElement('div');
|
||
contentHead.className = 'production-content-head';
|
||
contentHead.textContent = 'Lagerbestand';
|
||
card.appendChild(contentHead);
|
||
|
||
for (const c of contents) {
|
||
const row = document.createElement('div');
|
||
row.className = 'storage-fill-row';
|
||
const level = typeof c.fillLevel === 'number' ? Math.round(c.fillLevel) : 0;
|
||
row.innerHTML = `<span>${c.fillTypeName || 'Unbekannt'}</span><span>${level.toLocaleString('de-DE')} l</span>`;
|
||
card.appendChild(row);
|
||
}
|
||
}
|
||
|
||
productionListEl.appendChild(card);
|
||
}
|
||
}
|
||
}
|
||
|
||
function farmSuffix(ownerFarmId, show) {
|
||
return (show && ownerFarmId != null) ? ` (Betrieb #${ownerFarmId})` : '';
|
||
}
|
||
|
||
// ---------------------------------------------------------------------
|
||
// Helpers
|
||
// ---------------------------------------------------------------------
|
||
function formatNumber(n, digits) {
|
||
if (typeof n !== 'number' || Number.isNaN(n)) return '–';
|
||
return n.toFixed(digits);
|
||
}
|
||
|
||
function formatEuro(n) {
|
||
if (typeof n !== 'number' || Number.isNaN(n)) return '–';
|
||
return Math.round(n).toLocaleString('de-DE') + ' €';
|
||
}
|
||
|
||
window.addEventListener('resize', () => {
|
||
if (state.lastData) onData(state.lastData);
|
||
});
|
||
})();
|