Oolite
Loading...
Searching...
No Matches
OOShaderMaterial.m
Go to the documentation of this file.
1/*
2
3OOShaderMaterial.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
28#import "OOShaderMaterial.h"
29
30#if OO_SHADERS
31
33#import "OODebugFlags.h"
35#import "OOIsNumberLiteral.h"
36#import "OOLogging.h"
37#import "OOMacroOpenGL.h"
39#import "OOShaderProgram.h"
40#import "OOShaderUniform.h"
41#import "OOStringParsing.h"
42#import "OOTexture.h"
43#import "ResourceManager.h"
44#import "Universe.h"
45
46NSString* const kOOVertexShaderSourceKey = @"_oo_vertex_shader_source";
47NSString* const kOOVertexShaderNameKey = @"vertex_shader";
48NSString* const kOOFragmentShaderSourceKey = @"_oo_fragment_shader_source";
49NSString* const kOOFragmentShaderNameKey = @"fragment_shader";
50NSString* const kOOTexturesKey = @"textures";
51NSString* const kOOTextureObjectsKey = @"_oo_texture_objects";
52NSString* const kOOUniformsKey = @"uniforms";
53NSString* const kOOIsSynthesizedMaterialConfigurationKey = @"_oo_is_synthesized_config";
54NSString* const kOOIsSynthesizedMaterialMacrosKey = @"_oo_synthesized_material_macros";
55
56static BOOL GetShaderSource(NSString* fileName, NSString* shaderType, NSString* prefix, NSString** outResult);
57static NSString* MacrosToString(NSDictionary* macros);
58
59@interface OOShaderMaterial (OOPrivate)
60
61// Convert a "textures" array to an "_oo_texture_objects" array.
62- (NSArray*)loadTexturesFromArray:(NSArray*)textureSpecs unitCount:(GLuint)max;
63
64// Load up an array of texture objects.
65- (void)addTexturesFromArray:(NSArray*)textureObjects unitCount:(GLuint)max;
66
67@end
68
69@implementation OOShaderMaterial
70
71+ (BOOL)configurationDictionarySpecifiesShaderMaterial:(NSDictionary*)configuration
72{
73 if (configuration == nil)
74 return NO;
75
76 if ([configuration oo_stringForKey:kOOVertexShaderSourceKey] != nil)
77 return YES;
78 if ([configuration oo_stringForKey:kOOFragmentShaderSourceKey] != nil)
79 return YES;
80 if ([configuration oo_stringForKey:kOOVertexShaderNameKey] != nil)
81 return YES;
82 if ([configuration oo_stringForKey:kOOVertexShaderNameKey] != nil)
83 return YES;
84
85 return NO;
86}
87
88+ (instancetype)shaderMaterialWithName:(NSString*)name
89 configuration:(NSDictionary*)configuration
90 macros:(NSDictionary*)macros
91 bindingTarget:(id<OOWeakReferenceSupport>)target
92{
93 return [[[self alloc] initWithName:name configuration:configuration macros:macros bindingTarget:target] autorelease];
94}
95
96- (id)initWithName:(NSString*)name
97 configuration:(NSDictionary*)configuration
98 macros:(NSDictionary*)macros
99 bindingTarget:(id<OOWeakReferenceSupport>)target
100{
101 BOOL OK = YES;
102 NSString* macroString = nil;
103 NSString* vertexShader = nil;
104 NSString* fragmentShader = nil;
106 NSMutableDictionary* modifiedMacros = nil;
107 NSString* vsName = @"<synthesized>";
108 NSString* fsName = @"<synthesized>";
109 NSString* vsCacheKey = nil;
110 NSString* fsCacheKey = nil;
111
112 if (configuration == nil)
113 OK = NO;
114
115 self = [super initWithName:name configuration:configuration];
116 if (self == nil)
117 OK = NO;
118
119 if (OK) {
120 modifiedMacros = macros ? [macros mutableCopy] : [[NSMutableDictionary alloc] init];
121 [modifiedMacros autorelease];
122
123 [modifiedMacros setObject:[NSNumber numberWithUnsignedInt:textureUnits]
124 forKey:@"OO_TEXTURE_UNIT_COUNT"];
125
126 // used to test for simplified shaders - OO_REDUCED_COMPLEXITY - here
127 macroString = MacrosToString(modifiedMacros);
128 }
129
130 if (OK) {
131 vertexShader = [configuration oo_stringForKey:kOOVertexShaderSourceKey];
132 if (vertexShader == nil) {
133 vsName = [configuration oo_stringForKey:kOOVertexShaderNameKey];
134 vsCacheKey = vsName;
135 if (vsName != nil) {
136 if (!GetShaderSource(vsName, @"vertex", macroString, &vertexShader))
137 OK = NO;
138 }
139 } else {
140 vsCacheKey = vertexShader;
141 }
142 }
143
144 if (OK) {
145 fragmentShader = [configuration oo_stringForKey:kOOFragmentShaderSourceKey];
146 if (fragmentShader == nil) {
147 fsName = [configuration oo_stringForKey:kOOFragmentShaderNameKey];
148 fsCacheKey = fsName;
149 if (fsName != nil) {
150 if (!GetShaderSource(fsName, @"fragment", macroString, &fragmentShader))
151 OK = NO;
152 }
153 } else {
154 fsCacheKey = fragmentShader;
155 }
156 }
157
158 if (OK) {
159 if (vertexShader != nil || fragmentShader != nil) {
160 static NSDictionary* attributeBindings = nil;
161 if (attributeBindings == nil) {
162 attributeBindings = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kTangentAttributeIndex]
163 forKey:@"tangent"];
164 [attributeBindings retain];
165 }
166
167 NSString* cacheKey = [NSString stringWithFormat:@"$w12:\n%@\n\n$w13:\n%@\n\n$w14:\n%@\n", vsCacheKey, fsCacheKey, macroString];
168
169 OOLogIndent();
170 shaderProgram = [OOShaderProgram shaderProgramWithVertexShader:vertexShader
171 fragmentShader:fragmentShader
172 vertexShaderName:vsName
173 fragmentShaderName:fsName
174 prefix:macroString
175 attributeBindings:attributeBindings
176 cacheKey:cacheKey];
177 OOLogOutdent();
178
179// no reduced complexity mode now
180#if 0
181 if (shaderProgram == nil)
182 {
183
184 BOOL canFallBack = ![modifiedMacros oo_boolForKey:@"OO_REDUCED_COMPLEXITY"];
185#ifdef OO_DEBUG_MONITOR_ENABLED
186 if (gDebugFlags & DEBUG_NO_SHADER_FALLBACK) canFallBack = NO;
187#endif
188 if (canFallBack)
189 {
190 OOLogWARN(@"shader.load.fullModeFailed", @"Could not build shader %@/%@ in full complexity mode, trying simple mode.", vsName, fsName);
191
192 [modifiedMacros setObject:[NSNumber numberWithInt:1] forKey:@"OO_REDUCED_COMPLEXITY"];
193 macroString = MacrosToString(modifiedMacros);
194 cacheKey = [cacheKey stringByAppendingString:@"\n$w25 FALLBACK\n"];
195
196 OOLogIndent();
197 shaderProgram = [OOShaderProgram shaderProgramWithVertexShader:vertexShader
198 fragmentShader:fragmentShader
199 vertexShaderName:vsName
200 fragmentShaderName:fsName
201 prefix:macroString
202 attributeBindings:attributeBindings
203 cacheKey:cacheKey];
204 OOLogOutdent();
205
206 if (shaderProgram != nil)
207 {
208 OOLog(@"shader.load.fallbackSuccess", @"Simple mode fallback successful.");
209 }
210 }
211 }
212#endif
213
214 if (shaderProgram == nil) {
215 OOLogERR(@"shader.load.failed", @"Could not build shader %@/%@.", vsName, fsName);
216 }
217 } else {
218 OOLog(@"shader.load.noShader", @"***** Error: no vertex or fragment shader specified in shader dictionary:\n%@", configuration);
219 }
220
221 OK = (shaderProgram != nil);
222 if (OK)
223 [shaderProgram retain];
224 }
225
226 if (OK) {
227 // Load uniforms and textures, which are a flavour of uniform for our purpose.
228 NSDictionary* uniformDefs = [configuration oo_dictionaryForKey:kOOUniformsKey];
229
230 NSArray* textureArray = [configuration oo_arrayForKey:kOOTextureObjectsKey];
231 if (textureArray == nil) {
232 NSArray* textureSpecs = [configuration oo_arrayForKey:kOOTexturesKey];
233 if (textureSpecs != nil) {
234 textureArray = [self loadTexturesFromArray:textureSpecs unitCount:textureUnits];
235 }
236 }
237
238 uniforms = [[NSMutableDictionary alloc] initWithCapacity:[uniformDefs count] + [textureArray count]];
239 [self addUniformsFromDictionary:uniformDefs withBindingTarget:target];
240 [self addTexturesFromArray:textureArray unitCount:textureUnits];
241 }
242
243 if (OK) {
244 // write gloss and gamma correction preference to the uniforms dictionary
245
246 if (![uniforms objectForKey:@"uGloss"]) {
247 float gloss = OOClamp_0_1_f([configuration oo_floatForKey:@"gloss" defaultValue:0.5f]);
248 [self setUniform:@"uGloss" floatValue:gloss];
249 }
250
251 if (![uniforms objectForKey:@"uGammaCorrect"]) {
252 BOOL gammaCorrect = [configuration oo_boolForKey:@"gamma_correct"
253 defaultValue:![[NSUserDefaults standardUserDefaults] boolForKey:@"no-gamma-correct"]];
254 [self setUniform:@"uGammaCorrect" floatValue:(float)gammaCorrect];
255 }
256 }
257
258 if (!OK) {
259 [self release];
260 self = nil;
261 }
262 return self;
263}
264
265- (void)dealloc
266{
267 uint32_t i;
268
269 [self willDealloc];
270
271 [shaderProgram release];
272 [uniforms release];
273
274 if (textures != NULL) {
275 for (i = 0; i != texCount; ++i) {
276 [textures[i] release];
277 }
278 free(textures);
279 }
280
281 [bindingTarget release];
282
283 [super dealloc];
284}
285
286- (BOOL)bindUniform:(NSString*)uniformName
287 toObject:(id<OOWeakReferenceSupport>)source
288 property:(SEL)selector
289 convertOptions:(OOUniformConvertOptions)options
290{
291 OOShaderUniform* uniform = nil;
292
293 if (uniformName == nil)
294 return NO;
295
296 uniform = [[OOShaderUniform alloc] initWithName:uniformName
297 shaderProgram:shaderProgram
298 boundToObject:source
299 property:selector
300 convertOptions:options];
301 if (uniform != nil) {
302 OOLog(@"shader.uniform.set", @"Set up uniform %@", uniform);
303 [uniforms setObject:uniform forKey:uniformName];
304 [uniform release];
305 return YES;
306 } else {
307 OOLog(@"shader.uniform.unSet", @"Did not set uniform \"%@\"", uniformName);
308 [uniforms removeObjectForKey:uniformName];
309 return NO;
310 }
311}
312
313- (BOOL)bindSafeUniform:(NSString*)uniformName
314 toObject:(id<OOWeakReferenceSupport>)target
315 propertyNamed:(NSString*)property
316 convertOptions:(OOUniformConvertOptions)options
317{
318 SEL selector = NULL;
319
320 selector = NSSelectorFromString(property);
321
322 if (selector != NULL && OOUniformBindingPermitted(property, target)) {
323 return [self bindUniform:uniformName
324 toObject:target
325 property:selector
326 convertOptions:options];
327 } else {
328 OOLog(@"shader.uniform.unpermittedMethod", @"Did not bind uniform \"%@\" to property -[%@ %@] - unpermitted method.", uniformName, [target class], property);
329 }
330
331 return NO;
332}
333
334- (void)setUniform:(NSString*)uniformName intValue:(int)value
335{
336 OOShaderUniform* uniform = nil;
337
338 if (uniformName == nil)
339 return;
340
341 uniform = [[OOShaderUniform alloc] initWithName:uniformName
342 shaderProgram:shaderProgram
343 intValue:value];
344 if (uniform != nil) {
345 OOLog(@"shader.uniform.set", @"Set up uniform %@", uniform);
346 [uniforms setObject:uniform forKey:uniformName];
347 [uniform release];
348 } else {
349 OOLog(@"shader.uniform.unSet", @"Did not set uniform \"%@\"", uniformName);
350 [uniforms removeObjectForKey:uniformName];
351 }
352}
353
354- (void)setUniform:(NSString*)uniformName floatValue:(float)value
355{
356 OOShaderUniform* uniform = nil;
357
358 if (uniformName == nil)
359 return;
360
361 uniform = [[OOShaderUniform alloc] initWithName:uniformName
362 shaderProgram:shaderProgram
363 floatValue:value];
364 if (uniform != nil) {
365 OOLog(@"shader.uniform.set", @"Set up uniform %@", uniform);
366 [uniforms setObject:uniform forKey:uniformName];
367 [uniform release];
368 } else {
369 OOLog(@"shader.uniform.unSet", @"Did not set uniform \"%@\"", uniformName);
370 [uniforms removeObjectForKey:uniformName];
371 }
372}
373
374- (void)setUniform:(NSString*)uniformName vectorValue:(GLfloat[4])value
375{
376 OOShaderUniform* uniform = nil;
377
378 if (uniformName == nil)
379 return;
380
381 uniform = [[OOShaderUniform alloc] initWithName:uniformName
382 shaderProgram:shaderProgram
383 vectorValue:value];
384 if (uniform != nil) {
385 OOLog(@"shader.uniform.set", @"Set up uniform %@", uniform);
386 [uniforms setObject:uniform forKey:uniformName];
387 [uniform release];
388 } else {
389 OOLog(@"shader.uniform.unSet", @"Did not set uniform \"%@\"", uniformName);
390 [uniforms removeObjectForKey:uniformName];
391 }
392}
393
394- (void)setUniform:(NSString*)uniformName vectorObjectValue:(id)value
395{
396 if (uniformName == nil)
397 return;
398
399 GLfloat vecArray[4];
400 if ([value isKindOfClass:[NSArray class]] && [value count] == 4) {
401 for (unsigned i = 0; i < 4; i++) {
402 vecArray[i] = OOFloatFromObject([value objectAtIndex:i], 0.0f);
403 }
404 } else {
406 vecArray[0] = vec.x;
407 vecArray[1] = vec.y;
408 vecArray[2] = vec.z;
409 vecArray[3] = 1.0;
410 }
411
412 OOShaderUniform* uniform = [[OOShaderUniform alloc] initWithName:uniformName
413 shaderProgram:shaderProgram
414 vectorValue:vecArray];
415 if (uniform != nil) {
416 OOLog(@"shader.uniform.set", @"Set up uniform %@", uniform);
417 [uniforms setObject:uniform forKey:uniformName];
418 [uniform release];
419 } else {
420 OOLog(@"shader.uniform.unSet", @"Did not set uniform \"%@\"", uniformName);
421 [uniforms removeObjectForKey:uniformName];
422 }
423}
424
425- (void)setUniform:(NSString*)uniformName quaternionValue:(Quaternion)value asMatrix:(BOOL)asMatrix
426{
427 OOShaderUniform* uniform = nil;
428
429 if (uniformName == nil)
430 return;
431
432 uniform = [[OOShaderUniform alloc] initWithName:uniformName
433 shaderProgram:shaderProgram
434 quaternionValue:value
435 asMatrix:asMatrix];
436 if (uniform != nil) {
437 OOLog(@"shader.uniform.set", @"Set up uniform %@", uniform);
438 [uniforms setObject:uniform forKey:uniformName];
439 [uniform release];
440 } else {
441 OOLog(@"shader.uniform.unSet", @"Did not set uniform \"%@\"", uniformName);
442 [uniforms removeObjectForKey:uniformName];
443 }
444}
445
446- (void)addUniformsFromDictionary:(NSDictionary*)uniformDefs withBindingTarget:(id<OOWeakReferenceSupport>)target
447{
448 NSString* name = nil;
449 id definition = nil;
450 id value = nil;
451 NSString* binding = nil;
452 NSString* type = nil;
453 GLfloat floatValue;
454 BOOL gotValue;
455 OOUniformConvertOptions convertOptions;
456 BOOL quatAsMatrix = YES;
457 GLfloat scale = 1.0;
458 uint32_t randomSeed;
459 RANROTSeed savedSeed;
460 NSArray* keys = nil;
461
462 if ([target respondsToSelector:@selector(randomSeedForShaders)]) {
463 randomSeed = [(id)target randomSeedForShaders];
464 } else {
465 randomSeed = (uint32_t)(uintptr_t)self;
466 }
467 savedSeed = RANROTGetFullSeed();
468 ranrot_srand(randomSeed);
469
470 keys = [[uniformDefs allKeys] sortedArrayUsingSelector:@selector(compare:)];
471 foreach (name, keys) {
472 gotValue = NO;
473 definition = [uniformDefs objectForKey:name];
474
475 type = nil;
476 value = nil;
477 binding = nil;
478
479 if ([definition isKindOfClass:[NSDictionary class]]) {
480 value = [(NSDictionary*)definition objectForKey:@"value"];
481 binding = [(NSDictionary*)definition oo_stringForKey:@"binding"];
482 type = [(NSDictionary*)definition oo_stringForKey:@"type"];
483 scale = [(NSDictionary*)definition oo_floatForKey:@"scale" defaultValue:1.0];
484 if (type == nil) {
485 if (value == nil && binding != nil)
486 type = @"binding";
487 else
488 type = @"float";
489 }
490 } else if ([definition isKindOfClass:[NSNumber class]]) {
491 value = definition;
492 type = @"float";
493 } else if ([definition isKindOfClass:[NSString class]]) {
494 if (OOIsNumberLiteral(definition, NO)) {
495 value = definition;
496 type = @"float";
497 } else {
498 binding = definition;
499 type = @"binding";
500 }
501 } else if ([definition isKindOfClass:[NSArray class]]) {
502 binding = definition;
503 type = @"vector";
504 }
505
506 // Transform random values to concrete values
507 if ([type isEqualToString:@"randomFloat"]) {
508 type = @"float";
509 value = [NSNumber numberWithFloat:randf() * scale];
510 } else if ([type isEqualToString:@"randomUnitVector"]) {
511 type = @"vector";
513 } else if ([type isEqualToString:@"randomVectorSpatial"]) {
514 type = @"vector";
516 } else if ([type isEqualToString:@"randomVectorRadial"]) {
517 type = @"vector";
519 } else if ([type isEqualToString:@"randomQuaternion"]) {
520 type = @"quaternion";
522 }
523
524 if ([type isEqualToString:@"float"] || [type isEqualToString:@"real"]) {
525 gotValue = YES;
526 if ([value respondsToSelector:@selector(floatValue)])
527 floatValue = [value floatValue];
528 else if ([value respondsToSelector:@selector(doubleValue)])
529 floatValue = [value doubleValue];
530 else if ([value respondsToSelector:@selector(intValue)])
531 floatValue = [value intValue];
532 else
533 gotValue = NO;
534
535 if (gotValue) {
536 [self setUniform:name floatValue:floatValue];
537 }
538 } else if ([type isEqualToString:@"int"] || [type isEqualToString:@"integer"] || [type isEqualToString:@"texture"]) {
539 /* "texture" is allowed as a synonym for "int" because shader
540 uniforms are mapped to texture units by specifying an integer
541 index.
542 uniforms = { diffuseMap = { type = texture; value = 0; }; };
543 means "bind uniform diffuseMap to texture unit 0" (which will
544 have the first texture in the textures array).
545 */
546 if ([value respondsToSelector:@selector(intValue)]) {
547 [self setUniform:name intValue:[value intValue]];
548 gotValue = YES;
549 }
550 } else if ([type isEqualToString:@"vector"]) {
551 [self setUniform:name vectorObjectValue:value];
552 gotValue = YES;
553 } else if ([type isEqualToString:@"quaternion"]) {
554 if ([definition isKindOfClass:[NSDictionary class]]) {
555 quatAsMatrix = [definition oo_boolForKey:@"asMatrix" defaultValue:quatAsMatrix];
556 }
557 [self setUniform:name
558 quaternionValue:OOQuaternionFromObject(value, kIdentityQuaternion)
559 asMatrix:quatAsMatrix];
560 gotValue = YES;
561 } else if (target != nil && [type isEqualToString:@"binding"]) {
562 if ([definition isKindOfClass:[NSDictionary class]]) {
563 convertOptions = 0;
564 if ([definition oo_boolForKey:@"clamped" defaultValue:NO])
565 convertOptions |= kOOUniformConvertClamp;
566 if ([definition oo_boolForKey:@"normalized" defaultValue:[definition oo_boolForKey:@"normalised" defaultValue:NO]]) {
567 convertOptions |= kOOUniformConvertNormalize;
568 }
569 if ([definition oo_boolForKey:@"asMatrix" defaultValue:YES])
570 convertOptions |= kOOUniformConvertToMatrix;
571 if (![definition oo_boolForKey:@"bindToSubentity" defaultValue:NO])
572 convertOptions |= kOOUniformBindToSuperTarget;
573 } else {
574 convertOptions = kOOUniformConvertDefaults;
575 }
576
577 [self bindSafeUniform:name toObject:target propertyNamed:binding convertOptions:convertOptions];
578 gotValue = YES;
579 }
580
581 if (!gotValue) {
582 OOLog(@"shader.uniform.badDescription", @"----- Warning: could not bind uniform \"%@\" for target %@ -- could not interpret definition:\n%@", name, target, definition);
583 }
584 }
585
586 RANROTSetFullSeed(savedSeed);
587}
588
589- (BOOL)doApply
590{
591 OOShaderUniform* uniform = nil;
592 uint32_t i;
593
595
596 [super doApply];
597 [shaderProgram apply];
598
599 for (i = 0; i != texCount; ++i) {
600 OOGL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
601 [textures[i] apply];
602 }
603 if (texCount > 1)
604 OOGL(glActiveTextureARB(GL_TEXTURE0_ARB));
605
606 @try {
607 foreach (uniform, [uniforms allValues]) {
608 [uniform apply];
609 }
610 }
611 @catch (id exception) {
612 }
613
614 return YES;
615}
616
617- (void)ensureFinishedLoading
618{
619 uint32_t i;
620
621 if (textures != NULL) {
622 for (i = 0; i != texCount; ++i) {
623 [textures[i] ensureFinishedLoading];
624 }
625 }
626}
627
628- (BOOL)isFinishedLoading
629{
630 uint32_t i;
631
632 if (textures != NULL) {
633 for (i = 0; i != texCount; ++i) {
634 if (![textures[i] isFinishedLoading])
635 return NO;
636 }
637 }
638
639 return YES;
640}
641
642- (void)unapplyWithNext:(OOMaterial*)next
643{
644 uint32_t i, count;
645
646 if (![next isKindOfClass:[OOShaderMaterial class]]) // Avoid redundant state change
647 {
649 [OOShaderProgram applyNone];
650
651 /* BUG: unapplyWithNext: was failing to clear texture state. If a
652 shader material was followed by a basic material (with no texture),
653 the shader's #0 texture would be used.
654 It is necessary to clear at least one texture for the case where a
655 shader material with textures is followed by a shader material
656 without textures, then a basic material.
657 -- Ahruman 2007-08-13
658 */
659 count = texCount ? texCount : 1;
660 for (i = 0; i != count; ++i) {
661 OOGL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
663 }
664 if (count != 1)
665 OOGL(glActiveTextureARB(GL_TEXTURE0_ARB));
666 }
667}
668
669- (void)setBindingTarget:(id<OOWeakReferenceSupport>)target
670{
671 [[uniforms allValues] makeObjectsPerformSelector:@selector(setBindingTarget:) withObject:target];
672 [bindingTarget release];
673 bindingTarget = [target weakRetain];
674}
675
676- (BOOL)permitSpecular
677{
678 return YES;
679}
680
681#ifdef OO_DEBUG_MONITOR_ENABLED
682- (NSSet*)allTextures
683{
684 return [NSSet setWithObjects:textures count:texCount];
685}
686#endif
687
688@end
689
690@implementation OOShaderMaterial (OOPrivate)
691
692- (NSArray*)loadTexturesFromArray:(NSArray*)textureSpecs unitCount:(GLuint)max
693{
694 GLuint i, count = (GLuint)MIN([textureSpecs count], (NSUInteger)max);
695 NSMutableArray* result = [NSMutableArray arrayWithCapacity:count];
696
697 for (i = 0; i < count; i++) {
698 id textureSpec = [textureSpecs objectAtIndex:i];
699 OOTexture* texture = [OOTexture textureWithConfiguration:textureSpec];
700 if (texture == nil)
701 texture = [OOTexture nullTexture];
702 [result addObject:texture];
703 }
704
705 return result;
706}
707
708- (void)addTexturesFromArray:(NSArray*)textureObjects unitCount:(GLuint)max
709{
710 // Allocate space for texture object name array
711 texCount = (uint32_t)MIN([textureObjects count], (NSUInteger)max);
712 if (texCount == 0)
713 return;
714
715 textures = malloc(texCount * sizeof *textures);
716 if (textures == NULL) {
717 texCount = 0;
718 return;
719 }
720
721 // Set up texture object names and appropriate uniforms
722 unsigned i;
723 for (i = 0; i != texCount; ++i) {
724 textures[i] = [textureObjects objectAtIndex:i];
725 [textures[i] retain];
726 }
727}
728
729@end
730
731static NSString* MacrosToString(NSDictionary* macros)
732{
733 NSMutableString* result = nil;
734 id key = nil, value = nil;
735
736 if (macros == nil)
737 return nil;
738
739 result = [NSMutableString string];
740 foreachkey(key, macros)
741 {
742 if (![key isKindOfClass:[NSString class]])
743 continue;
744 value = [macros objectForKey:key];
745
746 [result appendFormat:@"#define %@ %@\n", key, value];
747 }
748
749 if ([result length] == 0)
750 return nil;
751 [result appendString:@"\n\n"];
752 return result;
753}
754
755#endif
756
757/* Attempt to load fragment or vertex shader source from a file.
758 Returns YES if source was loaded or no shader was specified, and NO if an
759 external shader was specified but could not be found.
760*/
761static BOOL GetShaderSource(NSString* fileName, NSString* shaderType, NSString* prefix, NSString** outResult)
762{
763 NSString* result = nil;
764 NSArray* extensions = nil;
765 NSString* extension = nil;
766 NSString* nameWithExtension = nil;
767
768 if (fileName == nil)
769 return YES; // It's OK for one or the other of the shaders to be undefined.
770
771 result = [ResourceManager stringFromFilesNamed:fileName inFolder:@"Shaders"];
772 if (result == nil) {
773 extensions = [NSArray arrayWithObjects:shaderType, [shaderType substringToIndex:4], nil]; // vertex and vert, or fragment and frag
774
775 // Futureproofing -- in future, we may wish to support automatic selection between supported shader languages.
776 if (![fileName pathHasExtensionInArray:extensions]) {
777 foreach (extension, extensions) {
778 nameWithExtension = [fileName stringByAppendingPathExtension:extension];
779 result = [ResourceManager stringFromFilesNamed:nameWithExtension
780 inFolder:@"Shaders"];
781 if (result != nil)
782 break;
783 }
784 }
785 if (result == nil) {
786 OOLog(kOOLogFileNotFound, @"GLSL ERROR: failed to find %@ program %@.", shaderType, fileName);
787 return NO;
788 }
789 }
790
791 if (outResult != NULL)
792 *outResult = result;
793 return YES;
794}
NSDictionary * OOPropertyListFromVector(Vector value)
Vector OOVectorFromObject(id object, Vector defaultValue)
NSDictionary * OOPropertyListFromQuaternion(Quaternion value)
float OOFloatFromObject(id object, float defaultValue)
#define gDebugFlags
@ DEBUG_NO_SHADER_FALLBACK
OOINLINE float OOClamp_0_1_f(float value) INLINE_CONST_FUNC
#define foreachkey(VAR, DICT)
BOOL OOIsNumberLiteral(NSString *string, BOOL allowSpaces)
#define OOLogWARN(class, format,...)
Definition OOLogging.h:126
#define OOLogERR(class, format,...)
Definition OOLogging.h:125
void OOLogOutdent(void)
Definition OOLogging.m:354
#define OOLog(class, format,...)
Definition OOLogging.h:84
NSString *const kOOLogFileNotFound
Definition OOLogging.m:601
void OOLogIndent(void)
Definition OOLogging.m:345
#define OO_ENTER_OPENGL()
#define MIN(A, B)
Definition OOMaths.h:91
#define OOGL(statement)
Definition OOOpenGL.h:262
unsigned count
return nil
struct Quaternion Quaternion
OOINLINE Quaternion OORandomQuaternion(void) ALWAYS_INLINE_FUNC
static BOOL GetShaderSource(NSString *fileName, NSString *shaderType, NSString *prefix, NSString **outResult)
struct Vector Vector
const Vector kZeroVector
Definition OOVector.m:27
Vector OORandomUnitVector(void)
Definition OOVector.m:76
Vector OOVectorRandomRadial(OOScalar maxLength)
Definition OOVector.m:102
Vector OOVectorRandomSpatial(OOScalar maxLength)
Definition OOVector.m:89
OOINLINE Vector vector_multiply_scalar(Vector v, OOScalar s) INLINE_CONST_FUNC
Definition OOVector.h:180
BOOL OOUniformBindingPermitted(NSString *propertyName, id bindingTarget)
OOOpenGLExtensionManager * sharedManager()
void applyNone()
Definition OOTexture.m:263
id textureWithConfiguration:(id configuration)
Definition OOTexture.m:186
NSString * stringFromFilesNamed:inFolder:(NSString *fileName,[inFolder] NSString *folderName)
RANROTSeed RANROTGetFullSeed(void)
void ranrot_srand(uint32_t seed)
void RANROTSetFullSeed(RANROTSeed seed)
struct RANROTSeed RANROTSeed
OOScalar x
Definition OOVector.h:32
OOScalar y
Definition OOVector.h:33
OOScalar z
Definition OOVector.h:34