/* Tarkov Maps -- every map on one shared canvas. * * The base layer is the overall satellite map, rotated so north is up. Every * detail map is scaled and positioned onto it, so zooming into Customs on the * world map lands you in the full-resolution re3mr Customs map. * * Coordinates: LatLng is (y, x) in *world pixels* at native resolution, where * one world pixel is 1/overallScale of an overall-map pixel. Each map's tiles * are numbered from its own padded cell origin -- see tools/common.py. */ const ZOOM_HEADROOM = 1; // how far past a layer's native detail we allow const ZOOM_SNAP = 0.25; const BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='; /* --- performance profile ---------------------------------------------- * Two things make the map stutter when you alt-tab to it mid-raid: a weak * device and a slow connection. Both are dominated by how many tiles are in * play, so the profile mostly decides that. 'auto' reads the hardware; * 'fast' and 'sharp' are the user's override (the Detail button). */ const QUALITY_KEY = 'tarkov-quality'; const QUALITY_MODES = ['auto', 'fast', 'sharp']; const storedQuality = localStorage.getItem(QUALITY_KEY); const qualityMode = QUALITY_MODES.includes(storedQuality) ? storedQuality : 'auto'; const connection = navigator.connection ?? {}; const lowEndDevice = (Number(navigator.deviceMemory) || 8) <= 4 || (Number(navigator.hardwareConcurrency) || 8) <= 2; const slowNetwork = connection.saveData === true || /^(slow-2g|2g|3g)$/.test(String(connection.effectiveType ?? '')); const fastMode = qualityMode === 'fast' || (qualityMode === 'auto' && (lowEndDevice || slowNetwork)); /* Leaflet picks its tile level with Math.round(mapZoom), so at zoom 2.25 it * takes level 2 and stretches it 1.19x; on a 1.5x display that compounds to a * visibly soft 1.78x upscale. Halving a tile's CSS size and asking for one * level deeper makes us downscale a denser level instead. * * The boost costs ~4x the tiles in view -- DOM nodes, decodes and bytes -- so * it is reserved for displays that can actually show the extra pixels (DPR * above 1) and for the explicit 'sharp' mode. A 1:1 display accepts at most a * 1.19x stretch at quarter zooms, which is not worth quadrupling the tiles * for on a weak machine or a slow link. */ const DENSITY_BOOST = qualityMode === 'sharp' ? 1 : (!fastMode && window.devicePixelRatio > 1.05 ? 1 : 0); const PERF = { // Tile fade-in is an opacity transition per tile; a weak GPU feels it. fade: !fastMode, // Load tiles when the pan settles, not during it. Leaflet defaults to this // on phones; the low-res underlay keeps the map readable meanwhile. updateWhenIdle: fastMode || L.Browser.mobile, updateInterval: fastMode ? 400 : 200, keepBuffer: fastMode ? 1 : 2, // Pyramid level of the always-resident low-res underlay per detail map. previewLevel: 4, // Deepest level warmed into the cache in the background. precacheLevel: fastMode ? 4 : 5, precache: !slowNetwork, }; const OffsetTileLayer = L.TileLayer.extend({ createTile(coords, done) { const tile = L.TileLayer.prototype.createTile.call(this, coords, done); // Decode off the main thread: a burst of forty WebP decodes at the end of // a pan is a visible hitch on a weak CPU. tile.decoding = 'async'; return tile; }, getTileUrl(coords) { const o = this.options; const perCell = (o.baseTileSize * 2 ** coords.z) / o.tileSize; // ?v= busts the week-long immutable cache when a map is re-tiled; the same // URL would otherwise serve a previous build's imagery. return L.Util.template(this._url, { z: coords.z + o.zoomOffset, x: coords.x - o.cell[0] * perCell, y: coords.y - o.cell[1] * perCell, }) + (o.version ? `?v=${o.version}` : ''); }, }); const rectOf = (m) => L.latLngBounds( [m.origin[1], m.origin[0]], [m.origin[1] + m.size[1], m.origin[0] + m.size[0]], ); const trimPointsOf = (m) => ( Array.isArray(m.trim?.points) && m.trim.points.length >= 3 ? m.trim.points : null ); // The aligned raster keeps its original rectangle, but navigation should use // the portion the trim polygon says is actually playable/visible. const viewRectOf = (m) => { const points = trimPointsOf(m); if (!points) return rectOf(m); const xs = points.map(([x]) => x); const ys = points.map(([, y]) => y); return L.latLngBounds( [m.origin[1] + Math.min(...ys) * m.size[1], m.origin[0] + Math.min(...xs) * m.size[0]], [m.origin[1] + Math.max(...ys) * m.size[1], m.origin[0] + Math.max(...xs) * m.size[0]], ); }; const viewContains = (m, latlng) => { const points = trimPointsOf(m); if (!points) return rectOf(m).contains(latlng); const x = (latlng.lng - m.origin[0]) / m.size[0]; const y = (latlng.lat - m.origin[1]) / m.size[1]; let inside = false; for (let i = 0, j = points.length - 1; i < points.length; j = i, i += 1) { const [xi, yi] = points[i]; const [xj, yj] = points[j]; if ((yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) { inside = !inside; } } return inside; }; const centerOf = (m) => L.latLng( m.origin[1] + m.size[1] / 2, m.origin[0] + m.size[0] / 2, ); const geometryOf = (m) => ({ center: centerOf(m), width: m.size[0], height: m.size[1], }); const rectAt = (geometry) => L.latLngBounds( [geometry.center.lat - geometry.height / 2, geometry.center.lng - geometry.width / 2], [geometry.center.lat + geometry.height / 2, geometry.center.lng + geometry.width / 2], ); function readHash() { const p = location.hash.replace(/^#/, '').split('/'); if (p.length !== 3) return null; const [z, y, x] = p.map(Number); return [z, y, x].every(Number.isFinite) ? { z, y, x } : null; } async function main() { const [world, markerConfig, capabilities] = await Promise.all([ fetch('data/world.json', { cache: 'no-cache' }).then((r) => { if (!r.ok) throw new Error(`world.json: ${r.status}`); return r.json(); }), fetch('data/marker-config.json', { cache: 'no-cache' }) .then((r) => (r.ok ? r.json() : { defaults: {}, groups: [], categories: {} })) .catch(() => ({ defaults: {}, groups: [], categories: {} })), fetch('data/capabilities.json', { cache: 'no-store' }) .then((r) => (r.ok ? r.json() : { editable: false })) .catch(() => ({ editable: false })), ]); if (!world.maps.length) throw new Error('world.json contains no maps'); const mapEditingEnabled = capabilities.mapEditing === true; const markerEditingEnabled = capabilities.markerEditing === true; const markerPersistence = capabilities.markerPersistence === 'server' ? 'server' : 'local'; const exportingEnabled = capabilities.exporting === true; const ZMAX = world.maxZoom; const base = world.maps.find((m) => m.base) ?? world.maps[0]; const CRS = L.extend({}, L.CRS.Simple, { transformation: new L.Transformation(1, 0, 1, 0), scale: (z) => 2 ** (z - ZMAX), zoom: (s) => Math.log(s) / Math.LN2 + ZMAX, }); const extent = L.latLngBounds([0, 0], [world.worldSize[1], world.worldSize[0]]); const map = L.map('map', { crs: CRS, minZoom: 0, maxZoom: ZMAX + ZOOM_HEADROOM, zoomSnap: ZOOM_SNAP, zoomDelta: 0.5, wheelPxPerZoomLevel: 90, maxBounds: extent.pad(0.05), maxBoundsViscosity: 0.75, fadeAnimation: PERF.fade, attributionControl: false, zoomControl: false, }); // Leaflet stacks bottom-corner controls upwards in insertion order, so the // attribution goes in first to sit flush in the corner, zoom above it. L.control.attribution({ prefix: false }) .addAttribution(world.attribution) .addTo(map); const zoomControl = L.control.zoom({ position: 'bottomright' }).addTo(map); // Leaflet's zoom buttons are , which browsers treat as draggable // links -- a slightly-moving click became a ghost-image link drag. Make them // behave like the plain

