Skip to content

Latest commit

 

History

History
345 lines (293 loc) · 21 KB

m1-classic-text.md

File metadata and controls

345 lines (293 loc) · 21 KB

M1 classic text, rules and city preferences

The portable F03 text reader, P04 label loader, all twelve classic rule-table readers and both city-production preference paths are implemented. Native JSON uses the System.Text.Json admission wrapper; classic text uses supplied file, section-index and byte-comparison services. Both rule paths produce RuleDefinitions, and both preference paths publish CityPreferences. This supplies part of M1's native/classic content boundary. The later conversion slice completes the three M1 conversions; playable session content admission remains later work. The completion audit records the closed M1 scope.

Text ownership

Production text uses unpadded owned strings and local references with explicit custom-name flags. F06 stored leaders use a separate lossless record type; live export translates name flags without narrowing text IDs. Label rebuilds preserve unrelated rule references. Semantic tests cover names, flags, retained references and publication. tools/check_original_rule_labels.py independently checks original data using the stored inspector; original ordinals do not define runtime allocation or text ownership.

Classic reader

src/OpenCiv2.Formats/Classic/TextReader.cs implements F03 §2/9 and the required retained state in Appendix A:

  • Reads contain at most 254 text-mode bytes. The owned memory adapter translates CRLF to LF while retaining physical offsets for seeks; long lines split across reads. Only terminal LF and edge ASCII spaces/tabs are removed. Blank lines, comments, headers, quotes and byte-order marks have no general skipping rule.
  • The shared workspace retains its token cursor. EOF/read failure clears only buffer byte 0 and closes the stream. A cursor within an established suffix can still read that suffix; a subsequent line read on a closed stream stops.
  • Comma tokenization preserves empty fields and semicolons. Decimal/hex/binary integer parsing wraps modulo 2^32, including decimal negation; ability parsing independently consumes an unprefixed binary run modulo 65536. Empty padded names become one space, while ordinary empty names remain empty.
  • Explicit opens append the language extension only if no dot occurs anywhere in the filename, uppercase through the supplied service, try search/home directories and restore the caller's working directory. Whole-line section matches leave the cursor at the header's end.
  • Reused streams search forward and rewind once on EOF. A failed reused search closes the stream; the wrapper's retry then reports an unavailable-stream boundary. It does not silently reopen a home file. Explicit-file wrapper retries can select a home section absent from an existing scenario file.
  • Supplied section-index offsets greater than zero cause a seek. No index is inferred from a dictionary: duplicate-header results retain the distinction between explicit, reused and indexed search. Index construction is separate.

TextWorkspace.backed_bytes identifies known buffer storage. A successful read establishes the trimmed visible prefix and its terminator. Bytes beyond that prefix are not a reconstruction of the original trimming scratch; a fixture can supply explicit backing for such reads. Unknown/unbacked cursor accesses, unterminated backing, failed seeks and inconsistent read-service results stop with TextError, preserving preceding effects. A service reporting unspecified partial buffer bytes on failure is rejected rather than assigned an invented meaning. The memory adapter also stops on NUL/control-Z; extending those raw text-mode cases needs an explicit contract or supplied service.

The default comparison is deliberately partial: equal lengths and bytes need no folding, differing ASCII bytes use ASCII case equivalence, and an encountered unequal high-byte pair reports comparison-unavailable. Path uppercasing accepts ASCII only. Other comparison services can be supplied explicitly. This does not close the F03/C01 non-ASCII comparison gap or turn the ordered original observation into a complete folding table. Byte text and presentation encoding remain separate.

Shared labels and startup

ClassicLabels.Load returns an owned LabelCatalog, including home fallback and popup text. It closes its reader before returning and never accesses live rule state. LabelCatalog.Install publishes owned text into the label table, retaining popup text when its source is absent. Parsing errors leave installed labels untouched. Language selection and GAME-cache setup belong to TextConfiguration.Initialize, independently of any label source.

Classic rule tables

