~loic.molinari/+junk/loicm-tools

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
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright © 2012 Loïc Molinari <loic.molinari@canonical.com>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#   * Neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# Converts the first object defined in a Wavefront OBJ mesh definition file to a
# C file with indexed vertex arrays that can be used with an OpenGL function
# such as glDrawElements to render primitives.
#
# Usage: obj2c.py src_obj_file dest_c_file variable_name

# FIXME(loicm) Faces with more than 3 vertices are not supported.
# FIXME(loicm) Compress duplicated attributes.

import sys, math

GL_UNSIGNED_BYTE = 0x1401
GL_UNSIGNED_SHORT = 0x1403
GL_UNSIGNED_INT = 0x1405
GL_FLOAT = 0x1406

gl_type_str = { GL_UNSIGNED_BYTE:  'GL_UNSIGNED_BYTE',
                GL_UNSIGNED_SHORT: 'GL_UNSIGNED_SHORT',
                GL_UNSIGNED_INT:   'GL_UNSIGNED_INT',
                GL_FLOAT:          'GL_FLOAT' }

def gl_type(size):
    if size <= 0xff:
        return GL_UNSIGNED_BYTE
    elif size <= 0xffff:
        return GL_UNSIGNED_SHORT
    else:
        return GL_UNSIGNED_INT

def type_str(size):
    if size <= 0xff:
        return 'unsigned char'
    elif size <= 0xffff:
        return 'unsigned short'
    else:
        return 'unsigned int'

def round_up_16(n):
    return ((n) + 15) & ~15

def main(args):
    # Parse and load arguments.
    if args[0] == '--help' or args[0] == '-help' or args[0] == '-h':
        print 'Usage: obj2c.py src_obj_file dest_c_file variable_name'
        sys.exit(0)
    elif len(args) != 3:
        print 'Usage: obj2c.py src_obj_file dest_c_file variable_name'
        sys.exit(1)
    src_filename = args[0]
    dest_filename = args[1]
    variable_name = args[2]

    vertices = [0]
    normals = [0]
    texcoords = [0]
    faces = []
    dest_vertices = []
    dest_normals = []
    dest_texcoords = []
    nr_faces = 0
    vertices_size = 0
    texcoords_size = 0
    max_v = 0.0
    store_vertex_w = False
    store_texcoord_t = False
    store_texcoord_r = False
    has_p = False
    has_l = False
    has_f = False
    has_ft= False
    current_line = 0

    src_file = open(src_filename, "r")
    dest_file = open(dest_filename, "w")

    # Parse OBJ file.
    lines = src_file.readlines()
    for line in lines:
        current_line += 1
        split_line = line.split()
        if len(split_line) == 0:
            continue
        tag = split_line[0]

        # v defines a vertex coordinate.
        if tag == 'v':
            v = split_line[1:]
            count = len(v)
            if count < 3 or count > 4:
                print 'error: vertex coordinate count at line', current_line, 'is wrong'
                sys.exit(1)
            vertex = [float(v[0]),
                      float(v[1]),
                      float(v[2]),
                      float(v[3]) if count == 4 else 1.0]
            vertices.append(vertex)
            store_vertex_w = vertex[3] != 1.0
            max_v = max(max_v, abs(vertex[0]), abs(vertex[1]), abs(vertex[2]))

        # vt defines a texture coordinate.
        elif tag == 'vt':
            vt = split_line[1:]
            count = len(vt)
            if count < 1 or count > 3:
                print 'error: texture coordinate count at line', current_line, 'is wrong'
                sys.exit(1)
            texcoord = [float(vt[0]),
                        float(vt[1]) if count > 1 else 0.0,
                        float(vt[2]) if count > 2 else 0.0]
            texcoords.append(texcoord)
            store_texcoord_t = texcoord[1] != 0.0
            store_texcoord_r = texcoord[2] != 0.0

        # vn defines a normal.
        elif tag == 'vn':
            vn = split_line[1:]
            count = len(vn)
            if count != 3:
                print 'error: normal count at line', current_line, 'is wrong'
                sys.exit(1)
            normal = [float(vn[0]), float(vn[1]), float(vn[2])]
            normals.append(normal)

        # p defines a face from vertices.
        elif tag == 'p':
            has_p = True
            if has_l or has_f or has_ft:
                print 'error: file with more than one type of face at line', current_line
                sys.exit(1)
            p = split_line[1:]
            if len(p) != 3:
                print 'error: p face with more or less than 3 vertices at line', current_line
                sys.exit(1)
            face = [int(p[0]), int(p[1]), int(p[2])]
            faces.append(face)

        # l defines a face from vertices and texture coordinates.
        elif tag == 'l':
            has_l = True
            if has_p or has_f or has_ft:
                print 'error: file with more than one type of face at line', current_line
                sys.exit(1)
            l = split_line[1:]
            if len(l) != 3:
                print 'error: l face with more or less than 3 vertices at line', current_line
                sys.exit(1)
            l0, l1, l2  = l[0].split('/'), l[1].split('/'), l[2].split('/')
            if len(l0) != 2 or len(l1) != 2 or len(l2) != 2:
                print 'error: l face index with more or less than 2 attribs at line', current_line
                sys.exit(1)
            face = [[int(l0[0]), int(l0[1])],
                    [int(l1[0]), int(l1[1])],
                    [int(l2[0]), int(l2[1])]]
            faces.append(face)

        # f defines a face from vertices, normals and texture coordinates (optional).
        elif tag == 'f':
            f = split_line[1:]
            if len(f) != 3:
                print 'error: f face with more or less than 3 vertices at line', current_line
                sys.exit(1)
            f0, f1, f2  = f[0].split('/'), f[1].split('/'), f[2].split('/')
            if len(f0) != 3 or len(f1) != 3 or len(f2) != 3:
                print 'error: f face index with more or less than 3 attribs at line', current_line
                sys.exit(1)
            if len(f0[1]) != 0:
                has_f = True
                if has_p or has_l or has_ft:
                    print 'error: file with more than one type of face at line', current_line
                    sys.exit(1)
                face = [[int(f0[0]), int(f0[1]), int(f0[2])],
                        [int(f1[0]), int(f1[1]), int(f1[2])],
                        [int(f2[0]), int(f2[1]), int(f2[2])]]
                faces.append(face)
            else:
                has_ft = True
                if has_p or has_l or has_f:
                    print 'error: file with more than one type of face at line', current_line
                    sys.exit(1)
                face = [[int(f0[0]), int(f0[2])],
                        [int(f1[0]), int(f1[2])],
                        [int(f2[0]), int(f2[2])]]
                faces.append(face)

        # Ignored tags.
        elif tag == 'o' or tag == 'g' or tag == 'usemtl':
            # print 'ignored: \'', tag, split_line[1], '\''
            continue

    # Normalize vertex coordinates (scaled to fit in the range [-1, 1] in ).
    vertices_count = len(vertices)
    if vertices_count != 0:
        for i in range(1, vertices_count):
            v = vertices[i]
            inv_max_v = 1.0 / max_v
            # FIXME(loicm) Not sure about scaling and keeping the w coord right.
            vertices[i] = [v[0] * inv_max_v, v[1] * inv_max_v, v[2] * inv_max_v, v[3]]

    # Normalize normals.
    normals_count = len(normals)
    if normals_count != 0:
        for i in range(1, normals_count):
            n = normals[i]
            length = n[0] * n[0] + n[1] * n[1] + n[2] * n[2]
            inv_length = 1.0 / length
            normals[i] = [n[0] * inv_length, n[1] * inv_length, n[2] * inv_length]

    # Store the attributes in the right order.
    if has_p:
        # FIXME(loicm) Add support for the p tag.
        print 'error: the tag p to declare faces is not supported'
        sys.exit(1)
    elif has_l:
        # FIXME(loicm) Add support for the l tag.
        print 'error: the tag l to declare faces is not supported'
        sys.exit(1)
    elif has_f:
        nr_faces = len(faces)
        vertices_size = 4 if store_vertex_w else 3
        texcoords_size = 3 if store_texcoord_r else 2 if store_texcoord_t else 1
        for i in range(nr_faces):
            dest_vertices.append(vertices[faces[i][0][0]][:vertices_size])
            dest_vertices.append(vertices[faces[i][1][0]][:vertices_size])
            dest_vertices.append(vertices[faces[i][2][0]][:vertices_size])
            dest_texcoords.append(texcoords[faces[i][0][1]][:texcoords_size])
            dest_texcoords.append(texcoords[faces[i][1][1]][:texcoords_size])
            dest_texcoords.append(texcoords[faces[i][2][1]][:texcoords_size])
            dest_normals.append(normals[faces[i][0][2]])
            dest_normals.append(normals[faces[i][1][2]])
            dest_normals.append(normals[faces[i][2][2]])
    elif has_ft:
        # FIXME(loicm) Add support for the f without texccords tag.
        print 'error: the tag f without texcoords to declare faces is not supported'
        sys.exit(1)

    # Write destination file using an interleaved array.
    attribute_size = vertices_size * 4 + texcoords_size * 4 + 3 * 4
    stride = round_up_16(attribute_size)
    padding = stride - attribute_size
    count = 3 * nr_faces
    dest_file.write('// This file has been automatically generated by obj2c.py.\n')
    dest_file.write('// <https://code.launchpad.net/~loic.molinari/+junk/loicm-tools>\n\n')
    dest_file.write('static const struct ' + variable_name + '_attribute {\n' +
                    '  float position[' + str(vertices_size) + '];\n' +
                    '  float texcoord[' + str(texcoords_size) + '];\n' +
                    '  float normal[' + str(3) + '];\n' +
                    '  unsigned char padding[' + str(padding) + '];\n' +
                    '} ' + variable_name + '_attributes[' + str(count) +
                    '] __attribute__((aligned(16))) = {\n  ')
    for face in range(nr_faces):
        i = face * 3
        dest_file.write(str(dest_vertices[i+0]).replace('[', '{\n    { ').replace(']', ' },\n'))
        dest_file.write(str(dest_texcoords[i+0]).replace('[', '    { ').replace(']', ' },\n'))
        dest_file.write(str(dest_normals[i+0]).replace('[', '    { ').replace(']', ' },\n  },'))
        dest_file.write(str(dest_vertices[i+1]).replace('[', '{\n    { ').replace(']', ' },\n'))
        dest_file.write(str(dest_texcoords[i+1]).replace('[', '    { ').replace(']', ' },\n'))
        dest_file.write(str(dest_normals[i+1]).replace('[', '    { ').replace(']', ' },\n  },'))
        dest_file.write(str(dest_vertices[i+2]).replace('[', '{\n    { ').replace(']', ' },\n'))
        dest_file.write(str(dest_texcoords[i+2]).replace('[', '    { ').replace(']', ' },\n'))
        dest_file.write(str(dest_normals[i+2]).replace('[', '    { ').replace(']', ' },\n  },'))
    dest_file.seek(-1, 1)
    dest_file.write('\n};\n\n')
    dest_file.write('static const ' + type_str(count) + ' ' + variable_name + '_indices[' +
                    str(count) + '] __attribute__((aligned(16))) = {\n')
    for face in range(nr_faces):
        i = face * 3
        dest_file.write('  ' + str(i+0) + ', ' + str(i+1) + ', ' + str(i+2) + ',\n')
    dest_file.seek(-2, 1)
    dest_file.write('\n};\n\n')
    dest_file.write('static struct {\n' +
                    '  int count;  // Number of vertices.\n' +
                    '  int size;  // Number of attributes.\n' +
                    '  int stride;  // Offset in bytes from one vertex to the other.\n' +
                    '  int vertices_size;  // Number of components per vertex.\n' +
                    '  int texcoords_size;  // Number of components per texcoord.\n' +
                    '  int normals_size;  // Number of component per normals.\n' +
                    '  int vertices_type;  // OpenGL type of the vertex components.\n' +
                    '  int texcoords_type; // OpenGL type of the texcoord components.\n' +
                    '  int normals_type;  // OpenGL type of the normal components.\n' +
                    '  int indices_type;  // OpenGL type of the indices.\n' +
                    '  const struct ' + variable_name + '_attribute* const attributes;' +
                    '  // Pointer to the attributes.\n' +
                    '  const ' + type_str(count) + '* const indices;' +
                    '  // Pointer to the indices.\n' +
                    '} ' + variable_name + ' = {\n' +
                    '  ' + str(count) + ',\n' +
                    '  ' + str(3) + ',\n' +
                    '  ' + str(stride) + ',\n' +
                    '  ' + str(vertices_size) + ',\n' +
                    '  ' + str(texcoords_size) + ',\n' +
                    '  3,\n' +
                    '  ' + hex(GL_FLOAT) + ',  // GL_FLOAT\n' +
                    '  ' + hex(GL_FLOAT) + ',  // GL_FLOAT\n' +
                    '  ' + hex(GL_FLOAT) + ',  // GL_FLOAT\n' +
                    '  ' + hex(gl_type(count)) + ',  // ' + gl_type_str[gl_type(count)] + '\n' +
                    '  ' + variable_name + '_attributes,\n' +
                    '  ' + variable_name + '_indices\n' +
                    '};\n')

    print 'OBJ file converted successfully!'

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))