summaryrefslogtreecommitdiff
path: root/glretrace.py
blob: b6d0f60954ab792b48e765d8ed8b9568a7159c8a (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
##########################################################################
#
# Copyright 2010 VMware, Inc.
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
##########################################################################/


"""GL retracer generator."""


import stdapi
import glapi
from retrace import Retracer


class GlRetracer(Retracer):

    def retrace_function(self, function):
        Retracer.retrace_function(self, function)

    array_pointer_function_names = set((
        "glVertexPointer",
        "glNormalPointer",
        "glColorPointer",
        "glIndexPointer",
        "glTexCoordPointer",
        "glEdgeFlagPointer",
        "glFogCoordPointer",
        "glSecondaryColorPointer",

        "glInterleavedArrays",

        #"glVertexPointerEXT",
        #"glNormalPointerEXT",
        #"glColorPointerEXT",
        #"glIndexPointerEXT",
        #"glTexCoordPointerEXT",
        #"glEdgeFlagPointerEXT",
        #"glFogCoordPointerEXT",
        #"glSecondaryColorPointerEXT",

        "glVertexAttribPointer",
        "glVertexAttribPointerARB",
        "glVertexAttribPointerNV",
        "glVertexAttribLPointer",
        "glVertexAttribLPointerEXT",
        
        #"glMatrixIndexPointerARB",
    ))

    draw_array_function_names = set([
        "glDrawArrays",
        "glDrawArraysEXT",
        "glDrawArraysIndirect",
        "glDrawArraysInstanced",
        "glDrawArraysInstancedARB",
        "glDrawArraysInstancedEXT",
        "glDrawMeshArraysSUN",
        "glMultiDrawArrays",
        "glMultiDrawArraysEXT",
        "glMultiModeDrawArraysIBM",
    ])

    draw_elements_function_names = set([
        "glDrawElements",
        "glDrawElementsBaseVertex",
        "glDrawElementsIndirect",
        "glDrawElementsInstanced",
        "glDrawElementsInstancedARB",
        "glDrawElementsInstancedBaseVertex",
        "glDrawElementsInstancedEXT",
        "glDrawRangeElements",
        "glDrawRangeElementsBaseVertex",
        "glDrawRangeElementsEXT",
        #"glMultiDrawElements",
        #"glMultiDrawElementsBaseVertex",
        #"glMultiDrawElementsEXT",
        #"glMultiModeDrawElementsIBM",
    ])

    def retrace_function_body(self, function):
        is_array_pointer = function.name in self.array_pointer_function_names
        is_draw_array = function.name in self.draw_array_function_names
        is_draw_elements = function.name in self.draw_elements_function_names

        if is_array_pointer or is_draw_array or is_draw_elements:
            print '    if (Trace::Parser::version < 1) {'

            if is_array_pointer or is_draw_array:
                print '        GLint __array_buffer = 0;'
                print '        glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &__array_buffer);'
                print '        if (!__array_buffer) {'
                self.fail_function(function)
                print '        }'

            if is_draw_elements:
                print '        GLint __element_array_buffer = 0;'
                print '        glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &__element_array_buffer);'
                print '        if (!__element_array_buffer) {'
                self.fail_function(function)
                print '        }'
            
            print '    }'

        Retracer.retrace_function_body(self, function)

    def call_function(self, function):
        if function.name == "glViewport":
            print '    if (x + width > __window_width) {'
            print '        __window_width = x + width;'
            print '        __reshape_window = true;'
            print '    }'
            print '    if (y + height > __window_height) {'
            print '        __window_height = y + height;'
            print '        __reshape_window = true;'
            print '    }'

        if function.name == "glEnd":
            print '    insideGlBeginEnd = false;'
        
        Retracer.call_function(self, function)

        if function.name == "glBegin":
            print '    insideGlBeginEnd = true;'
        else:
            # glGetError is not allowed inside glBegin/glEnd
            print '    checkGlError();'

    def extract_arg(self, function, arg, arg_type, lvalue, rvalue):
        if function.name in self.array_pointer_function_names and arg.name == 'pointer':
            print '    %s = %s.blob();' % (lvalue, rvalue)
            return

        if function.name in self.draw_elements_function_names and arg.name == 'indices':
            print '    %s = %s.blob();' % (lvalue, rvalue)
            return

        if function.name.startswith('glUniform') and function.args[0].name == arg.name == 'location':
            print '    GLint program = -1;'
            print '    glGetIntegerv(GL_CURRENT_PROGRAM, &program);'

        Retracer.extract_arg(self, function, arg, arg_type, lvalue, rvalue)


if __name__ == '__main__':
    print r'''
#include <string.h>
#include <stdio.h>
#include <iostream>

#define RETRACE

#include "glproc.hpp"
#include "glstate.hpp"

#include <GL/glut.h>

static bool double_buffer = false;
static bool insideGlBeginEnd = false;

static int __window_width = 256, __window_height = 256;
bool __reshape_window = false;

unsigned __frame = 0;
long long __startTime = 0;
bool __wait = false;

bool __benchmark = false;
const char *__compare_prefix = NULL;
const char *__snapshot_prefix = NULL;

unsigned __dump_state = ~0;


static void
checkGlError(void) {
    if (__benchmark || insideGlBeginEnd) {
        return;
    }

    GLenum error = glGetError();
    if (error == GL_NO_ERROR) {
        return;
    }

    std::cerr << "warning: glGetError() = ";
    switch (error) {
    case GL_INVALID_ENUM:
        std::cerr << "GL_INVALID_ENUM";
        break;
    case GL_INVALID_VALUE:
        std::cerr << "GL_INVALID_VALUE";
        break;
    case GL_INVALID_OPERATION:
        std::cerr << "GL_INVALID_OPERATION";
        break;
    case GL_STACK_OVERFLOW:
        std::cerr << "GL_STACK_OVERFLOW";
        break;
    case GL_STACK_UNDERFLOW:
        std::cerr << "GL_STACK_UNDERFLOW";
        break;
    case GL_OUT_OF_MEMORY:
        std::cerr << "GL_OUT_OF_MEMORY";
        break;
    case GL_INVALID_FRAMEBUFFER_OPERATION:
        std::cerr << "GL_INVALID_FRAMEBUFFER_OPERATION";
        break;
    case GL_TABLE_TOO_LARGE:
        std::cerr << "GL_TABLE_TOO_LARGE";
        break;
    default:
        std::cerr << error;
        break;
    }
    std::cerr << "\n";
}
'''
    api = glapi.glapi
    retracer = GlRetracer()
    retracer.retrace_api(glapi.glapi)
    print r'''

static Trace::Parser parser;

static void display_noop(void) {
}

#include "image.hpp"

static void snapshot(Image::Image &image) {
    GLint drawbuffer = double_buffer ? GL_BACK : GL_FRONT;
    GLint readbuffer = double_buffer ? GL_BACK : GL_FRONT;
    glGetIntegerv(GL_READ_BUFFER, &drawbuffer);
    glGetIntegerv(GL_READ_BUFFER, &readbuffer);
    glReadBuffer(drawbuffer);
    glReadPixels(0, 0, image.width, image.height, GL_RGBA, GL_UNSIGNED_BYTE, image.pixels);
    checkGlError();
    glReadBuffer(readbuffer);
}

static void frame_complete(void) {
    ++__frame;
    
    if (!__reshape_window && (__snapshot_prefix || __compare_prefix)) {
        Image::Image *ref = NULL;
        if (__compare_prefix) {
            char filename[PATH_MAX];
            snprintf(filename, sizeof filename, "%s%04u.png", __compare_prefix, __frame);
            ref = Image::readPNG(filename);
            if (!ref) {
                return;
            }
            if (verbosity >= 0)
                std::cout << "Read " << filename << "\n";
        }
        
        Image::Image src(__window_width, __window_height, true);
        snapshot(src);

        if (__snapshot_prefix) {
            char filename[PATH_MAX];
            snprintf(filename, sizeof filename, "%s%04u.png", __snapshot_prefix, __frame);
            if (src.writePNG(filename) && verbosity >= 0) {
                std::cout << "Wrote " << filename << "\n";
            }
        }

        if (ref) {
            std::cout << "Frame " << __frame << " average precision of " << src.compare(*ref) << " bits\n";
            delete ref;
        }
    }

}

static void display(void) {
    Trace::Call *call;

    while ((call = parser.parse_call())) {
        const std::string &name = call->name();

        if (call->no == __dump_state) {
            state_dump(std::cout);
        }

        if ((name[0] == 'w' && name[1] == 'g' && name[2] == 'l') ||
            (name[0] == 'g' && name[1] == 'l' && name[2] == 'X')) {
            // XXX: We ignore the majority of the OS-specific calls for now
            if (name == "glXSwapBuffers" ||
                name == "wglSwapBuffers") {
                if (verbosity >= 1) {
                    std::cout << *call;
                    std::cout.flush();
                };
                frame_complete();
                if (double_buffer)
                    glutSwapBuffers();
                else
                    glFlush();

                // Return now to allow GLUT to resize the window.
                delete call;
                return;
            } else if (name == "glXMakeCurrent" ||
                       name == "wglMakeCurrent") {
                glFlush();
                if (!double_buffer) {
                    frame_complete();
                    // Return now to allow GLUT to resize window.
                    delete call;
                    return;
                }
            } else {
                continue;
            }
        }

        if (name == "glFlush") {
            glFlush();
            if (!double_buffer) {
                frame_complete();
            }
        }
        
        retrace_call(*call);

        delete call;
    }

    // Reached the end of trace
    glFlush();

    long long endTime = OS::GetTime();
    float timeInterval = (endTime - __startTime) * 1.0E-6;

    if (verbosity >= -1) { 
        std::cout << 
            "Rendered " << __frame << " frames"
            " in " <<  timeInterval << " secs,"
            " average of " << (__frame/timeInterval) << " fps\n";
    }

    if (__wait) {
        glutDisplayFunc(&display_noop);
        glutIdleFunc(NULL);
    } else {
        exit(0);
    }
}

static void idle(void) {
    if (__reshape_window) {
        // XXX: doesn't quite work
        glutReshapeWindow(__window_width, __window_height);
        __reshape_window = false;
    }
    glutPostRedisplay();
}

static void usage(void) {
    std::cout << 
        "Usage: glretrace [OPTION] TRACE\n"
        "Replay TRACE.\n"
        "\n"
        "  -b           benchmark (no glgeterror; no messages)\n"
        "  -c PREFIX    compare against snapshots\n"
        "  -db          use a double buffer visual\n"
        "  -s PREFIX    take snapshots\n"
        "  -v           verbose output\n"
        "  -D CALLNO    dump state at specific call no\n"
        "  -w           wait on final frame\n";
}

int main(int argc, char **argv)
{

    int i;
    for (i = 1; i < argc; ++i) {
        const char *arg = argv[i];

        if (arg[0] != '-') {
            break;
        }

        if (!strcmp(arg, "--")) {
            break;
        } else if (!strcmp(arg, "-b")) {
            __benchmark = true;
            verbosity = -1;
        } else if (!strcmp(arg, "-c")) {
            __compare_prefix = argv[++i];
        } else if (!strcmp(arg, "-D")) {
            __dump_state = atoi(argv[++i]);
            verbosity = -2;
        } else if (!strcmp(arg, "-db")) {
            double_buffer = true;
        } else if (!strcmp(arg, "--help")) {
            usage();
            return 0;
        } else if (!strcmp(arg, "-s")) {
            __snapshot_prefix = argv[++i];
        } else if (!strcmp(arg, "-v")) {
            ++verbosity;
        } else if (!strcmp(arg, "-w")) {
            __wait = true;
        } else {
            std::cerr << "error: unknown option " << arg << "\n";
            usage();
            return 1;
        }
    }

    glutInit(&argc, argv);
    glutInitWindowPosition(0, 0);
    glutInitWindowSize(__window_width, __window_height);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_RGB | (double_buffer ? GLUT_DOUBLE : GLUT_SINGLE));
    glutCreateWindow(argv[0]);

    glutDisplayFunc(&display);
    glutIdleFunc(&idle);

    for (GLuint h = 0; h < 1024; ++h) {
        __list_map[h] = h;
    }

    for ( ; i < argc; ++i) {
        if (parser.open(argv[i])) {
            __startTime = OS::GetTime();
            glutMainLoop();
            parser.close();
        }
    }

    return 0;
}

'''