commit e377873a855d05be7e595bc092658fa1ca07aad8 Author: Michi Date: Fri Nov 13 00:38:47 2026 +0100 main init diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..fc8d48d --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,18 @@ +{ + "permissions": { + "allow": [ + "Edit(~/.claude/skills/neues-projekt/**)", + "PowerShell($sp='C:\\\\Users\\\\michi\\\\AppData\\\\Local\\\\Temp\\\\claude\\\\b5680fa1048cb998\\\\9fcb3de5-987d-4281-9ac7-7dba61480c94\\\\scratchpad'; Set-Location \"$sp\\\\Tpl Web\"; '{ \"page\": \"game/index.html\", \"size\": \"1280x800\", \"out\": \"shots\", \"shots\": [ { \"name\": \"menu\", \"wait\": 600 } ] }' | Set-Content -Encoding utf8 shots.json; node D:\\\\Oculusquest\\\\Projekt\\\\_Tools\\\\Itch\\\\itch_screens.mjs shots.json | Select-Object -Last 1)", + "PowerShell(foreach\\($p in 'Endless Battlelines','Byte Path','DesktopAnt','SmashFace'\\){ node D:\\\\Oculusquest\\\\Projekt\\\\_Tools\\\\Library\\\\tools\\\\project-check.mjs \"D:\\\\Oculusquest\\\\Projekt\\\\$p\" | Select-String -Pattern '^#|ComfyUI|^- \\(kein|Generator|Grafik|keine|\\\\d+× Synth|Story\\)' | % Line; '' })", + "PowerShell(foreach\\($p in 'Byte Path','DesktopAnt','Pipefix'\\){ node D:\\\\Oculusquest\\\\Projekt\\\\_Tools\\\\Library\\\\tools\\\\project-check.mjs \"D:\\\\Oculusquest\\\\Projekt\\\\$p\" | Select-String -Pattern '^#|ComfyUI|^- \\(kein|Generator|Grafik|keine|\\\\d+× Synth|Story|sprite\\)|Generator-Kopie' | % Line; '' })", + "Edit(~/.claude/skills/projekt-check/**)", + "PowerShell($g='D:\\\\Oculusquest\\\\Projekt\\\\_Tools\\\\ComfyGen'; foreach\\($f in 'generate_audio.py','generate_video.py','generate_voice.py','generate_variants.py'\\){ \"== $f\"; Get-Content \"$g\\\\$f\" -TotalCount 25 | Select-String -Pattern 'workflow|model|ckpt|safetensors|Usage|usage|python|\"\"\"' | select -First 8 | % { $_.Line.Trim\\(\\) } }; \"== README Modelle\"; Select-String -Path \"$g\\\\README.md\" -Pattern 'Modell|model|Workflow|workflow' | select -First 25 | % { $_.Line.Trim\\(\\).Substring\\(0,[Math]::Min\\(170,$_.Line.Trim\\(\\).Length\\)\\) }; try { $s = Invoke-RestMethod http://127.0.0.1:8188/system_stats -TimeoutSec 2; \"== system\"; $s.system.comfyui_version; $s.devices | % { \"$\\($_.name\\) VRAM $\\([math]::Round\\($_.vram_total/1GB,1\\)\\) GB\" } } catch { 'server aus' })", + "PowerShell(py -3.12 $c)", + "PowerShell(py -3.12 $c 'D:\\\\Oculusquest\\\\Projekt\\\\_Tools\\\\ComfyGen\\\\workflows\\\\Text to Image - Flux Klein.json')", + "PowerShell(py -3.12 $c 'D:\\\\Oculusquest\\\\Projekt\\\\_Tools\\\\ComfyGen\\\\workflows\\\\3d modell.json')", + "PowerShell(py -3.12 $c --log 20)", + "PowerShell($c='D:\\\\Oculusquest\\\\Projekt\\\\_Tools\\\\ComfyGen\\\\comfy_check.py'; py -3.12 $c | Select-Object -First 1; $sp='C:\\\\Users\\\\michi\\\\AppData\\\\Local\\\\Temp\\\\claude\\\\b5680fa1048cb998\\\\9fcb3de5-987d-4281-9ac7-7dba61480c94\\\\scratchpad'; $t = Get-Content 'D:\\\\Oculusquest\\\\Projekt\\\\_Tools\\\\ComfyGen\\\\workflows\\\\Text to Image - Flux Klein.json' -Raw; $t = $t.Replace\\('{{UNET}}','flux-dev-gibtsnicht.safetensors'\\).Replace\\('\"KSamplerSelect\"','\"KSamplerSelectX\"'\\).Replace\\('[\"11\", 0]','[\"99\", 0]'\\); [IO.File]::WriteAllText\\(\"$sp\\\\broken.json\", $t\\); py -3.12 $c \"$sp\\\\broken.json\"; Remove-Item \"$sp\\\\broken.json\")", + "Edit(~/.claude/skills/comfyui-workflow-expert/**)" + ] + } +} diff --git a/Backup/backup-config.json b/Backup/backup-config.json new file mode 100644 index 0000000..6da7b8e --- /dev/null +++ b/Backup/backup-config.json @@ -0,0 +1,25 @@ +{ + "source": "D:\\Oculusquest\\Projekt", + "target": "\\\\MYCLOUD-NESYFV\\Michael\\Projekte", + "targets": [ + { + "id": "q2jr36mi", + "name": "MYCLOUD-NESYFV", + "path": "\\\\MYCLOUD-NESYFV\\Michael\\Projekte" + } + ], + "excludeDirs": [ + "node_modules", + "__pycache__", + ".gradle", + ".venv", + "venv", + ".venv-tts", + ".bin" + ], + "excludeFiles": [ + "Thumbs.db", + "desktop.ini", + "~$*" + ] +} diff --git a/Backup/backup-projekte.bat b/Backup/backup-projekte.bat new file mode 100644 index 0000000..9716e05 --- /dev/null +++ b/Backup/backup-projekte.bat @@ -0,0 +1,27 @@ +@echo off +rem ============================================================================ +rem Backup D:\Oculusquest\Projekt -> \\MYCLOUD-NESYFV\Michael\Projekte +rem +rem 1. prueft, was neu/geaendert ist und im Backup fehlt (Anzahl, Groesse, pro Projekt) +rem 2. fragt nach und kopiert genau das +rem +rem Im Backup wird NIE etwas geloescht. Dateien, die es hier nicht mehr gibt, +rem werden nur angezeigt und bleiben im Backup erhalten. +rem +rem Nicht gesichert (wird neu erzeugt): node_modules, __pycache__, .gradle, .venv, venv, .venv-tts +rem +rem Aufruf: +rem backup-projekte.bat pruefen, nachfragen, kopieren +rem backup-projekte.bat test nur pruefen +rem backup-projekte.bat auto pruefen + kopieren ohne Nachfrage (Aufgabenplanung) +rem +rem Logik: backup-projekte.ps1 · Protokolle: logs\pruefung-*.log, logs\backup-*.log +rem ============================================================================ +setlocal enabledelayedexpansion +set "ARGS=" +for %%a in (%*) do ( + if /i "%%~a"=="test" set "ARGS=!ARGS! -Test" + if /i "%%~a"=="auto" set "ARGS=!ARGS! -Auto" +) +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0backup-projekte.ps1" !ARGS! +exit /b %ERRORLEVEL% diff --git a/Backup/backup-projekte.ps1 b/Backup/backup-projekte.ps1 new file mode 100644 index 0000000..f10c7c5 --- /dev/null +++ b/Backup/backup-projekte.ps1 @@ -0,0 +1,132 @@ +<# +.SYNOPSIS + Backup D:\Oculusquest\Projekt -> \\MYCLOUD-NESYFV\Michael\Projekte, in two steps: + 1. check: which files are new/changed (missing or outdated in the backup) + 2. copy exactly those (after asking, unless -Auto) + + Nothing is ever deleted in the backup. Files that exist only in the backup + (deleted or renamed locally) are listed and kept. + + Not backed up (regenerable): node_modules, __pycache__, .gradle, .venv, venv, .venv-tts + +.EXAMPLE + .\backup-projekte.ps1 check, ask, copy + .\backup-projekte.ps1 -Test only check + .\backup-projekte.ps1 -Auto check and copy without asking (task scheduler) +#> +param( + [string]$Source, + [string]$Target, + [switch]$Test, + [switch]$Auto +) +$ErrorActionPreference = 'Stop' + +# Same settings as the backup in the project dashboard: backup-config.json +$cfg = Get-Content (Join-Path $PSScriptRoot 'backup-config.json') -Raw -Encoding UTF8 | ConvertFrom-Json +if (-not $Source) { $Source = $cfg.source } +if (-not $Target) { $Target = $cfg.target } +$logDir = Join-Path $PSScriptRoot 'logs' +New-Item -ItemType Directory -Force $logDir | Out-Null +$stamp = Get-Date -Format 'yyyy-MM-dd_HH-mm' +$checkLog = Join-Path $logDir "pruefung-$stamp.log" +$copyLog = Join-Path $logDir "backup-$stamp.log" + +$common = @('/E', '/FFT', '/XJ', '/R:2', '/W:5', '/COPY:DAT', '/DCOPY:T', '/XD') + @($cfg.excludeDirs) + @('/XF') + @($cfg.excludeFiles) +# /FFT: NAS timestamps have 2 s precision - without it every file would look changed + +function Format-Size([double]$b) { + if ($b -ge 1GB) { return ('{0:N1} GB' -f ($b / 1GB)) } + if ($b -ge 1MB) { return ('{0:N0} MB' -f ($b / 1MB)) } + return ('{0:N0} KB' -f ($b / 1KB)) +} + +function Stop-Here([int]$code) { + if (-not $Auto) { Write-Host ''; Read-Host 'Enter zum Schliessen' | Out-Null } + exit $code +} + +Write-Host '' +Write-Host " Backup: $Source" -ForegroundColor Cyan +Write-Host " nach: $Target" -ForegroundColor Cyan +Write-Host '' + +if (-not (Test-Path -LiteralPath $Source)) { Write-Host " FEHLER: Quelle $Source fehlt." -ForegroundColor Red; Stop-Here 1 } +if (-not (Test-Path -LiteralPath $Target)) { + $share = Split-Path $Target -Parent + if (-not (Test-Path -LiteralPath $share)) { + Write-Host " FEHLER: MyCloud nicht erreichbar ($share). Eingeschaltet und im Netzwerk?" -ForegroundColor Red + Stop-Here 1 + } + New-Item -ItemType Directory $Target | Out-Null +} + +# ── 1. check ─────────────────────────────────────────────────────────────── +Write-Host ' 1/2 Pruefe, was neu ist und im Backup fehlt ...' -ForegroundColor Yellow +# /L = list only, /X = also report files that exist only in the backup +& robocopy $Source $Target @common /L /X /NJH /NJS /NDL /NP /FP /BYTES /UNILOG:$checkLog | Out-Null +if ($LASTEXITCODE -ge 8) { Write-Host " FEHLER bei der Pruefung (robocopy $LASTEXITCODE). Details: $checkLog" -ForegroundColor Red; Stop-Here 1 } + +$copy = New-Object System.Collections.Generic.List[object] +$extra = New-Object System.Collections.Generic.List[object] +foreach ($line in [IO.File]::ReadAllLines($checkLog)) { + $parts = $line.Split("`t") | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' } + if ($parts.Count -lt 3) { continue } + $path = $parts[-1]; $size = 0 + if (-not [int64]::TryParse($parts[-2], [ref]$size)) { continue } + $isExtra = $parts[0] -like '*EXTRA*' + $base = if ($isExtra) { $Target } else { $Source } + if (-not $path.StartsWith($base, [StringComparison]::OrdinalIgnoreCase)) { continue } + $rel = $path.Substring($base.Length).TrimStart('\') + # robocopy's class column: "Neue Datei"/"New File" = missing in the backup, otherwise newer/changed + $item = [pscustomobject]@{ Project = ($rel -split '\\')[0]; Rel = $rel; Size = $size; New = $parts[0] -match '^(Neue Datei|New File)$' } + if ($isExtra) { $extra.Add($item) } else { $copy.Add($item) } +} + +$newFiles = @($copy | Where-Object New) +$changed = @($copy | Where-Object { -not $_.New }) +$total = ($copy | Measure-Object Size -Sum).Sum + +Write-Host '' +if ($copy.Count -eq 0) { + Write-Host ' Alles aktuell - im Backup fehlt nichts.' -ForegroundColor Green +} else { + Write-Host (" Zu kopieren: {0:N0} Dateien, {1}" -f $copy.Count, (Format-Size $total)) -ForegroundColor White + Write-Host (" neu (fehlen im Backup): {0,8:N0} {1}" -f $newFiles.Count, (Format-Size (($newFiles | Measure-Object Size -Sum).Sum))) + Write-Host (" geaendert: {0,8:N0} {1}" -f $changed.Count, (Format-Size (($changed | Measure-Object Size -Sum).Sum))) + Write-Host '' + Write-Host ' Nach Projekt:' + $copy | Group-Object Project | ForEach-Object { + [pscustomobject]@{ Name = $_.Name; Files = $_.Count; Bytes = ($_.Group | Measure-Object Size -Sum).Sum } + } | Sort-Object Bytes -Descending | Select-Object -First 15 | ForEach-Object { + Write-Host (" {0,-28} {1,8:N0} Dateien {2,10}" -f $_.Name, $_.Files, (Format-Size $_.Bytes)) + } +} +if ($extra.Count) { + Write-Host '' + Write-Host (" Nur noch im Backup (hier geloescht/umbenannt): {0:N0} Dateien, {1} - bleiben erhalten." -f $extra.Count, (Format-Size (($extra | Measure-Object Size -Sum).Sum))) -ForegroundColor DarkGray +} +Write-Host '' +Write-Host " Vollstaendige Liste: $checkLog" -ForegroundColor DarkGray + +if ($copy.Count -eq 0) { Stop-Here 0 } +if ($Test) { Write-Host ''; Write-Host ' Testlauf - es wurde nichts kopiert.' -ForegroundColor Yellow; Stop-Here 0 } + +if (-not $Auto) { + Write-Host '' + $answer = Read-Host ' Jetzt kopieren? (J/N)' + if ($answer -notmatch '^(j|ja|y|yes)$') { Write-Host ' Abgebrochen, nichts kopiert.'; Stop-Here 0 } +} + +# ── 2. copy ──────────────────────────────────────────────────────────────── +Write-Host '' +Write-Host ' 2/2 Kopiere neue und geaenderte Dateien ...' -ForegroundColor Yellow +& robocopy $Source $Target @common /MT:16 /NDL /NP /TEE /UNILOG:$copyLog +$rc = $LASTEXITCODE +Write-Host '' +if ($rc -ge 8) { + Write-Host " FEHLER: Backup unvollstaendig (robocopy $rc). Details: $copyLog" -ForegroundColor Red + Stop-Here 1 +} +Write-Host (" Backup fertig: {0:N0} Dateien, {1}. Protokoll: {2}" -f $copy.Count, (Format-Size $total), $copyLog) -ForegroundColor Green +Stop-Here 0 diff --git a/Backup/logs/backup-2026-11-10_09-54.log b/Backup/logs/backup-2026-11-10_09-54.log new file mode 100644 index 0000000..27f8451 Binary files /dev/null and b/Backup/logs/backup-2026-11-10_09-54.log differ diff --git a/Backup/logs/backup-2026-11-10_10-07.log b/Backup/logs/backup-2026-11-10_10-07.log new file mode 100644 index 0000000..3c5eb5c Binary files /dev/null and b/Backup/logs/backup-2026-11-10_10-07.log differ diff --git a/Backup/logs/backup-2026-11-10_10-17.log b/Backup/logs/backup-2026-11-10_10-17.log new file mode 100644 index 0000000..f10688e Binary files /dev/null and b/Backup/logs/backup-2026-11-10_10-17.log differ diff --git a/Backup/logs/backup-2026-11-10_19-11-main-GallerySwiper.log b/Backup/logs/backup-2026-11-10_19-11-main-GallerySwiper.log new file mode 100644 index 0000000..d419d32 Binary files /dev/null and b/Backup/logs/backup-2026-11-10_19-11-main-GallerySwiper.log differ diff --git a/Backup/logs/backup-2026-11-11_08-08-main.log b/Backup/logs/backup-2026-11-11_08-08-main.log new file mode 100644 index 0000000..58f5aee Binary files /dev/null and b/Backup/logs/backup-2026-11-11_08-08-main.log differ diff --git a/Backup/logs/backup-2026-11-11_09-13-main-GladiatorIdle.log b/Backup/logs/backup-2026-11-11_09-13-main-GladiatorIdle.log new file mode 100644 index 0000000..976d445 Binary files /dev/null and b/Backup/logs/backup-2026-11-11_09-13-main-GladiatorIdle.log differ diff --git a/Backup/logs/backup-2026-11-12_00-35-main.log b/Backup/logs/backup-2026-11-12_00-35-main.log new file mode 100644 index 0000000..714e06d Binary files /dev/null and b/Backup/logs/backup-2026-11-12_00-35-main.log differ diff --git a/Backup/logs/backup-2026-11-12_08-34-q2jr36mi.log b/Backup/logs/backup-2026-11-12_08-34-q2jr36mi.log new file mode 100644 index 0000000..be5dde4 Binary files /dev/null and b/Backup/logs/backup-2026-11-12_08-34-q2jr36mi.log differ diff --git a/Backup/logs/backup-2026-11-12_12-08-q2jr36mi.log b/Backup/logs/backup-2026-11-12_12-08-q2jr36mi.log new file mode 100644 index 0000000..35cad6a Binary files /dev/null and b/Backup/logs/backup-2026-11-12_12-08-q2jr36mi.log differ diff --git a/Backup/logs/pruefung-2026-11-08_21-20.log b/Backup/logs/pruefung-2026-11-08_21-20.log new file mode 100644 index 0000000..2f7a9b1 Binary files /dev/null and b/Backup/logs/pruefung-2026-11-08_21-20.log differ diff --git a/Backup/logs/pruefung-2026-11-08_22-01-Familie-Malkano.log b/Backup/logs/pruefung-2026-11-08_22-01-Familie-Malkano.log new file mode 100644 index 0000000..49cc8ef Binary files /dev/null and b/Backup/logs/pruefung-2026-11-08_22-01-Familie-Malkano.log differ diff --git a/Backup/logs/pruefung-2026-11-08_22-11.log b/Backup/logs/pruefung-2026-11-08_22-11.log new file mode 100644 index 0000000..53604fb Binary files /dev/null and b/Backup/logs/pruefung-2026-11-08_22-11.log differ diff --git a/Backup/logs/pruefung-2026-11-08_22-24.log b/Backup/logs/pruefung-2026-11-08_22-24.log new file mode 100644 index 0000000..e629970 Binary files /dev/null and b/Backup/logs/pruefung-2026-11-08_22-24.log differ diff --git a/Backup/logs/pruefung-2026-11-10_09-52.log b/Backup/logs/pruefung-2026-11-10_09-52.log new file mode 100644 index 0000000..b7ce873 Binary files /dev/null and b/Backup/logs/pruefung-2026-11-10_09-52.log differ diff --git a/Backup/logs/pruefung-2026-11-10_10-05.log b/Backup/logs/pruefung-2026-11-10_10-05.log new file mode 100644 index 0000000..00ba9dd Binary files /dev/null and b/Backup/logs/pruefung-2026-11-10_10-05.log differ diff --git a/Backup/logs/pruefung-2026-11-10_10-11.log b/Backup/logs/pruefung-2026-11-10_10-11.log new file mode 100644 index 0000000..86546a6 Binary files /dev/null and b/Backup/logs/pruefung-2026-11-10_10-11.log differ diff --git a/Backup/logs/pruefung-2026-11-10_10-25-GladiatorIdle.log b/Backup/logs/pruefung-2026-11-10_10-25-GladiatorIdle.log new file mode 100644 index 0000000..adc2944 Binary files /dev/null and b/Backup/logs/pruefung-2026-11-10_10-25-GladiatorIdle.log differ diff --git a/Backup/logs/pruefung-2026-11-10_19-11-main-GallerySwiper.log b/Backup/logs/pruefung-2026-11-10_19-11-main-GallerySwiper.log new file mode 100644 index 0000000..d131394 Binary files /dev/null and b/Backup/logs/pruefung-2026-11-10_19-11-main-GallerySwiper.log differ diff --git a/Backup/logs/pruefung-2026-11-11_07-45-main.log b/Backup/logs/pruefung-2026-11-11_07-45-main.log new file mode 100644 index 0000000..a8dcccc Binary files /dev/null and b/Backup/logs/pruefung-2026-11-11_07-45-main.log differ diff --git a/Backup/logs/pruefung-2026-11-11_09-13-main-GladiatorIdle.log b/Backup/logs/pruefung-2026-11-11_09-13-main-GladiatorIdle.log new file mode 100644 index 0000000..149c876 Binary files /dev/null and b/Backup/logs/pruefung-2026-11-11_09-13-main-GladiatorIdle.log differ diff --git a/Backup/logs/pruefung-2026-11-12_00-12-main.log b/Backup/logs/pruefung-2026-11-12_00-12-main.log new file mode 100644 index 0000000..d6e07aa Binary files /dev/null and b/Backup/logs/pruefung-2026-11-12_00-12-main.log differ diff --git a/Backup/logs/pruefung-2026-11-12_00-34-main.log b/Backup/logs/pruefung-2026-11-12_00-34-main.log new file mode 100644 index 0000000..55b35be Binary files /dev/null and b/Backup/logs/pruefung-2026-11-12_00-34-main.log differ diff --git a/Backup/logs/pruefung-2026-11-12_08-32-q2jr36mi.log b/Backup/logs/pruefung-2026-11-12_08-32-q2jr36mi.log new file mode 100644 index 0000000..df8c9b3 Binary files /dev/null and b/Backup/logs/pruefung-2026-11-12_08-32-q2jr36mi.log differ diff --git a/Backup/logs/pruefung-2026-11-12_12-05-q2jr36mi.log b/Backup/logs/pruefung-2026-11-12_12-05-q2jr36mi.log new file mode 100644 index 0000000..1815c53 Binary files /dev/null and b/Backup/logs/pruefung-2026-11-12_12-05-q2jr36mi.log differ diff --git a/Backup/logs/pruefung-2026-11-12_12-10-q2jr36mi.log b/Backup/logs/pruefung-2026-11-12_12-10-q2jr36mi.log new file mode 100644 index 0000000..510a81b Binary files /dev/null and b/Backup/logs/pruefung-2026-11-12_12-10-q2jr36mi.log differ diff --git a/Backup/logs/pruefung-2026-11-12_12-52-q2jr36mi-Projekt.log b/Backup/logs/pruefung-2026-11-12_12-52-q2jr36mi-Projekt.log new file mode 100644 index 0000000..46b134b --- /dev/null +++ b/Backup/logs/pruefung-2026-11-12_12-52-q2jr36mi-Projekt.log @@ -0,0 +1 @@ +ÿþ \ No newline at end of file diff --git a/Cleanup/cleanup.ps1 b/Cleanup/cleanup.ps1 new file mode 100644 index 0000000..dce0386 --- /dev/null +++ b/Cleanup/cleanup.ps1 @@ -0,0 +1,172 @@ +<# +.SYNOPSIS + Finds regenerable build folders in all projects and (optionally) deletes them. + +.DESCRIPTION + Default: only lists what it found (dry run). Nothing is deleted without -Apply. + + Tiers: + Cache - always regenerable: node_modules, Unity Library/Temp, .NET bin/obj, + Gradle/CMake/Flutter/PyInstaller build, .gradle, __pycache__ + Release - finished builds: dist, builds (APKs, exe, zip). Rebuildable, but they are versions. + Output - raw ComfyUI images in generator output\ folders (adopted assets are already in the project). + + Safety: + - A folder is only a candidate when its parent proves the type (package.json, Assets+ProjectSettings, + *.csproj/*.sln, build.gradle, CMakeLists.txt, pubspec.yaml, *.spec). + - A folder that contains any git-tracked file is skipped. + - _Tools is never touched. + +.EXAMPLE + .\cleanup.ps1 # list Cache folders + .\cleanup.ps1 -Tier Cache,Release # list Cache + Release + .\cleanup.ps1 -Apply # delete Cache folders + .\cleanup.ps1 -Project GallerySwiper -Apply + .\cleanup.ps1 -Project GallerySwiper -Tier Cache,Output -Json # machine-readable (used by project-dashboard) + .\cleanup.ps1 -Project X -Tier Cache -Only 'X\node_modules|X\build' -Apply -Json + + Lists (-Tier, -Project, -Only) may also be one string separated by ',' or '|', + because powershell.exe -File cannot pass arrays. +#> +param( + [string]$Root = 'D:\Oculusquest\Projekt', + [string[]]$Tier = @('Cache'), + [string[]]$Project, + [string]$Only = '', # restrict -Apply to these paths (relative to Root, as listed) + [switch]$Apply, + [switch]$Json, + [int]$MaxDepth = 8 +) + +$ErrorActionPreference = 'Stop' +if ($Json) { [Console]::OutputEncoding = [Text.Encoding]::UTF8 } + +$Tier = @($Tier | ForEach-Object { $_ -split '[,|]' } | ForEach-Object { $_.Trim() } | Where-Object { $_ }) +foreach ($t in $Tier) { if (@('Cache', 'Release', 'Output') -notcontains $t) { throw "Unknown tier '$t' (Cache, Release, Output)" } } +$Project = @($Project | ForEach-Object { $_ -split '\|' } | ForEach-Object { $_.Trim() } | Where-Object { $_ }) +$OnlyList = @($Only -split '\|' | ForEach-Object { $_.Trim() } | Where-Object { $_ }) + +function Test-Any($dir, [string[]]$patterns) { + foreach ($p in $patterns) { + if (Get-ChildItem -LiteralPath $dir -Filter $p -Force -ErrorAction SilentlyContinue | Select-Object -First 1) { return $true } + } + return $false +} + +# Returns the tier for a folder, or $null when it is not a candidate. +function Get-Tier([IO.DirectoryInfo]$d) { + $p = $d.Parent.FullName + switch -Regex ($d.Name) { + '^node_modules$' { if (Test-Path -LiteralPath "$p\package.json") { return 'Cache' } } + '^(Library|Temp)$' { if ((Test-Path -LiteralPath "$p\Assets") -and (Test-Path -LiteralPath "$p\ProjectSettings")) { return 'Cache' } } + '^(bin|obj)$' { if (Test-Any $p @('*.csproj', '*.fsproj', '*.vbproj', '*.sln')) { return 'Cache' } } + '^build$' { + if (Test-Any $p @('build.gradle', 'build.gradle.kts', 'CMakeLists.txt', 'pubspec.yaml', '*.spec')) { return 'Cache' } + if ((Test-Path -LiteralPath "$p\Assets") -and (Test-Path -LiteralPath "$p\ProjectSettings")) { return 'Release' } + } + '^Build$' { if ((Test-Path -LiteralPath "$p\Assets") -and (Test-Path -LiteralPath "$p\ProjectSettings")) { return 'Release' } } + '^\.gradle$' { return 'Cache' } + '^__pycache__$' { return 'Cache' } + '^(dist|builds)$' { return 'Release' } + '^output$' { if ((Test-Path -LiteralPath "$p\config.py") -or (Test-Path -LiteralPath "$p\gen.cmd") -or (Test-Any $p @('gen_*.py'))) { return 'Output' } } + } + return $null +} + +function Get-RepoRoot([string]$path) { + $cur = $path + while ($cur -and $cur.Length -gt $Root.Length) { + if (Test-Path -LiteralPath "$cur\.git") { return $cur } + $cur = Split-Path $cur -Parent + } + return $null +} + +function Test-Tracked([string]$path) { + $repo = Get-RepoRoot (Split-Path $path -Parent) + if (-not $repo) { return $false } + $rel = $path.Substring($repo.Length + 1) + $hit = git -C $repo ls-files -- $rel 2>$null | Select-Object -First 1 + return [bool]$hit +} + +function Get-SizeBytes([string]$path) { + # robocopy /L counts fast and copes with long paths + $out = robocopy $path "$env:TEMP\__nul__" /L /S /NJH /BYTES /FP /NC /NDL /NFL /XJ /R:0 /W:0 2>$null + $line = $out | Where-Object { $_ -match '^\s*Bytes\s*:' } | Select-Object -First 1 + if ($line -match ':\s*(\d+)') { return [int64]$Matches[1] } + return [int64]0 +} + +$found = New-Object System.Collections.Generic.List[object] + +function Walk([IO.DirectoryInfo]$dir, [int]$depth) { + if ($depth -gt $MaxDepth) { return } + foreach ($d in (Get-ChildItem -LiteralPath $dir.FullName -Directory -Force -ErrorAction SilentlyContinue)) { + if ($d.Name -match '^(\.git|\.venv.*|venv|env)$' -or ($d.Attributes -band [IO.FileAttributes]::ReparsePoint)) { continue } + $t = Get-Tier $d + if ($t) { + $found.Add([pscustomobject]@{ Tier = $t; Dir = $d }) + continue # never descend into a candidate + } + Walk $d ($depth + 1) + } +} + +$projects = Get-ChildItem -LiteralPath $Root -Directory -Force | Where-Object { $_.Name -ne '_Tools' } +if ($Project) { $projects = $projects | Where-Object { $Project -contains $_.Name } } +foreach ($p in $projects) { Walk $p 1 } + +$rows = foreach ($f in $found) { + if ($Tier -notcontains $f.Tier) { continue } + $path = $f.Dir.FullName + $tracked = Test-Tracked $path + [pscustomobject]@{ + Tier = $f.Tier + MB = [math]::Round((Get-SizeBytes $path) / 1MB) + Skip = if ($tracked) { 'git-tracked' } else { '' } + Path = $path.Substring($Root.Length + 1) + } +} +$rows = @($rows | Sort-Object Tier, @{ e = 'MB'; Descending = $true }) + +$todo = @($rows | Where-Object { -not $_.Skip }) +if ($OnlyList.Count) { $todo = @($todo | Where-Object { $OnlyList -contains $_.Path }) } + +if (-not $Json) { + $big = @($rows | Where-Object { $_.MB -ge 1 }) + $big | Format-Table -AutoSize | Out-String -Width 220 | Write-Host + if ($rows.Count -gt $big.Count) { Write-Host ("+ {0} small folders under 1 MB (e.g. __pycache__)" -f ($rows.Count - $big.Count)) } + foreach ($t in $Tier) { + $gb = [math]::Round((($todo | Where-Object Tier -eq $t | Measure-Object MB -Sum).Sum) / 1024, 2) + Write-Host ("{0,-8} {1,7} GB" -f $t, $gb) + } + Write-Host ("{0} folders deletable, {1} skipped as git-tracked" -f $todo.Count, ($rows.Count - $todo.Count)) +} + +if (-not $Apply) { + if ($Json) { ConvertTo-Json -InputObject @($rows) -Compress } else { Write-Host 'Dry run. Add -Apply to delete.' } + exit 0 +} + +$freeBefore = (Get-PSDrive ($Root.Substring(0, 1))).Free +$deleted = @(); $failed = @() +foreach ($r in $todo) { + $full = Join-Path $Root $r.Path + if (-not $Json) { Write-Host "delete $($r.Path)" } + # rd with \\?\ prefix handles paths longer than 260 chars (node_modules) + # errors (locked files) go to nul; the Test-Path below reports leftovers and the loop continues + cmd /c "rd /s /q `"\\?\$full`" 2>nul" + if (Test-Path -LiteralPath $full) { + $failed += $r.Path + if (-not $Json) { Write-Warning "not fully deleted: $($r.Path)" } + } else { $deleted += $r.Path } +} +$freeAfter = (Get-PSDrive ($Root.Substring(0, 1))).Free +$freedGB = [math]::Round(($freeAfter - $freeBefore) / 1GB, 2) +if ($Json) { + ConvertTo-Json -InputObject @{ deleted = @($deleted); failed = @($failed); freedGB = $freedGB } -Compress +} else { + Write-Host ("Freed {0} GB" -f $freedGB) +} +exit 0 diff --git a/ComfyGen b/ComfyGen new file mode 160000 index 0000000..e7e3bcb --- /dev/null +++ b/ComfyGen @@ -0,0 +1 @@ +Subproject commit e7e3bcbbcb22227e1031c104c0da60769c115a28 diff --git a/Itch/README.md b/Itch/README.md new file mode 100644 index 0000000..dcf0366 --- /dev/null +++ b/Itch/README.md @@ -0,0 +1,21 @@ +# Itch – Werkzeuge für itch.io-Seiten + +Alles, um ein Projekt auf itch.io zu bringen. Ablauf steuert der Skill **`itchiocreater`**; Ergebnis landet +im Projekt unter `docs\itchio\`. Motive für Cover/Banner kommen aus ComfyGen (`gen generate itch_keyart`). + +| Ich brauche … | Werkzeug | Beispiel | +|---|---|---| +| Cover 630×500, Banner 960×256 + 1920×512, Hintergrund 1920×1200 mit Titel | `itch_images.py` | `py -3.12 itch_images.py --title "X" --tagline "…" --backdrop keyart.png [--cover-art cover.png] [--hero figur.png] [--font f.ttf] [--color "#hex"] --out docs\itchio` | +| Echte Screenshots eines HTML-Spiels (automatisch, Headless-Edge) | `itch_screens.mjs` | `node itch_screens.mjs docs\itchio\shots.json` (Format im Dateikopf: Seite, Größe, pro Bild Query/Tasten/Klicks/JS) | +| Screenshots eines exe-Spiels, während man spielt | `itch_capture.ps1` | `itch_capture.ps1 -Exe release\Spiel.exe -Every 4 -Count 20` · `-Hotkey` (F9 = Bild, Esc = Ende) · `-Title "Fenstertitel"` | +| Screenshots im Rahmen mit Bildunterschrift (Store-Look) | `itch_promo.py` | `py -3.12 itch_promo.py --shots …\screenshots --captions captions.txt --backdrop keyart.png --out …\promo` | +| Trailer-MP4 aus Screenshots + Musik (für YouTube-Link) | `itch_trailer.py` | `py -3.12 itch_trailer.py --shots … --music m.mp3 --title "X" --tagline "…" --footer "sn09.itch.io/x" --out trailer.mp4` | +| Prüfen vor dem Upload | `itch_check.py` | `py -3.12 itch_check.py docs\itchio --upload release\x-web.zip --upload release\X.exe` | + +Regeln: +- Screenshots zeigen immer das **echte Spiel** (itch.io-Regel, sonst irreführend). KI-Bilder nur für Cover, + Banner, Hintergrund und den Rahmen der Promo-Bilder. +- KI-Offenlegung auf itch.io immer **Yes** (Grafik/Sound mit ComfyUI). +- Voraussetzungen: Python 3.12 + Pillow, Node 18+, Microsoft Edge (Screenshots), ffmpeg (Trailer). + +Vorbilder: `GladiatorIdle\docs\itchio\` (vollständig inkl. Trailer, install.html), `Pipefix\docs\itchio\`. diff --git a/Itch/itch_capture.ps1 b/Itch/itch_capture.ps1 new file mode 100644 index 0000000..2c91b51 --- /dev/null +++ b/Itch/itch_capture.ps1 @@ -0,0 +1,94 @@ +<# + Screenshots of a running Windows game (exe) for itch.io: starts the game (or uses a running + window), then saves the game window every few seconds while you play. Afterwards pick the best. + + D:\Oculusquest\Projekt\_Tools\Itch\itch_capture.ps1 -Exe release\Spiel.exe -Out docs\itchio\screenshots + ... -Title "Gladiator" use an already running window whose title contains this text + ... -Every 4 -Count 30 -Delay 8 first shot after 8 s, then every 4 s, 30 shots + ... -Hotkey instead of a timer: one shot per press of F9 (Esc ends) + + Captures what is on screen in the window rectangle (the window must be visible, not covered). + Files: raw_001.png, raw_002.png, ... (existing ones are kept, numbering continues). +#> +param( + [string]$Exe, + [string]$Title, + [string]$Out = 'docs\itchio\screenshots', + [int]$Every = 4, + [int]$Count = 20, + [int]$Delay = 8, + [switch]$Hotkey +) +$ErrorActionPreference = 'Stop' +Add-Type -AssemblyName System.Drawing +Add-Type @' +using System; using System.Runtime.InteropServices; +public static class W32 { + [StructLayout(LayoutKind.Sequential)] public struct RECT { public int L, T, R, B; } + [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r); + [DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr h, int a, out RECT r, int s); + [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h); + [DllImport("user32.dll")] public static extern short GetAsyncKeyState(int k); + [DllImport("user32.dll")] public static extern bool SetProcessDPIAware(); +} +'@ +[W32]::SetProcessDPIAware() | Out-Null + +New-Item -ItemType Directory -Force $Out | Out-Null +$proc = $null +if ($Exe) { + $exePath = (Resolve-Path $Exe).Path + $proc = Start-Process $exePath -WorkingDirectory (Split-Path $exePath) -PassThru + "Gestartet: $exePath - warte auf das Fenster ..." +} +function Find-Window { + if ($proc) { $proc.Refresh(); if ($proc.MainWindowHandle -ne 0) { return $proc.MainWindowHandle } } + if ($Title) { + $p = Get-Process | Where-Object { $_.MainWindowHandle -ne 0 -and $_.MainWindowTitle -like "*$Title*" } | Select-Object -First 1 + if ($p) { return $p.MainWindowHandle } + } + if ($proc) { # launchers: the window may belong to a child process with the same name + $p = Get-Process -Name $proc.ProcessName -ErrorAction SilentlyContinue | Where-Object MainWindowHandle -ne 0 | Select-Object -First 1 + if ($p) { return $p.MainWindowHandle } + } + return [IntPtr]::Zero +} +$h = [IntPtr]::Zero +for ($i = 0; $i -lt 60 -and $h -eq [IntPtr]::Zero; $i++) { Start-Sleep -Milliseconds 500; $h = Find-Window } +if ($h -eq [IntPtr]::Zero) { throw 'Kein Spielfenster gefunden (-Exe oder -Title angeben).' } + +$n = (Get-ChildItem $Out -Filter 'raw_*.png' -ErrorAction SilentlyContinue | Measure-Object).Count +function Snap { + $r = New-Object W32+RECT + # DWM bounds exclude the invisible resize border of Windows 10/11 windows + if ([W32]::DwmGetWindowAttribute($h, 9, [ref]$r, 16) -ne 0) { [W32]::GetWindowRect($h, [ref]$r) | Out-Null } + $w = $r.R - $r.L; $hh = $r.B - $r.T + if ($w -lt 50 -or $hh -lt 50) { return } + $bmp = New-Object System.Drawing.Bitmap $w, $hh + $g = [System.Drawing.Graphics]::FromImage($bmp) + $g.CopyFromScreen($r.L, $r.T, 0, 0, $bmp.Size) + $script:n++ + $file = Join-Path $Out ('raw_{0:000}.png' -f $script:n) + $bmp.Save($file, [System.Drawing.Imaging.ImageFormat]::Png) + $g.Dispose(); $bmp.Dispose() + " $file ($w x $hh)" +} + +[W32]::SetForegroundWindow($h) | Out-Null +if ($Hotkey) { + 'F9 = Screenshot, Esc = fertig. Spiel jetzt im Vordergrund lassen.' + while ($true) { + if ([W32]::GetAsyncKeyState(0x78) -band 1) { Snap } # F9 + if ([W32]::GetAsyncKeyState(0x1B) -band 0x8000) { break } # Esc + Start-Sleep -Milliseconds 30 + } +} else { + "Erster Screenshot in $Delay s, dann alle $Every s ($Count Stück). Einfach spielen." + Start-Sleep -Seconds $Delay + for ($i = 0; $i -lt $Count; $i++) { + if ($proc -and $proc.HasExited -and (Find-Window) -eq [IntPtr]::Zero) { 'Spiel beendet.'; break } + Snap + Start-Sleep -Seconds $Every + } +} +"Fertig: $script:n Screenshots in $((Resolve-Path $Out).Path) - die besten 5-8 behalten, Rest loeschen." diff --git a/Itch/itch_check.py b/Itch/itch_check.py new file mode 100644 index 0000000..72396a1 --- /dev/null +++ b/Itch/itch_check.py @@ -0,0 +1,101 @@ +"""Pre-flight check of an itch.io package folder (docs/itchio) before uploading. + + py -3.12 itch_check.py docs/itchio [--upload release/game-web.zip] [--upload release/Game.exe] + +Checks: cover size/ratio, banner/background, screenshot count and size, description.html +(no + + diff --git a/Library/mobile/template/package.json b/Library/mobile/template/package.json new file mode 100644 index 0000000..1d480b7 --- /dev/null +++ b/Library/mobile/template/package.json @@ -0,0 +1,27 @@ +{ + "name": "{{SLUG}}", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "start": "vite", + "build": "tsc --noEmit && vite build", + "preview": "vite preview --port 5174", + "typecheck": "tsc --noEmit", + "android": "npm run build && npx cap sync android && npx cap open android", + "cap:sync": "npm run build && npx cap sync" + }, + "dependencies": { + "@capacitor-community/admob": "^8.0.0", + "@capacitor/android": "^8.3.0", + "@capacitor/app": "^8.1.1", + "@capacitor/cli": "^8.3.0", + "@capacitor/core": "^8.3.0", + "@capacitor/haptics": "^8.0.2", + "cordova-plugin-purchase": "^13.18.0" + }, + "devDependencies": { + "typescript": "^5.5.0", + "vite": "^5.4.0" + } +} diff --git a/Library/mobile/template/src/lang.ts b/Library/mobile/template/src/lang.ts new file mode 100644 index 0000000..069fea4 --- /dev/null +++ b/Library/mobile/template/src/lang.ts @@ -0,0 +1,26 @@ +// {{NAME}} - all visible texts, English + German (kit/i18n.ts). A new text always gets BOTH +// languages; German may leave a key out only by mistake (it then falls back to English). +import { createI18n } from "./kit/i18n"; + +const en = { + lang_self: "English", + coins: "Coins", + sound_on: "Sound on", + sound_off: "Sound off", + double_ad: "2x coins (ad)", +}; + +const de: Partial = { + lang_self: "Deutsch", + coins: "Münzen", + sound_on: "Sound an", + sound_off: "Sound aus", + double_ad: "2x Münzen (Werbung)", +}; + +export const { t, lang, setLang, langs } = createI18n({ en, de }, "{{SLUG}}_lang"); + +/** Next language (one button cycles through all); reloads the page. */ +export function nextLang(): void { + setLang(langs[(langs.indexOf(lang) + 1) % langs.length]); +} diff --git a/Library/mobile/template/src/main.ts b/Library/mobile/template/src/main.ts new file mode 100644 index 0000000..14398b7 --- /dev/null +++ b/Library/mobile/template/src/main.ts @@ -0,0 +1,100 @@ +// {{NAME}} - entry. Demo from the Library template: tap the orb for coins, watch an ad to +// double them. Replace the demo; keep the wiring (save, audio, haptics, ads, lifecycle, +// texts via t() from lang.ts, credits line). +import "./style.css"; +import { configureAudio, initAudio, playMusic, playSfx, toggleMute, isMuted } from "./kit/audio"; +import { createSaveStore, num } from "./kit/save"; +import { configureHaptics, hapticLight } from "./kit/haptics"; +import { configureAds, initAds, showRewarded } from "./kit/ads"; +import { onBack, onPause } from "./kit/lifecycle"; +import { t, lang, nextLang } from "./lang"; + +const ID = "{{SLUG}}"; +// Credits (standard for every app); external links open in the system browser +const DISCORD = "https://discord.gg/Ej4JPmCZva"; +const CREDITS = `© {{YEAR}} Michael Media · Discord`; + +// ---- save ------------------------------------------------------------------------------- +interface Save { + v: number; + coins: number; + taps: number; +} +const saves = createSaveStore({ + key: `${ID}_save`, + version: 1, + defaults: () => ({ v: 1, coins: 0, taps: 0 }), + normalize: (s, d) => ({ ...d, ...s, coins: num(s.coins, d.coins), taps: num(s.taps, d.taps) }), +}); +const save = saves.load(); +setInterval(() => saves.persist(save), 5000); +onPause(() => saves.persist(save)); + +// ---- services --------------------------------------------------------------------------- +configureAudio({ base: "/assets/Audio/", storageKey: ID, preload: ["sfx_tap", "music_game"], throttle: { sfx_tap: 50 } }); +configureHaptics(ID); +// Ad unit ids from the AdMob console; testing:true uses Google's test unit (set false for release) +configureAds({ testing: true, rewarded: { double: "" } }); +void initAds(); + +// ---- view ------------------------------------------------------------------------------- +const $ = (id: string) => document.getElementById(id) as T; +const cv = $("cv"); +const ctx = cv.getContext("2d")!; +let W = 0, H = 0; +function fit(): void { + const r = cv.getBoundingClientRect(), k = devicePixelRatio || 1; + W = r.width; H = r.height; + cv.width = Math.round(W * k); cv.height = Math.round(H * k); + ctx.setTransform(k, 0, 0, k, 0, 0); +} +addEventListener("resize", fit); +fit(); + +let pulse = 0; +cv.addEventListener("pointerdown", (e) => { + initAudio(); + playMusic("music_game"); + const r = cv.getBoundingClientRect(); + const x = e.clientX - r.left, y = e.clientY - r.top; + if (Math.hypot(x - W / 2, y - H / 2) < Math.min(W, H) * 0.22) { + save.coins += 1; save.taps += 1; pulse = 1; + playSfx("sfx_tap"); hapticLight(); + hud(); + } +}); + +$("bAd").onclick = async () => { + initAudio(); + if (await showRewarded("double")) { save.coins *= 2; saves.persist(save); hud(); } +}; +$("bMute").onclick = () => { initAudio(); toggleMute(); hud(); }; +$("bLang").onclick = nextLang; +onBack(() => false); // nothing to close -> app minimises + +// static texts (language is fixed per page load - nextLang() reloads) +document.documentElement.lang = lang; +$("lCoins").textContent = t("coins"); +$("bAd").textContent = t("double_ad"); +$("bLang").textContent = `🌐 ${t("lang_self")}`; +$("credits").innerHTML = CREDITS; + +function hud(): void { + $("coins").textContent = String(save.coins); + $("bMute").textContent = isMuted() ? t("sound_off") : t("sound_on"); +} + +function frame(): void { + pulse *= 0.9; + ctx.clearRect(0, 0, W, H); + const r = Math.min(W, H) * 0.2 * (1 + pulse * 0.12); + const g = ctx.createRadialGradient(W / 2, H / 2, r * 0.1, W / 2, H / 2, r); + g.addColorStop(0, "#bff3ff"); g.addColorStop(1, "#1a6d9a"); + ctx.fillStyle = g; + ctx.beginPath(); ctx.arc(W / 2, H / 2, r, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = "#8b97bd"; ctx.font = "12px system-ui"; ctx.textAlign = "center"; + ctx.fillText(`v${__APP_VERSION__}`, W / 2, H - 10); + requestAnimationFrame(frame); +} +hud(); +frame(); diff --git a/Library/mobile/template/src/style.css b/Library/mobile/template/src/style.css new file mode 100644 index 0000000..b5210e4 --- /dev/null +++ b/Library/mobile/template/src/style.css @@ -0,0 +1,20 @@ +:root { + --bg: #0b0f1a; --panel: #141b2d; --line: #2a3658; --text: #e3e9ff; --accent: #4fd8ff; + /* safe areas (notch, gesture bar) */ + --sat: env(safe-area-inset-top); --sab: env(safe-area-inset-bottom); +} +* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; } +html, body { margin: 0; height: 100%; overflow: hidden; background: var(--bg); color: var(--text); + font: 16px/1.4 system-ui, sans-serif; user-select: none; -webkit-user-select: none; touch-action: manipulation; } +#app { display: flex; flex-direction: column; height: 100%; padding: calc(8px + var(--sat)) 12px calc(8px + var(--sab)); gap: 8px; } +#hud, footer { display: flex; justify-content: space-between; align-items: center; gap: 8px; } +#hud b { color: var(--accent); font-variant-numeric: tabular-nums; } +canvas { flex: 1; width: 100%; min-height: 0; border-radius: 12px; background: #050913; display: block; } +button { font: inherit; color: var(--text); background: var(--panel); border: 1px solid var(--line); + border-radius: 10px; padding: 10px 16px; } +button:active { transform: scale(.97); } +footer button { flex: 1; } +.grow { flex: 1; } +/* credits (standard for every app: © year Michael Media + Discord) */ +.credits { margin: 0; text-align: center; font-size: 12px; color: #8b97bd; } +.credits a { color: var(--accent); text-decoration: none; } diff --git a/Library/mobile/template/src/vite-env.d.ts b/Library/mobile/template/src/vite-env.d.ts new file mode 100644 index 0000000..d5337f4 --- /dev/null +++ b/Library/mobile/template/src/vite-env.d.ts @@ -0,0 +1,2 @@ +/// +declare const __APP_VERSION__: string; diff --git a/Library/mobile/template/tsconfig.json b/Library/mobile/template/tsconfig.json new file mode 100644 index 0000000..e973d79 --- /dev/null +++ b/Library/mobile/template/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "ESNext", + "moduleResolution": "bundler", + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noEmit": true, + "isolatedModules": true, + "skipLibCheck": true + }, + "include": ["src"] +} diff --git a/Library/mobile/template/vite.config.ts b/Library/mobile/template/vite.config.ts new file mode 100644 index 0000000..93da8d9 --- /dev/null +++ b/Library/mobile/template/vite.config.ts @@ -0,0 +1,11 @@ +import { readFileSync } from "node:fs"; +import { defineConfig } from "vite"; + +// The version shown in-game comes from package.json. Keep versionName in +// android/app/build.gradle in step - a bug report is only useful if it names a build. +const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) as { version: string }; + +export default defineConfig({ + define: { __APP_VERSION__: JSON.stringify(pkg.version) }, + build: { target: "es2020" }, +}); diff --git a/Library/new-project.ps1 b/Library/new-project.ps1 new file mode 100644 index 0000000..2309c17 --- /dev/null +++ b/Library/new-project.ps1 @@ -0,0 +1,135 @@ +<# + Creates a new project from a Library template, or refreshes the kit copy in an existing one. + + New project (folder D:\Oculusquest\Projekt\): + .\new-project.ps1 -Name "Particle Panic" # HTML game (default) + .\new-project.ps1 -Name "Star Miner" -Type mobile # Vite + TS + Capacitor + options: -Root -NoGit -NoGenerator -Force (allow an existing EMPTY-ish folder) + + Refresh kit files after improving them in the Library: + .\new-project.ps1 -UpdateKit -Path D:\Oculusquest\Projekt\Pipefix2 + + Placeholders in template files: {{NAME}} {{SLUG}} {{IDENT}} {{DATE}} {{YEAR}} +#> +param( + [string]$Name, + [ValidateSet('webgame', 'mobile')][string]$Type = 'webgame', + [string]$Root = 'D:\Oculusquest\Projekt', + [string]$Path, + [switch]$UpdateKit, + [switch]$NoGit, + [switch]$NoGenerator, + [switch]$Force +) +$ErrorActionPreference = 'Stop' +$lib = $PSScriptRoot +$comfyTemplate = Join-Path (Split-Path $lib -Parent) 'ComfyGen\template' +$utf8 = New-Object System.Text.UTF8Encoding($false) + +function KitTarget([string]$dir, [string]$kind) { + if ($kind -eq 'mobile') { return Join-Path $dir 'src\kit' } + return Join-Path $dir 'game\kit' +} + +function Copy-Kit([string]$dir, [string]$kind) { + $src = Join-Path $lib "$(if ($kind -eq 'mobile') { 'mobile' } else { 'web' })\kit" + $dst = KitTarget $dir $kind + New-Item -ItemType Directory -Force $dst | Out-Null + $files = Get-ChildItem $src -File + foreach ($f in $files) { Copy-Item $f.FullName (Join-Path $dst $f.Name) -Force } + "Kit -> $dst ($($files.Count) Dateien: $(($files | ForEach-Object Name) -join ', '))" +} + +# ---------------------------------------------------------------- update kit only +if ($UpdateKit) { + if (-not $Path) { $Path = (Get-Location).Path } + $Path = (Resolve-Path $Path).Path + if (Test-Path (Join-Path $Path 'game\kit')) { $kind = 'webgame' } + elseif (Test-Path (Join-Path $Path 'src\kit')) { $kind = 'mobile' } + else { throw "Kein game\kit oder src\kit in $Path gefunden." } + Copy-Kit $Path $kind + 'Unterschiede pruefen: git diff -- ' + $(if ($kind -eq 'mobile') { 'src/kit' } else { 'game/kit' }) + exit 0 +} + +# ---------------------------------------------------------------- new project +if (-not $Name) { throw 'Parameter -Name fehlt (z. B. -Name "Particle Panic").' } +$slug = ($Name.ToLowerInvariant() -replace '[^a-z0-9]', '') +if (-not $slug) { throw "Aus '$Name' laesst sich kein Kurzname bilden (nur a-z, 0-9)." } +$ident = (($Name -split '[^A-Za-z0-9]+') | Where-Object { $_ } | ForEach-Object { $_.Substring(0, 1).ToUpperInvariant() + $_.Substring(1) }) -join '' +if ($ident -match '^[0-9]') { $ident = 'G' + $ident } + +$dest = Join-Path $Root $Name +if (Test-Path $dest) { + $existing = Get-ChildItem $dest -Force | Where-Object { $_.Name -notin '.claude', '.dashboard.json' } + if ($existing -and -not $Force) { throw "$dest existiert und ist nicht leer. Anderer Name oder -Force." } +} +New-Item -ItemType Directory -Force $dest | Out-Null + +$tpl = Join-Path $lib "$(if ($Type -eq 'mobile') { 'mobile' } else { 'web' })\template" +# copy file by file, skipping build output an editor may have created inside the template +$skip = '\\(bin|obj|node_modules|dist|release)(\\|$)' +Get-ChildItem $tpl -Recurse -File -Force | Where-Object { $_.FullName.Substring($tpl.Length) -notmatch $skip } | ForEach-Object { + # *.template = file an IDE must not pick up inside the Library (e.g. Launcher.csproj.template) + $target = Join-Path $dest ($_.FullName.Substring($tpl.Length + 1) -replace '\.template$', '') + New-Item -ItemType Directory -Force (Split-Path $target -Parent) | Out-Null + Copy-Item $_.FullName $target -Force +} + +# placeholders +$now = Get-Date +$map = @{ + '{{NAME}}' = $Name; '{{SLUG}}' = $slug; '{{IDENT}}' = $ident + '{{DATE}}' = $now.ToString('yyyy-MM-dd'); '{{YEAR}}' = $now.ToString('yyyy') +} +$textExt = '.html', '.js', '.mjs', '.ts', '.css', '.json', '.md', '.ps1', '.cs', '.csproj', '.py', '.txt', '.gitignore' +Get-ChildItem $dest -Recurse -File -Force | Where-Object { $textExt -contains $_.Extension -or $_.Name -eq '.gitignore' } | ForEach-Object { + $t = [IO.File]::ReadAllText($_.FullName, $utf8) + $n = $t + foreach ($k in $map.Keys) { $n = $n.Replace($k, $map[$k]) } + if ($n -ne $t) { [IO.File]::WriteAllText($_.FullName, $n, $utf8) } +} + +Copy-Kit $dest $Type + +# asset folders (ComfyGen adopt writes to ASSETS_DIR\Sprites and \Audio) +$assetRel = if ($Type -eq 'mobile') { 'public\assets' } else { 'game\assets' } +foreach ($sub in 'Sprites', 'Audio', 'Fonts') { New-Item -ItemType Directory -Force (Join-Path $dest "$assetRel\$sub") | Out-Null } + +# sprite generator (ComfyGen project) +if (-not $NoGenerator -and (Test-Path $comfyTemplate)) { + $gen = Join-Path $dest 'sprite-generator' + New-Item -ItemType Directory -Force $gen | Out-Null + Get-ChildItem $comfyTemplate -File | ForEach-Object { Copy-Item $_.FullName $gen -Force } + $cfgFile = Join-Path $gen 'config.py' + $parts = ($assetRel -split '\\' | ForEach-Object { '"' + $_ + '"' }) -join ', ' + $cfg = [IO.File]::ReadAllText($cfgFile, $utf8) + $cfg = [regex]::Replace($cfg, '(?m)^ASSETS_DIR\s*=.*$', "ASSETS_DIR = os.path.join(PROJECT_ROOT, $parts)") + [IO.File]::WriteAllText($cfgFile, $cfg, $utf8) + "Generator -> $gen (ASSETS_DIR = $assetRel)" +} + +# project dashboard entry +$dash = Join-Path $dest '.dashboard.json' +if (-not (Test-Path $dash)) { + $d = [ordered]@{ status = 'active'; priority = 'medium'; notes = "Vorlage $Type aus _Tools\Library"; tags = @($Type); + tasks = @(); thumbnail = ''; start = ''; updatedAt = $now.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ') } + [IO.File]::WriteAllText($dash, ($d | ConvertTo-Json -Depth 3), $utf8) +} + +# git (init only - the first commit is up to the user) +if (-not $NoGit -and (Get-Command git -ErrorAction SilentlyContinue) -and -not (Test-Path (Join-Path $dest '.git'))) { + git -C $dest init -q -b main 2>$null + if ($LASTEXITCODE -ne 0) { git -C $dest init -q } + 'git init (noch kein Commit)' +} + +'' +"Fertig: $dest (Typ $Type, Kurzname $slug, Ident $ident)" +if ($Type -eq 'webgame') { + " Spielen: $dest\game\index.html" + " Release: cd `"$dest`"; .\build.ps1" +} else { + " cd `"$dest`"; npm install; npm start" + " Android: npx cap add android; npm run android" +} diff --git a/Library/tools/project-check.mjs b/Library/tools/project-check.mjs new file mode 100644 index 0000000..37c0e6b --- /dev/null +++ b/Library/tools/project-check.mjs @@ -0,0 +1,268 @@ +// Project check: short report for the "projekt-check" skill - so Claude reads ~40 lines instead +// of the code. Stack, size, biggest files, kit status vs Library, re-implementations of kit +// features, Library candidates, hygiene (git, README, CLAUDE.md, release age, TODOs, credits/Discord). +// node D:\Oculusquest\Projekt\_Tools\Library\tools\project-check.mjs [projectPath] [--all] +// --all lists every finding instead of the top entries. +import fs from 'node:fs'; +import path from 'node:path'; +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { fileURLToPath } from 'node:url'; + +const LIB = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const args = process.argv.slice(2); +const ALL = args.includes('--all'); +const root = path.resolve(args.find(a => !a.startsWith('--')) || process.cwd()); +const name = path.basename(root); +const TOP = ALL ? 1e9 : 6; + +const SKIP = /^(node_modules|\.git|dist|build|builds|bin|obj|out|target|Library|Temp|Logs|output|release|publish.*|\.gradle|\.idea|\.vscode|\.vs|__pycache__|\.venv.*|venv|env|\.expo|\.cache|\.claude|ThirdParty|third_party|vendor|Packages|coverage|test-results|playwright-report|_archiv|archive|backup)$/i; +const SRC = /\.(js|mjs|cjs|ts|tsx|jsx|cs|cpp|cc|hpp|h|py|kt|java|dart|gd|html|css|ps1)$/i; + +// ---- walk --------------------------------------------------------------------------------- +const files = []; +(function walk(dir, depth) { + let ents = []; + try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; } + for (const e of ents) { + const p = path.join(dir, e.name); + if (e.isDirectory()) { + if (depth < 8 && !SKIP.test(e.name) && !(e.name === 'android' && fs.existsSync(path.join(root, 'capacitor.config.json')))) walk(p, depth + 1); + } else if (SRC.test(e.name) && files.length < 6000) { + let st; try { st = fs.statSync(p); } catch { continue; } + if (st.size > 3e6) continue; // generated bundles, data dumps + files.push({ p, rel: path.relative(root, p), size: st.size, mtime: st.mtimeMs }); + } + } +})(root, 0); + +const isKit = f => /(^|\\)(game|src)\\kit\\/.test(f.rel); +const isGen = f => /(^|\\)(sprite-?gen(erator)?|spritegenerator|design-gen|tools?|scripts?|tests?)\\/i.test(f.rel); +for (const f of files) { + try { f.text = fs.readFileSync(f.p, 'utf8'); } catch { f.text = ''; } + f.lines = f.text ? f.text.split('\n').length : 0; +} +const own = files.filter(f => !isKit(f)); +const code = own.filter(f => !/\.(html|css)$/i.test(f.rel) || f.lines > 300); // big inline-script html counts + +// ---- stack -------------------------------------------------------------------------------- +const has = p => fs.existsSync(path.join(root, p)); +const pkg = (() => { try { return JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); } catch { return null; } })(); +const deps = pkg ? { ...pkg.dependencies, ...pkg.devDependencies } : {}; +const ext = {}; +for (const f of code) { const e = path.extname(f.rel).slice(1).toLowerCase(); ext[e] = (ext[e] || 0) + f.lines; } +const stack = []; +if (deps['@capacitor/core']) stack.push('Capacitor'); +if (deps.vite) stack.push('Vite'); +if (deps.react) stack.push('React'); +if (deps.electron) stack.push('Electron'); +if (deps.expo) stack.push('Expo'); +if (has('game/index.html') || (has('index.html') && !pkg)) stack.push('HTML-Spiel'); +if (files.some(f => /\.csproj$/i.test(f.rel)) || own.some(f => f.rel.endsWith('.cs'))) stack.push('.NET'); +if (has('CMakeLists.txt')) stack.push('C++/CMake'); +if (has('pubspec.yaml')) stack.push('Flutter'); +if (has('ProjectSettings')) stack.push('Unity'); +if (own.some(f => f.rel.endsWith('.py')) && !stack.length) stack.push('Python'); +const kind = has('game/kit') || stack.includes('HTML-Spiel') ? 'web' : deps['@capacitor/core'] ? 'mobile' : null; + +// ---- kit status --------------------------------------------------------------------------- +const hash = s => createHash('sha1').update(s.replace(/\r\n/g, '\n')).digest('hex'); +const ver = s => +((s.match(/\(v(\d+)\)/) || [])[1] || 0); +const kitLines = []; +for (const [projDir, libDir] of [['game/kit', 'web/kit'], ['src/kit', 'mobile/kit']]) { + const pd = path.join(root, projDir), ld = path.join(LIB, libDir); + if (!fs.existsSync(pd)) continue; + const libFiles = fs.readdirSync(ld); + const st = { same: 0, old: [], changed: [], missing: [], extra: [] }; + for (const f of libFiles) { + const pf = path.join(pd, f); + if (!fs.existsSync(pf)) { st.missing.push(f); continue; } + const a = fs.readFileSync(pf, 'utf8'), b = fs.readFileSync(path.join(ld, f), 'utf8'); + if (hash(a) === hash(b)) st.same++; + else if (ver(a) < ver(b)) st.old.push(`${f} v${ver(a)}→v${ver(b)}`); + else st.changed.push(f); + } + for (const f of fs.readdirSync(pd)) if (!libFiles.includes(f)) st.extra.push(f); + kitLines.push(`${projDir}: ${st.same} aktuell` + + (st.old.length ? ` · VERALTET ${st.old.join(', ')}` : '') + + (st.changed.length ? ` · IM PROJEKT GEÄNDERT ${st.changed.join(', ')} (→ in Library übernehmen?)` : '') + + (st.missing.length ? ` · fehlt ${st.missing.join(', ')}` : '') + + (st.extra.length ? ` · nur hier ${st.extra.join(', ')}` : '')); +} + +// ---- own code doing what the kit already does --------------------------------------------- +const REINVENT = kind === 'mobile' ? [ + [/new AudioContext|webkitAudioContext/, 'eigenes WebAudio', 'kit/audio.ts'], + [/localStorage\.setItem\([^)]*save/i, 'eigener Spielstand', 'kit/save.ts createSaveStore'], + [/AdMob\./, 'AdMob direkt', 'kit/ads.ts'], + [/CdvPurchase|store\.register\(/, 'Käufe direkt', 'kit/iap.ts'], + [/Haptics\.impact/, 'Haptics direkt', 'kit/haptics.ts'], + [/addListener\(\s*["']backButton/, 'Zurück-Taste direkt', 'kit/lifecycle.ts'], +] : [ + [/new \(?window\.AudioContext|new AudioContext|webkitAudioContext/, 'eigenes WebAudio', 'Kit.createAudio'], + [/localStorage\.(get|set)Item/, 'localStorage direkt', 'Kit.store / Kit.saveSlot'], + [/firebasedatabase\.app|firebaseio\.com/, 'Firebase-REST direkt', 'Kit.scores'], + [/chrome\.webview/, 'WebView2-Bridge direkt', 'Kit.host'], + [/requestAnimationFrame\(/, 'eigene Spielschleife', 'Kit.loop'], + [/devicePixelRatio/, 'eigene HiDPI-Skalierung', 'Kit.fit / Kit.setRes'], + [/addEventListener\(\s*['"]keydown/, 'eigene Tastatur-Abfrage', 'Kit.input'], +]; +const reinvent = []; +if (kind) { + const web = code.filter(f => /\.(js|mjs|ts|tsx|jsx|html)$/i.test(f.rel) && !isGen(f)); + for (const [re, what, use] of REINVENT) { + // a file that already calls the kit piece is fine (e.g. Kit.input + one keydown for a text field) + const usesKit = new RegExp(use.split(' ')[0].replace(/^kit\//, 'kit/').replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\\\.ts$/, '')); + const hits = web.filter(f => re.test(f.text) && !usesKit.test(f.text)).map(f => f.rel); + if (hits.length) reinvent.push(`${what} in ${hits.slice(0, 3).join(', ')}${hits.length > 3 ? ` +${hits.length - 3}` : ''} → ${use}`); + } +} + +// ---- Library candidates: generic-looking modules ------------------------------------------ +const GENERIC = [ + [/achiev/i, 'Achievements', null], [/tutorial|onboard/i, 'Tutorial', null], [/solve|solver/i, 'Level-Löser', null], + [/verify|selftest/i, 'Selbsttest/Verifier', null], [/i18n|lang|locali|translat/i, 'Übersetzung', kind === 'mobile' ? 'i18n.ts' : null], + [/leaderboard|highscore|scores?\b/i, 'Bestenliste', 'Kit.scores'], [/audio|sound|music/i, 'Audio', 'Kit.createAudio / audio.ts'], + [/save|storage|persist/i, 'Speichern', 'Kit.saveSlot / save.ts'], [/particle|fx|tween|ease|juice/i, 'Effekte', 'Kit.fx'], + [/input|controls?|keys?\b|gamepad/i, 'Eingabe', 'Kit.input'], [/online|cloud|auth|firebase/i, 'Online/Cloud', null], + [/mission|daily|quest/i, 'Missionen/Daily', null], [/settings?|options|config/i, 'Einstellungen', null], + [/wiki|help/i, 'Hilfe/Wiki', null], [/debug|devshot|cheat/i, 'Debug-Werkzeug', null], + [/number|format/i, 'Zahlenformat', 'Kit.fmt'], [/rng|random/i, 'Zufall', 'Kit.rng'], + [/window|layered/i, 'Fenster-Helfer (Desktop)', null], [/screenshot|store.?screen|itch|make_images/i, 'Store-/itch-Bilder', '_Tools/Itch'], +]; +const cands = []; +for (const f of own) { + if (isKit(f) || f.lines < 40 || /(^|\\)(sprite-?gen(erator)?|spritegenerator|design-gen)\\/i.test(f.rel)) continue; + const base = path.basename(f.rel, path.extname(f.rel)); + const g = GENERIC.find(([re]) => re.test(base)); + if (!g) continue; + cands.push(`${f.rel} (${f.lines} Z.) ${g[1]}: ${g[2] ? `Library hat ${g[2]} – vergleichen` : 'FEHLT in Library → Kandidat'}`); +} +cands.sort((a, b) => (b.includes('FEHLT') - a.includes('FEHLT'))); + +// ---- hygiene ------------------------------------------------------------------------------ +const git = (...a) => { try { return execFileSync('git', ['-C', root, ...a], { encoding: 'utf8', timeout: 8000, stdio: ['ignore', 'pipe', 'ignore'] }).trim(); } catch { return null; } }; +const issues = []; +const isRepo = git('rev-parse', '--is-inside-work-tree') === 'true'; +if (!isRepo) issues.push('kein git-Repository'); +else { + const dirty = (git('status', '--porcelain') || '').split('\n').filter(Boolean).length; + const last = git('log', '-1', '--format=%cr'); + // no remote check: local git is enough (Michael's decision) + if (dirty) issues.push(`${dirty} ungesicherte Änderungen (letzter Commit ${last || '–'})`); + const tracked = (git('ls-files', '-z') || '').split('\0').filter(Boolean); + const big = tracked.map(t => { try { return [t, fs.statSync(path.join(root, t)).size]; } catch { return [t, 0]; } }) + .filter(([, s]) => s > 10e6).sort((a, b) => b[1] - a[1]); + if (big.length) issues.push(`große Dateien in git: ${big.slice(0, 3).map(([t, s]) => `${t} ${(s / 1e6).toFixed(0)} MB`).join(', ')}`); +} +for (const f of ['README.md', 'CLAUDE.md', '.gitignore']) if (!has(f)) issues.push(`${f} fehlt`); +// credits standard: "Michael Media" + Discord link visible in the app (source or language files) +{ + const appSrc = own.filter(f => !isGen(f) && !/(^|\\)docs\\/i.test(f.rel)); + let langText = ''; + for (const d of ['Languages', 'lang', 'locales', 'i18n']) { + if (!has(d)) continue; + try { for (const n of fs.readdirSync(path.join(root, d))) if (n.endsWith('.json')) langText += fs.readFileSync(path.join(root, d, n), 'utf8'); } catch { /* unreadable */ } + } + const inApp = re => re.test(langText) || appSrc.some(f => re.test(f.text)); + const discordInApp = inApp(/discord\.gg\//i); + if (!inApp(/michael\s*media/i)) issues.push('Credits fehlen im Spiel ("© Jahr Michael Media")'); + if (!discordInApp) issues.push('Discord-Link fehlt im Spiel (https://discord.gg/Ej4JPmCZva)'); + if (has('README.md') && !/michael\s*media/i.test(fs.readFileSync(path.join(root, 'README.md'), 'utf8'))) issues.push('README ohne "Michael Media"'); +} +if (!has('.dashboard.json')) issues.push('.dashboard.json fehlt (Projekt-Dashboard)'); +if (pkg && Object.keys(deps).length && !has('node_modules')) issues.push('node_modules fehlt (npm install)'); +if (has('.gitignore')) { + const gi = fs.readFileSync(path.join(root, '.gitignore'), 'utf8'); + for (const [dir, pat] of [['node_modules', /node_modules/], ['sprite-generator/output', /output/], ['release', /release/], ['bin', /\bbin\b/]]) { + if (has(dir.split('/')[0]) && has(dir) && !pat.test(gi)) issues.push(`${dir}/ nicht in .gitignore`); + } +} +// generator: own copy of the ComfyGen scripts? +for (const g of ['sprite-generator', 'Spritegenerator', 'design-gen', 'sprite-gen']) { + if (!has(g)) continue; + const gen = path.join(root, g); + const cmd = path.join(gen, 'gen.cmd'); + const usesTools = fs.existsSync(cmd) && /_Tools\\ComfyGen/i.test(fs.readFileSync(cmd, 'utf8')); + const pyCount = fs.readdirSync(gen).filter(f => f.endsWith('.py')).length; + if (!usesTools && pyCount > 3) issues.push(`${g}: eigene Generator-Kopie (${pyCount} .py) statt _Tools\\ComfyGen`); +} +// ---- ComfyUI: could graphics / sound / icon come from ComfyGen? ------------------------------ +const comfy = []; +{ + const MEDIA_IMG = /\.(png|jpe?g|webp|gif|bmp)$/i, MEDIA_SND = /\.(mp3|ogg|wav|flac)$/i; + let imgs = 0, snds = 0, icon = false; + (function walk(dir, depth) { + let ents = []; + try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; } + for (const e of ents) { + if (e.isDirectory()) { + if (depth < 7 && !SKIP.test(e.name) && !/^(sprite-?gen(erator)?|spritegenerator|design-gen|docs|screenshots|android|ios)$/i.test(e.name)) walk(path.join(dir, e.name), depth + 1); + } else if (MEDIA_IMG.test(e.name)) { imgs++; if (/^(app[_-]?)?icon|^ic_launcher|^logo/i.test(e.name)) icon = true; } + else if (MEDIA_SND.test(e.name)) snds++; + else if (/\.ico$/i.test(e.name)) icon = true; + } + })(root, 0); + const genDir = ['sprite-generator', 'Spritegenerator', 'design-gen', 'sprite-gen'].find(has); + const app = code.filter(f => !isGen(f)); + const count = re => app.reduce((n, f) => n + (f.text.match(re) || []).length, 0); + const drawn = count(/\b(fillRect|strokeRect|arc|ellipse|bezierCurveTo|FillRectangle|FillEllipse|DrawRectangle|DrawEllipse|pygame\.draw\.\w+|DrawCircle|DrawRect)\s*\(/g); + const synth = count(/createOscillator|\btone\(|OscillatorNode|winsound\.Beep|Console\.Beep|pygame\.sndarray|SineWave|SignalGenerator/g); + const voiceText = app.some(f => /\b(dialog|dialogue|story|narrat|speech|voice)\b/i.test(f.rel)); + if (!genDir) comfy.push(`kein ComfyGen-Generator – \`_Tools\\ComfyGen\\template\` → \`sprite-generator\\\` (gen generate/adopt/generate_audio)`); + else { + let prompts = 0, audio = 0; + try { prompts = (fs.readFileSync(path.join(root, genDir, 'prompts.py'), 'utf8').match(/^\s*\(\s*["']/gm) || []).length; } catch { /* none */ } + try { audio = (fs.readFileSync(path.join(root, genDir, fs.readdirSync(path.join(root, genDir)).find(n => /^audio.*\.py$/i.test(n)) || 'audio.py'), 'utf8').match(/^\s*\(\s*["']/gm) || []).length; } catch { /* none */ } + comfy.push(`Generator ${genDir}: ${prompts} Bild-Prompts, ${audio} Audio-Einträge · im Projekt ${imgs} Bilder, ${snds} Sounds`); + } + if (!icon) comfy.push('kein App-Icon → `gen generate icon` + `gen adopt --size 512 icon`'); + if (drawn > 40 && imgs < 10) comfy.push(`Grafik meist gezeichnet (${drawn} Zeichenbefehle, ${imgs} Bilder) → Sprites/Hintergründe per ComfyUI`); + if (snds === 0 && (synth || stack.some(s => /HTML|Capacitor|Unity|C\+\+|Python/.test(s)))) comfy.push(`keine Sounddateien${synth ? ` (${synth}× Synth-Ton im Code)` : ''} → Musik/SFX mit \`gen generate_audio\``); + else if (synth > 5 && snds < 5) comfy.push(`${synth}× Synth-Ton, nur ${snds} Sounddateien → echte SFX per \`gen generate_audio\``); + if (voiceText) comfy.push('Story/Dialog-Dateien gefunden → Erzählstimmen mit `gen generate_voice` möglich'); + // is the server up? (only informative, 800 ms) + try { const r = await fetch('http://127.0.0.1:8188/system_stats', { signal: AbortSignal.timeout(800) }); comfy.push(`ComfyUI-Server: ${r.ok ? 'läuft' : 'antwortet nicht richtig'}`); } + catch { comfy.push('ComfyUI-Server: aus (bei Bedarf `D:\\ComfyUI` starten)'); } +} + +// release older than the code +const newestSrc = Math.max(0, ...own.filter(f => !isGen(f)).map(f => f.mtime)); +for (const d of ['release', 'dist']) { + const dp = path.join(root, d); + if (!fs.existsSync(dp)) continue; + let newest = 0; + (function w(x, depth) { for (const e of fs.readdirSync(x, { withFileTypes: true })) { const p = path.join(x, e.name); if (e.isDirectory()) { if (depth < 3) w(p, depth + 1); } else newest = Math.max(newest, fs.statSync(p).mtimeMs); } })(dp, 0); + const days = (newestSrc - newest) / 864e5; + if (newest && days > 1) issues.push(`${d}/ ist ${Math.round(days)} Tage älter als der Code (neu bauen?)`); +} +const todo = own.reduce((n, f) => n + (f.text.match(/\b(TODO|FIXME|HACK|XXX)\b/g) || []).length, 0); +const logs = code.filter(f => /\.(js|ts|tsx|jsx)$/.test(f.rel) && !isGen(f)).reduce((n, f) => n + (f.text.match(/console\.log\(/g) || []).length, 0); +if (todo) issues.push(`${todo}× TODO/FIXME im Code`); +if (logs > 10) issues.push(`${logs}× console.log`); +const testDir = ['tests', 'test', 'tools', '__tests__'].some(has) || own.some(f => /\.(test|spec)\.|selftest|verify/i.test(f.rel)); +if (!testDir && code.length > 5) issues.push('keine Tests/Selbsttests gefunden'); +if (kind === 'web' && !has('game/kit') && !has('kit')) issues.push('nutzt web/kit nicht (Vorlage webgame: Release-Kette, Highscores, exe)'); +if (kind === 'mobile' && !has('src/kit')) issues.push('nutzt mobile/kit nicht'); + +// ---- report ------------------------------------------------------------------------------- +const total = code.reduce((n, f) => n + f.lines, 0); +const big = [...code].filter(f => !isGen(f)).sort((a, b) => b.lines - a.lines).filter(f => f.lines > 800); +const out = []; +out.push(`# ${name} [${stack.join(', ') || '?'}] ${code.length} Dateien, ${total.toLocaleString('de-DE')} Zeilen (${Object.entries(ext).sort((a, b) => b[1] - a[1]).slice(0, 4).map(([e, n]) => `${e} ${n}`).join(', ')})`); +if (big.length) out.push(`Groß (>800 Z., aufteilen?): ${big.slice(0, TOP).map(f => `${f.rel} ${f.lines}`).join(' · ')}`); +if (kitLines.length) out.push('Kit: ' + kitLines.join(' | ')); +const ORIGIN = { 'xp-battleship': 'mobile/kit', pipefix: 'web/kit + web/template', 'byte path': 'web/kit (Audio, Eingabe, Loop)' }; +if (ORIGIN[name.toLowerCase()]) out.push(`Hinweis: Ursprung von ${ORIGIN[name.toLowerCase()]} – Umstellung aufs Kit nur bei Bedarf, eher Neues von hier in die Library holen.`); +if (comfy.length) { out.push('ComfyUI:'); for (const c of comfy) out.push('- ' + c); } +if (reinvent.length) { out.push('Selbst gebaut, Kit kann es:'); for (const r of reinvent.slice(0, TOP)) out.push('- ' + r); } +if (cands.length && !kind) { + // stacks without a Library kit (C++, C#, Kotlin, Python): one line, details with --all + const missing = cands.filter(c => c.includes('FEHLT')); + const groups = [...new Set(missing.map(c => c.split(': ')[0].replace(/^.*\) /, '')))]; + out.push(`Library hat kein Kit für ${stack.join('/') || 'diesen Stack'}: ${missing.length} allgemein wirkende Module (${groups.slice(0, 6).join(', ')}), z. B. ${missing.slice(0, 3).map(c => c.split(' (')[0]).join(', ')}${ALL ? '' : ' (--all = Liste)'}`); + if (ALL) for (const c of cands) out.push('- ' + c); +} else if (cands.length) { out.push('Library-Kandidaten:'); for (const c of cands.slice(0, TOP)) out.push('- ' + c); if (cands.length > TOP) out.push(` (+${cands.length - TOP} weitere, --all)`); } +if (issues.length) { out.push('Hygiene:'); for (const i of issues) out.push('- ' + i); } +if (!reinvent.length && !cands.length && !issues.length) out.push('Keine Auffälligkeiten.'); +console.log(out.join('\n')); diff --git a/Library/web/kit/kit-audio.js b/Library/web/kit/kit-audio.js new file mode 100644 index 0000000..cdaad0e --- /dev/null +++ b/Library/web/kit/kit-audio.js @@ -0,0 +1,157 @@ +/* Kit audio (v1) - WebAudio for HTML games. From _Tools\Library\web\kit. Needs kit-core.js. + + const audio = Kit.createAudio({ + prefix: 'mygame', // localStorage keys mygame.muted / .music / .sfx + dir: 'assets/Audio/', ext: '.mp3', // where ComfyGen adopt_audio puts the files + files: ['sfx_click', 'sfx_win', 'music_game'], + throttle: { sfx_step: 60 }, // optional min gap in ms per clip + }); + audio.sfx('sfx_click') play once (silent if missing / not decoded yet) + audio.music('music_game') loop as music (switching tracks fades the old one) + const h = audio.loop('sfx_flow', 0.5); h.stop() looping effect + audio.tone(880, 0.1) / audio.noise(0.2) synth fallback sounds, no files needed + audio.toggleMute() / audio.setVolume(music, sfx) / audio.muted / audio.musicVol / audio.sfxVol + + Best effort everywhere: missing files, a blocked AudioContext or no WebAudio never throw. + The context is created on the first pointer/key press (autoplay policy) - nothing to call. */ +(function (root) { + 'use strict'; + const Kit = (root.Kit = root.Kit || {}); + + Kit.createAudio = (opt = {}) => { + const st = Kit.store(opt.prefix || 'kit'); + const dir = opt.dir || 'assets/Audio/', ext = opt.ext || '.mp3'; + const files = opt.files || [], throttle = opt.throttle || {}; + let ctx = null, musicGain = null, sfxGain = null, musicSrc = null, musicName = null, wantMusic = null; + const buffers = {}, loading = {}, last = {}; + const api = { + muted: st.get('muted', false), + musicVol: st.get('music', 0.35), + sfxVol: st.get('sfx', 0.8), + }; + // slider 0..1 -> gain; squared so the low end of a slider is fine-grained + const g = v => (api.muted ? 0 : v * v); + + function unlock() { + if (ctx) { if (ctx.state === 'suspended') ctx.resume().catch(() => {}); return; } + try { + ctx = new (root.AudioContext || root.webkitAudioContext)(); + musicGain = ctx.createGain(); musicGain.gain.value = g(api.musicVol); musicGain.connect(ctx.destination); + sfxGain = ctx.createGain(); sfxGain.gain.value = g(api.sfxVol); sfxGain.connect(ctx.destination); + for (const n of files) load(n); + if (wantMusic) api.music(wantMusic); + } catch (e) { ctx = null; } + } + if (typeof document !== 'undefined') { + for (const ev of ['pointerdown', 'keydown', 'touchstart']) addEventListener(ev, unlock, { capture: true, passive: true }); + // Android leaves a context suspended after backgrounding unless it is resumed by hand + document.addEventListener('visibilitychange', () => { + if (!ctx) return; + if (document.hidden) ctx.suspend().catch(() => {}); else ctx.resume().catch(() => {}); + }); + } + + function load(name) { + if (!ctx) return Promise.resolve(null); + if (buffers[name]) return Promise.resolve(buffers[name]); + if (loading[name]) return loading[name]; + return (loading[name] = Kit.loadBytes(Kit.asset(dir + name + ext)) + .then(b => ctx.decodeAudioData(b)) + .then(buf => (buffers[name] = buf)) + .catch(() => null) + .finally(() => { delete loading[name]; })); + } + + function start(buf, vol, loop, bus) { + const src = ctx.createBufferSource(); + src.buffer = buf; src.loop = loop; + const gn = ctx.createGain(); gn.gain.value = vol; + src.connect(gn).connect(bus); + src.start(); + src.gainNode = gn; + return src; + } + function fadeStop(src) { + if (!src || !ctx) return; + try { src.gainNode.gain.setTargetAtTime(0, ctx.currentTime, 0.08); src.stop(ctx.currentTime + 0.4); } catch (e) { /* stopped */ } + } + + api.sfx = (name, vol = 1) => { + if (!ctx || api.muted) return; + if (ctx.state === 'suspended') ctx.resume().catch(() => {}); + const gap = throttle[name] || 0, now = performance.now(); + if (gap && now - (last[name] || 0) < gap) return; + last[name] = now; + // first use of a clip that is still decoding: play it once it is ready instead of dropping it + if (buffers[name]) start(buffers[name], vol, false, sfxGain); + else load(name).then(b => { if (b && !api.muted) start(b, vol, false, sfxGain); }); + }; + + api.loop = (name, vol = 1) => { + const h = { src: null, stopped: false, stop() { h.stopped = true; fadeStop(h.src); h.src = null; } }; + if (!ctx) return h; + load(name).then(b => { if (b && !h.stopped) h.src = start(b, vol, true, sfxGain); }); + return h; + }; + + api.music = name => { + wantMusic = name; + if (!ctx || musicName === name) return; + musicName = name; + load(name).then(b => { + if (!b || musicName !== name) { if (!b && musicName === name) musicName = null; return; } + fadeStop(musicSrc); + musicSrc = start(b, 1, true, musicGain); + }); + }; + api.stopMusic = () => { wantMusic = null; musicName = null; fadeStop(musicSrc); musicSrc = null; }; + + function apply() { + if (musicGain) musicGain.gain.value = g(api.musicVol); + if (sfxGain) sfxGain.gain.value = g(api.sfxVol); + } + api.toggleMute = () => { api.muted = !api.muted; st.set('muted', api.muted); apply(); return api.muted; }; + api.setVolume = (music, sfx) => { + if (music != null) { api.musicVol = Kit.clamp(+music || 0, 0, 1); st.set('music', api.musicVol); } + if (sfx != null) { api.sfxVol = Kit.clamp(+sfx || 0, 0, 1); st.set('sfx', api.sfxVol); } + if (api.muted && (music > 0 || sfx > 0)) { api.muted = false; st.set('muted', false); } + apply(); + }; + // duck music under a big moment (ramped, no clicks) + api.duck = (on, secs = 0.2) => { + if (!ctx || !musicGain) return; + const t = ctx.currentTime; + musicGain.gain.cancelScheduledValues(t); + musicGain.gain.setValueAtTime(musicGain.gain.value, t); + musicGain.gain.linearRampToValueAtTime(on ? 0 : g(api.musicVol), t + secs); + }; + api.suspend = () => { if (ctx) ctx.suspend().catch(() => {}); }; + api.resume = () => { if (ctx && !document.hidden) ctx.resume().catch(() => {}); }; + api.unlock = unlock; + + // ---- synth (placeholder sounds until ComfyGen clips exist) -------------------------- + api.tone = (freq, dur = 0.1, type = 'square', vol = 0.3, slide = 0, delay = 0) => { + if (!ctx || api.muted) return; + const t = ctx.currentTime + delay; + const o = ctx.createOscillator(), gn = ctx.createGain(); + o.type = type; o.frequency.setValueAtTime(freq, t); + if (slide) o.frequency.exponentialRampToValueAtTime(Math.max(30, freq + slide), t + dur); + gn.gain.setValueAtTime(vol, t); gn.gain.exponentialRampToValueAtTime(0.001, t + dur); + o.connect(gn).connect(sfxGain); o.start(t); o.stop(t + dur + 0.02); + }; + api.noise = (dur = 0.2, vol = 0.3, cutoff = 1200, delay = 0) => { + if (!ctx || api.muted) return; + const t = ctx.currentTime + delay, len = Math.floor(ctx.sampleRate * dur); + const buf = ctx.createBuffer(1, len, ctx.sampleRate), d = buf.getChannelData(0); + for (let i = 0; i < len; i++) d[i] = (Math.random() * 2 - 1) * (1 - i / len); + const src = ctx.createBufferSource(), f = ctx.createBiquadFilter(), gn = ctx.createGain(); + src.buffer = buf; f.type = 'lowpass'; f.frequency.value = cutoff; gn.gain.value = vol; + src.connect(f).connect(gn).connect(sfxGain); src.start(t); + }; + // little arpeggio: audio.arp([523, 659, 784], 0.12) + api.arp = (freqs, step = 0.08, type = 'square', vol = 0.18) => + freqs.forEach((f, i) => api.tone(f, step * 1.6, type, vol, 0, i * step)); + + return api; + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/Library/web/kit/kit-core.js b/Library/web/kit/kit-core.js new file mode 100644 index 0000000..1bd0b67 --- /dev/null +++ b/Library/web/kit/kit-core.js @@ -0,0 +1,142 @@ +/* Kit core (v1) - from D:\Oculusquest\Projekt\_Tools\Library\web\kit. + Do not fork this copy inside a project: improve it in the Library and re-copy with + new-project.ps1 -UpdateKit. Classic script (no ES module) so the game also runs from file://. + + Kit.$(id) document.getElementById + Kit.asset(path) path, or the data: URI the single-file build embedded + Kit.loadBytes(url) ArrayBuffer (works for data: URIs and files) + Kit.images(names, dir, ext) { name: Image } - img.ok is true once loaded + Kit.store(prefix) safe localStorage JSON get/set/del + Kit.saveSlot(key, defaults, opt) versioned save with backup copy + defaults merge + Kit.rng(seed) seeded random() in [0,1) (mulberry32) + Kit.clamp / lerp / shuffle / pick / fmt +*/ +(function (root) { + 'use strict'; + const Kit = (root.Kit = root.Kit || {}); + Kit.version = 1; + Kit.$ = id => document.getElementById(id); + + // ---- assets --------------------------------------------------------------------------- + // build-web.mjs puts every asset into window.KIT_ASSETS as a data: URI, so the release + // HTML works from file:// and on any web host without a folder next to it. + Kit.asset = path => (root.KIT_ASSETS && root.KIT_ASSETS[path]) || path; + + Kit.loadBytes = url => { + if (url.startsWith('data:')) { + const bin = atob(url.slice(url.indexOf(',') + 1)); + const buf = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i); + return Promise.resolve(buf.buffer); + } + return fetch(url).then(r => (r.ok ? r.arrayBuffer() : Promise.reject(new Error(r.status + ' ' + url)))); + }; + + // Missing images are fine: draw a fallback shape while !img.ok. + Kit.images = (names, dir = 'assets/Sprites/', ext = '.png') => { + const out = {}; + for (const n of names) { + const im = new Image(); + im.ok = false; + im.onload = () => { im.ok = true; }; + im.src = Kit.asset(dir + n + ext); + out[n] = im; + } + return out; + }; + + // ---- storage -------------------------------------------------------------------------- + // Every access is wrapped: private mode, blocked storage or a full quota must not crash. + Kit.store = prefix => { + const p = prefix ? prefix + '.' : ''; + return { + get(k, d) { + try { const v = localStorage.getItem(p + k); return v == null ? d : JSON.parse(v); } catch (e) { return d; } + }, + set(k, v) { + try { localStorage.setItem(p + k, JSON.stringify(v)); return true; } catch (e) { return false; } + }, + del(k) { try { localStorage.removeItem(p + k); } catch (e) { /* ignore */ } }, + }; + }; + + /* Save slot for game progress. + const slot = Kit.saveSlot('mygame.save', () => ({ level: 1, best: {} }), { version: 2, migrate }) + let save = slot.load(); ... slot.save(save); + - defaults() is a function so every load gets fresh nested objects. + - Loaded data is merged over defaults (one level deep for plain objects), so fields added + in a later version exist in old saves. + - migrate(data, fromVersion) runs when the stored version is older; return the data. + - Every backupEvery-th save also writes a backup; a corrupt primary falls back to it. + - slot.failed() turns true once a write failed - tell the player once. */ + Kit.saveSlot = (key, defaults, opt = {}) => { + const version = opt.version || 1, every = opt.backupEvery || 10; + let since = 0, failed = false; + const isObj = v => v && typeof v === 'object' && !Array.isArray(v); + function merge(d, s) { + const out = Object.assign({}, d, s); + for (const k of Object.keys(d)) if (isObj(d[k]) && isObj(s[k])) out[k] = Object.assign({}, d[k], s[k]); + return out; + } + function read(k) { + try { + const raw = localStorage.getItem(k); + if (!raw) return null; + const parsed = JSON.parse(raw); + if (!isObj(parsed)) return null; + const from = typeof parsed._v === 'number' ? parsed._v : 1; + let s = merge(defaults(), parsed); + if (from < version && opt.migrate) s = opt.migrate(s, from) || s; + s._v = version; + return s; + } catch (e) { return null; } + } + return { + load() { return read(key) || read(key + '.bak') || Object.assign(defaults(), { _v: version }); }, + save(data) { + data._v = version; + try { + const json = JSON.stringify(data); + localStorage.setItem(key, json); + if (++since >= every) { since = 0; localStorage.setItem(key + '.bak', json); } + return true; + } catch (e) { failed = true; return false; } + }, + clear() { try { localStorage.removeItem(key); localStorage.removeItem(key + '.bak'); } catch (e) { /* ignore */ } }, + failed: () => failed, + }; + }; + + // ---- math / random -------------------------------------------------------------------- + Kit.rng = seed => { + let a = seed >>> 0 || 1; + return () => { + a = (a + 0x6d2b79f5) | 0; + let t = Math.imul(a ^ (a >>> 15), 1 | a); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; + }; + Kit.clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v); + Kit.lerp = (a, b, t) => a + (b - a) * t; + Kit.pick = (arr, rnd = Math.random) => arr[Math.floor(rnd() * arr.length)]; + Kit.shuffle = (arr, rnd = Math.random) => { + for (let i = arr.length - 1; i > 0; i--) { + const j = Math.floor(rnd() * (i + 1)); + [arr[i], arr[j]] = [arr[j], arr[i]]; + } + return arr; + }; + // 1234567 -> "1.23M" (idle games); below 10 000 plain with thousands separator + Kit.fmt = n => { + if (!Number.isFinite(n)) return '0'; + const a = Math.abs(n); + if (a < 1e4) return Math.round(n).toLocaleString('en-US'); + const units = ['K', 'M', 'B', 'T', 'Qa', 'Qi']; + let u = -1, v = a; + while (v >= 1000 && u < units.length - 1) { v /= 1000; u++; } + return (n < 0 ? '-' : '') + (v >= 100 ? v.toFixed(0) : v >= 10 ? v.toFixed(1) : v.toFixed(2)) + units[u]; + }; + + if (typeof module !== 'undefined' && module.exports) module.exports = Kit; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/Library/web/kit/kit-fx.js b/Library/web/kit/kit-fx.js new file mode 100644 index 0000000..0e4aaaf --- /dev/null +++ b/Library/web/kit/kit-fx.js @@ -0,0 +1,72 @@ +/* Kit fx (v1) - small juice helpers for canvas games. From _Tools\Library\web\kit. + + const fx = Kit.fx(); + fx.burst(x, y, '#ffd83a', 16, 180) particles (count, speed px/s) + fx.float(x, y, '+10', '#fff') rising, fading text + fx.shake(8) screen shake strength in px (decays) + fx.update(dt) in loop update + fx.apply(ctx) ... draw world ... ctx.restore() (apply saves + offsets for shake) + fx.draw(ctx) particles + texts on top + Kit.tween(from, to, t, Kit.ease.outBack) */ +(function (root) { + 'use strict'; + const Kit = (root.Kit = root.Kit || {}); + + Kit.ease = { + linear: t => t, + outQuad: t => 1 - (1 - t) * (1 - t), + inOutQuad: t => (t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2), + outCubic: t => 1 - Math.pow(1 - t, 3), + outBack: t => 1 + 2.70158 * Math.pow(t - 1, 3) + 1.70158 * Math.pow(t - 1, 2), + outElastic: t => (t === 0 || t === 1 ? t : Math.pow(2, -10 * t) * Math.sin((t * 10 - 0.75) * (2 * Math.PI / 3)) + 1), + }; + Kit.tween = (a, b, t, ease = Kit.ease.outQuad) => a + (b - a) * ease(Math.max(0, Math.min(1, t))); + + Kit.fx = () => { + const parts = [], texts = []; + let shake = 0; + return { + burst(x, y, color = '#fff', n = 14, speed = 160, life = 0.6) { + for (let i = 0; i < n; i++) { + const a = Math.random() * Math.PI * 2, v = speed * (0.4 + Math.random() * 0.8); + parts.push({ x, y, vx: Math.cos(a) * v, vy: Math.sin(a) * v, life, max: life, color, r: 2 + Math.random() * 2.5 }); + } + }, + float(x, y, text, color = '#fff', size = 18) { texts.push({ x, y, text, color, size, life: 0.9, max: 0.9 }); }, + shake(px) { shake = Math.max(shake, px); }, + update(dt) { + for (let i = parts.length - 1; i >= 0; i--) { + const p = parts[i]; + p.life -= dt; if (p.life <= 0) { parts.splice(i, 1); continue; } + p.x += p.vx * dt; p.y += p.vy * dt; p.vx *= 0.96; p.vy = p.vy * 0.96 + 220 * dt; + } + for (let i = texts.length - 1; i >= 0; i--) { + const t = texts[i]; + t.life -= dt; if (t.life <= 0) { texts.splice(i, 1); continue; } + t.y -= 40 * dt; + } + shake = Math.max(0, shake - 40 * dt); + }, + apply(ctx) { + ctx.save(); + if (shake > 0) ctx.translate((Math.random() * 2 - 1) * shake, (Math.random() * 2 - 1) * shake); + }, + draw(ctx) { + for (const p of parts) { + ctx.globalAlpha = p.life / p.max; + ctx.fillStyle = p.color; + ctx.beginPath(); ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2); ctx.fill(); + } + ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + for (const t of texts) { + ctx.globalAlpha = Math.min(1, t.life / t.max * 2); + ctx.font = `bold ${t.size}px system-ui, sans-serif`; + ctx.lineWidth = 4; ctx.strokeStyle = 'rgba(0,0,0,.6)'; ctx.strokeText(t.text, t.x, t.y); + ctx.fillStyle = t.color; ctx.fillText(t.text, t.x, t.y); + } + ctx.globalAlpha = 1; + }, + clear() { parts.length = 0; texts.length = 0; shake = 0; }, + }; + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/Library/web/kit/kit-host.js b/Library/web/kit/kit-host.js new file mode 100644 index 0000000..20278a3 --- /dev/null +++ b/Library/web/kit/kit-host.js @@ -0,0 +1,39 @@ +/* Kit host (v1) - window control for the desktop exe (WebView2 launcher) and the browser. + From _Tools\Library\web\kit. + + Kit.host.exe true inside the launcher (Launcher.csproj); gets class "exe" + Kit.host.fullscreen() exe: toggle borderless-maximised; browser: Fullscreen API + Kit.host.minimize() / Kit.host.quit() exe only (no-ops in the browser) + Kit.host.dragArea(el) mousedown on el itself drags the window, double-click = fullscreen + + The launcher draws no title bar; put minimise/fullscreen/close buttons into the page and + show them only for html.exe (template: #winctl). */ +(function (root) { + 'use strict'; + const Kit = (root.Kit = root.Kit || {}); + const wv = root.chrome && root.chrome.webview; + const send = c => { if (wv) wv.postMessage(c); }; + + const host = { + exe: !!wv, + send, + fullscreen() { + if (wv) return send('maximize'); + if (document.fullscreenElement) document.exitFullscreen().catch(() => {}); + else document.documentElement.requestFullscreen().catch(() => {}); + }, + minimize: () => send('minimize'), + quit: () => send('quit'), + dragArea(el) { + if (!wv) return; + el.addEventListener('mousedown', e => { if (e.button === 0 && e.target === el) send('drag'); }); + el.addEventListener('dblclick', e => { if (e.target === el) send('maximize'); }); + }, + }; + Kit.host = host; + if (wv && typeof document !== 'undefined') document.documentElement.classList.add('exe'); + // F11 in the browser: same toggle as the exe (the launcher handles F11 / Alt+Enter itself) + if (!wv && typeof addEventListener !== 'undefined') { + addEventListener('keydown', e => { if (e.key === 'F11') { e.preventDefault(); host.fullscreen(); } }); + } +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/Library/web/kit/kit-i18n.js b/Library/web/kit/kit-i18n.js new file mode 100644 index 0000000..be73653 --- /dev/null +++ b/Library/web/kit/kit-i18n.js @@ -0,0 +1,62 @@ +/* Kit i18n (v1) - texts in several languages for HTML games. From _Tools\Library\web\kit. + Needs kit-core.js. Dictionaries live in game/lang.js (a script, not JSON: file:// cannot fetch). + + game/lang.js: window.LANG = { en: { play: 'Play', score: 'Score {n}' }, de: { play: 'Spielen' } }; + const L = Kit.i18n(window.LANG, { prefix: 'mygame' }); + L.t('score', { n: 5 }) "Score 5" - missing key: English, then the key itself (visible = easy to spot) + L.lang / L.langs current language / ['en', 'de'] + L.set('de') switch + remember; re-fills data-i18n elements, calls onChange listeners + L.next() cycle to the next language (one "English / Deutsch" button) + L.apply(root) fills [data-i18n="key"] (text), [data-i18n-html] (HTML), [data-i18n-title], + [data-i18n-placeholder]; runs once at start and after every set() + L.onChange(fn) re-render menus/HUD after a switch + Start language: saved choice, else browser language if there is a dictionary, else the first one. */ +(function (root) { + 'use strict'; + const Kit = (root.Kit = root.Kit || {}); + + Kit.i18n = (dicts, opt = {}) => { + const langs = Object.keys(dicts || {}); + if (!langs.length) throw new Error('Kit.i18n: no dictionaries (game/lang.js loaded?)'); + const st = Kit.store(opt.prefix || 'kit'); + const fallback = dicts.en ? 'en' : langs[0]; + const listeners = []; + const browser = (typeof navigator !== 'undefined' && (navigator.language || '').slice(0, 2).toLowerCase()) || ''; + const saved = st.get('lang', null); + const api = { + langs, + lang: langs.includes(saved) ? saved : langs.includes(browser) ? browser : fallback, + }; + + api.t = (key, vars) => { + let s = dicts[api.lang]?.[key] ?? dicts[fallback]?.[key] ?? key; + if (vars) for (const [k, v] of Object.entries(vars)) s = s.split(`{${k}}`).join(String(v)); + return s; + }; + + api.apply = (scope = typeof document !== 'undefined' ? document : null) => { + if (!scope) return; + for (const el of scope.querySelectorAll('[data-i18n]')) el.textContent = api.t(el.dataset.i18n); + for (const el of scope.querySelectorAll('[data-i18n-html]')) el.innerHTML = api.t(el.dataset.i18nHtml); + for (const el of scope.querySelectorAll('[data-i18n-title]')) el.title = api.t(el.dataset.i18nTitle); + for (const el of scope.querySelectorAll('[data-i18n-placeholder]')) el.placeholder = api.t(el.dataset.i18nPlaceholder); + if (typeof document !== 'undefined') document.documentElement.lang = api.lang; + }; + + api.set = l => { + if (!langs.includes(l) || l === api.lang) return; + api.lang = l; + st.set('lang', l); + api.apply(); + for (const fn of listeners) fn(l); + }; + api.next = () => api.set(langs[(langs.indexOf(api.lang) + 1) % langs.length]); + api.onChange = fn => { listeners.push(fn); }; + + if (typeof document !== 'undefined') { + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => api.apply()); + else api.apply(); + } + return api; + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/Library/web/kit/kit-input.js b/Library/web/kit/kit-input.js new file mode 100644 index 0000000..494fc0a --- /dev/null +++ b/Library/web/kit/kit-input.js @@ -0,0 +1,73 @@ +/* Kit input (v1) - keyboard + touch buttons mapped to actions. From _Tools\Library\web\kit. + + const input = Kit.input({ + keys: { ArrowUp: 'up', w: 'up', ArrowDown: 'down', s: 'down', ArrowLeft: 'left', a: 'left', + ArrowRight: 'right', d: 'right', ' ': 'action', p: 'pause', Escape: 'pause', m: 'mute' }, + onPress(action, e) {}, // first press only (no key repeat) + onRelease(action) {}, + }); + input.down('left') is it held right now? + input.latest(['up','right','down','left']) most recently pressed of these that is still held + input.consume('action') true once per press (polling style inside update()) + + Touch buttons: any element with data-action="left" works like the key (pointer capture, + so sliding off the button releases it). Typing into /