import Kernel from '../Kernel' ; import Material from './Material' ; import ImageUtils from '../Image' ; type ImageType = HTMLImageElement | string ; export default class MeshTextureMaterial extends Material { texture : WebGLTexture ; image : HTMLImageElement ; private ready : boolean = false ; private deleted : boolean = false ; constructor ( imageOrUrl = null , public flipY = false ) { super ( ) ; this . texture = Kernel . gl . createTexture ( ) ; if ( imageOrUrl ) { this . setImageOrUrl ( imageOrUrl ) ; } } isReady ( ) { return this . ready && ! this . deleted ; } setImageOrUrl ( imageOrUrl ? ) { if ( ! imageOrUrl ) { return ; } if ( imageOrUrl instanceof Image && imageOrUrl . width > 0 && imageOrUrl . height > 0 ) { this . setImage ( imageOrUrl ) ; } else if ( typeof imageOrUrl === "string" ) { this . setImageUrl ( imageOrUrl ) ; } } setImage ( image ) { if ( image . width > 0 && image . height > 0 ) { this . ready = false ; this . image = image ; this . onLoad ( ) ; } } setImageUrl ( url ) { var tileImage = ImageUtils . get ( url ) ; if ( tileImage ) { this . setImage ( tileImage ) ; } else { this . ready = false ; this . image = new Image ( ) ; this . image . crossOrigin = 'anonymous' ; this . image . onload = this . onLoad . bind ( this ) ; this . image . src = url ; } } protected onLoad ( ) { if ( this . deleted ) { return ; } var gl = Kernel . gl ; gl . bindTexture ( gl . TEXTURE_2D , this . texture ) ; if ( this . flipY ) { gl . pixelStorei ( gl . UNPACK_FLIP_Y_WEBGL , + true ) ; } else { gl . pixelStorei ( gl . UNPACK_FLIP_Y_WEBGL , + false ) ; } gl . texImage2D ( gl . TEXTURE_2D , 0 , gl . RGBA , gl . RGBA , gl . UNSIGNED_BYTE , this . image ) ; gl . texParameteri ( gl . TEXTURE_2D , gl . TEXTURE_MIN_FILTER , gl . LINEAR ) ; gl . texParameteri ( gl . TEXTURE_2D , gl . TEXTURE_MAG_FILTER , gl . LINEAR ) ; gl . texParameteri ( gl . TEXTURE_2D , gl . TEXTURE_WRAP_S , gl . CLAMP_TO_EDGE ) ; gl . texParameteri ( gl . TEXTURE_2D , gl . TEXTURE_WRAP_T , gl . CLAMP_TO_EDGE ) ; this . ready = true ; } destroy ( ) { var gl = Kernel . gl ; if ( this . texture ) { gl . deleteTexture ( this . texture ) ; } if ( this . image && ! this . ready ) { this . image . src = "" ; } this . ready = false ; this . texture = null ; this . deleted = true ; } } ;