1 // Copyright 2018 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "chrome/browser/vr/base_graphics_delegate.h"
6 
7 #include <utility>
8 
9 #include "base/callback_helpers.h"
10 #include "base/logging.h"
11 #include "base/trace_event/trace_event.h"
12 #include "ui/gl/gl_context.h"
13 #include "ui/gl/gl_share_group.h"
14 #include "ui/gl/gl_surface.h"
15 #include "ui/gl/init/gl_factory.h"
16 
17 namespace vr {
18 
BaseGraphicsDelegate()19 BaseGraphicsDelegate::BaseGraphicsDelegate() {}
20 
~BaseGraphicsDelegate()21 BaseGraphicsDelegate::~BaseGraphicsDelegate() {
22   if (curr_context_id_ != kNone)
23     contexts_[curr_context_id_]->ReleaseCurrent(surface_.get());
24 }
25 
Initialize(const scoped_refptr<gl::GLSurface> & surface)26 bool BaseGraphicsDelegate::Initialize(
27     const scoped_refptr<gl::GLSurface>& surface) {
28   surface_ = surface;
29   share_group_ = base::MakeRefCounted<gl::GLShareGroup>();
30   for (auto& context : contexts_) {
31     context = gl::init::CreateGLContext(share_group_.get(), surface_.get(),
32                                         gl::GLContextAttribs());
33     if (!context.get()) {
34       LOG(ERROR) << "gl::init::CreateGLContext failed";
35       return false;
36     }
37   }
38   return MakeContextCurrent(kMainContext);
39 }
40 
RunInSkiaContext(base::OnceClosure callback)41 bool BaseGraphicsDelegate::RunInSkiaContext(base::OnceClosure callback) {
42   DCHECK_EQ(curr_context_id_, kMainContext);
43   if (!MakeContextCurrent(kSkiaContext))
44     return false;
45   std::move(callback).Run();
46   return MakeContextCurrent(kMainContext);
47 }
48 
SwapSurfaceBuffers()49 void BaseGraphicsDelegate::SwapSurfaceBuffers() {
50   TRACE_EVENT0("gpu", __func__);
51   DCHECK(surface_);
52   surface_->SwapBuffers(base::DoNothing());
53 }
54 
MakeContextCurrent(ContextId context_id)55 bool BaseGraphicsDelegate::MakeContextCurrent(ContextId context_id) {
56   DCHECK(context_id > kNone && context_id < kNumContexts);
57   if (curr_context_id_ == context_id)
58     return true;
59   auto& context = contexts_[context_id];
60   if (!context->MakeCurrent(surface_.get())) {
61     LOG(ERROR) << "gl::GLContext::MakeCurrent() failed";
62     return false;
63   }
64   curr_context_id_ = context_id;
65   return true;
66 }
67 
68 }  // namespace vr
69