using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace GvrMapExtract;
/// 작은 glTF 2.0 바이너리(glb) 작성기: 버퍼 하나에 accessor · 이미지를 차례로 붙인다
public sealed class Glb
{
private readonly MemoryStream _bin = new();
public readonly JsonArray BufferViews = new(), Accessors = new(), Images = new(), Textures = new(), Materials = new(), Meshes = new(), Nodes = new(), Samplers = new();
public JsonObject? Extras;
/// 장면의 최상위 노드 (비면 모든 노드)
public readonly List Roots = new();
private int View(ReadOnlySpan data, int? target)
{
while (_bin.Length % 4 != 0) _bin.WriteByte(0);
var v = new JsonObject { ["buffer"] = 0, ["byteOffset"] = _bin.Length, ["byteLength"] = data.Length };
if (target is { } t) v["target"] = t;
_bin.Write(data);
BufferViews.Add(v);
return BufferViews.Count - 1;
}
private int Accessor(int view, int componentType, int count, string type, bool normalized = false, float[]? min = null, float[]? max = null)
{
var a = new JsonObject { ["bufferView"] = view, ["componentType"] = componentType, ["count"] = count, ["type"] = type };
if (normalized) a["normalized"] = true;
if (min != null) a["min"] = new JsonArray(min.Select(x => (JsonNode)x).ToArray());
if (max != null) a["max"] = new JsonArray(max.Select(x => (JsonNode)x).ToArray());
Accessors.Add(a);
return Accessors.Count - 1;
}
public int Floats(float[] data, int comps, bool bounds = false)
{
float[]? min = null, max = null;
if (bounds)
{
min = Enumerable.Repeat(float.MaxValue, comps).ToArray();
max = Enumerable.Repeat(float.MinValue, comps).ToArray();
for (var i = 0; i < data.Length; i++)
{
min[i % comps] = Math.Min(min[i % comps], data[i]);
max[i % comps] = Math.Max(max[i % comps], data[i]);
}
}
var v = View(System.Runtime.InteropServices.MemoryMarshal.AsBytes(data.AsSpan()), 34962);
return Accessor(v, 5126, data.Length / comps, comps switch { 1 => "SCALAR", 2 => "VEC2", 3 => "VEC3", _ => "VEC4" }, false, min, max);
}
/// 정규화된 unsigned byte (색 · 가중치)
public int Bytes(byte[] data, int comps, bool normalized = true)
{
var v = View(data, 34962);
return Accessor(v, 5121, data.Length / comps, comps switch { 1 => "SCALAR", 2 => "VEC2", 3 => "VEC3", _ => "VEC4" }, normalized);
}
public int Ushorts(ushort[] data, int comps)
{
var v = View(System.Runtime.InteropServices.MemoryMarshal.AsBytes(data.AsSpan()), 34962);
return Accessor(v, 5123, data.Length / comps, comps switch { 1 => "SCALAR", 2 => "VEC2", 3 => "VEC3", _ => "VEC4" });
}
public int Indices(uint[] data)
{
var v = View(System.Runtime.InteropServices.MemoryMarshal.AsBytes(data.AsSpan()), 34963);
return Accessor(v, 5125, data.Length, "SCALAR");
}
/// 행렬 같은 비정점 데이터 (target 없음)
public int Raw(float[] data, string type)
{
var v = View(System.Runtime.InteropServices.MemoryMarshal.AsBytes(data.AsSpan()), null);
var comps = type switch { "MAT4" => 16, "VEC4" => 4, "VEC3" => 3, _ => 1 };
return Accessor(v, 5126, data.Length / comps, type);
}
private int _clampSampler = -1;
/// 텍스처 번호 (기본 반복 샘플러, clamp 면 가장자리 고정 샘플러)
public int Texture(byte[] image, string mime, bool clamp = false)
{
if (Samplers.Count == 0) Samplers.Add(new JsonObject { ["magFilter"] = 9729, ["minFilter"] = 9987, ["wrapS"] = 10497, ["wrapT"] = 10497 });
var sampler = 0;
if (clamp)
{
if (_clampSampler < 0)
{
Samplers.Add(new JsonObject { ["magFilter"] = 9729, ["minFilter"] = 9987, ["wrapS"] = 33071, ["wrapT"] = 33071 });
_clampSampler = Samplers.Count - 1;
}
sampler = _clampSampler;
}
Images.Add(new JsonObject { ["bufferView"] = View(image, null), ["mimeType"] = mime });
Textures.Add(new JsonObject { ["sampler"] = sampler, ["source"] = Images.Count - 1 });
return Textures.Count - 1;
}
public void Write(string file, JsonObject? extra = null)
{
var gltf = new JsonObject
{
["asset"] = new JsonObject { ["version"] = "2.0", ["generator"] = "gvr-map-extract" },
["scene"] = 0,
["scenes"] = new JsonArray(new JsonObject { ["nodes"] = new JsonArray((Roots.Count > 0 ? Roots : Enumerable.Range(0, Nodes.Count)).Select(i => (JsonNode)i).ToArray()) }),
["nodes"] = Nodes,
["meshes"] = Meshes,
["accessors"] = Accessors,
["bufferViews"] = BufferViews,
["buffers"] = new JsonArray(new JsonObject { ["byteLength"] = _bin.Length }),
};
if (Materials.Count > 0) gltf["materials"] = Materials;
if (Textures.Count > 0)
{
gltf["textures"] = Textures;
gltf["images"] = Images;
gltf["samplers"] = Samplers;
}
if (extra != null)
foreach (var (k, v) in extra) gltf[k] = v?.DeepClone();
if (Extras != null) gltf["extras"] = Extras;
var json = Encoding.UTF8.GetBytes(gltf.ToJsonString(new JsonSerializerOptions { WriteIndented = false }));
var jsonPad = (4 - json.Length % 4) % 4;
while (_bin.Length % 4 != 0) _bin.WriteByte(0);
using var fs = File.Create(file);
using var w = new BinaryWriter(fs);
w.Write(0x46546C67u); // glTF
w.Write(2u);
w.Write((uint)(12 + 8 + json.Length + jsonPad + 8 + _bin.Length));
w.Write((uint)(json.Length + jsonPad));
w.Write(0x4E4F534Au); // JSON
w.Write(json);
for (var i = 0; i < jsonPad; i++) w.Write((byte)' ');
w.Write((uint)_bin.Length);
w.Write(0x004E4942u); // BIN
_bin.Position = 0;
_bin.CopyTo(fs);
}
}