Skip to content

Acceptance standard: readable source and exact machine code

The deliverable is human-readable C/C++ that compiles to the original bytes. Both requirements are mandatory. Matching bytes with unreadable memory manipulation is not a completed function. Attractive source that does not match is not a completed function either.

Review the source and the layouts alongside the byte comparison. A matching object establishes what the compiler emitted. The debug records and callers establish what the names and types mean.

Required source quality

  1. Use meaningful names. Preserve recovered function, type, member and parameter names where they are reliable. Name new locals for their purpose, such as distance, actor, remainingCount or enabled. Do not submit register/decompiler names such as a0, v0, param_1, uVar3 or DAT_00401234 as the recovered interface/data model. Do not invent confident semantic names without evidence; report uncertainty honestly.

  2. Use real pointer and reference types. An actor pointer is ZActor*, not an integer containing an address. Use const where the original signature/behavior supports it. Express calls through named functions or correctly typed callbacks. No hard-coded numeric object/function pointers, integer-plus-offset dereferences, numeric jumps to original code, or renamed numeric-address wrappers.

  3. Model objects with structs/classes and named fields. Recover the relevant layout in an approved header and write actor->m_fEndDist, not a cast into anonymous memory at offset 0x584. Represent globals with named, typed declarations rather than scattered numeric addresses or DAT_... labels. Preserve widths, signedness, alignment, offsets, calling convention and known object sizes. Use target-compatible layout checks where appropriate. A partial type with documented padding for genuinely unknown regions is acceptable; using one giant byte buffer and addressing all meaningful fields by numbers is not. If a named global needs unsupported relocation/linker work, report that blocker instead of hard-coding its address.

  4. Use enums, named constants and named flags when their meanings are known. Represent actor states, modes, event types and similar finite choices with recovered enums. Give semantic masks/flags meaningful names or use a verified bitfield layout. Keep genuine numeric quantities readable; do not replace every number with an equally opaque constant name. Do not change a one-byte stored state into a four-byte enum field and silently move the following members. A narrow storage field plus a typed enum conversion can be correct.

  5. Distinguish pointers from handles and IDs. A documented engine handle, resource ID, index or serialized offset can legitimately be an integer. Give it the recovered type or a meaningful typedef when known. Do not reinterpret a handle as a pointer to make it look more object-oriented. Conversely, do not keep a real object pointer in an integer merely because the PS2 address fits in 32 bits.

  6. Reconstruct control flow and intent. Prefer ordinary if, switch, loops, expressions and named operations. Do not transliterate assembly into a register machine, opaque temporaries, instruction tables or a maze of jumps. Preserve observable behavior and evaluation order. Do not invent a different algorithm just because it produces the same answer for one example.

  7. Use source supported by the historical compiler. This project targets the pinned EE GCC toolchain, with C/C++98-era constructs. Use ordinary enums and compatible typedef/layout checks, not unsupported features such as enum class, auto type inference or modern static_assert syntax. Any code-generation-sensitive construct needs a clear data/ABI explanation; do not add arbitrary volatile, opaque casts or unions solely as an unexplained opcode-shaping trick.

  8. Explain evidence and uncertainty concisely. Useful comments explain a layout assumption, field width, platform constraint or necessary compiler-sensitive expression. They should not merely repeat every instruction. Keep detailed experiments and disassembly reasoning in the task handoff; the production source should read like a maintainable program.

Rules settled during bulk recovery

  • Trivial bodies are valid. An override that the original compiles to a bare jr ra is void C::F(Type *) {}. Leave parameters unnamed in the definition when the body does not use them, and keep the debug-signature names in the declaration.
  • Discarded calls. When the original calls a function and drops its result, the debug record has no local for it and the bytes require the call, write a bare call such as GetHM3GameData()->GetHitman();. Use ZASSERT(expr) for an evidenced compiled-out assertion whose expression or inline cost is observable.
  • Names come from evidence. Field names come from analysis/recovered-types.h at the same offset and width. Parameter names come from the debug signature (tools/debug_context.py <id>, or analysis/debug-function-signatures.cpp); recovered functions no longer carry it as a comment. A match that stores one parameter into two fields is reported as found; do not rename fields to make the story tidier.
  • Static data is a named member. Use static T name; in the owning class, or an extern declaration near the top of the source file for a true global. Both link by the original symbol name. Never take the address of a numeric location.
  • Property tables use ZPropertyInfo. The shared engine/geomsbase/zpropertyinfo.h struct has three named fields and a 12-byte size check guarded for the host test.
  • Enum returns use enum names. return PRIORITY_High; is accepted; return static_cast<EEventPriority>(3); is not when a named value exists.
  • Layout splits keep a verified shape. When padding is split around a recovered field, the remaining padding must keep the class size, and existing padding comments move with the first piece.
  • Templates are written once. A function family that the original instantiates from one template (ZGeomValidator<T>) is a real template with an explicit instantiation, not many hand-copied bodies.
  • Declared signatures must match the original mangling. Do not alter a parameter type or const-ness to make a candidate compile if it changes the symbol.
  • A compile error is not a reason to loosen a type. If a needed type is not declared, forward-declare a class, include the header that owns it, or skip the function.

