Design doc and reference implementation sketch for the reference layer

Design for a poseable mannequin plus glTF/GLB import overlay in Umamo:
world axes, orbit camera, draw path, UMA persistence, UI, risks.

docs/seams.md lists the RenderDevice additions the feature needs:
PrimitiveTopology, DepthState, depthAttachment, WorldToClip,
ReferenceMeshSpec.

sketch/ mirrors the algorithms in Kotlin. verify/verify.py proves them:
30 checks, all passing. Two findings: accessor byteOffset must be a
multiple of the component size, and the screen-right basis collapses to a
zero vector at pitch +/-90 degrees, so pitch is clamped to an open
interval.
This commit is contained in:
litruv
2026-11-03 18:14:07 +11:00
parent e95d7795ae
commit 4eb583b5f3
10 changed files with 1913 additions and 2 deletions
+94
View File
@@ -0,0 +1,94 @@
package org.umamo.format.gltf
// Reference sketch for PR 1. Container rules only - the JSON half is
// kotlinx-serialization-json, already a :format dependency. Everything here is
// commonMain-safe: no java.nio, no platform math, no assumption about byte order
// beyond the one the format states.
/** GLB magic, "glTF" read as a little-endian uint32. */
public const val GLB_MAGIC: Int = 0x46546C67
/** The only container version this reader accepts. */
public const val GLB_VERSION: Int = 2
private const val CHUNK_JSON: Int = 0x4E4F4A42
private const val CHUNK_BIN: Int = 0x004E4942
/** The two chunks a GLB carries, in the order they were read. */
public class GlbChunks(
public val jsonBytes: ByteArray,
public val binBytes: ByteArray,
)
public class GlbException(message: String) : Exception(message)
/**
* Reads the GLB container.
*
* Three rules that are easy to get wrong and are enforced here rather than assumed:
*
* 1. The declared total length must equal the actual length. A file that declares more than it
* holds reads as a truncated chunk, and a truncated chunk is an error, not a short read.
* 2. Chunk data is padded to a 4-byte boundary - spaces for JSON, zeros for BIN. The padding is
* part of the chunk length, so the JSON bytes handed back include it. The JSON parser must
* not be given the padding as content; trim before parsing.
* 3. An unknown chunk type is skipped, not rejected. A GLB with an extra chunk is still a valid
* GLB. More than one chunk of a known type is not.
*
* @param ByteArray data The whole file.
* @return GlbChunks The JSON and BIN chunks.
*/
public fun readGlb(data: ByteArray): GlbChunks {
if (data.size < 12) {
throw GlbException("shorter than the 12-byte header")
}
if (readUint32(data, 0) != GLB_MAGIC) {
throw GlbException("magic is not 'glTF'")
}
val version = readUint32(data, 4)
if (version != GLB_VERSION) {
throw GlbException("container version $version, this reader accepts 2")
}
val declared = readUint32(data, 8)
if (declared != data.size) {
throw GlbException("declared length $declared, actual ${data.size}")
}
var json: ByteArray? = null
var bin: ByteArray? = null
var pos = 12
while (pos + 8 <= data.size) {
val length = readUint32(data, pos)
val type = readUint32(data, pos + 4)
val start = pos + 8
if (start + length > data.size) {
throw GlbException("chunk at $pos declares $length bytes, only ${data.size - start} remain")
}
val payload = data.copyOfRange(start, start + length)
if (type == CHUNK_JSON) {
if (json != null) {
throw GlbException("more than one JSON chunk")
}
json = payload
} else if (type == CHUNK_BIN) {
if (bin != null) {
throw GlbException("more than one BIN chunk")
}
bin = payload
}
// An unknown type is skipped.
pos = start + length
}
if (json == null) {
throw GlbException("no JSON chunk")
}
return GlbChunks(json, bin ?: ByteArray(0))
}
/** Little-endian uint32. glTF is little-endian everywhere; there is no host-order reading here. */
private fun readUint32(data: ByteArray, offset: Int): Int =
(data[offset].toInt() and 0xFF) or
((data[offset + 1].toInt() and 0xFF) shl 8) or
((data[offset + 2].toInt() and 0xFF) shl 16) or
((data[offset + 3].toInt() and 0xFF) shl 24)
+115
View File
@@ -0,0 +1,115 @@
package org.umamo.format.gltf
// Reference sketch for PR 1: accessor resolution. This is the part of the reader with rules
// that produce wrong numbers silently rather than failing, so it is written as its own seam.
public class GltfException(message: String) : Exception(message)
/** glTF component types. The codes are the format's constants, not Umamo's. */
public enum class ComponentType(val code: Int, val byteSize: Int) {
Int8(5120, 1),
Uint8(5121, 1),
Int16(5122, 2),
Uint16(5123, 2),
Uint32(5125, 4),
Float32(5126, 4);
public companion object {
/** An unknown code is a hard failure, not a fallback: a wrong component size shifts every value after it. */
public fun fromCode(code: Int): ComponentType =
entries.firstOrNull { it.code == code } ?: throw GltfException("unknown componentType $code")
}
}
/** Number of components per element. */
public enum class ComponentCount(val code: String, val components: Int) {
Scalar("SCALAR", 1),
Vec2("VEC2", 2),
Vec3("VEC3", 3),
Vec4("VEC4", 4);
public companion object {
public fun fromCode(code: String): ComponentCount =
entries.firstOrNull { it.code == code } ?: throw GltfException("unknown accessor type $code")
}
}
public data class BufferView(
val bufferIndex: Int,
val byteOffset: Int,
val byteLength: Int,
val byteStride: Int?,
)
public data class Accessor(
val bufferViewIndex: Int,
val byteOffset: Int,
val componentType: ComponentType,
val componentCount: ComponentCount,
val count: Int,
val byteStride: Int?,
)
/**
* Reads one accessor as floats.
*
* Two rules enforced here:
*
* 1. The resolved byte offset must be a multiple of the component size. glTF states this as a
* validity requirement; a reader that ignores it reads a shifted value and gets a plausible
* wrong number rather than an error. This is the single most common glTF corruption.
* 2. The read must stay inside the buffer view's byteLength. Reading past it is an error, not a
* zero fill - a zero-filled vertex collapses a mesh quietly.
*
* `normalized` is deliberately not applied. A reference layer needs raw positions and indices;
* normalizing a position would scale it by 65535. If a material factor ever needs it, that is a
* separate read, not this one.
*
* @param ByteArray bin The BIN chunk.
* @param List<BufferView> views The document's buffer views.
* @param Accessor accessor The accessor to read.
* @return FloatArray The values, element-major.
*/
public fun readFloats(bin: ByteArray, views: List<BufferView>, accessor: Accessor): FloatArray {
val view = views[accessor.bufferViewIndex]
val size = accessor.componentType.byteSize
val n = accessor.componentCount.components
val stride = accessor.byteStride ?: view.byteStride ?: size * n
val start = view.byteOffset + accessor.byteOffset
if (start % size != 0) {
throw GltfException("accessor byte offset $start is not a multiple of component size $size")
}
val needed = (accessor.count - 1) * stride + size * n
if (start + needed > view.byteLength) {
throw GltfException("accessor reads $needed bytes, buffer view holds ${view.byteLength}")
}
val out = FloatArray(accessor.count * n)
for (i in 0 until accessor.count) {
for (c in 0 until n) {
out[i * n + c] = readComponent(bin, start + i * stride + c * size, accessor.componentType)
}
}
return out
}
private fun readComponent(bin: ByteArray, offset: Int, type: ComponentType): Float {
val b = (bin[offset].toInt() and 0xFF) or
((bin[offset + 1].toInt() and 0xFF) shl 8) or
((bin[offset + 2].toInt() and 0xFF) shl 16) or
((bin[offset + 3].toInt() and 0xFF) shl 24)
return when (type) {
ComponentType.Float32 -> Float.fromBits(b)
ComponentType.Uint32 -> b.toLong().and(0xFFFFFFFFL).toFloat()
ComponentType.Int8 -> bin[offset].toInt().toFloat()
ComponentType.Uint8 -> (bin[offset].toInt() and 0xFF).toFloat()
ComponentType.Int16 -> shortAt(bin, offset).toInt().toFloat()
ComponentType.Uint16 -> (shortAt(bin, offset).toInt() and 0xFFFF).toFloat()
}
}
private fun shortAt(bin: ByteArray, offset: Int): Short {
val v = (bin[offset].toInt() and 0xFF) or ((bin[offset + 1].toInt() and 0xFF) shl 8)
return v.toShort()
}