Primitive object size in java/scala and 'as<SomePrimitive>Buffer() methods invocation -


my objective generalize shapes creation android opengl es tutorial here: http://developer.android.com/training/graphics/opengl/shapes.html looks right now:

val squarecoords = array( -0.5f,  0.5f, 0.0f,   // top left   -0.5f, -0.5f, 0.0f,   // bottom left   0.5f, -0.5f, 0.0f,   // bottom right   0.5f,  0.5f, 0.0f ) // top right  val vertexbuffer = bytebuffer.allocatedirect(   // (# of coordinate values * 4 bytes per float)   squarecoords.length * 4)   .order(byteorder.nativeorder())   .asfloatbuffer()   .put(squarecoords)   .position(0) 

so, float size hardcoded. have short arrays too:

val draworder = array[short] ( 0, 1, 2, 0, 2, 3 )  val drawlistbuffer = bytebuffer.allocatedirect(   // (# of coordinate values * 2 bytes per short)   draworder.length * 2) .order(byteorder.nativeorder()) .asshortbuffer() drawlistbuffer.put(draworder) drawlistbuffer.position(0) 

code looks similar challenge part choose right method asfloatbuffer()/asshortbuffer() in case , use right primitive value.

i wrote code resolve issue:

import scala.reflect.runtime.universe._  implicit class sbytebuffer[t <: anyval : typetag] (coords: array[t]) {   private val length = coords.length   def buffer(): buffer = {      def allocatebb(mod: int) = {       bytebuffer.allocatedirect(length * mod)       .order(byteorder.nativeorder())     }     val buffer = typeof[t] match {       case t if t =:= typeof[float] => allocatebb(4).asfloatbuffer().put(coords.asinstanceof[array[float]])       case t if t =:= typeof[short] => allocatebb(2).asshortbuffer().put(coords.asinstanceof[array[short]])     }     buffer.position(0)    } }   val squarecoords = array( -0.5f,  0.5f, 0.0f,   // top left   -0.5f, -0.5f, 0.0f,   // bottom left   0.5f, -0.5f, 0.0f,   // bottom right   0.5f,  0.5f, 0.0f ) // top right  val vertexbuffer = squarecoords.buffer() 

but seems complicated , there code repeats. can advice how refactor code more concise , possibly rid of runtime type checks?

you better off creating separate implicit classes each primitive type want support:

abstract class arrayopsbase[t <: anyval] ( val coords: array[t] ) {   protected val length = coords.length   protected def allocatebb(mod: int) = {     bytebuffer.allocatedirect(length * mod)     .order(byteorder.nativeorder())   }   def buffer(): buffer }  implicit class floatarraybufferops( coords: array[float] ) extends arrayopsbase[float]( coords ) {   def buffer = allocatebb(4).asfloatbuffer.put( coords ).position( 0 ) } implicit class shortarraybufferops( coords: array[short] ) extends arrayopsbase[short]( coords ) {   def buffer = allocatebb(2).asshortbuffer.put( coords ).position( 0 ) } 

Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -