1//
2// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6
7// debug.cpp: Debugging utilities.
8
9#include "common/debug.h"
10#include "common/system.h"
11#include <d3d9.h>
12
13namespace gl
14{
15
16typedef void (WINAPI *PerfOutputFunction)(D3DCOLOR, LPCWSTR);
17
18static void output(bool traceFileDebugOnly, PerfOutputFunction perfFunc, const char *format, va_list vararg)
19{
20#if !defined(ANGLE_DISABLE_PERF)
21    if (perfActive())
22    {
23        char message[32768];
24        int len = vsprintf_s(message, format, vararg);
25        if (len < 0)
26        {
27            return;
28        }
29
30        // There are no ASCII variants of these D3DPERF functions.
31        wchar_t wideMessage[32768];
32        for (int i = 0; i < len; ++i)
33        {
34            wideMessage[i] = message[i];
35        }
36        wideMessage[len] = 0;
37
38        perfFunc(0, wideMessage);
39    }
40#endif
41
42#if !defined(ANGLE_DISABLE_TRACE)
43#if defined(NDEBUG)
44    if (traceFileDebugOnly)
45    {
46        return;
47    }
48#endif
49
50    FILE* file = fopen(TRACE_OUTPUT_FILE, "a");
51    if (file)
52    {
53        vfprintf(file, format, vararg);
54        fclose(file);
55    }
56#endif
57}
58
59void trace(bool traceFileDebugOnly, const char *format, ...)
60{
61    va_list vararg;
62    va_start(vararg, format);
63#if defined(ANGLE_DISABLE_PERF)
64    output(traceFileDebugOnly, NULL, format, vararg);
65#else
66    output(traceFileDebugOnly, D3DPERF_SetMarker, format, vararg);
67#endif
68    va_end(vararg);
69}
70
71bool perfActive()
72{
73#if defined(ANGLE_DISABLE_PERF)
74    return false;
75#else
76    static bool active = D3DPERF_GetStatus() != 0;
77    return active;
78#endif
79}
80
81ScopedPerfEventHelper::ScopedPerfEventHelper(const char* format, ...)
82{
83#if !defined(ANGLE_DISABLE_PERF)
84#if defined(ANGLE_DISABLE_TRACE)
85    if (!perfActive())
86    {
87        return;
88    }
89#endif
90    va_list vararg;
91    va_start(vararg, format);
92    output(true, reinterpret_cast<PerfOutputFunction>(D3DPERF_BeginEvent), format, vararg);
93    va_end(vararg);
94#endif
95}
96
97ScopedPerfEventHelper::~ScopedPerfEventHelper()
98{
99#if !defined(ANGLE_DISABLE_PERF)
100    if (perfActive())
101    {
102        D3DPERF_EndEvent();
103    }
104#endif
105}
106}
107