-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathConverter.cs
More file actions
667 lines (576 loc) · 23.8 KB
/
Converter.cs
File metadata and controls
667 lines (576 loc) · 23.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Linq;
using SilentWave.Obj2Gltf.WaveFront;
using System.IO;
using Newtonsoft.Json;
using SilentWave.Obj2Gltf.Gltf;
namespace SilentWave.Obj2Gltf
{
/// <summary>
/// A delegate to get an existing texture index or add it to the list
/// </summary>
/// <param name="texturePath">The path where the texture can be found</param>
/// <returns>The texture index (zero based)</returns>
public delegate int GetOrAddTexture(string texturePath);
/// <summary>
/// obj2gltf converter
/// </summary>
public class Converter
{
public static Converter MakeDefault() => new(new ObjParser(), new MtlParser());
private readonly ObjParser _objParser;
private readonly IMtlParser _mtlParser;
/// <summary>
///
/// </summary>
/// <param name="objPath">obj file path</param>
/// <param name="options"></param>
public Converter(ObjParser objParser, IMtlParser mtlParser)
{
_objParser = objParser ?? throw new ArgumentNullException(nameof(objParser));
_mtlParser = mtlParser ?? throw new ArgumentNullException(nameof(mtlParser));
}
public void Convert(string objPath, string gltfPath, GltfConverterOptions options = null)
{
if (string.IsNullOrWhiteSpace(objPath))
throw new ArgumentNullException(nameof(objPath));
options ??= new GltfConverterOptions();
var objModel = _objParser.Parse(objPath, options.RemoveDegenerateFaces, options.ObjEncoding);
var objFolder = Path.GetDirectoryName(objPath);
if (!string.IsNullOrEmpty(objModel.MatFilename))
{
var matFile = Path.Combine(objFolder, objModel.MatFilename);
var mats = _mtlParser.ParseAsync(matFile).Result;
objModel.Materials.AddRange(mats);
}
Convert(objModel, gltfPath, options);
if (options.DeleteOriginals)
{
if (!string.IsNullOrEmpty(objModel.MatFilename))
{
var matFile = Path.Combine(objFolder, objModel.MatFilename);
File.Delete(matFile);
}
File.Delete(objPath);
}
}
private void Convert(ObjModel objModel, string outputFile, GltfConverterOptions options = null)
{
if (objModel == null) throw new ArgumentNullException(nameof(objModel));
options ??= new GltfConverterOptions();
var u32IndicesEnabled = objModel.RequiresUint32Indices();
var gltfModel = new GltfModel();
using (var bufferState = new BufferState(gltfModel, outputFile, u32IndicesEnabled))
{
gltfModel.Scenes.Add(new Scene());
gltfModel.Materials.AddRange(objModel.Materials.Select(x => ConvertMaterial(x, t => GetTextureIndex(gltfModel, t))));
var meshes = objModel.Geometries.ToArray();
var meshesLength = meshes.Length;
for (var i = 0; i < meshesLength; i++)
{
var mesh = meshes[i];
if (!mesh.Faces.Any()) continue;
var meshIndex = AddMesh(gltfModel, objModel, bufferState, mesh);
AddNode(gltfModel, mesh.Id, meshIndex, null);
}
}
if (gltfModel.Images.Count > 0)
{
gltfModel.Samplers.Add(new TextureSampler
{
MagFilter = MagnificationFilterKind.Linear,
MinFilter = MinificationFilterKind.NearestMipmapLinear,
WrapS = TextureWrappingMode.Repeat,
WrapT = TextureWrappingMode.Repeat
});
}
WriteFile(gltfModel, outputFile);
}
/// <summary>
/// write converted data to file
/// </summary>
/// <param name="outputFile"></param>
private void WriteFile(GltfModel gltfModel, string outputFile)
{
if (gltfModel == null) throw new ArgumentNullException();
using var file = File.CreateText(outputFile);
ToJson(gltfModel, file);
}
private static void ToJson(object model, StreamWriter sw)
{
var serializer = new JsonSerializer
{
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.Indented,
ContractResolver = new CustomContractResolver()
};
serializer.Serialize(sw, model);
}
private bool CheckWindingCorrect(SVec3 a, SVec3 b, SVec3 c, SVec3 normal)
{
var ba = new SVec3(b.X - a.X, b.Y - a.Y, b.Z - a.Z);
var ca = new SVec3(c.X - a.X, c.Y - a.Y, c.Z - a.Z);
var cross = SVec3.Cross(ba, ca);
return SVec3.Dot(normal, cross) >= 0;
}
#region Materials
/// <summary>
/// Translate the blinn-phong model to the pbr metallic-roughness model
/// Roughness factor is a combination of specular intensity and shininess
/// Metallic factor is 0.0
/// Textures are not converted for now
/// </summary>
/// <param name="color"></param>
/// <returns></returns>
public static double Luminance(FactorColor color)
{
return color.Red * 0.2125 + color.Green * 0.7154 + color.Blue * 0.0721;
}
private int AddTexture(GltfModel gltfModel, string textureFilename)
{
var image = new Image
{
Name = textureFilename,
Uri = textureFilename
};
var imageIndex = gltfModel.AddImage(image);
var textureIndex = gltfModel.Textures.Count;
var t = new Gltf.Texture
{
Name = textureFilename,
Source = imageIndex,
Sampler = 0
};
gltfModel.Textures.Add(t);
return textureIndex;
}
private Gltf.Material GetDefault(string name = "default", AlphaMode mode = AlphaMode.OPAQUE)
{
return new Gltf.Material
{
AlphaMode = mode,
Name = name,
//EmissiveFactor = new double[] { 1, 1, 1 },
PbrMetallicRoughness = new PbrMetallicRoughness
{
BaseColorFactor = new double[] { 0.5, 0.5, 0.5, 1 },
MetallicFactor = 1.0,
RoughnessFactor = 0.0
}
};
}
private static double Clamp(double val, double min, double max)
{
if (val < min) return min;
if (val > max) return max;
return val;
}
/// <summary>
///
/// </summary>
/// <param name="mat"></param>
/// <returns>roughnessFactor</returns>
private static double ConvertTraditional2MetallicRoughness(WaveFront.Material mat)
{
// Transform from 0-1000 range to 0-1 range. Then invert.
//var roughnessFactor = mat.SpecularExponent; // options.metallicRoughness ? 1.0 : 0.0;
//roughnessFactor = roughnessFactor / 1000.0;
var roughnessFactor = 1.0 - mat.SpecularExponent / 1000.0;
roughnessFactor = Clamp(roughnessFactor, 0.0, 1.0);
if (mat.Specular == null || mat.Specular.Color == null)
{
mat.Specular = new Reflectivity(new FactorColor());
return roughnessFactor;
}
// Translate the blinn-phong model to the pbr metallic-roughness model
// Roughness factor is a combination of specular intensity and shininess
// Metallic factor is 0.0
// Textures are not converted for now
var specularIntensity = Luminance(mat.Specular.Color);
// Low specular intensity values should produce a rough material even if shininess is high.
if (specularIntensity < 0.1)
{
roughnessFactor *= (1.0 - specularIntensity);
}
var metallicFactor = 0.0;
mat.Specular = new Reflectivity(new FactorColor(metallicFactor));
return roughnessFactor;
}
private int AddMaterial(GltfModel gltfModel, Gltf.Material material)
{
if (material == null) throw new ArgumentNullException(nameof(material));
var matIndex = gltfModel.Materials.Count;
gltfModel.Materials.Add(material);
return matIndex;
}
int GetTextureIndex(GltfModel gltfModel, string path)
{
for (var i = 0; i < gltfModel.Textures.Count; i++)
{
if (path == gltfModel.Textures[i].Name)
{
return i;
}
}
return AddTexture(gltfModel, path);
}
public static Gltf.Material ConvertMaterial(WaveFront.Material mat, GetOrAddTexture getOrAddTextureFunction)
{
var roughnessFactor = ConvertTraditional2MetallicRoughness(mat);
var gMat = new Gltf.Material
{
Name = mat.Name,
AlphaMode = AlphaMode.OPAQUE
};
var alpha = mat.GetAlpha();
var metallicFactor = 0.0;
if (mat.Specular != null && mat.Specular.Color != null)
{
metallicFactor = mat.Specular.Color.Red;
}
gMat.PbrMetallicRoughness = new PbrMetallicRoughness
{
RoughnessFactor = roughnessFactor,
MetallicFactor = metallicFactor
};
if (mat.Diffuse != null)
{
gMat.PbrMetallicRoughness.BaseColorFactor = mat.Diffuse.Color.ToArray(alpha);
}
else if (mat.Ambient != null)
{
gMat.PbrMetallicRoughness.BaseColorFactor = mat.Ambient.Color.ToArray(alpha);
}
else
{
gMat.PbrMetallicRoughness.BaseColorFactor = new double[] { 0.7, 0.7, 0.7, alpha };
}
var hasTexture = !string.IsNullOrEmpty(mat.DiffuseTextureFile);
if (hasTexture)
{
var index = getOrAddTextureFunction(mat.DiffuseTextureFile);
gMat.PbrMetallicRoughness.BaseColorTexture = new TextureReferenceInfo
{
Index = index
};
}
var hasNormalTexture = !string.IsNullOrEmpty(mat.NormalTextureFile);
if (hasNormalTexture)
{
var index = getOrAddTextureFunction(mat.NormalTextureFile);
gMat.normalTexture = new TextureReferenceInfo
{
Index = index
};
}
if (mat.Emissive != null && mat.Emissive.Color != null)
{
gMat.EmissiveFactor = mat.Emissive.Color.ToArray();
}
if (alpha < 1.0)
{
gMat.AlphaMode = AlphaMode.BLEND;
gMat.DoubleSided = true;
}
return gMat;
}
//TODO: move to gltf model ?!?
private int GetMaterialIndex(GltfModel gltfModel, string matName)
{
for (var i = 0; i < gltfModel.Materials.Count; i++)
{
if (gltfModel.Materials[i].Name == matName)
{
return i;
}
}
return -1;
}
#endregion Materials
#region Meshes
private int AddMesh(GltfModel gltfModel, ObjModel objModel, BufferState buffer, Geometry mesh)
{
var ps = AddVertexAttributes(gltfModel, objModel, buffer, mesh);
var m = new Mesh
{
Name = mesh.Id,
Primitives = ps
};
var meshIndex = gltfModel.Meshes.Count;
gltfModel.Meshes.Add(m);
return meshIndex;
}
private List<Primitive> AddVertexAttributes(GltfModel gltfModel,
ObjModel objModel,
BufferState bufferState,
Geometry mesh)
{
var facesGroup = mesh.Faces.GroupBy(c => c.MatName);
var faces = new List<Face>();
foreach (var fg in facesGroup)
{
var matName = fg.Key;
var f = new Face(matName);
foreach (var ff in fg)
f.Triangles.AddRange(ff.Triangles);
if (f.Triangles.Count > 0)
faces.Add(f);
}
// Vertex attributes are shared by all primitives in the mesh
var name0 = mesh.Id;
var ps = new List<Primitive>(faces.Count * 2);
var index = 0;
foreach (var f in faces)
{
var faceName = name0;
if (index > 0)
{
faceName = $"{name0}_{index}";
}
var hasUvs = f.Triangles.Any(d => d.V1.T > 0);
var hasNormals = f.Triangles.Any(d => d.V1.N > 0);
var hasColors = objModel.Colors.Count == objModel.Vertices.Count;
var materialIndex = GetMaterialIndexOrDefault(gltfModel, objModel, f.MatName);
// Fix Issue #36: look up the OBJ material by name instead of relying
// on the gltfModel index, which can diverge from objModel.Materials
// when the default material is inserted at index 0.
var material = !string.IsNullOrEmpty(f.MatName)
? objModel.Materials.FirstOrDefault(m => m.Name == f.MatName)
?? (materialIndex < objModel.Materials.Count ? objModel.Materials[materialIndex] : null)
: objModel.Materials.FirstOrDefault();
var materialHasTexture = material?.DiffuseTextureFile != null;
// every primitive needs their own vertex indices(v,t,n)
var faceVertexCache = new Dictionary<string, int>();
var faceVertexCount = 0;
var atts = new Dictionary<string, int>();
var indicesAccessorIndex = bufferState.MakeIndicesAccessor(faceName + "_indices");
var accessorIndex = bufferState.MakePositionAccessor(faceName + "_positions");
atts.Add("POSITION", accessorIndex);
if (hasNormals)
{
var normalsAccessorIndex = bufferState.MakeNormalAccessors(faceName + "_normals");
atts.Add("NORMAL", normalsAccessorIndex);
}
if (materialHasTexture)
{
if (hasUvs)
{
var uvAccessorIndex = bufferState.MakeUvAccessor(faceName + "_texcoords");
atts.Add("TEXCOORD_0", uvAccessorIndex);
}
else
{
var gMat = gltfModel.Materials[materialIndex];
if (gMat.PbrMetallicRoughness.BaseColorTexture != null)
{
gMat.PbrMetallicRoughness.BaseColorTexture = null;
}
}
}
if (hasColors)
{
var colorsAccessorIndex = bufferState.MakeColorsAccessor(faceName + "_colors");
atts.Add("COLOR_0", colorsAccessorIndex);
}
// f is a primitive
var iList = new List<int>(f.Triangles.Count * 3 * 2); // primitive indices
foreach (var triangle in f.Triangles)
{
var v1Index = triangle.V1.V - 1;
var v2Index = triangle.V2.V - 1;
var v3Index = triangle.V3.V - 1;
var v1 = objModel.Vertices[v1Index];
var v2 = objModel.Vertices[v2Index];
var v3 = objModel.Vertices[v3Index];
var n1 = new SVec3();
var n2 = new SVec3();
var n3 = new SVec3();
if (triangle.V1.N > 0) // hasNormals
{
var n1Index = triangle.V1.N - 1;
var n2Index = triangle.V2.N - 1;
var n3Index = triangle.V3.N - 1;
n1 = objModel.Normals[n1Index];
n2 = objModel.Normals[n2Index];
n3 = objModel.Normals[n3Index];
}
var t1 = new SVec2();
var t2 = new SVec2();
var t3 = new SVec2();
if (materialHasTexture)
{
if (triangle.V1.T > 0) // hasUvs
{
var t1Index = triangle.V1.T - 1;
var t2Index = triangle.V2.T - 1;
var t3Index = triangle.V3.T - 1;
t1 = objModel.Uvs[t1Index];
t2 = objModel.Uvs[t2Index];
t3 = objModel.Uvs[t3Index];
}
}
var v1Str = triangle.V1.ToString();
if (!faceVertexCache.ContainsKey(v1Str))
{
faceVertexCache.Add(v1Str, faceVertexCount++);
bufferState.AddPosition(v1);
if (triangle.V1.N > 0) // hasNormals
{
bufferState.AddNormal(n1);
}
if (hasColors)
{
bufferState.AddColor(SrgbToLinear(objModel.Colors[v1Index]));
}
if (materialHasTexture)
{
if (triangle.V1.T > 0) // hasUvs
{
var uv = new SVec2(t1.U, 1 - t1.V);
bufferState.AddUv(uv);
}
}
}
var v2Str = triangle.V2.ToString();
if (!faceVertexCache.ContainsKey(v2Str))
{
faceVertexCache.Add(v2Str, faceVertexCount++);
bufferState.AddPosition(v2);
if (triangle.V2.N > 0) // hasNormals
{
bufferState.AddNormal(n2);
}
if (hasColors)
{
bufferState.AddColor(SrgbToLinear(objModel.Colors[v2Index]));
}
if (materialHasTexture)
{
if (triangle.V2.T > 0) // hasUvs
{
var uv = new SVec2(t2.U, 1 - t2.V);
bufferState.AddUv(uv);
}
}
}
var v3Str = triangle.V3.ToString();
if (!faceVertexCache.ContainsKey(v3Str))
{
faceVertexCache.Add(v3Str, faceVertexCount++);
bufferState.AddPosition(v3);
if (triangle.V3.N > 0) // hasNormals
{
bufferState.AddNormal(n3);
}
if (hasColors)
{
bufferState.AddColor(SrgbToLinear(objModel.Colors[v3Index]));
}
if (materialHasTexture)
{
if (triangle.V3.T > 0) // hasUvs
{
var uv = new SVec2(t3.U, 1 - t3.V);
bufferState.AddUv(uv);
}
}
}
// Vertex Indices
var correctWinding = CheckWindingCorrect(v1, v2, v3, n1);
if (correctWinding)
{
iList.AddRange(new[] {
faceVertexCache[v1Str],
faceVertexCache[v2Str],
faceVertexCache[v3Str]
});
}
else
{
iList.AddRange(new[] {
faceVertexCache[v1Str],
faceVertexCache[v3Str],
faceVertexCache[v2Str]
});
}
}
foreach (var i in iList)
{
bufferState.AddIndex(i);
}
var p = new Primitive
{
Attributes = atts,
Indices = indicesAccessorIndex,
Material = materialIndex,
Mode = MeshMode.Triangles
};
ps.Add(p);
index++;
}
return ps;
}
private int GetMaterialIndexOrDefault(GltfModel gltfModel, ObjModel objModel, string materialName)
{
if (string.IsNullOrEmpty(materialName)) materialName = "default";
var materialIndex = GetMaterialIndex(gltfModel, materialName);
if (materialIndex == -1)
{
var objMaterial = objModel.Materials.FirstOrDefault(c => c.Name == materialName);
if (objMaterial == null)
{
materialName = "default";
materialIndex = GetMaterialIndex(gltfModel, materialName);
if (materialIndex == -1)
{
var gMat = GetDefault();
materialIndex = AddMaterial(gltfModel, gMat);
}
else
{
#if DEBUG
Debugger.Break();
#endif
}
}
else
{
var gMat = ConvertMaterial(objMaterial, t => GetTextureIndex(gltfModel, t));
materialIndex = AddMaterial(gltfModel, gMat);
}
}
return materialIndex;
}
private int AddNode(GltfModel gltfModel, string name, int? meshIndex, int? parentIndex = null)
{
var node = new Node { Name = name, Mesh = meshIndex };
var nodeIndex = gltfModel.Nodes.Count;
gltfModel.Nodes.Add(node);
gltfModel.Scenes[gltfModel.Scene].Nodes.Add(nodeIndex);
return nodeIndex;
}
#endregion Meshes
#region sRGB to Linear
/// <summary>
/// Converts an sRGB color to linear RGB for glTF COLOR_0 attribute.
/// Uses IEC 61966-2-1 transfer function.
/// </summary>
private static SVec3 SrgbToLinear(SVec3 srgb)
{
return new SVec3(
SrgbChannelToLinear(srgb.X),
SrgbChannelToLinear(srgb.Y),
SrgbChannelToLinear(srgb.Z));
}
private static float SrgbChannelToLinear(float c)
{
if (c <= 0.04045f)
return c / 12.92f;
return (float)Math.Pow((c + 0.055) / 1.055, 2.4);
}
#endregion sRGB to Linear
}
}