Assembly and address tricks are not recovery

An accepted recovered body must not use inline assembly, .word, .incbin, copied instruction-byte arrays, naked assembly functions, disguised INCLUDE_ASM macros, or a wrapper that just calls/jumps to the old function body. Do not attach an asm symbol name to an unrelated C function to evade recovering the correct C++ signature.

Unrecovered functions retain their existing INCLUDE_ASM blocks. They are explicitly unfinished inputs and do not count as recovered C/C++. Out-of-scope SDK, runtime and library objects have no source at all; the build copies their code from the original executable.

Ordinary named, typed calls to other game functions or platform/library APIs are valid source concepts. They must not be implemented as inline assembly or numeric-address dispatch to get around the build. The current linker limitations may prevent accepting such a function yet; that is a blocker to report, not permission for a pointer/assembly workaround. Hardware address declarations, if later needed, belong in a separately reviewed typed platform interface, not ad hoc literals in worker-recovered bodies.

Concrete example from this project

Do not submit offset-based pseudocode like this, even if it could compile to matching instructions:

void ZActor::SetStopDistance(float value) {
    *reinterpret_cast<float*>(reinterpret_cast<unsigned char*>(this) + 0x584) = value;
}

The existing readable form expresses the operation through the recovered field:

void ZActor::SetStopDistance(float fDist) {
    m_fEndDist = fDist;
}

The field's position belongs in the validated class layout. Existing matched methods also show typed state conversion and a named bitfield:

ACTORSTATE ZActor::GetActorState() const {
    return static_cast<ACTORSTATE>(m_ActorState);
}

void ZActor::EnablePathFinder(bool bEnable) {
    flags.bits.m_bPathFinderEnabled = bEnable;
}

Here m_ActorState retains its original narrow storage width, while the interface uses the recovered ACTORSTATE enum. The point is to recover a supported model of the original data, not to hide the same anonymous pointer arithmetic behind nicer variable names or a macro.

Typed array indexing and byte-buffer access are appropriate when the original operation really manipulates an array, packed file data or a byte buffer. They are not an excuse to avoid reconstructing known object fields.

Reviewing a change

For each candidate, record PASS or FAIL with concrete source/layout evidence for:

  • Names and signatures express the recovered function's purpose.
  • Pointers, references, handles and IDs have justified types.
  • Object accesses use named fields and supported layouts.
  • Known states/flags use meaningful enums, constants or named bits.
  • Control flow is understandable C/C++, with explained necessary quirks.
  • There is no hidden assembly, opcode encoding, raw-address dispatch or offset-based object-access workaround.

Read the diff and the declarations it relies on. Run make match, make match-scripts, make test and, for changed matching sources, make digests. If the readable source still differs, keep the fallback and record the differing instructions and the evidence for the remaining obstacle.

Platform intrinsics

Use the typed helper when the original instructions show its operation. The headers provide the host implementation or fallback. New inline assembly requires review. Paths in this table start at src/engine/system/.

Helper Header Evidence at the call site
ZDebugBreak debugbreak.h IOI's break 0
ZSqrt, ZAbs sqrt.h, abs.h The inline square root without GCC's two leading nops, or IOI's float absolute value
ZMin, ZMax minmax.h The inline min.s or max.s where a plain comparison schedules differently
ZCountLeadingSignBits _ps2/leadingbits.h plzcw
ZSyncMemory, ZEnableInterrupts sync.h, _ps2/interrupts.h The DMA barrier or interrupt enable
ZPrefetch _ps2/prefetch.h pref with a folded address offset
ZPor, ZPxor, ZPceqh, ZPpacb, ZPcpyld, ZPcpyud, ZMovz, ZPrefetchPointer _ps2/mmi.h The corresponding MMI instruction, conditional move with a live destination, or register-address prefetch. PS2 intrinsics approved 13 November 2026.
ZSetStackPointer, ZJumpToExit _ps2/stackpointer.h, _ps2/exit.h A stack switch in the restart path (approved 13 November 2026), or a jump to exit without an epilogue

Approved multi-instruction helpers

Use these helpers only where the original contains the corresponding block. The dates record the project owner's decisions in November 2026.

