GLCanvas.m 12 KB
Newer Older
1 2 3 4

#import "RCTBridge.h"
#import "RCTUtils.h"
#import "RCTConvert.h"
5
#import "RCTEventDispatcher.h"
6 7 8 9 10 11 12
#import "RCTLog.h"
#import "GLCanvas.h"
#import "GLShader.h"
#import "GLShadersRegistry.h"
#import "GLTexture.h"
#import "GLImage.h"
#import "GLRenderData.h"
13
#import "UIView+React.h"
14

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28

NSString* srcResource (id res)
{
  NSString *src;
  if ([res isKindOfClass:[NSString class]]) {
    src = [RCTConvert NSString:res];
  } else {
    BOOL isStatic = [RCTConvert BOOL:res[@"isStatic"]];
    src = [RCTConvert NSString:res[@"path"]];
    if (!src || isStatic) src = [RCTConvert NSString:res[@"uri"]];
  }
  return src;
}

29 30 31 32 33
// For reference, see implementation of gl-shader's GLCanvas

@implementation GLCanvas
{
  RCTBridge *_bridge; // bridge is required to instanciate GLReactImage
34
  
35 36
  GLRenderData *_renderData;
  
37
  NSArray *_contentTextures;
38 39 40 41
  NSDictionary *_images; // This caches the currently used images (imageSrc -> GLReactImage)
  
  BOOL _opaque; // opaque prop (if false, the GLCanvas will become transparent)
  
42
  BOOL _deferredRendering; // This flag indicates a render has been deferred to the next frame (when using contents)
43 44
  
  GLint defaultFBO;
45 46 47
  
  NSMutableArray *_preloaded;
  BOOL _preloadingDone;
48 49
  
  NSTimer *animationTimer;
50 51 52
}

- (instancetype)initWithBridge:(RCTBridge *)bridge
53
                   withContext:(EAGLContext *)context
54 55 56 57
{
  if ((self = [super init])) {
    _bridge = bridge;
    _images = @{};
58 59
    _preloaded = [[NSMutableArray alloc] init];
    _preloadingDone = false;
60
    self.context = context;
61
    self.contentScaleFactor = RCTScreenScale();
62 63 64 65 66 67
  }
  return self;
}

RCT_NOT_IMPLEMENTED(-init)

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
68 69
//// Props Setters

70 71 72 73
-(void)setImagesToPreload:(NSArray *)imagesToPreload
{
  if (_preloadingDone) return;
  if ([imagesToPreload count] == 0) {
74
    [self dispatchOnLoad];
75 76
    _preloadingDone = true;
  }
77 78 79
  else {
    _preloadingDone = false;
  }
80 81
  _imagesToPreload = imagesToPreload;
}
82 83 84 85 86 87 88

- (void)setOpaque:(BOOL)opaque
{
  _opaque = opaque;
  [self setNeedsDisplay];
}

89 90
- (void)setRenderId:(NSNumber *)renderId
{
91
  if (_nbContentTextures > 0) {
92 93 94 95
    [self setNeedsDisplay];
  }
}

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
- (void)setAutoRedraw:(BOOL)autoRedraw
{
  if (autoRedraw) {
    if (!animationTimer)
      animationTimer = // FIXME: can we do better than this?
      [NSTimer scheduledTimerWithTimeInterval:1.0/60.0
                                       target:self
                                     selector:@selector(setNeedsDisplay)
                                     userInfo:nil
                                      repeats:YES];
  }
  else {
    if (animationTimer) {
      [animationTimer invalidate];
    }
  }
}

- (void)setEventsThrough:(BOOL)eventsThrough
{
116
  _eventsThrough = eventsThrough;
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
117
  [self syncEventsThrough];
118 119 120 121 122
}

-(void)setVisibleContent:(BOOL)visibleContent
{
  _visibleContent = visibleContent;
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
123
  [self syncEventsThrough];
124 125
}

126 127 128 129 130 131
- (void)setData:(GLData *)data
{
  _data = data;
  [self requestSyncData];
}

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
132 133 134 135 136 137 138 139 140 141 142 143 144 145
- (void)setNbContentTextures:(NSNumber *)nbContentTextures
{
  [self resizeUniformContentTextures:[nbContentTextures intValue]];
  _nbContentTextures = nbContentTextures;
}

//// Sync methods (called from props setters)

- (void) syncEventsThrough
{
  self.userInteractionEnabled = !(_eventsThrough);
  self.superview.userInteractionEnabled = !(_eventsThrough && !_visibleContent);
}

146 147 148 149 150 151 152 153 154
- (void)requestSyncData
{
  [self syncData];
}