src/OpenCiv2.Formats/Classic/RuleLoader.cs implements F03 §§3–7/9 and the declared Appendix A reference vocabulary. RuleLoader.Load requests COSMIC, CIVILIZE, IMPROVE, ENDWONDER, UNITS, TERRAIN, GOVERNMENTS, LEADERS, CARAVAN, ORDERS, DIFFICULTY and ATTITUDES in that order. The first three opens use an owned explicit filename; later sections reuse the selected improvement stream. Physical section order can differ. A successful full load closes the stream. Individual section readers start immediately after an already selected header.

The loader updates existing definitions field by field. It preserves caller identity IDs and never infers them from classic names. Shared cosmic, movement, HP, cost and leader normalization is applied once; the cosmic helper also supports individual line publication. Advances reset enablement/prerequisites, apply only their documented tail defaults and fix references after the full table. Improvement prerequisites follow disabled advances, while unit references and wonder expiry do not. Enabled cycles remain accepted. Unit abilities assign a zero-extended 16-bit result into the 32-bit logical field, clearing old high bits. Special terrain rows retain existing work/transformation values.

Individual advance, improvement and unit readers support keepNames, including default tails. Government definitions always change. Leader preservation consumes and stores the new strings, then restores each previous field individually; it neither selects a new current name nor installs default title pairs. Repeated optional title overrides use the last value. The loader retains each leader's usage count and city-name cursor.

RuleState owns decoded definitions, labels, 21 live leaders and the double-movement flag. Definitions and live leaders carry owned text values; custom-name status is an explicit flag. Preserving names does not publish discarded replacements. Label rebuilds preserve unrelated rule and leader text; new-game preparation replaces the whole state. The original parallel unit-name pointer table has no runtime consumer and is omitted.

The separate F06 StoredLeader type preserves every byte of an imported record. Live name restoration consumes its sign markers, and live saving writes canonical markers without depending on UI text allocation history. Original observations are recorded separately in the text observation procedure. No original source/harness is an implementation input.

Reference failures retain the specified prefix and report the module, code, row, position and offending line. A returning diagnostic/cleanup callback is followed by RuleLoadError; it cannot resume parsing. An invalid optional title index stops before allocating that pair or attempting an out-of-bounds write. Missing explicit sections stop at the failed open with a separate diagnostic, without inventing an original fatal-reference code. Failed reused sections and unbacked cursor/stream accesses retain the reader's bounded TextError behavior. Fixed-row reads use the retained buffer after an EOF result until the next unsupported access; they do not fill missing tables with stock rows. The safe missing-section stop is not a claim about an original invalid-access result.

Stored names currently require reversible Windows-1252 presentation decoding. Undefined bytes fail before storing that name, preserving earlier updates; other language encodings and the broader comparison profile remain open. There is no filesystem discovery, session reload orchestration or classic export command hidden in this API. The separate native rule installer now applies admitted semantic input to the same retained state.

City-production preferences

ClassicCityContent.LoadPreferences follows F03 §8 incrementally. It clears the active count, retains unused list payload and NoDefend, checks NODEFEND presence, closes, and independently opens AUTOBUILD. It reads current improvement names 1…38 in ascending order, appends the first match, retains duplicates and stops at the first unmatched token, EOF or 32 entries. Trailing tokens are ignored. Missing content creates no stock list. Name reads remain owned for the duration of the preference read, so file callbacks cannot change the captured matching names. Both overloads capture improvement names from the supplied rule definitions before reading the preference file. The mutable RuleState overload reads the currently installed definitions; the snapshot overload reads its owned input.

NativeCityContent.LoadPreferences validates a selected resolved pack's openciv2-city-preferences/1 component and its complete native rules. IDs must resolve to improvements 1…38; at most 32 entries are accepted. The validator rejects an ID whose classic name first matches an earlier improvement, including case collisions. Empty/padded-space names cannot round-trip through the trimmed token and are rejected. Unestablished comparisons get a distinct diagnostic. The immutable result retains the selected rules and preference source receipts.

CityPreferences.Apply validates the complete native update before publication, then replaces the active prefix while retaining unused payload. deprioritize writes NoDefend=1; unchanged preserves its incoming value. This does not choose city production, modify automation flags or reset other settings. It does not change the classic loader's incremental failure behavior.

The native command accepts the same explicit parent mounts, locale and gameplay profile gate as other content commands:

src/OpenCiv2.Cli/bin/Release/net11.0/oc2 content validate-preferences path/to/content.json --json

