1 #import <QuartzCore/CALayerContext.h>
2 #import <QuartzCore/CALayer.h>
3 #import <QuartzCore/CARenderer.h>
4 #import <Foundation/NSString.h>
6 @interface CALayer(private)
7 -(void)_setContext:(CALayerContext *)context;
8 -(NSNumber *)_textureId;
9 -(void)_setTextureId:(NSNumber *)value;
12 @implementation CALayerContext
14 -initWithFrame:(CGRect)rect {
17 CGLPixelFormatAttribute attributes[1]={
20 GLint numberOfVirtualScreens;
22 CGLChoosePixelFormat(attributes,&_pixelFormat,&numberOfVirtualScreens);
24 if((error=CGLCreateContext(_pixelFormat,NULL,&_glContext))!=kCGLNoError)
25 NSLog(@"CGLCreateContext failed with %d in %s %d",error,__FILE__,__LINE__);
29 GLint width=rect.size.width;
30 GLint height=rect.size.height;
32 GLint backingOrigin[2]={rect.origin.x,rect.origin.y};
33 GLint backingSize[2]={width,height};
35 CGLSetParameter(_glContext,kCGLCPSurfaceBackingOrigin,backingOrigin);
36 CGLSetParameter(_glContext,kCGLCPSurfaceBackingSize,backingSize);
39 CGLSetParameter(_glContext,kCGLCPSurfaceOpacity,&opacity);
41 _renderer=[[CARenderer rendererWithCGLContext:_glContext options:nil] retain];
52 -(void)setFrame:(CGRect)rect {
55 GLint width=rect.size.width;
56 GLint height=rect.size.height;
58 GLint backingOrigin[2]={rect.origin.x,rect.origin.y};
59 GLint backingSize[2]={width,height};
61 CGLSetParameter(_glContext,kCGLCPSurfaceBackingOrigin,backingOrigin);
62 CGLSetParameter(_glContext,kCGLCPSurfaceBackingSize,backingSize);
65 -(void)setLayer:(CALayer *)layer {
70 [_layer _setContext:self];
71 [_renderer setLayer:layer];
77 -(void)assignTextureIdsToLayerTree:(CALayer *)layer {
79 if([layer _textureId]==nil){
82 glGenTextures(1,&texture);
83 [layer _setTextureId:[NSNumber numberWithUnsignedInt:texture]];
86 for(CALayer *child in layer.sublayers)
87 [self assignTextureIdsToLayerTree:child];
90 -(void)renderLayer:(CALayer *)layer {
91 CGLSetCurrentContext(_glContext);
93 glEnable(GL_DEPTH_TEST);
94 glShadeModel(GL_SMOOTH);
96 GLint width=_frame.size.width;
97 GLint height=_frame.size.height;
99 glViewport(0,0,width,height);
100 glMatrixMode(GL_PROJECTION);
102 glOrtho (0, width, 0, height, -1, 1);
105 GLuint deleteIds[[_deleteTextureIds count]];
107 for(NSNumber *number in _deleteTextureIds)
108 deleteIds[i++]=[number unsignedIntValue];
111 glDeleteTextures(i,deleteIds);
113 [_deleteTextureIds removeAllObjects];
115 [self assignTextureIdsToLayerTree:layer];
121 [self renderLayer:_layer];
124 -(void)timer:(NSTimer *)timer {
125 [_renderer beginFrameAtTime:CACurrentMediaTime() timeStamp:NULL];
129 [_renderer endFrame];
132 -(void)startTimerIfNeeded {
134 _timer=[[NSTimer scheduledTimerWithTimeInterval:1.0/60.0 target:self selector:@selector(timer:) userInfo:nil repeats:YES] retain];
137 -(void)deleteTextureId:(NSNumber *)textureId {
138 [_deleteTextureIds addObject:textureId];