Skip to content

Commit

Permalink
Replace bogus normals with (1,0,0) which is bogus but well-formed
Browse files Browse the repository at this point in the history
Fixes #10
  • Loading branch information
kythyria committed Mar 14, 2020
1 parent 944d044 commit d9b5160
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
15 changes: 13 additions & 2 deletions PD2ModelParser/Exporters/GltfExporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -254,9 +254,20 @@ GLTF.Mesh GetMeshForModel(Model model)

if (geometry.normals.Count > 0)
{
Vector3 MakeNormal(Nexus.Vector3D norm)
Vector3 MakeNormal(Nexus.Vector3D norm, int idx)
{
return Vector3.Normalize(norm.ToVector3());
var normalized = Vector3.Normalize(norm.ToVector3());
if(!normalized.IsFinite())
{
Log.Default.Warn("Vertex {0} of geometry {1}|{2} is bogus ({3})", idx, geometry.SectionId, geometry.hashname, norm);
return new Vector3(1, 0, 0);
}
if(!normalized.IsUnitLength())
{
Log.Default.Warn("Vertex {0} of geometry {1}|{2} is bogus length {4} ({3})", idx, geometry.SectionId, geometry.hashname, norm, norm.Length());
return new Vector3(1, 0, 0);
}
return normalized;
}
var a_norm = MakeVertexAttributeAccessor("vnorm", geometry.normals, 12, GLTF.DimensionType.VEC3, MakeNormal, ma => ma.AsVector3Array());
result.Add(("NORMAL", a_norm));
Expand Down
20 changes: 20 additions & 0 deletions PD2ModelParser/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,26 @@ public static byte ClampFloatToByte(double input)
var rounded = Math.Round(scaled);
return (byte)rounded;
}

public static Boolean IsFinite(this System.Numerics.Vector3 vec)
{
return !(
float.IsInfinity(vec.X)
|| float.IsInfinity(vec.Y)
|| float.IsInfinity(vec.Z)
|| float.IsNaN(vec.X)
|| float.IsNaN(vec.Y)
|| float.IsNaN(vec.Z)
);
}

// From https://github.com/KhronosGroup/glTF-Validator/blob/master/lib/src/errors.dart
// which says, "these values are slightly greater than the maximum error from signed 8-bit quantization"
const float UnitLengthThresholdVec3 = 0.00674f;
const float UnitLengthThresholdVec4 = 0.00769f;

public static Boolean IsUnitLength(this System.Numerics.Vector3 vec) =>
Math.Abs(vec.Length() - 1) <= UnitLengthThresholdVec3;
}

public static class MatrixExtensions
Expand Down

0 comments on commit d9b5160

Please sign in to comment.