Its report format is openciv2-city-preferences-validation/1, with scope rules-gameplay-and-city-preferences, ordered buildSlots, the defense action, the partial comparison policy and source receipts. Exit codes are 0 for admitted content, 1 for semantic/comparison rejection, 2 for usage/source failure and 4 for malformed JSON. No files or live state are changed. This command does not certify full classic export representability: complete row lengths and section marker collisions still belong to the conversion boundary.

Process preferences and CIV2.DAT

F03 section 8 preference initialization and persistence operate on semantic ordinary and multiplayer values in ProcessContext. They are distinct from live world options and saved multiplayer state. Existing core-load consumers use the same multiplayer fields; the accepted-file load caller reads ordinary_preferences.game_options. Client-session transitions retain both records, and preference input alone changes no world options or random context.

Ordinary defaults use the supplied startup screen width and renderer animation availability, including the width-greater-than-999 boundary and herald gate. They assign the documented settings and empty the preference text. Multiplayer defaults empty the name/address strings and set custom timer text to 60. Live text is owned string, binary settings are bool, and established choice meanings use named enums. Unknown legacy settings and padding are stored codec concerns. The logical startup inputs do not emulate the original native memory API or prescribe renderer allocations.

src/OpenCiv2.Formats/ClassicPreferences.cs implements every field of F06's 72-byte ordinary item and 444-byte multiplayer item. Pure codecs decode owned transferred prefixes against explicit prior values. Successful stored items retain arbitrary scalar bits and unterminated fixed strings. Stored prefix helpers retain untransferred bytes from the supplied prior record. Live conversion uses text through the first NUL, decodes CP1252 into C# strings and interprets nonzero binary flags as true. Unassigned binary-field bytes retain their matching C1 characters for reversible export; strict content-file text decoding continues to reject them. Live export writes 0/1 flags, zero-filled text tails and legacy settings, and rejects oversized or embedded-NUL text without truncation. The second item starts at the actual cursor. Trailing file bytes are ignored.

src/OpenCiv2.Session/PreferenceFiles.cs snapshots preferences and defaults, borrows a FileStorage provider, reads both items and closes before installing either result. Missing files default both records. Short items use their own fallback; close failure returns PreferenceLoadStatus.Input with installed preferences unchanged. Exceptions close once without publishing a prefix. Saves snapshot both records, require successful write and close, and attempt removal after reported output failure. Accepted configuration changes remain if persistence fails.

The following counts describe the earlier item-oriented revision; current regressions assert staging, entry snapshots, cursor continuation, defaults and truthful finalization as well as codec fidelity.

Thirteen new portable cases cover field offsets, defaults, every transferred prefix, invalid item-service results, live reads, cursor continuation, ignored tails, failure/delete ordering and process lifetime. Another portable composition case passes real F03-loaded options through the F06 accepted-file caller. A native case exercises actual replacement, reload and failed-output deletion; three CLI cases check complete/trailing input, truncated rejection, source preservation and no-overwrite output. These are specification-derived inputs and expectations.

The native comparison driver separately checks lossless stored re-encoding and the semantic values installed by F03 preference input. It requires at least 516 input bytes so defaults cannot be mistaken for a successful original-file round trip. Its optional output is a separate new 516-byte file; ignored trailing input is reported separately:

tests/OpenCiv2.PreferenceRoundTrip/bin/Release/net11.0/OpenCiv2.PreferenceRoundTrip path/to/CIV2.DAT path/to/new-copy.dat

On 2026-11-14 UTC, the driver read the existing 516-byte CIV2.DAT from the isolated original-game runtime used in the original live-save exchange. Both items reproduced byte for byte. Input SHA-256 before and after input, and the separate output's SHA-256, were all 318a571574588fce7fda32feed0c84bd70b76988abe80867f041c92c92a5411a. The local input is build/original-text-runtime/CIV2.DAT; the output is build/original-preferences-roundtrip-2d22a52.dat. Neither is committed. This checks original-file input/re-encoding through the file codec path; it is not a new original-program execution or acceptance of edited preferences.

Accepted setup rules, application startup binding, native preference presentation and original reload of an edited preference file remain separate work. Accepted in-game changes now use the operations described below.

