trait Bound {
def unbind: Unit
}
trait Bind {
protected def bind: Bound
def boundWith( p: =>Unit ) = {
val b = bind
p
b.unbind
}
def &&&(other: Bind) = new Bind {
class CompositeBound( a:Bound, b:Bound ) extends Bound {
def unbind = {
a.unbind
b.unbind
}
}
protected def bind = {
new CompositeBound( Bind.this.bind, other.bind )
}
}
}
And an implementation for those wonderful glEnable/glDisable chains:object GLUnchanged extends Bound{ def unbind = () }
object GLStateUtil {
def glSet( s:Int, v:Boolean ) = if(v) GL11.glEnable(s) else GL11.glDisable(s)
}
case class GLEnabledBound( state:Int, value:Boolean ) extends Bound {
def unbind = GLStateUtil.glSet(state,value)
}
case class GLSetEnabled( state:Int, value:Boolean ) extends Bind {
protected def bind = if( GL11.glIsEnabled(state) == value ) {
GLUnchanged
} else {
GLStateUtil.glSet( state, value )
GLEnabledBound( state, !value )
}
}And finally a stupid example of usage (I'm refactoring a lot of the rendering code, so I don't have a real example to hand right now):
val playerState = GLSetEnabled( GL13.GL_TEXTURE_CUBE_MAP, false ) &&&
GLSetEnabled( GL11.GL_TEXTURE_2D, false ) &&&
GLSetEnabled( GL11.GL_LIGHTING, false )
playerState boundWith {
playerModel.render
}
I suspect there's a better way to handle the Bound class returned such that it's not sat in the open, and the terminology may change quite a bit (bind/unbind came from various C++ implementations of similar stuff, none this nice to use). I quite like the way state changes can be composed, although it doesn't even attempt to perform any optimisation on the combined set.
I think it could also be made less verbose to good effect, and possibly a way to skip the redundant state checks would also be nice in case the state of the GL changes due to things outside the scope of these classes - especially for debugging.
At some point I think I'll combine all the resources into implementations of this class.
Anyway, back to playing with code...