From ac62ab7b795c9b04aedb8a23d5bc10f05cf21e52 Mon Sep 17 00:00:00 2001 From: Flavio Giacchetti Date: Wed, 7 Oct 2026 15:53:09 +0200 Subject: [PATCH 1/3] feat: embed versioned maps and integrate compatible game provider --- CHANGELOG.md | 9 +++- README.md | 8 +--- ats-dualsense/desktop/embed-maps.cjs | 22 ++++++++++ ats-dualsense/desktop/main.cjs | 10 ++--- ats-dualsense/desktop/maps.cjs | 41 +++++++++++++++++++ ats-dualsense/desktop/package.cjs | 15 +++++-- ats-dualsense/desktop/policy.cjs | 2 +- ats-dualsense/desktop/test/maps.test.cjs | 18 ++++++++ ats-dualsense/scripts/export-road-map.py | 7 ++++ ats-dualsense/scripts/install-desktop.sh | 2 +- ats-dualsense/scripts/package-release.sh | 4 +- .../third_party/ets2la-provider/LICENSE | 9 ++++ .../third_party/ets2la-provider/README.md | 11 +++++ ats-dualsense/ui/index.html | 4 +- ats-dualsense/ui/navigation.js | 21 ++++++---- docs/ARCHITECTURE.md | 4 +- docs/QUALIFICATION.md | 6 +++ docs/RELEASING.md | 2 +- docs/SIGNAL-PROVIDER.md | 4 ++ docs/WEB-NAVIGATOR.md | 16 +++++--- tests/browser-procedural.cjs | 2 +- tests/browser-scene.cjs | 2 +- tests/desktop.cjs | 6 +-- 23 files changed, 182 insertions(+), 43 deletions(-) create mode 100644 ats-dualsense/desktop/embed-maps.cjs create mode 100644 ats-dualsense/desktop/maps.cjs create mode 100644 ats-dualsense/desktop/test/maps.test.cjs create mode 100644 ats-dualsense/third_party/ets2la-provider/LICENSE create mode 100644 ats-dualsense/third_party/ets2la-provider/README.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f833ce..1d52abc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,13 @@ # Changelog -## Unreleased — original low-poly driving scene +## Unreleased — embedded versioned maps and driving scene + +- Removed map file selection/forget controls. Standalone loads compressed game-matching app resources directly and ignores obsolete IndexedDB imports. +- Added automatic Steam library discovery, version-archive/content inventory compatibility checks, bounded gzip decoding and pack checksum validation. Incompatible packs are disabled after game/DLC changes. +- Local packaging embeds the qualified ATS 1.61.3.1 scene (about 24 MiB compressed). Public archives exclude local game-derived data; automatic extraction for other/new versions remains unimplemented. +- Bundled the MIT, checksum-pinned ETS2LA 1.61 provider with automatic installation for verified compatible game packs, existing DLL backups and installation/restart status. Live feed qualification remains separate from successful installation. +- Added embedded pack selection, tampering, version/DLC changes and clean-profile app reload/restart regressions. + - Replaced the triangle position marker with an original generic tractor and optional straight trailer proxy, following measured world pose. - Added a smoothed 30 FPS chase camera, persistent overview switch and shortest-angle heading interpolation; hidden/paused views stop animation. diff --git a/README.md b/README.md index cc4716f..b7ee23c 100644 --- a/README.md +++ b/README.md @@ -41,13 +41,9 @@ The app reuses `haulsense.service` when present, otherwise starts its bundled na ### Maps and live signal/GPS provider -Use **Load road map** once. IndexedDB restores that map on the next launch/reload; **Forget map** removes the saved copy. The standalone also checks `${XDG_DATA_HOME:-~/.local/share}/haulsense/maps/ats.json` on its first launch. Game-derived map files are not shipped in public releases. See [export, limits and map setup](docs/WEB-NAVIGATOR.md). +The standalone selects an embedded, compressed map automatically. There is no map file picker and old IndexedDB imports are ignored. Local packaging (`npm run --prefix ats-dualsense/desktop package -- --local-maps`, also used by the source desktop installer) embeds `build/ats-scene.json` / `build/ets2-scene.json` with extracted `gameVersion` metadata. Steam libraries are discovered automatically. The installed version archive and game/DLC archive inventory must match the pack; game/content updates disable incompatible roads instead of silently using stale data. The verified local ATS pack is **1.61.3.1**, approximately **24 MiB compressed**. ETS2 has no locally qualified embedded pack yet. -For **ATS/ETS2 1.61 only**, install the separate, checksum-pinned ETS2LA provider, then restart the game: - -```bash -GAME_VERSION=1.61 ATS_DIR='/path/to/American Truck Simulator' ./ats-dualsense/scripts/install-signal-provider.sh -``` +The standalone also bundles the checksum-pinned MIT **1.61.x** ETS2LA provider and installs it automatically into a verified matching Windows game installation, backing up a different existing DLL. Its status distinguishes installation from a live connection. Restart the game after a new provider installation. Game-derived packs stay in the local application; the public source/archive excludes them. Automatic extraction for arbitrary fresh installations and future game versions is not implemented; those builds need matching map packs prepared during packaging. See [pack creation and compatibility](docs/WEB-NAVIGATOR.md). Under Wine/Proton, the provider creates `/dev/shm/ETS2LASemaphore` and `/dev/shm/ETS2LARoute`. HaulSense reads them without writing controls or injecting into game memory. Do not use this pinned provider for another game version. [Provider ABI, compatibility and freshness](docs/SIGNAL-PROVIDER.md) explains the limitations and live qualification gap. diff --git a/ats-dualsense/desktop/embed-maps.cjs b/ats-dualsense/desktop/embed-maps.cjs new file mode 100644 index 0000000..b7cf73f --- /dev/null +++ b/ats-dualsense/desktop/embed-maps.cjs @@ -0,0 +1,22 @@ +'use strict'; +// Local game-derived packs stay in build/resources, outside source and public archives. +const fs=require('node:fs/promises'),path=require('node:path'),zlib=require('node:zlib'); +const {libraries,identify,digest,regular}=require('./maps.cjs'); +async function embed(target,home){ + const root=path.resolve(__dirname,'../..'),packs=[]; + for(const game of ['ats','ets2']){ + const source=path.join(root,'build',game+'-scene.json');let map;try{map=JSON.parse(await regular(source));}catch(error){if(error.code==='ENOENT')continue;throw error;} + if(map.game!==game||map.version!==2||!/^\d+\.\d+\.\d+\.\d+$/.test(map.gameVersion||''))throw Error('Map must contain its extracted gameVersion: '+source); + let directory;for(const library of await libraries(home)){const candidate=path.join(library,'steamapps','common',game==='ats'?'American Truck Simulator':'Euro Truck Simulator 2');try{await identify(candidate);directory=candidate;break;}catch{}} + if(!directory)throw Error('Cannot verify the game installation for '+game); + // Check extracted version against the current game's log before binding archive identity. + const id=game==='ats'?'270880':'227300';const steamapps=path.dirname(path.dirname(directory));const log=path.join(steamapps,'compatdata',id,'pfx','drive_c','users','steamuser','Documents',path.basename(directory),'game.log.txt'); + const versionStat=await fs.stat(path.join(directory,'version.scs')),logStat=await fs.stat(log);if(versionStat.mtimeMs>logStat.mtimeMs)throw Error('Run the updated game once before embedding its map'); + const text=await fs.readFile(log,'utf8');const match=text.match(/Loaded pack set version (\d+\.\d+\.\d+\.\d+)/);if(match?.[1]!==map.gameVersion)throw Error('Extracted map does not match the installed game log'); + const identity=await identify(directory),data=Buffer.from(JSON.stringify(map)),compressed=zlib.gzipSync(data,{level:9}),file=game+'-'+map.gameVersion+'.json.gz'; + await fs.mkdir(path.join(target,'maps'),{recursive:true});await fs.writeFile(path.join(target,'maps',file),compressed); + packs.push({game,gameVersion:map.gameVersion,file,bytes:data.length,sha256:digest(compressed),...identity}); + } + await fs.mkdir(path.join(target,'maps'),{recursive:true});await fs.writeFile(path.join(target,'maps','manifest.json'),JSON.stringify({format:1,packs},null,2));return packs; +} +module.exports={embed}; diff --git a/ats-dualsense/desktop/main.cjs b/ats-dualsense/desktop/main.cjs index 9733fa9..bbd5b9c 100644 --- a/ats-dualsense/desktop/main.cjs +++ b/ats-dualsense/desktop/main.cjs @@ -1,7 +1,7 @@ 'use strict'; const {app,BrowserWindow,Menu,protocol,session,dialog,net}=require('electron'); const {spawn}=require('node:child_process'); -const fs=require('node:fs'),path=require('node:path'),{Readable}=require('node:stream'); +const fs=require('node:fs'),path=require('node:path'); const {ORIGIN,allowedURL,allowedPath}=require('./policy.cjs'); const demo=process.argv.includes('--demo'); const service=demo?'http://127.0.0.1:39076':'http://127.0.0.1:39056';let window,ownedDaemon; @@ -25,15 +25,15 @@ async function ensureService(){ } async function start(){ await ensureService(); + const maps=new (require('./maps.cjs').EmbeddedMaps)(app.isPackaged?process.resourcesPath:path.resolve(__dirname,'../../build/embedded-resources'),app.getPath('home'));await maps.init(); + async function mapGame(){try{const state=await (await net.fetch(service+'/api/state',{signal:AbortSignal.timeout(1000)})).json();if(['ats','ets2'].includes(state.telemetry?.game))return state.telemetry.game;}catch{}return maps.manifest.packs[0]?.game||'ats';} const ses=session.fromPartition('persist:haulsense'); ses.setPermissionRequestHandler((_contents,_permission,callback)=>callback(false));ses.setPermissionCheckHandler(()=>false); ses.webRequest.onBeforeRequest((details,callback)=>callback({cancel:!allowedURL(details.url)})); ses.protocol.handle('haulsense',async request=>{ const url=new URL(request.url);if(!allowedURL(request.url)||url.search||!allowedPath(url.pathname,request.method))return new Response('Not found',{status:404}); - if(url.pathname==='/api/map'){ - const dataHome=process.env.XDG_DATA_HOME||path.join(app.getPath('home'),'.local','share'); - const map=path.join(dataHome,'haulsense','maps','ats.json'); - try{const stat=await fs.promises.lstat(map);if(!stat.isFile()||stat.size>96*1024*1024)throw Error('Invalid map');return new Response(Readable.toWeb(fs.createReadStream(map)),{headers:{'Content-Type':'application/json','Cache-Control':'no-store'}});}catch{return new Response('No installed map',{status:404});} + if(url.pathname==='/api/map-status'||url.pathname==='/api/map'){ + try{const game=await mapGame();if(url.pathname==='/api/map-status'){const {state,pack}=await maps.status(game);return Response.json({...state,id:pack?.sha256||null},{headers:{'Cache-Control':'no-store'}});}return new Response(await maps.read(game),{headers:{'Content-Type':'application/json','Cache-Control':'no-store'}});}catch{return new Response('Embedded map unavailable',{status:503});} } const headers={};if(request.method==='POST'){headers['X-HaulSense']='1';headers['Content-Type']='application/x-www-form-urlencoded';headers.Origin=service;} try{return await net.fetch(service+url.pathname,{method:request.method,headers,body:request.method==='POST'?await request.text():undefined,signal:AbortSignal.timeout(3000)});}catch{return new Response('Local service unavailable',{status:503});} diff --git a/ats-dualsense/desktop/maps.cjs b/ats-dualsense/desktop/maps.cjs new file mode 100644 index 0000000..ee999be --- /dev/null +++ b/ats-dualsense/desktop/maps.cjs @@ -0,0 +1,41 @@ +'use strict'; +// Trusted application resources only. Renderer input never supplies filesystem paths. +const fs=require('node:fs/promises'),path=require('node:path'),crypto=require('node:crypto'),zlib=require('node:zlib'); +const GAMES={ats:{id:'270880',directory:'American Truck Simulator'},ets2:{id:'227300',directory:'Euro Truck Simulator 2'}}; +const MAX=96*1024*1024; +const digest=data=>crypto.createHash('sha256').update(data).digest('hex'); +async function regular(file,max=MAX){const s=await fs.lstat(file);if(!s.isFile()||s.size>max)throw Error('Invalid application resource');return fs.readFile(file);} +async function libraries(home){ + const roots=[path.join(home,'.steam','steam'),path.join(home,'.local','share','Steam'),path.join(home,'.var','app','com.valvesoftware.Steam','data','Steam')];const result=new Set(); + for(const root of roots){try{const vdf=await fs.readFile(path.join(root,'steamapps','libraryfolders.vdf'),'utf8');result.add(root);for(const m of vdf.matchAll(/"path"\s+"([^"\r\n]+)"/g))if(path.isAbsolute(m[1]))result.add(m[1].replace(/\\\\/g,'\\'));}catch{}} + return [...result]; +} +async function identify(directory){ + const versionSha256=digest(await regular(path.join(directory,'version.scs'),1024*1024)); + const archives=[];for(const name of (await fs.readdir(directory)).filter(n=>/^[a-z0-9_]+\.scs$/i.test(n)).sort()){const s=await fs.lstat(path.join(directory,name));if(!s.isFile())throw Error('Invalid game archive');archives.push([name,s.size]);} + return {versionSha256,archiveSignature:digest(JSON.stringify(archives))}; +} +function compatible(pack,identity){return pack.versionSha256===identity.versionSha256&&pack.archiveSignature===identity.archiveSignature;} +class EmbeddedMaps{ + constructor(resources,home){this.resources=resources;this.home=home;this.checked=new Map();} + async init(){try{this.manifest=JSON.parse(await regular(path.join(this.resources,'maps','manifest.json'),1024*1024));if(this.manifest.format!==1||!Array.isArray(this.manifest.packs))throw Error('Invalid map catalog');}catch{this.manifest={format:1,packs:[]};}this.roots=await libraries(this.home);} + async status(game='ats'){ + if(!GAMES[game])game='ats';const packs=this.manifest.packs.filter(p=>p.game===game);let installation; + for(const root of this.roots){const directory=path.join(root,'steamapps','common',GAMES[game].directory);try{const identity=await identify(directory);installation={directory,identity};break;}catch{}} + const pack=installation&&packs.find(p=>compatible(p,installation.identity)); + const state={game,ready:!!pack,version:pack?.gameVersion||null,reason:!installation?'game-not-installed':!packs.length?'map-not-bundled':!pack?'version-mismatch':'ready',provider:'waiting',message:!installation?'Steam game installation not found.':!packs.length?'This app has no embedded map for '+game.toUpperCase()+'.':!pack?'Game content changed. A matching app map pack is required; incompatible roads are disabled.':'Embedded '+game.toUpperCase()+' '+pack.gameVersion+' map · verified against installed game archives'}; + if(pack&&pack.gameVersion.startsWith('1.61.')){try{state.provider=await this.provision(installation.directory);}catch{state.provider='install-failed';}} + if(pack&&!pack.gameVersion.startsWith('1.61.'))state.provider='unsupported-version'; + return {state,pack}; + } + async provision(directory){ + const source=path.join(this.resources,'providers','ets2la_plugin.dll');const expected='0e1893719f84f28079857451b82a22a263401d98b8fc299cd561eb7695bfa88f'; + const data=await regular(source,1024*1024);if(digest(data)!==expected)throw Error('Invalid provider checksum'); + const plugins=path.join(directory,'bin','win_x64','plugins');await fs.mkdir(plugins,{recursive:true});if(!(await fs.lstat(plugins)).isDirectory())throw Error('Invalid plugins directory');const target=path.join(plugins,'ets2la_plugin.dll'); + try{if(digest(await regular(target,1024*1024))===expected){const status=this.checked.get(directory)||'installed';this.checked.set(directory,status);return status;}await fs.copyFile(target,target+'.backup-'+Date.now(),fs.constants.COPYFILE_EXCL);}catch(error){if(error.code!=='ENOENT')throw error;} + const temporary=path.join(plugins,'.haulsense-provider-'+crypto.randomBytes(8).toString('hex'));try{await fs.writeFile(temporary,data,{mode:0o644,flag:'wx'});await fs.rename(temporary,target);}finally{await fs.unlink(temporary).catch(()=>{});} + this.checked.set(directory,'restart-required');return 'restart-required'; + } + async read(game){const {state,pack}=await this.status(game);if(!state.ready)throw Error(state.message);if(!/^(ats|ets2)-[0-9.]+\.json\.gz$/.test(pack.file))throw Error('Invalid map pack filename');const bytes=await regular(path.join(this.resources,'maps',pack.file));if(digest(bytes)!==pack.sha256)throw Error('Map pack checksum mismatch');const data=zlib.gunzipSync(bytes,{maxOutputLength:MAX});if(data.length!==pack.bytes)throw Error('Map pack size mismatch');return data;} +} +module.exports={EmbeddedMaps,libraries,identify,compatible,digest,regular}; diff --git a/ats-dualsense/desktop/package.cjs b/ats-dualsense/desktop/package.cjs index ef9ec9f..390c479 100644 --- a/ats-dualsense/desktop/package.cjs +++ b/ats-dualsense/desktop/package.cjs @@ -1,10 +1,19 @@ 'use strict'; -const path=require('node:path'),fs=require('node:fs/promises'); +const path=require('node:path'),fs=require('node:fs/promises'),os=require('node:os'); +const localMaps=process.argv.includes('--local-maps'); (async()=>{ + const provider=path.resolve(__dirname,'../../build/ets2la-provider/ets2la_plugin.dll'); + const expected='0e1893719f84f28079857451b82a22a263401d98b8fc299cd561eb7695bfa88f';let providerBytes; + try{providerBytes=await fs.readFile(provider);}catch(error){if(error.code!=='ENOENT')throw error;const response=await fetch('https://raw.githubusercontent.com/ETS2LA/ETS2LA/41945bc41e36191fbdf277c7fa6f7dd6f101d679/Assets/SDKs/1.61/Windows/ets2la_plugin.dll',{signal:AbortSignal.timeout(90000)});if(!response.ok||Number(response.headers.get('content-length'))>1024*1024)throw Error('Provider download failed');providerBytes=Buffer.from(await response.arrayBuffer());} + if(providerBytes.length>1024*1024||require('./maps.cjs').digest(providerBytes)!==expected)throw Error('Provider checksum mismatch'); const {packager}=await import('@electron/packager'); const output=path.resolve(__dirname,'../../build/desktop'); const {flipFuses,FuseVersion,FuseV1Options}=await import('@electron/fuses'); - const paths=await packager({dir:__dirname,out:output,name:'HaulSense',executableName:'haulsense-app',platform:'linux',arch:'x64',electronVersion:require('./package.json').devDependencies.electron,overwrite:true,asar:true,prune:true,ignore:[/^\/test(?:\/|$)/,/^\/package\.cjs$/,/^\/node_modules$/]}); - for(const directory of paths){await flipFuses(path.join(directory,'haulsense-app'),{version:FuseVersion.V1,[FuseV1Options.RunAsNode]:false,[FuseV1Options.EnableNodeOptionsEnvironmentVariable]:false,[FuseV1Options.EnableNodeCliInspectArguments]:false,[FuseV1Options.OnlyLoadAppFromAsar]:true});const target=path.join(directory,'resources','daemon');await fs.mkdir(target,{recursive:true});await fs.copyFile(path.resolve(__dirname,'../../build/ats-dualsense/daemon/haulsense'),path.join(target,'haulsense'));await fs.chmod(path.join(target,'haulsense'),0o755);await fs.copyFile(path.resolve(__dirname,'../../LICENSE'),path.join(directory,'HAULSENSE-LICENSE'));} + const paths=await packager({dir:__dirname,out:output,name:'HaulSense',executableName:'haulsense-app',platform:'linux',arch:'x64',electronVersion:require('./package.json').devDependencies.electron,overwrite:true,asar:true,prune:true,ignore:[/^\/test(?:\/|$)/,/^\/(?:package|embed-maps)\.cjs$/,/^\/node_modules$/]}); + for(const directory of paths){await flipFuses(path.join(directory,'haulsense-app'),{version:FuseVersion.V1,[FuseV1Options.RunAsNode]:false,[FuseV1Options.EnableNodeOptionsEnvironmentVariable]:false,[FuseV1Options.EnableNodeCliInspectArguments]:false,[FuseV1Options.OnlyLoadAppFromAsar]:true});const target=path.join(directory,'resources','daemon');await fs.mkdir(target,{recursive:true});await fs.copyFile(path.resolve(__dirname,'../../build/ats-dualsense/daemon/haulsense'),path.join(target,'haulsense'));await fs.chmod(path.join(target,'haulsense'),0o755);await fs.copyFile(path.resolve(__dirname,'../../LICENSE'),path.join(directory,'HAULSENSE-LICENSE')); + if(localMaps)await require('./embed-maps.cjs').embed(path.join(directory,'resources'),os.homedir()); + const destination=path.join(directory,'resources','providers');await fs.mkdir(destination,{recursive:true});await fs.writeFile(path.join(destination,'ets2la_plugin.dll'),providerBytes);await fs.copyFile(path.resolve(__dirname,'../third_party/ets2la-provider/LICENSE'),path.join(destination,'LICENSE')); + } + console.log(paths.join('\n')); })().catch(e=>{console.error(e.message);process.exitCode=1;}); diff --git a/ats-dualsense/desktop/policy.cjs b/ats-dualsense/desktop/policy.cjs index 150bf71..9ca00ce 100644 --- a/ats-dualsense/desktop/policy.cjs +++ b/ats-dualsense/desktop/policy.cjs @@ -3,6 +3,6 @@ const ORIGIN='haulsense://app'; function allowedURL(value){try{const u=new URL(value);return u.protocol==='haulsense:'&&u.hostname==='app'&&!u.username&&!u.password&&!u.port;}catch{return false;}} function allowedPath(path,method='GET'){ if(method==='POST')return path==='/api/config'; - return method==='GET'&&(['/','/hud','/navigation.js','/scene.js','/routing-worker.js','/dashboard.js','/hud.js','/persistence.js','/jobs.js','/api/state','/api/config','/api/route','/api/signals','/api/jobs','/api/map'].includes(path)||/^\/api\/jobs\/\d{1,24}$/.test(path)); + return method==='GET'&&(['/','/hud','/navigation.js','/scene.js','/routing-worker.js','/dashboard.js','/hud.js','/persistence.js','/jobs.js','/api/state','/api/config','/api/route','/api/signals','/api/jobs','/api/map','/api/map-status'].includes(path)||/^\/api\/jobs\/\d{1,24}$/.test(path)); } module.exports={ORIGIN,allowedURL,allowedPath}; diff --git a/ats-dualsense/desktop/test/maps.test.cjs b/ats-dualsense/desktop/test/maps.test.cjs new file mode 100644 index 0000000..0245490 --- /dev/null +++ b/ats-dualsense/desktop/test/maps.test.cjs @@ -0,0 +1,18 @@ +'use strict'; +const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path'),zlib=require('node:zlib'); +const {EmbeddedMaps,identify,digest,libraries}=require('../maps.cjs'); +test('embedded map selects the installed game and refuses updated or missing archives',async()=>{ + const temp=await fs.mkdtemp(path.join(os.tmpdir(),'haulsense-map-'));try{ + const home=path.join(temp,'home'),library=path.join(temp,'library'),resources=path.join(temp,'resources'),game=path.join(library,'steamapps','common','American Truck Simulator'); + await fs.mkdir(path.join(home,'.steam','steam','steamapps'),{recursive:true});await fs.mkdir(game,{recursive:true});await fs.mkdir(path.join(resources,'maps'),{recursive:true}); + await fs.writeFile(path.join(home,'.steam','steam','steamapps','libraryfolders.vdf'),'"path" "'+library+'"');await fs.writeFile(path.join(game,'version.scs'),'1.61');await fs.writeFile(path.join(game,'base_map.scs'),'roads'); + assert((await libraries(home)).includes(library));const data=Buffer.from(JSON.stringify({game:'ats',gameVersion:'1.61.3.1',roads:[]})),gz=zlib.gzipSync(data),file='ats-1.61.3.1.json.gz'; + const pack={game:'ats',gameVersion:'1.61.3.1',file,bytes:data.length,sha256:digest(gz),...await identify(game)}; + await fs.writeFile(path.join(resources,'maps',file),gz);await fs.writeFile(path.join(resources,'maps','manifest.json'),JSON.stringify({format:1,packs:[pack]}));const maps=new EmbeddedMaps(resources,home);await maps.init(); + assert.equal((await maps.status('ats')).state.ready,true);assert.deepEqual(await maps.read('ats'),data);assert.equal((await maps.status('ets2')).state.ready,false); + await fs.writeFile(path.join(resources,'maps',file),'tampered');await assert.rejects(maps.read('ats'),/checksum/);await fs.writeFile(path.join(resources,'maps',file),gz); + await fs.writeFile(path.join(game,'version.scs'),'1.62');assert.equal((await maps.status('ats')).state.reason,'version-mismatch');await assert.rejects(maps.read('ats'),/changed/); + await fs.writeFile(path.join(game,'version.scs'),'1.61');await fs.writeFile(path.join(game,'dlc_new.scs'),'new DLC');assert.equal((await maps.status('ats')).state.reason,'version-mismatch'); + await fs.unlink(path.join(game,'dlc_new.scs'));await fs.unlink(path.join(game,'base_map.scs'));assert.equal((await maps.status('ats')).state.ready,false); + }finally{await fs.rm(temp,{recursive:true,force:true});} +}); diff --git a/ats-dualsense/scripts/export-road-map.py b/ats-dualsense/scripts/export-road-map.py index 1255936..3dafa1f 100644 --- a/ats-dualsense/scripts/export-road-map.py +++ b/ats-dualsense/scripts/export-road-map.py @@ -7,6 +7,7 @@ import argparse import json import math +import re from pathlib import Path from scene_map import scene_export @@ -131,6 +132,12 @@ def read(kind): if not roads: raise ValueError('No roads in export; check source and bounds') result = {'version': 2, 'game': game, 'coordinates': 'scs-xz-metres', 'name': f'{game.upper()} · extracted roads', 'roads': roads, 'roadStyles':styles, 'labels':labels} + version_file = source / f'{prefix}-version.txt' + if version_file.exists(): + game_version = version_file.read_text().strip() + if not re.fullmatch(r'\d+\.\d+\.\d+\.\d+', game_version): + raise ValueError('Invalid extracted game version') + result['gameVersion'] = game_version result.update(scene_export(source, prefix, nodes, region)) # Reject invalid source coordinates before emitting a file accepted by the UI. for p in [p for road in roads for p in road] + [l['position'] for l in labels]: diff --git a/ats-dualsense/scripts/install-desktop.sh b/ats-dualsense/scripts/install-desktop.sh index dc4e64b..ba21d52 100755 --- a/ats-dualsense/scripts/install-desktop.sh +++ b/ats-dualsense/scripts/install-desktop.sh @@ -7,7 +7,7 @@ if [[ -x "$root/standalone/haulsense-app" ]]; then else npm ci --prefix "$root/ats-dualsense/desktop" --ignore-scripts --no-audit --no-fund node "$root/ats-dualsense/desktop/node_modules/electron/install.js" - npm run --prefix "$root/ats-dualsense/desktop" package + npm run --prefix "$root/ats-dualsense/desktop" package -- --local-maps fi install_dir="${XDG_DATA_HOME:-$HOME/.local/share}/haulsense/desktop" mkdir -p -- "$(dirname -- "$install_dir")" "$HOME/.local/bin" diff --git a/ats-dualsense/scripts/package-release.sh b/ats-dualsense/scripts/package-release.sh index eaafe7f..846e511 100755 --- a/ats-dualsense/scripts/package-release.sh +++ b/ats-dualsense/scripts/package-release.sh @@ -15,11 +15,13 @@ for part in config daemon plugin-win scripts systemd third_party ui; do cp -r "$ROOT/ats-dualsense/$part/." "$STAGE/ats-dualsense/$part/" done mkdir -p "$STAGE/ats-dualsense/desktop" -for file in main.cjs policy.cjs package.cjs package.json package-lock.json; do install -m644 "$ROOT/ats-dualsense/desktop/$file" "$STAGE/ats-dualsense/desktop/$file"; done +for file in main.cjs policy.cjs maps.cjs embed-maps.cjs package.cjs package.json package-lock.json; do install -m644 "$ROOT/ats-dualsense/desktop/$file" "$STAGE/ats-dualsense/desktop/$file"; done cp -r "$ROOT/ats-dualsense/desktop/test" "$STAGE/ats-dualsense/desktop/" mkdir -p "$STAGE/scripts" cp -r "$ROOT/scripts/." "$STAGE/scripts/" if [[ -x "$ROOT/build/desktop/HaulSense-linux-x64/haulsense-app" ]]; then cp -r "$ROOT/build/desktop/HaulSense-linux-x64" "$STAGE/standalone"; fi +# Game-derived packs belong to the local installation, never the public archive. +rm -rf -- "$STAGE/standalone/resources/maps" find "$STAGE" -type d -name __pycache__ -prune -exec rm -rf -- {} + install -m755 "$ROOT/build/ats-dualsense/daemon/haulsense" "$STAGE/ats-dualsense/bin/haulsense" rm -f "$STAGE/ats-dualsense/plugin-win/"*.lib "$STAGE/ats-dualsense/plugin-win/"*.obj "$STAGE/ats-dualsense/plugin-win/"*_stub.dll diff --git a/ats-dualsense/third_party/ets2la-provider/LICENSE b/ats-dualsense/third_party/ets2la-provider/LICENSE new file mode 100644 index 0000000..121b4ec --- /dev/null +++ b/ats-dualsense/third_party/ets2la-provider/LICENSE @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2024 Dario Wouters + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/ats-dualsense/third_party/ets2la-provider/README.md b/ats-dualsense/third_party/ets2la-provider/README.md new file mode 100644 index 0000000..32f2543 --- /dev/null +++ b/ats-dualsense/third_party/ets2la-provider/README.md @@ -0,0 +1,11 @@ +# ETS2LA memory provider + +The standalone build includes the upstream MIT Windows DLL for ATS/ETS2 **1.61.x**, fetched at build time and verified by SHA-256. Its own MIT license is distributed beside the DLL. The HaulSense renderer is original code. + +Binary: `ETS2LA/ETS2LA`, commit `41945bc41e36191fbdf277c7fa6f7dd6f101d679`, `Assets/SDKs/1.61/Windows/ets2la_plugin.dll`. + +SHA-256: `0e1893719f84f28079857451b82a22a263401d98b8fc299cd561eb7695bfa88f`. + +License/source: [dariowouters/ets2la_plugin](https://github.com/dariowouters/ets2la_plugin/tree/c925bd965a96c58b73eaea9ca033fe0f0dc623a7). + +The app installs the DLL automatically only when an embedded map verifies the installed game content and identifies a supported 1.61.x version. An existing different DLL is backed up. The game must restart after a new installation. No running-game memory writes or driving controls are performed by HaulSense. diff --git a/ats-dualsense/ui/index.html b/ats-dualsense/ui/index.html index 9ce04e6..bae8c01 100644 --- a/ats-dualsense/ui/index.html +++ b/ats-dualsense/ui/index.html @@ -30,8 +30,8 @@
Waiting for position—
Your next horizon.

