Skip to content

Latest commit

 

History

History
1005 lines (916 loc) · 67.1 KB

MODELS.md

File metadata and controls

1005 lines (916 loc) · 67.1 KB

Models: meshes, materials, BeginMode3D, 3D shapes and model files

raylib's CPU mesh data, the mesh generators (the par_shapes sphere, hemisphere and torus included, under the glibc profiles), mesh utilities and export, mesh/model collision queries, BeginMode3D/EndMode3D for orthographic cameras, every rmodels.c 3D shape, materials, DrawMesh/DrawModel*/billboards and OBJ (with MTL) loading, all reproducing pinned raylib 6.2 exactly. Altered Bend adaptations of rmodels.c and of rcore.c's BeginMode3D/EndMode3D (zlib, LICENSES/raylib.txt); 3D drawing renders through the Bend adaptation of rlsw.h 1.5 (MIT, LICENSES/rlsw.txt) described in FRAME.md and RLGL.md. Code: the section "Models" of jonlib.bend, src/mesh.bend (attribute generation, tangents, bounding boxes, OBJ and code text), src/par_shapes.bend (the par_shapes adaptation, MIT, LICENSES/par_shapes.txt), src/shapes3d.bend (the rlgl streams of the 3D shapes), src/mesh_draw.bend (the DrawMesh and DrawBillboardPro streams) and src/obj.bend (the tinyobj_loader_c adaptation raylib vendors, MIT, LICENSES/tinyobj_loader_c.txt).

Mesh and Model

type MeshBones is Data:
  MeshBones{indices: +List<U32>, weights: +List<F32>, animated: Maybe<&2, +List<F32>>}

type Mesh is Data:
  Mesh{vertex_count: U32, triangle_count: U32, vertices: Maybe<&2, +List<F32>>, texcoords: Maybe<&2, +List<F32>>,
    texcoords2: Maybe<&2, +List<F32>>, normals: Maybe<&2, +List<F32>>, tangents: Maybe<&2, +List<F32>>,
    colors: Maybe<&2, +List<U32>>, indices: Maybe<&2, +List<U32>>, bones: Maybe<&2, MeshBones>}

type MaterialMap is Data:
  MaterialMap{texture: TextureInfo, color: U32, value: F32}

type Material is Data:
  Material{maps: +List<MaterialMap>, params: +List<F32>}

type Model is Data:
  Model{transform: M.Matrix, meshes: +List<Mesh>, materials: +List<Material>, mesh_material: +List<U32>}

A Mesh holds raylib's CPU attribute arrays as F32 (or byte/index) lists in raylib's order, None where raylib's pointer is NULL. Indices are the unsigned short values (generators take them modulo 2^16, as C converts). Vertex arrays raylib allocates with zero elements (malloc(0)) are Some{Nil}. bones is raylib 6.2's bone data: boneIndices (four unsigned chars a vertex) and boneWeights (four floats a vertex) as a loader leaves them, kept together (raylib may hold one alone, but only the pair is ever read), and animVertices (animated), None until UpdateModelAnimation skins the mesh; DrawMesh then draws them instead of the vertices (see Poses). animNormals are not modeled: the software renderer's glNormalPointer does nothing, so they reach no pixel, and no API reads them back. GPU buffer ids (vaoId, vboId, all 0 on the software renderer) are not modeled; UnloadMesh and UnloadModel consume the value. A Model keeps its transform, meshes, materials and the material index of each mesh (meshMaterial, C ints as U32 words); LoadModelFromMesh is Model.from_mesh (identity transform, Material.load_default(), mesh material 0).

A Material holds raylib's 12 maps (MAX_MATERIAL_MAPS) and four params. A map's texture is raylib's Texture2D struct as a TextureInfo (id 0: no texture); the texels stay with the Texture value that owns them (Jonlib textures are affine, TEXTURES.md). Drawing a mesh whose diffuse map names a texture therefore takes the textures as a list and hands them back: the one with the map's id is bound, as raylib binds the id it holds. Shaders are not modeled: on the software renderer every shader id is 0 (rlGetShaderIdDefault, and LoadShader compiles nothing under OpenGL 1.1).

