// ==UserScript== // @name OE2 VITAL — Vessel Integrity Tracking & Assessment Layer // @namespace https://game.dev.outerempires.net/ // @version 3.1 // @description Real-time ship maintenance grade — A-F rating, component list, and details (WebSocket-driven ShipPartsUpdate) // @match https://game.dev.outerempires.net/* // @grant none // @run-at document-start // ==/UserScript== (function () { 'use strict'; var POS_KEY = 'oe2_vital_pos'; var SLOTS = { Weapons: { label: 'WPN' }, Turrets: { label: 'TRT' }, Engines: { label: 'ENG' }, Core: { label: 'CORE' }, Shields: { label: 'SHD' }, Ammo: { label: 'AMMO' } }; var API_BASE = localStorage.getItem('_oe2_api_base') || ''; var API_AUTH = localStorage.getItem('_oe2_api_auth') || ''; var API_CHAR_ID = localStorage.getItem('_oe2_api_char_id') || ''; var _snapshotFetched = false; console.log('[VITAL] v3.0 loaded' + (API_BASE ? ' (cached creds)' : ' (awaiting creds)')); var overlayEl = null; var reopenBtn = null; var vtgBtn = null; var isDragging = false; var dragOffX = 0, dragOffY = 0; var isExpanded = false; var isVisible = false; var isUserHidden = false; var components = {}; var shipName = ''; var shipId = ''; var shieldData = null; var powerData = null; var lastBuzzZeroTime = 0; var lastBuzzBelow10Time = 0; var lastBuzzBelow25Time = 0; // Credential capture from game traffic + localStorage persistence (shared with other OE2 scripts) (function () { var origFetch = window.fetch; window.fetch = function (input, init) { var r = origFetch.apply(this, arguments); r.then(function (resp) { try { var url = typeof input === 'string' ? input : input ? input.url : ''; if (!url || url.indexOf('twitch') !== -1) return; if (url.indexOf('oe2') === -1 && url.indexOf('outerempires') === -1) return; var changed = false; if (!API_BASE) { var m = url.match(/^(https:\/\/[^/]+)/); if (m) { API_BASE = m[1]; localStorage.setItem('_oe2_api_base', API_BASE); changed = true; } } var cm = url.match(/characterId=(\d+)/); if (cm) { API_CHAR_ID = cm[1]; localStorage.setItem('_oe2_api_char_id', API_CHAR_ID); changed = true; } var headers = init ? init.headers : (input ? input.headers : {}); if (typeof headers === 'object' && !Array.isArray(headers)) { var auth = headers.Authorization || headers.authorization || ''; if (auth && (!API_AUTH || auth !== API_AUTH)) { var prevAuth = API_AUTH; API_AUTH = auth; localStorage.setItem('_oe2_api_auth', API_AUTH); changed = true; // If auth token changed (renewed), allow snapshot retry if (prevAuth && auth !== prevAuth) _snapshotFetched = false; } } if (changed) console.log('[VITAL] Credentials ready' + (API_CHAR_ID ? ' char=' + API_CHAR_ID : '')); if (changed) fetchInitialSnapshot(); // Detect repair API calls and refresh snapshot if (resp && resp.ok && url.indexOf('repair') !== -1) { console.log('[VITAL] Repair detected, refreshing snapshot'); refreshSnapshot(); } } catch (e) {} }); return r; }; // Also capture from XHR (game may use this for some calls) var _open = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function (method, url) { this._vitalUrl = url; return _open.apply(this, arguments); }; var _setH = XMLHttpRequest.prototype.setRequestHeader; XMLHttpRequest.prototype.setRequestHeader = function (k, v) { var u = this._vitalUrl || ''; if (u.indexOf('oe2') !== -1 || u.indexOf('outerempires') !== -1) { if (u.indexOf('twitch') === -1 && k.toLowerCase() === 'authorization' && (!API_AUTH || v !== API_AUTH)) { if (API_AUTH && v !== API_AUTH) _snapshotFetched = false; API_AUTH = v; localStorage.setItem('_oe2_api_auth', API_AUTH); console.log('[VITAL] Credentials ready (XHR)'); fetchInitialSnapshot(); } if (!API_BASE) { var m = u.match(/^(https:\/\/[^/]+)/); if (m) { API_BASE = m[1]; localStorage.setItem('_oe2_api_base', API_BASE); } } var cm = u.match(/characterId=(\d+)/); if (cm) { API_CHAR_ID = cm[1]; localStorage.setItem('_oe2_api_char_id', API_CHAR_ID); } } return _setH.apply(this, arguments); }; var _send = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.send = function () { var xhr = this; var u = xhr._vitalUrl || ''; if (u.indexOf('repair') !== -1 && (u.indexOf('oe2') !== -1 || u.indexOf('outerempires') !== -1)) { xhr.addEventListener('load', function () { if (xhr.status >= 200 && xhr.status < 300) { console.log('[VITAL] Repair detected (XHR), refreshing snapshot'); refreshSnapshot(); } }); } return _send.apply(this, arguments); }; })(); // WebSocket interceptor — catches GameUpdate/ShipPartsUpdate messages (function () { console.log('[VITAL] WS interceptor installing at document-start'); var _origAdd = EventTarget.prototype.addEventListener; EventTarget.prototype.addEventListener = function (type, listener, options) { if (type === 'message' && this instanceof WebSocket) { var self = this; var wrapped = function (e) { if (typeof e.data === 'string') tryProcess(e.data); if (typeof listener === 'function') return listener.apply(self, arguments); else if (listener && typeof listener.handleEvent === 'function') return listener.handleEvent(e); }; return _origAdd.call(this, type, wrapped, options); } return _origAdd.apply(this, arguments); }; if (window.WebSocket) { var _origWS = window.WebSocket; window.WebSocket = function (url, protocols) { var ws = new _origWS(url, protocols); Object.defineProperty(ws, 'onmessage', { configurable: true, enumerable: true, get: function () { return this.__vital_om; }, set: function (fn) { this.__vital_om = fn; _origAdd.call(ws, 'message', function (e) { if (typeof e.data === 'string') tryProcess(e.data); if (this.__vital_om) this.__vital_om.call(this, e); }); } }); return ws; }; window.WebSocket.prototype = _origWS.prototype; window.WebSocket.CONNECTING = 0; window.WebSocket.OPEN = 1; window.WebSocket.CLOSING = 2; window.WebSocket.CLOSED = 3; } function tryProcess(text) { try { var p = JSON.parse(text); } catch (e) { return; } var msgs = Array.isArray(p) ? p : [p]; for (var i = 0; i < msgs.length; i++) { var m = msgs[i]; if (m.message_type === 'GameUpdate' && m.message) { handleGameUpdate(m.message); } } } })(); function handleGameUpdate(msg) { var action = msg.action; var payload = msg.payload; if (!action || !payload) return; if (action === 'ShipPartsUpdate') { applyPartUpdates(payload); } else if (action === 'CombinedUpdate' && Array.isArray(payload)) { for (var i = 0; i < payload.length; i++) { if (payload[i].action === 'ShipPartsUpdate') { applyPartUpdates(payload[i].payload); } } } else if (action === 'Update' && Array.isArray(payload) && payload.length > 0) { for (var ui = 0; ui < payload.length; ui++) { var sd = payload[ui]; // Track player's own ship var cid = sd.char_id !== undefined && sd.char_id !== null ? '' + sd.char_id : ''; if (cid && cid === API_CHAR_ID) { if (sd.ship_id !== undefined) shipId = sd.ship_id; if (sd.name) shipName = sd.name; if (sd.shield) shieldData = sd.shield; if (sd.power) powerData = sd.power; // Check for component-like data in any field for (var key in sd) { if (Array.isArray(sd[key]) && sd[key].length > 0 && sd[key][0].healthPercentage !== undefined) { applyPartUpdates(sd[key]); } } // Re-render if we got new data (even just shield/power update) renderFromState(); } } } } function applyPartUpdates(parts) { if (!Array.isArray(parts) || !parts.length) return; var changed = false; for (var i = 0; i < parts.length; i++) { var c = parts[i]; var id = c.Id !== undefined && c.Id !== null ? '' + c.Id : c.id !== undefined && c.id !== null ? '' + c.id : null; if (!id) continue; // Dedup: remove any synthetic 'c_' entry that matches this component name var staleKeys = Object.keys(components).filter(function (k) { return k.indexOf('c_') === 0 && components[k].name === c.name; }); for (var si = 0; si < staleKeys.length; si++) { delete components[staleKeys[si]]; changed = true; } if (!components[id]) { components[id] = JSON.parse(JSON.stringify(c)); if (i === 0) console.log('[VITAL] New component via WS:', id, c.name, Object.keys(c).join(',')); } else { var oldHP = components[id].healthPercentage; for (var k in c) { if (c.hasOwnProperty(k)) components[id][k] = c[k]; } var newHP = components[id].healthPercentage; if (oldHP !== undefined && newHP !== undefined && newHP < oldHP) { components[id]._damageFlash = Date.now(); components[id]._lastDamagedAt = Date.now(); } } changed = true; } if (changed) renderFromState(); } function fetchInitialSnapshot() { if (!API_BASE || !API_AUTH) { console.log('[VITAL] Waiting for credentials...'); setTimeout(fetchInitialSnapshot, 3000); return; } _snapshotFetched = true; console.log('[VITAL] Fetching initial ship snapshot...'); fetch(API_BASE + '/v1/character/' + API_CHAR_ID + '/availableShips', { headers: { 'Authorization': API_AUTH } }).then(function (resp) { if (!resp.ok) { console.log('[VITAL] Snapshot fetch failed:', resp.status); return null; } return resp.json(); }).then(function (body) { if (!body || !body.success) { console.log('[VITAL] Snapshot response invalid'); return; } var ships = body.data; if (!Array.isArray(ships) || !ships.length) { console.log('[VITAL] No ships in snapshot'); return; } // Try to find current ship by shipId from WS, fallback to first var ship = null; if (shipId) { for (var si = 0; si < ships.length; si++) { if (ships[si].ship_id && '' + ships[si].ship_id === '' + shipId) { ship = ships[si]; break; } if (ships[si].id && '' + ships[si].id === '' + shipId) { ship = ships[si]; break; } } } if (!ship) ship = ships[0]; shipName = ship.summary ? (ship.summary.shipName || ship.summary.shipType || '') : (ship.name || ''); console.log('[VITAL] Snapshot loaded: ' + shipName + (ship.components ? ' (' + ship.components.length + ' components)' : ' (no components)')); if (ship.components) { for (var j = 0; j < ship.components.length; j++) { var c = ship.components[j]; var id = c.Id !== undefined && c.Id !== null ? '' + c.Id : c.id !== undefined && c.id !== null ? '' + c.id : null; if (id) { components[id] = c; } else { console.log('[VITAL] Component missing id:', c.name || '?'); } } } renderFromState(); }).catch(function () { console.log('[VITAL] Snapshot fetch error'); }); } function refreshSnapshot() { if (!API_BASE || !API_AUTH || !API_CHAR_ID) { console.log('[VITAL] refreshSnapshot: no creds'); return; } console.log('[VITAL] Refreshing snapshot...'); var prevDamage = {}; for (var id in components) { if (components[id]._lastDamagedAt) prevDamage[id] = components[id]._lastDamagedAt; } fetch(API_BASE + '/v1/character/' + API_CHAR_ID + '/availableShips', { headers: { 'Authorization': API_AUTH } }).then(function (resp) { if (!resp.ok) { console.log('[VITAL] Refresh failed:', resp.status); return null; } return resp.json(); }).then(function (body) { if (!body || !body.success) return; var ships = body.data; if (!Array.isArray(ships) || !ships.length) return; // Try to find current ship by shipId from WS, fallback to first var ship = null; if (shipId) { for (var si = 0; si < ships.length; si++) { if (ships[si].ship_id && '' + ships[si].ship_id === '' + shipId) { ship = ships[si]; break; } if (ships[si].id && '' + ships[si].id === '' + shipId) { ship = ships[si]; break; } } } if (!ship) ship = ships[0]; shipName = ship.summary ? (ship.summary.shipName || ship.summary.shipType || '') : (ship.name || ''); components = {}; if (ship.components) { for (var j = 0; j < ship.components.length; j++) { var c = ship.components[j]; var id = c.Id !== undefined && c.Id !== null ? '' + c.Id : c.id !== undefined && c.id !== null ? '' + c.id : null; if (!id) continue; components[id] = JSON.parse(JSON.stringify(c)); if (prevDamage[id]) components[id]._lastDamagedAt = prevDamage[id]; } } renderFromState(); console.log('[VITAL] Snapshot refreshed'); }).catch(function () { console.log('[VITAL] Refresh error'); }); } function renderFromState() { var compList = []; var now = Date.now(); for (var id in components) { if (components[id]._damageFlash && now - components[id]._damageFlash > 1000) { delete components[id]._damageFlash; } if (components[id]._lastDamagedAt && now - components[id]._lastDamagedAt > 30000) { delete components[id]._lastDamagedAt; } compList.push(components[id]); } var total = 0, count = 0, damaged = false; for (var i = 0; i < compList.length; i++) { var hp = compList[i].healthPercentage; if (hp !== null && hp !== undefined) { total += hp; count++; } if (hp !== null && hp !== undefined && hp < 90) damaged = true; } // Include shield/power data from WS if available var wsInfo = {}; if (shieldData) wsInfo.shield = shieldData; if (powerData) wsInfo.power = powerData; render({ summary: { shipName: shipName, shipType: shipName, overallIntegrity: count > 0 ? total / count : null, isDamaged: damaged }, components: compList, wsInfo: wsInfo }); } function healthColor(pct) { if (pct === null || pct === undefined) return '#888'; if (pct > 80) return '#4dd0e1'; if (pct > 60) return '#00eda2'; if (pct > 40) return '#ff9800'; if (pct > 20) return '#ffc107'; return '#ff6b6b'; } function maintenanceGrade(pct) { if (pct === null || pct === undefined) return { grade: '\u2014\u2014', color: '#3a6ea8' }; if (pct >= 95) return { grade: 'A', color: '#00eda2' }; if (pct >= 85) return { grade: 'B', color: '#8bc34a' }; if (pct >= 70) return { grade: 'C', color: '#ffc107' }; if (pct >= 50) return { grade: 'D', color: '#ff9800' }; return { grade: 'F', color: '#ff6b6b' }; } function dotColor(pct) { if (pct === null || pct === undefined) return '#888'; if (pct > 80) return '#4dd0e1'; if (pct > 60) return '#00eda2'; if (pct > 40) return '#ff9800'; if (pct > 20) return '#ffc107'; return '#ff6b6b'; } function getSlot(name, blue) { name = (name || '').toLowerCase(); blue = (blue || '').toLowerCase(); if (blue === 'weapon' || blue === 'weapons' || name.match(/laser|missile|rail|cannon|launcher|turret|beam|blaster/)) return name.includes('turret') ? 'Turrets' : 'Weapons'; if (blue === 'engine' || blue === 'engines' || name.match(/engine|drive|thruster|propul|warp/)) return 'Engines'; if (blue === 'core' || name.match(/reactor|core|power|cpu|processor/)) return 'Core'; if (blue === 'shield' || blue === 'shields' || name.match(/shield|deflector|armor|plat/)) return 'Shields'; if (blue === 'ammo' || name.match(/ammo|charge|battery|cell/)) return 'Ammo'; if (blue === 'turret' || name.includes('turret')) return 'Turrets'; return 'Core'; } function scrapeDOMComponents() { // DOM scraping disabled — all component data comes from WebSocket ShipPartsUpdate. // Old CSS classes (#ShipInformation, .CargoItem, .CargoType, .MiniPie) no longer exist. return 0; } function createOverlay() { isUserHidden = false; if (overlayEl) { overlayEl.style.display = ''; if (vtgBtn) vtgBtn.style.display = ''; isVisible = true; fetchInitialSnapshot(); return; } console.log('[VITAL] Creating overlay'); if (reopenBtn) reopenBtn.style.display = 'none'; overlayEl = document.createElement('div'); overlayEl.id = 'oe2-vital-overlay'; overlayEl.style.cssText = [ 'position:fixed', 'z-index:280', 'bottom:20px', 'right:16px', 'background:rgba(6,12,22,0.3)', 'padding:4px 0', 'font-family:Rajdhani,"Segoe UI",sans-serif', 'color:#e0e8f0', 'font-size:15px', 'width:260px', 'pointer-events:auto', 'cursor:move', 'user-select:none', 'text-shadow:0 0 8px #000,0 1px 4px #000', ].join(';') + ';'; var saved = localStorage.getItem(POS_KEY); if (saved) { try { var p = JSON.parse(saved); overlayEl.style.left = p.x + 'px'; overlayEl.style.bottom = p.y + 'px'; overlayEl.style.right = ''; } catch (e) {} } overlayEl.innerHTML = '
' + '\u25C6 VITAL ' + '\u2295' + '
' + '
'; var hud = document.querySelector('#ui-component') || document.body; hud.appendChild(overlayEl); vtgBtn = overlayEl.querySelector('.vtg'); vtgBtn.addEventListener('click', toggleExpand); isVisible = true; overlayEl.addEventListener('mousedown', function (e) { isDragging = true; var r = overlayEl.getBoundingClientRect(); dragOffX = e.clientX - r.left; dragOffY = e.clientY - r.top; overlayEl.style.right = ''; overlayEl.style.left = r.left + 'px'; overlayEl.style.bottom = (window.innerHeight - e.clientY + dragOffY - r.height) + 'px'; }); injectStyles(); fetchInitialSnapshot(); setTimeout(function () { scrapeDOMComponents(); }, 500); } function hideOverlay(auto) { if (!overlayEl) return; overlayEl.style.display = 'none'; if (vtgBtn) vtgBtn.style.display = 'none'; isVisible = false; if (!auto) createReopenBtn(); } function createReopenBtn() { if (reopenBtn) { reopenBtn.style.display = ''; return; } reopenBtn = document.createElement('div'); reopenBtn.id = 'oe2-vital-reopen'; reopenBtn.textContent = '\u25C6'; reopenBtn.title = 'Open VITAL panel'; Object.assign(reopenBtn.style, { position:'fixed',zIndex:'999997',bottom:'16px',right:'16px', width:'32px',height:'32px',borderRadius:'50%', background:'rgba(6,12,22,0.35)',border:'1px solid rgba(0,229,255,0.3)', color:'#00e5ff',fontSize:'14px',cursor:'pointer',display:'flex', alignItems:'center',justifyContent:'center', boxShadow:'0 0 12px rgba(0,229,255,0.1)',transition:'all 0.2s',userSelect:'none' }); reopenBtn.addEventListener('mouseenter', function () { reopenBtn.style.borderColor = '#4dd0e1'; reopenBtn.style.boxShadow = '0 0 16px rgba(0,229,255,0.2)'; }); reopenBtn.addEventListener('mouseleave', function () { reopenBtn.style.borderColor = 'rgba(0,229,255,0.3)'; reopenBtn.style.boxShadow = '0 0 12px rgba(0,229,255,0.1)'; }); reopenBtn.addEventListener('click', function () { createOverlay(); reopenBtn.style.display = 'none'; }); document.body.appendChild(reopenBtn); } function toggleExpand() { isExpanded = !isExpanded; if (vtgBtn) { vtgBtn.textContent = isExpanded ? '\u2296' : '\u2295'; vtgBtn.title = isExpanded ? 'Show damaged only' : 'Show all'; } renderFromState(); } function injectStyles() { if (document.getElementById('vital-st')) return; var el = document.createElement('style'); el.id = 'vital-st'; el.textContent = "@import url('https://fonts.googleapis.com/css2?family=Rajdhani:wght@400;600;700&display=swap');" + '.vtg:hover{opacity:1!important;color:#4dd0e1!important}' + '.vlist{overflow:hidden}' + '.vsi{padding:0 4px 2px 4px}' + '.vr{display:flex;align-items:center;gap:4px;padding:2px 0;transition:all 0.3s ease;overflow:hidden;min-width:0}' + '#oe2-vital-overlay .vr:hover{background:rgba(255,255,255,0.02)}' + '.vr-enter{opacity:0;transform:translateY(16px);max-height:0;padding-top:0;padding-bottom:0}' + '.vr-enter-active{opacity:1;transform:translateY(0);max-height:30px}' + '.vr-leave{opacity:0;transform:translateY(16px);max-height:0;padding-top:0;padding-bottom:0;margin:0}' + '.vt{width:22px;font-size:10px;font-weight:700;text-align:center;flex-shrink:0}' + '.vn{flex:1;font-size:13px;font-weight:600;color:#e0e8f0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}' + '.vp2{width:30px;text-align:right;font-size:11px;font-weight:700;flex-shrink:0}' + '.vd{display:inline-block;width:6px;height:6px;border-radius:50%;margin:1px}' + '@keyframes vital-flash-zero{0%{box-shadow:inset 0 0 0 999px rgba(255,0,0,0.65)}25%{box-shadow:inset 0 0 0 999px transparent}50%{box-shadow:inset 0 0 0 999px rgba(255,0,0,0.65)}75%{box-shadow:inset 0 0 0 999px transparent}100%{box-shadow:inset 0 0 0 999px transparent}}' + '.vr-flash-zero{animation:vital-flash-zero 1s ease forwards}' + '@keyframes vital-flash-below{0%{box-shadow:inset 0 0 0 999px transparent}40%{box-shadow:inset 0 0 0 999px rgba(255,165,0,0.55)}60%{box-shadow:inset 0 0 0 999px rgba(255,165,0,0.55)}100%{box-shadow:inset 0 0 0 999px transparent}}' + '.vr-flash-below{animation:vital-flash-below 2s ease forwards}' + '@keyframes vital-dmg-flash{0%{box-shadow:inset 0 0 0 0 transparent}25%{box-shadow:inset 0 0 18px 4px rgba(255,140,0,0.55)}to{box-shadow:inset 0 0 0 0 transparent}}' + '.vr-dmg-flash{animation:vital-dmg-flash .5s ease-out forwards!important}'; document.head.appendChild(el); } function renderComp(c, slotDef) { var hp = c.healthPercentage; var pct = hp !== null && hp !== undefined ? Math.round(hp) : null; var col = healthColor(pct); var mr = null; var mrFields = ['lastRepairHealthPercentage', 'maxRepair', 'maxRepairPercentage']; for (var fi = 0; fi < mrFields.length; fi++) { var v = c[mrFields[fi]]; if (v !== null && v !== undefined) { mr = Math.round(v); break; } } var bg = ''; var cls = 'vr'; if (pct !== null && mr !== null && mr > pct) { bg = 'linear-gradient(to right,rgba(102,162,103,0.5) 0%,rgba(102,162,103,0.5) ' + pct + '%,rgba(234,237,137,0.5) ' + pct + '%,rgba(234,237,137,0.5) ' + mr + '%,rgba(166,69,68,0.5) ' + mr + '%,rgba(166,69,68,0.5) 100%)'; } else if (pct !== null) { bg = 'linear-gradient(to right,rgba(102,162,103,0.5) 0%,rgba(102,162,103,0.5) ' + pct + '%,rgba(166,69,68,0.5) ' + pct + '%,rgba(166,69,68,0.5) 100%)'; } if (pct !== null && pct < 25) { var slotKey = getSlot(c.name, c.blueprintType); if (slotKey === 'Core' || pct === 0) { col = '#ff0000'; } } if (c._damageFlash && Date.now() - c._damageFlash < 500) cls += ' vr-dmg-flash'; return '
' + '' + slotDef.label + '' + '' + esc(c.name || '?') + '' + '' + (pct !== null ? pct + '%' : '--') + '' + '
'; } function renderShieldPower() { // Build shield/power HTML from WS data var html = ''; if (shieldData && shieldData.max_hit_points > 0) { var sPct = Math.round(shieldData.current_hit_points / shieldData.max_hit_points * 100); var shCol = sPct > 50 ? '#4dd0e1' : sPct > 25 ? '#ff9800' : '#ff6b6b'; html += '
SHD
' + sPct + '%
'; } if (powerData && powerData.max > 0) { var pPct = Math.round(powerData.current / powerData.max * 100); var pCol = pPct > 50 ? '#4dd0e1' : pPct > 25 ? '#ff9800' : '#ff6b6b'; html += '
PWR
' + pPct + '%
'; } return html; } function render(ship) { if (!overlayEl) return; var body = overlayEl.querySelector('.vb'); if (!ship) { body.innerHTML = '
\u2014 waiting\u2014
'; return; } var sum = ship.summary || {}; var comps = ship.components || []; var nameEl = overlayEl.querySelector('.vln'); if (nameEl) nameEl.textContent = ' \u2014 ' + (sum.shipName || shipName || ''); // Ensure we have shield/power info area and vlist if (!body.querySelector('.vsi')) { body.innerHTML = '
'; } var vsi = body.querySelector('.vsi'); var list = body.querySelector('.vlist'); // Update shield/power display var spHtml = renderShieldPower(); if (spHtml) vsi.innerHTML = spHtml; var wanted = []; var now = Date.now(); var DAMAGE_WINDOW = 30000; if (isExpanded) { for (var i = 0; i < comps.length; i++) { var c = comps[i]; var hp = c.healthPercentage; var pct = hp !== null && hp !== undefined ? Math.round(hp) : null; var key = getSlot(c.name, c.blueprintType); var def = SLOTS[key] || SLOTS.Core; wanted.push({ comp: c, pct: pct, slotDef: def, idx: i }); } wanted.sort(function (a, b) { var ha = a.pct !== null ? a.pct : 999; var hb = b.pct !== null ? b.pct : 999; return ha - hb; }); } else { for (var i = 0; i < comps.length; i++) { var c = comps[i]; var hp = c.healthPercentage; var pct = hp !== null && hp !== undefined ? Math.round(hp) : null; var isRecent = c._lastDamagedAt && now - c._lastDamagedAt < DAMAGE_WINDOW; var isLow = pct !== null && pct < 65; if (isRecent || isLow) { var key = getSlot(c.name, c.blueprintType); var def = SLOTS[key] || SLOTS.Core; wanted.push({ comp: c, pct: pct, slotDef: def, idx: i, lastDamagedAt: c._lastDamagedAt || 0 }); } } wanted.sort(function (a, b) { var ha = a.pct !== null ? a.pct : 999; var hb = b.pct !== null ? b.pct : 999; return ha - hb; }); if (wanted.length === 0) { list.innerHTML = '
\u2714 All clear
'; return; } } var zeroCount = 0; var below25Count = 0; for (var zi = 0; zi < comps.length; zi++) { var zh = comps[zi].healthPercentage; if (zh !== null && zh !== undefined) { var slotKey = getSlot(comps[zi].name, comps[zi].blueprintType); if (Math.round(zh) === 0 || (slotKey === 'Core' && zh < 25)) { zeroCount++; } else if (zh < 25) { below25Count++; } } } var currById = {}; list.querySelectorAll('.vr').forEach(function (el) { currById[el.getAttribute('data-id') || ''] = el; }); var wantedIds = {}; wanted.forEach(function (w) { var id = w.comp.Id !== undefined && w.comp.Id !== null ? '' + w.comp.Id : w.comp.id !== undefined && w.comp.id !== null ? '' + w.comp.id : 'c_' + w.idx; w.id = id; wantedIds[id] = true; }); var leaving = []; Object.keys(currById).forEach(function (id) { if (!wantedIds[id]) leaving.push(currById[id]); }); if (leaving.length > 0) { leaving.forEach(function (el) { el.classList.add('vr-leave'); }); setTimeout(function () { rebuildList(list, currById, wanted); }, 300); } else { rebuildList(list, currById, wanted); } } function rebuildList(list, currById, wanted) { var frag = document.createDocumentFragment(); var animQueue = []; wanted.forEach(function (w) { var html = renderComp(w.comp, w.slotDef); var temp = document.createElement('div'); temp.innerHTML = html; var el = temp.firstChild; el.setAttribute('data-id', w.id); if (!currById[w.id]) { el.classList.add('vr-enter'); animQueue.push(el); } frag.appendChild(el); }); list.innerHTML = ''; list.appendChild(frag); animQueue.forEach(function (el) { requestAnimationFrame(function () { el.classList.add('vr-enter-active'); }); }); if (animQueue.length > 0) { setTimeout(function () { animQueue.forEach(function (el) { el.classList.remove('vr-enter'); el.classList.remove('vr-enter-active'); }); }, 400); } } function esc(s) { var d = document.createElement('div'); d.textContent = s; return d.innerHTML; } function playBuzz(count) { try { var ctx = new (window.AudioContext || window.webkitAudioContext)(); function buzz(t) { var o = ctx.createOscillator(); var g = ctx.createGain(); o.type = 'sawtooth'; o.frequency.value = 150; g.gain.setValueAtTime(0.02, t); g.gain.exponentialRampToValueAtTime(0.001, t + 0.35); o.connect(g); g.connect(ctx.destination); o.start(t); o.stop(t + 0.35); } buzz(ctx.currentTime); if (count >= 2) buzz(ctx.currentTime + 0.15); } catch (e) {} } function playBelow25Buzz(count) { try { var ctx = new (window.AudioContext || window.webkitAudioContext)(); function buzz(t) { var o = ctx.createOscillator(); var g = ctx.createGain(); o.type = 'triangle'; o.frequency.value = 350; g.gain.setValueAtTime(0.015, t); g.gain.exponentialRampToValueAtTime(0.001, t + 0.3); o.connect(g); g.connect(ctx.destination); o.start(t); o.stop(t + 0.3); } buzz(ctx.currentTime); } catch (e) {} } function statusMsg(msg) { if (!overlayEl) return; var b = overlayEl.querySelector('.vb'); if (b) b.innerHTML = '
' + msg + '
'; } function flashRow(id, className) { if (!overlayEl) return; var list = overlayEl.querySelector('.vlist'); if (!list) return; var row = list.querySelector('[data-id="' + id + '"]'); if (row) { row.classList.add(className); setTimeout(function () { row.classList.remove(className); }, 2200); } } function startBuzzTimer() { setInterval(function () { var zeroIds = [], below10Ids = [], below25Ids = []; for (var id in components) { var zh = components[id].healthPercentage; if (zh !== null && zh !== undefined) { var sk = getSlot(components[id].name, components[id].blueprintType); if (Math.round(zh) === 0 || (sk === 'Core' && zh < 25)) { zeroIds.push(id); } else if (zh < 15) { below10Ids.push(id); } else if (zh < 30 || (sk === 'Core' && zh < 50)) { below25Ids.push(id); } } } var now = Date.now(); if (zeroIds.length > 0 && now - lastBuzzZeroTime >= 5000) { lastBuzzZeroTime = now; playBuzz(zeroIds.length); zeroIds.forEach(function (id) { flashRow(id, 'vr-flash-zero'); }); } if (below10Ids.length > 0 && now - lastBuzzBelow10Time >= 10000) { lastBuzzBelow10Time = now; playBelow25Buzz(below10Ids.length); below10Ids.forEach(function (id) { flashRow(id, 'vr-flash-below'); }); } if (below25Ids.length > 0 && now - lastBuzzBelow25Time >= 20000) { lastBuzzBelow25Time = now; playBelow25Buzz(below25Ids.length); below25Ids.forEach(function (id) { flashRow(id, 'vr-flash-below'); }); } }, 1000); } function start() { createOverlay(); startBuzzTimer(); setInterval(refreshSnapshot, 60000); setTimeout(function () { scrapeDOMComponents(); }, 3000); setInterval(function () { scrapeDOMComponents(); }, 15000); } document.addEventListener('mousemove', function (e) { if (!isDragging || !overlayEl) return; overlayEl.style.left = (e.clientX - dragOffX) + 'px'; overlayEl.style.bottom = (window.innerHeight - (e.clientY - dragOffY) - overlayEl.offsetHeight) + 'px'; }); document.addEventListener('mouseup', function () { if (isDragging && overlayEl) { isDragging = false; overlayEl.style.cursor = ''; var r = overlayEl.getBoundingClientRect(); localStorage.setItem(POS_KEY, JSON.stringify({ x: r.left, y: window.innerHeight - r.bottom })); } }); document.addEventListener('keydown', function (e) { if (e.altKey && e.key === 'v') { e.preventDefault(); if (isVisible && overlayEl && overlayEl.style.display !== 'none') { isUserHidden = true; hideOverlay(); } else { isUserHidden = false; createOverlay(); } } }); var started = false; function tryStart() { if (started) return; started = true; setTimeout(start, 2000); } if (document.readyState === 'complete' || document.readyState === 'interactive') tryStart(); else document.addEventListener('DOMContentLoaded', tryStart); window.addEventListener('load', tryStart); })();