-
Notifications
You must be signed in to change notification settings - Fork 0
/
OBJLoader.cs
1452 lines (1264 loc) · 69.3 KB
/
OBJLoader.cs
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
using System.Text.RegularExpressions;
using UnityEngine.Networking;
using System.Globalization;
public class OBJLoader : MonoBehaviour
{
/// <summary>class for the vertex/uv couple</summary>
public struct TVertexUv
{
public int u;
public int v;
public TVertexUv(int _u, int _v)
{
u = _u;
v = _v;
}
}
/// <summary>Class for the vertex/normal couple</summary>
public struct TVertexNormal
{
public int u;
public int v;
public TVertexNormal(int _u, int _v)
{
u = _u;
v = _v;
}
}
/// <summary>Class for the vertex/uv/normal</summary>
public struct TVertexUvNormal
{
public int t;
public int u;
public int v;
public TVertexUvNormal(int _t, int _u, int _v)
{
t = _t;
u = _u;
v = _v;
}
}
/// <summary>Class for add vertices, normals, uvs and triangles</summary>
public class CMeshData
{
public List<Vector3> vertices; //Store vertices
public List<Vector3> normals; //Store Normals
public List<Vector2> uvs; //Store UVS
public CMeshData() //builder
{
vertices = new List<Vector3>();
normals = new List<Vector3>();
uvs = new List<Vector2>();
}
}
/// <summary>Class to store any of the objects read from the object file</summary>
public class COBJFileObject
{
public bool hasNormals; //contains if the object has normals or not
public bool hasUvs; //contains if the object has texture or not
public List<int> triangles; //Store the object triangles
public List<string> identv; //list for save the different identifiers of vertices
public List<string> identu; //list for save the different identifiers of uvs/texture
public List<string> identn; //list for save the different identifiers of normals
public List<int> triangv; //list for save the different identifiers of vertices ordered without repeat
public List<int> triangu; //list for save the different identifiers of uvs ordered without repeat
public List<int> triangn; //list for save the different identifiers of normals ordered without repeat
public List<int> aIden; //list for save the position of each vertex, uvs and normal, for unit them later and form triangles
public int quantity; //quantity of news numbers to identify
public int account; //counts the quantity of numbers identified
public string name; //Object name
public int partNumber; //Object part number. Zero if there just one part
public string materialName; //Name of the material of the object
// Constructors
public COBJFileObject() {
Initialize();
}
public COBJFileObject(string _name)
{
Initialize();
name = _name;
}
void Initialize()
{
hasNormals = false;
hasUvs = false;
quantity = 0;
account = 0;
partNumber = 0;
materialName = "";
//creates the lists
identv = new List<string>();
identu = new List<string>();
identn = new List<string>();
triangv = new List<int>();
triangu = new List<int>();
triangn = new List<int>();
aIden = new List<int>();
//myMesh = new Mesh_type();
triangles = new List<int>();
}
public void Clear()
{
identv.Clear();
identu .Clear();
identn .Clear();
triangv .Clear();
triangu .Clear();
triangn.Clear();
aIden.Clear();
triangles.Clear();
}
}
const int M = 65000; //maximum number of vertices for each object son
private enum fileOrigin_type { resources, web }; //two different origins for the file
private fileOrigin_type fileOrigin; //variables to select if, in the editor, we want to read the file from a file in the resources folder or from a URL (emulating WebGL)
//string folder; //will be take the folder select between local or web file
string fullFileUrl;
//string localFile;
string fullFilePath; //file name
string baseUrlOBJFile;
string pathFilePath;
C3DFileData file; //3D file data
Hom3rFileReader fileToRead; //will reads the file loaded
GameObject defaultParent; //father object for each file loaded
string multiplePartObjectPrefix; //part of the name of each object son
int numberOfObjectsRead; //Store the number of objects read from the file
GameObject multiplePartObject; //Store the parent object when one object have multiple parts, more than 65000 vertices.
bool loadingMaterialFile; //Is true when a material file is been loading
List<Material> listOfReadMaterials; //list of materials loaded of the mtl file
Texture2D webTexture; //Texture to download from the web
bool firstmat = true; //control if the same object use various materials
bool mapKsTextureExist; // Control if the KS texture exist or not
public CMeshData mymesh; //Store vertices, normals and UVS from the read file
COBJFileObject newReadObject; //One object
//List<COBJFileObject> listOfReadObjects; //List of objects read from the file
public Dictionary<TVertexUv, int> triangVertexUvDictionary; //dictionary for find vertices/uvs faster
public Dictionary<TVertexNormal, int> triangVertexNormalDictionary; //dictionary for find vertices/uvs faster
public Dictionary<TVertexUvNormal, int> triangVertexUvNormalDictionary; //dictionary for find vertices/uvs faster
public Dictionary<int, int> triangVertexDictionary; //dictionary for find vertices faster
bool error; //To store if exist any error during the file download
System.Diagnostics.Stopwatch stopwatch;
void Awake()
{
//Initialize variables
numberOfObjectsRead = 0;
loadingMaterialFile = false;
listOfReadMaterials = new List<Material>();
newReadObject = new COBJFileObject();
//listOfReadObjects = new List<COBJFileObject>();
mymesh = new CMeshData();
triangVertexUvDictionary = new Dictionary<TVertexUv, int>();
triangVertexNormalDictionary = new Dictionary<TVertexNormal, int>();
triangVertexUvNormalDictionary = new Dictionary<TVertexUvNormal, int>();
triangVertexDictionary = new Dictionary<int, int>();
multiplePartObjectPrefix = "part"; // Part of the name of each object son
error = false; // Initialize to false
}
////////////////////////
// Paint Methods
////////////////////////
/// <summary>Find a name to the object to be painted</summary>
/// <param name="_name">Suggested name</param>
/// <returns></returns>
string FindNameToObject(string _name)
{
int i = 1;
string finalName = _name;
while (GameObject.Find(finalName) != null)
{
i++;
finalName = _name + "_" + i.ToString();
}
return finalName;
}
/// <summary>Create a object in the Unity scene hierarchy tree</summary>
/// <param name="_object">Object data read from the OBJ file</param>
/// <returns></returns>
GameObject PaintCreateObject(COBJFileObject _object)
{
GameObject newObject;
if (_object.partNumber == 0)
{
if (_object.name == null) { return defaultParent; } //If the file does not contain a object Name we make child of the default object
newObject = new GameObject(FindNameToObject(_object.name)); //creates the object 3D with the name previously saved
newObject.transform.parent = defaultParent.transform; //sets the object parent
return newObject;
}
else if (_object.partNumber == 1)
{
if (_object.name == null)
{
multiplePartObject = defaultParent; //If the file does not contain a object Name we make child of the default object
}
else
{
//Create the multiple part parent
newObject = new GameObject(FindNameToObject(_object.name)); //Creates the multiple-part parent object 3D with the name previously saved
newObject.transform.parent = defaultParent.transform; //sets the object parent
multiplePartObject = newObject; //Saves the multiple-part parent
}
//Create the first part
newObject = new GameObject(multiplePartObject.name + "_" + multiplePartObjectPrefix + "_" + _object.partNumber.ToString()); //Creates the object 3D with the name previously saved
newObject.transform.parent = multiplePartObject.transform; //sets the object parent
return newObject;
}
else
{
if (multiplePartObject != null)
{
//Create the n part
newObject = new GameObject(multiplePartObject.name + "_" + multiplePartObjectPrefix + "_" + _object.partNumber.ToString()); //Creates the object 3D with the name previously saved
newObject.transform.parent = multiplePartObject.transform; //sets the object parent
return newObject;
}
}
return null;
}
/// <summary>Paint one object</summary>
/// <param name="_object">Object data read from the OBJ file</param>
void PaintOneObject(COBJFileObject _object)
{
GameObject newObject;
CMeshData buildingMesh; //Store the final mesh
buildingMesh = new CMeshData(); //Initialize Mesh structure;
////////////////////////
// CREATE THE OBJECT
////////////////////////
newObject = PaintCreateObject(_object); //Create the object
if (newObject==null) { return; } //If we cannot create the object do nothing
newObject.AddComponent<MeshFilter>(); //Adds to the object a new mesh
newObject.AddComponent<MeshRenderer>(); //Adds to the object the new material
//////////
// MESH
//////////
Mesh tempMesh = new Mesh(); //creates the mesh
tempMesh.name = _object.name; //name of the mesh
//Vertices
for (int i = 0; i < _object.triangv.Count; i++) //for all vertices
{
//takes the identifier of the vertex, searches it in personal mesh and adds it to the final mesh
buildingMesh.vertices.Add(mymesh.vertices[_object.triangv[i]]);
}
tempMesh.vertices = buildingMesh.vertices.ToArray(); //assigns the vertices of the final mesh to the mesh of the object created
//Triangles
tempMesh.triangles = _object.triangles.ToArray(); //assigns the triangles of the personal mesh to the mesh of the object
//UVS
if (_object.hasUvs == true) //if has texture, adds it
{
for (int i = 0; i < _object.triangu.Count; i++) //for all uvs
{
//takes the identifier of the uv, searches it in personal mesh and adds it to the final mesh
buildingMesh.uvs.Add(mymesh.uvs[_object.triangu[i]]);
}
tempMesh.uv = buildingMesh.uvs.ToArray(); //assigns the uvs of the final mesh to the mesh of the object created
}
//Normals
if (_object.hasNormals == true) //if the file has normals, adds them
{
for (int i = 0; i < _object.triangn.Count; i++) //for all normals
{
//takes the identifier of the normal, searches it in personal mesh and adds it to the final mesh
buildingMesh.normals.Add(mymesh.normals[_object.triangn[i]]);
}
tempMesh.normals = buildingMesh.normals.ToArray(); //assigns the normals of the final mesh to the mesh of the object
}
else //if the file has not normals
{
tempMesh.RecalculateNormals(); //recalculates the normals
}
//////////////
// MATERIAL
//////////////
Material mat = new Material(Shader.Find("Standard")); //loads the material
int index = listOfReadMaterials.FindIndex(r => r.name == _object.materialName);
if (index != -1) { mat = listOfReadMaterials[index]; } //loads it
/////////////////////////////////////////////
// Copy Material and Mesh to the object
/////////////////////////////////////////////
newObject.GetComponent<Renderer>().material = mat; //sets the material of the object
newObject.GetComponent<MeshFilter>().mesh = tempMesh; //sets the mesh of the object and shows it
}
/// <summary>Clear all the structure when the execution has finished</summary>
void Reset()
{
listOfReadMaterials.Clear(); //resets the list of the materials
numberOfObjectsRead = 0;
newReadObject = new COBJFileObject(); //Initialize the temp object to store one read object
//listOfReadObjects.Clear(); //Initialize the list of objects to be read
mymesh = new CMeshData();
}
/////////////////////
// Material loader
/////////////////////
/// <summary>Load texture file from a URL</summary>
/// <param name="url">texture file path</param>
/// <returns></returns>
IEnumerator CoroutineLoadTextureFromWebFile(string pictureFileName, string url)
{
if (url == null)
{
LoadTextureFromWebFile_Error("The texture file called " + pictureFileName + " cannot be found.");
yield break;
}
//webTexture = new Texture2D(1, 1); //Create a new texture file
SendMessageToUI("Downloading " + pictureFileName + " : 0%"); //Send message to UI
//WWW www = new WWW(url); //Start download
UnityWebRequest www = UnityWebRequestTexture.GetTexture(url);
www.SendWebRequest();
while (!www.isDone)
{
//Show downloaded progress
SendMessageToUI("Downloading texture file " + pictureFileName + " : " + Mathf.Round(www.downloadProgress * 100.0f).ToString() + "%"); //Send message to UI
yield return new WaitForSeconds(0.1f);
}
if (www.isNetworkError || www.isHttpError) {
LoadTextureFromWebFile_Error("Error downloading texture file " + pictureFileName);
Debug.Log("Texture download error: " + www.error); //shows the error
} else {
//if there is no error
SendMessageToUI("Downloading texture file " + pictureFileName + " : 100%"); //Send message to UI
SendMessageToUI("Opening " + pictureFileName + "..."); //Send message to UI
webTexture = ((DownloadHandlerTexture)www.downloadHandler).texture;
//www.LoadImageIntoTexture(webTexture); //Load texture into the variable
webTexture.name = pictureFileName; //Save texture name
}
}
private void LoadTextureFromWebFile_Error(string error_message)
{
error = true;
hom3r.coreLink.EmitEvent(new CCoreEvent(TCoreEvent.ModelManagement_3DLoadError, error_message));
hom3r.coreLink.EmitEvent(new CCoreEvent(TCoreEvent._3DFileManager_ShowMessageConsole, "Texture download error: " + error_message));
}
/// <summary>Process material file line</summary>
/// <param name="row">string line to process</param>
/// <param name="material">material to store the info read</param>
void ProcessMaterialFileLine(string row, ref Material material)
{
float Ns;
float visibility;
Color ctemp;
if (row.StartsWith("newmtl ")) //new material
{
if (material != null) //if is not the first material
{
listOfReadMaterials.Add(material); //adds the last material to the list
}
material = new Material(Shader.Find("Standard")); //creates a new standard material by default
material.name = row.Replace("newmtl ", "").Trim(); //name of the new material
mapKsTextureExist = false;
}
else if (row.StartsWith("Ns ")) //specular exponent that ponders the value of specular colour
{
Ns = float.Parse(row.Replace("Ns ", "").Trim(), CultureInfo.InvariantCulture); //converts the value read to float
Ns = Ns / 1000; //possible values between 0 and 1000
if (!mapKsTextureExist)
{
//Map into the _Glossiness parameter because there are not KS texture
material.SetFloat("_Glossiness", Ns); //sets this value in the material
} else {
//Map into the _GlossMapScale parameter because there are KS texture
material.SetFloat("_GlossMapScale", Ns); //sets this value in the material
}
}
else if (row.StartsWith("Ka ")) //ambient colour
{
//converts the value read to colour type in secondary function and sets this value in the material
material.SetColor("_EmissionColor", ConColor(row.Replace("Ka ", "").Trim(), 0.05f));
material.EnableKeyword("_EMISSION"); //sets a shader keyword
}
else if (row.StartsWith("Kd ")) //diffuse colour
{
//converts the value read to colour type in secondary function and sets this value in the material
material.SetColor("_Color", ConColor(row.Replace("Kd ", "").Trim()));
}
else if (row.StartsWith("Ks ")) //specular colour
{
//converts the value read to colour type in secondary function and sets this value in the material
material.SetColor("_SpecColor", ConColor(row.Replace("Ks ", "").Trim()));
}
else if (row.StartsWith("d ") || row.StartsWith("Tr ")) //transparency
{
if (row.StartsWith("d ")) //Transparency factor, opaque(1) and transparent(0)
{
visibility = float.Parse(row.Replace("d ", "").Trim(), CultureInfo.InvariantCulture); //converts it to float
}
else if (row.StartsWith("Tr ")) //opposite to the transparency factor, transparent(1) and opaque(0)
{
visibility = 1 - float.Parse(row.Replace("Tr ", "").Trim(), CultureInfo.InvariantCulture); //transparency factor = 1 - value read
}
else //should not enter here, but fail if removed
{
visibility = 1; //for default, totally opaque
}
if (visibility < 1) //if is not totally opaque
{
ctemp = material.color; //loads the colour
ctemp.a = visibility; //sets the new transparency factor
material.SetColor("_Color", ctemp); //sets the new colour
//transparency enabler
material.SetFloat("_Mode", 3);
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt("_ZWrite", 0);
material.DisableKeyword("_ALPHATEST_ON");
material.EnableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = 3000;
}
}
else if (row.StartsWith("map_Kd ")) //texture
{
//loads texture from file
if ((Application.platform == RuntimePlatform.WindowsEditor) || (Application.platform == RuntimePlatform.OSXEditor) || (Application.platform == RuntimePlatform.WindowsPlayer) || (Application.platform == RuntimePlatform.OSXPlayer))
{
string dirIma = pathFilePath + row.Replace("map_Kd ", "").Trim(); //image direction
if (File.Exists(dirIma)) //if exist the file
{
string ext = Path.GetExtension(dirIma).ToLower(); //gets the image extension and converts in lower-case
//https://stackoverflow.com/questions/45416808/unity-create-texture-from-tga
if ((ext == ".png") || (ext == ".jpg")) //image format, png or jpg
{
Texture2D tex = new Texture2D(1, 1); //new texture
tex.LoadImage(File.ReadAllBytes(dirIma)); //loads the image and sets the texture
material.SetTexture("_MainTex", tex); //sets the material with the loaded texture
}
else //other types, not identified
{
Debug.Log("Texture not support: " + ext); //shows it the error
}
}
}
}
else if (row.StartsWith("map_bump ") || row.StartsWith("bump ")) //bump mapping
{
if ((Application.platform == RuntimePlatform.WindowsEditor) || (Application.platform == RuntimePlatform.OSXEditor) || (Application.platform == RuntimePlatform.WindowsPlayer) || (Application.platform == RuntimePlatform.OSXPlayer))
{
//loads bump texture from file
string dirIma; //saves the image direction
if (row.StartsWith("map_bump "))
{
dirIma = pathFilePath + row.Replace("map_bump ", "").Trim(); //image direction
}
else //row.StartsWith("bump ")
{
dirIma = pathFilePath + row.Replace("bump ", "").Trim(); //image direction
}
if (File.Exists(dirIma)) //if exist the file
{
string ext = Path.GetExtension(dirIma).ToLower(); //gets the image extension and converts in lower-case
if ((ext == ".png") || (ext == ".jpg")) //image format, png or jpg
{
Texture2D tex = new Texture2D(1, 1); //creates the new texture
tex.LoadImage(File.ReadAllBytes(dirIma)); //loads the image and sets the texture
Color[] pixels = tex.GetPixels(); //gets the pixels and assigns them to the array
for (int i = 0; i < pixels.Length; i++) //for all pixels
{
Color colTemp = pixels[i]; //creates a temporal colour
colTemp.r = pixels[i].g; //assigns the green to the red
colTemp.a = pixels[i].r; //assigns the red to the alpha
pixels[i] = colTemp; //saves the temporal colour modified
}
tex.SetPixels(pixels); //sets the texture with the new pixels
material.SetTexture("_BumpMap", tex); //sets the material with the loaded texture
material.EnableKeyword("_NORMALMAP"); //sets a shader keyword
material.SetFloat("_BumpScale", (float)0.5); //sets the intensity of the normal map
}
else //other types, not identified
{
Debug.Log("Texture not support: " + ext); //shows it the error
}
}
}
}
}
/// <summary>Loads the material file from a URL path</summary>
/// <param name="url">URL file path</param>
/// <returns></returns>
IEnumerator CoroutineLoadMaterialFile_fromUrl(string materialFileName, string url)
{
if (url == null)
{
LoadMaterialFile_fromUrl_Error("The material file called " + materialFileName + " cannot be found.");
yield break;
}
SendMessageToUI("Downloading " + materialFileName + " : 0%"); //Send message to UI
//WWW fileWWW = new WWW(url); //Download material file
UnityWebRequest fileWWW = UnityWebRequest.Get(url);
fileWWW.SendWebRequest();
//Show downloaded progress
while (!fileWWW.isDone)
{
SendMessageToUI("Downloading " + materialFileName + " : " + Mathf.Round(fileWWW.downloadProgress * 100.0f).ToString() + "%");
yield return new WaitForSeconds(0.1f);
}
// Check if error
if (fileWWW.isNetworkError || fileWWW.isHttpError) {
//error = true;
//FinishOBJDownload();
//hom3r.coreLink.Do(new CIOCommand(TIOCommands.ReportError, "Error downloading material file " + materialFileName), Constants.undoNotAllowed);
LoadMaterialFile_fromUrl_Error("Error downloading material file " + materialFileName);
Debug.LogError("WWW error: " + fileWWW.error); //shows the error
} else {
SendMessageToUI("Downloading " + materialFileName + " file : 100%");
Hom3rFileReader materialFileToRead = new Hom3rFileReader(fileWWW); //file read from the direction passed as parameter
SendMessageToUI("Reading " + materialFileName + "...");
//Process file line by line
bool nextLine = true;
string lineRead;
Material material = null; //sets up the materials later
while (nextLine) //if can continue reading the file
{
lineRead = materialFileToRead.GetLine(); //reads the line in secondary function
if (lineRead != null) //if is not last line
{
lineRead = lineRead.Trim(); //Clean spaces
if (lineRead.StartsWith("map_Kd "))
{
//loads texture from URL
string cleanedLine = lineRead.Replace("map_Kd ", "").Trim(); //image direction
//Get Parameters and filename
string pictureFileName;
string[] parameters; // TODO use parameters
ExtractDataFrom(cleanedLine, out pictureFileName, out parameters);
//Image file extension
string pictureExtension = Path.GetExtension(pictureFileName).ToLower(); //gets the image extension and converts in lower-case
if ((pictureExtension == ".png") || (pictureExtension == ".jpg")) //image format, png or jpg
{
string pictureUrl = GetResourcesFileURL(pictureFileName);
//Texture webTexture = null; // new Texture(); //Texture to download from the web
yield return StartCoroutine(CoroutineLoadTextureFromWebFile(pictureFileName, pictureUrl)); //Download the texture and wait until it finish
material.SetTexture("_MainTex", webTexture); //sets the material with the loaded texture
//Check Colour - If the colour is black we change it to white
if (material.GetColor("_Color") == Color.black) { material.SetColor("_Color", Color.white); }
}
else //other types, not identified
{
Debug.Log("Texture not support: " + pictureExtension); //shows it the error
this.SendMessageToUI("Texture not support: " + pictureExtension);
}
}
else if (lineRead.StartsWith("map_bump ") || lineRead.StartsWith("bump ")) //bump mapping
{
//loads bump texture from URL
string cleanedLine;
//Image path
cleanedLine = lineRead.Replace("bump ", "").Trim();
cleanedLine = lineRead.Replace("map_", "").Trim();
//Get Parameters and filename
string pictureFileName;
string[] parameters; // TODO use parameters
ExtractDataFrom(cleanedLine, out pictureFileName, out parameters);
//Image file extension
string pictureExtension = Path.GetExtension(pictureFileName).ToLower(); //gets the image extension and converts in lower-case
if ((pictureExtension == ".png") || (pictureExtension == ".jpg"))
{
string pictureUrl = GetResourcesFileURL(pictureFileName);
Debug.Log(pictureUrl);
//Texture2D webTexture = new Texture2D(1, 1); //Texture to download from the web
yield return StartCoroutine(CoroutineLoadTextureFromWebFile(pictureFileName, pictureUrl)); //Download the texture and wait until it finish
Color[] pixels = webTexture.GetPixels(); //gets the pixels and assigns them to the array
for (int i = 0; i < pixels.Length; i++) //for all pixels
{
Color colTemp = pixels[i]; //creates a temporal colour
colTemp.r = pixels[i].g; //assigns the green to the red
colTemp.a = pixels[i].r; //assigns the red to the alpha
pixels[i] = colTemp; //saves the temporal colour modified
}
webTexture.SetPixels(pixels); //sets the texture with the new pixels
material.SetTexture("_BumpMap", webTexture); //sets the material with the loaded texture
material.EnableKeyword("_NORMALMAP"); //sets a shader keyword
material.SetFloat("_BumpScale", (float)1f); //sets the intensity of the normal map
}
else //other types, not identified
{
Debug.Log("Texture not support: " + pictureExtension); //shows it the error
this.SendMessageToUI("Texture not support: " + pictureExtension);
}
}
else if (lineRead.StartsWith("map_Ks "))
{
//loads texture from URL
string cleanedLine = lineRead.Replace("map_Ks ", "").Trim(); //image direction
//Get Parameters and filename
string pictureFileName;
string[] parameters; // TODO use parameters
ExtractDataFrom(cleanedLine, out pictureFileName, out parameters);
//Image file extension
string pictureExtension = Path.GetExtension(pictureFileName).ToLower(); //gets the image extension and converts in lower-case
if ((pictureExtension == ".png") || (pictureExtension == ".jpg")) //image format, png or jpg
{
string pictureUrl = GetResourcesFileURL(pictureFileName);
yield return StartCoroutine(CoroutineLoadTextureFromWebFile(pictureFileName, pictureUrl)); //Download the texture and wait until it finish
material.SetTexture("_MetallicGlossMap", webTexture); //sets the material with the loaded texture
material.EnableKeyword("_METALLICGLOSSMAP");
//float temp = Mathf.Exp(-3.0f / 18f);
//material.SetFloat("_GlossMapScale", temp); //sets this value in the material
mapKsTextureExist = true;
}
else //other types, not identified
{
Debug.Log("Texture not support: " + pictureExtension); //shows it the error
this.SendMessageToUI("Texture not support: " + pictureExtension);
}
}
else
{
ProcessMaterialFileLine(lineRead, ref material); //checks the line in secondary function
}
}
else
{
nextLine = false;
if (material != null) //if material exists
{
listOfReadMaterials.Add(material); //adds it to the list of materials
}
}
}
}
loadingMaterialFile = false;
}
private void LoadMaterialFile_fromUrl_Error(string error_message)
{
error = true;
//hom3r.coreLink.Do(new CIOCommand(TIOCommands.ReportError, error_message), Constants.undoNotAllowed);
hom3r.coreLink.EmitEvent(new CCoreEvent(TCoreEvent.ModelManagement_3DLoadError, error_message));
}
/// <summary>
/// Get parameters and filename
/// </summary>
/// <param name="input"></param>
/// <param name="fileName"></param>
/// <param name="parameters"></param>
private void ExtractDataFrom(string input, out string fileName, out string[] parameters)
{
parameters = input.Split(' ');
fileName = parameters[parameters.Length - 1];
Array.Resize<string>(ref parameters, parameters.Length - 1);
}
/// <summary>Loads the material file from local path</summary>
/// <param name="materialFilePath">file-path of the file</param>
IEnumerator CoroutineLoadMaterialFile_fromFile(string materialFilePath)
{
Hom3rFileReader materialFileToRead = new Hom3rFileReader(materialFilePath); //loads the file
bool nextLine = true;
string lineRead;
Material material = null; //sets up the materials later
while (nextLine) //if can continue reading the file
{
lineRead = materialFileToRead.GetLine(); //reads the line in secondary function
if (lineRead != null) //if is not last line
{
ProcessMaterialFileLine(lineRead.Trim(), ref material); //checks the line in secondary function
}
else
{
nextLine = false;
if (material != null) //if material exists
{
listOfReadMaterials.Add(material); //adds it to the list of materials
}
}
}
materialFileToRead.Close(); //closes the file
loadingMaterialFile = false;
yield return null;
}
/// <summary>Start to load the material file</summary>
/// <param name="materialFileName">file-path or URL of the file</param>
IEnumerator StartMaterialLoad(string materialFileName)
{
string url = GetResourcesFileURL(materialFileName); //Get file URL
loadingMaterialFile = true;
if ((Application.platform == RuntimePlatform.WebGLPlayer) || (Application.platform == RuntimePlatform.Android)) //if we work from internet
{
yield return StartCoroutine(CoroutineLoadMaterialFile_fromUrl(materialFileName, url)); //loads the file from URL
}
else if ((Application.platform == RuntimePlatform.WindowsEditor) || (Application.platform == RuntimePlatform.OSXEditor) || (Application.platform == RuntimePlatform.WindowsPlayer) || (Application.platform == RuntimePlatform.OSXPlayer))
{
//if we work from unity
if (fileOrigin == fileOrigin_type.resources) //if we select a local file
{
if (File.Exists(url)) //if exist the file in the direction
{
yield return StartCoroutine(CoroutineLoadMaterialFile_fromFile(url));
}
}
else //if we select a web file
{
yield return StartCoroutine(CoroutineLoadMaterialFile_fromUrl(materialFileName, url)); //loads the file from URL
}
}
}
/// <summary>Get the resource file URL</summary>
/// <param name="fileName">file name</param>
/// <returns>file URL</returns>
string GetResourcesFileURL(string fileName)
{
string url = this.GetComponent<_3DFileManager>().GetResourceFileURL(fileName);
//If the URL has been received from the interface we return it,
//if not we try to find it in the same URL that the OBJ file
if ( url != null) { return url; }
else if (baseUrlOBJFile != null) { return baseUrlOBJFile + fileName; }
else { return null; }
}
/////////////////////
// OBJ File loader
/////////////////////
/// <summary>Create a new object and reset temporary variables</summary>
/// <param name="_objectName">String that contains the new object name</param>
void CreateNewEmptyObject(string _objectName)
{
//clears the dictionaries for the next object
triangVertexUvDictionary.Clear();
triangVertexNormalDictionary.Clear();
triangVertexUvNormalDictionary.Clear();
triangVertexDictionary.Clear();
newReadObject = new COBJFileObject(_objectName); //Initialize the temp read object, removes "o " and assigns it to object name
}
void PaintObject(COBJFileObject newReadObject)
{
//int index = listOfReadMaterials.FindIndex(r => r.name == newReadObject.materialName);
//if ((!loadingMaterialFile) && (index != -1))
//{
//SendMessageToUI("Drawing " + newReadObject.name); //UI Message
PaintOneObject(newReadObject); //Paint the object
//}
//else
//{
// //Error
//}
}
/// <summary>Process OBJ file line</summary>
/// <param name="row">Line read from the file</param>
void ProcessOBJFileLine(string row)
{
List<string> temp = new List<string>(); //temporal variable for reads lines of triangles
List<string> pair = new List<string>(); //temporal variable for reads only pairs triangles
if (row.StartsWith("mtllib ")) //material to load
{
string materialFileName = row.Replace("mtllib ", "").Trim(); //material file path
StartMaterialLoad(materialFileName);
}
else if (row.StartsWith("o ") || row.StartsWith("g ")) //object name
{
if (numberOfObjectsRead != 0) {
//listOfReadObjects.Add(newReadObject); //Save the read object in the list, non the first time
PaintObject(newReadObject);
}
numberOfObjectsRead++;
firstmat = true; //control if the same object use various materials
if (row.StartsWith("o "))
{
CreateNewEmptyObject(row.Replace("o ", "").Trim());
}
else //row.StartsWith("g ")
{
CreateNewEmptyObject(row.Replace("g ", "").Trim());
}
}
else if (row.StartsWith("v ")) //vertex
{
mymesh.vertices.Add(ConVec3(row.Replace("v ", "").Trim(), file.invertZAxis)); //converts the line to Vec3 and add the coordinates
}
else if (row.StartsWith("vn ")) //normal
{
mymesh.normals.Add(ConVec3(row.Replace("vn ", "").Trim(), file.invertZAxis)); //converts the line to Vec3 and add the coordinates
}
else if (row.StartsWith("vt ")) //texture
{
mymesh.uvs.Add(ConVec2(row.Replace("vt ", "").Trim())); //converts the line to Vec2 and add the coordinates
}
else if (row.StartsWith("usemtl ")) //name of the material used
{
if (firstmat)
{
firstmat = false; //the next material will not be the first material
}
else //if do not be the first material
{
string saveName = newReadObject.name;
//listOfReadObjects.Add(newReadObject); //Save the read object in the list, non the first time
PaintObject(newReadObject);
CreateNewEmptyObject(saveName); //Create next part object
}
newReadObject.materialName = row.Replace("usemtl ", "").Trim(); //removes "usemtl " and assigns it to object name
}
else if (row.StartsWith("f ")) //triangles
{
// Check if the polygonal face data come in more of one line
if (row[row.Length - 1] == '\\')
{
row = ReadMultipleLine_PolygonalFace(row); // Read all the lines
}
ProcessOBJFileLine_PolygonalFace(row); // Process the polygonal face
}
}
/// <summary>Read all the file lines that contains the polygonal face data</summary>
/// <param name="partialRow">First line</param>
/// <returns>All the file lines together</returns>
string ReadMultipleLine_PolygonalFace(string partialRow)
{
List<string> partialRows = new List<string>();
string fullRow = "";
//Get all the partial Rows
while (partialRow[partialRow.Length - 1] == '\\')
{
partialRows.Add(partialRow.TrimEnd('\\', ' '));
partialRow = fileToRead.GetLine().Trim();
}
partialRows.Add(partialRow.TrimEnd('\\', ' '));
foreach (string r in partialRows)
{
fullRow = fullRow + ' ' + r;
}
return fullRow;
}
void ProcessOBJFileLine_PolygonalFace(string row)
{
int i;
List<string> temp = new List<string>(); //temporal variable for reads lines of triangles
List<string> pair = new List<string>(); //temporal variable for reads only pairs triangles
int bar = 0; //counter of data taken
int d1 = 0, d2 = 0, d3 = 0;
row = row.Replace("f ", "").Trim(); //removes "f "
temp.AddRange(row.Split(' ')); //removes all spaces and add the data to the temporal list
if ((newReadObject.triangv.Count + temp.Count) > M) //If the old plus the new vertices is greater than the maximum
{
// More than 65000 vertexes Multiple part Object
if (newReadObject.partNumber == 0) { newReadObject.partNumber = 1; } //Check if it is the fist part of the object
//listOfReadObjects.Add(newReadObject); //Save the read object in the list, non the first time
PaintObject(newReadObject);
//Save info from first part
int _newPartNumber = newReadObject.partNumber + 1; //Save Next part number
string _newName = newReadObject.name; //Save Next part name
string _materialName = newReadObject.materialName; //Save the material name
//Create next part
CreateNewEmptyObject(_newName); //Create next part object
newReadObject.partNumber = _newPartNumber; //Update next part number
newReadObject.materialName = _materialName; //Update the material name
}
for (i = 0; i < temp.Count; i++) //the new data
{
if (temp[i].IndexOf("//") == -1) //if has not "//"
{
if (temp[i].IndexOf("/") == -1) //if has not "/", format X X X X
{
//this format, has not normals, has not texture
newReadObject.hasNormals = false;
newReadObject.hasUvs = false;
newReadObject.identv.Add(temp[i]); //add the identifier of the vertex
}
else //if has "/", format X/X or X/X/X
{
//remove all '/' of the line and add it to the possibles identifiers
pair.AddRange(temp[i].Split('/'));
if ((pair.Count - bar) == 2) //if has two data, format X/X
{
//this format, has not normals, has texture
newReadObject.hasNormals = false;
newReadObject.hasUvs = true;
newReadObject.identv.Add(pair[i * 2]); //takes the first of two for the vertices
newReadObject.identu.Add(pair[(i * 2) + 1]); //takes the second of two for the uvs
bar = bar + 2; //sums the number of data taken
}
else if ((pair.Count - bar) == 3) //if has three data, format X/X/X
{
//this format, has normals, has texture
newReadObject.hasNormals = true;
newReadObject.hasUvs = true;
newReadObject.identv.Add(pair[i * 3]); //takes the first of three for the vertices
newReadObject.identu.Add(pair[(i * 3) + 1]); //takes the second of three for the uvs
newReadObject.identn.Add(pair[(i * 3) + 2]); //takes the third of three for the normals
bar = bar + 3; //sums the number of data taken
}