Helper Approved Block and placement
ZDot(v0, v1), ZDot(result, v0, v1) 9 Nov, reference form 13 Nov All six loads precede mula.s, madda.s, madd.s. Use the reference form when the result is stored through a temporary. Interleaved loads use ordinary vdot. See system/_ps2/dot.h.
ZWaitVU0Microprogram 12 Nov Twelve words polling the COP0 condition flag with bc0t and bc0f. See system/_ps2/vu0wait.h.
ZSaveFloatRegisters, ZRestoreFloatRegisters 12 Nov Store or load all 32 FP registers at consecutive word offsets. Used by LoadHandlerInit and LoadHandlerExit. See system/_ps2/floatingregisters.h.
ZMatrixTransform<iPad>, ZMatrixTransformMul 12–13 Nov Fixed-register 3×3 matrix blocks in zstdlib/zmath.h. The transform uses the call site's five or six hazard nops. The multiply accumulates the point row with adda.s. Choose the overload that writes separate outputs or updates the input matrix and point in place.
ZJumpToFunction 13 Nov Move the argument to $4 and jump through the function register after switching the stack in NukeAndRestart. See system/_ps2/exit.h.
ZAddScaled 13 Nov Load zero into $f0, then three adda.s and madd.s pairs. The macro writes a shared 12-byte output at the caller's line. See system/_ps2/addscaled.h.
ZPackUnitColor 13 Nov Clamp three channels, set the accumulator once, then scale, convert and pack the bytes as one unit. See system/_ps2/packunitcolor.h.
ZCross 13 Nov Six contiguous multiply/subtract instructions, with memory outputs that preserve a temporary next to each component. See system/_ps2/cross.h.

Hand-written assembly functions live in an assembly unit

A few IOI functions use a private calling convention that no compiler produces: arguments in $f0-$f2 (the EE o32 ABI starts float arguments at $f12) and $ra parked in a call-clobbered $t register across the call. Nine sites in the whole 3.5 MB text have that shape. The PS2 branch of src/engine/zstdlib/_ps2/fastbgeom.cpp preserves their original entry labels, stack frames and returns in file-scope assembly. The portable branch implements the same geometry operations in C++. The manifest records these units with original_assembly: true so make progress counts their PS2 functions under "Original assembly units".

Original inline-assembly blocks

A function may contain one __asm__ __volatile__ block only when the original function demonstrably contains an instruction sequence GCC cannot emit: VU0 macro-mode code (lqc2, vcallms, v* operations, qmfc2) or packed MMI operations such as pcpyh, pmaxw, ppacb or pextlb. The block reproduces the original instruction sequence, uses named %[operand] constraints for every C++ value it reads or writes, and keeps the original's fixed VU registers. Everything outside the block is ordinary readable C++. A single instruction that already has an intrinsic (ZSqrt, ZAbs, ZCountLeadingSignBits, ZDebugBreak, ZSyncMemory, ZPrefetch, ZEnableInterrupts) uses the intrinsic instead, and a loads-first dot product uses ZDot.

