Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/tools-changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## [0.1.0-preview.1]

- `IOScene.Formats` reads embedded GLB and OBJ geometry and writes GLB from an IOScene document.
- `IOScene.Formats` reads embedded GLB and OBJ geometry and writes GLB and OBJ from an IOScene document.
- `IOCoord` provides measurements, surface clearance, hard clashes with an estimated depth, box overlap checks,
duplicate geometry detection, solid containment, grid queries, revision comparison and BCF 2.1 export.
- Both packages use the public IOScene 0.1 API and can be installed independently.
Expand Down
5 changes: 5 additions & 0 deletions docs/tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,18 @@ using IOScene.Formats;

var scene = SceneJson.Load("model.scene.json");
GlbSceneWriter.Save(scene, "model.glb");
ObjSceneWriter.Save(scene, "model.obj");
```

`GlbSceneReader.Load` reads embedded float32 positions and normals, unsigned indices and base material colours.
It flattens the node placements into one model and imports triangle, line and point primitives. Files declaring
required glTF extensions are rejected. The OBJ reader `ObjSceneReader.Load` groups faces by object and assumes
metres with Z up.

`ObjSceneWriter` bakes placed vertices into OBJ with Z up and writes triangle faces, line segments and points.
Its text-writer overload can also write an adjacent MTL library with effective colours and opacity.
The OBJ reader currently imports faces and ignores MTL libraries.

The writer emits [glTF 2.0 binary](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html) with the element tree,
indexed and non-indexed triangles, lines and points, shared mesh buffers, and placements with rotation, translation,
scale or reflection. The scene root rotates the metre-based geometry from Z up to glTF Y up. Materials carry
Expand Down
14 changes: 1 addition & 13 deletions src/IOScene.Formats/GlbSceneWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,7 @@ public static class GlbSceneWriter
public static void Save(SceneDocument scene, string path)
{
ArgumentNullException.ThrowIfNull(scene);
ArgumentException.ThrowIfNullOrWhiteSpace(path);
string fullPath = Path.GetFullPath(path);
string temporaryPath = Path.Combine(Path.GetDirectoryName(fullPath)!, $".{Guid.NewGuid():N}.glb.tmp");
var file = new FileStream(temporaryPath, FileMode.CreateNew, FileAccess.Write, FileShare.None);
try
{
using (file) Write(scene, file);
File.Move(temporaryPath, fullPath, overwrite: true);
}
finally
{
File.Delete(temporaryPath);
}
SceneFormatFile.Replace(path, "glb", file => Write(scene, file));
}

/// <summary>Writes the scene to an open stream. The stream remains open.</summary>
Expand Down
2 changes: 1 addition & 1 deletion src/IOScene.Formats/IOScene.Formats.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<PropertyGroup>
<Version>0.1.0-preview.1</Version>
<PackageId>IOScene.Formats</PackageId>
<Description>GLB and OBJ import and GLB export for IOScene models.</Description>
<Description>GLB and OBJ import and export for IOScene models.</Description>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<!-- NU5104 reports the prerelease bound that excludes IOScene 0.2 previews. -->
<NoWarn>$(NoWarn);NU5104</NoWarn>
Expand Down
117 changes: 117 additions & 0 deletions src/IOScene.Formats/ObjSceneWriter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
namespace IOScene.Formats;

/// <summary>Writes placed scene geometry as Wavefront OBJ in metres with Z up.</summary>
public static class ObjSceneWriter
{
/// <summary>Writes geometry to a UTF-8 OBJ file and replaces an existing file after a successful export.</summary>
/// <param name="scene">The scene to export.</param>
/// <param name="path">Path to the OBJ file.</param>
public static void Save(SceneDocument scene, string path)
{
ArgumentNullException.ThrowIfNull(scene);
SceneFormatFile.Replace(path, "obj", file =>
{
using var writer = new StreamWriter(file, leaveOpen: true);
Write(scene, writer);
});
}

/// <summary>Writes geometry to an OBJ text writer. The writer stays open.</summary>
/// <param name="scene">The scene to export.</param>
/// <param name="output">The OBJ text writer.</param>
public static void Write(SceneDocument scene, TextWriter output) => WriteScene(scene, output, null, null);

/// <summary>Writes OBJ geometry and an MTL library with the effective colours and opacity. Both writers stay open.</summary>
/// <param name="scene">The scene to export.</param>
/// <param name="output">The OBJ text writer.</param>
/// <param name="materials">The MTL text writer.</param>
/// <param name="materialFileName">File name of the adjacent MTL library, without a path or whitespace.</param>
public static void Write(SceneDocument scene, TextWriter output, TextWriter materials, string materialFileName)
{
ArgumentNullException.ThrowIfNull(materials);
ArgumentException.ThrowIfNullOrWhiteSpace(materialFileName);
if (ReferenceEquals(output, materials))
throw new ArgumentException("OBJ and MTL require separate text writers.", nameof(materials));
if (materialFileName is "." or ".." || materialFileName.Any(c => char.IsWhiteSpace(c) || char.IsControl(c)
|| c is '/' or '\\' or ':' or '#'))
throw new ArgumentException("Use a single MTL file name without paths, spaces or comments.", nameof(materialFileName));
WriteScene(scene, output, materials, materialFileName);
}

private static void WriteScene(SceneDocument scene, TextWriter output, TextWriter? materials, string? materialFileName)
{
ArgumentNullException.ThrowIfNull(scene);
ArgumentNullException.ThrowIfNull(output);
if (scene.Validate().FirstOrDefault(issue => issue.Severity == SceneSeverity.Error) is { } error)
throw new InvalidDataException($"Invalid scene ({error.Code}): {error.Message}");

var elements = scene.Elements.ToDictionary(item => item.Id);
var geometries = scene.Geometries.ToDictionary(item => item.Id);
var materialColours = materials is null ? null : scene.Materials.ToDictionary(item => item.Id, item => item.Color);
var colourNames = new Dictionary<RgbaColor, string>();
long vertexOffset = 1;
if (materialFileName is not null) output.WriteLine($"mtllib {materialFileName}");
foreach (var instance in scene.Instances)
{
var geometry = geometries[instance.GeometryId];
if (geometry.Vertices.Count == 0) continue;
var name = instance.Name ?? elements[instance.ElementId].Name;
string safeName = new(name.Select(c => char.IsWhiteSpace(c) || char.IsControl(c) || c is '#' or '\\' ? '_' : c).ToArray());
output.WriteLine($"o {(safeName.Length == 0 ? "Element" : safeName)}");

if (materials is not null)
{
var colour = instance.Color ?? (instance.MaterialId is int id ? materialColours![id] : RgbaColor.White);
if (!colourNames.TryGetValue(colour, out string? materialName))
{
materialName = FormattableString.Invariant($"material_{colourNames.Count + 1}");
colourNames.Add(colour, materialName);
materials.WriteLine($"newmtl {materialName}");
materials.WriteLine(FormattableString.Invariant($"Kd {colour.R / 255d:R} {colour.G / 255d:R} {colour.B / 255d:R}"));
materials.WriteLine(FormattableString.Invariant($"d {colour.A / 255d:R}"));
materials.WriteLine("illum 2");
}
output.WriteLine($"usemtl {materialName}");
}

var transform = instance.Transform ?? Transform3d.Identity;
foreach (var vertex in geometry.Vertices)
{
var point = transform.Apply(vertex);
if (!double.IsFinite(point.X) || !double.IsFinite(point.Y) || !double.IsFinite(point.Z))
throw new InvalidDataException("An OBJ vertex coordinate is outside the finite range.");
output.WriteLine(FormattableString.Invariant($"v {point.X:R} {point.Y:R} {point.Z:R}"));
}

int stride = geometry.Topology switch
{
SceneTopology.Triangles => 3,
SceneTopology.Lines => 2,
SceneTopology.Points => 1,
_ => throw new InvalidDataException($"Unsupported OBJ topology: {geometry.Topology}."),
};
bool mirrored = stride == 3 &&
Vector3d.Dot(Vector3d.Cross(ScaleAxis(transform.XAxis), ScaleAxis(transform.YAxis)), ScaleAxis(transform.ZAxis)) < 0;
int count = geometry.Indices.Count == 0 ? geometry.Vertices.Count : geometry.Indices.Count;
for (int i = 0; i < count; i += stride)
{
var record = stride switch
{
3 => FormattableString.Invariant($"f {Index(i)} {Index(i + (mirrored ? 2 : 1))} {Index(i + (mirrored ? 1 : 2))}"),
2 => FormattableString.Invariant($"l {Index(i)} {Index(i + 1)}"),
_ => FormattableString.Invariant($"p {Index(i)}"),
};
output.WriteLine(record);
}
vertexOffset += geometry.Vertices.Count;

long Index(int index) => vertexOffset + (geometry.Indices.Count == 0 ? index : geometry.Indices[index]);
}
}

private static Vector3d ScaleAxis(Vector3d axis)
{
double scale = Math.Max(Math.Abs(axis.X), Math.Max(Math.Abs(axis.Y), Math.Abs(axis.Z)));
return scale > 0 ? axis / scale : axis;
}
}
21 changes: 21 additions & 0 deletions src/IOScene.Formats/SceneFormatFile.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
namespace IOScene.Formats;

internal static class SceneFormatFile
{
internal static void Replace(string path, string extension, Action<Stream> write)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
string fullPath = Path.GetFullPath(path);
string temporaryPath = Path.Combine(Path.GetDirectoryName(fullPath)!, $".{Guid.NewGuid():N}.{extension}.tmp");
var file = new FileStream(temporaryPath, FileMode.CreateNew, FileAccess.Write, FileShare.None);
try
{
using (file) write(file);
File.Move(temporaryPath, fullPath, overwrite: true);
}
finally
{
File.Delete(temporaryPath);
}
}
}
85 changes: 85 additions & 0 deletions tests/IOScene.Tools.Tests/ObjSceneWriterTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
using System.Text;
using IOScene.Formats;

namespace IOScene.Tools.Tests;

public class ObjSceneWriterTests
{
[Fact]
public void Write_BakesPlacementAndPreservesWindingWhenMirrored()
{
var scene = new SceneDocument();
scene.AddMesh("Left panel\nf 9 8 7\\", [Vector3d.Zero, Vector3d.UnitX, Vector3d.UnitZ], [0, 1, 2]);
scene.Instances[0].Transform = new(-Vector3d.UnitX, Vector3d.UnitY, Vector3d.UnitZ, new(10, 20, 30));
using var obj = new StringWriter();

ObjSceneWriter.Write(scene, obj);

string text = obj.ToString();
Assert.Equal(["o Left_panel_f_9_8_7_", "v 10 20 30", "v 9 20 30", "v 10 20 31", "f 1 3 2"],
text.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries));
using var input = new MemoryStream(Encoding.UTF8.GetBytes(text));
var geometry = Assert.Single(ObjSceneReader.Load(input).Geometries);
Assert.Equal([new(10, 20, 30), new(10, 20, 31), new(9, 20, 30)], geometry.Vertices);
}

[Fact]
public void Write_EmitsLinesPointsAndEffectiveMaterialColours()
{
var scene = new SceneDocument();
scene.AddMesh("Line", [Vector3d.Zero, Vector3d.UnitX], []);
scene.Geometries[0].Topology = SceneTopology.Lines;
scene.AddMesh("Point", [Vector3d.UnitZ], []);
scene.Geometries[1].Topology = SceneTopology.Points;
scene.Materials.Add(new SceneMaterial { Id = 1, Color = new(255, 0, 0) });
scene.Instances[0].MaterialId = 1;
scene.Instances[0].Color = new(0, 255, 0, 128);
scene.Instances[1].MaterialId = 1;
using var obj = new StringWriter();
using var mtl = new StringWriter();

ObjSceneWriter.Write(scene, obj, mtl, "model.mtl");

string objText = obj.ToString();
Assert.Contains("mtllib model.mtl", objText);
Assert.Contains("usemtl material_1", objText);
Assert.Contains("usemtl material_2", objText);
Assert.Contains("l 1 2", objText);
Assert.Contains("p 3", objText);
string mtlText = mtl.ToString();
Assert.Contains("Kd 0 1 0", mtlText);
Assert.Contains("d 0.5019607843137255", mtlText);
Assert.Contains("Kd 1 0 0", mtlText);
}

[Fact]
public void Write_InvalidMaterialNameLeavesBothWritersEmpty()
{
using var obj = new StringWriter();
using var mtl = new StringWriter();

Assert.Throws<ArgumentException>(() => ObjSceneWriter.Write(new SceneDocument(), obj, mtl, "../model.mtl"));
Assert.Empty(obj.ToString());
Assert.Empty(mtl.ToString());
}

[Fact]
public void Save_ExportFailurePreservesAnExistingFile()
{
var scene = new SceneDocument();
scene.AddMesh("Panel", [Vector3d.Zero, new(double.MaxValue, 0, 0), Vector3d.UnitY], [0, 1, 2]);
scene.Instances[0].Transform = new(Vector3d.UnitX * 2, Vector3d.UnitY, Vector3d.UnitZ, Vector3d.Zero);
string path = Path.Combine(Path.GetTempPath(), $"scene-{Guid.NewGuid():N}.obj");
try
{
File.WriteAllText(path, "existing content");

Assert.Throws<InvalidDataException>(() => ObjSceneWriter.Save(scene, path));
Assert.Equal("existing content", File.ReadAllText(path));
}
finally
{
File.Delete(path);
}
}
}
Loading