World position requires the updated telemetry plugin.

Import a local road map to see ATS / ETS2 roads. Without one, only the measured journey trace is shown.
-

Maps are saved locally after import.

-

Load a detailed map for routing. Orange: future route · cyan: travelled trace.

Live signal states require the optional ETS2LA plugin.

Exact game GPS requires an optional route provider.

Original low-poly road diorama. Generic truck and straight trailer proxy; original game meshes, terrain and live traffic are not included.

+

Checking embedded game map…

+

The app selects the matching game map automatically. Orange: future route · cyan: travelled trace.

Traffic lights · waiting for game connection.

Game GPS · waiting for game connection.

Original low-poly road diorama. Generic truck and straight trailer proxy; original game meshes, terrain and live traffic are not included.

Journey companion

Local session
Remaining—Game travel time · —
Fuel margin—Estimated range after arrival
Driven—Odometer · this session
Cab attitude—Roll · —
Waiting for live truck data.
Cargo condition · —Trailer · —
Session kept in this tab
diff --git a/ats-dualsense/ui/navigation.js b/ats-dualsense/ui/navigation.js index 4549d35..854406e 100644 --- a/ats-dualsense/ui/navigation.js +++ b/ats-dualsense/ui/navigation.js @@ -50,6 +50,7 @@ function createNavigator({document,window}) { function reset(){trace=[];last=null;baseOdometer=null;previousOdometer=null;driven=0;lastSequence=null;} function formatKm(km,digits=0){return finite(km)?(metric?km:km/1.609344).toFixed(digits)+(metric?' km':' mi'):'—';} function update(s,isMetric=true){ + if(Date.now()-lastMapCheck>5000)restoreMap(); metric=isMetric;current=s; const t=s.active?s.telemetry:{},p=t.world_position; if(lastDemo!==s.demo||lastGame!==t.game&&s.active){reset();routePoints=[];gpsUntil=0;gpsKey='';gpsFailedKey='';routeRequest++;routePending=false;routeGoal=null;lastDemo=s.demo;if(s.active)lastGame=t.game;} @@ -141,7 +142,7 @@ function createNavigator({document,window}) { c.shadowColor='#d8ee8680';c.shadowBlur=18;c.fillStyle='#d8ee86';c.strokeStyle='#0b141a';c.lineWidth=2;c.beginPath();c.moveTo(0,-15);c.lineTo(11,12);c.lineTo(0,7);c.lineTo(-11,12);c.closePath();c.fill();c.stroke();c.restore(); c.font='10px system-ui';c.fillStyle='#8096a4';c.textAlign='left';c.fillText('SCS WORLD · '+(perspective?'PERSPECTIVE':'2D'),16,h-16); } - function loadMap(data){mapRevision++;const candidate=validateMap(data);candidate.bounds=candidate.roads.map(r=>{const b=[Infinity,Infinity,-Infinity,-Infinity];for(const [x,z]of r){b[0]=Math.min(b[0],x);b[1]=Math.min(b[1],z);b[2]=Math.max(b[2],x);b[3]=Math.max(b[3],z);}return b;});buildSceneIndex(candidate);roads=candidate;mapError='';if(scene){scene.dispose();scene=null;}sceneFailed=false;setupRouting();el('map-unload').hidden=false;if(current)update(current,metric);} + function loadMap(data){mapRevision++;const candidate=validateMap(data);candidate.bounds=candidate.roads.map(r=>{const b=[Infinity,Infinity,-Infinity,-Infinity];for(const [x,z]of r){b[0]=Math.min(b[0],x);b[1]=Math.min(b[1],z);b[2]=Math.max(b[2],x);b[3]=Math.max(b[3],z);}return b;});buildSceneIndex(candidate);roads=candidate;mapError='';if(scene){scene.dispose();scene=null;}sceneFailed=false;setupRouting();if(current)update(current,metric);} function buildSceneIndex(data){ const grid=new Map(),size=500; @@ -207,8 +208,6 @@ function createNavigator({document,window}) { el('route-destination').addEventListener('change',()=>{routeRequest++;routePending=false;routeGoal=null;gpsUntil=0;routeSource=null;gpsKey='';routePoints=[];texts('gps-status','Automatic mode can use the game GPS; selected cities use HaulSense routing.');maybeRoute(true);}); el('route-plan').addEventListener('click',()=>{routeReady=!!routeWorker;maybeRoute(true);}); el('route-clear').addEventListener('click',()=>{routePoints=[];routeGoal=null;routeRequest++;lastRoutePosition=null;routePending=false;routeReady=false;texts('route-status','Route cleared. Calculate route to start again.');draw();}); - el('map-file').addEventListener('change',async()=>{const file=el('map-file').files?.[0];if(!file)return;mapRevision++;try{if(file.size>limit.bytes)throw Error('Map exceeds 96 MiB. Export a smaller region.');loadMap(JSON.parse(await file.text()));try{await window.HaulSenseStorage?.saveMap(file,file.name);texts('map-storage','Saved on this device · restored automatically next launch');}catch(error){texts('map-storage','Map loaded, but persistence failed: '+error.message);}}catch(e){mapError='Map not loaded: '+e.message;text('map-note',mapError);}finally{el('map-file').value='';}}); - el('map-unload').addEventListener('click',()=>{mapRevision++;window.HaulSenseStorage?.forgetMap().then(()=>texts('map-storage','Saved map removed')).catch(error=>texts('map-storage',error.message));roads=null;mapError='';stopRouting();if(scene){scene.dispose();scene=null;}el('road-scene').hidden=true;el('map-unload').hidden=true;if(current)update(current,metric);}); el('map-perspective').addEventListener('click',()=>{perspective=!perspective;el('map-perspective').setAttribute('aria-pressed',String(perspective));el('map-perspective').textContent=perspective?'3D / Perspective':'2D';if(current)update(current,metric);}); el('map-camera').setAttribute('aria-pressed',String(chase));el('map-camera').textContent=chase?'Chase camera':'Overview camera'; el('map-camera').addEventListener('click',()=>{chase=!chase;if(chase){north=false;el('map-north').setAttribute('aria-pressed','false');}el('map-camera').setAttribute('aria-pressed',String(chase));el('map-camera').textContent=chase?'Chase camera':'Overview camera';window.HaulSenseStorage?.remember({camera:chase?'chase':'overview'});draw();}); @@ -216,12 +215,16 @@ function createNavigator({document,window}) { el('map-zoom-in').addEventListener('click',()=>{zoom=Math.min(4,zoom*1.4);draw();});el('map-zoom-out').addEventListener('click',()=>{zoom=Math.max(.25,zoom/1.4);draw();}); el('map-clear').addEventListener('click',()=>{trace=[];last=null;draw();});el('trip-reset').addEventListener('click',()=>{reset();if(current)update(current,metric);}); el('map-fullscreen').addEventListener('click',async()=>{try{if(document.fullscreenElement)await document.exitFullscreen();else await el('navigator').requestFullscreen();}catch{ text('map-note','Fullscreen unavailable in this browser.');}}); - async function restoreMap(){const revision=mapRevision;try{const entry=await window.HaulSenseStorage.readMap();if(revision!==mapRevision)return; - let blob=entry?.blob,name=entry?.name||'Installed local map'; - if(!blob&&window.location?.protocol==='haulsense:'){const response=await window.fetch('/api/map');if(response.ok)blob=await response.blob();} - if(!blob)return;if(blob.size>limit.bytes)throw Error('Saved map exceeds import limit');texts('map-storage','Restoring '+name+'…');const data=JSON.parse(await blob.text());if(revision!==mapRevision)return;loadMap(data);texts('map-storage','Restored automatically · saved on this device');if(!entry)await window.HaulSenseStorage.saveMap(blob,name); - }catch(error){texts('map-storage','Saved map unavailable: '+error.message);}} - if(window.HaulSenseStorage)restoreMap(); + let embeddedId=null,mapChecking=false,lastMapCheck=0; + function clearEmbeddedMap(){mapRevision++;roads=null;stopRouting();if(scene){scene.dispose();scene=null;}el('road-scene').hidden=true;embeddedId=null;el('map-storage').dataset.mapReady='false';} + async function restoreMap(){if(mapChecking||window.location?.protocol!=='haulsense:')return;mapChecking=true;lastMapCheck=Date.now();try{ + const response=await window.fetch('/api/map-status');if(!response.ok)throw Error('Map compatibility check unavailable');const status=await response.json();texts('map-storage',status.message); + if(!status.ready){if(roads)clearEmbeddedMap();return;} + if(!current?.active){const message=status.provider==='installed'?'Integrated provider ready · waiting for live game telemetry':status.provider==='restart-required'?'Integrated provider installed · restart the game to connect':status.provider==='unsupported-version'?'Live provider has no compatible build for this game version':'Integrated provider setup failed · check game folder permissions';texts('signal-status',message);texts('gps-status',message);} + if(status.id===embeddedId)return; + clearEmbeddedMap();const revision=mapRevision;texts('map-storage','Loading embedded '+status.game.toUpperCase()+' '+status.version+' map…');const mapResponse=await window.fetch('/api/map');if(!mapResponse.ok)throw Error('Matching embedded map unavailable');const blob=await mapResponse.blob();if(blob.size>limit.bytes)throw Error('Embedded map exceeds limit');const data=JSON.parse(await blob.text());if(revision!==mapRevision)return;if(data.game!==status.game||data.gameVersion!==status.version)throw Error('Embedded map identity mismatch');loadMap(data);embeddedId=status.id;el('map-storage').dataset.mapReady='true';texts('map-storage',status.message); + }catch(error){clearEmbeddedMap();texts('map-storage',error.message);}finally{mapChecking=false;}} + if(window.location?.protocol==='haulsense:')restoreMap();else texts('map-storage','Embedded game maps are available in the standalone app.'); document.addEventListener('fullscreenchange',draw);window.addEventListener('resize',draw); return {update,draw,loadMap,validateMap,queryScene,stats:()=>scene?.stats()}; } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0e5bf96..335505e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -19,7 +19,7 @@ The optional GTK HUD polls HTTP in one background thread. GTK updates and render The v6 packet appends a 38-byte suffix to the unchanged 825-byte v5 ABI: placement availability, three double-precision world coordinates, heading/pitch/roll in SDK turns, and game identity. V5 frames are normalized internally to v6 with no placement; the source version remains visible in snapshots. Placement comes from the SDK dplacement callback with explicit no-value clearing. Coordinates and orientation must be finite and bounded before acceptance. -The navigator embeds same-origin `/navigation.js`, `/scene.js` (MIT Three.js bundle) and `/routing-worker.js`. Detailed imports are limited to 96 MiB with bounded scene arrays, coordinate/reference checks and text-only labels. The canvas fallback and WebGL schematic scene follow dashboard polling without a separate animation loop. A 500-metre index culls objects/prefabs/signs/POIs, road bounding boxes cull lines, and templates, instancing and geometry batching reduce duplication and draw calls. WebGL uses a floating local origin and pixel ratio at most 1.5. The measured trace is bounded to 1,200 points; maps/trip state remain in tab memory. Game mismatch and unavailable placement hide the scene. +The navigator embeds same-origin `/navigation.js`, `/scene.js` (MIT Three.js bundle) and `/routing-worker.js`. Detailed maps are limited to 96 MiB with bounded scene arrays, coordinate/reference checks and text-only labels. Scene inputs follow dashboard polling; a bounded 30 FPS animation loop interpolates the chase camera and stops on hidden/paused views. A 500-metre index culls objects/prefabs/signs/POIs, road bounding boxes cull lines, and templates, instancing and geometry batching reduce duplication and draw calls. WebGL uses a floating local origin and pixel ratio at most 1.5. The measured trace is bounded to 1,200 points; maps/trip state remain in tab memory. Game mismatch and unavailable placement hide the scene. Routing runs in a Web Worker with a directed CSR graph and A* search. Road edges retain their curves; prefab links use supplied physical/AI navigation topology. Exact optional GPS UIDs must resolve to known connected directed edges. The independent path is explicitly labelled HaulSense and does not alter game navigation. @@ -27,7 +27,7 @@ A native RouteReader thread polls the optional ETS2LA 96,000-byte local route fi ## Standalone release candidate -The standalone Electron main process serves a privileged `haulsense://app` scheme with an explicit resource/API allowlist. API requests are forwarded to the fixed loopback service; renderer code cannot choose filesystem paths, execute Node or communicate through a generic IPC bridge. A persistent partition holds map cache/preferences. A native save dialog handles local JSON downloads. Browser mode remains available. Native/config/world placement data are kept out of remote navigation. +The standalone Electron main process serves a privileged `haulsense://app` scheme with an explicit resource/API allowlist. API requests are forwarded to the fixed loopback service; renderer code cannot choose filesystem paths, execute Node or communicate through a generic IPC bridge. A persistent partition holds preferences. Maps load from versioned compressed app resources, with checksum/size limits and installed game version/archive inventory verification; legacy map caches are ignored. The main process discovers Steam libraries and installs a checksum-pinned compatible provider, retaining backups of replaced DLLs. A native save dialog handles local JSON downloads. Browser mode remains available. Native/config/world placement data are kept out of remote navigation. `backgroundThrottling: false` keeps renderer timers/frames live outside focus, while the native service records every accepted UDP frame independently from the UI. Browser hidden tabs still conserve rendering work; background job capture is not tied to browser visibility. The scene and chart remain bounded; no general GPU/FPS guarantee is implied by cached draw timings. diff --git a/docs/QUALIFICATION.md b/docs/QUALIFICATION.md index 5f88940..1f357a9 100644 --- a/docs/QUALIFICATION.md +++ b/docs/QUALIFICATION.md @@ -138,3 +138,9 @@ This supersedes the earlier centerline-only navigator limitations; those dated r - Live v6 game-driving/map alignment, road width accuracy, original scenery reconstruction, complete DLC/mod coverage, ferry/restriction routing and a long-haul performance run remain open. Existing physical controller qualification is separate. - Installed daemon and all served JavaScript assets match the tested build; `haulsense.service` is active. Prior executable/DLL and unchanged config/HUD preferences were preserved in `build/pre-scene-install-20261007-070558/`. This scene update did not replace the already installed v6 DLL or restart ATS. The provider endpoint reports unavailable on the actual installed service. + +## Embedded maps qualification (2026-10-07) + +Local ATS 1.61.3.1 pack (about 24 MiB gzip) loaded from standalone resources with a clean Electron profile, after reload and after full app restart. A deliberately incompatible legacy IndexedDB entry was ignored; no file input exists. Telemetry sequence advanced while minimized. The actual installed packaged application was launched without `--no-sandbox`, selected the archive-matching pack, exposed no renderer Node access and reported no page errors. Native CTest (6/6), real-socket integration, desktop map/policy tests, converter and DOM/geometry/routing regressions passed. Pack tests reject tampering, game-version changes, added DLC and missing archives. + +This verifies map packaging/loading and installer identity, not live driving alignment or live semaphore/GPS freshness. The installed MIT provider hash matches the pin. No ETS2 map is locally qualified. Fresh public installations and future game versions still need a prepared matching embedded pack; arbitrary-version automatic extraction is not implemented. Active map mods are not included in the base/DLC content identity. diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 1ae331e..f4b99b0 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -6,6 +6,6 @@ Work on a feature branch and submit a PR. The main ruleset requires linear histo Local release gates: native Release/UBSan tests, exact v4/v5/v6/v7 and HTTP regressions, job journal resume/delivery tests, signal/route provider freshness tests, desktop isolation/background/cache tests, browser layout and report/export checks, pinned Windows DLL build, npm audit, secret scan and archive inspection. Keep fixture, rendered, actual driving and physical-controller evidence distinct. -Build the native binary, Windows DLL and standalone package, then run `ats-dualsense/scripts/package-release.sh`. The archive contains the standalone app, native/source/plugin/installer files, third-party licenses and documentation. Exclude maps, extraction output, local job reports, user config, IDE files, npm caches and signing secrets. Retain SHA-256 checksums. Electron packages disable RunAsNode, NODE_OPTIONS, Node CLI inspection and directory fallback through fuses; Linux ASAR signing/integrity is not claimed. +Build the native binary, Windows DLL and standalone package, then run `ats-dualsense/scripts/package-release.sh`. The archive contains the standalone app, native/source/plugin/installer files, third-party licenses and documentation. The local `--local-maps` desktop build embeds qualified map packs; the public release script strips `standalone/resources/maps` even when packaging that local build. Include the verified MIT provider DLL and its license. Exclude maps, extraction output, local job reports, user config, IDE files, npm caches and signing secrets. Retain SHA-256 checksums. Electron packages disable RunAsNode, NODE_OPTIONS, Node CLI inspection and directory fallback through fuses; Linux ASAR signing/integrity is not claimed. A draft/prerelease can be prepared from the reviewed candidate branch. Publish stable 1.0 only after passing remote gates and recording live v7 delivery/cancellation, actual signal/GPS alignment after restart, a long-haul background/performance run and the remaining device/transport qualification. The release notes must list any surviving limits. Never promote fixture-only traffic or job evidence to a real driving claim. diff --git a/docs/SIGNAL-PROVIDER.md b/docs/SIGNAL-PROVIDER.md index 4556d9e..779e2be 100644 --- a/docs/SIGNAL-PROVIDER.md +++ b/docs/SIGNAL-PROVIDER.md @@ -31,3 +31,7 @@ A read-only native thread samples at 10 Hz, validates file owner/type/exact size `--semaphore-file PATH` selects an alternate fixture/provider file. `--route-file PATH` overrides the separate 96,000-byte route ABI; see [navigator](WEB-NAVIGATOR.md). Both feeds additionally require active non-demo telemetry. The pinned provider and file ABI were verified from first-party source/binary; native fixtures and rendered synthetic provider tests are separate from a real driving session. A successful DLL installation is not proof of live compatibility with every ATS 1.61 patch/mod or TruckersMP. Verify actual `/api/signals` freshness after game restart before treating live integration as qualified. + +## Standalone integration + +The desktop bundle carries the pinned 1.61.x provider and its MIT license. It discovers Steam installations and installs the DLL automatically only after its embedded map verifies the game version/content and names a supported 1.61.x version. Existing different DLLs are backed up; a new installation requires restarting the game. Waiting for telemetry is displayed separately from provider installation. Packaging downloads/checks the immutable DLL at build time; the renderer never downloads code. The standalone does not claim that an installed DLL alone proves a fresh live signal/GPS feed. diff --git a/docs/WEB-NAVIGATOR.md b/docs/WEB-NAVIGATOR.md index ecdc3f5..3ecd297 100644 --- a/docs/WEB-NAVIGATOR.md +++ b/docs/WEB-NAVIGATOR.md @@ -2,13 +2,15 @@ The navigator follows SDK world placement in the X/Z horizontal plane (north is -Z). Heading is a counterclockwise turn fraction: 0 north, .25 west, .5 south, .75 east. Pitch/roll also use turns. Position is double precision on the wire. V6 adds placement; v5/v4 still work with position unavailable. Restart ATS after replacing the DLL. -## Load a local scene +## Embedded game scene -Use **Load road map** in the cockpit and select a game-matching JSON. On this workstation, `build/ats-scene.json` contains the installed ATS 1.61.3.1 map: 47,383 road lines, 289 cities, 50,551 visible prefab instances, 235,305 object instances and 93,891 placed signs. The complete detailed file is approximately 82 MiB. Older v1 centerline maps remain supported. +The standalone loads its matching map from `resources/maps/` automatically, without selecting a file. The local ATS 1.61.3.1 pack contains 47,383 road lines, 289 cities, 50,551 visible prefab instances, 235,305 object instances and 93,891 placed signs (about 24 MiB gzip / 81 MiB JSON). Packs record schema/game version, compressed SHA-256, bounded uncompressed size, SHA-256 of the game's `version.scs` and a signature of installed `.scs` filenames/sizes. Steam libraries are discovered from the standard native/Flatpak Steam library registries. Compatibility is rechecked every five seconds; mismatched version/content disables roads and routing. This identifies the installed base/DLC content, not active mod overrides. Map coverage warnings still apply. -**3D / Perspective** uses an embedded, offline Three.js WebGL renderer. Without WebGL or with a v1 map, a canvas perspective/2D fallback remains available. The default **Chase camera** follows an original generic tractor, with a straight trailer proxy only when SDK coupling is active. **Overview camera** restores the wider navigator; north-up selects overview. Camera preference survives reload. Controls also select zoom, fullscreen and props/signs/details. Mobile places the navigator above instruments. Pause, missing placement and game mismatch hide the scene. Nothing is uploaded. Imported maps persist in IndexedDB and restore after refresh/relaunch; Forget map removes the cached copy. The standalone can bootstrap a local installed `maps/ats.json`. Session-only cyan history remains distinct from the native persisted job route. +The old IndexedDB import is never used by the standalone. Map bytes remain compressed on disk and are decoded on load. The renderer receives only map/status responses, never filesystem paths. The public browser endpoint currently has no embedded-map loader; use the standalone for this feature. A missing pack produces an explicit status, without opening an import dialog. Arbitrary-version extraction is not yet automatic; a maintainer prepares the matching embedded pack. ETS2 packaging supports the same format, but no local ETS2 extraction is qualified. -The scene includes road elevation, extracted lane counts/shoulders, prefab road surfaces and navigation curves, roadside signs with extracted text, semaphore positions, dividers and POIs. Original procedural building/house roofs, vegetation, lamps, bollards and generic prop shapes use measured bounds and map-provided placements. Very large panorama bounds remain low footprint markers to avoid opaque blocks enclosing the street. The current local export provides building model descriptions; vegetation and other model classes render only when included in an imported map. No decorative positions are invented. Road widths use a 3.5-metre lane estimate plus extracted offsets/shoulders, with geometric edge/centre paint and dashed lane dividers. These are schematic marking rules, not decoded road material meshes. Signs use a readable schematic style; atlas names can appear as text. Original game meshes/textures, terrain surfaces and animated traffic are absent. Only live semaphore phases require the optional ETS2LA provider; missing/stale input leaves them unknown. Static signals use dark three-lamp housings; live heads show the provider position/state with a readable camera-facing symbolic orientation. Divider rails are symbolic representations of extracted divider paths. This is a schematic navigator, not a complete replica of the rendered game world. +**3D / Perspective** uses an embedded, offline Three.js WebGL renderer. Without WebGL or with a v1 map, a canvas perspective/2D fallback remains available. The default **Chase camera** follows an original generic tractor, with a straight trailer proxy only when SDK coupling is active. **Overview camera** restores the wider navigator; north-up selects overview. Camera preference survives reload. Controls also select zoom, fullscreen and props/signs/details. Mobile places the navigator above instruments. Pause, missing placement and game mismatch hide the scene. Nothing is uploaded. The embedded map restores directly from app resources on refresh/relaunch. No external map file or IndexedDB copy is required. Session-only cyan history remains distinct from the native persisted job route. + +The scene includes road elevation, extracted lane counts/shoulders, prefab road surfaces and navigation curves, roadside signs with extracted text, semaphore positions, dividers and POIs. Original procedural building/house roofs, vegetation, lamps, bollards and generic prop shapes use measured bounds and map-provided placements. Very large panorama bounds remain low footprint markers to avoid opaque blocks enclosing the street. The current local export provides building model descriptions; vegetation and other model classes render only when included in an imported map. No decorative positions are invented. Road widths use a 3.5-metre lane estimate plus extracted offsets/shoulders, with geometric edge/centre paint and dashed lane dividers. These are schematic marking rules, not decoded road material meshes. Signs use a readable schematic style; atlas names can appear as text. Original game meshes/textures, terrain surfaces and animated traffic are absent. Live semaphore phases use the integrated ETS2LA provider; missing/stale input leaves them unknown. Static signals use dark three-lamp housings; live heads show the provider position/state with a readable camera-facing symbolic orientation. Divider rails are symbolic representations of extracted divider paths. This is a schematic navigator, not a complete replica of the rendered game world. Objects are indexed in 500-metre buckets; roads use bounding boxes. Visible radius is capped at 1,400 metres; object instances at 2,200, placed signs at 180 and nearby sign labels at 24. Prefab templates avoid duplicating intersection geometry in the JSON. Road triangles/curve segments are batched and objects instanced. A floating local origin preserves GPU precision. Static geometry rebuilds on 80-metre camera cells, zoom/layer changes or new data; static scene/route input updates at dashboard cadence while camera/model interpolation renders at most 30 FPS. Hidden views and paused/missing placement stop the animation loop; resuming restarts it. Shortest-angle interpolation handles the heading wrap and large teleports snap immediately. WebGL pixel ratio is capped at 1.5. Repeated overlays share signal primitives; visible sign-text canvases are recycled. Dash generation and divider posts are bounded. Tractor pitch/roll follow telemetry, while generic dimensions, mapped road contact (within 10 metres horizontally and five metres vertically, otherwise a generic chassis offset), straight trailer shape and symbolic lamp facing are approximations. No trailer world pose or exact truck model mesh is claimed. @@ -18,13 +20,13 @@ Orange indicates the future route; cyan is the measured travelled trace (at most **HaulSense route** uses a Web Worker and an A* graph with extracted road directions and prefab navigation connections. Choose a city or use automatic job destination matching. It reroutes after movement and never writes to the game's GPS. It is a mapped, driveable geometric path, not the game's chosen route. It does not account for truck orientation, temporary closures, ferry services, truck restrictions or the game's routing preferences. City endpoints snap to mapped nodes; offsets are not rendered as invented road connections. Disconnected paths return an error. -**Game GPS route · ETS2LA provider** is optional. The daemon reads `/dev/shm/ETS2LARoute` (override with `--route-file PATH`) using the [ETS2LA NavigationProvider ABI](https://github.com/ETS2LA/ETS2LA/blob/main/ETS2LA.Game/SDK/Navigation.cs): 6,000 little-endian records of a 64-bit node UID and two float32 distance/time values, 96,000 bytes. The optional installer can install a pinned upstream 1.61 provider; HaulSense itself does not read game process memory. The pinned provider detects Wine/Proton and creates Linux-accessible shared files. A Windows named mapping alone is insufficient. +**Game GPS route · ETS2LA provider** uses the integrated compatible provider. The daemon reads `/dev/shm/ETS2LARoute` (override with `--route-file PATH`) using the [ETS2LA NavigationProvider ABI](https://github.com/ETS2LA/ETS2LA/blob/main/ETS2LA.Game/SDK/Navigation.cs): 6,000 little-endian records of a 64-bit node UID and two float32 distance/time values, 96,000 bytes. The standalone automatically installs the checksum-pinned upstream 1.61 provider for a verified supported pack; HaulSense itself does not read game process memory. The pinned provider detects Wine/Proton and creates Linux-accessible shared files. A Windows named mapping alone is insufficient. The file is read on a separate native thread, read-only, with owner/type/size checks and two matching reads. Its ABI has no heartbeat: freshness requires an observed content change, expires after 2.5 seconds, and additionally requires live non-demo telemetry. A stationary, unchanged route can therefore be conservatively withheld. Browser polling is at most once per second while active, with automatic destination selected. Every UID and directed connection must match the imported map; otherwise the route is rejected. No straight-line links are invented. HaulSense routing remains available when the provider is absent/stale. Exact-provider integration has fixture coverage; live ATS/Proton provider operation remains unqualified. The SCS SDK alone supplies navigation distance, time and speed limit, not future route geometry. A manually selected GPS destination has no city name in these channels. The city selector remains available for independent navigation. -## Export from your game +## Prepare an embedded pack (maintainers) Use the [TruckSim Maps parser](https://github.com/truckermudgeon/maps) to extract installed ATS/ETS2 archives into a directory, then run: @@ -34,6 +36,8 @@ python3 ats-dualsense/scripts/export-road-map.py /path/to/parser-output /path/to python3 ats-dualsense/scripts/export-road-map.py /path/to/parser-output /path/to/region.json --game ats --bounds -106000 5000 -100000 18000 ``` +The converter retains the parser `usa-version.txt` / `europe-version.txt` as `gameVersion`. Local packaging requires this metadata and a game log for the same version, newer than the installed version archive. Put the result in `build/ats-scene.json` or `build/ets2-scene.json`, then run `npm run --prefix ats-dualsense/desktop package -- --local-maps`. The source desktop installer invokes this packaging mode automatically. Public packaging omits game-derived packs. + The converter reads `usa-*` / `europe-*` arrays: nodes, roads, roadLooks, cities, prefabDescriptions/prefabs, modelDescriptions/models, signDescriptions/signs, dividers and pois. Missing optional datasets are recorded in `coverage`; roads with missing nodes are counted. Hidden/secret roads and prefabs are excluded. Preserve 64-bit UIDs as hexadecimal strings. Elevation comes from the parser's node `z`; its `y` is game world Z. No proprietary game assets or map files are shipped in the repository. The local source is retained in `build/map-source/` and `build/map-extraction.log`. Parser revision `d56d0e3` needed a temporary speed-limit-array assertion workaround for ATS 1.61; speed-limit definitions are not used by this scene. The parser reported an unknown South Dakota archive and other warnings; this is not proof of complete DLC coverage. Re-extract after game/mod changes. ETS2 extraction/alignment has not been qualified on this workstation. diff --git a/tests/browser-procedural.cjs b/tests/browser-procedural.cjs index d88e379..adf38be 100644 --- a/tests/browser-procedural.cjs +++ b/tests/browser-procedural.cjs @@ -8,7 +8,7 @@ const {chromium}=require('playwright'),assert=require('node:assert/strict'); await page.route('**/api/state',async route=>{const s=await(await route.fetch()).json();s.active=active;s.demo=false;s.telemetry={...s.telemetry,game:'ats',world_position:[x,1,z],heading:0,pitch:0,roll:0,trailer_connected:true,destination:''};await route.fulfill({json:s});}); await page.route('**/api/signals',route=>route.fulfill({json:{source:'ets2la',available:true,fresh:active,objects:[{type:1,state,position:[7,0,-48],remaining_s:12,id:1}]}})); await page.goto(process.argv[2]||'http://127.0.0.1:39076');await page.waitForFunction(()=>document.querySelector('#status').textContent!=='Connecting'); - await page.locator('#map-file').setInputFiles({name:'original-demo.json',mimeType:'application/json',buffer:Buffer.from(JSON.stringify(map))}); + await page.evaluate(map=>navigatorView.loadMap(map),map); await page.waitForFunction(()=>navigatorView.stats()?.frame>2&&navigatorView.stats()?.signals.some(s=>s.state===8)); await page.evaluate(()=>{document.querySelector('#status').textContent='DEMO · synthetic road / signal fixtures';}); await page.screenshot({path:'build/procedural-chase-demo.png'});const first=await page.evaluate(()=>navigatorView.stats());assert.equal(first.camera,'chase');assert(first.truck&&first.trailer);assert.equal(first.frameCap,30);assert.equal(first.signals[0].colours[2],0x83efb3); diff --git a/tests/browser-scene.cjs b/tests/browser-scene.cjs index be507ed..53612c9 100644 --- a/tests/browser-scene.cjs +++ b/tests/browser-scene.cjs @@ -3,7 +3,7 @@ const {chromium}=require('playwright'),fs=require('fs'),assert=require('node:ass (async()=>{const browser=await chromium.launch({headless:true,executablePath:process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH||undefined,args:['--enable-unsafe-swiftshader']});const page=await browser.newPage({viewport:{width:1500,height:1000}});const errors=[];page.on('pageerror',e=>errors.push(e.message)); const mapPath=process.argv[2],baseUrl=process.argv[3]||'http://127.0.0.1:39076';if(!mapPath)throw Error('Usage: node tests/browser-scene.cjs scene.json [mock dashboard URL]');const data=JSON.parse(fs.readFileSync(mapPath));const edge=data.graph.edges.find(e=>e[3]&&e[3][0][0]<-104000&&e[3][0][0]>-105000&&e[3][0][1]>6000&&e[3][0][1]<9000);const node=data.graph.nodes[edge[0]],uids=[data.graph.nodes[edge[0]][3],data.graph.nodes[edge[1]][3]];let fresh=true,active=true,game='ats',ids=uids; await page.route('**/api/state',async route=>{let s=await(await route.fetch()).json();s.active=active;s.demo=false;s.telemetry={...s.telemetry,game,world_position:[node[0],node[2]+2,node[1]],heading:.75,destination:'Los Angeles'};await route.fulfill({json:s});}); -await page.route('**/api/route',route=>route.fulfill({json:{source:'ets2la',available:true,fresh,node_uids:ids}}));await page.goto(baseUrl);await page.locator('#map-file').setInputFiles(mapPath);await page.waitForFunction(()=>document.querySelector('#route-status').textContent.includes('Game GPS route'),null,{timeout:60000}); +await page.route('**/api/route',route=>route.fulfill({json:{source:'ets2la',available:true,fresh,node_uids:ids}}));await page.goto(baseUrl);await page.evaluate(map=>navigatorView.loadMap(map),JSON.parse(fs.readFileSync(mapPath,'utf8')));await page.waitForFunction(()=>document.querySelector('#route-status').textContent.includes('Game GPS route'),null,{timeout:60000}); const perf=await page.evaluate(()=>{const durations=[];for(let i=0;i<10;i++){const start=performance.now();navigatorView.draw();durations.push(performance.now()-start);}return {durations,stats:navigatorView.stats()};});console.log('Render performance',perf);fs.writeFileSync('build/scene-render-metrics.json',JSON.stringify(perf)); active=false;await page.waitForFunction(()=>document.querySelector('#road-scene').hidden);active=true;fresh=false;await page.waitForFunction(()=>document.querySelector('#route-status').textContent.includes('calculated on mapped roads')); ids=['ffffffffffffffff','fffffffffffe'];fresh=true;await page.waitForFunction(()=>document.querySelector('#gps-status').textContent.includes('do not match'));await page.waitForFunction(()=>document.querySelector('#route-status').textContent.includes('calculated on mapped roads')); diff --git a/tests/desktop.cjs b/tests/desktop.cjs index a5ba14e..775e161 100644 --- a/tests/desktop.cjs +++ b/tests/desktop.cjs @@ -3,7 +3,7 @@ const {_electron:electron}=require('playwright'),assert=require('node:assert/str (async()=>{const profile='/tmp/haulsense-desktop-review-'+Date.now();fs.mkdirSync(profile);const app=await electron.launch({executablePath:process.cwd()+'/ats-dualsense/desktop/node_modules/electron/dist/electron',args:[process.cwd()+'/ats-dualsense/desktop','--demo'],env:{...process.env,HAULSENSE_TEST_PROFILE:profile},timeout:30000});const page=await app.firstWindow();const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.waitForFunction(()=>document.querySelector('#status')?.textContent.includes('DEMO')); console.log('desktop',await page.title(),await page.url());console.log(await app.evaluate(({BrowserWindow})=>{const w=BrowserWindow.getAllWindows()[0];return {sandbox:w.webContents.getLastWebPreferences().sandbox,node:w.webContents.getLastWebPreferences().nodeIntegration,throttle:w.webContents.backgroundThrottling};})); console.log('prefs',await page.evaluate(()=>({node:typeof require,location:location.protocol,visibility:document.visibilityState}))); -await page.locator('#map-file').setInputFiles(process.argv[2]||'build/ats-scene.json');await page.waitForFunction(()=>document.querySelector('#map-storage').textContent.includes('Saved on'),null,{timeout:60000});await page.waitForTimeout(500);await page.screenshot({path:'build/standalone-desktop-demo.png'});const before=await page.evaluate(()=>state.sequence); +assert.equal(await page.locator('input[type=file]').count(),0);await page.waitForFunction(()=>document.querySelector('#map-storage').dataset.mapReady==='true',null,{timeout:60000});await page.waitForTimeout(500);await page.screenshot({path:'build/standalone-desktop-demo.png'});const before=await page.evaluate(()=>state.sequence); await app.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows()[0].minimize());await new Promise(r=>setTimeout(r,1500));const after=await page.evaluate(()=>state.sequence);assert(after>before);console.log('minimized sequence advanced',before,after); -await app.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows()[0].restore());await page.reload();await page.waitForFunction(()=>document.querySelector('#map-storage').textContent.includes('Restored automatically'),null,{timeout:60000});assert(await page.locator('#map-unload').isVisible());console.log('map restored after reload'); -await page.locator('#tab-jobs').click();await page.waitForTimeout(300);await page.screenshot({path:'build/standalone-job-empty.png'});console.log('errors',errors);assert.equal(errors.length,0);await app.close();const reopened=await electron.launch({executablePath:process.cwd()+'/ats-dualsense/desktop/node_modules/electron/dist/electron',args:[process.cwd()+'/ats-dualsense/desktop','--demo'],env:{...process.env,HAULSENSE_TEST_PROFILE:profile},timeout:30000});const restored=await reopened.firstWindow();await restored.waitForFunction(()=>document.querySelector('#map-storage').textContent.includes('Restored automatically'),null,{timeout:60000});console.log('map restored after full app restart');await reopened.close();})(); +await app.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows()[0].restore());await page.evaluate(()=>window.HaulSenseStorage.saveMap(new Blob([JSON.stringify({version:1,game:'ets2',coordinates:'scs-xz-metres',roads:[]})]),'obsolete-cache.json'));await page.reload();await page.waitForFunction(()=>document.querySelector('#map-storage').dataset.mapReady==='true',null,{timeout:60000});assert.equal(await page.locator('#map-unload').count(),0);assert(await page.locator('#route-destination option').count()>200);console.log('embedded map restored; incompatible legacy cache ignored'); +await page.locator('#tab-jobs').click();await page.waitForTimeout(300);await page.screenshot({path:'build/standalone-job-empty.png'});console.log('errors',errors);assert.equal(errors.length,0);await app.close();const reopened=await electron.launch({executablePath:process.cwd()+'/ats-dualsense/desktop/node_modules/electron/dist/electron',args:[process.cwd()+'/ats-dualsense/desktop','--demo'],env:{...process.env,HAULSENSE_TEST_PROFILE:profile},timeout:30000});const restored=await reopened.firstWindow();await restored.waitForFunction(()=>document.querySelector('#map-storage').dataset.mapReady==='true',null,{timeout:60000});console.log('map restored after full app restart');await reopened.close();})(); From 198688ba426e7e29808cfdb505f75a9a51c62fa4 Mon Sep 17 00:00:00 2001 From: Flavio Giacchetti Date: Wed, 7 Oct 2026 15:57:38 +0200 Subject: [PATCH 2/3] fix: read map resources through bounded no-follow file handles --- ats-dualsense/desktop/embed-maps.cjs | 6 +++--- ats-dualsense/desktop/maps.cjs | 8 ++++++-- ats-dualsense/desktop/package.cjs | 2 +- ats-dualsense/desktop/test/maps.test.cjs | 1 + ats-dualsense/scripts/download-signal-provider.sh | 13 +++++++++++++ tests/browser-procedural.cjs | 4 ++-- 6 files changed, 26 insertions(+), 8 deletions(-) create mode 100755 ats-dualsense/scripts/download-signal-provider.sh diff --git a/ats-dualsense/desktop/embed-maps.cjs b/ats-dualsense/desktop/embed-maps.cjs index b7cf73f..f455e6e 100644 --- a/ats-dualsense/desktop/embed-maps.cjs +++ b/ats-dualsense/desktop/embed-maps.cjs @@ -1,7 +1,7 @@ 'use strict'; // Local game-derived packs stay in build/resources, outside source and public archives. const fs=require('node:fs/promises'),path=require('node:path'),zlib=require('node:zlib'); -const {libraries,identify,digest,regular}=require('./maps.cjs'); +const {libraries,identify,digest,regular,readResource}=require('./maps.cjs'); async function embed(target,home){ const root=path.resolve(__dirname,'../..'),packs=[]; for(const game of ['ats','ets2']){ @@ -11,8 +11,8 @@ async function embed(target,home){ if(!directory)throw Error('Cannot verify the game installation for '+game); // Check extracted version against the current game's log before binding archive identity. const id=game==='ats'?'270880':'227300';const steamapps=path.dirname(path.dirname(directory));const log=path.join(steamapps,'compatdata',id,'pfx','drive_c','users','steamuser','Documents',path.basename(directory),'game.log.txt'); - const versionStat=await fs.stat(path.join(directory,'version.scs')),logStat=await fs.stat(log);if(versionStat.mtimeMs>logStat.mtimeMs)throw Error('Run the updated game once before embedding its map'); - const text=await fs.readFile(log,'utf8');const match=text.match(/Loaded pack set version (\d+\.\d+\.\d+\.\d+)/);if(match?.[1]!==map.gameVersion)throw Error('Extracted map does not match the installed game log'); + const versionResource=await readResource(path.join(directory,'version.scs'),1024*1024),logResource=await readResource(log,16*1024*1024);if(versionResource.stat.mtimeMs>logResource.stat.mtimeMs)throw Error('Run the updated game once before embedding its map'); + const text=logResource.data.toString('utf8');const match=text.match(/Loaded pack set version (\d+\.\d+\.\d+\.\d+)/);if(match?.[1]!==map.gameVersion)throw Error('Extracted map does not match the installed game log'); const identity=await identify(directory),data=Buffer.from(JSON.stringify(map)),compressed=zlib.gzipSync(data,{level:9}),file=game+'-'+map.gameVersion+'.json.gz'; await fs.mkdir(path.join(target,'maps'),{recursive:true});await fs.writeFile(path.join(target,'maps',file),compressed); packs.push({game,gameVersion:map.gameVersion,file,bytes:data.length,sha256:digest(compressed),...identity}); diff --git a/ats-dualsense/desktop/maps.cjs b/ats-dualsense/desktop/maps.cjs index ee999be..6db7176 100644 --- a/ats-dualsense/desktop/maps.cjs +++ b/ats-dualsense/desktop/maps.cjs @@ -4,7 +4,11 @@ const fs=require('node:fs/promises'),path=require('node:path'),crypto=require('n const GAMES={ats:{id:'270880',directory:'American Truck Simulator'},ets2:{id:'227300',directory:'Euro Truck Simulator 2'}}; const MAX=96*1024*1024; const digest=data=>crypto.createHash('sha256').update(data).digest('hex'); -async function regular(file,max=MAX){const s=await fs.lstat(file);if(!s.isFile()||s.size>max)throw Error('Invalid application resource');return fs.readFile(file);} +async function readResource(file,max=MAX){ + const handle=await fs.open(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW); + try{const stat=await handle.stat();if(!stat.isFile()||stat.size>max)throw Error('Invalid application resource');const data=Buffer.alloc(stat.size);let offset=0;while(offset{ const provider=path.resolve(__dirname,'../../build/ets2la-provider/ets2la_plugin.dll'); const expected='0e1893719f84f28079857451b82a22a263401d98b8fc299cd561eb7695bfa88f';let providerBytes; - try{providerBytes=await fs.readFile(provider);}catch(error){if(error.code!=='ENOENT')throw error;const response=await fetch('https://raw.githubusercontent.com/ETS2LA/ETS2LA/41945bc41e36191fbdf277c7fa6f7dd6f101d679/Assets/SDKs/1.61/Windows/ets2la_plugin.dll',{signal:AbortSignal.timeout(90000)});if(!response.ok||Number(response.headers.get('content-length'))>1024*1024)throw Error('Provider download failed');providerBytes=Buffer.from(await response.arrayBuffer());} + try{providerBytes=await require('./maps.cjs').regular(provider,1024*1024);}catch(error){if(error.code!=='ENOENT')throw error;await require('node:util').promisify(require('node:child_process').execFile)('bash',[path.resolve(__dirname,'../scripts/download-signal-provider.sh')],{timeout:100000});providerBytes=await require('./maps.cjs').regular(provider,1024*1024);} if(providerBytes.length>1024*1024||require('./maps.cjs').digest(providerBytes)!==expected)throw Error('Provider checksum mismatch'); const {packager}=await import('@electron/packager'); const output=path.resolve(__dirname,'../../build/desktop'); diff --git a/ats-dualsense/desktop/test/maps.test.cjs b/ats-dualsense/desktop/test/maps.test.cjs index 0245490..8bad3ac 100644 --- a/ats-dualsense/desktop/test/maps.test.cjs +++ b/ats-dualsense/desktop/test/maps.test.cjs @@ -11,6 +11,7 @@ test('embedded map selects the installed game and refuses updated or missing arc await fs.writeFile(path.join(resources,'maps',file),gz);await fs.writeFile(path.join(resources,'maps','manifest.json'),JSON.stringify({format:1,packs:[pack]}));const maps=new EmbeddedMaps(resources,home);await maps.init(); assert.equal((await maps.status('ats')).state.ready,true);assert.deepEqual(await maps.read('ats'),data);assert.equal((await maps.status('ets2')).state.ready,false); await fs.writeFile(path.join(resources,'maps',file),'tampered');await assert.rejects(maps.read('ats'),/checksum/);await fs.writeFile(path.join(resources,'maps',file),gz); + await fs.rename(path.join(resources,'maps',file),path.join(resources,'maps','real.gz'));await fs.symlink('real.gz',path.join(resources,'maps',file));await assert.rejects(maps.read('ats'),{code:'ELOOP'});await fs.unlink(path.join(resources,'maps',file));await fs.rename(path.join(resources,'maps','real.gz'),path.join(resources,'maps',file)); await fs.writeFile(path.join(game,'version.scs'),'1.62');assert.equal((await maps.status('ats')).state.reason,'version-mismatch');await assert.rejects(maps.read('ats'),/changed/); await fs.writeFile(path.join(game,'version.scs'),'1.61');await fs.writeFile(path.join(game,'dlc_new.scs'),'new DLC');assert.equal((await maps.status('ats')).state.reason,'version-mismatch'); await fs.unlink(path.join(game,'dlc_new.scs'));await fs.unlink(path.join(game,'base_map.scs'));assert.equal((await maps.status('ats')).state.ready,false); diff --git a/ats-dualsense/scripts/download-signal-provider.sh b/ats-dualsense/scripts/download-signal-provider.sh new file mode 100755 index 0000000..21c18ee --- /dev/null +++ b/ats-dualsense/scripts/download-signal-provider.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Build dependency only: immutable upstream MIT binary, verified before publication. +set -euo pipefail +root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd) +target="$root/build/ets2la-provider" +mkdir -p -- "$target" +staged=$(mktemp "$target/.provider.XXXXXX") +trap 'rm -f -- "$staged"' EXIT +curl --fail --location --proto '=https' --tlsv1.2 --max-time 90 'https://raw.githubusercontent.com/ETS2LA/ETS2LA/41945bc41e36191fbdf277c7fa6f7dd6f101d679/Assets/SDKs/1.61/Windows/ets2la_plugin.dll' --output "$staged" +actual=$(sha256sum -- "$staged");actual=${actual%% *} +[[ "$actual" == '0e1893719f84f28079857451b82a22a263401d98b8fc299cd561eb7695bfa88f' ]] || { echo 'Provider checksum mismatch' >&2; exit 1; } +chmod 644 "$staged" +mv -- "$staged" "$target/ets2la_plugin.dll" diff --git a/tests/browser-procedural.cjs b/tests/browser-procedural.cjs index adf38be..266915d 100644 --- a/tests/browser-procedural.cjs +++ b/tests/browser-procedural.cjs @@ -11,9 +11,9 @@ const {chromium}=require('playwright'),assert=require('node:assert/strict'); await page.evaluate(map=>navigatorView.loadMap(map),map); await page.waitForFunction(()=>navigatorView.stats()?.frame>2&&navigatorView.stats()?.signals.some(s=>s.state===8)); await page.evaluate(()=>{document.querySelector('#status').textContent='DEMO · synthetic road / signal fixtures';}); - await page.screenshot({path:'build/procedural-chase-demo.png'});const first=await page.evaluate(()=>navigatorView.stats());assert.equal(first.camera,'chase');assert(first.truck&&first.trailer);assert.equal(first.frameCap,30);assert.equal(first.signals[0].colours[2],0x83efb3); + await page.screenshot({path:'build/procedural-chase-demo.png'});const first=await(await page.waitForFunction(()=>{const s=navigatorView.stats();return s?.signals.some(l=>l.state===8&&l.colours[2]===0x83efb3)?s:false;})).jsonValue();assert.equal(first.camera,'chase');assert(first.truck&&first.trailer);assert.equal(first.frameCap,30);assert.equal(first.signals[0].colours[2],0x83efb3); x=2;z=-10;await page.waitForTimeout(600);await page.locator('#map-camera').click();await page.waitForFunction(()=>navigatorView.stats()?.camera==='overview');await page.screenshot({path:'build/procedural-overview-demo.png'}); - await page.reload();await page.waitForFunction(()=>navigatorView.stats()?.camera==='overview');await page.locator('#map-camera').click();await page.waitForFunction(()=>navigatorView.stats()?.camera==='chase'); + await page.reload();await page.evaluate(map=>navigatorView.loadMap(map),map);await page.waitForFunction(()=>navigatorView.stats()?.camera==='overview');await page.locator('#map-camera').click();await page.waitForFunction(()=>navigatorView.stats()?.camera==='chase'); const memories=[];for(let i=0;i<12;i++){state=i%2?2:8;await page.waitForFunction(expected=>navigatorView.stats()?.signals.some(s=>s.state===expected),state);memories.push(await page.evaluate(()=>navigatorView.stats()));} assert(Math.max(...memories.map(s=>s.geometries))<=first.geometries+5);assert(Math.max(...memories.map(s=>s.textures))<=first.textures+2); active=false;await page.waitForFunction(()=>document.querySelector('#road-scene').hidden);const paused=await page.evaluate(()=>navigatorView.stats().frame);await page.waitForTimeout(300);assert.equal(await page.evaluate(()=>navigatorView.stats().frame),paused); From 108089e8c9f4fb57dc36fcf759f8a455ec247e30 Mon Sep 17 00:00:00 2001 From: Flavio Giacchetti Date: Wed, 7 Oct 2026 16:01:03 +0200 Subject: [PATCH 3/3] test: stream full scene fixtures without browser-driver serialization --- tests/browser-scene.cjs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/tests/browser-scene.cjs b/tests/browser-scene.cjs index 53612c9..a7fe884 100644 --- a/tests/browser-scene.cjs +++ b/tests/browser-scene.cjs @@ -1,12 +1,13 @@ // Optional real-browser check against a detailed ATS map and an isolated mock daemon. -const {chromium}=require('playwright'),fs=require('fs'),assert=require('node:assert/strict'); +const {chromium}=require('playwright'),fs=require('fs'),http=require('node:http'),assert=require('node:assert/strict'); (async()=>{const browser=await chromium.launch({headless:true,executablePath:process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH||undefined,args:['--enable-unsafe-swiftshader']});const page=await browser.newPage({viewport:{width:1500,height:1000}});const errors=[];page.on('pageerror',e=>errors.push(e.message)); -const mapPath=process.argv[2],baseUrl=process.argv[3]||'http://127.0.0.1:39076';if(!mapPath)throw Error('Usage: node tests/browser-scene.cjs scene.json [mock dashboard URL]');const data=JSON.parse(fs.readFileSync(mapPath));const edge=data.graph.edges.find(e=>e[3]&&e[3][0][0]<-104000&&e[3][0][0]>-105000&&e[3][0][1]>6000&&e[3][0][1]<9000);const node=data.graph.nodes[edge[0]],uids=[data.graph.nodes[edge[0]][3],data.graph.nodes[edge[1]][3]];let fresh=true,active=true,game='ats',ids=uids; +const mapPath=process.argv[2],baseUrl=process.argv[3]||'http://127.0.0.1:39076';if(!mapPath)throw Error('Usage: node tests/browser-scene.cjs scene.json [mock dashboard URL]');const upstream=new URL(baseUrl);const fixture=http.createServer((request,response)=>{if(request.method!=='GET'||!request.url.startsWith('/')){response.writeHead(404).end();return;}if(request.url==='/__scene-test-map.json'){response.setHeader('Content-Type','application/json');fs.createReadStream(mapPath).pipe(response);return;}const forwarded=http.request({hostname:upstream.hostname,port:upstream.port,path:request.url,headers:{host:upstream.host}},remote=>{response.writeHead(remote.statusCode,remote.headers);remote.pipe(response);});forwarded.on('error',()=>response.writeHead(503).end());forwarded.end();});await new Promise(resolve=>fixture.listen(0,'127.0.0.1',resolve)); +const data=JSON.parse(fs.readFileSync(mapPath));const edge=data.graph.edges.find(e=>e[3]&&e[3][0][0]<-104000&&e[3][0][0]>-105000&&e[3][0][1]>6000&&e[3][0][1]<9000);const node=data.graph.nodes[edge[0]],uids=[data.graph.nodes[edge[0]][3],data.graph.nodes[edge[1]][3]];let fresh=true,active=true,game='ats',ids=uids; await page.route('**/api/state',async route=>{let s=await(await route.fetch()).json();s.active=active;s.demo=false;s.telemetry={...s.telemetry,game,world_position:[node[0],node[2]+2,node[1]],heading:.75,destination:'Los Angeles'};await route.fulfill({json:s});}); -await page.route('**/api/route',route=>route.fulfill({json:{source:'ets2la',available:true,fresh,node_uids:ids}}));await page.goto(baseUrl);await page.evaluate(map=>navigatorView.loadMap(map),JSON.parse(fs.readFileSync(mapPath,'utf8')));await page.waitForFunction(()=>document.querySelector('#route-status').textContent.includes('Game GPS route'),null,{timeout:60000}); +await page.route('**/api/route',route=>route.fulfill({json:{source:'ets2la',available:true,fresh,node_uids:ids}}));await page.goto('http://127.0.0.1:'+fixture.address().port);await page.evaluate(async()=>navigatorView.loadMap(await(await fetch('/__scene-test-map.json')).json()));await page.waitForFunction(()=>document.querySelector('#route-status').textContent.includes('Game GPS route'),null,{timeout:60000}); const perf=await page.evaluate(()=>{const durations=[];for(let i=0;i<10;i++){const start=performance.now();navigatorView.draw();durations.push(performance.now()-start);}return {durations,stats:navigatorView.stats()};});console.log('Render performance',perf);fs.writeFileSync('build/scene-render-metrics.json',JSON.stringify(perf)); active=false;await page.waitForFunction(()=>document.querySelector('#road-scene').hidden);active=true;fresh=false;await page.waitForFunction(()=>document.querySelector('#route-status').textContent.includes('calculated on mapped roads')); ids=['ffffffffffffffff','fffffffffffe'];fresh=true;await page.waitForFunction(()=>document.querySelector('#gps-status').textContent.includes('do not match'));await page.waitForFunction(()=>document.querySelector('#route-status').textContent.includes('calculated on mapped roads')); game='ets2';await page.waitForFunction(()=>document.querySelector('#road-scene').hidden);game='ats';await page.waitForFunction(()=>!document.querySelector('#road-scene').hidden); await page.evaluate(()=>document.querySelector('#road-scene').getContext('webgl2').getExtension('WEBGL_lose_context').loseContext());await page.waitForFunction(()=>document.querySelector('#scene-status').textContent.includes('WebGL unavailable'));assert(await page.locator('#road-scene').isHidden()); -console.log('GPS source, expiry, UID mismatch, pause, game mismatch and lost-context fallback passed',errors);assert.equal(errors.length,0);await browser.close();})(); +console.log('GPS source, expiry, UID mismatch, pause, game mismatch and lost-context fallback passed',errors);assert.equal(errors.length,0);await browser.close();await new Promise(resolve=>fixture.close(resolve));})();