Consumers check that a mesh is consistent: each present attribute holds vertex_count elements, indices 3*triangle_count, counts below 2^22 (raylib's int size arithmetic). An inconsistent mesh, or a triangle index not below vertex_count, would make raylib read outside its arrays; Jonlib answers None.

API

raylib Jonlib Result
GenMeshPoly Mesh.gen_poly_for(libm, sides, radius), Mesh.gen_poly Maybe<Mesh>
GenMeshPlane Mesh.gen_plane(width, length, res_x, res_z) Maybe<Mesh>
GenMeshCube Mesh.gen_cube(width, height, length) Mesh
GenMeshSphere Mesh.gen_sphere_for(arithmetic, libm, radius, rings, slices), Mesh.gen_sphere Maybe<Mesh>
GenMeshHemiSphere Mesh.gen_hemi_sphere_for(arithmetic, libm, after_sphere, radius, rings, slices), Mesh.gen_hemi_sphere Maybe<Mesh>
GenMeshTorus Mesh.gen_torus_for(arithmetic, libm, radius, size, rad_seg, sides), Mesh.gen_torus Maybe<Mesh>
GenMeshCylinder Mesh.gen_cylinder_for(arithmetic, libm, radius, height, slices), Mesh.gen_cylinder Maybe<Mesh>
GenMeshCone Mesh.gen_cone_for(arithmetic, libm, radius, height, slices), Mesh.gen_cone Maybe<Mesh>
GenMeshKnot Mesh.gen_knot_for(arithmetic, libm, radius, size, rad_seg, sides), Mesh.gen_knot Maybe<Mesh>
GenMeshHeightmap Mesh.gen_heightmap_for(arithmetic, image, size), Mesh.gen_heightmap Result<&1, &1, Surface & Surface.Error, Mesh>
GenMeshCubicmap Mesh.gen_cubicmap(image, cube_size) Result<&1, &1, Surface & Surface.Error, Mesh>
GenMeshTangents Mesh.gen_tangents_for(arithmetic, mesh), Mesh.gen_tangents Maybe<Mesh>
GetMeshBoundingBox Mesh.bounding_box_for(libm, mesh), Mesh.bounding_box Maybe<BoundingBox>
ExportMesh Mesh.obj_text(mesh) -> Maybe<String>, Mesh.export(mesh, path) text / IO(Result<&1, &1, Surface.IOError, Unit>)
ExportMeshAsCode Mesh.code_text(mesh, path) -> Maybe<String>, Mesh.export_as_code(mesh, path) text / IO(Result<...>)
UnloadMesh Mesh.unload(mesh) -> Unit
UploadMesh Mesh.upload(mesh, dynamic) -> Mesh the mesh given: vertex buffers are OpenGL 3.3/ES2's
UpdateMeshBuffer Mesh.update_buffer(mesh, index, size, offset) -> Maybe<Mesh> the mesh given: vboId[index] is 0 on the software renderer and rlUpdateVertexBuffer does nothing, the data is not read; None for an index outside the 9 vertex buffers UploadMesh allocates in the reference build (GPU skinning adds the bone ids and weights) (vboId read past its end)
LoadModelFromMesh / UnloadModel Model.from_mesh(mesh), Model.unload(model)
IsModelValid Model.is_valid(model) Bool
SetModelMeshMaterial Model.set_mesh_material(model, mesh_id, material_id) Maybe<Model>
LoadModel Model.load_for(arithmetic, frame, path), Model.load(frame, path) IO(Frame & Result<&1, &1, Surface.IOError, LoadedModel>)
LoadMaterials Material.load_materials_for(arithmetic, frame, path), Material.load_materials IO(Frame & Result<&1, &1, Surface.IOError, LoadedMaterials>)
LoadMaterialDefault / IsMaterialValid Material.load_default(), Material.is_valid(material) Material / Bool
UnloadMaterial Material.unload(frame, textures, material) Frame & List<Texture>
SetMaterialTexture Material.set_texture(material, map_type, info) Maybe<Material>
DrawMesh / DrawMeshInstanced Draw.mesh(frame, textures, mesh, material, transform), Draw.mesh_instanced(frame, textures, mesh, material, transforms) Frame & List<Texture>
DrawModel / DrawModelEx Draw.model(frame, textures, model, position, scale, tint), Draw.model_ex_for(libm, frame, textures, model, position, axis, angle, scale, tint), Draw.model_ex Frame & List<Texture>
DrawModelWires / DrawModelWiresEx Draw.model_wires, Draw.model_wires_ex_for, Draw.model_wires_ex (the same parameters) Frame & List<Texture>
DrawBillboard / DrawBillboardRec / DrawBillboardPro Draw.billboard(frame, camera, texture, position, scale, tint), Draw.billboard_rec(frame, camera, texture, source, position, size, tint), Draw.billboard_pro_for(libm, frame, camera, texture, source, position, up, size, origin, rotation, tint), Draw.billboard_pro Frame & Texture
GetModelBoundingBox Model.bounding_box_for(arithmetic, libm, model), Model.bounding_box Maybe<BoundingBox>
GetRayCollisionMesh Collision.ray_mesh_for(arithmetic, ray, mesh, transform), Collision.ray_mesh Maybe<RayCollision>
BeginMode3D / EndMode3D Frame.begin_mode_3d_for(libm, frame, camera) (Frame.begin_mode_3d(frame, camera): AppleLibm), Frame.end_mode_3d(frame) Frame
DrawLine3D / DrawPoint3D Draw.line_3d(frame, start, end, color), Draw.point_3d(frame, position, color) Frame
DrawCircle3D Draw.circle_3d_for(libm, frame, center, radius, axis, angle, color) Frame
DrawTriangle3D / DrawTriangleStrip3D Draw.triangle_3d(frame, v1, v2, v3, color), Draw.triangle_strip_3d(frame, points, color) Frame
DrawCube(V) / DrawCubeWires(V) Draw.cube, Draw.cube_v, Draw.cube_wires, Draw.cube_wires_v Frame
DrawSphere / DrawSphereEx / DrawSphereWires Draw.sphere_for, Draw.sphere_ex_for, Draw.sphere_wires_for Frame
DrawCylinder(Wires) / DrawCylinder(Wires)Ex Draw.cylinder_for, Draw.cylinder_wires_for, Draw.cylinder_ex_for, Draw.cylinder_wires_ex_for Frame
DrawCapsule / DrawCapsuleWires Draw.capsule_for, Draw.capsule_wires_for Frame
DrawPlane / DrawRay / DrawGrid / DrawBoundingBox Draw.plane, Draw.ray, Draw.grid, Draw.bounding_box Frame

Every _for function has a convenience form without the profiles (M.Uncontracted{}, M.AppleLibm{}, as elsewhere; the par_shapes generators use M.Glibc239Libm{}, the only profile they support). C int parameters of the drawing functions (rings, slices, sides, grid slices) are F32 values converted as C converts them; the generators take U32 counts. Points of DrawTriangleStrip3D are a +List<M.Vector3> (its count is the length).

Profiles

  • Contraction (M.Contraction). The raymath helpers rmodels.c inlines are contracted by the reference compiler where it contracts (Apple clang arm64): cross products fma(a, b, -(c*d)), dot products and lengths fma(z, w, fma(x, u, y*v)), Vector3Transform fused three-term sums plus the translation, and the tangent terms (t2*x1 - t1*x2)*r as fma(t2, x1, -(t1*x2))*r. GenMeshHeightmap (normals), GenMeshTangents, GetRayCollisionMesh and GetModelBoundingBox take the profile, as do the par_shapes generators (their cross and dot products, the welding distance and the torus radius 1 + minor*cos); the other generators have no multiply-add. The 3D shapes are drawn as the frame is: uncontracted (the reference renderer is built with -ffp-contract=off, FRAME.md).
  • libm (M.Libm). sinf/cosf arguments must lie in the profile's verified set (FRAME.md): under M.AppleLibm{} the integral degrees fl(DEG2RAD*d), |d| <= 360 (except 13, 19, 22, 103, 188); under the glibc profiles every normal or zero argument (SINCOSF.md). Other arguments refuse the call (None, or an undefined frame). GetMeshBoundingBox uses fminf/fmaxf and so the profile's signed-zero ties (NATIVE-MATH-PROFILES.md).

Generators

  • GenMeshPoly emits sides triangles (origin, p(d), p(d + step)) with d accumulating 360/sides in F32, p(d) = (sinf(DEG2RAD*d)*r, 0, cosf(DEG2RAD*d)*r), normals (0, 1, 0) and zero texcoords. Fewer than 3 sides give the empty mesh; more than 4096 sides are None. Under M.AppleLibm{} the sides whose steps stay on verified degrees (3, 4, 5, 6, 8, 9, 10, 12, 15, 18, 20, 24, 36, ...) are reproduced.
  • GenMeshPlane follows the CUSTOM_MESH_GEN_PLANE path: `(resX + 1)*(resZ
    • 1)vertices((x/resX - 0.5)*width, 0, (z/resZ - 0.5)*length), texcoords (x/resX, z/resZ)and two indexed triangles per face. A resolution of 0 divides 0 by 0 (a NaN whose sign is platform-defined) and grids above 2^20 vertices areNone`.
  • GenMeshCube (CUSTOM_MESH_GEN_CUBE): 24 vertices with -width/2 ... coordinates, per-face normals and texcoords, 36 indices.
  • GenMeshHeightmap loads the image's colors (LoadImageColors, any format Jonlib converts), heights (r + g + b)/3*size.y/255, one quad per 2x2 pixels (vertices A B C C B F), per-triangle normals Vector3Normalize(Vector3CrossProduct(B - A, C - A)). Images 1 pixel wide or tall give vertex_count 0 with empty (present) arrays.
  • GenMeshCubicmap: WHITE (0xFFFFFFFF) cells become cubes whose top and bottom are always emitted and whose sides are emitted toward BLACK (0x000000FF) neighbors or the map border; BLACK cells get a floor and a roof; other colors nothing. Texcoords are the six 0.5-wide atlas rectangles of rmodels.c.
  • GenMeshTangents accumulates per-triangle sdir/tdir (r = 0 when |s1*t2 - s2*t1| < 0.0001f) per vertex, then Gram-Schmidt against the normal, Vector3Normalize((-n.y, n.x, 0)) (or (1, 0, 0) when |n.z| > 0.707f) for tangents shorter than 0.0001f, and the handedness from dot(cross(n, t), bitangent) < 0. A mesh without vertices, texcoords or normals is returned unchanged; existing tangents are replaced.
  • GetMeshBoundingBox: Vector3Min/Vector3Max from the first vertex over the vertices the signed count reads (one vertex when the count is not positive, otherwise vertex_count); floats past that read and every other attribute are ignored. A null vertex buffer is the zero box. A buffer shorter than the read is None.

par_shapes generators

GenMeshSphere, GenMeshHemiSphere and GenMeshTorus build a par_shapes parametric mesh (Philip Rideout, MIT, LICENSES/par_shapes.txt), ported in src/par_shapes.bend:

  • Points. (slices + 1)*(stacks + 1) points from u = stack/stacks, v = slice/slices; the angles are (float)(u*PAR_PI) (or (u*2)*PAR_PI) with PAR_PI = 3.14159265359 multiplied in binary64 and rounded to F32 (BINARY64.md), then sinf/cosf. Sphere (cos t sin p, sin t sin p, cos p) (t over a full turn), hemisphere the same over half a turn, torus (cos t*b, sin t*b, sin p*minor) with b = 1 + minor*cos p (fused under M.Fused{}). Texcoords are (u, v).
  • Welded normals. par_shapes_weld maps the points into a 20-cell grid ((p - min)*19/(max - min) per axis), sorts them by cell index with qsort, welds each unwelded point's neighbors in the cells within 0.001f whose squared distance is below 0.001f, condenses the points, drops collapsed triangles and maps the welded points back; the normals are par_shapes_compute_normals of that welded mesh (summed cross products, normalized), shared by every point of a weld.
  • The sort is the C library's. qsort does not specify the order of equal keys, and the first point of a cell becomes the weld representative whose coordinates enter the normals: building par_shapes.h with the host qsort, a stable sort and a reverse-stable one changes the normals of 26 of 27 meshes tried. Jonlib reproduces glibc's qsort (a stable merge sort; Jonlib uses a stable counting sort, the same order), so these generators need a glibc M.Libm profile; under M.AppleLibm{} they are None (macOS sinf/cosf is not verified on these angles either). Their convenience forms therefore use M.Glibc239Libm{}.
  • Degenerate triangles. The sphere and hemisphere drop triangles whose squared cross product is below (2*area)^2. par_shapes keeps area as process state: 0.0001f initially, and GenMeshSphere sets it to 0 for the rest of the process. Mesh.gen_hemi_sphere_for takes that state as after_sphere.
  • Refusals (None). Meshes above 65535 points (par_shapes' 16-bit indices wrap), welds raylib leaves undefined (a point welded to a later one makes it read an unset map entry), nonfinite radii or sizes. Fewer than 3 slices or stacks give raylib's empty mesh.

The generated mesh is scaled (radius, or size/2 for the torus) and unrolled per triangle corner as raylib does (no indices).

GenMeshCylinder and GenMeshCone build par_shapes' cylinder or cone of 8 stacks (the same parametric grid and welded normals), then:

  • par_shapes_scale(radius, radius, height): the points, and unless the three factors are equal the normals by the inverse factors, normalized (a zero factor follows par_shapes' rules: the normals keep only the axis that is alone at zero);
  • par_shapes_rotate by -PI/2.0f around X (and for the cone PI/2.0f around Y): a matrix from sinf/cosf applied to points and normals;
  • par_shapes_create_disk caps: a fan around the origin whose rim is (float)(radius*cos(theta)), (float)(radius*sin(theta)) with theta = (float)(i*PAR_PI*2/slices), every operation in binary64 (M.Libm.cos64/sin64, MATH.md). par_shapes then rotates the disk by (float)acos(normal.z) around the cross product of its normal and (0, 0, -1), which is the zero vector for these normals: nothing for the top disk, and a matrix of cosf(pi) on the diagonal for the bottom one (the points and the normal change sign);
  • the caps' own rotations and the top one's translation, their texture coordinates (0 on top, 0.95 below), and par_shapes_merge.

They need M.Glibc239Libm{} (the only profile with the binary64 cos and sin) and M.Uncontracted{}; another profile or M.Fused{} is None.

GenMeshKnot builds par_shapes' trefoil knot (radSeg slices by sides stacks, the radius clamped to 0.5f..3) with welded normals and scales it by size. par_shapes__trefoil computes in double around cos and sin of float angles and stores every intermediate in a float: the curve r = a + b*cos(1.5f*u), (r*cos(u), r*sin(u), c*sin(1.5f*u)), its tangent q (normalized in float), qvn = normalize(q.y, -q.x, 0), ww = cross(q, qvn) and the point x + d*(qvn.x*cos(v) + ww.x*sin(v)), ..., z + (d*ww.z)*sin(v) with d = radius*0.1f. Each sum and product is one binary64 operation in the source's order (the last one a float product first), narrowed where the source assigns a float.

Gate mesh-tube (tools/mesh_tube_probe.py) compares hashes of the vertices, texture coordinates and normals of 88 meshes with the native generators: cylinders and cones of 3 to 40 slices with equal, unequal, zero and negative sizes, and eight knots (the 16 x 128 one of models_mesh_generation, the smallest, radii outside the clamp, a zero and a negative size), on a host whose sin and cos reproduce the glibc 2.39 controls.

Export

  • ExportMesh writes, for a .obj path (ASCII case-insensitive, as IsFileExtension), raylib's banner, # Vertex Count/# Triangle Count, g mesh, v %.6f %.6f %.6f, vt %.6f %.6f and vn %.4f %.4f %.4f lines and f a/a/a b/b/b c/c/c faces (indices + 1, or 1, 4, 7, ... without indices), formatted exactly as C's %.Nf (FILES.md; NaN, whose spelling differs between C libraries, is None). raylib dereferences the texcoords and normals, so a mesh without them is None, as is text longer than raylib's estimated buffer (dataSize + 1000 bytes, dataSize from the counts) and inconsistent meshes. Other extensions write nothing (raylib returns false): InvalidRequest.
  • ExportMeshAsCode writes the banner, <NAME>_VERTEX_COUNT and <NAME>_TRIANGLE_COUNT defines and one array per present attribute (vertices, texcoords, texcoords2, normals, tangents as %.3ff; colors as 0x%x; indices as %i), 20 values per line, where NAME is GetFileNameWithoutExt with a-z upper-cased. A present empty array makes raylib read element -1: None; text beyond the 64 MB buffer is None.

Materials

  • LoadMaterialDefault (Material.load_default): 12 zeroed maps; the diffuse map holds (Texture2D){ rlGetTextureIdDefault(), 1, 1, 1, 7 }, whose id is 0 under OpenGL 1.1, and the diffuse and specular colors are WHITE.
  • IsMaterialValid needs shader.id > 0: always false on the software renderer (the probe checks it natively).
  • SetMaterialTexture stores the texture struct (TextureInfo, from Texture.info) in the map; the previous texture is not unloaded. A map type of 12 or more makes raylib write past the maps: None.
  • UnloadMaterial unloads, in map order, every map texture whose id is not 0 (rlGetTextureIdDefault()). Those textures are taken from the list passed in and unloaded into the frame (their ids return to the pool, so the next texture reuses them); the others are handed back. A second map with an id already unloaded is an rlsw no-op (swDeleteTextures ignores invalid ids). Refused (the frame marked undefined): an id that is not in the list (raylib would unload a texture Jonlib does not hold) or a primitive being recorded.
  • SetModelMeshMaterial with C int ids as U32 words: a mesh id at or beyond the mesh count, or a non-negative material id at or beyond the material count, changes nothing (raylib warns); a negative material id is stored as raylib stores it (drawing that mesh is refused); a negative mesh id makes raylib write before the array: None.
  • IsModelValid requires meshes, materials and mesh materials, and every present attribute uploaded to a GPU buffer. UploadMesh creates no buffers under OpenGL 1.1, so on the software renderer only models whose meshes have no attributes at all (raylib's empty generated meshes) are valid. Meshes are assumed uploaded, as every generator and loader leaves them (raylib dereferences a NULL vboId for a mesh it never uploaded).

Drawing meshes, models and billboards

What rmodels.c does under GRAPHICS_API_OPENGL_SOFTWARE (which defines GRAPHICS_API_OPENGL_11), traced in the pinned sources and checked by the probe:

  • DrawMesh takes its OpenGL 1.1 branch: rlEnableTexture(diffuse id) when the mesh has texcoords and the id is positive, rlEnableStatePointer for vertices, texcoords and colors (rlsw ignores normals), rlPushMatrix, rlMultMatrixf(transform), rlColor4ub(diffuse color), then rlDrawVertexArray(0, vertexCount) or rlDrawVertexArrayElements(0, 3*triangleCount, indices), rlPopMatrix, the state pointers disabled and rlDisableTexture. rlsw's swDrawArrays/swDrawElements push every vertex through the immediate path as GL_TRIANGLES: the texcoord (through the texture matrix), the color (byte*SW_INV_255) when the mesh has colors, then the position; a vertex count that is not a multiple of 3 leaves its last vertices pending. Their begin resets rlsw's per-primitive alpha flag, so a translucent material color alone does not blend: the triangles are stored with the material's alpha, unblended. A mesh without vertices draws nothing (an rlsw error) but still sets the color and the texture state. Inside an rlBegin primitive rlsw refuses the arrays: Jonlib refuses the call.
  • DrawMeshInstanced is compiled only for OpenGL 3.3 and ES2: a no-op.
  • DrawModelEx multiplies the model transform by MatrixMultiply(MatrixMultiply(MatrixScale, MatrixRotate(axis, angle*DEG2RAD)), MatrixTranslate) (raymath, uncontracted as the reference renderer is built; sinf/cosf from the M.Libm profile, an unverified argument refuses the draw), then draws each mesh with its material, whose diffuse color is tinted per channel as (c*t)/255. DrawModel is DrawModelEx about (0, 1, 0) by 0 degrees with a uniform scale. The Wires forms wrap them in rlEnableWireMode/rlDisableWireMode (polygons are filled afterwards, whatever the mode was). DrawModelPoints(Ex) is not part of raylib 6.2.
  • DrawBillboardPro takes the first row of MatrixLookAt(camera) as the right vector (scaled by size.x) and up*size.y; a negative size flips the source, the vector and the origin; the corners 0, right, up + right and up, less Normalize(right)*origin.x + Normalize(up)*origin.y, are rotated with Vector3RotateByAxisAngle(cross(right, up), rotation*DEG2RAD) when the rotation is not 0 (sinf/cosf of half the angle, checked for the profile) and moved to the position; texcoords are the source over the texture's int size. One textured RL_QUADS with the tint. DrawBillboardRec uses up (0, 1, 0), origin size*0.5 and no rotation; DrawBillboard the whole texture with size (scale*fabsf(width/height), scale). Billboards use the camera only through MatrixLookAt and draw through the current projection (orthographic in BeginMode3D).

Refused draws mark the frame undefined: inconsistent attribute lists, indices not below the vertex count, color values above 255, a diffuse id missing from the textures, a mesh material index beyond the materials, unverified sinf/ cosf arguments, and the rules of RLGL.md.

Loading models (OBJ and MTL)

Model.load_for(arithmetic, frame, path) is LoadModel: .obj (case-insensitive, as IsFileExtension) through LoadOBJ; .glb files through LoadGLTF (the next section); .vox files through LoadVOX (MagicaVoxel); .iqm files through LoadIQM (Inter-Quake Model); .m3d files through LoadM3D (Model 3D); glTF as text (which raylib loads) is UnsupportedFileType; other extensions, and OBJ files that do not open or are empty, give raylib's model without meshes and with the default material. The result is a LoadedModel{model, textures}: the textures the MTL file's materials loaded into the frame, which raylib's UnloadModel leaves loaded (the caller unloads them). LoadModel sets an identity transform and uploads nothing on the software renderer. The contraction profile is the reference's for tryParseDouble (below); the convenience Model.load uses M.Uncontracted{}.

  • Text. LoadFileText and strlen: the text ends at its first NUL. A text whose first byte is NUL makes tinyobj_parse_obj fail, after which LoadOBJ returns without restoring the working directory: refused.
  • Lines (tinyobj_parse_obj). Lines end at \n and at a \r followed by another byte than \n; a line's \r before its \n is dropped. The last line runs to the end of the text, except that when the text has no terminator at all tinyobj drops its last byte. An empty line after a lone \r underflows its length: refused. A line of up to 4095 bytes is parsed; a longer one makes raylib 6.2's parseLine return before it sets the command's type, which tinyobj_parse_obj then reads from malloc'd memory: refused.
  • Commands (parseLine). v, vn, vt (parseFloat: spaces, then the token up to NUL, space, tab or \r), f (i, i/j, i//k, i/j/k with my_atoi; more than 5 vertices make raylib 6.2's tinyobj return after setting the command's type but not its counts, which are then read uninitialized, and more than 16 overflow its array: refused), usemtl (the rest of the line, trailing spaces included; an empty name keeps the material), mtllib (the last one is loaded), g and o (shapes). mtllib, g or o with nothing after their space make tinyobj read past the line, and an int overflow in an index or exponent is undefined: refused.
  • Numbers (tryParseDouble). The C grammar ([sign] digits ['.' digits] [e [sign] digits], greedy; a failed parse leaves 0) evaluated in binary64 as tinyobj writes it: mantissa*10 + digit, frac_value = 0.1^read by repeated products, mantissa += digit*frac_value (one rounding under M.Fused{}, as the arm64 Apple clang reference contracts it; the probe includes literals near binary32 midpoints that round differently in the two profiles), 5^e and 2^e by repeated products (inverted for a negative exponent), mantissa*a*b and (float). The operations run through Jonlib's checked binary64 helpers (BINARY64.md); a value whose steps leave their domains (more than about 39 integer digits, about 80 fraction digits, exponents above 54) is refused when LoadOBJ reads it (unread values do not matter).
  • Indices and faces. fixIndex makes indices zero-based, negative ones relative to the counts read so far; faces are triangulated as fans (f0, f[k-1], f[k]). Materials come from the MTL file's table (djb2 hashes of the names, 64-bit, in tinyobj's open table of capacity 10 grown to 2*max(capacity, n + 1) with quadratic probing; an insertion that finds no slot loops forever in C: refused); an unknown name is -1.
  • Shapes and meshes (LoadOBJ). tinyobj's shapes record face offsets in face lines; LoadOBJ compares them with triangle indices, starting a new mesh at each shape boundary it crosses and at each material change after a known material (a change from -1 does not split). A mesh holds 3 vertices per triangle: positions, normals ((0, 1, 0) without a valid index) and, when the file has texcoords, texcoords with v flipped as 1 - v (0 without a valid index); colors are NULL under OpenGL 1.1. Its material is that of its last face (0 when that is not an MTL index). An index outside its array (negative after fixIndex or past the end) is skipped, as raylib 6.2's LoadOBJ does: the vertex stays (0, 0, 0), the normal is (0, 1, 0) and the texcoord stays (0, 0).
  • MTL files (tinyobj_parse_and_index_mtl_file) open relative to the OBJ's directory: LoadOBJ changes the working directory to GetDirectoryPath(fileName), and Jonlib prefixes relative names with it instead. Lines come from dynamic_fgets, so a last line without \n is never parsed. newmtl takes sscanf("%s") (a missing name, one of 4096 bytes or more, or a longer line is refused); properties before the first newmtl are lost; Kd, Ks, Ke, Ns and the texture names map_Kd, map_Ks, map_bump/bump and disp (the rest of the line up to \r or \n, after one separator) are used; the other keywords are parsed (and checked for undefined behavior) but unused. A file that does not open leaves no materials; NUL bytes are refused.
  • ProcessMaterialsOBJ. Per material: LoadMaterialDefault, the diffuse texture (else the Kd color), the specular texture and Ks color, the bump texture as the normal map (WHITE, value Ns), the Ke emission color and the displacement texture as the height map. Colors are (unsigned char)(x*255.0f) with alpha 255 (a product outside (-1, 256) is undefined: refused). Textures load in that order with LoadTexture: a file that does not open (or an empty name) gives (Texture2D){ 0 }; a file Jonlib's LoadImage does not decode is refused (raylib may decode it), as are exhausted texture ids.
  • LoadMaterials (Material.load_materials_for): a .mtl file's materials through the same parser and ProcessMaterialsOBJ, with texture names opened from the working directory as they are; other extensions and files that do not open give no materials.
  • Paths. OBJ paths and MTL and texture names must be printable ASCII (Jonlib passes them to the file system unchanged); OBJ paths must not contain backslashes (GetDirectoryPath splits at them, chdir would not) and must fit GetDirectoryPath's buffer. Paths that name directories are outside the contract.

Loading models (binary glTF)

Model.load_for(M.Uncontracted{}, frame, path) of a .glb file is raylib's LoadGLTF for a first slice of the format (src/gltf.bend, with the JSON reader src/json.bend and the decimal conversion src/strtod.bend):

  • Container: the glTF magic, version 2, the total length, a JSON chunk and a BIN chunk holding the one buffer (no uri).
  • Meshes: every node with a mesh, in node order, and each of its triangle primitives (mode 4, the default) becomes one Mesh; other modes are skipped, as in raylib, and one mesh under two nodes is loaded twice.
  • Attributes, in the order the file lists them: POSITION and NORMAL (VEC3 float), TANGENT (VEC4 float), TEXCOORD_0 and TEXCOORD_1 (VEC2 float); a further texcoord set and unknown or custom attributes are ignored. Elements are read as LOAD_ATTRIBUTE reads them: the view's and the accessor's offsets each divided by the component size, the stride (the view's byteStride, or the element size) divided by it as well.
  • Indices of 8, 16 or 32 bits, kept as 16 (raylib truncates); triangleCount is their count over 3, or vertexCount/3 without them.
  • Transforms: the node's world matrix as cgltf computes it in binary32 (matrix, or rotation, scale and translation; then each ancestor's 3x3 part and translation), applied to positions and tangents with Vector3Transform, and its inverse transpose to normals. JSON numbers are (float)atof(...), through M.Float64.from_decimal.
  • Materials: the default material, then one per glTF material with its baseColorFactor as the albedo color ((unsigned char)(factor*255); white without pbrMetallicRoughness) and its baseColorTexture as the albedo texture: the image's bytes from its buffer view (mime type image/png), decoded as LoadImageFromMemory(".png") does and uploaded, in material order, so the texture ids are the reference's. The textures come back with the model. A texture without a source and an image with neither a uri nor a buffer view give no texture, as in raylib. meshMaterial is the primitive's material index plus one, or 0.
  • Skins: a skinned mesh's vertices are placed as any other's, and its bone data comes from a second walk over the nodes, for every triangle primitive, skins or not. JOINTS_n (a VEC4 of 8 or 16 bits; 16-bit indices kept as (unsigned char)) becomes boneIndices, WEIGHTS_n (a VEC4 of 8 or 16 bits, divided by 255.0f or 65535.0f, or of floats) boneWeights, read as LOAD_ATTRIBUTE reads them into buffers of vertexCount*4 elements (zeros past the accessor's); a later attribute of a kind replaces an earlier one (JOINTS_1 included). With skins, a primitive without JOINTS_n of a node whose parent has no mesh and is one of the first skin's joints (its first place there) has every vertex attached to that bone: boneIndices[4k] the bone as an unsigned char, boneWeights[4k] 1, zeros after. The skeleton and the animations are below.
  • Indices of other sections: cgltf fails the parse when an index points past its array (a texture's source or sampler, an image's buffer view, a material's texture, a skin's joints, skeleton or inverse bind matrices, a node's children, mesh, skin or camera, a scene's nodes, an animation's samplers and channels); such a file is refused.

The loader refuses (OutOfDomain) everything else the reference would read: the other texture kinds (metallic-roughness, normal, occlusion, emissive), an image given by a uri, in another format than PNG (JPEG included), through a strided buffer view, without a mime type, or that does not decode; a texture with extensions; COLOR_n attributes; JOINTS_n or WEIGHTS_n of another layout (raylib only warns and keeps the earlier data) or with more elements than the mesh has vertices (a write past the mesh's buffers natively); other component types, sparse accessors, an accessor without a buffer view, primitive extensions and morph targets, required extensions, a buffer outside the file, an accessor that reaches past the buffer (an out-of-bounds read natively), a node with two parents, a color factor outside 0..1, a number M.Float64.from_decimal does not answer, JSON that is not well formed, and contracted arithmetic. glTF as text (.gltf) is UnsupportedFileType. A missing file gives the empty model, as raylib does.

Skeletons and animations

Jonlib's Model has no skeleton, so a model's is loaded beside it:

raylib Jonlib Result
model.skeleton after LoadModel Model.load_skeleton(path) IO(Result<IOError, ModelSkeleton>): ModelSkeleton{bones, bind_pose} with BoneInfo{name, parent} (parent 4294967295 for -1) and Transforms; no bones without a skin
LoadModelAnimations Model.load_animations_for(libm, path) / Model.load_animations(path) IO(Result<IOError, List<ModelAnimation>>): ModelAnimation{name, bone_count, keyframe_count, keyframe_poses}; no animations without a skin
UnloadModelAnimations Model.unload_animations(animations) Unit

For a .glb file (src/gltf_anim.bend, over the loader's container, accessor and node code):

  • Bones: the first skin's joints, each with its node's name (31 bytes, as strncpy keeps) and its parent bone: raylib 6.2 walks up from the joint's parent node past every node that is not a joint, to the first joint (its place among the joints) or the root (-1).
  • Bind pose: with inverse bind matrices for every joint (an accessor of at least joints_count elements), MatrixDecompose(MatrixInvert(inverseBindMatrices[i])); without them, or with fewer, MatrixDecompose of each joint's world matrix.
  • Animations: for each one, the channels whose node is a joint (a later channel for the same bone and path replaces an earlier one; raylib 6.2 reads each channel's own sampler interpolation); the duration is the largest last key time of those channels; keyframeCount = (int)(duration*60) + 1, frame j at j/60 seconds.
  • Poses: each bone starts from its node's translation, rotation and scale and takes its channels' values at the frame's time: the key i with times[i] <= time < times[i + 1]; without one the last pair (count - 2, so t clamps to 1 and STEP reads the key before the last), or the first pair when the time is before the first key (t clamps to 0); a sampler of one key is constant. t = (time - tstart)/max(tend - tstart, EPSILON) clamped to 0..1, the key's value for STEP or equal key times, else Vector3Lerp or QuaternionSlerp to the next key. Each joint's pose is then composed as a matrix (scale, rotation, translation), multiplied by its extOffset (the product, from the joint's parent up to its parent bone or the root, of each node that is not a joint, built the same way from its own translation, rotation and scale) and decomposed again (MatrixDecompose); every bone is then composed with its parent's (BuildPoseFromParentJoints: a bone listed before its parent is left as it is). The root bone is not composed with the world transform of the first joint's parent node.
  • libm: QuaternionSlerp calls acosf and sinf unless the two rotations are within about 36 degrees of each other; Model.load_animations_for takes the profile and refuses where it does not answer (the Apple profile and glibc 2.41 have no acosf here).

Refused (OutOfDomain): CUBICSPLINE samplers, key times or values that are not float accessors inside the buffer, a sampler without keys, a pose that would read past its output accessor, inverse bind matrices (for every joint) that are not float MAT4 elements inside the buffer (cgltf converts other component types, reads zeros without a buffer view and nothing from a sparse accessor), a skin without joints, a cycle of nodes above a joint (the reference's walk does not end), a node with two parents, more than 100000 keyframes, and what the loader refuses of the container. Other extensions are UnsupportedFileType.

Gate gltf-anim (tools/gltf_anim_probe.py) compares the skeleton words and a hash of every keyframe pose of greenman.glb (12 bones, 4 animations) and robot.glb (43 bones, 14 animations), both with inverse bind matrices and joints under nodes that are not joints, and of generated files for each rule above with the native loader. greenman.glb's rotation keys stay within the band above, so that file is compared on every profile; robot.glb's do not, and off Glibc239Libm the load is a contract.

Poses

model.currentPose and model.boneMatrices are a value beside the model too: ModelPose{current, matrices}. The meshes' animVertices are in the model, so the updates that skin take the model and give it back with the pose: AnimatedModel{model, pose}.

raylib Jonlib Result
the pose after LoadModel Model.pose(skeleton) ModelPose: zeroed transforms and an identity matrix for every bone
UpdateModelAnimationBones (6.2) Model.update_animation_bones_for(libm, skeleton, animation, frame, pose) / Model.update_animation_bones(...) Maybe<ModelPose>
UpdateModelAnimationBonesEx (6.2) Model.update_animation_bones_ex_for(libm, skeleton, first, first_frame, second, second_frame, blend, pose) / Model.update_animation_bones_ex(...) Maybe<ModelPose>
UpdateModelAnimation Model.update_animation_for(libm, model, skeleton, animation, frame, pose) / Model.update_animation(...) Maybe<AnimatedModel>
UpdateModelAnimationEx Model.update_animation_ex_for(libm, model, skeleton, first, first_frame, second, second_frame, blend, pose) / Model.update_animation_ex(...) Maybe<AnimatedModel>
IsModelAnimationValid Model.is_animation_valid(skeleton, animation) Bool: the bone counts are equal
  • UpdateModelAnimation: keyframes (int)frame and the next one, each wrapped by the keyframe count when it reaches it; the blend is Clamp(frame - (int)frame, 0, 1); each bone is Vector3Lerp of the translations and scales and QuaternionSlerp of the rotations, and its matrix MatrixInvert(bind pose)*pose, each built as scale, rotation, translation.
  • UpdateModelAnimationEx: each animation at keyframe (int)frame%keyframeCount towards the next one by Clamp(frame - that keyframe, 0, 1): the native function subtracts the wrapped keyframe, so a frame past the count takes the next keyframe whole. The two poses are then blended the same way.
  • Nothing changes (the pose and the model come back) for a skeleton without bones (model.boneMatrices is NULL) and an animation without keyframes; for the blend also when it is outside 0 to 1 or not a number.
  • CPU skinning (raylib 6.2's UpdateModelAnimationVertexBuffers, after the bones in UpdateModelAnimation and UpdateModelAnimationEx, never in the Bones forms): every mesh with bone indices and weights is skinned unless its material's shader has a bone-ids location. On the software renderer none has: the default shader's locations are NULL (rlGetShaderLocsDefault answers them only under OpenGL 3.3/ES2) and LoadShader compiles nothing, so its locations are all -1; Jonlib's materials hold no shader. The first time, animVertices is allocated; each time, every vertex starts at zero and, for each of its four bones in order whose weight is not 0.0f, adds Vector3Transform(vertex, boneMatrices[index]) times the weight, component by component (F32, in that order). A vertex whose weights are all zero goes to the origin (IQM meshes without blend arrays do that whole). The bind vertices are never changed; GetMeshBoundingBox, GetModelBoundingBox and GetRayCollisionMesh read them, as raylib's do. DrawMesh (and so DrawModel, DrawModelEx, the wires and points forms) draws animVertices once there are any. The normals raylib skins beside them reach no pixel on the software renderer and are not modeled.
  • None: a frame whose int conversion or keyframe is undefined (UpdateModelAnimation: -1 and below; the blend: a negative remainder, that is -1 and below unless a multiple of the count; both: 2147483648 and above, or not a number), an animation with fewer bones than the skeleton or fewer poses than its count (read past the end natively), a rotation the libm profile's QuaternionSlerp does not answer, and, in the skinning, a weighted bone index past the skeleton (a read outside boneMatrices) or a mesh whose lists disagree with its counts.

Gate model-pose (tools/model_pose_probe.py) runs one sequence of fifteen calls natively and with Jonlib on greenman.glb, robot.glb (nineteen skinned meshes, 7218 vertices) and on generated models (a quad blending two bones with one vertex of zero weights, a quad without JOINTS_0 under a joint), a model without bones and one with fewer bones than the animations included, and compares a hash of the pose, of the bone matrices and of every mesh's animVertices after every call; the undefined calls are a contract.

One case differs and is outside the contract: an IQM file without joints. LoadIQM allocates its skeleton with zero bones (RL_CALLOC(0), not NULL) and bone data for every mesh, so UpdateModelAnimation skins the meshes there (to the origin without blend weights); Jonlib's ModelSkeleton has no bones either way, and a skeleton without bones changes nothing, as the NULL skeleton of a glTF or M3D file without one does.

Gate gltf (tools/gltf_probe.py) loads generated files covering each of those rules, and the models the examples use (plane.glb, old_car_new.glb: 9281 and 24 vertices under a scaled and translated node; greenman.glb with its skin and 512x512 texture, its hat, sword and shield; robot.glb: 19 primitives under a skin of 43 joints), natively and with Jonlib, and compares every mesh and material word, the albedo texture's id, size and format included.

Loading models (MagicaVoxel)

Model.load_for of a .vox file is LoadVOX over vox_loader.h (src/vox.bend). The file is VOX , a version (150 or 200) and chunks: a name, the size of its contents, the size of its children, its contents.

  • SIZE allocates the voxel array: the file's sizes rounded up to multiples of 16, its Y and Z changed over (Vox_AllocArray(x, z, y)). A second SIZE starts an empty array again.
  • XYZI sets numVoxels voxels, Vox_SetVoxel(x, z, sizeZ - y - 1, id): a voxel set twice keeps its last id, and id 0 empties it. A voxel outside the padded sizes (or before any SIZE, whose sizes are 0) is not set, and a count is cut to the voxels the file holds (raylib 6.2's range checks).
  • RGBA gives palette[1..255] from its first 255 colors (palette[0] and a file without the chunk are all zeros, alpha included). The loader then stands four bytes before the chunk's end: what follows is read as a chunk named by the palette's last color and sized by the next chunk's name, which skips the rest of the file in every MagicaVoxel file (chunks after a palette are not seen). That quirk is kept.
  • Any other chunk is skipped by its size; a size that passes the end of the file ends the reading.
  • The reading also ends, keeping what was read, where fewer bytes are left than a chunk header (12), a SIZE (12), a voxel count (4) or a palette (1020) needs; a file that ends with its palette leaves four bytes, so it ends there.

The mesh has a quad for every face of a voxel whose neighbor is empty or outside the array, in the loader's order: x, then z, then y, and for a voxel the faces -X, +X, -Y, +Y, -Z, +Z. Corners are (corner + position) * 0.25, normals the face's axis, colors the voxel's palette color four times, indices 0 2 1 and 0 3 2 from the quad's first vertex. LoadVOX makes 1 + vertices/65536 meshes of 65532 vertices each and what remains in the last (when that is more than 65532 the vertices past it are left out, as upstream), all with the default material and an identity transform. A mesh keeps the 3*triangleCount indices its triangles use (the reference copies the whole index array into each mesh; the rest is never read).

UnsupportedFileType is not an answer here: a file that is not VOX or has another version, an empty file and one that does not open are the empty model, as in raylib. OutOfDomain for what the reference leaves undefined or the profile leaves out: a magic or a version cut short (reads past the file); a file without a visible voxel (LoadVOX allocates zero bytes for its mesh and GetModelBoundingBox would read them), which a file whose voxels are all outside the sizes or after a cut is; a file over 2 MiB, a size over 1024 and an array over 2^21 cells (a 256x256x256 file among them: the profile's limit, not the format's).

Gate vox (tools/vox_probe.py) loads generated files covering each of those rules and the four models of models_loading_vox (chr_knight, chr_sword, monu9: 138304 vertices in three meshes, fez: 189232), natively and with Jonlib, and compares the counts, an FNV-1a hash of every mesh's vertex, normal, color and index words, and every material map.

Loading models (Inter-Quake Model)

Model.load_for of an .iqm file is LoadIQM (src/iqm.bend), which copies what the header points at: the file is INTERQUAKEMODEL, version 2, and counts and offsets of its arrays.

  • Meshes. One Mesh a mesh: its vertices and normals (3 floats a vertex) and texcoords (2) from the vertex arrays of those kinds, from the mesh's first vertex; zeros where the file has no such array (the loader allocates them cleared). Colors (4 bytes a vertex) only when the file has a color array. Bone data for every mesh (raylib allocates it cleared): the blend indexes as boneIndices (signed chars copied as unsigned chars) and the blend weights over 255.0f as boneWeights, four a vertex, zeros without those arrays; tangents and custom arrays are not read. Two arrays of a kind: the last one counts. The array's own format and size are ignored, as upstream.
  • Indices. A triangle's corners reversed, each less the mesh's first vertex, as unsigned shorts (a corner below the first vertex wraps).
  • Materials. One a mesh, meshMaterial[i] = i: LoadMaterialDefault with its albedo texture replaced by LoadTexture(directory/material), the material's name in the file; an empty name (raylib checks TextLength(material) > 0) loads no texture and keeps the default one. A name that opens no file gives a texture of zeros (id 0), as LoadTexture returns; the loaded textures come back with the model. A file without meshes is the empty model.
  • Skeleton (Model.load_skeleton): the joints' names and parents, and BuildPoseFromParentJoints of their transforms: a joint whose parent comes later, or is negative, stays as read; a joint that is its own parent composes with what each statement has just written.

Model.load_animations_for of an .iqm file is LoadModelAnimationsIQM: an animation has the file's poses as bones and num_frames keyframes. A keyframe gives each pose ten channels (translation, rotation, scale): the channel's offset, plus the next unsigned short of the frame data times the channel's scale where the pose's mask has the channel's bit (the data is read on from first_frame*num_framechannels, whatever the channel count says). The rotation is normalized, then the poses are composed in order, in place: the rotation under the parent's, the translation turned by the parent's rotation and moved by its translation, the scale multiplied. A parent that comes later is taken as read, and a pose that is its own parent composes with what it has become. No libm call; uncontracted arithmetic.

A file with another magic or version, an empty file and one that does not open are the empty model without bones or animations. OutOfDomain for what the loaders leave undefined: a file shorter than its header; an array (meshes, triangles, a vertex array of a kind that is read, joints, poses, animations, frame data) outside the file; a mesh, material, bone or animation name whose 32 bytes pass the end of the file; a material, bone or animation name without its NUL in those bytes; a mesh whose vertices or triangles pass the file's counts, and one without vertices or triangles (the loader allocates zero bytes); a material name that starts with a slash; frame data that ends before the masks do; a pose whose parent is not a pose. The profile ends at files of 2 MiB, 524288 vertices, 65535 frames or channels, 4096 poses and 262144 poses in an animation's keyframes.

Gate iqm (tools/iqm_probe.py) loads generated files covering each of those rules and the two files of models_loading_iqm (guy.iqm: one mesh of 224 vertices, 112 triangles and an empty material name, and 14 joints; guyanim.iqm: two animations of 61 keyframes), natively and with Jonlib, and compares the model (as gate vox does), every bone's parent, name and bind pose, and a hash of every keyframe's pose.

Loading models (Model 3D)

Model.load_for of an .m3d file is LoadM3D over m3d.h's importer (src/m3d.bend), in its binary variant: 3DMO, the file's length, an optional preview chunk, then HEAD or a zlib stream that inflates to it. The header gives the scale (1 when it is not positive) and a types word with the size of every index (1, 2 or 4 bytes; an index of one byte reads 254 and 255 as -2 and -1, of two bytes 65534 and 65535 likewise), then chunks follow up to OMD3. raylib does not build the ASCII variant: 3dmo gives no model.

  • CMAP, TMAP, VRTS. A color map, texture coordinates (bytes over 255, shorts over 65535, or floats) and vertices (signed bytes over 127, signed shorts over 32767, or floats; x y z w, a color by index or as a word, a skin index). A second chunk of a kind is skipped.
  • BONE. The bones (parent, name, a position vertex and an orientation vertex) and the skins (the bones of up to eight weights).
  • MTRL. A material's name and properties. A map property without a name is dropped, as the importer drops a texture it does not find.
  • MESH. Records: a material selection, or a triangle whose corners are a vertex and, by the record's flags, a texture coordinate and a normal.
  • ACTN. An action: its name, its duration and frames, each a time and the bones whose position or orientation vertex changes.

LoadM3D makes one mesh a run of faces of one material, three vertices a face (no indices): the positions times the scale, the texture coordinates with v turned over, the normals, and colors when the run has no material (white where a vertex has none) or a vertex of it has no color. There are at least as many meshes as materials (those no run uses are empty), and one material more than the file's: the default one first. A material takes its Kd, Ks, Ns, Ke, Pm, Pr and Ps properties. The skeleton (Model.load_skeleton) has a bone a bone, its position times the scale and its orientation normalized, composed with its parent's in the bones' order (a parent that comes later is still zeros, as the loader's cleared array is), then a bone named NO BONE.

A file with bones and skins gives every mesh bone data, four a corner: the corner's skin (its four bone ids as unsigned chars, M3D_UNDEF giving 255 with a weight of 0) or, for a vertex without a skin that exists, the no-bone bone (numbone) with weight 1 and zeros. A skin's weights are the importer's: each of its first four nonzero weight bytes over 255.0f, then all divided by their sum unless it is 0 or 1; then, unless the importer returned from its chunk loop, its post-processing divides the weights again by their sum (from the first, up to the first undefined bone or weight not above 0) once for every vertex that names the skin.

Model.load_animations_for is LoadModelAnimationsM3D: an animation an action, duration/17 keyframes, keyframe i being m3d_pose at 17*i ms: the frames whose time is not past it applied in order, then, unless the last one is at that time, an interpolation towards the next frame (the first one after the last): positions linearly, orientations with the importer's approximated NLERP and its inverse square root. The factor of that interpolation is changed by every orientation it interpolates and the next bone starts from the changed one, as upstream does. Poses are composed in model space as the skeleton is. No libm call; uncontracted arithmetic.

No model for another magic, an empty file, a file that does not open, an index size the importer does not take or a missing end mark: the empty model, no bones, no animations. A file without faces is the empty model too, with its animations. OutOfDomain for what the importer or the loaders leave undefined: a header, a chunk or a record cut short; an index past the vertices, the texture map, the color map, the bones or the skins; a material without a name after another, a bone or an action without one where it is copied; an action whose frames its chunk does not hold; and for what is outside the profile: faces without normals (the importer generates them), a map property that names a texture (an inlined asset or a file the importer would look for in the working directory), procedural, shape, voxel and label chunks, coordinates as doubles, a zlib stream the decoder does not finish, files over 2 MiB, strings over 255 bytes, more than 65535 bones or 65536 keyframes.

Gate m3d (tools/m3d_probe.py) loads generated files covering each of those rules and the examples' files (cesium_man.m3d: 4672 faces, 19 bones and an action of 112 keyframes; suzanne.m3d; seagull.m3d is refused for its inlined texture), natively and with Jonlib, and compares the rows of gate iqm.

Collision

  • GetRayCollisionMesh transforms each triangle's vertices with Vector3Transform (profiled), runs GetRayCollisionTriangle (COLLISION.md) and keeps the nearest hit (a later hit replaces it only when strictly nearer). The signed triangleCount selects the triangles: a count that is not positive, or a null vertex buffer, has no hit. Indexed triangles read indices[3*i .. 3*i+2] and those vertices; a mesh without indices reads vertices 3*i .. 3*i+2. vertexCount and the other attributes are not read. An index or a sequential span outside the vertex buffer is None.
  • GetModelBoundingBox starts from the first mesh's box and widens it with each further mesh using rmodels.c's strict comparisons (a < b ? a : b, so NaN and equal values pick the other mesh's), then transforms both corners with Vector3Transform. Each mesh is read as GetMeshBoundingBox. A model without meshes has the transformed zero box. A mesh whose vertex read is outside its buffer makes the model box None.

BeginMode3D and the 3D shapes

Frame.begin_mode_3d(frame, camera) is BeginMode3D on the memory platform: rlMatrixMode(RL_PROJECTION), rlPushMatrix (ignored when the two-entry stack is full), rlLoadIdentity, the projection, then rlMatrixMode(RL_MODELVIEW), rlLoadIdentity, rlMultMatrixf(MatrixLookAt(position, target, up)) (uncontracted) and rlEnableDepthTest. The aspect is (float)width/(float)height of the current color buffer (the render texture's in texture mode).

  • Orthographic (CAMERA_ORTHOGRAPHIC): rlOrtho(-right, right, -top, top, 0.05, 4000.0) with top = fovy/2.0 and right = top*aspect in binary64. Both are exact, so swOrtho's cells are F32 operations: 2/(fovy*aspect), 2/fovy, -0.0f/rl (the sign of fovy) for the centers, and the depth cells -2/(float)(4000 - 0.05) and -(float)4000.05/(4000 - 0.05) rounded once (0xBA0313DA, 0xBF8000D2). fovy, the span fovy*aspect and both scales must be finite and nonzero; otherwise a cell is a NaN of platform-defined sign (or an infinity that makes one) and the frame is refused.
  • Perspective (CAMERA_PERSPECTIVE, Frame.begin_mode_3d_for(libm, frame, camera)): rlFrustum(-right, right, -top, top, 0.05, 4000.0) with top = 0.05*tan(fovy*0.5*DEG2RAD) and right = top*aspect in binary64, the tangent from the profile's M.Libm.tan (PERSPECTIVE.md). swFrustum divides (float)0.1 by the binary64 spans 2*right and 2*top and narrows m0/m5 to F32; m8/m9 are +0.0 over the spans (the sign of fovy) and m10, m11, m14 are constants (0xBF8000D2, -1, 0xBDCCCD75). A zero or nonfinite m0/m5 refuses the frame. Under AppleLibm (and so Frame.begin_mode_3d) every perspective camera is refused: macOS misrounds 22.7% of these tangents, fovy = 45 included, and its tan is unpublished.
  • Other projection values keep the identity projection, as raylib does.

Frame.end_mode_3d pops the projection and resets the modelview; the depth test stays enabled, so later 2D drawing is depth-tested as in raylib. Ending a mode that was never begun pops the last projection (undefined in rlsw): the frame is refused. A render texture has its own depth buffer (RLGL.md).

Each shape is the rlPushMatrix/rlTranslatef/rlRotatef/rlScalef/ rlBegin/rlColor4ub/rlVertex3f/rlEnd/rlPopMatrix stream of rmodels.c, with its F32 arithmetic in source order (x - width/2 with x = 0, the sphere's incremental rotations, Vector3Perpendicular bases for the Ex cylinders and capsules), drawn through the current matrices (inside or outside BeginMode3D). rlNormal3f does nothing in rlsw. The color is set exactly as often as rmodels.c sets it, which matters for rlsw's per-primitive alpha flag (FRAME.md).

  • Trigonometry. DrawCircle3D uses multiples of 10 degrees and its rlRotatef angle; DrawSphereEx and DrawSphereWires the two angles DEG2RAD*(180/rings) and DEG2RAD*(360/slices); DrawCylinder(Wires) (DEG2RAD*i)*(360/sides); the Ex cylinders and capsules ((2*PI)/slices)*i and (PI*0.5/rings)*i. Every argument must be verified for the profile.
  • Rings and slices. DrawSphereEx draws rings bands with the ring angle 180/rings, so nothing is drawn below one ring. DrawSphereWires draws, on the same rotated vertices, per face the longitude, latitude and diagonal lines 0-1, 0-2 and 0-3. DrawCapsule(Wires) take (start, end, radius, rings, slices) and raise rings below 1 to 1.
  • Loops. rings, slices and sides above 4096 and grids above 4097 lines are refused, as are NaN or out-of-range C ints.

Verification

Gate Tool Compares
models tools/models_probe.py 25 3D scenes (192 operations, 6 random orthographic scenes) byte for byte against the uncontracted memory-platform raylib with the host libm, with the projection/modelview matrices read back; contracts and unverified arguments must be refused (on macOS 15 compared, 10 refused)
models-gnu tools/models_probe.py --gnu-libm the same scenes against the glibc-model reference: raylib built with sinf/cosf replaced by the Arm optimized-routines model (tools/trig_probe.py) and qsort by a stable merge sort (glibc's order), Jonlib with M.Glibc239Libm{}: spheres, cylinders and capsules (18 compared, 7 refused)
mesh tools/mesh_probe.py every attribute word, bounding box, collision and exported byte of the generators, tangents, exports, ray and model queries against the linked raylib with the host contraction and libm, including a non-positive signed count and an index inside the buffer past vertex_count. Linux M.Uncontracted{} and M.Glibc239Libm{}: 263 cases, 249 compared, 14 refused. macOS arm64 runs the same corpus under M.Fused{}.
mesh-uncontracted tools/mesh_probe.py --uncontracted-control the same cases against the raylib built with -ffp-contract=off (M.Uncontracted{})
mesh-gnu tools/mesh_probe.py --gnu-libm the same cases plus the par_shapes spheres, hemispheres (before and after a GenMeshSphere) and tori with their tangents, exports and ray queries (bounding boxes left out: their fminf is the host's), against the glibc-model build with M.Uncontracted{} and M.Glibc239Libm{}
model-draw tools/model_draw_probe.py 27 scenes (216 operations, 6 random orthographic scenes of custom meshes) byte for byte against the uncontracted memory-platform raylib with the host libm: DrawMesh of generated, empty and custom meshes (indexed or not, texcoords, colors, no vertices, leftover vertices, translucent materials, textures from the scene's slots), DrawModel(Ex), DrawModelWires(Ex) (also after point mode), two-mesh models with SetModelMeshMaterial and a model transform, DrawMeshInstanced, DrawBillboard(Rec, Pro) (negative sizes, origins, rotations), and logged IsMaterialValid, IsModelValid, LoadMaterialDefault/SetMaterialTexture maps and UnloadMaterial (its ids reused by the next texture); contracts must be refused (on macOS 20 compared, 7 refused; on glibc 22 and 5)
obj tools/obj_probe.py 40 OBJ/MTL loads (written by the probe with PNG textures) word for word against the linked raylib with the host contraction (on macOS arm64 the fused tryParseDouble, M.Fused{}): mesh and material counts, IsModelValid, every mesh's counts, material index and vertex, normal and texcoord word, every material map; 27 compared, 13 refused
obj-uncontracted tools/obj_probe.py --uncontracted-control the same files against the raylib built with -ffp-contract=off (M.Uncontracted{}); the corpus includes literals whose fused and unfused parses round to different floats
vox tools/vox_probe.py 53 MagicaVoxel loads (the four models of models_loading_vox and files written by the probe): mesh and material counts, IsModelValid, every mesh's counts, material index and FNV-1a hashes of its vertex, normal, color and index words, every material map; 33 compared, 20 refused
iqm tools/iqm_probe.py 46 Inter-Quake Model files (the two of models_loading_iqm and files written by the probe) through LoadModel, the skeleton and LoadModelAnimations against the uncontracted raylib build: the model rows of gate vox, every bone's parent, name and bind pose words, every animation's name, counts and a hash of each keyframe's pose; 63 loads compared, 29 refused
m3d tools/m3d_probe.py 65 Model 3D files (the three of the models examples and files written by the probe) through LoadModel, the skeleton and LoadModelAnimations against the uncontracted raylib build, with the rows of gate iqm; 80 loads compared, 50 refused
python3 tools/run_gates.py --bend-source "$BEND_SOURCE" --raylib-source "$RAYLIB_SOURCE" --only models

Every probe runs CPU-1, CPU-2 and JavaScript lanes. Attributes of more than 3000 words are compared through an FNV-1a hash of all their words plus the count; image inputs are read from files. The largest meshes (a 256x256-vertex plane, a 32x32 heightmap) also exercise the JavaScript lane's stack: the attribute builders are tail-recursive.

Gaps

  • GenMeshCylinder, GenMeshCone and GenMeshKnot outside M.Glibc239Libm{} and under M.Fused{}; the par_shapes sphere, hemisphere and torus under Apple's qsort and sinf/cosf; their fused contraction is implemented but only the uncontracted glibc reference is compared.
  • Perspective cameras under the Apple profile; the Apple profile's sinf/cosf beyond the integral degrees (most curved shapes are verified only under the glibc profile).
  • Shaders (no shader is compiled under OpenGL 1.1), UploadMesh/GPU buffers, UpdateMeshBuffer's buffer contents, the skinned normals (animNormals, no pixel reads them) and an IQM file without joints under UpdateModelAnimation (see Poses).
  • glTF as text: LoadModel answers UnsupportedFileType (raylib loads it; the text container is not ported). Model 3D: textures (inlined or looked up), generated normals, voxels, shapes, procedural surfaces and the ASCII variant. Binary glTF is loaded for the slice above: the other texture kinds and attribute formats are refused.
  • OBJ: faces of 6 or 7 vertices (accepted by builds without asserts, refused here), numbers beyond the checked binary64 domains, non-ASCII names, and texture files Jonlib's LoadImage does not decode.
  • Textures shared between models: a material holds a texture's struct, but the drawing call needs the owning Texture value in its list.
  • Metal lane and performance: not measured.