- (void)syncData
{
  [EAGLContext setCurrentContext:self.context];
  @autoreleasepool {
155
    
156 157 158
    NSDictionary *prevImages = _images;
    NSMutableDictionary *images = [[NSMutableDictionary alloc] init];
    
159 160 161
    GLRenderData * (^traverseTree) (GLData *data);
    __block __weak GLRenderData * (^weak_traverseTree)(GLData *data);
    weak_traverseTree = traverseTree = ^GLRenderData *(GLData *data) {
162 163
      NSNumber *width = data.width;
      NSNumber *height = data.height;
164 165 166 167 168 169
      int fboId = [data.fboId intValue];
      
      NSMutableArray *contextChildren = [[NSMutableArray alloc] init];
      for (GLData *child in data.contextChildren) {
        [contextChildren addObject:weak_traverseTree(child)];
      }
170 171 172
      
      NSMutableArray *children = [[NSMutableArray alloc] init];
      for (GLData *child in data.children) {
173
        [children addObject:weak_traverseTree(child)];
174 175 176 177 178 179 180 181 182 183 184 185
      }
      
      GLShader *shader = [GLShadersRegistry getShader:data.shader];
      
      NSDictionary *uniformTypes = [shader uniformTypes];
      NSMutableDictionary *uniforms = [[NSMutableDictionary alloc] init];
      NSMutableDictionary *textures = [[NSMutableDictionary alloc] init];
      int units = 0;
      for (NSString *uniformName in data.uniforms) {
        id value = [data.uniforms objectForKey:uniformName];
        GLenum type = [uniformTypes[uniformName] intValue];
        
186
        if (type == GL_SAMPLER_2D || type == GL_SAMPLER_CUBE) {
187
          uniforms[uniformName] = [NSNumber numberWithInt:units++];
188 189 190 191
          if (!value) {
            GLTexture *emptyTexture = [[GLTexture alloc] init];
            [emptyTexture setPixelsEmpty];
            textures[uniformName] = emptyTexture;
192
          }
193 194 195 196 197 198 199 200
          else {
            NSString *type = [RCTConvert NSString:value[@"type"]];
            if ([type isEqualToString:@"content"]) {
              int id = [[RCTConvert NSNumber:value[@"id"]] intValue];
              if (id >= [_contentTextures count]) {
                [self resizeUniformContentTextures:id+1];
              }
              textures[uniformName] = _contentTextures[id];
201
            }
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
            else if ([type isEqualToString:@"fbo"]) {
              NSNumber *id = [RCTConvert NSNumber:value[@"id"]];
              GLFBO *fbo = [GLShadersRegistry getFBO:id];
              textures[uniformName] = fbo.color[0];
            }
            else if ([type isEqualToString:@"uri"]) {
              NSString *src = srcResource(value);
              if (!src) {
                RCTLogError(@"texture uniform '%@': Invalid uri format '%@'", uniformName, value);
              }
              
              GLImage *image = images[src];
              if (image == nil) {
                image = prevImages[src];
                if (image != nil)
                  images[src] = image;
              }
              if (image == nil) {
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
220
                __weak GLCanvas *weakSelf = self;
221
                image = [[GLImage alloc] initWithBridge:_bridge withOnLoad:^{
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
222
                  if (weakSelf) [weakSelf onImageLoad:src];
223 224
                }];
                image.src = src;
225
                images[src] = image;
226 227
              }
              textures[uniformName] = [image getTexture];
228
            }
229 230
            else {
              RCTLogError(@"texture uniform '%@': Unexpected type '%@'", uniformName, type);
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
            }
          }
        }
        else {
          uniforms[uniformName] = value;
        }
      }
      
      int maxTextureUnits;
      glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &maxTextureUnits);
      if (units > maxTextureUnits) {
        RCTLogError(@"Maximum number of texture reach. got %i >= max %i", units, maxTextureUnits);
      }
      
      for (NSString *uniformName in shader.uniformTypes) {
        if (uniforms[uniformName] == nil) {
          RCTLogError(@"All defined uniforms must be provided. Missing '%@'", uniformName);
        }
      }
250
      
251 252 253 254 255 256 257 258
      return [[GLRenderData alloc]
              initWithShader:shader
              withUniforms:uniforms
              withTextures:textures
              withWidth:width
              withHeight:height
              withFboId:fboId
              withContextChildren:contextChildren
259
              withChildren:children];
260 261
    };
    
262
    _renderData = traverseTree(_data);
263 264 265 266 267 268
    _images = images;
    
    [self setNeedsDisplay];
  }
}

269
- (void)syncContentTextures
270 271
{
  int i = 0;
272
  for (GLTexture *texture in _contentTextures) {
273 274
    UIView* view = self.superview.subviews[i]; // We take siblings by index (closely related to the JS code)
    if (view) {
275 276 277 278
      if ([view.subviews count] == 1)
        [texture setPixelsWithView:view.subviews[0]];
      else
        [texture setPixelsWithView:view];
279 280 281 282 283 284 285
    } else {
      [texture setPixelsEmpty];
    }
    i ++;
  }
}

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
286 287 288

