Oolite
Loading...
Searching...
No Matches
OOShaderProgram.m
Go to the documentation of this file.
1/*
2
3OOShaderProgram.m
4
5
6Copyright (C) 2007-2013 Jens Ayton
7
8Permission is hereby granted, free of charge, to any person obtaining a copy
9of this software and associated documentation files (the "Software"), to deal
10in the Software without restriction, including without limitation the rights
11to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12copies of the Software, and to permit persons to whom the Software is
13furnished to do so, subject to the following conditions:
14
15The above copyright notice and this permission notice shall be included in all
16copies or substantial portions of the Software.
17
18THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24SOFTWARE.
25
26*/
27
29
30#if OO_SHADERS
31
32#import "MyOpenGLView.h"
34#import "OODebugFlags.h"
36#import "OOMacroOpenGL.h"
38#import "OOShaderProgram.h"
39#import "OOStringParsing.h"
40#import "ResourceManager.h"
41#import "Universe.h"
42
43static NSMutableDictionary* sShaderCache = nil;
44static OOShaderProgram* sActiveProgram = nil;
45
46static BOOL GetShaderSource(NSString* fileName, NSString* shaderType, NSString* prefix, NSString** outResult);
47#if OOLITE_MAC_OS_X
48static NSString* TranslateGLSL330To120(NSString* source, BOOL isVertexShader, NSMutableDictionary* attributeBindings);
49#endif
50static NSString* GetGLSLInfoLog(GLhandleARB shaderObject);
51
52@interface OOShaderProgram (OOPrivate)
53
54- (id)initWithVertexShaderSource:(NSString*)vertexSource
55 fragmentShaderSource:(NSString*)fragmentSource
56 prefixString:(NSString*)prefixString
57 vertexName:(NSString*)vertexName
58 fragmentName:(NSString*)fragmentName
59 attributeBindings:(NSDictionary*)attributeBindings
60 key:(NSString*)key;
61
62- (void)bindAttributes:(NSDictionary*)attributeBindings;
63- (void)bindStandardMatrixUniforms;
64
65@end
66
67@implementation OOShaderProgram
68
69+ (id)shaderProgramWithVertexShader:(NSString*)vertexShaderSource
70 fragmentShader:(NSString*)fragmentShaderSource
71 vertexShaderName:(NSString*)vertexShaderName
72 fragmentShaderName:(NSString*)fragmentShaderName
73 prefix:(NSString*)prefixString // String prepended to program source (both vs and fs)
74 attributeBindings:(NSDictionary*)attributeBindings // Maps vertex attribute names to "locations".
75 cacheKey:(NSString*)cacheKey
76{
77 OOShaderProgram* result = nil;
78
79 if ([prefixString length] == 0)
80 prefixString = nil;
81
82 // Use cache to avoid creating duplicate shader programs -- saves on GPU resources and potentially state changes.
83 // FIXME: probably needs to respond to graphics resets.
84 result = [[sShaderCache objectForKey:cacheKey] pointerValue];
85
86 if (result == nil) {
87 // No cached program; create one...
88 result = [[OOShaderProgram alloc] initWithVertexShaderSource:vertexShaderSource
89 fragmentShaderSource:fragmentShaderSource
90 prefixString:prefixString
91 vertexName:vertexShaderName
92 fragmentName:fragmentShaderName
93 attributeBindings:attributeBindings
94 key:cacheKey];
95 [result autorelease];
96
97 if (result != nil && cacheKey != nil) {
98 // ...and add it to the cache.
99 if (sShaderCache == nil)
100 sShaderCache = [[NSMutableDictionary alloc] init];
101 [sShaderCache setObject:[NSValue valueWithPointer:result] forKey:cacheKey]; // Use NSValue so dictionary doesn't retain program
102 }
103 }
104
105 return result;
106}
107
108+ (id)shaderProgramWithVertexShaderName:(NSString*)vertexShaderName
109 fragmentShaderName:(NSString*)fragmentShaderName
110 prefix:(NSString*)prefixString
111 attributeBindings:(NSDictionary*)attributeBindings
112{
113 NSString* cacheKey = nil;
114 OOShaderProgram* result = nil;
115 NSString* vertexSource = nil;
116 NSString* fragmentSource = nil;
117
118 if ([prefixString length] == 0)
119 prefixString = nil;
120
121 // Use cache to avoid creating duplicate shader programs -- saves on GPU resources and potentially state changes.
122 // FIXME: probably needs to respond to graphics resets.
123 cacheKey = [NSString stringWithFormat:@"vertex:%@\nfragment:%@\n----\n%@", vertexShaderName, fragmentShaderName, prefixString ?: (NSString*)@""];
124 result = [[sShaderCache objectForKey:cacheKey] pointerValue];
125
126 if (result == nil) {
127 // No cached program; create one...
128 if (!GetShaderSource(vertexShaderName, @"vertex", prefixString, &vertexSource))
129 return nil;
130 if (!GetShaderSource(fragmentShaderName, @"fragment", prefixString, &fragmentSource))
131 return nil;
132#if OOLITE_MAC_OS_X
133 /* The macOS legacy OpenGL context only supports GLSL 1.20, so shaders
134 written for #version 330 are translated when loaded.
135 */
136 if ([prefixString hasPrefix:@"#version 330"]) {
137 NSMutableDictionary* bindings = [NSMutableDictionary dictionaryWithDictionary:attributeBindings ?: [NSDictionary dictionary]];
138 vertexSource = TranslateGLSL330To120(vertexSource, YES, bindings);
139 fragmentSource = TranslateGLSL330To120(fragmentSource, NO, bindings);
140 attributeBindings = bindings;
141 prefixString = [@"#version 120\n#extension GL_EXT_gpu_shader4 : enable\n" stringByAppendingString:[prefixString substringFromIndex:[@"#version 330" length]]];
142 }
143#endif
144 result = [[OOShaderProgram alloc] initWithVertexShaderSource:vertexSource
145 fragmentShaderSource:fragmentSource
146 prefixString:prefixString
147 vertexName:vertexShaderName
148 fragmentName:fragmentShaderName
149 attributeBindings:attributeBindings
150 key:cacheKey];
151
152 if (result != nil) {
153 // ...and add it to the cache.
154 [result autorelease];
155 if (sShaderCache == nil)
156 sShaderCache = [[NSMutableDictionary alloc] init];
157 [sShaderCache setObject:[NSValue valueWithPointer:result] forKey:cacheKey]; // Use NSValue so dictionary doesn't retain program
158 }
159 }
160
161 return result;
162}
163
164- (void)dealloc
165{
167
168#ifndef NDEBUG
169 if (EXPECT_NOT(sActiveProgram == self)) {
170 OOLog(@"shader.dealloc.imbalance", @"%@", @"***** OOShaderProgram deallocated while active, indicating a retain/release imbalance. Expect imminent crash.");
171 [OOShaderProgram applyNone];
172 }
173#endif
174
175 if (key != nil) {
176 [sShaderCache removeObjectForKey:key];
177 [key release];
178 }
179
180 if (standardMatrixUniformLocations != nil) {
181 [standardMatrixUniformLocations release];
182 }
183
184 OOGL(glDeleteObjectARB(program));
185
186 [super dealloc];
187}
188
189- (void)apply
190{
192
193 if (sActiveProgram != self) {
194 [sActiveProgram release];
195 sActiveProgram = [self retain];
196 OOGL(glUseProgramObjectARB(program));
197 [self bindStandardMatrixUniforms];
198 }
199}
200
201+ (void)applyNone
202{
204
205 if (sActiveProgram != nil) {
206 [sActiveProgram release];
207 sActiveProgram = nil;
208 OOGL(glUseProgramObjectARB(NULL_SHADER));
209 }
210}
211
212- (GLhandleARB)program
213{
214 return program;
215}
216
217@end
218
219static BOOL ValidateShaderObject(GLhandleARB object, NSString* name)
220{
221 GLint type, subtype = 0, status;
222 GLenum statusType;
223 NSString* subtypeString = nil;
224 NSString* actionString = nil;
225
227
228 OOGL(glGetObjectParameterivARB(object, GL_OBJECT_TYPE_ARB, &type));
229 BOOL linking = type == GL_PROGRAM_OBJECT_ARB;
230
231 if (linking) {
232 subtypeString = @"shader program";
233 actionString = @"linking";
234 statusType = GL_OBJECT_LINK_STATUS_ARB;
235 } else {
236 // FIXME
237 OOGL(glGetObjectParameterivARB(object, GL_OBJECT_SUBTYPE_ARB, &subtype));
238 switch (subtype) {
239 case GL_VERTEX_SHADER_ARB:
240 subtypeString = @"vertex shader";
241 break;
242
243 case GL_FRAGMENT_SHADER_ARB:
244 subtypeString = @"fragment shader";
245 break;
246
247#if GL_EXT_geometry_shader4
248 case GL_GEOMETRY_SHADER_EXT:
249 subtypeString = @"geometry shader";
250 break;
251#endif
252
253 default:
254 subtypeString = [NSString stringWithFormat:@"<unknown shader type 0x%.4X>", subtype];
255 }
256 actionString = @"compilation";
257 statusType = GL_OBJECT_COMPILE_STATUS_ARB;
258 }
259
260 OOGL(glGetObjectParameterivARB(object, statusType, &status));
261 if (status == GL_FALSE) {
262 NSString* msgClass = [NSString stringWithFormat:@"shader.%@.failure", linking ? @"link" : @"compile"];
263 OOLogERR(msgClass, @"GLSL %@ %@ failed for %@:\n>>>>> GLSL log:\n%@\n", subtypeString, actionString, name, GetGLSLInfoLog(object));
264 return NO;
265 }
266
267#ifdef OO_DEBUG_MONITOR_ENABLED
269 OOGL(glValidateProgramARB(object));
270 OOGL(glGetObjectParameterivARB(object, GL_OBJECT_VALIDATE_STATUS_ARB, &status));
271 if (status == GL_FALSE) {
272 NSString* msgClass = [NSString stringWithFormat:@"shader.%@.validationFailure", linking ? @"link" : @"compile"];
273 OOLogWARN(msgClass, @"GLSL %@ %@ failed for %@:\n>>>>> GLSL log:\n%@\n", subtypeString, @"validation", name, GetGLSLInfoLog(object));
274 return NO;
275 }
276 }
277#endif
278
279 return YES;
280}
281
282@implementation OOShaderProgram (OOPrivate)
283
284- (id)initWithVertexShaderSource:(NSString*)vertexSource
285 fragmentShaderSource:(NSString*)fragmentSource
286 prefixString:(NSString*)prefixString
287 vertexName:(NSString*)vertexName
288 fragmentName:(NSString*)fragmentName
289 attributeBindings:(NSDictionary*)attributeBindings
290 key:(NSString*)inKey
291{
292 BOOL OK = YES;
293 const GLcharARB* sourceStrings[3] = { "", "#line 0\n", NULL };
294 GLhandleARB vertexShader = NULL_SHADER;
295 GLhandleARB fragmentShader = NULL_SHADER;
296
298
299 self = [super init];
300 if (self == nil)
301 OK = NO;
302
303 if (OK && vertexSource == nil && fragmentSource == nil)
304 OK = NO; // Must have at least one shader!
305
306 if (OK && prefixString != nil) {
307 sourceStrings[0] = [prefixString UTF8String];
308 }
309
310 if (OK && vertexSource != nil) {
311 // Compile vertex shader.
312 OOGL(vertexShader = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
313 if (vertexShader != NULL_SHADER) {
314 sourceStrings[2] = [vertexSource UTF8String];
315 OOGL(glShaderSourceARB(vertexShader, 3, sourceStrings, NULL));
316 OOGL(glCompileShaderARB(vertexShader));
317
318 OK = ValidateShaderObject(vertexShader, vertexName);
319 } else
320 OK = NO;
321 }
322
323 if (OK && fragmentSource != nil) {
324 // Compile fragment shader.
325 OOGL(fragmentShader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
326 if (fragmentShader != NULL_SHADER) {
327 sourceStrings[2] = [fragmentSource UTF8String];
328 OOGL(glShaderSourceARB(fragmentShader, 3, sourceStrings, NULL));
329 OOGL(glCompileShaderARB(fragmentShader));
330
331 OK = ValidateShaderObject(fragmentShader, fragmentName);
332 } else
333 OK = NO;
334 }
335
336 if (OK) {
337 // Link shader.
338 OOGL(program = glCreateProgramObjectARB());
339 if (program != NULL_SHADER) {
340 if (vertexShader != NULL_SHADER)
341 OOGL(glAttachObjectARB(program, vertexShader));
342 if (fragmentShader != NULL_SHADER)
343 OOGL(glAttachObjectARB(program, fragmentShader));
344 [self bindAttributes:attributeBindings];
345 OOGL(glLinkProgramARB(program));
346
347 OK = ValidateShaderObject(program, [NSString stringWithFormat:@"%@/%@", vertexName, fragmentName]);
348 } else
349 OK = NO;
350 }
351
352 if (OK) {
353 key = [inKey copy];
354 }
355
356 if (vertexShader != NULL_SHADER)
357 OOGL(glDeleteObjectARB(vertexShader));
358 if (fragmentShader != NULL_SHADER)
359 OOGL(glDeleteObjectARB(fragmentShader));
360
361 if (OK) {
362 OOOpenGLMatrixManager* matrixManager = [[UNIVERSE gameView] getOpenGLMatrixManager];
363 standardMatrixUniformLocations = [matrixManager standardMatrixUniformLocations:program];
364 } else {
365 if (self != nil && program != NULL_SHADER) {
366 OOGL(glDeleteObjectARB(program));
367 program = NULL_SHADER;
368 }
369
370 [self release];
371 self = nil;
372 }
373 return self;
374}
375
376- (void)bindAttributes:(NSDictionary*)attributeBindings
377{
379
380 NSString* attrKey = nil;
381
382 foreachkey(attrKey, attributeBindings)
383 {
384 OOGL(glBindAttribLocationARB(program, [attributeBindings oo_unsignedIntForKey:attrKey], [attrKey UTF8String]));
385 }
386}
387
388- (void)bindStandardMatrixUniforms
389{
390 if (standardMatrixUniformLocations != nil) {
391 OOOpenGLMatrixManager* matrixManager = [[UNIVERSE gameView] getOpenGLMatrixManager];
392 id obj;
393 NSArray* pair;
394
396
397 [matrixManager syncModelView];
398 foreach (obj, standardMatrixUniformLocations) {
399 if ([obj isKindOfClass:[NSArray class]]) {
400 pair = (NSArray*)obj;
401 if ([[pair oo_stringAtIndex:2] compare:@"mat3"] == 0) {
402 OOGL(GLUniformMatrix3([pair oo_intAtIndex:0], [matrixManager getMatrix:[pair oo_intAtIndex:1]]));
403 } else {
404 GLUniformMatrix([pair oo_intAtIndex:0], [matrixManager getMatrix:[pair oo_intAtIndex:1]]);
405 }
406 }
407 }
408 }
409 return;
410}
411
412@end
413
414/* Attempt to load fragment or vertex shader source from a file.
415 Returns YES if source was loaded or no shader was specified, and NO if an
416 external shader was specified but could not be found.
417*/
418static BOOL GetShaderSource(NSString* fileName, NSString* shaderType, NSString* prefix, NSString** outResult)
419{
420 NSString* result = nil;
421 NSArray* extensions = nil;
422 NSString* extension = nil;
423 NSString* nameWithExtension = nil;
424
425 if (fileName == nil)
426 return YES; // It's OK for one or the other of the shaders to be undefined.
427
428 result = [ResourceManager stringFromFilesNamed:fileName inFolder:@"Shaders"];
429 if (result == nil) {
430 extensions = [NSArray arrayWithObjects:shaderType, [shaderType substringToIndex:4], nil]; // vertex and vert, or fragment and frag
431
432 // Futureproofing -- in future, we may wish to support automatic selection between supported shader languages.
433 if (![fileName pathHasExtensionInArray:extensions]) {
434 foreach (extension, extensions) {
435 nameWithExtension = [fileName stringByAppendingPathExtension:extension];
436 result = [ResourceManager stringFromFilesNamed:nameWithExtension
437 inFolder:@"Shaders"];
438 if (result != nil)
439 break;
440 }
441 }
442 if (result == nil) {
443 OOLog(kOOLogFileNotFound, @"GLSL ERROR: failed to find fragment program %@.", fileName);
444 return NO;
445 }
446 }
447 /*
448 if (result != nil && prefix != nil)
449 {
450 result = [prefix stringByAppendingString:result];
451 }
452 */
453 if (outResult != NULL)
454 *outResult = result;
455 return YES;
456}
457
458static NSString* GetGLSLInfoLog(GLhandleARB shaderObject)
459{
460 GLint length;
461 GLcharARB* log = NULL;
462 NSString* result = nil;
463
465
466 if (EXPECT_NOT(shaderObject == NULL_SHADER))
467 return nil;
468
469 OOGL(glGetObjectParameterivARB(shaderObject, GL_OBJECT_INFO_LOG_LENGTH_ARB, &length));
470 log = malloc(length);
471 if (log == NULL) {
472 length = 1024;
473 log = malloc(length);
474 if (log == NULL)
475 return @"<out of memory>";
476 }
477 OOGL(glGetInfoLogARB(shaderObject, length, NULL, log));
478
479 result = [NSString stringWithUTF8String:log];
480 if (result == nil)
481 result = [[[NSString alloc] initWithBytes:log length:length - 1 encoding:NSISOLatin1StringEncoding] autorelease];
482 free(log);
483
484 return result;
485}
486
487#endif // OO_SHADERS
488
489
490#if OOLITE_MAC_OS_X
491static NSString* ReplaceRegex(NSString* source, NSString* pattern, NSString* replacement)
492{
493 NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionAnchorsMatchLines error:NULL];
494 return [regex stringByReplacingMatchesInString:source options:0 range:NSMakeRange(0, [source length]) withTemplate:replacement];
495}
496
497
498/* Translate the subset of GLSL 3.30 used by Oolite's post-processing shaders
499 to GLSL 1.20 (plus GL_EXT_gpu_shader4). Only top-level declarations are
500 rewritten, so in/out parameter qualifiers inside functions are untouched.
501*/
502static NSString* TranslateGLSL330To120(NSString* source, BOOL isVertexShader, NSMutableDictionary* attributeBindings)
503{
504 if (source == nil)
505 return nil;
506
507 NSRegularExpression* regex = nil;
508 NSArray* matches = nil;
509 NSTextCheckingResult* match = nil;
510
511 if (isVertexShader) {
512 // layout(location = N) in TYPE NAME; -> attribute binding NAME = N
513 regex = [NSRegularExpression regularExpressionWithPattern:@"^\\s*layout\\s*\\(\\s*location\\s*=\\s*(\\d+)\\s*\\)\\s*in\\s+\\w+\\s+(\\w+)\\s*;" options:NSRegularExpressionAnchorsMatchLines error:NULL];
514 matches = [regex matchesInString:source options:0 range:NSMakeRange(0, [source length])];
515 foreach (match, matches) {
516 NSString* location = [source substringWithRange:[match rangeAtIndex:1]];
517 NSString* name = [source substringWithRange:[match rangeAtIndex:2]];
518 [attributeBindings setObject:[NSNumber numberWithInt:[location intValue]] forKey:name];
519 }
520 } else {
521 // [layout(location = N)] out vec4 NAME; -> #define NAME gl_FragData[N]
522 NSMutableString* result = [NSMutableString stringWithString:source];
523 regex = [NSRegularExpression regularExpressionWithPattern:@"^\\s*(?:layout\\s*\\(\\s*location\\s*=\\s*(\\d+)\\s*\\)\\s*)?out\\s+vec4\\s+(\\w+)\\s*;" options:NSRegularExpressionAnchorsMatchLines error:NULL];
524 matches = [regex matchesInString:source options:0 range:NSMakeRange(0, [source length])];
525 foreach (match, [matches reverseObjectEnumerator]) {
526 NSRange locationRange = [match rangeAtIndex:1];
527 NSString* location = locationRange.location != NSNotFound ? [source substringWithRange:locationRange] : @"0";
528 NSString* name = [source substringWithRange:[match rangeAtIndex:2]];
529 [result replaceCharactersInRange:[match range] withString:[NSString stringWithFormat:@"#define %@ gl_FragData[%@]", name, location]];
530 }
531 source = result;
532 }
533
534 source = ReplaceRegex(source, @"layout\\s*\\‍([^)]*\\‍)\\s*", @"");
535 if (isVertexShader) {
536 source = ReplaceRegex(source, @"^(\\s*)in\\s+", @"$1attribute ");
537 source = ReplaceRegex(source, @"^(\\s*)out\\s+", @"$1varying ");
538 } else {
539 source = ReplaceRegex(source, @"^(\\s*)in\\s+", @"$1varying ");
540 }
541 source = ReplaceRegex(source, @"\\btexture\\s*\\‍(", @"texture2D(");
542 source = ReplaceRegex(source, @"\\btextureSize\\s*\\‍(", @"textureSize2D(");
543 if ([source rangeOfString:@"isnan("].location != NSNotFound) {
544 // isnan() is not available before GLSL 1.30.
545 source = [@"bool oo_isnan(float x) { return !(x < 0.0 || x > 0.0 || x == 0.0); }\n" stringByAppendingString:ReplaceRegex(source, @"\\bisnan\\s*\\(", @"oo_isnan(")];
546 }
547
548 return source;
549}
550#endif
#define gDebugFlags
@ DEBUG_SHADER_VALIDATION
#define foreachkey(VAR, DICT)
#define EXPECT_NOT(x)
#define OOLogWARN(class, format,...)
Definition OOLogging.h:126
#define OOLogERR(class, format,...)
Definition OOLogging.h:125
#define OOLog(class, format,...)
Definition OOLogging.h:84
NSString *const kOOLogFileNotFound
Definition OOLogging.m:601
#define OO_ENTER_OPENGL()
void GLUniformMatrix3(GLint location, OOMatrix M)
#define GLUniformMatrix(location, M)
Definition OOMatrix.h:113
#define NULL_SHADER
Definition OOOpenGL.h:41
#define OOGL(statement)
Definition OOOpenGL.h:262
return nil
static BOOL GetShaderSource(NSString *fileName, NSString *shaderType, NSString *prefix, NSString **outResult)
NSArray * standardMatrixUniformLocations:(GLhandleARB program)
NSString * stringFromFilesNamed:inFolder:(NSString *fileName,[inFolder] NSString *folderName)