summaryrefslogtreecommitdiff
path: root/Extras/obj2sdf/obj2sdf.cpp
blob: a59cd68f5daae5735ee9219adc8161f62f6906ad (plain)
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
/// obj2sdf will load a Wavefront .obj file that may contain many parts/materials
/// it will split into separate obj files for each part/material and
/// create an sdf file with visuals/collisions pointing to the new obj files
/// this will make it easier to load complex obj files into pybullet
/// see for example export in data/kitchens/fathirmutfak.sdf

///Bullet Continuous Collision Detection and Physics Library
///Erwin Coumans (C) 2018
///http://bulletphysics.org
///
///This software is provided 'as-is', without any express or implied warranty.
///In no event will the authors be held liable for any damages arising from the use of this software.
///Permission is granted to anyone to use this software for any purpose,
///including commercial applications, and to alter it and redistribute it freely,
///subject to the following restrictions:
///
///1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
///2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
///3. This notice may not be removed or altered from any source distribution.
	
#include <string.h>
#include <stdio.h>
#include <assert.h>
#define ASSERT_EQ(a, b) assert((a) == (b));
#include "Wavefront/tiny_obj_loader.h"
#include <vector>
#include "Bullet3Common/b3FileUtils.h"
#include "../Utils/b3ResourcePath.h"
#include "Bullet3Common/b3CommandLineArgs.h"
#include "Bullet3Common/b3HashMap.h"
#include "../Utils/b3BulletDefaultFileIO.h"

using tinyobj::index_t;

struct ShapeContainer
{
	std::string m_matName;
	std::string m_shapeName;
	tinyobj::material_t material;
	std::vector<float> positions;
	std::vector<float> normals;
	std::vector<float> texcoords;
	std::vector<index_t> indices;
	b3AlignedObjectArray<int> m_shapeIndices;
};

b3HashMap<b3HashString, ShapeContainer> gMaterialNames;

#define MAX_PATH_LEN 1024

std::string StripExtension(const std::string& sPath)
{
	for (std::string::const_reverse_iterator i = sPath.rbegin(); i != sPath.rend(); i++)
	{
		if (*i == '.')
		{
			return std::string(sPath.begin(), i.base() - 1);
		}

		// if we find a slash there is no extension
		if (*i == '\\' || *i == '/')
			break;
	}

	// we didn't find an extension
	return sPath;
}