//// Draw

289 290
- (void)drawRect:(CGRect)rect
{
291 292
  self.layer.opaque = _opaque;
  [self syncEventsThrough];
293
  
294 295 296 297 298
  if (!_preloadingDone) {
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glClear(GL_COLOR_BUFFER_BIT);
    return;
  }
299
  BOOL needsDeferredRendering = _nbContentTextures > 0 && !_autoRedraw;
300 301 302 303 304 305 306
  if (needsDeferredRendering && !_deferredRendering) {
    dispatch_async(dispatch_get_main_queue(), ^{
      _deferredRendering = true;
      [self setNeedsDisplay];
    });
  }
  else {
307
    [self render];
308 309 310 311
    _deferredRendering = false;
  }
}

312
- (void)render
313 314 315 316 317 318 319 320 321 322 323 324
{
  if (!_renderData) return;
  
  CGFloat scale = RCTScreenScale();
  
  @autoreleasepool {
    void (^recDraw) (GLRenderData *renderData);
    __block __weak void (^weak_recDraw) (GLRenderData *renderData);
    weak_recDraw = recDraw = ^void(GLRenderData *renderData) {
      float w = [renderData.width floatValue] * scale;
      float h = [renderData.height floatValue] * scale;
      
325 326 327
      for (GLRenderData *child in renderData.contextChildren)
        weak_recDraw(child);
      
328
      for (GLRenderData *child in renderData.children)
329
        weak_recDraw(child);
330
      
331
      if (renderData.fboId == -1) {
332 333 334 335
        glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO);
        glViewport(0, 0, w, h);
      }
      else {
336
        GLFBO *fbo = [GLShadersRegistry getFBO:[NSNumber numberWithInt:renderData.fboId]];
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
        [fbo setShapeWithWidth:w withHeight:h];
        [fbo bind];
      }
      
      [renderData.shader bind];
      
      for (NSString *uniformName in renderData.textures) {
        GLTexture *texture = renderData.textures[uniformName];
        int unit = [((NSNumber *)renderData.uniforms[uniformName]) intValue];
        [texture bind:unit];
      }
      
      for (NSString *uniformName in renderData.uniforms) {
        [renderData.shader setUniform:uniformName withValue:renderData.uniforms[uniformName]];
      }
      
353
      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
354 355
      glClearColor(0.0, 0.0, 0.0, 0.0);
      glClear(GL_COLOR_BUFFER_BIT);
356 357 358
      glDrawArrays(GL_TRIANGLES, 0, 6);
    };
    
359 360
    // DRAWING THE SCENE
    
361
    [self syncContentTextures];
362
    
363
    glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO);
364
    glEnable(GL_BLEND);
365 366
    recDraw(_renderData);
    glDisable(GL_BLEND);
367 368 369 370
    glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO);
  }
}

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
//// utility methods

- (void)onImageLoad:(NSString *)loaded
{
  if (!_preloadingDone) {
    [_preloaded addObject:loaded];
    int count = [self countPreloaded];
    int total = (int) [_imagesToPreload count];
    double progress = ((double) count) / ((double) total);
    [self dispatchOnProgress:progress withLoaded:count withTotal:total];
    if (count == total) {
      [self dispatchOnLoad];
      _preloadingDone = true;
      [self requestSyncData];
    }
  }
  else {
    // Any texture image load will trigger a future re-sync of data (if no preloaded)
    [self requestSyncData];
  }
}

- (int)countPreloaded
{
  int nb = 0;
  for (id toload in _imagesToPreload) {
    if ([_preloaded containsObject:srcResource(toload)])
      nb++;
  }
  return nb;
}
402

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
- (void)resizeUniformContentTextures:(int)n
{
  [EAGLContext setCurrentContext:self.context];
  int length = (int) [_contentTextures count];
  if (length == n) return;
  if (n < length) {
    _contentTextures = [_contentTextures subarrayWithRange:NSMakeRange(0, n)];
  }
  else {
    NSMutableArray *contentTextures = [[NSMutableArray alloc] initWithArray:_contentTextures];
    for (int i = (int) [_contentTextures count]; i < n; i++) {
      [contentTextures addObject:[[GLTexture alloc] init]];
    }
    _contentTextures = contentTextures;
  }
}

- (void)dispatchOnLoad
{
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
422
  [_bridge.eventDispatcher sendInputEventWithName:@"load" body:@{ @"target": self.reactTag }];
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
423 424 425 426
}

- (void)dispatchOnProgress: (double)progress withLoaded:(int)loaded withTotal:(int)total
{
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
427 428 429 430 431 432 433
  NSDictionary *event =
  @{
    @"target": self.reactTag,
    @"progress": @(progress),
    @"loaded": @(loaded),
    @"total": @(total) };
  [_bridge.eventDispatcher sendInputEventWithName:@"progress" body:event];
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
434
}
435

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
436
@end