1 // Copyright (c) 2012 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.
5 #include "base/logging.h"
6 #include "base/numerics/safe_math.h"
7 #include "third_party/mesa/src/include/GL/osmesa.h"
8 #include "ui/gl/gl_bindings.h"
9 #include "ui/gl/gl_context.h"
10 #include "ui/gl/gl_surface_osmesa.h"
11 #include "ui/gl/scoped_make_current.h"
15 GLSurfaceOSMesa::GLSurfaceOSMesa(OSMesaSurfaceFormat format
,
16 const gfx::Size
& size
)
19 case OSMesaSurfaceFormatBGRA
:
20 format_
= OSMESA_BGRA
;
22 case OSMesaSurfaceFormatRGBA
:
23 format_
= OSMESA_RGBA
;
26 // Implementations of OSMesa surface do not support having a 0 size. In such
27 // cases use a (1, 1) surface.
28 if (size_
.GetArea() == 0)
32 bool GLSurfaceOSMesa::Initialize() {
36 void GLSurfaceOSMesa::Destroy() {
40 bool GLSurfaceOSMesa::Resize(const gfx::Size
& new_size
) {
41 scoped_ptr
<ui::ScopedMakeCurrent
> scoped_make_current
;
42 GLContext
* current_context
= GLContext::GetCurrent();
44 current_context
&& current_context
->IsCurrent(this);
46 scoped_make_current
.reset(
47 new ui::ScopedMakeCurrent(current_context
, this));
48 current_context
->ReleaseCurrent(this);
51 // Preserve the old buffer.
52 scoped_ptr
<int32
[]> old_buffer(buffer_
.release());
54 base::CheckedNumeric
<int> checked_size
= sizeof(buffer_
[0]);
55 checked_size
*= new_size
.width();
56 checked_size
*= new_size
.height();
57 if (!checked_size
.IsValid())
60 // Allocate a new one.
61 buffer_
.reset(new int32
[new_size
.GetArea()]);
65 memset(buffer_
.get(), 0, new_size
.GetArea() * sizeof(buffer_
[0]));
67 // Copy the old back buffer into the new buffer.
68 if (old_buffer
.get()) {
69 int copy_width
= std::min(size_
.width(), new_size
.width());
70 int copy_height
= std::min(size_
.height(), new_size
.height());
71 for (int y
= 0; y
< copy_height
; ++y
) {
72 for (int x
= 0; x
< copy_width
; ++x
) {
73 buffer_
[y
* new_size
.width() + x
] = old_buffer
[y
* size_
.width() + x
];
83 bool GLSurfaceOSMesa::IsOffscreen() {
87 gfx::SwapResult
GLSurfaceOSMesa::SwapBuffers() {
88 NOTREACHED() << "Should not call SwapBuffers on an GLSurfaceOSMesa.";
89 return gfx::SwapResult::SWAP_FAILED
;
92 gfx::Size
GLSurfaceOSMesa::GetSize() {
96 void* GLSurfaceOSMesa::GetHandle() {
100 unsigned GLSurfaceOSMesa::GetFormat() {
104 GLSurfaceOSMesa::~GLSurfaceOSMesa() {
108 bool GLSurfaceOSMesaHeadless::IsOffscreen() { return false; }
110 gfx::SwapResult
GLSurfaceOSMesaHeadless::SwapBuffers() {
111 return gfx::SwapResult::SWAP_ACK
;
114 GLSurfaceOSMesaHeadless::GLSurfaceOSMesaHeadless()
115 : GLSurfaceOSMesa(OSMesaSurfaceFormatBGRA
, gfx::Size(1, 1)) {
118 GLSurfaceOSMesaHeadless::~GLSurfaceOSMesaHeadless() { Destroy(); }