Accepted in-game configuration

src/OpenCiv2.Session/Configuration.cs applies F03 section 8's accepted game, graphics and message choices to live session state and persists them through the real two-item preference writer. Cancellation leaves both records alone. Game options clear their eleven controlled bits, apply sound/music choices and the specified music operations, then apply the remaining nine choices and save the full live word. Graphics options replace their six bits in order; a new herald enable still applies after an advisory resource warning. Message choices replace the entire disabled-message word, clearing unknown bits. Required child exceptions retain preceding effects; reported preference-save failures do not roll back accepted options.

src/OpenCiv2.Core implements the actual F03 table transformation. It visits all 62 unit types and changes land movement, preserving byte wrapping when doubling and dividing the signed current byte with truncation toward zero when removing doubling. It preserves air/sea types and existing units' spent movement. The retained applied flag changes before the table, and status redraw follows the complete table. Single-player mode and repeated requests leave the flag and table alone.

MultiplayerOptionOperation composes F03 with N03 section 11. It saves chat choices before host/change gates. A changed multi-player host proposal prepares owned text/options, initializes the signed pending count and starts an owned OptionVoteChannel. The first poll then yields; presentation can display the proposal while the ordinary scheduler continues.

Each later poll performs bounded channel work and checks handoff, the signed wrapping 2401-tick deadline, pending count and rejection status. Completion captures a fresh tick. Rejection or cancellation restores remembered double settings from current authoritative values. Acceptance installs them and applies the actual movement transformation, then evaluates the live publication gate. Its selected tail sends units/options and acceptance in order even if a child changes mode. Double options receive no second preference save.

The operation pins the world across suspension, retains borrowed dependency handles, rejects reentrant polling and releases the channel once on success, cancellation or failure. Cancellation during a channel call is deferred until that call returns. The broadcaster, storage provider and callback owners outlive the operation; their state is shared across calls rather than cloned into each operation. Ordinary game/graphics/message configuration also pins world references through external children, including configuration before a client session exists.

Shared configuration and multiplayer-option cases cover checkbox mappings, audio ordering, save failures, required-child stops, all 256 movement bytes, signed removal, authority changes during persistence, proposal rejection and acceptance, live callback mutations, raw simultaneous words, clock wrap and the 2400/2401 timeout boundary. They also test yielding, channel ownership, cancellation, exception cleanup and pending-world protection. Expectations are specification-derived with supplied child outcomes; actual network/modal/audio integration and X02 registration remain separate work.

Application command/widget binding, P10 audio implementations, N02 option wire dispatch and replies, presentation and full F05 setup remain required owning work. Runtime and injected services outlive their pending operation.

Evidence and remaining work

Portable reader, classic/native rule, label and text tests cover authored parsing, fallback, name preservation, malformed-input bounds and real I/O failures. Paired installation compares semantic values with different preceding text allocations. Large-ID tests verify intended names remain correct above 65535; separate tests preserve signed codec fields and verify custom-name restoration. Label rebuild tests retain old rule and popup text. Original allocation counts, padding and manufactured allocator callbacks are no longer acceptance criteria. The preference cases cover paired inputs, first-match behavior, retained fields and live name changes. Two additional native CLI cases check real mounted files, source preservation, receipts and collision/comparison diagnostics. These are specification-derived and regression checks, not new original-game observations or independently reviewed X02 fixtures. F03 is not yet registered with X02.

The city-name providers now implement C01's ordered default naming through both paths, with shared counter/publication behavior and a native validation command.

The F03 reload context and native file services now compose label rebuilding, sprite callback, scenario/home selection, full table loading and final name-preserving reloads over real native streams. Four portable wrapper cases and seven native adapter/integration cases cover the ordering, partial effects and full disk load-edit-save-reload. The graphical resource consumer, GAME cache and browser persistence remain separate integration work.

M1 closeout is limited to M1-02 and regression checks for the implemented readers. The complete comparison profile, other native components, GAME-cache construction, application wiring and owning consumers remain M2–M5 work. The completed reader contract does not expand M1 into those later integrations.

Current C# sources and tests are mapped in implementation coverage. Run the native/browser and CLI checks; validation status records executed evidence and remaining gates.