Oolite
Loading...
Searching...
No Matches
OOTextureLoader.m
Go to the documentation of this file.
1/*
2
3OOTextureLoader.m
4
5
6Copyright (C) 2007-2014 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 "OOTextureLoader.h"
31#import "OODebugStandards.h"
33#import "OOMaths.h"
37#import "OOTextureScaling.h"
38#import "ResourceManager.h"
39#import "Universe.h"
40#include <stdlib.h>
41
42#define DUMP_CONVERTED_CUBE_MAPS 0
43
44enum {
45 // Thresholds for reduced-detail texture shrinking in different circumstances.
51};
52
53static unsigned sGLMaxSize;
54static uint32_t sUserMaxSize;
55static BOOL sReducedDetail;
56static BOOL sHaveNPOTTextures = NO; // TODO: support "true" non-power-of-two textures.
57static BOOL sHaveSetUp = NO;
58
59@interface OOTextureLoader (OOPrivate)
60
61+ (void)setUp;
62
63- (void)applySettings;
64- (void)getDesiredWidth:(OOPixMapDimension*)outDesiredWidth andHeight:(OOPixMapDimension*)outDesiredHeight;
65
66@end
67
68@implementation OOTextureLoader
69
70+ (id)loaderWithPath:(NSString*)inPath options:(uint32_t)options
71{
72 NSString* extension = nil;
73 id result = nil;
74
75 if (EXPECT_NOT(inPath == nil))
76 return nil;
78 [self setUp];
79
80 // Get reduced detail setting (every time, in case it changes; we don't want to call through to Universe on the loading thread in case the implementation becomes non-trivial).
81 sReducedDetail = [UNIVERSE reducedDetail];
82
83 // Get a suitable loader. FIXME -- this should sniff the data instead of relying on extensions.
84 extension = [[inPath pathExtension] lowercaseString];
85 if ([extension isEqualToString:@"png"]) {
86 result = [[[OOPNGTextureLoader alloc] initWithPath:inPath options:options] autorelease];
87 } else {
88 OOLog(@"texture.load.unknownType", @"Can't use %@ as a texture - extension \"%@\" does not identify a known type.", inPath, extension);
89 }
90
91 if (result != nil) {
92 if (![[OOAsyncWorkManager sharedAsyncWorkManager] addTask:result priority:kOOAsyncPriorityMedium])
93 result = nil;
94 }
95
96 return result;
97}
98
99+ (id)loaderWithTextureSpecifier:(id)specifier extraOptions:(uint32_t)extraOptions folder:(NSString*)folder
100{
101 NSString* name = nil;
102 NSString* path = nil;
103 uint32_t options = 0;
104
105 if (!OOInterpretTextureSpecifier(specifier, &name, &options, NULL, NULL, NO))
106 return nil;
107 options |= extraOptions;
109 if (path == nil) {
110 if (!(options & kOOTextureNoFNFMessage)) {
111 OOLogWARN(kOOLogFileNotFound, @"Could not find texture file \"%@\".", name);
112 OOStandardsError(@"Texture file not found");
113 }
114 return nil;
115 }
116
117 return [self loaderWithPath:path options:options];
118}
119
120- (id)initWithPath:(NSString*)inPath options:(uint32_t)options
121{
122 self = [super init];
123 if (self == nil)
124 return nil;
125
126 _path = [inPath copy];
127 if (EXPECT_NOT(_path == nil)) {
128 [self release];
129 return nil;
130 }
131
132 _options = options;
133
135
137 _avoidShrinking = (options & kOOTextureNoShrink) != 0;
141 } else if (options & kOOTextureExtraShrink) {
144 } else {
146 }
147#if OO_TEXTURE_CUBE_MAP
148 _allowCubeMap = (options & kOOTextureAllowCubeMap) != 0;
149#endif
150
151 if (options & kOOTextureExtractChannelMask) {
152 _extractChannel = YES;
153 switch (options & kOOTextureExtractChannelMask) {
156 break;
157
160 break;
161
164 break;
165
168 break;
169
170 default:
171 OOLogERR(@"texture.load.unknownExtractChannelMask", @"Unknown texture extract channel mask (0x%.4X). This is an internal error, please report it.", options & kOOTextureExtractChannelMask);
172 _extractChannel = NO;
173 }
174 }
175
176 return self;
177}
178
179- (void)dealloc
180{
181 [_path autorelease];
182 _path = nil;
183 free(_data);
184 _data = NULL;
185
186 [super dealloc];
187}
188
190{
191 NSString* state = nil;
192
193 if (_ready) {
194 if (_data != NULL)
195 state = @"ready";
196 else
197 state = @"failed";
198 } else {
199 state = @"loading";
200#if INSTRUMENT_TEXTURE_LOADING
201 if (debugHasLoaded)
202 state = @"loaded";
203#endif
204 }
205
206 return [NSString stringWithFormat:@"{%@ -- %@}", _path, state];
207}
208
210{
211 return [_path lastPathComponent];
212}
213
214- (NSString*)path
215{
216 return _path;
217}
218
219- (BOOL)isReady
220{
221 return _ready;
222}
223
224- (BOOL)getResult:(OOPixMap*)result
225 format:(OOTextureDataFormat*)outFormat
226 originalWidth:(uint32_t*)outWidth
227 originalHeight:(uint32_t*)outHeight
228{
229 NSParameterAssert(result != NULL && outFormat != NULL);
230
231 BOOL OK = YES;
232
233 if (!_ready) {
235 }
236 if (_data == NULL)
237 OK = NO;
238
239 if (OK) {
241 _data = NULL;
242 *outFormat = _format;
243 OK = OOIsValidPixMap(*result);
244 if (outWidth != NULL)
245 *outWidth = _originalWidth;
246 if (outHeight != NULL)
247 *outHeight = _originalHeight;
248 }
249
250 if (!OK) {
251 *result = kOONullPixMap;
252 *outFormat = kOOTextureDataInvalid;
253 }
254
255 return OK;
256}
257
258- (NSString*)cacheKey
259{
260 return [NSString stringWithFormat:@"%@:0x%.4X", [[self path] lastPathComponent], _options];
261}
262
267
268+ (void)setUp
269{
270 // Load two maximum sizes - graphics hardware limit and user-specified limit.
271 GLint maxSize;
272 OOGL(glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxSize));
273 sGLMaxSize = MAX(maxSize, 64);
274 OOLog(@"texture.load.rescale.maxSize", @"GL maximum texture size: %u", sGLMaxSize);
275
276 // Why 0x80000000? Because it's the biggest number OORoundUpToPowerOf2() can handle.
277 sUserMaxSize = [[NSUserDefaults standardUserDefaults] oo_unsignedIntForKey:@"max-texture-size" defaultValue:0x80000000];
278 if (sUserMaxSize < 0x80000000)
279 OOLog(@"texture.load.rescale.maxSize", @"User maximum texture size: %u", sUserMaxSize);
282
283 sHaveSetUp = YES;
284}
285
286/*** Methods performed on the loader thread. ***/
287
289{
290 @try {
291 OOLog(@"texture.load.asyncLoad", @"Loading texture %@", [_path lastPathComponent]);
292
293 [self loadTexture];
294
295 // Catch an error I've seen but not diagnosed yet.
296 if (_data != NULL && OOTextureComponentsForFormat(_format) == 0) {
297 OOLog(@"texture.load.failed.internalError", @"Texture loader internal error for %@: data is non-null but data format is invalid (%u).", _path, _format);
298 free(_data);
299 _data = NULL;
300 }
301
302 if (_data != NULL)
303 [self applySettings];
304
305 OOLog(@"texture.load.asyncLoad.done", @"%@", @"Loading complete.");
306 }
307 @catch (NSException* exception) {
308 OOLog(@"texture.load.asyncLoad.exception", @"***** Exception loading texture %@: %@ (%@).", _path, [exception name], [exception reason]);
309
310 // Be sure to signal load failure.
311 free(_data);
312 _data = NULL;
313 }
314}
315
317{
318 // Generate mip maps for each cube face.
319 NSParameterAssert(_data != NULL);
320
321 uint8_t components = OOTextureComponentsForFormat(_format);
322 size_t srcSideSize = _width * _width * components; // Space for one side without mip-maps.
323 size_t newSideSize = srcSideSize * 4 / 3; // Space for one side with mip-maps.
324 newSideSize = (newSideSize + 15) & ~15; // Round up to multiple of 16 bytes.
325 size_t newSize = newSideSize * 6; // Space for all six sides.
326
327 void* newData = malloc(newSize);
328 if (EXPECT_NOT(newData == NULL)) {
329 _generateMipMaps = NO;
331 return;
332 }
333
334 unsigned i;
335 for (i = 0; i < 6; i++) {
336 void* srcBytes = ((uint8_t*)_data) + srcSideSize * i;
337 void* dstBytes = ((uint8_t*)newData) + newSideSize * i;
338
339 memcpy(dstBytes, srcBytes, srcSideSize);
341 }
342
343 free(_data);
344 _data = newData;
345}
346
348{
349 OOPixMapDimension desiredWidth, desiredHeight;
350 BOOL rescale;
351 size_t newSize;
352 uint8_t components;
353 OOPixMap pixMap;
354
355 components = OOTextureComponentsForFormat(_format);
356
357 // Apply defaults.
358 if (_originalWidth == 0)
359 _originalWidth = _width;
360 if (_originalHeight == 0)
361 _originalHeight = _height;
362 if (_rowBytes == 0)
363 _rowBytes = _width * components;
364
365 pixMap = OOMakePixMap(_data, _width, _height, components, _rowBytes, 0);
366
367 if (_extractChannel) {
368 if (OOExtractPixMapChannel(&pixMap, _extractChannelIndex, NO)) {
369 _format = kOOTextureDataGrayscale;
370 components = 1;
371 } else {
372 OOLogWARN(@"texture.load.extractChannel.invalid", @"Cannot extract channel from texture \"%@\"", [_path lastPathComponent]);
373 }
374 }
375
376 [self getDesiredWidth:&desiredWidth andHeight:&desiredHeight];
377
378 if (_isCubeMap && !OOCubeMapsAvailable()) {
379 OOPixMapToRGBA(&pixMap);
380 desiredHeight = MIN(desiredWidth * 2, 512U);
381 if (sReducedDetail && desiredHeight > kCubeShrinkThreshold)
382 desiredHeight /= 2;
383 desiredWidth = desiredHeight * 2;
384
385 OOPixMap converted = OOConvertCubeMapToLatLong(pixMap, desiredHeight, _generateMipMaps);
386 OOFreePixMap(&pixMap);
387 pixMap = converted;
388 _isCubeMap = NO;
389
390#if DUMP_CONVERTED_CUBE_MAPS
391 OODumpPixMap(pixMap, [NSString stringWithFormat:@"converted cube map %@", [[_path lastPathComponent] stringByDeletingPathExtension]]);
392#endif
393 }
394
395 // Rescale if needed.
396 rescale = (_width != desiredWidth || _height != desiredHeight);
397 if (rescale) {
398 BOOL leaveSpaceForMipMaps = _generateMipMaps;
399#if OO_TEXTURE_CUBE_MAP
400 if (_isCubeMap)
401 leaveSpaceForMipMaps = NO;
402#endif
403
404 OOLog(@"texture.load.rescale", @"Rescaling texture \"%@\" from %u x %u to %u x %u.", [_path lastPathComponent], pixMap.width, pixMap.height, desiredWidth, desiredHeight);
405
406 pixMap = OOScalePixMap(pixMap, desiredWidth, desiredHeight, leaveSpaceForMipMaps);
407 if (EXPECT_NOT(!OOIsValidPixMap(pixMap)))
408 return;
409
410 _data = pixMap.pixels;
411 _width = pixMap.width;
412 _height = pixMap.height;
413 _rowBytes = pixMap.rowBytes;
414 }
415
416#if OO_TEXTURE_CUBE_MAP
417 if (_isCubeMap) {
418 if (_generateMipMaps) {
420 }
421 return;
422 }
423#endif
424
425 // Generate mip maps if needed.
426 if (_generateMipMaps) {
427 // Make space if needed.
428 newSize = desiredWidth * components * desiredHeight;
429 newSize = (newSize * 4) / 3;
430 // +1 to fix overrun valgrind spotted - CIM
431 _generateMipMaps = OOExpandPixMap(&pixMap, newSize + 1);
432
433 _data = pixMap.pixels;
434 _width = pixMap.width;
435 _height = pixMap.height;
436 _rowBytes = pixMap.rowBytes;
437 }
438 if (_generateMipMaps) {
439 OOGenerateMipMaps(_data, _width, _height, _format);
440 }
441
442 // All done.
443}
444
445- (void)getDesiredWidth:(OOPixMapDimension*)outDesiredWidth andHeight:(OOPixMapDimension*)outDesiredHeight
446{
447 OOPixMapDimension desiredWidth, desiredHeight;
448
449 // Work out appropriate final size for textures.
450 if (!_noScalingWhatsoever) {
451 // Cube maps are six times as high as they are wide, and we need to preserve that.
452 if (_allowCubeMap && _height == _width * 6) {
453 _isCubeMap = YES;
454
455 desiredWidth = OORoundUpToPowerOf2_PixMap((2 * _width) / 3);
456 desiredWidth = MIN(desiredWidth, sGLMaxSize / 8);
457 if (sReducedDetail) {
458 if (256 < desiredWidth)
459 desiredWidth /= 2;
460 }
461 desiredWidth = MIN(desiredWidth, sUserMaxSize / 4);
462
463 desiredHeight = desiredWidth * 6;
464 } else {
465 if (!sHaveNPOTTextures) {
466 // Round to nearest power of two. NOTE: this is duplicated in OOTextureVerifierStage.m.
467 desiredWidth = OORoundUpToPowerOf2_PixMap((2 * _width) / 3);
468 desiredHeight = OORoundUpToPowerOf2_PixMap((2 * _height) / 3);
469 } else {
470 desiredWidth = _width;
471 desiredHeight = _height;
472 }
473
474 desiredWidth = MIN(desiredWidth, sGLMaxSize);
475 desiredHeight = MIN(desiredHeight, sGLMaxSize);
476
477 if (!_avoidShrinking) {
478 if (sReducedDetail) {
479 if (_shrinkThreshold < desiredWidth)
480 desiredWidth /= 2;
481 if (_shrinkThreshold < desiredHeight)
482 desiredHeight /= 2;
483 }
484
485 desiredWidth = MIN(desiredWidth, _maxSize);
486 desiredHeight = MIN(desiredHeight, _maxSize);
487 }
488 }
489 } else {
490 desiredWidth = _width;
491 desiredHeight = _height;
492 }
493
494 if (outDesiredWidth != NULL)
495 *outDesiredWidth = desiredWidth;
496 if (outDesiredHeight != NULL)
497 *outDesiredHeight = desiredHeight;
498}
499
501{
502 _ready = YES;
503}
504
505@end
@ kOOAsyncPriorityMedium
OOPixMap OOConvertCubeMapToLatLong(OOPixMap sourcePixMap, OOPixMapDimension height, BOOL leaveSpaceForMipMaps)
void OOStandardsError(NSString *message)
OOINLINE INLINE_CONST_FUNC uint32_t OORoundUpToPowerOf2_32(uint32_t value)
#define EXPECT_NOT(x)
#define OOLogWARN(class, format,...)
Definition OOLogging.h:126
#define OOLogERR(class, format,...)
Definition OOLogging.h:125
#define OOLogGenericSubclassResponsibility()
Definition OOLogging.h:141
#define OOLog(class, format,...)
Definition OOLogging.h:84
NSString *const kOOLogFileNotFound
Definition OOLogging.m:601
#define MAX(A, B)
Definition OOMaths.h:94
#define MIN(A, B)
Definition OOMaths.h:91
#define OOGL(statement)
Definition OOOpenGL.h:262
BOOL OOExtractPixMapChannel(OOPixMap *ioPixMap, uint8_t channelIndex, BOOL compactWhenDone)
BOOL OOPixMapToRGBA(OOPixMap *ioPixMap)
void OOFreePixMap(OOPixMap *ioPixMap)
Definition OOPixMap.m:80
uint32_t OOPixMapDimension
Definition OOPixMap.h:32
void OODumpPixMap(OOPixMap pixMap, NSString *name)
Definition OOPixMap.m:140
const OOPixMap kOONullPixMap
Definition OOPixMap.m:30
#define OORoundUpToPowerOf2_PixMap
Definition OOPixMap.h:34
OOPixMap OOMakePixMap(void *pixels, OOPixMapDimension width, OOPixMapDimension height, OOPixMapFormat format, size_t rowBytes, size_t bufferSize)
Definition OOPixMap.m:44
BOOL OOIsValidPixMap(OOPixMap pixMap)
Definition OOPixMap.m:39
BOOL OOExpandPixMap(OOPixMap *ioPixMap, size_t desiredSize)
Definition OOPixMap.m:125
return nil
static unsigned sGLMaxSize
static BOOL sHaveSetUp
@ kCubeShrinkThreshold
@ kNeverShrinkThreshold
@ kExtraShrinkMaxSize
@ kExtraShrinkThreshold
@ kDefaultShrinkThreshold
static BOOL sReducedDetail
static uint32_t sUserMaxSize
static BOOL sHaveNPOTTextures
OOPixMap OOScalePixMap(OOPixMap srcPixMap, OOPixMapDimension dstWidth, OOPixMapDimension dstHeight, BOOL leaveSpaceForMipMaps)
BOOL OOGenerateMipMaps(void *textureBytes, OOPixMapDimension width, OOPixMapDimension height, OOPixMapFormat format)
BOOL OOCubeMapsAvailable(void)
Definition OOTexture.m:643
uint8_t OOTextureComponentsForFormat(OOTextureDataFormat format)
Definition OOTexture.m:624
@ kOOTextureExtractChannelA
Definition OOTexture.h:70
@ kOOTextureExtractChannelB
Definition OOTexture.h:69
@ kOOTextureNoFNFMessage
Definition OOTexture.h:58
@ kOOTextureNoShrink
Definition OOTexture.h:53
@ kOOTextureExtractChannelMask
Definition OOTexture.h:65
@ kOOTextureMinFilterLinear
Definition OOTexture.h:47
@ kOOTextureAllowCubeMap
Definition OOTexture.h:61
@ kOOTextureMinFilterMask
Definition OOTexture.h:72
@ kOOTextureMinFilterMipMap
Definition OOTexture.h:48
@ kOOTextureNeverScale
Definition OOTexture.h:59
@ kOOTextureExtraShrink
Definition OOTexture.h:54
@ kOOTextureExtractChannelG
Definition OOTexture.h:68
@ kOOTextureExtractChannelR
Definition OOTexture.h:67
@ kOOTextureDataGrayscale
Definition OOTexture.h:104
@ kOOTextureDataInvalid
Definition OOTexture.h:101
OOPixMapFormat OOTextureDataFormat
Definition OOTexture.h:107
BOOL OOInterpretTextureSpecifier(id specifier, NSString **outName, OOTextureFlags *outOptions, float *outAnisotropy, float *outLODBias, BOOL ignoreExtract)
Definition OOTexture.m:648
void waitForTaskToComplete:(id< OOAsyncWorkTask > task)
OOAsyncWorkManager * sharedAsyncWorkManager()
NSString * cacheKey()
OOTextureDataFormat _format
uint32_t _originalWidth
NSString * descriptionComponents()
uint8_t _extractChannelIndex
NSString * shortDescriptionComponents()
OOTextureFlags _options
uint32_t _shrinkThreshold
id loaderWithPath:options:(NSString *path,[options] uint32_t options)
uint32_t _originalHeight
uint8_t _noScalingWhatsoever
void getDesiredWidth:andHeight:(OOPixMapDimension *outDesiredWidth, [andHeight] OOPixMapDimension *outDesiredHeight)
NSString * pathForFileNamed:inFolder:(NSString *fileName,[inFolder] NSString *folderName)
OOPixMapDimension height
Definition OOPixMap.h:45
size_t rowBytes
Definition OOPixMap.h:47
void * pixels
Definition OOPixMap.h:44
OOPixMapDimension width
Definition OOPixMap.h:45