Enter or click elsewhere saves · Esc cancels

`; const inlineLabelInput = inlineBox.querySelector('.marker-edit-label'); const inlineCategoryInput = inlineBox.querySelector('.marker-edit-category'); const inlineMapName = inlineBox.querySelector('.marker-edit-box-map'); const inlineDeleteButton = inlineBox.querySelector('.marker-edit-box-delete'); for (const category of editorCategories) { const option = document.createElement('option'); option.value = category; option.textContent = categoryLabel(category); inlineCategoryInput.appendChild(option); } const inlinePopup = L.popup({ pane: 'marker-editor', className: 'marker-edit-popup', closeButton: false, closeOnClick: false, closeOnEscapeKey: false, autoClose: false, autoPan: true, autoPanPadding: [24, 24], minWidth: 230, maxWidth: 280, }).setContent(inlineBox); let editSession = null; const editedRecord = (session) => ( session.isNew ? session.draft : markerRecords.get(session.id) ); const editedLeafletMarker = (session) => ( session.isNew ? session.draftMarker : renderedMarkers.get(session.id) ); const discardDraft = (session) => { if (session?.draftMarker) map.removeLayer(session.draftMarker); }; const endSession = (session) => { if (!session || editSession !== session) return; editSession = null; if (inlinePopup.isOpen()) map.closePopup(inlinePopup); }; // Follow a dragging marker without auto-panning the map out from under // the pointer. const syncInlinePopup = (session, latlng) => { if (editSession !== session || !inlinePopup.isOpen()) return; inlinePopup.options.autoPan = false; inlinePopup.setLatLng(latlng); inlinePopup.options.autoPan = true; }; const restyleEditedMarker = (session, category) => { const record = editedRecord(session); const leafletMarker = editedLeafletMarker(session); if (!record || !leafletMarker) return; const styled = { ...record, category }; leafletMarker.setIcon(createMarkerIcon(styled)); if (session.isNew) { session.draft.category = category; } else { cacheMarkerParts(leafletMarker, styled); scheduleMarkerLabelLayout(); } }; const openSession = (session, { pan = true } = {}) => { if (editSession && editSession !== session) void commitInlineEditor(); editSession = session; const record = editedRecord(session); session.originalCategory = record.category; inlineLabelInput.value = record.label ?? ''; inlineCategoryInput.value = editorCategories.includes(record.category) ? record.category : (editorCategories[0] ?? 'poi'); inlineMapName.textContent = session.isNew ? `New marker · ${record.mapName}` : record.mapName; inlineDeleteButton.hidden = session.isNew; inlineDeleteButton.disabled = false; const size = safeSize(categoryConfig(record.category).size); inlinePopup.options.offset = L.point(0, -((size * markerScale) / 2) - 2); inlinePopup.options.autoPan = pan; const latlng = session.isNew ? session.draftMarker.getLatLng() : L.latLng(record.worldY, record.worldX); if (inlinePopup.isOpen()) { inlinePopup.setLatLng(latlng); inlinePopup.update(); } else { inlinePopup.setLatLng(latlng).openOn(map); } inlinePopup.options.autoPan = true; inlineLabelInput.focus({ preventScroll: true }); inlineLabelInput.select(); }; async function commitInlineEditor() { const session = editSession; if (!session || session.busy) return; const current = editedRecord(session); if (!current) { endSession(session); return; } const category = inlineCategoryInput.value; const typed = inlineLabelInput.value.trim(); const previousLabel = String(current.label ?? ''); const label = typed || (session.isNew ? categoryLabel(category) : previousLabel); if (!session.isNew && label === previousLabel && category === current.category) { endSession(session); return; } session.busy = true; showMarkerStatus(markerPersistence === 'local' ? 'Saving marker in this browser…' : 'Saving marker…'); try { const saved = await persistMarker({ ...current, label, category }); discardDraft(session); replaceMarkerRecord(saved); endSession(session); showMarkerStatus(markerPersistence === 'local' ? 'Marker saved locally.' : 'Marker saved.'); } catch (error) { session.busy = false; showMarkerStatus(`Save failed: ${error.message}`, true); if (editSession === session) inlineLabelInput.focus(); else discardDraft(session); } } const cancelInlineEditor = () => { const session = editSession; if (!session || session.busy) return; if (session.isNew) discardDraft(session); else if (inlineCategoryInput.value !== session.originalCategory) { restyleEditedMarker(session, session.originalCategory); } endSession(session); showMarkerStatus(session.isNew ? 'New marker discarded.' : 'Edit cancelled.'); }; // Leaving marker editing (mode toggle, map switch, reset) keeps whatever // was typed: "anything else saves". const clearMarkerSelection = () => { const session = editSession; if (session) { void commitInlineEditor(); endSession(session); } setMarkerDropping(false); }; const localMarkerValues = (record, id = record.id) => ({ id, mapId: record.mapId, x: Number(record.x), y: Number(record.y), label: String(record.label).trim(), category: String(record.category), source: id.startsWith('local-') ? 'Local marker' : record.source, }); const persistLocalMarker = (record) => { const edits = readLocalMarkerEdits(record.mapId); let id = record.id; if (!id || id.startsWith('draft-')) { const random = globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(16).slice(2)}`; id = `local-${random}`; } const saved = localMarkerValues(record, id); const addedIndex = edits.added.findIndex((marker) => marker.id === id); if (id.startsWith('local-') || addedIndex >= 0) { if (addedIndex >= 0) edits.added[addedIndex] = saved; else edits.added.push(saved); } else { edits.overrides[id] = { x: saved.x, y: saved.y, label: saved.label, category: saved.category, }; } edits.deleted = edits.deleted.filter((deletedId) => deletedId !== id); writeLocalMarkerEdits(record.mapId, edits); return { ...record, ...saved }; }; const deleteLocalMarker = (record) => { const edits = readLocalMarkerEdits(record.mapId); const addedLength = edits.added.length; edits.added = edits.added.filter((marker) => marker.id !== record.id); if (edits.added.length === addedLength) { if (!edits.deleted.includes(record.id)) edits.deleted.push(record.id); delete edits.overrides[record.id]; } writeLocalMarkerEdits(record.mapId, edits); }; const persistMarker = async (record) => { if (markerPersistence === 'local') return persistLocalMarker(record); const response = await fetch('api/marker', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: record.id?.startsWith('draft-') ? null : record.id, mapId: record.mapId, x: record.x, y: record.y, label: record.label, category: record.category, }), }); const responseText = await response.text(); let result; try { result = JSON.parse(responseText); } catch { result = {}; } if (!response.ok) throw new Error( result.error || 'This server is read-only; start it with server/run.ps1 -Editable', ); return result.marker; }; selectEditableMarker = (id, { pan = true } = {}) => { if (!markerEditing.active) return; const record = markerRecords.get(id); if (!record) return; if (editSession && !editSession.isNew && editSession.id === id) return; setMarkerDropping(false); renderedMarkers.get(id)?.closeTooltip(); openSession({ id, isNew: false, busy: false }, { pan }); showMarkerStatus('Rename it, choose a category, or drag it to move it.'); }; onEditedMarkerDrag = (id, leafletMarker) => { const session = editSession; if (session && !session.isNew && session.id === id) { syncInlinePopup(session, leafletMarker.getLatLng()); } }; saveDraggedMarker = async (id, leafletMarker) => { const record = markerRecords.get(id); const m = record && byId.get(record.mapId); const point = m && normalizedPoint(m, leafletMarker.getLatLng()); if (!record || !m || !point) { if (record) { leafletMarker.setLatLng([record.worldY, record.worldX]); onEditedMarkerDrag(id, leafletMarker); } showMarkerStatus('Keep the marker inside its source map.', true); return; } // A drag is a save: it takes whatever is in the edit box along with it. const session = editSession && !editSession.isNew && editSession.id === id ? editSession : null; const label = session ? (inlineLabelInput.value.trim() || record.label) : record.label; const category = session ? inlineCategoryInput.value : record.category; if (session) session.busy = true; leafletMarker.dragging.disable(); showMarkerStatus(markerPersistence === 'local' ? 'Saving the new marker position in this browser…' : 'Saving the new marker position…'); try { const saved = await persistMarker({ ...record, x: point[0], y: point[1], label, category }); replaceMarkerRecord(saved); if (session) endSession(session); selectEditableMarker(saved.id); showMarkerStatus(markerPersistence === 'local' ? 'Marker position saved locally.' : 'Marker position saved.'); } catch (error) { leafletMarker.setLatLng([record.worldY, record.worldX]); leafletMarker.dragging.enable(); onEditedMarkerDrag(id, leafletMarker); if (session) session.busy = false; showMarkerStatus(`Save failed: ${error.message}`, true); } }; function closeMarkerEditor() { clearMarkerSelection(); hideContextMenu(); markerEditing.active = false; markerEditorPanel.hidden = true; markerEditButton.setAttribute('aria-pressed', 'false'); map.getContainer().classList.remove('marker-editing', 'marker-dropping'); for (const leafletMarker of renderedMarkers.values()) leafletMarker.dragging?.disable(); showMarkerStatus(''); } function openMarkerEditor(m) { if (!markerEditingEnabled || !m || m.base) return; if (editor.active) closeEditor(); if (trimEditor.active) closeTrimEditor(); markerEditing.selectedMapId = m.id; markerEditing.active = true; markerEditorPanel.hidden = false; markerEditButton.disabled = false; markerEditButton.setAttribute('aria-pressed', 'true'); markerEditorName.textContent = `${m.name} markers`; if (!markersVisible) { markersVisible = true; localStorage.setItem('tarkov-markers-visible', 'true'); renderMarkerVisibility(); } map.getContainer().classList.add('marker-editing'); scheduleMarkerRefresh(); requestAnimationFrame(() => { for (const leafletMarker of renderedMarkers.values()) leafletMarker.dragging?.enable(); }); showMarkerStatus(markerPersistence === 'local' ? 'Changes are saved only in this browser. Right-click the map to add a marker.' : 'Right-click the map to add a marker, or click one to edit it.'); focus(m.id); } markerDropButton.addEventListener('click', () => { if (markerEditing.dropping) { setMarkerDropping(false); showMarkerStatus('Drop cancelled.'); return; } clearMarkerSelection(); setMarkerDropping(true); showMarkerStatus('Click inside the selected map to place a new marker (or right-click anywhere).'); }); markerResetButton.addEventListener('click', async () => { const mapId = markerEditing.selectedMapId; const m = byId.get(mapId); if (markerPersistence !== 'local' || !m) return; if (!window.confirm(`Discard all local marker changes for ${m.name} and reload the published markers?`)) { return; } markerResetButton.disabled = true; showMarkerStatus('Fetching the latest published markers…'); try { const published = await fetchMarkerMap(mapId, { force: true, publishedOnly: true }); localStorage.removeItem(localMarkerEditKey(mapId)); clearMarkerSelection(); replaceLoadedMarkerMap(mapId, published); showMarkerStatus('Local changes cleared. Latest published markers loaded.'); } catch (error) { showMarkerStatus(`Reset failed: ${error.message}`, true); } finally { markerResetButton.disabled = false; } }); inlineDeleteButton.addEventListener('click', async () => { const session = editSession; if (!session || session.isNew || session.busy) return; const record = markerRecords.get(session.id); if (!record) return; const confirmation = markerPersistence === 'local' ? `Delete “${record.label}” from this browser?` : `Delete “${record.label}”? The default backup is unchanged.`; if (!window.confirm(confirmation)) return; session.busy = true; inlineDeleteButton.disabled = true; showMarkerStatus('Deleting marker…'); try { if (markerPersistence === 'local') { deleteLocalMarker(record); } else { const response = await fetch('api/marker', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'delete', id: record.id, mapId: record.mapId }), }); const responseText = await response.text(); let result; try { result = JSON.parse(responseText); } catch { result = {}; } if (!response.ok) throw new Error( result.error || 'This server is read-only; start it with server/run.ps1 -Editable', ); } removeIndexedMarker(record.id); loadedMarkerMaps.get(record.mapId)?.delete(record.id); refreshMarkerCounts(); scheduleMarkerRefresh(); endSession(session); showMarkerStatus(markerPersistence === 'local' ? 'Marker deleted locally. Reset this map to restore published markers.' : 'Marker deleted. The read-only default remains available for restoration.'); } catch (error) { session.busy = false; inlineDeleteButton.disabled = false; showMarkerStatus(`Delete failed: ${error.message}`, true); } }); inlineCategoryInput.addEventListener('change', () => { if (editSession) restyleEditedMarker(editSession, inlineCategoryInput.value); }); inlineBox.addEventListener('keydown', (event) => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); cancelInlineEditor(); } else if (event.key === 'Enter' && event.target.tagName !== 'BUTTON') { event.preventDefault(); void commitInlineEditor(); } }); // Any left click outside the box (map, another marker, the toolbar…) // commits the open edit. The click that ends a map pan is not a click. document.addEventListener('click', (event) => { if (!editSession || event.button !== 0) return; const { target } = event; if (!(target instanceof Node)) return; if (inlineBox.contains(target) || markerContextMenu.contains(target)) return; if (editedLeafletMarker(editSession)?.getElement()?.contains(target)) return; if (map.getContainer().contains(target) && map.dragging?.moved?.()) return; void commitInlineEditor(); }, true); // --- new markers: right-click menu / drop click ---------------------- const startMarkerDraft = (m, latlng, category) => { const point = normalizedPoint(m, latlng); if (!point) { showMarkerStatus('Click inside the selected map to place the marker.', true); return false; } setMarkerDropping(false); const draft = { id: `draft-${Date.now()}`, mapId: m.id, mapName: m.name, x: point[0], y: point[1], category, label: categoryLabel(category), source: 'User marker', }; const draftMarker = L.marker(latlng, { icon: createMarkerIcon(draft), pane: 'semantic-markers', draggable: true, keyboard: false, zIndexOffset: 12000, }).addTo(map); const session = { id: draft.id, isNew: true, draft, draftMarker, busy: false }; draftMarker.on('drag', () => syncInlinePopup(session, draftMarker.getLatLng())); draftMarker.on('dragend', (dragEvent) => { const next = normalizedPoint(m, dragEvent.target.getLatLng()); if (!next) { dragEvent.target.setLatLng([ m.origin[1] + draft.y * m.size[1], m.origin[0] + draft.x * m.size[0], ]); syncInlinePopup(session, dragEvent.target.getLatLng()); showMarkerStatus('Keep the marker inside the selected map.', true); return; } draft.x = next[0]; draft.y = next[1]; }); openSession(session); showMarkerStatus('Name the marker, then click anywhere else to save it.'); return true; }; // Smallest map under the pointer wins (Dorms beats Customs), preferring // maps whose tiles are actually showing at this zoom; the map being edited // wins outright while the pointer is inside it. const mapAtLatLng = (latlng) => { const selected = markerEditing.active ? byId.get(markerEditing.selectedMapId) : null; if (selected && normalizedPoint(selected, latlng)) return selected; const containing = detail .filter((m) => normalizedPoint(m, latlng)) .sort((a, b) => a.size[0] * a.size[1] - b.size[0] * b.size[1]); return containing.find((m) => map.getZoom() >= m.minZoom) ?? containing[0] ?? null; }; let contextTarget = null; const contextHeader = document.createElement('div'); contextHeader.className = 'context-menu-header'; markerContextMenu.appendChild(contextHeader); const knownGroups = new Set(groups.map((group) => group.id)); const menuGroups = [...groups, { id: '__other', label: 'Other' }]; for (const group of menuGroups) { const categories = editorCategories.filter((category) => { const own = categoryConfig(category).group; return (knownGroups.has(own) ? own : '__other') === group.id; }); if (!categories.length) continue; const heading = document.createElement('div'); heading.className = 'context-menu-group'; heading.textContent = group.label; markerContextMenu.appendChild(heading); for (const category of categories) { const settings = categoryConfig(category); const item = document.createElement('button'); item.type = 'button'; item.setAttribute('role', 'menuitem'); item.dataset.category = category; const swatch = document.createElement('span'); swatch.className = 'marker-category-swatch'; swatch.style.background = safeColor(settings.color); swatch.textContent = settings.symbol ?? '•'; const text = document.createElement('span'); text.textContent = categoryLabel(category); item.append(swatch, text); item.addEventListener('click', () => chooseContextCategory(category)); markerContextMenu.appendChild(item); } } function hideContextMenu() { markerContextMenu.hidden = true; contextTarget = null; } const showContextMenu = (event) => { hideContextMenu(); const m = mapAtLatLng(event.latlng); if (!m) return; contextTarget = { m, latlng: event.latlng }; contextHeader.textContent = `Add marker · ${m.name}`; markerContextMenu.hidden = false; const { clientX, clientY } = event.originalEvent; const margin = 8; const left = Math.min(clientX, window.innerWidth - markerContextMenu.offsetWidth - margin); const top = Math.min(clientY, window.innerHeight - markerContextMenu.offsetHeight - margin); markerContextMenu.style.left = `${Math.max(margin, left)}px`; markerContextMenu.style.top = `${Math.max(margin, top)}px`; markerContextMenu.querySelector('button')?.focus({ preventScroll: true }); }; const chooseContextCategory = (category) => { const target = contextTarget; hideContextMenu(); if (!target) return; const { m, latlng } = target; if (!markerEditing.active || markerEditing.selectedMapId !== m.id) { selectTarget(m); if (!markerEditing.active) openMarkerEditor(m); } if (!markerEditing.active) return; startMarkerDraft(m, latlng, category); }; if (markerEditingEnabled) { map.on('contextmenu', showContextMenu); map.on('movestart zoomstart', hideContextMenu); window.addEventListener('resize', hideContextMenu); document.addEventListener('pointerdown', (event) => { if (!markerContextMenu.hidden && !markerContextMenu.contains(event.target)) hideContextMenu(); }, true); markerContextMenu.addEventListener('keydown', (event) => { const items = [...markerContextMenu.querySelectorAll('button')]; const index = items.indexOf(document.activeElement); if (event.key === 'Escape') { event.preventDefault(); hideContextMenu(); } else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { event.preventDefault(); const step = event.key === 'ArrowDown' ? 1 : -1; items[(index + step + items.length) % items.length]?.focus({ preventScroll: true }); } }); } const showStatus = (message, isError = false) => { status.textContent = message; status.dataset.error = String(isError); }; const writeGeometry = (geometry) => { xInput.value = (geometry.center.lng / world.overallScale).toFixed(3); yInput.value = (geometry.center.lat / world.overallScale).toFixed(3); widthInput.value = (geometry.width / world.overallScale).toFixed(3); heightInput.value = (geometry.height / world.overallScale).toFixed(3); aspectOutput.textContent = `Aspect ratio ${(geometry.width / geometry.height).toFixed(3)}:1`; }; const setPreviewGeometry = (m, geometry) => { const normalized = { ...geometry, center: L.latLng(geometry.center) }; previewGeometry.set(m.id, normalized); updatePreviewTransform(m); editor.marker?.setLatLng(normalized.center); editor.outline?.setBounds(rectAt(normalized)); writeGeometry(normalized); }; const clearEditorLayers = () => { if (editor.marker) map.removeLayer(editor.marker); if (editor.outline) map.removeLayer(editor.outline); editor.marker = null; editor.outline = null; }; const resetPreview = (m) => { if (!m) return; previewGeometry.set(m.id, geometryOf(m)); updatePreviewTransform(m); }; const closeEditor = () => { const m = byId.get(editor.selectedId); resetPreview(m); restoreMapAppearance(m); clearEditorLayers(); editor.active = false; editorPanel.hidden = true; editButton.setAttribute('aria-pressed', 'false'); showStatus(''); }; const openEditor = (m) => { if (!mapEditingEnabled || !m || m.base) return; if (trimEditor.active) closeTrimEditor(); if (markerEditing.active) closeMarkerEditor(); const previous = byId.get(editor.selectedId); if (previous && previous.id !== m.id) { resetPreview(previous); restoreMapAppearance(previous); } clearEditorLayers(); editor.selectedId = m.id; editor.active = true; editorPanel.hidden = false; editButton.disabled = false; editButton.setAttribute('aria-pressed', 'true'); editorName.textContent = m.name; showStatus('Unsaved changes stay in this preview until you save.'); setLayerSource(m, false); const geometry = previewGeometry.get(m.id) ?? geometryOf(m); editor.outline = L.rectangle(rectAt(geometry), { color: '#ffe66d', weight: 2, dashArray: '8 7', fill: false, interactive: false, }).addTo(map); editor.marker = L.marker(geometry.center, { draggable: true, zIndexOffset: 10000, icon: L.divIcon({ className: 'placement-anchor', iconSize: [28, 28] }), }).addTo(map); editor.marker.on('drag', (event) => setPreviewGeometry(m, { ...previewGeometry.get(m.id), center: event.target.getLatLng(), })); editor.marker.on('dragend', () => showStatus('Ready to save and rebuild.')); writeGeometry(geometry); panes.get(m.id).style.opacity = '0.5'; const inside = insidePanes.get(m.id); if (inside) inside.style.display = 'none'; focus(m.id); }; const selectTarget = (m) => { const mode = editor.active ? 'placement' : (trimEditor.active ? 'trim' : (markerEditing.active ? 'markers' : null)); if (editor.active) closeEditor(); if (trimEditor.active) closeTrimEditor(); if (markerEditing.active) closeMarkerEditor(); editor.selectedId = m.base ? null : m.id; trimEditor.selectedId = m.base ? null : m.id; markerEditing.selectedMapId = m.base ? null : m.id; editButton.disabled = !mapEditingEnabled || !!m.base; trimButton.disabled = !mapEditingEnabled || !!m.base; markerEditButton.disabled = !markerEditingEnabled || !!m.base; buttons.forEach((b) => { b.dataset.selected = String(b.dataset.id === m.id); }); overviewButton.dataset.selected = String(!!m.base); if (mapEditingEnabled && !m.base && mode === 'placement') openEditor(m); if (mapEditingEnabled && !m.base && mode === 'trim') openTrimEditor(m); if (markerEditingEnabled && !m.base && mode === 'markers') openMarkerEditor(m); }; const roots = detail.filter((m) => !m.parent); const orderedDetail = roots.flatMap((m) => [ m, ...detail.filter((child) => child.parent === m.id), ]); const orderedIds = new Set(orderedDetail.map((m) => m.id)); orderedDetail.push(...detail.filter((m) => !orderedIds.has(m.id))); const buttons = orderedDetail.map((m) => { const b = document.createElement('button'); b.textContent = m.name; b.dataset.id = m.id; b.dataset.subMap = String(!!m.parent); b.addEventListener('click', () => { selectTarget(m); map.flyToBounds(familyViewRect(m), { padding: [24, 24], duration: 0.7 }); // A phone has no hover: picking a map gives the screen back to the map. if (window.matchMedia('(max-width: 640px)').matches) setPanelPinned(false); }); list.appendChild(b); return b; }); overviewButton.addEventListener('click', () => { selectTarget(base); focus(base.id); map.flyToBounds(familyViewRect(base), { padding: [24, 24], duration: 0.7 }); }); editButton.setAttribute('aria-pressed', 'false'); trimButton.setAttribute('aria-pressed', 'false'); markerEditButton.setAttribute('aria-pressed', 'false'); exportButton.addEventListener('click', async () => { exportButton.disabled = true; exportStatus.dataset.error = 'false'; exportStatus.textContent = 'Building static ZIP…'; try { const response = await fetch('api/export', { method: 'POST' }); const result = await response.json().catch(() => ({})); if (!response.ok) throw new Error(result.error || `Export failed (${response.status})`); const sizeMiB = (Number(result.zipBytes) / 1024 / 1024).toFixed(1); exportStatus.textContent = `Created ${result.fileName} (${sizeMiB} MiB, ${result.fileCount} files).`; const download = document.createElement('a'); download.href = `${result.download}?v=${Date.now()}`; download.download = result.fileName; document.body.appendChild(download); download.click(); download.remove(); } catch (error) { exportStatus.dataset.error = 'true'; exportStatus.textContent = error.message; } finally { exportButton.disabled = false; } }); editButton.addEventListener('click', () => { if (editor.active) closeEditor(); else openEditor(byId.get(editor.selectedId)); }); trimButton.addEventListener('click', () => { if (trimEditor.active) closeTrimEditor(); else openTrimEditor(byId.get(trimEditor.selectedId)); }); markerEditButton.addEventListener('click', () => { if (markerEditing.active) closeMarkerEditor(); else openMarkerEditor(byId.get(markerEditing.selectedMapId)); }); const applyInputs = () => { const m = byId.get(editor.selectedId); const cx = Number(xInput.value); const cy = Number(yInput.value); const width = Number(widthInput.value); const height = Number(heightInput.value); if (!m || ![cx, cy, width, height].every(Number.isFinite) || width <= 0 || height <= 0) return; setPreviewGeometry(m, { center: L.latLng(cy * world.overallScale, cx * world.overallScale), width: width * world.overallScale, height: height * world.overallScale, }); showStatus('Ready to save and rebuild.'); }; xInput.addEventListener('input', applyInputs); yInput.addEventListener('input', applyInputs); widthInput.addEventListener('input', applyInputs); heightInput.addEventListener('input', applyInputs); resetButton.addEventListener('click', () => { const m = byId.get(editor.selectedId); if (!m) return; setPreviewGeometry(m, geometryOf(m)); showStatus('Reset to the last saved center.'); }); saveButton.addEventListener('click', async () => { const m = byId.get(editor.selectedId); const geometry = m && previewGeometry.get(m.id); if (!m || !geometry) return; saveButton.disabled = true; resetButton.disabled = true; showStatus('Saving maps.json and rebuilding this map…'); try { const response = await fetch('api/placement', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: m.id, cx: geometry.center.lng / world.overallScale, cy: geometry.center.lat / world.overallScale, w: geometry.width / world.overallScale, h: geometry.height / world.overallScale, }), }); const responseText = await response.text(); let result; try { result = JSON.parse(responseText); } catch { result = {}; } if (!response.ok) throw new Error( result.error || 'This server is read-only; start it with server/run.ps1 -Editable', ); showStatus('Saved. Reloading rebuilt tiles…'); const z = Math.round(map.getZoom() * 4) / 4; history.replaceState( null, '', `#${z}/${Math.round(geometry.center.lat)}/${Math.round(geometry.center.lng)}`, ); location.reload(); } catch (error) { showStatus(`Save failed: ${error.message}`, true); saveButton.disabled = false; resetButton.disabled = false; } }); // --- playable-area trim editor --------------------------------------- const showTrimStatus = (message, isError = false) => { trimStatus.textContent = message; trimStatus.dataset.error = String(isError); }; const trimLatLngs = (m) => trimEditor.points.map(([x, y]) => L.latLng( m.origin[1] + y * m.size[1], m.origin[0] + x * m.size[0], )); const normalizedPoint = (m, latlng) => { const x = (latlng.lng - m.origin[0]) / m.size[0]; const y = (latlng.lat - m.origin[1]) / m.size[1]; if (x < 0 || x > 1 || y < 0 || y > 1) return null; return [Math.max(0, Math.min(1, x)), Math.max(0, Math.min(1, y))]; }; const updateTrimUI = () => { const count = trimEditor.points.length; trimPointCount.textContent = `${count} point${count === 1 ? '' : 's'}`; trimTransparency.value = String(Math.round(trimEditor.transparency * 100)); trimTransparencyValue.textContent = `${Math.round(trimEditor.transparency * 100)}%`; trimUndo.disabled = count === 0; trimClear.disabled = count === 0; trimSave.disabled = count === 1 || count === 2; }; const clearTrimEditorLayers = () => { trimEditor.markers.forEach((marker) => map.removeLayer(marker)); trimEditor.markers = []; if (trimEditor.outline) map.removeLayer(trimEditor.outline); trimEditor.outline = null; }; const updateTrimShape = (m) => { const latlngs = trimLatLngs(m); if (trimEditor.outline) { const shape = latlngs.length >= 3 ? [...latlngs, latlngs[0]] : latlngs; trimEditor.outline.setLatLngs(shape); } renderTrim(m, trimEditor.points, trimEditor.transparency); updateTrimUI(); }; const rebuildTrimEditorLayers = (m) => { clearTrimEditorLayers(); const latlngs = trimLatLngs(m); if (latlngs.length) { const shape = latlngs.length >= 3 ? [...latlngs, latlngs[0]] : latlngs; trimEditor.outline = L.polyline(shape, { color: '#ffcf4a', weight: 2, dashArray: '7 6', interactive: false, }).addTo(map); } trimEditor.markers = latlngs.map((latlng, index) => { const marker = L.marker(latlng, { draggable: true, zIndexOffset: 11000, icon: L.divIcon({ className: 'trim-vertex', iconSize: [14, 14] }), }).addTo(map); marker.on('drag', (event) => { const point = normalizedPoint(m, event.target.getLatLng()); if (!point) return; trimEditor.points[index] = point; updateTrimShape(m); }); marker.on('dragend', () => showTrimStatus('Ready to save.')); return marker; }); updateTrimShape(m); }; function closeTrimEditor() { const m = byId.get(trimEditor.selectedId); clearTrimEditorLayers(); trimEditor.active = false; trimPanel.hidden = true; trimButton.setAttribute('aria-pressed', 'false'); restoreMapAppearance(m); showTrimStatus(''); } function openTrimEditor(m) { if (!mapEditingEnabled || !m || m.base) return; if (editor.active) closeEditor(); if (markerEditing.active) closeMarkerEditor(); clearTrimEditorLayers(); const saved = savedTrim(m); trimEditor.selectedId = m.id; trimEditor.active = true; trimEditor.points = saved.points; trimEditor.transparency = saved.transparency; trimPanel.hidden = false; trimButton.disabled = false; trimButton.setAttribute('aria-pressed', 'true'); trimName.textContent = m.name; setLayerSource(m, false); showTrimStatus(saved.points.length ? 'Drag existing points or click the map to add more.' : 'Add at least three points around the playable area.'); rebuildTrimEditorLayers(m); focus(m.id); } trimTransparency.addEventListener('input', () => { const m = byId.get(trimEditor.selectedId); if (!m) return; trimEditor.transparency = Number(trimTransparency.value) / 100; renderTrim(m, trimEditor.points, trimEditor.transparency); updateTrimUI(); showTrimStatus('Ready to save.'); }); trimUndo.addEventListener('click', () => { const m = byId.get(trimEditor.selectedId); if (!m || !trimEditor.points.length) return; trimEditor.points.pop(); rebuildTrimEditorLayers(m); showTrimStatus(trimEditor.points.length >= 3 ? 'Ready to save.' : 'Add at least three points.'); }); trimClear.addEventListener('click', () => { const m = byId.get(trimEditor.selectedId); if (!m) return; trimEditor.points = []; rebuildTrimEditorLayers(m); showTrimStatus('Trim cleared. Save to restore the full map.'); }); trimSave.addEventListener('click', async () => { const m = byId.get(trimEditor.selectedId); if (!m || (trimEditor.points.length > 0 && trimEditor.points.length < 3)) return; trimSave.disabled = true; showTrimStatus('Saving and rendering a permanent trimmed copy…'); try { const response = await fetch('api/trim', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: m.id, points: trimEditor.points, outsideTransparency: trimEditor.transparency, }), }); const responseText = await response.text(); let result; try { result = JSON.parse(responseText); } catch { result = {}; } if (!response.ok) throw new Error( result.error || 'This server is read-only; start it with server/run.ps1 -Editable', ); m.trim = result.trim; m.version = result.map.version; m.trimmedVersion = result.map.trimmedVersion; showTrimStatus('Saved. Loading the permanent trimmed tiles…'); closeTrimEditor(); } catch (error) { showTrimStatus(`Save failed: ${error.message}`, true); } finally { updateTrimUI(); } }); map.on('click', (event) => { if (markerEditing.active && markerEditing.dropping) { const m = byId.get(markerEditing.selectedMapId); if (!m) return; const category = editorCategories.includes('poi') ? 'poi' : editorCategories[0]; startMarkerDraft(m, event.latlng, category); return; } if (!trimEditor.active) return; const m = byId.get(trimEditor.selectedId); const point = m && normalizedPoint(m, event.latlng); if (!m || !point) { showTrimStatus('Click inside the selected map to add a point.', true); return; } trimEditor.points.push(point); rebuildTrimEditorLayers(m); showTrimStatus(trimEditor.points.length >= 3 ? 'Ready to save.' : 'Add at least three points.'); }); const updateAllTrimClips = () => { if (!trimEditor.active) return; const m = byId.get(trimEditor.selectedId); if (m && trimEditor.points.length >= 3) updateTrimClip(m, trimEditor.points); }; const syncUI = () => { const c = map.getCenter(); // Smallest non-base map containing the centre wins -- Dorms beats Customs. const hit = markerZoomVisible() ? world.maps .filter((m) => !m.base && viewContains(m, c) && map.getZoom() >= m.minZoom) .sort((a, b) => a.size[0] * a.size[1] - b.size[0] * b.size[1])[0] : null; buttons.forEach((b) => b.setAttribute( 'aria-current', String(!!hit && hit.id === b.dataset.id))); overviewButton.setAttribute('aria-current', String(!hit)); focus(editor.active ? editor.selectedId : (trimEditor.active ? trimEditor.selectedId : (markerEditing.active ? markerEditing.selectedMapId : hit?.id))); const z = Math.round(map.getZoom() * 4) / 4; history.replaceState(null, '', `#${z}/${Math.round(c.lat)}/${Math.round(c.lng)}`); }; map.on('moveend zoomend', syncUI); map.on('move zoom zoomend', () => { updatePreviewTransforms(); updateAllTrimClips(); }); // --- detail / performance mode --------------------------------------- const qualityButton = document.getElementById('quality-toggle'); const qualityLabels = { auto: 'Auto', fast: 'Fast', sharp: 'Sharp' }; const effective = fastMode ? 'fast' : (DENSITY_BOOST ? 'sharp' : 'balanced'); qualityButton.textContent = `Detail: ${qualityLabels[qualityMode]}` + (qualityMode === 'auto' ? ` (${effective})` : ''); qualityButton.title = 'Fast: fewer, lighter tiles for weak devices and slow connections. ' + 'Sharp: denser tiles for high-DPI screens. Auto picks from the hardware. Reloads the page.'; qualityButton.addEventListener('click', () => { const next = QUALITY_MODES[(QUALITY_MODES.indexOf(qualityMode) + 1) % QUALITY_MODES.length]; localStorage.setItem(QUALITY_KEY, next); location.reload(); // tile size and layer options are fixed at creation }); const h = readHash(); if (h) map.setView([h.y, h.x], h.z); else map.fitBounds(rectOf(base), { padding: [10, 10] }); detail.forEach(restoreMapAppearance); syncUI(); document.getElementById('boot').remove(); // --- warm the cache ---------------------------------------------------- /* The overview plus every map's shallow levels are small (z<=5 for the * whole world is a few hundred tiles, a few MB). Fetching them once in the * background means the next visit -- or the next alt-tab from the game -- * paints every map from cache, and only the deep levels of the map you are * actually looking at still touch the network. It also keeps the low-res * underlay permanently warm. Tile responses are immutable for a year, so * repeating this later costs nothing: every fetch is a cache hit. */ const precacheUrls = () => { const urls = []; const ts = world.tileSize; for (const m of world.maps) { const trimmed = usesPermanentTrim(m); const version = trimmed ? m.trimmedVersion : m.version; const template = tileUrl(m, trimmed) + (version ? `?v=${version}` : ''); const top = m.base ? m.maxNativeZoom : Math.min(m.maxNativeZoom, PERF.precacheLevel); for (let z = m.minZoom; z <= top; z += 1) { const s = 2 ** (z - ZMAX); const px = (m.origin[0] - m.cell[0] * world.cellSize) * s; const py = (m.origin[1] - m.cell[1] * world.cellSize) * s; const cw = Math.max(1, Math.round(m.size[0] * s)); const ch = Math.max(1, Math.round(m.size[1] * s)); for (let tx = Math.floor(px / ts); tx < Math.ceil((px + cw) / ts); tx += 1) { for (let ty = Math.floor(py / ts); ty < Math.ceil((py + ch) / ts); ty += 1) { urls.push(template.replace('{z}', z).replace('{x}', tx).replace('{y}', ty)); } } } } return urls; }; const warmTileCache = () => { if (!PERF.precache) return; const stampKey = 'tarkov-precache'; const stamp = world.maps.map((m) => `${m.id}:${m.trimmedVersion ?? m.version}`).join(','); const [lastStamp, lastTime] = (localStorage.getItem(stampKey) ?? '').split('|'); if (lastStamp === stamp && Date.now() - Number(lastTime) < 7 * 86400e3) return; const queue = precacheUrls(); let busy = false; let active = 0; map.on('movestart zoomstart', () => { busy = true; }); map.on('moveend zoomend', () => { busy = false; }); const idle = window.requestIdleCallback ?? ((cb) => setTimeout(cb, 200)); const pump = () => { if (busy) { setTimeout(pump, 500); return; } while (active < 2 && queue.length) { active += 1; fetch(queue.shift(), { priority: 'low' }) .catch(() => {}) .finally(() => { active -= 1; if (queue.length) idle(pump, { timeout: 2000 }); else if (!active) localStorage.setItem(stampKey, `${stamp}|${Date.now()}`); }); } }; // Let the first view land before spending bandwidth on the rest. setTimeout(() => idle(pump, { timeout: 2000 }), 4000); }; warmTileCache(); // --- service worker ----------------------------------------------------- /* Offline and instant-start for the read-only viewer. The authoring server * is excluded: its whole point is seeing a rebuild immediately, and a * cached shell would get in the way. Browsers only allow service workers * on HTTPS or localhost, so a plain-HTTP LAN address silently skips this * and relies on the ordinary HTTP cache, which the warm-up above fills. */ if ('serviceWorker' in navigator) { if (mapEditingEnabled) { navigator.serviceWorker.getRegistrations() .then((registrations) => registrations.forEach((r) => r.unregister())) .catch(() => {}); } else { navigator.serviceWorker.register('sw.js').then((registration) => { const tell = (worker) => worker?.postMessage({ type: 'tile-versions', versions: world.maps.flatMap((m) => [m.version, m.trimmedVersion]).filter(Boolean), }); tell(registration.active ?? navigator.serviceWorker.controller); navigator.serviceWorker.addEventListener('controllerchange', () => { tell(navigator.serviceWorker.controller); }); }).catch((error) => console.warn('service worker unavailable:', error.message)); } } window.tarkovMap = map; window.tarkovWorld = world; } main().catch((err) => { document.getElementById('boot').textContent = `Failed to load: ${err.message}`; console.error(err); });