int main(int argc, char* argv[])
{
	b3CommandLineArgs args(argc, argv);
	char* fileName;
	args.GetCmdLineArgument("fileName", fileName);
	if (fileName == 0)
	{
		printf("required --fileName=\"name\"");
		exit(0);
	}
	std::string matLibName = StripExtension(fileName);

	printf("fileName = %s\n", fileName);
	if (fileName == 0)
	{
		printf("Please use --fileName=\"pathToObj\".");
		exit(0);
	}
	bool mergeMaterials = args.CheckCmdLineFlag("mergeMaterials");

	char fileNameWithPath[MAX_PATH_LEN];
	bool fileFound = (b3ResourcePath::findResourcePath(fileName, fileNameWithPath, MAX_PATH_LEN,0)) > 0;
	char materialPrefixPath[MAX_PATH_LEN];
	b3FileUtils::extractPath(fileNameWithPath, materialPrefixPath, MAX_PATH_LEN);

	std::vector<tinyobj::shape_t> shapes;
	tinyobj::attrib_t attribute;

	b3BulletDefaultFileIO fileIO;
	std::string err = tinyobj::LoadObj(attribute, shapes, fileNameWithPath, materialPrefixPath,&fileIO);

	char sdfFileName[MAX_PATH_LEN];
	sprintf(sdfFileName, "%s%s.sdf", materialPrefixPath, "newsdf");
	FILE* sdfFile = fopen(sdfFileName, "w");
	if (sdfFile == 0)
	{
		printf("Fatal error: cannot create sdf file %s\n", sdfFileName);
		exit(0);
	}

	fprintf(sdfFile, "<sdf version='1.6'>\n\t<world name='default'>\n\t<gravity>0 0 -9.8</gravity>\n");

	for (int s = 0; s < (int)shapes.size(); s++)
	{
		tinyobj::shape_t& shape = shapes[s];
		tinyobj::material_t mat = shape.material;

		b3HashString key = mat.name.length() ? mat.name.c_str() : "";
		if (!gMaterialNames.find(key))
		{
			ShapeContainer container;
			container.m_matName = mat.name;
			container.m_shapeName = shape.name;
			container.material = mat;
			gMaterialNames.insert(key, container);
		}

		ShapeContainer* shapeC = gMaterialNames.find(key);
		if (shapeC)
		{
			shapeC->m_shapeIndices.push_back(s);

			int curPositions = shapeC->positions.size() / 3;
			int curNormals = shapeC->normals.size() / 3;
			int curTexcoords = shapeC->texcoords.size() / 2;

			int faceCount = shape.mesh.indices.size();
			int vertexCount = attribute.vertices.size();
			for (int v = 0; v < vertexCount; v++)
			{
				shapeC->positions.push_back(attribute.vertices[v]);
			}
			int numNormals = int(attribute.normals.size());
			for (int vn = 0; vn < numNormals; vn++)
			{
				shapeC->normals.push_back(attribute.normals[vn]);
			}
			int numTexCoords = int(attribute.texcoords.size());
			for (int vt = 0; vt < numTexCoords; vt++)
			{
				shapeC->texcoords.push_back(attribute.texcoords[vt]);
			}

			for (int face = 0; face < faceCount; face += 3)
			{
				if (face < 0 && face >= int(shape.mesh.indices.size()))
				{
					continue;
				}

				index_t index;
				for (int ii = 0; ii < 3; ii++)
				{
					index.vertex_index = shape.mesh.indices[face + ii].vertex_index + curPositions;
					index.normal_index = shape.mesh.indices[face + ii].normal_index + curNormals;
					index.texcoord_index = shape.mesh.indices[face + ii].texcoord_index + curTexcoords;
					shapeC->indices.push_back(index);
				}
			}
		}
	}

	printf("unique materials=%d\n", gMaterialNames.size());

	if (mergeMaterials)
	{
		for (int m = 0; m < gMaterialNames.size(); m++)
		{
			if (gMaterialNames.getAtIndex(m)->m_shapeIndices.size() == 0)
				continue;

			ShapeContainer* shapeCon = gMaterialNames.getAtIndex(m);

			printf("object name = %s\n", shapeCon->m_shapeName.c_str());

			char objSdfPartFileName[MAX_PATH_LEN];
			sprintf(objSdfPartFileName, "part%d.obj", m);

			char objFileName[MAX_PATH_LEN];
			if (strlen(materialPrefixPath) > 0)
			{
				sprintf(objFileName, "%s/part%d.obj", materialPrefixPath, m);
			}
			else
			{
				sprintf(objFileName, "part%d.obj", m);
			}

			FILE* f = fopen(objFileName, "w");
			if (f == 0)
			{
				printf("Fatal error: cannot create part obj file %s\n", objFileName);
				exit(0);
			}
			fprintf(f, "# Exported using automatic converter by Erwin Coumans\n");
			if (matLibName.length())
			{
				fprintf(f, "mtllib %s.mtl\n", matLibName.c_str());
			}
			else
			{
				fprintf(f, "mtllib bedroom.mtl\n");
			}

			int faceCount = shapeCon->indices.size();
			int vertexCount = shapeCon->positions.size();
			tinyobj::material_t mat = shapeCon->material;
			if (shapeCon->m_matName.length())
			{
				const char* objName = shapeCon->m_matName.c_str();
				printf("mat.name = %s\n", objName);
				fprintf(f, "#object %s\n\n", objName);
			}
			for (int v = 0; v < vertexCount / 3; v++)
			{
				fprintf(f, "v %f %f %f\n", shapeCon->positions[v * 3 + 0], shapeCon->positions[v * 3 + 1], shapeCon->positions[v * 3 + 2]);
			}

			if (mat.name.length())
			{
				fprintf(f, "usemtl %s\n", mat.name.c_str());
			}
			else
			{
				fprintf(f, "usemtl wire_028089177\n");
			}

			fprintf(f, "\n");
			int numNormals = int(shapeCon->normals.size());

			for (int vn = 0; vn < numNormals / 3; vn++)
			{
				fprintf(f, "vn %f %f %f\n", shapeCon->normals[vn * 3 + 0], shapeCon->normals[vn * 3 + 1], shapeCon->normals[vn * 3 + 2]);
			}

			fprintf(f, "\n");
			int numTexCoords = int(shapeCon->texcoords.size());
			for (int vt = 0; vt < numTexCoords / 2; vt++)
			{
				fprintf(f, "vt %f %f\n", shapeCon->texcoords[vt * 2 + 0], shapeCon->texcoords[vt * 2 + 1]);
			}

			fprintf(f, "s off\n");

			for (int face = 0; face < faceCount; face += 3)
			{
				if (face < 0 && face >= int(shapeCon->indices.size()))
				{
					continue;
				}
				fprintf(f, "f %d/%d/%d %d/%d/%d %d/%d/%d\n",
						shapeCon->indices[face].vertex_index + 1, shapeCon->indices[face].texcoord_index + 1, shapeCon->indices[face].normal_index + 1,
						shapeCon->indices[face + 1].vertex_index + 1, shapeCon->indices[face + 1].texcoord_index + 1, shapeCon->indices[face + 1].normal_index + 1,
						shapeCon->indices[face + 2].vertex_index + 1, shapeCon->indices[face + 2].texcoord_index + 1, shapeCon->indices[face + 2].normal_index + 1);
			}
			fclose(f);

			float kdRed = mat.diffuse[0];
			float kdGreen = mat.diffuse[1];
			float kdBlue = mat.diffuse[2];
			float transparency = mat.transparency;

			fprintf(sdfFile,
					"\t\t<model name='%s'>\n"
					"\t\t\t<static>1</static>\n"
					"\t\t\t<pose >0 0 0 0 0 0</pose>\n"
					"\t\t\t<link name='link_d%d'>\n"
					"\t\t\t<inertial>\n"
					"\t\t\t<mass>0</mass>\n"
					"\t\t\t<inertia>\n"
					"\t\t\t<ixx>0.166667</ixx>\n"
					"\t\t\t<ixy>0</ixy>\n"
					"\t\t\t<ixz>0</ixz>\n"
					"\t\t\t<iyy>0.166667</iyy>\n"
					"\t\t\t<iyz>0</iyz>\n"
					"\t\t\t<izz>0.166667</izz>\n"
					"\t\t\t</inertia>\n"
					"\t\t\t</inertial>\n"
					"\t\t\t<collision concave='yes' name='collision_%d'>\n"
					"\t\t\t<geometry>\n"
					"\t\t\t<mesh>\n"
					"\t\t\t<scale>1 1 1</scale>\n"
					"\t\t\t\t<uri>%s</uri>\n"
					"\t\t\t</mesh>\n"
					"\t\t\t</geometry>\n"
					"\t\t\t  </collision>\n"
					"\t\t\t<visual name='visual'>\n"
					"\t\t\t\t<geometry>\n"
					"\t\t\t\t<mesh>\n"
					"\t\t\t\t\t<scale>1 1 1</scale>\n"
					"\t\t\t\t\t<uri>%s</uri>\n"
					"\t\t\t\t</mesh>\n"
					"\t\t\t\t</geometry>\n"
					"\t\t\t<material>\n"
					"\t\t\t\t<ambient>1 0 0 1</ambient>\n"
					"\t\t\t\t<diffuse>%f %f %f %f</diffuse>\n"
					"\t\t\t\t<specular>0.1 0.1 0.1 1</specular>\n"
					"\t\t\t\t<emissive>0 0 0 0</emissive>\n"
					"\t\t\t </material>\n"
					"\t\t\t </visual>\n"
					"\t\t\t </link>\n"
					"\t\t\t</model>\n",
					objSdfPartFileName, m, m,
					objSdfPartFileName, objSdfPartFileName,
					kdRed, kdGreen, kdBlue, transparency);
		}
	}
	else
	{
		for (int s = 0; s < (int)shapes.size(); s++)
		{
			tinyobj::shape_t& shape = shapes[s];

			if (shape.name.length())
			{
				printf("object name = %s\n", shape.name.c_str());
			}

			char objFileName[MAX_PATH_LEN];
			if (strlen(materialPrefixPath) > 0)
			{
				sprintf(objFileName, "%s/part%d.obj", materialPrefixPath, s);
			}
			else
			{
				sprintf(objFileName, "part%d.obj", s);
			}
			FILE* f = fopen(objFileName, "w");
			if (f == 0)
			{
				printf("Fatal error: cannot create part obj file %s\n", objFileName);
				exit(0);
			}
			fprintf(f, "# Exported using automatic converter by Erwin Coumans\n");
			if (matLibName.length())
			{
				fprintf(f, "mtllib %s.mtl\n", matLibName.c_str());
			}
			else
			{
				fprintf(f, "mtllib bedroom.mtl\n");
			}

			int faceCount = shape.mesh.indices.size();
			int vertexCount = attribute.vertices.size();
			tinyobj::material_t mat = shape.material;
			if (shape.name.length())
			{
				const char* objName = shape.name.c_str();
				printf("mat.name = %s\n", objName);
				fprintf(f, "#object %s\n\n", objName);
			}
			for (int v = 0; v < vertexCount / 3; v++)
			{
				fprintf(f, "v %f %f %f\n", attribute.vertices[v * 3 + 0], attribute.vertices[v * 3 + 1], attribute.vertices[v * 3 + 2]);
			}

			if (mat.name.length())
			{
				fprintf(f, "usemtl %s\n", mat.name.c_str());
			}
			else
			{
				fprintf(f, "usemtl wire_028089177\n");
			}

			fprintf(f, "\n");
			int numNormals = int(attribute.normals.size());

			for (int vn = 0; vn < numNormals / 3; vn++)
			{
				fprintf(f, "vn %f %f %f\n", attribute.normals[vn * 3 + 0], attribute.normals[vn * 3 + 1], attribute.normals[vn * 3 + 2]);
			}

			fprintf(f, "\n");
			int numTexCoords = int(attribute.texcoords.size());
			for (int vt = 0; vt < numTexCoords / 2; vt++)
			{
				fprintf(f, "vt %f %f\n", attribute.texcoords[vt * 2 + 0], attribute.texcoords[vt * 2 + 1]);
			}

			fprintf(f, "s off\n");

			for (int face = 0; face < faceCount; face += 3)
			{
				if (face < 0 && face >= int(shape.mesh.indices.size()))
				{
					continue;
				}
				fprintf(f, "f %d/%d/%d %d/%d/%d %d/%d/%d\n",
                                        shape.mesh.indices[face].vertex_index + 1,     shape.mesh.indices[face].texcoord_index + 1,     shape.mesh.indices[face].normal_index + 1,
                                        shape.mesh.indices[face + 1].vertex_index + 1, shape.mesh.indices[face + 1].texcoord_index + 1, shape.mesh.indices[face + 1].normal_index + 1,
                                        shape.mesh.indices[face + 2].vertex_index + 1, shape.mesh.indices[face + 2].texcoord_index + 1, shape.mesh.indices[face + 2].normal_index + 1);
			}
                        fclose(f);

			float kdRed = mat.diffuse[0];
			float kdGreen = mat.diffuse[1];
			float kdBlue = mat.diffuse[2];
			float transparency = mat.transparency;
			char objSdfPartFileName[MAX_PATH_LEN];
			sprintf(objSdfPartFileName, "part%d.obj", s);
			fprintf(sdfFile,
					"\t\t<model name='%s'>\n"
					"\t\t\t<static>1</static>\n"
					"\t\t\t<pose>0 0 0 0 0 0</pose>\n"
					"\t\t\t<link name='link_d%d'>\n"
					"\t\t\t<inertial>\n"
					"\t\t\t<mass>0</mass>\n"
					"\t\t\t<inertia>\n"
					"\t\t\t<ixx>0.166667</ixx>\n"
					"\t\t\t<ixy>0</ixy>\n"
					"\t\t\t<ixz>0</ixz>\n"
					"\t\t\t<iyy>0.166667</iyy>\n"
					"\t\t\t<iyz>0</iyz>\n"
					"\t\t\t<izz>0.166667</izz>\n"
					"\t\t\t</inertia>\n"
					"\t\t\t</inertial>\n"
					"\t\t\t<collision name='collision_%d'>\n"
					"\t\t\t<geometry>\n"
					"\t\t\t<mesh>\n"
					"\t\t\t<scale>1 1 1</scale>\n"
					"\t\t\t\t<uri>%s</uri>\n"
					"\t\t\t</mesh>\n"
					"\t\t\t</geometry>\n"
					"\t\t\t  </collision>\n"
					"\t\t\t<visual name='visual'>\n"
					"\t\t\t\t<geometry>\n"
					"\t\t\t\t<mesh>\n"
					"\t\t\t\t\t<scale>1 1 1</scale>\n"
					"\t\t\t\t\t<uri>%s</uri>\n"
					"\t\t\t\t</mesh>\n"
					"\t\t\t\t</geometry>\n"
					"\t\t\t<material>\n"
					"\t\t\t\t<ambient>1 0 0 1</ambient>\n"
					"\t\t\t\t<diffuse>%f %f %f %f</diffuse>\n"
					"\t\t\t\t<specular>0.1 0.1 0.1 1</specular>\n"
					"\t\t\t\t<emissive>0 0 0 0</emissive>\n"
					"\t\t\t </material>\n"
					"\t\t\t </visual>\n"
					"\t\t\t </link>\n"
					"\t\t\t</model>\n",
					objSdfPartFileName, s, s,
					objSdfPartFileName, objSdfPartFileName,
					kdRed, kdGreen, kdBlue, transparency);
		}
	}
	fprintf(sdfFile, "\t</world>\n</sdf>\n");

	fclose(sdfFile);

	return 0;
}