diff --git a/AGENTS.md b/AGENTS.md index 9026946..514202f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,218 +1,120 @@ -# OGS Mahjong (`mj`) +# OGS applications (`mj`) -A macOS SwiftUI app for **OGS Mahjong**, built on the **Dialect v4** declarative -reactive engine (see the sibling `../dialect` repo — this project is a -downstream consumer of its code generator). +Native SwiftUI applications using the Dialect v4 declarative reactive engine. +Version: `2.0.0`. Remote: `https://git.opengamestudio.org/mahjong/mahjong`. -Business logic lives in `dialect.yml` (YAML). A generator turns it into -`game/ver-mac/src/dialect.swift` (the runtime engine + `struct F` field -constants + component/should/effect registration). The Swift app shell -(`GameApp`/`AppDelegate`) and the SwiftUI views live outside the generated file -and talk to the engine through generated functions like `rootSet(...)`. +## Current status -Remote: `https://git.opengamestudio.org/mahjong/mahjong` · Version: `2.0.0` +- `ogs-blue/` is the active minimal graphics example for macOS and iOS: a solid + blue raylib background with a SwiftUI overlay. It has no model/texture/shadow + scene; rlgl still creates its default internal GPU resources. +- `ogs-mahjong/` contains the macOS Mahjong scaffold and counter-template logic; + Mahjong gameplay has not been implemented. +- `ogs-chkgfx/` is a companion graphics scaffold with macOS/iOS project files. + Older targets can lag behind shared-component changes; verify each target + separately before claiming it builds. +- The previous `game/ver-mac` and root `dialect.yml` layout is obsolete. -> `dialect.yml` is still the "Root / counter" template with a `Render` context -> bolted on: the Mahjong game logic has not been written yet. The app shell, -> packaging, symlink wiring and the raylib renderer are in place. +## Source layout -## Structure +- `/dialect.yml`: per-application logic; generates + `/ver-mac/src/dialect.swift`. Blue iOS links to its macOS generated file. +- `components/`: shared source of truth. App `src/` files use relative symlinks; + edit real component files and preserve symlink parity. +- `components/render/`: shared component/model/constants, plus mirrored `ios/` + and `mac/` effects, helpers and native/SwiftUI views. macOS additionally has + `renderConstMac.swift` for native pixel-format attributes. +- `components/raybri/raybri.h`: declarations plus implementation gated by + `RAYBRI_IMPLEMENTATION`; clears blue, renders and shuts down rlgl. +- `components/raybri/raybriConst.h`: shared constants with an implementation macro. + `components/raybri/mac/raybriAux.h`: macOS OpenGL symbol loader. +- `components/egl/egl.h` and `eglConst.h`: EGL state/helpers and configuration, + using single-header implementation macros. +- `ogs-blue/ver-{mac,ios}/src/Blue.c`: platform C implementation translation units. +- `history/gitjs/`: historical JavaScript Mahjong reference, outside the build. + `ref/swiftraylib` links to the sibling renderer sample. -``` -dialect.yml Single source of truth for the reactive logic. - Generates game/ver-mac/src/dialect.swift +## Graphics ownership and platform differences -components/ SHARED source-of-truth for all components. - other/other.swift Shared helpers (otherPrintStderr, otherWriteFile, - otherSetupConsoleLogging, ...) - raybri/raybri.h C API of the raylib bridge (raybri_config, raybri_init, - raybri_load_model, raybri_resize, raybri_set_rotation, - raybri_render, raybri_shutdown); extern "C" guards. - raybri/raybri.c Bridge implementation: rlgl scene, shadow pass, shaders. - root/root.swift RootComponent (owns DialectController, registers - effects + shoulds, sets didSetup on setup()) - root/rootVM.swift RootVM (ObservableObject / @Published countText) - root/mac/view/RootView.swift SwiftUI view: RenderView in a ZStack + UI - render/render.swift RenderComponent (controller, effects + shoulds) - render/renderVM.swift RenderVM (weak shared; glView, didPrepareGL, - pixelSize, startTime, timer) - render/renderConst.swift RENDER_CONFIG (raybri_config), RENDER_FPS, - RENDER_MODEL_CUBE, RENDER_OPENGL_ATTRS - render/renderConstShader.swift RENDER_SHADER_* GLSL sources (GLSL 150) - render/renderAux.swift renderDraw(vm), renderPixelSize(view) - render/renderEffect.swift renderInit, renderLoadCubeModel, - renderStartTimer, renderDeinit - render/mac/view/RenderGLView.swift Thin NSOpenGLView: pixel format, callbacks - -> renderSet(...), draw -> renderDraw - render/mac/view/RenderView.swift NSViewRepresentable wrapper +Every GPU operation requires its context current on the calling thread. +`rlLoadExtensions` also requires an existing current context; it precedes +`rlglInit`, not native context creation. -game/ver-mac/ macOS app (SPM executable target "ogs-mahjong") - Package.swift SPM manifest (macOS 13+, swift-tools 5.9); C target - "RaylibBridge" (path src/raybri, publicHeadersPath ".") + - links Homebrew raylib; the Swift target excludes raybri - and gets -Xcc -DGL_SILENCE_DEPRECATION - Info.plist Bundle id org.opengamestudio.Mahjong, exec ogs-mahjong - Resources/AppIcon.icns App icon - Resources/assets/ Bundled glTF assets: cube.gltf (static), - cube_texture.png, cube_normal.png - src/ - GameApp.swift @main SwiftUI App entry - AppDelegate.swift Creates Render/Root components + VMs, calls setup() - dialect.swift GENERATED — do not hand-edit (see chicken-egg below) - other/other.swift -> symlink components/other/other.swift - raybri/raybri.c -> symlink components/raybri/raybri.c - raybri/raybri.h -> symlink components/raybri/raybri.h - render/render.swift -> symlink components/render/render.swift - render/renderAux.swift -> symlink components/render/renderAux.swift - render/renderConst.swift -> symlink components/render/renderConst.swift - render/renderConstShader.swift -> symlink .../renderConstShader.swift - render/renderEffect.swift -> symlink components/render/renderEffect.swift - render/renderVM.swift -> symlink components/render/renderVM.swift - render/view/RenderGLView.swift -> symlink components/render/mac/view/... - render/view/RenderView.swift -> symlink components/render/mac/view/... - root/root.swift -> symlink components/root/root.swift - root/rootVM.swift -> symlink components/root/rootVM.swift - root/view/RootView.swift -> symlink components/root/mac/view/... +macOS uses `NSOpenGLView` (OpenGL 3.2 Core). `renderInit` makes its context +current, enables VSync, loads extensions with the C loader callback and starts +raylib. The timer requests `needsDisplay`; `draw(_:)` forwards to `renderDraw`, +which activates the context, renders and presents via `flushBuffer`. -ref/swiftraylib Symlink to ../../swiftraylib — the raylib/SwiftUI - renderer sample the game will use for 3D rendering. +Blue's SPM `RaylibBridge` target compiles `src/Blue.c`, exposes headers in +`src/raybri`, and links Homebrew raylib. It does NOT define +`RLGL_IMPLEMENTATION`: Homebrew headers omit the `external/glad.h` needed to +compile desktop rlgl locally. Swift imports `RaylibBridge`. `RAYLIB_PREFIX` +defaults to `/opt/homebrew`; build scripts detect `brew --prefix raylib`. +The installed raylib may produce a deployment-target linker warning. -util/ Build/run scripts (see Build & Run) - paths APP_MAC = .build/OGS Mahjong.app - build-mac generateDialect -> buildMac -> packageMac - run-mac runMac - rm-mac-geom Resets saved window geometry - step/ Sourced steps: generateDialect, buildMac, - packageMac, runMac +On iOS, UIKit owns the view/layer and `RenderGLView.st` owns an `EGLState`. +Swift effects create EGL/ANGLE state and surface, make the context current, +and initialize raylib. Timer ticks call rendering directly; presentation uses +`eglSwapBuffers`. Pixel sizes come from view bounds and content scale. +Dialect's resize event triggers `renderRecreateSurface`; the macOS helper is +intentionally a no-op. Teardown must stop the timer, activate the context, +release rlgl resources, then destroy EGL surface/context/display resources. -history/gitjs/ GitJS "Glavred" history + the original JS source of the - web Mahjong, kept for reference — not part of the build. +Blue iOS uses `src/BlueBridgingHeader.h` to expose C APIs to Swift. `Blue.c` +compiles EGL helpers and rlgl using their implementation macros exactly once. +It uses the raylib-iOS XCFramework headers but does not link its full raylib +library. The app links/embeds `libEGL` and `libGLESv2` (ANGLE's Metal backend). +The XcodeGen settings define `PLATFORM_IOS`, `GRAPHICS_API_OPENGL_ES3`, and +`GL_GLEXT_PROTOTYPES`. Minimum iOS is 15.0; portrait and both landscape +orientations are enabled in Blue's Info.plist. + +## Build and prerequisites + +- macOS: `brew install raylib`. +- iOS project generation: `brew install xcodegen`; supply sibling + `../raylib-ios-xcframeworks` containing raylib/libEGL/libGLESv2 XCFrameworks. + `checkRaylibIOS` checks presence; it does not download them. +- Dialect: sibling `../dialect`, built with `(cd ../dialect && util/build-generator)`. + +```sh +util/build-ogs-blue-mac +util/run-ogs-blue-mac +util/prepare-ogs-blue-ios ``` -## Symlink parity rule +The corresponding macOS build/run scripts also exist for `ogs-chkgfx` and +`ogs-mahjong`; `prepare-ogs-chkgfx-ios` exists as well. Inspect their individual +configuration before assuming parity with Blue. -`components/` is the source of truth; `game/ver-mac/src/` contains real -directories whose files are **relative symlinks** back into `components/`: +macOS build scripts generate Dialect, run `swift build`, and package resources +from `ver-mac/res/` into `ver-mac/.build/.app`. iOS preparation checks +XCFrameworks, generates Dialect, stages ANGLE include/library symlinks in +`ver-ios/.build/`, then runs XcodeGen. Build Blue for Simulator with: -``` -src/other/other.swift -> ../../../../components/other/other.swift (4 up) -src/raybri/raybri.c -> ../../../../components/raybri/raybri.c (4 up) -src/raybri/raybri.h -> ../../../../components/raybri/raybri.h (4 up) -src/render/render.swift -> ../../../../components/render/render.swift (4 up) -src/render/renderAux.swift -> ../../../../components/render/renderAux.swift (4 up) -src/render/renderConst.swift-> ../../../../components/render/renderConst.swift (4 up) -src/render/renderConstShader.swift -> ../../../../components/render/renderConstShader.swift (4 up) -src/render/renderEffect.swift -> ../../../../components/render/renderEffect.swift (4 up) -src/render/renderVM.swift -> ../../../../components/render/renderVM.swift (4 up) -src/root/root.swift -> ../../../../components/root/root.swift (4 up) -src/root/rootVM.swift -> ../../../../components/root/rootVM.swift (4 up) -src/root/view/RootView.swift-> ../../../../../components/root/mac/view/RootView.swift (5 up) -src/render/view/RenderGLView.swift -> ../../../../../components/render/mac/view/RenderGLView.swift (5 up) -src/render/view/RenderView.swift -> ../../../../../components/render/mac/view/RenderView.swift (5 up) +```sh +xcodebuild -project 'ogs-blue/ver-ios/OGS blue.xcodeproj' -scheme ogs-blue \ + -sdk iphonesimulator -destination 'generic/platform=iOS Simulator' \ + CODE_SIGNING_ALLOWED=NO build ``` -SPM silently **skips** a dangling symlink (no error), so after moving -`components/` or a subdir, audit for broken links: +Audit dangling source symlinks after moves (SPM can silently skip them): -```bash -find . -type l ! -exec test -e {} \; -not -path './.build/*' +```sh +find components ogs-blue ogs-chkgfx ogs-mahjong -type l ! -exec test -e {} \; -not -path '*/.build/*' ``` -## Prerequisite: the generator - -`util/step/generateDialect` calls the **sibling** dialect repo: - -```bash -$SDIR/../../dialect/util/run-generator --file=$SDIR/../dialect.yml -``` - -So `/Volumes/MOE/p/dialect` must exist and its generator must be built before -`util/build-mac` can regenerate: - -```bash -(cd ../dialect && util/build-generator) # once, or after dialect core changes -``` - -The generator resolves the `output:` path **relative to `dialect.yml`'s -directory**, which is why `dialect.yml` says `game/ver-mac/src/dialect.swift`. - -## Prerequisite: raylib - -The 3D scene links against Homebrew **raylib** (`brew install raylib`). The -`RaylibBridge` C target and the link step read `RAYLIB_PREFIX` (default -`/opt/homebrew`); `util/step/buildMac` auto-detects it via `brew --prefix raylib`. -The bridge renders with raylib's rlgl layer into an `NSOpenGLView` — raylib never -creates its own window. `RootView` puts `RenderView` (backed by `RenderGLView`) -behind the SwiftUI UI in a `ZStack`. A textured cube is drawn from `Resources/assets` (`cube.gltf` + -`cube_texture.png` + `cube_normal.png`); the app rotates it each frame via `raybri_set_rotation`. -(raylib's `LoadModelAnimations` only handles *skinned* meshes, so a plain -node-rotation glTF animation cannot be played by the renderer — hence the cube is -app-driven.) `packageMac` bundles `Resources/assets/` into the app. - -Shaders and render constants live in **Swift**, not in C: GLSL sources are -`RENDER_SHADER_*` in `components/render/renderConstShader.swift`, and -`RENDER_CONFIG` / `raybri_config` tunables are in `renderConst.swift`. `raybri_init` -compiles the shaders in place (no storage/`strdup`). `cube_normal.png` drives -tangentless normal mapping via the derivative-based `cotangentFrame`. The -context is OpenGL 3.2 Core (`RENDER_OPENGL_ATTRS`); on Apple Silicon the driver -still reports 4.1/GLSL 4.10. - -## Render architecture - -The `Render` dialect context owns the GL scene. `RenderGLView` is a thin -`NSOpenGLView`; it only translates AppKit callbacks into dialect fields, and the -`render*` files do the actual work. - -1. `AppDelegate` creates `RenderComponent` + `RenderVM` and calls - `render.setup()` -> `didSetup` -> `didLaunch` (should) -> `pixelSize = [1, 1]`. -2. SwiftUI builds `RenderView` -> `RenderGLView`; `prepareOpenGL()` sets - `F.didPrepareGL`. Its oneliners run `renderInit` (`raybri_init`), set - `RenderVM.didPrepareGL = true`, and `renderStartTimer`. -3. `reshape()` / `viewDidChangeBackingProperties()` compute the backing pixel - size via `renderPixelSize` and set `F.reshapePixelSize` / - `F.backingPixelSize`. The `pixelSize` shoulds fold these into `F.pixelSize`, - whose oneliner stores `RenderVM.pixelSize`. -4. The timer only sets `needsDisplay` every `1 / RENDER_FPS`. `draw(_:)` forwards - to `renderDraw` (make context current, `raybri_resize`, `raybri_set_rotation`, - `raybri_render`, `flushBuffer`). -5. A button click runs `rootSet(F.didClickIncrement)` -> RootComponent oneliner - `renderSet(F.didClickIncrement)` -> `renderLoadCubeModel` (the cube is loaded - on demand, not at startup). -6. `RenderGLView.deinit` sets `F.willDeinit` -> `renderDeinit` (stop timer, - `raybri_shutdown`). - -**GL context rule**: every raylib call must run with the view's context current. -`renderInit`, `renderLoadCubeModel`, `renderDeinit` and `renderDraw` all call -`openGLContext?.makeCurrentContext()` first. Loading a model/texture without it -fails silently with `WARNING: TEXTURE: Failed to load texture`. - -## Build & Run - -```bash -util/build-mac # generateDialect + swift build + package OGS Mahjong.app -util/run-mac # runs .build/OGS Mahjong.app/Contents/MacOS/ogs-mahjong -util/rm-mac-geom # reset the app's saved window geometry -``` - -`build-mac` sources `util/paths` then the `util/step/*` scripts in order: - -1. `generateDialect` — runs the sibling generator, writes `src/dialect.swift` -2. `buildMac` — `brew --prefix raylib` -> `RAYLIB_PREFIX`, `swift build` -3. `packageMac` — assembles `.build/OGS Mahjong.app` (binary `ogs-mahjong`, - `Info.plist`, `Resources/AppIcon.icns`, `Resources/assets/`) - ## Editing the dialect -- Add/modify contexts and components in `dialect.yml`, then run - `util/build-mac` to regenerate `dialect.swift`. +- Add/modify contexts and components in `/dialect.yml`, then run + `util/build--mac` to regenerate `dialect.swift`. - **Chicken-egg**: `struct F` (field-name constants) lives only in the - generated `dialect.swift`. Adding a new field to a context in `dialect.yml` + generated `dialect.swift`. Adding a new field to a context in `/dialect.yml` requires hand-patching its `static let = ""` into `struct F` in `dialect.swift` (ASCII-alphabetical order) if you cannot regenerate first, otherwise the build fails on `F.` being unresolved. - `dialect.swift` is generated — edits there are overwritten on the next - `util/build-mac`. Change the source (`dialect.yml` / `components/`) instead. -- **Validate `dialect.yml` after edits** (e.g. `ruby -ryaml -e 'YAML.load_file("dialect.yml")'`). + `util/build--mac`. Change the source (`/dialect.yml` / `components/`) instead. +- **Validate `/dialect.yml` after edits** (e.g. `ruby -ryaml -e 'YAML.load_file("ogs-blue/dialect.yml")'`). Every should-branch label (`1. Upon each ...`) MUST end with a colon — the parser (`components/yml/ymlFun.swift`) blindly `dropLast()`s it, so a missing colon silently eats the label's last character in the generated `about` @@ -246,17 +148,13 @@ Do not flip it on without addressing those. - Never call raylib / `raybri_*` without making the view's GL context current first (see the GL context rule above). -## Skill: source-file study documents - -When the task is to produce a source-code study document — a self-contained, -downloadable HTML file with a line-by-line table of the file and its -explanations (and, on request, a second version highlighting changes after a -fix) — follow the skill in `docs/file-summary.md`. - -- Write the result to `docs/.html` (e.g. `docs/RaylibGLView.html`) and - name the file's Git revision in the header. The file is the source of truth — - document the exact revision requested, not the working tree. -- Existing example: `docs/RaylibGLView.html` — documents the historical - single-cube `RaylibGLView.swift`, since split into `RenderGLView.swift` plus - the `render*` files. +## Source study documents +- Single-file source studies: follow [docs/file-summary.md](docs/file-summary.md). +- Mirrored platform studies: follow [docs/mirror-summary.md](docs/mirror-summary.md). + Produce one self-contained downloadable HTML with aligned function starts, + original line numbers, green/orange number fills, counts/percentages and a + non-repetitive explanation column. +- Existing mirrored example: `docs/render-platform-comparison.html`, documenting + the revision named in its header. Never silently substitute working-tree code + for a requested historical revision. diff --git a/docs/mirror-summary.md b/docs/mirror-summary.md new file mode 100644 index 0000000..d3edfa2 --- /dev/null +++ b/docs/mirror-summary.md @@ -0,0 +1,68 @@ +# Mirrored source-file study documents + +Use this workflow when comparing corresponding source files across platforms. +The established example is `docs/render-platform-comparison.html`. +For a single-file study, follow `docs/file-summary.md` instead. + +## Source and scope + +- Read sources from the exact requested Git revision with `git show REV:path`. + If no revision is specified, use HEAD and record its full commit hash. +- Discover matching relative filenames beneath the two platform directories. + State which platform-only files are excluded; never invent a counterpart. +- Produce one downloadable, self-contained HTML document in `docs/`, with + navigation links and one section per file pair. Preserve earlier documents + unless removal is requested. +- Record both source paths and the source revision. Preserve every source line, + original line number, indentation and blank line. Escape HTML characters. + +## Comparison layout + +- Use one table per pair with three columns: first platform's numbered source, + second platform's numbered source, and explanation. Do not create separate + line-by-line explanation tables or a Status column. +- Align corresponding function starts where possible. Insert missing-line + placeholders to keep later functions aligned; preserve source order and + original numbers. For example, macOS renderEffect line 12 aligns with iOS + line 16 at revision f0972f0d5ba796e3fa417081f43c00a9654b2aa6. +- Within each function or intervening block, align lines sequentially unless + better semantic alignment is needed. Equal line numbers need not share a row + when function alignment requires padding. +- Compare the exact source text in each aligned row, including whitespace. + Fill BOTH line-number backgrounds green when they match. Fill numbers orange + when they differ. A missing line is an orange-filled dash, not a plain dash. + Keep code backgrounds neutral and retain syntax highlighting. +- Include two filled statistics boxes beneath each section heading: green for + matching line count and percentage, orange for mismatched count and percentage. + Show the total line count as plain text alongside them. +- Count actual lines across BOTH files, including blank lines. A matching pair + contributes two matching lines; a differing pair contributes two mismatches; + a platform-only line contributes one mismatch. Missing placeholders do not + count. Percentages use the combined actual-line total. Recalculate after any + alignment change, and explain this counting convention in the document. + +## Explanations + +- Explain each distinct point once across the document, at its first relevant + occurrence. Leave later cells empty unless they add information. +- Eliminate semantic repetition, not just identical sentences. Do not repeat + platform/import boilerplate such as “UIKit serves iOS” for every import. +- Explain shared behavior once. Label iOS/macOS details only when needed to + distinguish behavior. Explain the reason or consequence of platform differences. +- Avoid redundant function summaries when the individual operations already + explain the same behavior. Leave blank lines and closing braces unexplained. +- When realigning rows, anchor each platform-specific explanation to its own + source line rather than to the old visual row. + +## Presentation and verification + +- Inline all CSS and syntax highlighting; no external fonts, scripts or requests. +- Use `
`, `white-space: pre-wrap`, and `overflow-wrap: anywhere`.
+  Give the code columns equal width; ensure long lines remain readable without
+  horizontal scrolling. Do not use striped row shading.
+- Verify every source line and number against the named Git revision, in order,
+  with no omissions or duplicates. Check function anchors, placeholder fills,
+  both matching-number fills, statistics, and explanation attachment.
+- Review explanations for repeated clauses as well as repeated sentences.
+- Inspect the rendered HTML for layout problems. Return a clickable file link;
+  tell the user to refresh an already open document after updates.