GLTexture.m 1.82 KB
Newer Older
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
#import "GLTexture.h"
#import "GLUtils.h"
#import "RCTLog.h"

@implementation GLTexture
{
  GLuint handle; // The identifier of the gl texture
  ImageData* dataCurrentlyUploaded; // The last set data (cache)
}

- (instancetype)init
{
  self = [super init];
  if (self) {
    [self makeTexture];
  }
  return self;
}

- (void)dealloc
{
  glDeleteTextures(1, &handle);
  dataCurrentlyUploaded = nil;
}

- (void) makeTexture
{
  glGenTextures(1, &handle);
  glBindTexture(GL_TEXTURE_2D, handle);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}

- (bool) ensureContext
{
  if (![EAGLContext setCurrentContext:_context]) {
    RCTLogError(@"Failed to set current OpenGL context");
    return false;
  }
  return true;
}

- (int)bind: (int)unit
{
  glActiveTexture(GL_TEXTURE0 + unit);
  glBindTexture(GL_TEXTURE_2D, handle);
  return unit;
}

- (void)setPixels: (ImageData *)data
{
  if (data != dataCurrentlyUploaded) {
    dataCurrentlyUploaded = data;
    glBindTexture(GL_TEXTURE_2D, handle);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, data.width, data.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data.data);
  }
}

- (void)setPixelsEmpty
{
  ImageData* data = genPixelsEmpty(2, 2);
  [self setPixels:data];
}

- (void)setPixelsRandom: (int)width withHeight:(int)height // for testing
{
  ImageData* data = genPixelsRandom(width, height);
  [self setPixels:data];
}

- (void)setPixelsWithImage: (UIImage *)image
{
  ImageData *data = genPixelsWithImage(image);
  if (!data) return;
  [self setPixels:data];
}

- (void)setPixelsWithView: (UIView *)view
{
  ImageData *data = genPixelsWithView(view);
  [self setPixels:data];
}


@end