Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minor improvements, refactor and cleanup #71

Merged
merged 4 commits into from
Nov 3, 2024
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
14 changes: 14 additions & 0 deletions .idea/.idea.Obj2Tiles/.idea/inspectionProfiles/Project_Default.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 6 additions & 6 deletions Obj2Tiles.Library.Test/Obj2Tiles.Library.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.10.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0" />
<PackageReference Include="NUnit" Version="3.13.3" />
<PackageReference Include="NUnit3TestAdapter" Version="4.4.2" />
<PackageReference Include="coverlet.collector" Version="3.2.0">
<PackageReference Include="FluentAssertions" Version="6.12.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="NUnit" Version="4.2.2" />
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0" />
<PackageReference Include="coverlet.collector" Version="6.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="SixLabors.ImageSharp" Version="3.0.1" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.5" />
</ItemGroup>

<ItemGroup>
Expand Down
6 changes: 2 additions & 4 deletions Obj2Tiles.Library/Algos/MaxRectanglesBinPack.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ public class MaxRectanglesBinPack
public int binHeight = 0;
public bool allowRotations;

public readonly List<Rectangle> usedRectangles = new();
public readonly List<Rectangle> freeRectangles = new();
public readonly List<Rectangle> usedRectangles = [];
public readonly List<Rectangle> freeRectangles = [];


