1/*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "VisualStreamTimingModule.h"
9
10#include "SkCanvas.h"
11
12DEFINE_bool(reset, true, "Reset the GL context between samples.");
13
14VisualStreamTimingModule::VisualStreamTimingModule(VisualBench* owner)
15    : fInitState(kReset_InitState)
16    , fOwner(owner) {
17    fBenchmarkStream.reset(new VisualBenchmarkStream(owner->getSurfaceProps()));
18}
19
20inline void VisualStreamTimingModule::handleInitState(SkCanvas* canvas) {
21    switch (fInitState) {
22        case kNewBenchmark_InitState:
23            fBenchmarkStream->current()->delayedSetup();
24            // fallthrough
25        case kReset_InitState:
26            // This will flicker unfortunately, but as we are reseting the GLContext each bench,
27            // we unfortunately don't have a choice
28            fOwner->clear(canvas, SK_ColorWHITE, 3);
29            fBenchmarkStream->current()->preTimingHooks(canvas);
30            break;
31        case kNone_InitState:
32            break;
33    }
34    fInitState = kNone_InitState;
35}
36
37inline void VisualStreamTimingModule::handleTimingEvent(SkCanvas* canvas,
38                                                        TimingStateMachine::ParentEvents event) {
39    switch (event) {
40        case TimingStateMachine::kTiming_ParentEvents:
41            break;
42        case TimingStateMachine::kTimingFinished_ParentEvents:
43            if (this->timingFinished(fBenchmarkStream->current(), fTSM.loops(),
44                                     fTSM.lastMeasurement())) {
45                fBenchmarkStream->current()->postTimingHooks(canvas);
46                fOwner->reset();
47                fTSM.nextBenchmark();
48                if (!fBenchmarkStream->next()) {
49                    SkDebugf("Exiting VisualBench successfully\n");
50                    fOwner->closeWindow();
51                } else {
52                    fInitState = kNewBenchmark_InitState;
53                }
54                break;
55            }
56            // fallthrough
57        case TimingStateMachine::kReset_ParentEvents:
58            if (FLAGS_reset) {
59                fBenchmarkStream->current()->postTimingHooks(canvas);
60                fOwner->reset();
61                fInitState = kReset_InitState;
62            }
63            break;
64    }
65}
66
67void VisualStreamTimingModule::draw(SkCanvas* canvas) {
68    if (!fBenchmarkStream->current()) {
69        // this should never happen but just to be safe
70        // TODO research why this does happen on mac
71        return;
72    }
73
74    this->handleInitState(canvas);
75    this->renderFrame(canvas, fBenchmarkStream->current(), fTSM.loops());
76    fOwner->present();
77    TimingStateMachine::ParentEvents event = fTSM.nextFrame(FLAGS_reset);
78    this->handleTimingEvent(canvas, event);
79}
80