1cb93a386Sopenharmony_ci/*
2cb93a386Sopenharmony_ci * Copyright 2021 Google Inc.
3cb93a386Sopenharmony_ci *
4cb93a386Sopenharmony_ci * Use of this source code is governed by a BSD-style license that can be
5cb93a386Sopenharmony_ci * found in the LICENSE file.
6cb93a386Sopenharmony_ci */
7cb93a386Sopenharmony_ci
8cb93a386Sopenharmony_ci#include "bench/MSKPBench.h"
9cb93a386Sopenharmony_ci#include "include/core/SkCanvas.h"
10cb93a386Sopenharmony_ci#include "include/gpu/GrDirectContext.h"
11cb93a386Sopenharmony_ci#include "include/gpu/GrRecordingContext.h"
12cb93a386Sopenharmony_ci#include "tools/MSKPPlayer.h"
13cb93a386Sopenharmony_ci
14cb93a386Sopenharmony_ciMSKPBench::MSKPBench(SkString name, std::unique_ptr<MSKPPlayer> player)
15cb93a386Sopenharmony_ci        : fName(name), fPlayer(std::move(player)) {}
16cb93a386Sopenharmony_ci
17cb93a386Sopenharmony_ciMSKPBench::~MSKPBench() = default;
18cb93a386Sopenharmony_ci
19cb93a386Sopenharmony_civoid MSKPBench::onDraw(int loops, SkCanvas* canvas) {
20cb93a386Sopenharmony_ci    for (int i = 0; i < loops; ++i) {
21cb93a386Sopenharmony_ci        for (int f = 0; f < fPlayer->numFrames(); ++f) {
22cb93a386Sopenharmony_ci            canvas->save();
23cb93a386Sopenharmony_ci            canvas->clipIRect(SkIRect::MakeSize(fPlayer->frameDimensions(f)));
24cb93a386Sopenharmony_ci            fPlayer->playFrame(canvas, f);
25cb93a386Sopenharmony_ci            canvas->restore();
26cb93a386Sopenharmony_ci            if (auto dContext = GrAsDirectContext(canvas->recordingContext())) {
27cb93a386Sopenharmony_ci                dContext->flushAndSubmit();
28cb93a386Sopenharmony_ci            }
29cb93a386Sopenharmony_ci        }
30cb93a386Sopenharmony_ci        // Ensure each loop replays all offscreen layer draws from scratch.
31cb93a386Sopenharmony_ci        fPlayer->rewindLayers();
32cb93a386Sopenharmony_ci    }
33cb93a386Sopenharmony_ci}
34cb93a386Sopenharmony_ci
35cb93a386Sopenharmony_ciconst char* MSKPBench::onGetName() { return fName.c_str(); }
36cb93a386Sopenharmony_ci
37cb93a386Sopenharmony_ciSkIPoint MSKPBench::onGetSize() {
38cb93a386Sopenharmony_ci    auto dims = fPlayer->maxDimensions();
39cb93a386Sopenharmony_ci    return {dims.width(), dims.height()};
40cb93a386Sopenharmony_ci}
41cb93a386Sopenharmony_ci
42cb93a386Sopenharmony_civoid MSKPBench::onPreDraw(SkCanvas* canvas) {
43cb93a386Sopenharmony_ci    // We don't benchmark creation of the backing stores for layers so ensure they're all created.
44cb93a386Sopenharmony_ci    fPlayer->allocateLayers(canvas);
45cb93a386Sopenharmony_ci}
46cb93a386Sopenharmony_ci
47cb93a386Sopenharmony_civoid MSKPBench::onPostDraw(SkCanvas*) {
48cb93a386Sopenharmony_ci    // nanobench can tear down the 3D API context/device before destroying the benchmarks.
49cb93a386Sopenharmony_ci    fPlayer->resetLayers();
50cb93a386Sopenharmony_ci}
51