public MaxRectanglesBinPack(int width, int height, bool rotations = true)
Expand Down Expand Up @@ -311,7 +311,6 @@ private Rectangle FindPositionForNewNodeBestAreaFit(int width, int height, out i
ref int bestShortSideFit)
{
var bestNode = new Rectangle();
//memset(&bestNode, 0, sizeof(Rectangle));

bestAreaFit = int.MaxValue;

Expand Down Expand Up @@ -391,7 +390,6 @@ private int ContactPointScoreNode(int x, int y, int width, int height)
private Rectangle FindPositionForNewNodeContactPoint(int width, int height, out int bestContactScore)
{
var bestNode = new Rectangle();
//memset(&bestNode, 0, sizeof(Rectangle));

bestContactScore = -1;

Expand Down
2 changes: 1 addition & 1 deletion Obj2Tiles.Library/Common.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace Obj2Tiles.Library;

public static class Common
{
public static double Epsilon = double.Epsilon * 10;
public static readonly double Epsilon = double.Epsilon * 10;

public static void CopyImage(Image<Rgba32> sourceImage, Image<Rgba32> dest, int sourceX, int sourceY, int sourceWidth, int sourceHeight, int destX, int destY)
{
Expand Down
13 changes: 6 additions & 7 deletions Obj2Tiles.Library/Extenders.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,14 @@ public static int AddIndex<T>(this ICollection<T> collection, T item)

public static int AddIndex<T>(this IDictionary<T, int> dictionary, T item)
{
// If the item is not already in the dictionary, add it and return the index
if (!dictionary.ContainsKey(item))
{
dictionary.Add(item, dictionary.Count);
return dictionary.Count - 1;
}

// If the item is already in the dictionary, return the index
return dictionary[item];
if (dictionary.TryGetValue(item, out var index))
return index;

// If the item is not in the dictionary, add it and return the index
dictionary.Add(item, dictionary.Count);
return dictionary.Count - 1;

}
}
81 changes: 44 additions & 37 deletions Obj2Tiles.Library/Geometry/MeshT.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ public class MeshT : IMesh
public MeshT(IEnumerable<Vertex3> vertices, IEnumerable<Vertex2> textureVertices,
IEnumerable<FaceT> faces, IEnumerable<Material> materials)
{
_vertices = new List<Vertex3>(vertices);
_textureVertices = new List<Vertex2>(textureVertices);
_faces = new List<FaceT>(faces);
_materials = new List<Material>(materials);
_vertices = [..vertices];
_textureVertices = [..textureVertices];
_faces = [..faces];
_materials = [..materials];
}

public int Split(IVertexUtils utils, double q, out IMesh left,
Expand Down Expand Up @@ -818,8 +818,8 @@ private static List<List<int>> GetFacesClusters(IEnumerable<int> facesIndexes,
if (remainingFacesIndexes.Count == 0) break;

// Let's continue with the next cluster
currentCluster = new List<int> { remainingFacesIndexes[0] };
currentClusterCache = new HashSet<int> { remainingFacesIndexes[0] };
currentCluster = [remainingFacesIndexes[0]];
currentClusterCache = [remainingFacesIndexes[0]];
remainingFacesIndexes.RemoveAt(0);
}

Expand Down Expand Up @@ -847,7 +847,7 @@ private static Dictionary<int, List<int>> GetFacesMapper(Dictionary<Edge, List<i
{
var faceIndex = edge.Value[i];
if (!facesMapper.ContainsKey(faceIndex))
facesMapper.Add(faceIndex, new List<int>());
facesMapper.Add(faceIndex, []);

for (var index = 0; index < edge.Value.Count; index++)
{
Expand Down Expand Up @@ -876,13 +876,13 @@ private Dictionary<Edge, List<int>> GetEdgesMapper(IReadOnlyList<int> facesIndex
var e3 = new Edge(f.TextureIndexA, f.TextureIndexC);

if (!edgesMapper.ContainsKey(e1))
edgesMapper.Add(e1, new List<int>());
edgesMapper.Add(e1, []);

if (!edgesMapper.ContainsKey(e2))
edgesMapper.Add(e2, new List<int>());
edgesMapper.Add(e2, []);

if (!edgesMapper.ContainsKey(e3))
edgesMapper.Add(e3, new List<int>());
edgesMapper.Add(e3, []);

edgesMapper[e1].Add(faceIndex);
edgesMapper[e2].Add(faceIndex);
Expand Down Expand Up @@ -991,7 +991,7 @@ public Vertex3 GetVertexBaricenter()

public void WriteObj(string path, bool removeUnused = true)
{
if (!_materials.Any() || !_textureVertices.Any())
if (_materials.Count == 0 || _textureVertices.Count == 0)
_WriteObjWithoutTexture(path, removeUnused);
else
_WriteObjWithTexture(path, removeUnused);
Expand Down Expand Up @@ -1103,8 +1103,10 @@ private void _WriteObjWithTexture(string path, bool removeUnused = true)

var materialsPath = Path.ChangeExtension(path, "mtl");

var folderPath = Path.GetDirectoryName(path) ?? string.Empty;

if (TexturesStrategy == TexturesStrategy.Repack || TexturesStrategy == TexturesStrategy.RepackCompressed)
TrimTextures(Path.GetDirectoryName(path));
TrimTextures(folderPath);

using (var writer = new FormattingStreamWriter(path, CultureInfo.InvariantCulture))
{
Expand Down Expand Up @@ -1156,43 +1158,48 @@ into g

if (material.Texture != null)
{
if (TexturesStrategy == TexturesStrategy.KeepOriginal)
switch (TexturesStrategy)
{
var folder = Path.GetDirectoryName(path);
case TexturesStrategy.KeepOriginal:
{
var folder = Path.GetDirectoryName(path);

var textureFileName =
$"{Path.GetFileNameWithoutExtension(path)}-texture-{index}{Path.GetExtension(material.Texture)}";
var textureFileName =
$"{Path.GetFileNameWithoutExtension(path)}-texture-{index}{Path.GetExtension(material.Texture)}";

var newTexturePath =
folder != null ? Path.Combine(folder, textureFileName) : textureFileName;
var newTexturePath =
folder != null ? Path.Combine(folder, textureFileName) : textureFileName;

if (!File.Exists(newTexturePath))
File.Copy(material.Texture, newTexturePath, true);
if (!File.Exists(newTexturePath))
File.Copy(material.Texture, newTexturePath, true);

material.Texture = textureFileName;
}
else if (TexturesStrategy == TexturesStrategy.Compress)
{
var folder = Path.GetDirectoryName(path);
material.Texture = textureFileName;
break;
}
case TexturesStrategy.Compress:
{
var folder = Path.GetDirectoryName(path);

var textureFileName =
$"{Path.GetFileNameWithoutExtension(path)}-texture-{index}.jpg";
var textureFileName =
$"{Path.GetFileNameWithoutExtension(path)}-texture-{index}.jpg";

var newTexturePath =
folder != null ? Path.Combine(folder, textureFileName) : textureFileName;
var newTexturePath =
folder != null ? Path.Combine(folder, textureFileName) : textureFileName;

if (File.Exists(newTexturePath))
if (File.Exists(newTexturePath))

File.Delete(newTexturePath);
File.Delete(newTexturePath);

Console.WriteLine($" -> Compressing texture '{material.Texture}'");
Console.WriteLine($" -> Compressing texture '{material.Texture}'");

using (var image = Image.Load(material.Texture))
{
image.SaveAsJpeg(newTexturePath, encoder);
}
using (var image = Image.Load(material.Texture))
{
image.SaveAsJpeg(newTexturePath, encoder);
}

material.Texture = textureFileName;
material.Texture = textureFileName;
break;
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion Obj2Tiles.Library/Geometry/MeshUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public static IMesh LoadMesh(string fileName, out string[] dependencies)

dependencies = deps.ToArray();

return textureVertices.Any()
return textureVertices.Count != 0
? new MeshT(vertices, textureVertices, facesT, materials)
: new Mesh(vertices, faces);
}
Expand Down
2 changes: 1 addition & 1 deletion Obj2Tiles.Library/Obj2Tiles.Library.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="SixLabors.ImageSharp" Version="3.0.1" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.5" />
</ItemGroup>

</Project>
25 changes: 11 additions & 14 deletions Obj2Tiles.Library/TexturesCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,26 @@ namespace Obj2Tiles.Library;

public static class TexturesCache
{
private static readonly ConcurrentDictionary<string, Image<Rgba32>> _textures = new();
private static readonly ConcurrentDictionary<string, Image<Rgba32>> Textures = new();

public static Image<Rgba32> GetTexture(string textureName)
{
if (!_textures.ContainsKey(textureName))
{
var texture = Image.Load<Rgba32>(textureName);

_textures.TryAdd(textureName, texture);

return texture;

}

return _textures[textureName];
if (Textures.TryGetValue(textureName, out var txout))
return txout;

var texture = Image.Load<Rgba32>(textureName);
Textures.TryAdd(textureName, texture);

return texture;

}

public static void Clear()
{
foreach(var texture in _textures)
foreach(var texture in Textures)
{
texture.Value.Dispose();
}
_textures.Clear();
Textures.Clear();
}
}
8 changes: 4 additions & 4 deletions Obj2Tiles.Test/Obj2Tiles.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0" />
<PackageReference Include="NUnit" Version="3.13.3" />
<PackageReference Include="NUnit3TestAdapter" Version="4.4.2" />
<PackageReference Include="coverlet.collector" Version="3.2.0">
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="NUnit" Version="4.2.2" />
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0" />
<PackageReference Include="coverlet.collector" Version="6.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down
5 changes: 3 additions & 2 deletions Obj2Tiles/Obj2Tiles.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<AssemblyVersion>1.0.12</AssemblyVersion>
<FileVersion>1.0.12</FileVersion>
<AssemblyVersion>1.0.13</AssemblyVersion>
<FileVersion>1.0.13</FileVersion>
<InvariantGlobalization>true</InvariantGlobalization>
<Version>1.0.13</Version>
</PropertyGroup>

<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion Obj2Tiles/Options.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public sealed class Options
[Option("keep-intermediate", Required = false, HelpText = "Keeps the intermediate files (do not cleanup)", Default = false)]
public bool KeepIntermediateFiles { get; set; }

[Option('t', "y-up-to-z-up", Required = true, HelpText = "Convert the upward Y-axis to the upward Z-axis, which is used in some situations where the upward axis may be the Y-axis or the Z-axis after the obj is exported.", Default = true)]
[Option('t', "y-up-to-z-up", Required = false, HelpText = "Convert the upward Y-axis to the upward Z-axis, which is used in some situations where the upward axis may be the Y-axis or the Z-axis after the obj is exported.", Default = true)]
public bool? YUpToZUp { get; set; }
}

Expand Down
6 changes: 3 additions & 3 deletions Obj2Tiles/Tiles/B3dm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@ public B3dm(byte[] glb): this()

public byte[] ToBytes()
{
var header_length = 28;
const int headerLength = 28;

var featureTableJson = BufferPadding.AddPadding(FeatureTableJson, header_length);
var featureTableJson = BufferPadding.AddPadding(FeatureTableJson, headerLength);
var batchTableJson = BufferPadding.AddPadding(BatchTableJson);
var featureTableBinary = BufferPadding.AddPadding(FeatureTableBinary);
var batchTableBinary = BufferPadding.AddPadding(BatchTableBinary);

B3dmHeader.ByteLength = GlbData.Length + header_length + featureTableJson.Length + Encoding.UTF8.GetByteCount(batchTableJson) + batchTableBinary.Length + FeatureTableBinary.Length;
B3dmHeader.ByteLength = GlbData.Length + headerLength + featureTableJson.Length + Encoding.UTF8.GetByteCount(batchTableJson) + batchTableBinary.Length + FeatureTableBinary.Length;

B3dmHeader.FeatureTableJsonByteLength = featureTableJson.Length;
B3dmHeader.BatchTableJsonByteLength = Encoding.UTF8.GetByteCount(batchTableJson);
Expand Down
8 changes: 2 additions & 6 deletions Obj2Tiles/Tiles/B3dmHeader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,7 @@ public B3dmHeader(BinaryReader reader)
BatchTableBinaryByteLength = (int)reader.ReadUInt32();
}

public int Length {
get {
return 28 + FeatureTableJsonByteLength + FeatureTableBinaryByteLength + BatchTableJsonByteLength + BatchTableBinaryByteLength;
}
}
public int Length => 28 + FeatureTableJsonByteLength + FeatureTableBinaryByteLength + BatchTableJsonByteLength + BatchTableBinaryByteLength;

public byte[] AsBinary()
{
Expand All @@ -64,7 +60,7 @@ public List<string> Validate()
{
var res = new List<string>();

var headerByteLength = AsBinary().Count();
var headerByteLength = AsBinary().Length;
var featureTableJsonByteOffset = headerByteLength;
var featureTableBinaryByteOffset = featureTableJsonByteOffset + FeatureTableJsonByteLength;
var batchTableJsonByteOffset = featureTableBinaryByteOffset + FeatureTableBinaryByteLength;
Expand Down
Loading
Loading