opengl: Add Driver

This commit is contained in:
Hajime Hoshi 2018-11-06 03:56:04 +09:00
parent ed961505d2
commit 07ae1db0dd
13 changed files with 191 additions and 101 deletions

View File

@ -169,7 +169,7 @@ func (q *commandQueue) Flush() {
// Note that the vertices passed to BufferSubData is not under GC management
// in opengl package due to unsafe-way.
// See BufferSubData in context_mobile.go.
opengl.BufferSubData(vs[:nv], es[:ne])
opengl.GetDriver().BufferSubData(vs[:nv], es[:ne])
es = es[ne:]
vs = vs[nv:]
}
@ -189,7 +189,7 @@ func (q *commandQueue) Flush() {
}
if 0 < nc {
// Call glFlush to prevent black flicking (especially on Android (#226) and iOS).
opengl.GetContext().Flush()
opengl.GetDriver().Flush()
}
q.commands = q.commands[nc:]
}
@ -234,10 +234,10 @@ func (c *drawImageCommand) Exec(indexOffsetInBytes int) error {
c.dst.image.SetAsDestination()
c.src.image.SetAsSource()
if err := opengl.UseProgram(c.mode, c.color, c.filter); err != nil {
if err := opengl.GetDriver().UseProgram(c.mode, c.color, c.filter); err != nil {
return err
}
opengl.GetContext().DrawElements(c.nindices, indexOffsetInBytes)
opengl.GetDriver().DrawElements(c.nindices, indexOffsetInBytes)
// glFlush() might be necessary at least on MacBook Pro (a smilar problem at #419),
// but basically this pass the tests (esp. TestImageTooManyFill).
@ -301,7 +301,7 @@ func (c *replacePixelsCommand) String() string {
func (c *replacePixelsCommand) Exec(indexOffsetInBytes int) error {
// glFlush is necessary on Android.
// glTexSubImage2D didn't work without this hack at least on Nexus 5x and NuAns NEO [Reloaded] (#211).
opengl.GetContext().Flush()
opengl.GetDriver().Flush()
c.dst.image.TexSubImage2D(c.pixels, c.x, c.y, c.width, c.height)
return nil
}
@ -407,7 +407,7 @@ func (c *newImageCommand) String() string {
// Exec executes a newImageCommand.
func (c *newImageCommand) Exec(indexOffsetInBytes int) error {
i, err := opengl.NewImage(c.width, c.height)
i, err := opengl.GetDriver().NewImage(c.width, c.height)
if err != nil {
return err
}
@ -446,7 +446,7 @@ func (c *newScreenFramebufferImageCommand) String() string {
// Exec executes a newScreenFramebufferImageCommand.
func (c *newScreenFramebufferImageCommand) Exec(indexOffsetInBytes int) error {
c.result.image = opengl.NewScreenFramebufferImage(c.width, c.height)
c.result.image = opengl.GetDriver().NewScreenFramebufferImage(c.width, c.height)
return nil
}
@ -470,5 +470,5 @@ func (c *newScreenFramebufferImageCommand) CanMerge(dst, src *Image, color *affi
// ResetGraphicsDriverState resets or initializes the current graphics driver state.
func ResetGraphicsDriverState() error {
return opengl.Reset()
return opengl.GetDriver().Reset()
}

View File

@ -30,7 +30,7 @@ var (
// MaxImageSize returns the maximum of width/height of an image.
func MaxImageSize() int {
if maxTextureSize == 0 {
maxTextureSize = opengl.GetContext().MaxTextureSize()
maxTextureSize = opengl.GetDriver().MaxTextureSize()
if maxTextureSize == 0 {
panic("graphics: failed to get the max texture size")
}

View File

@ -55,6 +55,7 @@ func convertOperation(op graphics.Operation) operation {
}
}
// TODO: Unexport this
type Context struct {
locationCache *locationCache
screenFramebuffer framebufferNative // This might not be the default frame buffer '0' (e.g. iOS).
@ -69,10 +70,6 @@ type Context struct {
var theContext Context
func GetContext() *Context {
return &theContext
}
func (c *Context) bindTexture(t textureNative) {
if c.lastTexture == t {
return
@ -110,7 +107,7 @@ func (c *Context) getScreenFramebuffer() framebufferNative {
return c.screenFramebuffer
}
func (c *Context) MaxTextureSize() int {
func (c *Context) getMaxTextureSize() int {
if c.maxTextureSize == 0 {
c.maxTextureSize = c.maxTextureSizeImpl()
}

View File

@ -487,7 +487,7 @@ func (c *Context) deleteBuffer(b buffer) {
})
}
func (c *Context) DrawElements(len int, offsetInBytes int) {
func (c *Context) drawElements(len int, offsetInBytes int) {
_ = mainthread.Run(func() error {
gl.DrawElements(gl.TRIANGLES, int32(len), gl.UNSIGNED_SHORT, gl.PtrOffset(offsetInBytes))
return nil
@ -505,7 +505,7 @@ func (c *Context) maxTextureSizeImpl() int {
return size
}
func (c *Context) Flush() {
func (c *Context) flush() {
_ = mainthread.Run(func() error {
gl.Flush()
return nil

View File

@ -477,7 +477,7 @@ func (c *Context) deleteBuffer(b buffer) {
gl.Call("deleteBuffer", js.Value(b))
}
func (c *Context) DrawElements(len int, offsetInBytes int) {
func (c *Context) drawElements(len int, offsetInBytes int) {
c.ensureGL()
gl := c.gl
gl.Call("drawElements", triangles, len, unsignedShort, offsetInBytes)
@ -489,19 +489,19 @@ func (c *Context) maxTextureSizeImpl() int {
return gl.Call("getParameter", maxTextureSize).Int()
}
func (c *Context) Flush() {
func (c *Context) flush() {
c.ensureGL()
gl := c.gl
gl.Call("flush")
}
func (c *Context) IsContextLost() bool {
func (c *Context) isContextLost() bool {
c.ensureGL()
gl := c.gl
return gl.Call("isContextLost").Bool()
}
func (c *Context) RestoreContext() {
func (c *Context) restoreContext() {
if c.loseContext != js.Null() {
c.loseContext.Call("restoreContext")
}

View File

@ -83,7 +83,7 @@ func InitWithContext(context mgl.Context) {
theContext.gl = context
}
func (c *Context) DoWork(chError <-chan error, chDone <-chan struct{}) error {
func (c *Context) doWork(chError <-chan error, chDone <-chan struct{}) error {
if c.worker == nil {
panic("not reached")
}
@ -386,7 +386,7 @@ func (c *Context) deleteBuffer(b buffer) {
gl.DeleteBuffer(mgl.Buffer(b))
}
func (c *Context) DrawElements(len int, offsetInBytes int) {
func (c *Context) drawElements(len int, offsetInBytes int) {
gl := c.gl
gl.DrawElements(mgl.TRIANGLES, len, mgl.UNSIGNED_SHORT, offsetInBytes)
}
@ -396,7 +396,7 @@ func (c *Context) maxTextureSizeImpl() int {
return gl.GetInteger(mgl.MAX_TEXTURE_SIZE)
}
func (c *Context) Flush() {
func (c *Context) flush() {
gl := c.gl
gl.Flush()
}

84
internal/opengl/driver.go Normal file
View File

@ -0,0 +1,84 @@
// Copyright 2018 The Ebiten Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package opengl
import (
"github.com/hajimehoshi/ebiten/internal/affine"
"github.com/hajimehoshi/ebiten/internal/graphics"
"github.com/hajimehoshi/ebiten/internal/math"
)
var theDriver Driver
func GetDriver() *Driver {
return &theDriver
}
type Driver struct {
}
func (d *Driver) NewImage(width, height int) (*Image, error) {
i := &Image{
width: width,
height: height,
}
w := math.NextPowerOf2Int(width)
h := math.NextPowerOf2Int(height)
checkSize(w, h)
t, err := theContext.newTexture(w, h)
if err != nil {
return nil, err
}
i.textureNative = t
return i, nil
}
func (d *Driver) NewScreenFramebufferImage(width, height int) *Image {
checkSize(width, height)
i := &Image{
width: width,
height: height,
}
// The (default) framebuffer size can't be converted to a power of 2.
// On browsers, c.width and c.height are used as viewport size and
// Edge can't treat a bigger viewport than the drawing area (#71).
i.framebuffer = newScreenFramebuffer(width, height)
return i
}
// Reset resets or initializes the current OpenGL state.
func (d *Driver) Reset() error {
return theOpenGLState.reset()
}
func (d *Driver) BufferSubData(vertices []float32, indices []uint16) {
bufferSubData(vertices, indices)
}
func (d *Driver) UseProgram(mode graphics.CompositeMode, colorM *affine.ColorM, filter graphics.Filter) error {
return useProgram(mode, colorM, filter)
}
func (d *Driver) DrawElements(len int, offsetInBytes int) {
theContext.drawElements(len, offsetInBytes)
}
func (d *Driver) Flush() {
theContext.flush()
}
func (d *Driver) MaxTextureSize() int {
return theContext.getMaxTextureSize()
}

View File

@ -0,0 +1,25 @@
// Copyright 2018 The Ebiten Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build js
package opengl
func (d *Driver) IsContextLost() bool {
return theContext.isContextLost()
}
func (d *Driver) RestoreContext() {
theContext.restoreContext()
}

View File

@ -0,0 +1,21 @@
// Copyright 2018 The Ebiten Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build android ios
package opengl
func (d *Driver) DoWork(chError <-chan error, chDone <-chan struct{}) error {
return theContext.doWork(chError, chDone)
}

View File

@ -27,7 +27,7 @@ func checkSize(width, height int) {
if height < 1 {
panic(fmt.Sprintf("opengl: height (%d) must be equal or more than 1.", height))
}
m := theContext.MaxTextureSize()
m := theContext.getMaxTextureSize()
if width > m {
panic(fmt.Sprintf("opengl: width (%d) must be less than or equal to %d", width, m))
}
@ -43,35 +43,6 @@ type Image struct {
height int
}
func NewImage(width, height int) (*Image, error) {
i := &Image{
width: width,
height: height,
}
w := math.NextPowerOf2Int(width)
h := math.NextPowerOf2Int(height)
checkSize(w, h)
t, err := theContext.newTexture(w, h)
if err != nil {
return nil, err
}
i.textureNative = t
return i, nil
}
func NewScreenFramebufferImage(width, height int) *Image {
checkSize(width, height)
i := &Image{
width: width,
height: height,
}
// The (default) framebuffer size can't be converted to a power of 2.
// On browsers, c.width and c.height are used as viewport size and
// Edge can't treat a bigger viewport than the drawing area (#71).
i.framebuffer = newScreenFramebuffer(width, height)
return i
}
func (i *Image) IsInvalidated() bool {
return !theContext.isTexture(i.textureNative)
}

View File

@ -54,18 +54,18 @@ func (a *arrayBufferLayout) totalBytes() int {
// newArrayBuffer creates OpenGL's buffer object for the array buffer.
func (a *arrayBufferLayout) newArrayBuffer() buffer {
return GetContext().newArrayBuffer(a.totalBytes() * IndicesNum)
return theContext.newArrayBuffer(a.totalBytes() * IndicesNum)
}
// enable binds the array buffer the given program to use the array buffer.
func (a *arrayBufferLayout) enable(program program) {
for _, p := range a.parts {
GetContext().enableVertexAttribArray(program, p.name)
theContext.enableVertexAttribArray(program, p.name)
}
total := a.totalBytes()
offset := 0
for _, p := range a.parts {
GetContext().vertexAttribPointer(program, p.name, p.num, float, total, offset)
theContext.vertexAttribPointer(program, p.name, p.num, float, total, offset)
offset += float.SizeInBytes() * p.num
}
}
@ -74,7 +74,7 @@ func (a *arrayBufferLayout) enable(program program) {
func (a *arrayBufferLayout) disable(program program) {
// TODO: Disabling should be done in reversed order?
for _, p := range a.parts {
GetContext().disableVertexAttribArray(program, p.name)
theContext.disableVertexAttribArray(program, p.name)
}
}
@ -149,14 +149,9 @@ const (
maxQuads = maxTriangles / 2
)
// Reset resets or initializes the current OpenGL state.
func Reset() error {
return theOpenGLState.reset()
}
// reset resets or initializes the OpenGL state.
func (s *openGLState) reset() error {
if err := GetContext().reset(); err != nil {
if err := theContext.reset(); err != nil {
return err
}
@ -171,51 +166,51 @@ func (s *openGLState) reset() error {
// However, it is not assumed that reset is called only when context lost happens.
// Let's delete them explicitly.
if s.programNearest != zeroProgram {
GetContext().deleteProgram(s.programNearest)
theContext.deleteProgram(s.programNearest)
}
if s.programLinear != zeroProgram {
GetContext().deleteProgram(s.programLinear)
theContext.deleteProgram(s.programLinear)
}
if s.programScreen != zeroProgram {
GetContext().deleteProgram(s.programScreen)
theContext.deleteProgram(s.programScreen)
}
// On browsers (at least Chrome), buffers are already detached from the context
// and must not be deleted by DeleteBuffer.
if !web.IsBrowser() {
if s.arrayBuffer != zeroBuffer {
GetContext().deleteBuffer(s.arrayBuffer)
theContext.deleteBuffer(s.arrayBuffer)
}
if s.elementArrayBuffer != zeroBuffer {
GetContext().deleteBuffer(s.elementArrayBuffer)
theContext.deleteBuffer(s.elementArrayBuffer)
}
}
shaderVertexModelviewNative, err := GetContext().newShader(vertexShader, shaderStr(shaderVertexModelview))
shaderVertexModelviewNative, err := theContext.newShader(vertexShader, shaderStr(shaderVertexModelview))
if err != nil {
panic(fmt.Sprintf("graphics: shader compiling error:\n%s", err))
}
defer GetContext().deleteShader(shaderVertexModelviewNative)
defer theContext.deleteShader(shaderVertexModelviewNative)
shaderFragmentNearestNative, err := GetContext().newShader(fragmentShader, shaderStr(shaderFragmentNearest))
shaderFragmentNearestNative, err := theContext.newShader(fragmentShader, shaderStr(shaderFragmentNearest))
if err != nil {
panic(fmt.Sprintf("graphics: shader compiling error:\n%s", err))
}
defer GetContext().deleteShader(shaderFragmentNearestNative)
defer theContext.deleteShader(shaderFragmentNearestNative)
shaderFragmentLinearNative, err := GetContext().newShader(fragmentShader, shaderStr(shaderFragmentLinear))
shaderFragmentLinearNative, err := theContext.newShader(fragmentShader, shaderStr(shaderFragmentLinear))
if err != nil {
panic(fmt.Sprintf("graphics: shader compiling error:\n%s", err))
}
defer GetContext().deleteShader(shaderFragmentLinearNative)
defer theContext.deleteShader(shaderFragmentLinearNative)
shaderFragmentScreenNative, err := GetContext().newShader(fragmentShader, shaderStr(shaderFragmentScreen))
shaderFragmentScreenNative, err := theContext.newShader(fragmentShader, shaderStr(shaderFragmentScreen))
if err != nil {
panic(fmt.Sprintf("graphics: shader compiling error:\n%s", err))
}
defer GetContext().deleteShader(shaderFragmentScreenNative)
defer theContext.deleteShader(shaderFragmentScreenNative)
s.programNearest, err = GetContext().newProgram([]shader{
s.programNearest, err = theContext.newProgram([]shader{
shaderVertexModelviewNative,
shaderFragmentNearestNative,
})
@ -223,7 +218,7 @@ func (s *openGLState) reset() error {
return err
}
s.programLinear, err = GetContext().newProgram([]shader{
s.programLinear, err = theContext.newProgram([]shader{
shaderVertexModelviewNative,
shaderFragmentLinearNative,
})
@ -231,7 +226,7 @@ func (s *openGLState) reset() error {
return err
}
s.programScreen, err = GetContext().newProgram([]shader{
s.programScreen, err = theContext.newProgram([]shader{
shaderVertexModelviewNative,
shaderFragmentScreenNative,
})
@ -244,7 +239,7 @@ func (s *openGLState) reset() error {
// Note that the indices passed to NewElementArrayBuffer is not under GC management
// in opengl package due to unsafe-way.
// See NewElementArrayBuffer in context_mobile.go.
s.elementArrayBuffer = GetContext().newElementArrayBuffer(IndicesNum * 2)
s.elementArrayBuffer = theContext.newElementArrayBuffer(IndicesNum * 2)
return nil
}
@ -262,13 +257,12 @@ func areSameFloat32Array(a, b []float32) bool {
return true
}
func BufferSubData(vertices []float32, indices []uint16) {
c := GetContext()
c.arrayBufferSubData(vertices)
c.elementArrayBufferSubData(indices)
func bufferSubData(vertices []float32, indices []uint16) {
theContext.arrayBufferSubData(vertices)
theContext.elementArrayBufferSubData(indices)
}
func UseProgram(mode graphics.CompositeMode, colorM *affine.ColorM, filter graphics.Filter) error {
func useProgram(mode graphics.CompositeMode, colorM *affine.ColorM, filter graphics.Filter) error {
destination := theOpenGLState.destination
if destination == nil {
panic("destination image is not set")
@ -288,7 +282,7 @@ func UseProgram(mode graphics.CompositeMode, colorM *affine.ColorM, filter graph
dw, dh := destination.width, destination.height
sw, sh := source.width, source.height
GetContext().blendFunc(mode)
theContext.blendFunc(mode)
theOpenGLState.useProgram(proj, dw, dh, sw, sh, colorM, filter)
theOpenGLState.source = nil
@ -298,8 +292,6 @@ func UseProgram(mode graphics.CompositeMode, colorM *affine.ColorM, filter graph
// useProgram uses the program (programTexture).
func (s *openGLState) useProgram(proj []float32, dstW, dstH, srcW, srcH int, colorM *affine.ColorM, filter graphics.Filter) {
c := GetContext()
texture := theOpenGLState.source.textureNative
var program program
@ -315,16 +307,16 @@ func (s *openGLState) useProgram(proj []float32, dstW, dstH, srcW, srcH int, col
}
if s.lastProgram != program {
c.useProgram(program)
theContext.useProgram(program)
if s.lastProgram != zeroProgram {
theArrayBufferLayout.disable(s.lastProgram)
}
theArrayBufferLayout.enable(program)
if s.lastProgram == zeroProgram {
c.bindBuffer(arrayBuffer, s.arrayBuffer)
c.bindBuffer(elementArrayBuffer, s.elementArrayBuffer)
c.uniformInt(program, "texture", 0)
theContext.bindBuffer(arrayBuffer, s.arrayBuffer)
theContext.bindBuffer(elementArrayBuffer, s.elementArrayBuffer)
theContext.uniformInt(program, "texture", 0)
}
s.lastProgram = program
@ -336,7 +328,7 @@ func (s *openGLState) useProgram(proj []float32, dstW, dstH, srcW, srcH int, col
}
if !areSameFloat32Array(s.lastProjectionMatrix, proj) {
c.uniformFloats(program, "projection_matrix", proj)
theContext.uniformFloats(program, "projection_matrix", proj)
if s.lastProjectionMatrix == nil {
s.lastProjectionMatrix = make([]float32, 16)
}
@ -348,7 +340,7 @@ func (s *openGLState) useProgram(proj []float32, dstW, dstH, srcW, srcH int, col
esBody, esTranslate := colorM.UnsafeElements()
if !areSameFloat32Array(s.lastColorMatrix, esBody) {
c.uniformFloats(program, "color_matrix_body", esBody)
theContext.uniformFloats(program, "color_matrix_body", esBody)
if s.lastColorMatrix == nil {
s.lastColorMatrix = make([]float32, 16)
}
@ -356,7 +348,7 @@ func (s *openGLState) useProgram(proj []float32, dstW, dstH, srcW, srcH int, col
s.lastColorMatrix = esBody
}
if !areSameFloat32Array(s.lastColorMatrixTranslation, esTranslate) {
c.uniformFloats(program, "color_matrix_translation", esTranslate)
theContext.uniformFloats(program, "color_matrix_translation", esTranslate)
if s.lastColorMatrixTranslation == nil {
s.lastColorMatrixTranslation = make([]float32, 4)
}
@ -368,17 +360,17 @@ func (s *openGLState) useProgram(proj []float32, dstW, dstH, srcW, srcH int, col
sh := emath.NextPowerOf2Int(srcH)
if s.lastSourceWidth != sw || s.lastSourceHeight != sh {
c.uniformFloats(program, "source_size", []float32{float32(sw), float32(sh)})
theContext.uniformFloats(program, "source_size", []float32{float32(sw), float32(sh)})
s.lastSourceWidth = sw
s.lastSourceHeight = sh
}
if program == s.programScreen {
scale := float32(dstW) / float32(srcW)
c.uniformFloat(program, "scale", scale)
theContext.uniformFloat(program, "scale", scale)
}
// We don't have to call gl.ActiveTexture here: GL_TEXTURE0 is the default active texture
// See also: https://www.opengl.org/sdk/docs/man2/xhtml/glActiveTexture.xml
c.bindTexture(texture)
theContext.bindTexture(texture)
}

View File

@ -206,8 +206,8 @@ func (u *userInterface) update(g GraphicsContext) error {
}
hooks.ResumeAudio()
if opengl.GetContext().IsContextLost() {
opengl.GetContext().RestoreContext()
if opengl.GetDriver().IsContextLost() {
opengl.GetDriver().RestoreContext()
g.Invalidate()
// Need to return once to wait restored (#526)

View File

@ -53,7 +53,7 @@ func Render(chError <-chan error) error {
// TODO: Check this is called on the rendering thread
select {
case renderCh <- struct{}{}:
return opengl.GetContext().DoWork(chError, renderChEnd)
return opengl.GetDriver().DoWork(chError, renderChEnd)
case <-time.After(500 * time.Millisecond):
// This function must not be blocked. We need to break for timeout.
return nil