The eligible functions are the VU0 lighting and bone-matrix routines (ApplyOmniLighting, ApplyCircSpotLighting, ApplySquareSpotLighting, ApplyEnvironmentLighting, ApplyDirectionalLighting, VU0ExecBoneMats, InitBoneDma, VU0ExecParentBoneMatsSafe, InitParentBoneDmaSimple, DataLaunch) and the packed-MMI users fast_mod, qpul, ZOldViewPS2::ExitVsExitChck, ZOctreeCompiled::CheckLinesegment2, memsetuint32, ZPostFilterEvent::BlendPalettes, ZCloth::CollidePlanes and ZCloth::DrawIt (their originals hold trapping add/sub and fixed $f19-$f31 accumulator blocks; project owner, 13 November 2026), vpul (the vector twin of qpul: one block ending in an unfilled jr $ra; nop) and mrot (five hazard nops and fixed $f9-$f19; project owner, 13 November 2026), TransferCamAndExits in spherechecks.cpp (one asm statement on one source line: fixed $f0-$f11 held across both loops, explicit nops and mtc1 $0,$f31; adda.s; project owner, 13 November 2026), ZPrimControlBase::ColorFVTOIU (zprimcontrolbase.cpp) and GenQuadruple (zolddrawps2.cpp) (fixed $t0-$t3/$f0-$f4 in order, in-place cvt.w.s, an unfilled jr $ra; nop, and in GenQuadruple an asm block spanning about 43 source lines; project owner, 13 November 2026), and the two fixed-register float macros fast_cos and fast_asin (owner's decision, 12 November 2026). Adding a function to this list needs the same evidence: an instruction that no matched C++ function contains.

fast_cos and fast_asin are the arithmetic case of the same rule. Their originals carry hand-placed hazard nops in the constant setup (lui then five nops before mtc1 in fast_cos, one at entry in fast_asin), a mula.s/msuba.s accumulator chain in fixed registers, and a magnitude test done on the raw bit pattern (subu 0x3f3504f3 - |bits(x)|, srl 31) whose sign is injected into the coefficient encodings with or/movz/xor. None of that is reachable from C++ and none of it is hardware-specific: the block is arithmetic, so it is recovered as one __asm__ __volatile__ block with typed operands, like the others.

Original assembly units and drafts

The 13 original assembly units use file-scope assembly under OPENBLOOD_TARGET_PS2 in their .cpp files. Twelve also supply portable C++ implementations. The host supplies process startup and exit for crt0.

A readable body that does not match yet may stay in the tree as #ifdef NON_MATCHING followed by the body, #else, the original INCLUDE_ASM line and #endif. The normal build never sees the body, progress never counts it, and make drafts scores every draft. A draft must already meet this readability standard.

Duplicated statements in both arms of a test

A test whose two arms contain the same statement is accepted when the duplicate reproduces the original's register allocation (project owner, 13 November 2026). GCC merges the identical arms after reload, so the output has one copy, but the extra references before allocation give the variables the priorities the original had. Use it only where the surrounding code has the same test shape (the neighbouring branch tests the same condition) or the line table places the statement in each arm. ZEditorSpline::GetTangent and Zhm3Actor__Findclosestcharactertype are the examples.

ZMinTo(fDest, fVal, fLimit) and ZMaxTo(...) in engine/system/minmax.h are the same single min.s/max.s as ZMin/ZMax, written straight into an lvalue such as an array element. IOI's original wrote its box expansion this way: the asm output is the element itself, which keeps an unnamed stack temporary per element and the stores GCC would otherwise drop. They are macros because an inline function or braced block frees those temporaries early. CRigidBody::Move uses them.

Compiled-out debug output: ZTRACE

ZTRACE(...) in engine/system/zassert.h is IOI's compiled-out debug-output macro (project owner, 14 November 2026). It expands to an empty while (0) { }: GCC 3.2 deletes the loop but keeps its loop notes, which act as a barrier to the first scheduling pass and the live-range pass, and the statement leaves no code. Use it only where the original's line table shows code-less source lines at that point and the barrier is measurable (a draft that becomes exact or much closer with it). ZASSERT's do { } while (0) leaves no loop notes and is a different tool.

Also accepted on 14 November 2026: an if/else on a value stored on the line before, whose dead arm is ZDebugBreak() (ZActor::Initialize; the test folds after CSE starts and ends a CSE block as the original's did), and the reconstructed leftover double loop in ZOldDrawPS2::PrimInstanceCreateWaterPatch, whose loop structure the line table shows.

Compiled-out debug switches and dead stores (owner, 14 November 2026)

The owner accepted these shapes, each only where the original's code needs it and a measurement shows it:

  • A compiled-out debug switch: a local flag set once to a constant and tested once, such as bool bBreakOnVU0CodeLoad = false; and if (bBreakOnVU0CodeLoad) ZDebugBreak(); in ZOldDrawPS2::UpdateLight. GCSE's last constant propagation folds the test, which reruns CSE; nothing of it is left in the code.
  • A dead store on a code-less line that a later statement overwrites, such as fTime = bPushed ? 0.0f : m_fTime; in ZTextCredits::Update; its join label ends CSE.
  • A guessed member test around two identical arms when the original's condition left no code (m_CurrentStatus & PLAYER_STATUS_Dead in ZHitman3::CalcBonesFromMotion).
  • An unnamed address-taken reference to a local (Animation::Header *const &pSecondHeader in ZLNKOBJ::SetDualFrame), which GCC leaves out of the debug record.
  • A literal among named constants when the scheduler needs it (SetCompanionEntryTo(2) in ZHM3ActorMovesets::Initialize).

Other evidenced platform and debug operations

Existing PS2 code uses ZCopyQuadWords in engine/zstdlib/_ps2/ps2_optimize.h for aligned transfers and ReadCycleCount and typed hardware-register accessors in engine/system/_ps2/ps2registers.h. Their use in the original platform code does not imply blanket approval for new assembly helpers.

A compiled-out debug message can leave a 128-byte szDebugText buffer. Original stores and named debug locals account for the otherwise unused variables in PF4RunTime::ZData::CloseExit. A discarded TIMETYPE or an assertion around a comparison may also leave an observable temporary. Require the matching instructions and line evidence before retaining such a local.