diff --git a/base/sources/backends/android_net.c b/base/sources/backends/android_net.c index 489bf6a2..a79804d4 100644 --- a/base/sources/backends/android_net.c +++ b/base/sources/backends/android_net.c @@ -3,13 +3,14 @@ #include #include #include -#include #include +#include ANativeActivity *iron_android_get_activity(void); jclass iron_android_find_class(JNIEnv *env, const char *name); -void iron_net_request(const char *url_base, const char *url_path, const char *data, int port, int method, iron_https_callback_t callback, void *callbackdata, const char *dst_path) { +void iron_net_request(const char *url_base, const char *url_path, const char *data, int port, int method, iron_https_callback_t callback, void *callbackdata, + const char *dst_path) { ANativeActivity *activity = iron_android_get_activity(); JNIEnv *env; JavaVM *vm = iron_android_get_activity()->vm; @@ -18,9 +19,10 @@ void iron_net_request(const char *url_base, const char *url_path, const char *da jstring jurl_base = (*env)->NewStringUTF(env, url_base); jstring jurl_path = (*env)->NewStringUTF(env, url_path); - jbyteArray bytes_array = (jbyteArray)((*env)->CallStaticObjectMethod( - env, activityClass, (*env)->GetStaticMethodID(env, activityClass, "androidHttpRequest", "(Ljava/lang/String;Ljava/lang/String;)[B"), jurl_base, - jurl_path)); + jbyteArray bytes_array = (jbyteArray)((*env)->CallStaticObjectMethod(env, activityClass, + (*env)->GetStaticMethodID(env, activityClass, "androidHttpRequest", + "(Ljava/lang/String;Ljava/lang/String;)[B"), + jurl_base, jurl_path)); if (bytes_array == NULL) { callback(NULL, callbackdata); @@ -50,7 +52,6 @@ void iron_net_request(const char *url_base, const char *url_path, const char *da (*vm)->DetachCurrentThread(vm); } -void iron_net_update() { -} +void iron_net_update() {} volatile uint64_t iron_net_bytes_downloaded = 0; diff --git a/base/sources/backends/apple_net.m b/base/sources/backends/apple_net.m index 8decdc3c..527b01e2 100644 --- a/base/sources/backends/apple_net.m +++ b/base/sources/backends/apple_net.m @@ -1,34 +1,38 @@ -#include #import +#include #import -volatile uint64_t iron_net_bytes_downloaded = 0; -static NSURLSession *download_session = nil; +volatile uint64_t iron_net_bytes_downloaded = 0; +static NSURLSession *download_session = nil; @interface IronDownloadDelegate : NSObject @end @implementation IronDownloadDelegate -- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask + didWriteData:(int64_t)bytesWritten + totalBytesWritten:(int64_t)totalBytesWritten + totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { iron_net_bytes_downloaded += bytesWritten; } - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { NSString *dstPath = objc_getAssociatedObject(downloadTask, @"dst_path"); if (dstPath) { - NSError *error = nil; - NSURL *destURL = [NSURL fileURLWithPath:dstPath]; + NSError *error = nil; + NSURL *destURL = [NSURL fileURLWithPath:dstPath]; [[NSFileManager defaultManager] moveItemAtURL:location toURL:destURL error:&error]; // todo if ([dstPath hasSuffix:@"sd_vulkan"] || [dstPath hasSuffix:@"sd_cpu"]) { - NSDictionary *attrs = @{ NSFilePosixPermissions : @0755 }; - NSError *chmodError = nil; + NSDictionary *attrs = @{NSFilePosixPermissions : @0755}; + NSError *chmodError = nil; [[NSFileManager defaultManager] setAttributes:attrs ofItemAtPath:dstPath error:&chmodError]; } } else { - NSData *fileData = [NSData dataWithContentsOfURL:location options:NSDataReadingMappedIfSafe error:nil]; + NSData *fileData = [NSData dataWithContentsOfURL:location options:NSDataReadingMappedIfSafe error:nil]; NSMutableData *memoryData = objc_getAssociatedObject(downloadTask, @"memoryData"); [memoryData appendData:fileData]; } @@ -36,12 +40,12 @@ static NSURLSession *download_session = nil; - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSURLSessionDownloadTask *downloadTask = (NSURLSessionDownloadTask *)task; - NSValue *cbVal = objc_getAssociatedObject(task, @"callback"); - NSValue *dataVal = objc_getAssociatedObject(task, @"callbackdata"); - NSString *dstPath = objc_getAssociatedObject(task, @"dst_path"); - NSMutableData *memoryData = objc_getAssociatedObject(task, @"memoryData"); - iron_https_callback_t callback = cbVal ? [cbVal pointerValue] : NULL; - void *callbackdata = dataVal ? [dataVal pointerValue] : NULL; + NSValue *cbVal = objc_getAssociatedObject(task, @"callback"); + NSValue *dataVal = objc_getAssociatedObject(task, @"callbackdata"); + NSString *dstPath = objc_getAssociatedObject(task, @"dst_path"); + NSMutableData *memoryData = objc_getAssociatedObject(task, @"memoryData"); + iron_https_callback_t callback = cbVal ? [cbVal pointerValue] : NULL; + void *callbackdata = dataVal ? [dataVal pointerValue] : NULL; dispatch_async(dispatch_get_main_queue(), ^{ if (dstPath) { callback(NULL, callbackdata); @@ -57,27 +61,26 @@ static NSURLSession *download_session = nil; @end -void iron_net_request(const char *url_base, const char *url_path, const char *data, int port, int method, iron_https_callback_t callback, void *callbackdata, const char *dst_path) { +void iron_net_request(const char *url_base, const char *url_path, const char *data, int port, int method, iron_https_callback_t callback, void *callbackdata, + const char *dst_path) { if (!download_session) { NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; - NSOperationQueue *queue = [[NSOperationQueue alloc] init]; - queue.qualityOfService = NSQualityOfServiceUtility; + NSOperationQueue *queue = [[NSOperationQueue alloc] init]; + queue.qualityOfService = NSQualityOfServiceUtility; static IronDownloadDelegate *delegate = nil; - static dispatch_once_t onceToken; + static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ delegate = [[IronDownloadDelegate alloc] init]; }); download_session = [NSURLSession sessionWithConfiguration:config delegate:delegate delegateQueue:queue]; } - NSString *urlStr = [NSString stringWithFormat:@"https://%@:%d/%@", - [NSString stringWithUTF8String:url_base], - port, - [NSString stringWithUTF8String:url_path]]; - NSURL *url = [NSURL URLWithString:urlStr]; + NSString *urlStr = + [NSString stringWithFormat:@"https://%@:%d/%@", [NSString stringWithUTF8String:url_base], port, [NSString stringWithUTF8String:url_path]]; + NSURL *url = [NSURL URLWithString:urlStr]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; - request.HTTPMethod = (method == IRON_HTTPS_GET) ? @"GET" : @"POST"; + request.HTTPMethod = (method == IRON_HTTPS_GET) ? @"GET" : @"POST"; NSURLSessionDownloadTask *task = [download_session downloadTaskWithRequest:request]; objc_setAssociatedObject(task, @"callback", [NSValue valueWithPointer:callback], OBJC_ASSOCIATION_RETAIN_NONATOMIC); @@ -89,5 +92,4 @@ void iron_net_request(const char *url_base, const char *url_path, const char *da [task resume]; } -void iron_net_update() { -} +void iron_net_update() {} diff --git a/base/sources/backends/direct3d12_gpu.c b/base/sources/backends/direct3d12_gpu.c index 6c9fa91c..56fe2702 100644 --- a/base/sources/backends/direct3d12_gpu.c +++ b/base/sources/backends/direct3d12_gpu.c @@ -12,7 +12,7 @@ #include #include -static ID3D12Device *device = NULL; +static ID3D12Device *device = NULL; static ID3D12CommandQueue *queue; static IDXGISwapChain *window_swapchain; static ID3D12RootSignature *root_signature = NULL; diff --git a/base/sources/backends/ios_system.m b/base/sources/backends/ios_system.m index 4a566e6b..63cefb36 100644 --- a/base/sources/backends/ios_system.m +++ b/base/sources/backends/ios_system.m @@ -498,12 +498,15 @@ void importFile(NSURL *url) { file_path = [file_path stringByAppendingPathComponent:suggestedName]; [url startAccessingSecurityScopedResource]; NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil]; - [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingWithoutChanges error:nil byAccessor:^(NSURL *new_url) { - if ([[NSFileManager defaultManager] fileExistsAtPath:file_path]) { - [[NSFileManager defaultManager] removeItemAtPath:file_path error:nil]; - } - [[NSFileManager defaultManager] copyItemAtURL:new_url toURL:[NSURL fileURLWithPath:file_path] error:nil]; - }]; + [coordinator coordinateReadingItemAtURL:url + options:NSFileCoordinatorReadingWithoutChanges + error:nil + byAccessor:^(NSURL *new_url) { + if ([[NSFileManager defaultManager] fileExistsAtPath:file_path]) { + [[NSFileManager defaultManager] removeItemAtPath:file_path error:nil]; + } + [[NSFileManager defaultManager] copyItemAtURL:new_url toURL:[NSURL fileURLWithPath:file_path] error:nil]; + }]; [url stopAccessingSecurityScopedResource]; const char *cpath = [file_path cStringUsingEncoding:NSUTF8StringEncoding]; diff --git a/base/sources/backends/linux_system.c b/base/sources/backends/linux_system.c index 98d35be4..aa602660 100644 --- a/base/sources/backends/linux_system.c +++ b/base/sources/backends/linux_system.c @@ -1495,12 +1495,12 @@ void iron_gamepad_rumble(int gamepad, float left, float right) {} #include extern void (*iron_save_and_quit)(bool); static bool iron_gtk_setlocale_disabled = false; -void iron_gtk_disable_setlocale() { - if (iron_gtk_setlocale_disabled) { - return; - } - gtk_disable_setlocale(); - iron_gtk_setlocale_disabled = true; +void iron_gtk_disable_setlocale() { + if (iron_gtk_setlocale_disabled) { + return; + } + gtk_disable_setlocale(); + iron_gtk_setlocale_disabled = true; } #endif diff --git a/base/sources/backends/macos_system.m b/base/sources/backends/macos_system.m index 56f08158..e29c7bd5 100644 --- a/base/sources/backends/macos_system.m +++ b/base/sources/backends/macos_system.m @@ -1191,9 +1191,9 @@ void deviceRemoved(void *inContext, IOReturn inResult, void *inSender, IOHIDDevi extern void (*iron_save_and_quit)(bool); bool _save_and_quit_callback_internal() { - bool save = false; + bool save = false; NSString *title = [window title]; - bool dirty = [title rangeOfString:@"* - ArmorPaint"].location != NSNotFound; + bool dirty = [title rangeOfString:@"* - ArmorPaint"].location != NSNotFound; if (dirty) { NSAlert *alert = [[NSAlert alloc] init]; [alert setMessageText:@"Project has been modified, save changes?"]; @@ -1220,16 +1220,16 @@ volatile int iron_exec_async_done = 1; void iron_exec_async(const char *path, char *argv[]) { iron_exec_async_done = 0; - NSTask *task = [[NSTask alloc] init]; + NSTask *task = [[NSTask alloc] init]; [task setLaunchPath:[NSString stringWithUTF8String:path]]; NSMutableArray *args = [NSMutableArray array]; - int i = 1; + int i = 1; while (argv[i] != NULL) { [args addObject:[NSString stringWithUTF8String:argv[i]]]; i++; } [task setArguments:args]; - task.terminationHandler = ^(NSTask *t){ + task.terminationHandler = ^(NSTask *t) { iron_exec_async_done = 1; }; [task launch]; diff --git a/base/sources/backends/metal_gpu.m b/base/sources/backends/metal_gpu.m index 6e2125a0..b0132268 100644 --- a/base/sources/backends/metal_gpu.m +++ b/base/sources/backends/metal_gpu.m @@ -11,10 +11,10 @@ id get_metal_layer(void); id get_metal_device(void); id get_metal_queue(void); -static id command_buffer = nil; -static id command_encoder = nil; -static id argument_encoder = nil; -static id argument_buffer = nil; +static id command_buffer = nil; +static id command_encoder = nil; +static id argument_encoder = nil; +static id argument_buffer = nil; static id drawable; static id linear_sampler; static id point_sampler; diff --git a/base/sources/backends/webgpu_gpu.c b/base/sources/backends/webgpu_gpu.c index ad17c214..69cbaee1 100644 --- a/base/sources/backends/webgpu_gpu.c +++ b/base/sources/backends/webgpu_gpu.c @@ -672,7 +672,7 @@ void gpu_texture_init_from_bytes(gpu_texture_t *texture, void *data, int width, } else #endif - if (aligned_bpr != width * bpp) { + if (aligned_bpr != width * bpp) { upload_size = (size_t)aligned_bpr * height; upload_data = malloc(upload_size); for (int row = 0; row < height; ++row) { diff --git a/base/sources/backends/windows_mini.h b/base/sources/backends/windows_mini.h index 411af241..0b419b1d 100644 --- a/base/sources/backends/windows_mini.h +++ b/base/sources/backends/windows_mini.h @@ -5,9 +5,9 @@ typedef unsigned __int64 UINT_PTR; typedef __int64 LONG_PTR; typedef unsigned __int64 ULONG_PTR; -typedef unsigned long DWORD; +typedef unsigned long DWORD; typedef unsigned short WORD; -typedef DWORD *LPDWORD; +typedef DWORD *LPDWORD; #define STD_OUTPUT_HANDLE ((DWORD) - 11) #define STD_ERROR_HANDLE ((DWORD) - 12) #define WINAPI __stdcall @@ -96,57 +96,42 @@ typedef BYTE *LPBYTE; #define CREATE_NO_WINDOW 0x08000000 typedef struct _STARTUPINFOW { - DWORD cb; - LPWSTR lpReserved; - LPWSTR lpDesktop; - LPWSTR lpTitle; - DWORD dwX; - DWORD dwY; - DWORD dwXSize; - DWORD dwYSize; - DWORD dwXCountChars; - DWORD dwYCountChars; - DWORD dwFillAttribute; - DWORD dwFlags; - WORD wShowWindow; - WORD cbReserved2; - LPBYTE lpReserved2; - HANDLE hStdInput; - HANDLE hStdOutput; - HANDLE hStdError; + DWORD cb; + LPWSTR lpReserved; + LPWSTR lpDesktop; + LPWSTR lpTitle; + DWORD dwX; + DWORD dwY; + DWORD dwXSize; + DWORD dwYSize; + DWORD dwXCountChars; + DWORD dwYCountChars; + DWORD dwFillAttribute; + DWORD dwFlags; + WORD wShowWindow; + WORD cbReserved2; + LPBYTE lpReserved2; + HANDLE hStdInput; + HANDLE hStdOutput; + HANDLE hStdError; } STARTUPINFOW, *LPSTARTUPINFOW; -typedef STARTUPINFOW STARTUPINFO; +typedef STARTUPINFOW STARTUPINFO; typedef LPSTARTUPINFOW LPSTARTUPINFO; typedef struct _PROCESS_INFORMATION { - HANDLE hProcess; - HANDLE hThread; - DWORD dwProcessId; - DWORD dwThreadId; + HANDLE hProcess; + HANDLE hThread; + DWORD dwProcessId; + DWORD dwThreadId; } PROCESS_INFORMATION, *PPROCESS_INFORMATION, *LPPROCESS_INFORMATION; WINBASEAPI DWORD WINAPI GetEnvironmentVariableW(LPCWSTR lpName, LPWSTR lpBuffer, DWORD nSize); -WINBASEAPI BOOL WINAPI CreateProcessW( - LPCWSTR lpApplicationName, - LPWSTR lpCommandLine, - LPSECURITY_ATTRIBUTES lpProcessAttributes, - LPSECURITY_ATTRIBUTES lpThreadAttributes, - BOOL bInheritHandles, - DWORD dwCreationFlags, - LPVOID lpEnvironment, - LPCWSTR lpCurrentDirectory, - LPSTARTUPINFOW lpStartupInfo, - LPPROCESS_INFORMATION lpProcessInformation -); +WINBASEAPI BOOL WINAPI CreateProcessW(LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, + LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, + LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); -WINBASEAPI DWORD WINAPI WaitForSingleObject( - HANDLE hHandle, - DWORD dwMilliseconds -); +WINBASEAPI DWORD WINAPI WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds); -WINBASEAPI BOOL WINAPI GetExitCodeProcess( - HANDLE hProcess, - LPDWORD lpExitCode -); +WINBASEAPI BOOL WINAPI GetExitCodeProcess(HANDLE hProcess, LPDWORD lpExitCode); diff --git a/base/sources/backends/windows_system.c b/base/sources/backends/windows_system.c index 22b6d645..1edf236c 100644 --- a/base/sources/backends/windows_system.c +++ b/base/sources/backends/windows_system.c @@ -23,17 +23,17 @@ void iron_microsoft_format(const char *format, va_list args, wchar_t *buffer) { void _wassert(wchar_t const *message, wchar_t const *filename, unsigned line) { __debugbreak(); } -void _RTC_CheckStackVars(void) {} -void _RTC_InitBase(void) {} -void _RTC_Shutdown(void) {} -void _RTC_AllocaHelper(void) {} -void _RTC_CheckStackVars2(void) {} -void __GSHandlerCheck(void) {} +void _RTC_CheckStackVars(void) {} +void _RTC_InitBase(void) {} +void _RTC_Shutdown(void) {} +void _RTC_AllocaHelper(void) {} +void _RTC_CheckStackVars2(void) {} +void __GSHandlerCheck(void) {} void __fastcall __security_check_cookie(_In_ uintptr_t _StackCookie) {} -uintptr_t __security_cookie; -int _fltused = 1; -void __report_rangecheckfailure(void) {} -void __chkstk(void) {} +uintptr_t __security_cookie; +int _fltused = 1; +void __report_rangecheckfailure(void) {} +void __chkstk(void) {} #endif #endif @@ -94,7 +94,7 @@ static BOOL CALLBACK EnumerationCallback(HMONITOR monitor, HDC hdc_unused, LPREC HDC hdc = CreateDCA(NULL, display->name, NULL, NULL); display->ppi = GetDeviceCaps(hdc, LOGPIXELSX); - /* int scale =*/ GetDeviceCaps(hdc, SCALINGFACTORX); + /* int scale =*/GetDeviceCaps(hdc, SCALINGFACTORX); DeleteDC(hdc); if (MyGetDpiForMonitor != NULL) { diff --git a/base/sources/iron_array.h b/base/sources/iron_array.h index 23dd6770..6ac75f2e 100644 --- a/base/sources/iron_array.h +++ b/base/sources/iron_array.h @@ -117,37 +117,37 @@ void buffer_set_u32(buffer_t *b, uint32_t p, uint32_t n); void buffer_set_i32(buffer_t *b, uint32_t p, int32_t n); void buffer_set_f32(buffer_t *b, uint32_t p, float n); -buffer_t *buffer_create(uint32_t length); -buffer_t *buffer_create_from_raw(uint8_t *raw, uint32_t length); -f32_array_t *f32_array_create(uint32_t length); -f32_array_t *f32_array_create_from_buffer(buffer_t *b); -f32_array_t *f32_array_create_from_array(f32_array_t *from); -f32_array_t *f32_array_create_from_raw(float *raw, uint32_t length); -f32_array_t *f32_array_create_x(float x); -f32_array_t *f32_array_create_xy(float x, float y); -f32_array_t *f32_array_create_xyz(float x, float y, float z); -f32_array_t *f32_array_create_xyzw(float x, float y, float z, float w); -f32_array_t *f32_array_create_xyzwv(float x, float y, float z, float w, float v); -u32_array_t *u32_array_create(uint32_t length); -u32_array_t *u32_array_create_from_array(u32_array_t *from); -u32_array_t *u32_array_create_from_raw(uint32_t *raw, uint32_t length); -i32_array_t *i32_array_create(uint32_t length); -i32_array_t *i32_array_create_from_array(i32_array_t *from); -i32_array_t *i32_array_create_from_raw(int32_t *raw, uint32_t length); -u16_array_t *u16_array_create(uint32_t length); -u16_array_t *u16_array_create_from_raw(uint16_t *raw, uint32_t length); -i16_array_t *i16_array_create(uint32_t length); -i16_array_t *i16_array_create_from_array(i16_array_t *from); -i16_array_t *i16_array_create_from_raw(int16_t *raw, uint32_t length); -u8_array_t *u8_array_create(uint32_t length); -u8_array_t *u8_array_create_from_array(u8_array_t *from); -u8_array_t *u8_array_create_from_raw(uint8_t *raw, uint32_t length); -u8_array_t *u8_array_create_from_string(char *s); -char *u8_array_to_string(u8_array_t *a); -i8_array_t *i8_array_create(uint32_t length); -i8_array_t *i8_array_create_from_raw(int8_t *raw, uint32_t length); -any_array_t *any_array_create(uint32_t length); -any_array_t *any_array_create_from_raw(void **raw, uint32_t length); +buffer_t *buffer_create(uint32_t length); +buffer_t *buffer_create_from_raw(uint8_t *raw, uint32_t length); +f32_array_t *f32_array_create(uint32_t length); +f32_array_t *f32_array_create_from_buffer(buffer_t *b); +f32_array_t *f32_array_create_from_array(f32_array_t *from); +f32_array_t *f32_array_create_from_raw(float *raw, uint32_t length); +f32_array_t *f32_array_create_x(float x); +f32_array_t *f32_array_create_xy(float x, float y); +f32_array_t *f32_array_create_xyz(float x, float y, float z); +f32_array_t *f32_array_create_xyzw(float x, float y, float z, float w); +f32_array_t *f32_array_create_xyzwv(float x, float y, float z, float w, float v); +u32_array_t *u32_array_create(uint32_t length); +u32_array_t *u32_array_create_from_array(u32_array_t *from); +u32_array_t *u32_array_create_from_raw(uint32_t *raw, uint32_t length); +i32_array_t *i32_array_create(uint32_t length); +i32_array_t *i32_array_create_from_array(i32_array_t *from); +i32_array_t *i32_array_create_from_raw(int32_t *raw, uint32_t length); +u16_array_t *u16_array_create(uint32_t length); +u16_array_t *u16_array_create_from_raw(uint16_t *raw, uint32_t length); +i16_array_t *i16_array_create(uint32_t length); +i16_array_t *i16_array_create_from_array(i16_array_t *from); +i16_array_t *i16_array_create_from_raw(int16_t *raw, uint32_t length); +u8_array_t *u8_array_create(uint32_t length); +u8_array_t *u8_array_create_from_array(u8_array_t *from); +u8_array_t *u8_array_create_from_raw(uint8_t *raw, uint32_t length); +u8_array_t *u8_array_create_from_string(char *s); +char *u8_array_to_string(u8_array_t *a); +i8_array_t *i8_array_create(uint32_t length); +i8_array_t *i8_array_create_from_raw(int8_t *raw, uint32_t length); +any_array_t *any_array_create(uint32_t length); +any_array_t *any_array_create_from_raw(void **raw, uint32_t length); string_array_t *string_array_create(uint32_t length); -uint16_t float_to_half_fast(float value); -uint8_t half_to_u8_fast(uint16_t h); +uint16_t float_to_half_fast(float value); +uint8_t half_to_u8_fast(uint16_t h); diff --git a/base/sources/iron_compress.h b/base/sources/iron_compress.h index eed9f557..7d3d36a4 100644 --- a/base/sources/iron_compress.h +++ b/base/sources/iron_compress.h @@ -3,6 +3,6 @@ #include "iron_array.h" #include -buffer_t *iron_inflate(buffer_t *bytes, bool raw); -buffer_t *iron_deflate(buffer_t *bytes, bool raw); +buffer_t *iron_inflate(buffer_t *bytes, bool raw); +buffer_t *iron_deflate(buffer_t *bytes, bool raw); unsigned char *iron_deflate_raw(unsigned char *data, int data_len, int *out_len, int quality); diff --git a/base/sources/iron_draw.c b/base/sources/iron_draw.c index 9838d9cb..85079d46 100644 --- a/base/sources/iron_draw.c +++ b/base/sources/iron_draw.c @@ -13,9 +13,9 @@ draw_font_t *draw_font = NULL; int draw_font_size; gpu_texture_t *_draw_current = NULL; -static mat3_t draw_transform; -static uint32_t draw_color = 0; -static gpu_pipeline_t *draw_custom_pipeline = NULL; +static mat3_t draw_transform; +static uint32_t draw_color = 0; +static gpu_pipeline_t *draw_custom_pipeline = NULL; static gpu_buffer_t rect_vertex_buffer; static gpu_buffer_t rect_index_buffer; @@ -226,7 +226,9 @@ void draw_end(void) { void draw_scaled_sub_image(gpu_texture_t *tex, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh) { if (mat3_isnan(draw_transform)) { - gpu_set_pipeline(draw_custom_pipeline != NULL ? draw_custom_pipeline : (_draw_current != NULL && _draw_current->format == GPU_TEXTURE_FORMAT_R8) ? &image_r8_pipeline : &image_pipeline); + gpu_set_pipeline(draw_custom_pipeline != NULL ? draw_custom_pipeline + : (_draw_current != NULL && _draw_current->format == GPU_TEXTURE_FORMAT_R8) ? &image_r8_pipeline + : &image_pipeline); } else { gpu_set_pipeline(draw_custom_pipeline != NULL ? draw_custom_pipeline : &image_transform_pipeline); @@ -745,7 +747,7 @@ void draw_inner_line(float x1, float y1, float x2, float y2, float strength) { else { vec = (vec2_t){1, -(x2 - x1) / (y2 - y1)}; } - vec = vec2_set_len(vec, strength); + vec = vec2_set_len(vec, strength); vec2_t p1 = {x1 + side * vec.x, y1 + side * vec.y}; vec2_t p2 = {x2 + side * vec.x, y2 + side * vec.y}; vec2_t p3 = vec2_sub(p1, vec); diff --git a/base/sources/iron_gpu.c b/base/sources/iron_gpu.c index 079c637e..29464ef4 100644 --- a/base/sources/iron_gpu.c +++ b/base/sources/iron_gpu.c @@ -227,8 +227,8 @@ void gpu_vertex_structure_add(gpu_vertex_structure_t *structure, const char *nam void gpu_vertex_struct_add(gpu_vertex_structure_t *raw, char *name, gpu_vertex_data_t data) { gpu_vertex_element_t *e = &raw->elements[raw->size]; - e->name = name; - e->data = data; + e->name = name; + e->data = data; raw->size++; } diff --git a/base/sources/iron_gpu.h b/base/sources/iron_gpu.h index 2ec014d1..e63bf36e 100644 --- a/base/sources/iron_gpu.h +++ b/base/sources/iron_gpu.h @@ -149,7 +149,7 @@ typedef struct gpu_pipeline { } gpu_pipeline_t; typedef struct gpu_raytrace_pipeline { - gpu_buffer_t *constant_buffer; + gpu_buffer_t *constant_buffer; gpu_pipeline_impl_t impl; } gpu_raytrace_pipeline_t; diff --git a/base/sources/iron_image.c b/base/sources/iron_image.c index bbafb14b..cf23fe23 100644 --- a/base/sources/iron_image.c +++ b/base/sources/iron_image.c @@ -16,7 +16,7 @@ void _write_image(char *path, buffer_t *bytes, i32 w, i32 h, i32 format, int ima unsigned char *pixels = NULL; unsigned char *rgba = (unsigned char *)bytes->buffer; if (format == 0) { // RGBA - comp = 4; + comp = 4; #ifdef IRON_BGRA pixels = (unsigned char *)malloc(w * h * comp); for (int i = 0; i < w * h; ++i) { diff --git a/base/sources/iron_image.h b/base/sources/iron_image.h index 104934fd..f58dac76 100644 --- a/base/sources/iron_image.h +++ b/base/sources/iron_image.h @@ -1,10 +1,10 @@ #pragma once -#include "iron_global.h" #include "iron_array.h" +#include "iron_global.h" -void iron_write_jpg(char *path, buffer_t *bytes, i32 w, i32 h, i32 format, i32 quality); -void iron_write_png(char *path, buffer_t *bytes, i32 w, i32 h, i32 format); +void iron_write_jpg(char *path, buffer_t *bytes, i32 w, i32 h, i32 format, i32 quality); +void iron_write_png(char *path, buffer_t *bytes, i32 w, i32 h, i32 format); buffer_t *iron_encode_jpg(buffer_t *bytes, i32 w, i32 h, i32 format, i32 quality); buffer_t *iron_encode_png(buffer_t *bytes, i32 w, i32 h, i32 format); diff --git a/base/sources/iron_input.c b/base/sources/iron_input.c index 3c841291..f7d385a2 100644 --- a/base/sources/iron_input.c +++ b/base/sources/iron_input.c @@ -18,17 +18,17 @@ bool _input_registered = false; // Mouse string_array_t *_mouse_buttons = NULL; -u8_array_t *_mouse_buttons_down = NULL; -u8_array_t *_mouse_buttons_started = NULL; -u8_array_t *_mouse_buttons_released = NULL; -f32 mouse_x = -1.0f; -f32 mouse_y = -1.0f; -bool mouse_moved = false; -f32 mouse_movement_x = 0.0f; -f32 mouse_movement_y = 0.0f; -f32 mouse_wheel_delta = 0.0f; -f32 mouse_last_x = -1.0f; -f32 mouse_last_y = -1.0f; +u8_array_t *_mouse_buttons_down = NULL; +u8_array_t *_mouse_buttons_started = NULL; +u8_array_t *_mouse_buttons_released = NULL; +f32 mouse_x = -1.0f; +f32 mouse_y = -1.0f; +bool mouse_moved = false; +f32 mouse_movement_x = 0.0f; +f32 mouse_movement_y = 0.0f; +f32 mouse_wheel_delta = 0.0f; +f32 mouse_last_x = -1.0f; +f32 mouse_last_y = -1.0f; #if defined(IRON_ANDROID) || defined(IRON_IOS) f32 mouse_pinch_dist = 0.0f; @@ -39,29 +39,29 @@ f32 mouse_pinch_smooth = 0.0f; // Pen string_array_t *pen_buttons = NULL; -u8_array_t *pen_buttons_down = NULL; -u8_array_t *pen_buttons_started = NULL; -u8_array_t *pen_buttons_released = NULL; -f32 pen_x = 0.0f; -f32 pen_y = 0.0f; -bool pen_moved = false; -f32 pen_movement_x = 0.0f; -f32 pen_movement_y = 0.0f; -f32 pen_pressure = 0.0f; -bool pen_connected = false; -bool pen_in_use = false; -f32 pen_last_x = -1.0f; -f32 pen_last_y = -1.0f; +u8_array_t *pen_buttons_down = NULL; +u8_array_t *pen_buttons_started = NULL; +u8_array_t *pen_buttons_released = NULL; +f32 pen_x = 0.0f; +f32 pen_y = 0.0f; +bool pen_moved = false; +f32 pen_movement_x = 0.0f; +f32 pen_movement_y = 0.0f; +f32 pen_pressure = 0.0f; +bool pen_connected = false; +bool pen_in_use = false; +f32 pen_last_x = -1.0f; +f32 pen_last_y = -1.0f; // Keyboard string_array_t *keyboard_keys = NULL; -i32_map_t *keyboard_keys_down = NULL; -i32_map_t *keyboard_keys_started = NULL; -i32_map_t *keyboard_keys_released = NULL; +i32_map_t *keyboard_keys_down = NULL; +i32_map_t *keyboard_keys_started = NULL; +i32_map_t *keyboard_keys_released = NULL; string_array_t *keyboard_keys_frame = NULL; -bool keyboard_repeat_key = false; -f32 keyboard_repeat_time = 0.0f; +bool keyboard_repeat_key = false; +f32 keyboard_repeat_time = 0.0f; #ifdef WITH_GAMEPAD @@ -70,7 +70,7 @@ f32 keyboard_repeat_time = 0.0f; string_array_t *gamepad_buttons_ps = NULL; string_array_t *gamepad_buttons_xbox = NULL; string_array_t *gamepad_buttons = NULL; -any_array_t *gamepad_raws = NULL; +any_array_t *gamepad_raws = NULL; #endif diff --git a/base/sources/iron_input.h b/base/sources/iron_input.h index 08764535..52e4b305 100644 --- a/base/sources/iron_input.h +++ b/base/sources/iron_input.h @@ -18,17 +18,17 @@ void input_register(void); // Mouse extern string_array_t *_mouse_buttons; -extern u8_array_t *_mouse_buttons_down; -extern u8_array_t *_mouse_buttons_started; -extern u8_array_t *_mouse_buttons_released; -extern f32 mouse_x; -extern f32 mouse_y; -extern bool mouse_moved; -extern f32 mouse_movement_x; -extern f32 mouse_movement_y; -extern f32 mouse_wheel_delta; -extern f32 mouse_last_x; -extern f32 mouse_last_y; +extern u8_array_t *_mouse_buttons_down; +extern u8_array_t *_mouse_buttons_started; +extern u8_array_t *_mouse_buttons_released; +extern f32 mouse_x; +extern f32 mouse_y; +extern bool mouse_moved; +extern f32 mouse_movement_x; +extern f32 mouse_movement_y; +extern f32 mouse_wheel_delta; +extern f32 mouse_last_x; +extern f32 mouse_last_y; void mouse_end_frame(void); void mouse_reset(void); @@ -59,19 +59,19 @@ f32 mouse_view_y(void); // Pen extern string_array_t *pen_buttons; -extern u8_array_t *pen_buttons_down; -extern u8_array_t *pen_buttons_started; -extern u8_array_t *pen_buttons_released; -extern f32 pen_x; -extern f32 pen_y; -extern bool pen_moved; -extern f32 pen_movement_x; -extern f32 pen_movement_y; -extern f32 pen_pressure; -extern bool pen_connected; -extern bool pen_in_use; -extern f32 pen_last_x; -extern f32 pen_last_y; +extern u8_array_t *pen_buttons_down; +extern u8_array_t *pen_buttons_started; +extern u8_array_t *pen_buttons_released; +extern f32 pen_x; +extern f32 pen_y; +extern bool pen_moved; +extern f32 pen_movement_x; +extern f32 pen_movement_y; +extern f32 pen_pressure; +extern bool pen_connected; +extern bool pen_in_use; +extern f32 pen_last_x; +extern f32 pen_last_y; void pen_end_frame(void); void pen_reset(void); @@ -88,12 +88,12 @@ f32 pen_view_y(void); // Keyboard extern string_array_t *keyboard_keys; -extern i32_map_t *keyboard_keys_down; -extern i32_map_t *keyboard_keys_started; -extern i32_map_t *keyboard_keys_released; +extern i32_map_t *keyboard_keys_down; +extern i32_map_t *keyboard_keys_started; +extern i32_map_t *keyboard_keys_released; extern string_array_t *keyboard_keys_frame; -extern bool keyboard_repeat_key; -extern f32 keyboard_repeat_time; +extern bool keyboard_repeat_key; +extern f32 keyboard_repeat_time; void keyboard_end_frame(void); void keyboard_reset(void); @@ -132,7 +132,7 @@ typedef struct gamepad { extern string_array_t *gamepad_buttons_ps; extern string_array_t *gamepad_buttons_xbox; extern string_array_t *gamepad_buttons; -extern any_array_t *gamepad_raws; +extern any_array_t *gamepad_raws; void gamepad_end_frame(void); gamepad_stick_t *gamepad_stick_create(void); diff --git a/base/sources/iron_lz4.c b/base/sources/iron_lz4.c index 7f4cf513..d9f811e5 100644 --- a/base/sources/iron_lz4.c +++ b/base/sources/iron_lz4.c @@ -28,7 +28,7 @@ buffer_t *lz4_encode(buffer_t *b) { if (_lz4_hash_table == NULL) { _lz4_hash_table = i32_array_create(65536); - gc_root(_lz4_hash_table); + gc_root(_lz4_hash_table); } for (uint32_t i = 0; i < _lz4_hash_table->length; ++i) { _lz4_hash_table->buffer[i] = -65536; @@ -46,7 +46,7 @@ buffer_t *lz4_encode(buffer_t *b) { uint32_t moffset = 0; uint32_t sequence = ((uint32_t)ibuf->buffer[ipos] << 8) | ((uint32_t)ibuf->buffer[ipos + 1] << 16) | ((uint32_t)ibuf->buffer[ipos + 2] << 24); - // Match-finding loop + // Match-finding loop while (ipos <= last_match_pos) { sequence = (sequence >> 8) | ((uint32_t)ibuf->buffer[ipos + 3] << 24); uint32_t hash = ((sequence * 0x9e37) & 0xffff) + ((sequence * 0x79b1) >> 16) & 0xffff; @@ -60,12 +60,12 @@ buffer_t *lz4_encode(buffer_t *b) { ipos += 1; } - // No match found + // No match found if (ipos > last_match_pos) { break; } - // Match found + // Match found uint32_t llen = ipos - anchor_pos; uint32_t mlen = ipos; ipos += 4; @@ -77,7 +77,7 @@ buffer_t *lz4_encode(buffer_t *b) { mlen = ipos - mlen; uint32_t token = mlen < 19 ? mlen - 4 : 15; - // Write token, length of literals if needed + // Write token, length of literals if needed if (llen >= 15) { obuf->buffer[opos++] = 0xf0 | token; uint32_t l = llen - 15; @@ -91,7 +91,7 @@ buffer_t *lz4_encode(buffer_t *b) { obuf->buffer[opos++] = (llen << 4) | token; } - // Write literals + // Write literals while (llen-- > 0) { obuf->buffer[opos++] = ibuf->buffer[anchor_pos++]; } @@ -100,12 +100,12 @@ buffer_t *lz4_encode(buffer_t *b) { break; } - // Write offset of match + // Write offset of match obuf->buffer[opos + 0] = moffset; obuf->buffer[opos + 1] = moffset >> 8; opos += 2; - // Write length of match if needed + // Write length of match if needed if (mlen >= 19) { uint32_t l = mlen - 19; while (l >= 255) { @@ -118,7 +118,7 @@ buffer_t *lz4_encode(buffer_t *b) { anchor_pos = ipos; } - // Last sequence is literals only + // Last sequence is literals only uint32_t llen = ilen - anchor_pos; if (llen >= 15) { obuf->buffer[opos++] = 0xf0; @@ -149,10 +149,10 @@ buffer_t *lz4_decode(buffer_t *b, uint32_t olen) { while (ipos < ilen) { uint32_t token = ibuf->buffer[ipos++]; - // Literals + // Literals uint32_t clen = token >> 4; - // Length of literals + // Length of literals if (clen != 0) { if (clen == 15) { uint32_t l = 0; @@ -166,7 +166,7 @@ buffer_t *lz4_decode(buffer_t *b, uint32_t olen) { clen += l; } - // Copy literals + // Copy literals uint32_t end = ipos + clen; while (ipos < end) { obuf->buffer[opos++] = ibuf->buffer[ipos++]; @@ -176,14 +176,14 @@ buffer_t *lz4_decode(buffer_t *b, uint32_t olen) { } } - // Match + // Match uint32_t moffset = ibuf->buffer[ipos + 0] | (ibuf->buffer[ipos + 1] << 8); if (moffset == 0 || moffset > opos) { return NULL; } ipos += 2; - // Length of match + // Length of match clen = (token & 0x0f) + 4; if (clen == 19) { uint32_t l = 0; @@ -197,7 +197,7 @@ buffer_t *lz4_decode(buffer_t *b, uint32_t olen) { clen += l; } - // Copy match + // Copy match uint32_t mpos = opos - moffset; uint32_t end = opos + clen; while (opos < end) { diff --git a/base/sources/iron_map.h b/base/sources/iron_map.h index 963dbe80..085f6574 100644 --- a/base/sources/iron_map.h +++ b/base/sources/iron_map.h @@ -5,17 +5,17 @@ typedef struct i32_map { string_array_t *keys; - i32_array_t *values; + i32_array_t *values; } i32_map_t; typedef struct f32_map { string_array_t *keys; - f32_array_t *values; + f32_array_t *values; } f32_map_t; typedef struct any_map { string_array_t *keys; - any_array_t *values; + any_array_t *values; } any_map_t; void i32_map_set(i32_map_t *m, char *k, int v); diff --git a/base/sources/iron_math.c b/base/sources/iron_math.c index 329e279e..12386f63 100644 --- a/base/sources/iron_math.c +++ b/base/sources/iron_math.c @@ -707,10 +707,10 @@ mat4_t mat4_mult_mat3x4(mat4_t a, mat4_t b) { float a31 = a.m[13]; float a32 = a.m[14]; float a33 = a.m[15]; - float b0 = b.m[0]; - float b1 = b.m[4]; - float b2 = b.m[8]; - float b3 = b.m[12]; + float b0 = b.m[0]; + float b1 = b.m[4]; + float b2 = b.m[8]; + float b3 = b.m[12]; mat4_t m; m.m[0] = a00 * b0 + a01 * b1 + a02 * b2 + a03 * b3; diff --git a/base/sources/iron_math.h b/base/sources/iron_math.h index 377aafc6..efdcd5ea 100644 --- a/base/sources/iron_math.h +++ b/base/sources/iron_math.h @@ -69,11 +69,11 @@ typedef union mat4 { }; } mat4_t; -void iron_color_components(uint32_t color, float *red, float *green, float *blue, float *alpha); -void iron_random_init(int64_t seed); -int64_t iron_random_get(void); -int64_t iron_random_get_max(int64_t max); -int64_t iron_random_get_in(int64_t min, int64_t max); +void iron_color_components(uint32_t color, float *red, float *green, float *blue, float *alpha); +void iron_random_init(int64_t seed); +int64_t iron_random_get(void); +int64_t iron_random_get_max(int64_t max); +int64_t iron_random_get_in(int64_t min, int64_t max); float vec2_len(vec2_t v); vec2_t vec2_set_len(vec2_t v, float length); @@ -137,12 +137,12 @@ typedef struct mat4_decomposed { vec4_t scl; } mat4_decomposed_t; -mat4_t mat4_identity(); -mat4_t mat4_from_f32_array(f32_array_t *a, int offset); -mat4_t mat4_persp(float fov_y, float aspect, float zn, float zf); -mat4_t mat4_ortho(float left, float right, float bottom, float top, float znear, float zfar); -mat4_t mat4_rot_z(float alpha); -mat4_t mat4_compose(vec4_t loc, quat_t rot, vec4_t scl); +mat4_t mat4_identity(); +mat4_t mat4_from_f32_array(f32_array_t *a, int offset); +mat4_t mat4_persp(float fov_y, float aspect, float zn, float zf); +mat4_t mat4_ortho(float left, float right, float bottom, float top, float znear, float zfar); +mat4_t mat4_rot_z(float alpha); +mat4_t mat4_compose(vec4_t loc, quat_t rot, vec4_t scl); mat4_decomposed_t *mat4_decompose(mat4_t m); mat4_t mat4_set_loc(mat4_t m, vec4_t v); mat4_t mat4_from_quat(quat_t q); diff --git a/base/sources/iron_net.h b/base/sources/iron_net.h index f5b38088..c6fa535f 100644 --- a/base/sources/iron_net.h +++ b/base/sources/iron_net.h @@ -8,6 +8,7 @@ typedef void (*iron_https_callback_t)(const char *body, void *callbackdata); -void iron_net_request(const char *url_base, const char *url_path, const char *data, int port, int method, iron_https_callback_t callback, void *callbackdata, const char *dst_path); +void iron_net_request(const char *url_base, const char *url_path, const char *data, int port, int method, iron_https_callback_t callback, void *callbackdata, + const char *dst_path); void iron_net_update(); extern volatile uint64_t iron_net_bytes_downloaded; diff --git a/base/sources/iron_path.c b/base/sources/iron_path.c index 2f46e0c8..108dc756 100644 --- a/base/sources/iron_path.c +++ b/base/sources/iron_path.c @@ -12,8 +12,8 @@ bool path_is_protected_linux = false; #endif -string_array_t *_path_mesh_formats = NULL; -string_array_t *_path_texture_formats = NULL; +string_array_t *_path_mesh_formats = NULL; +string_array_t *_path_texture_formats = NULL; static string_array_t *_path_base_color_ext = NULL; static string_array_t *_path_opacity_ext = NULL; static string_array_t *_path_normal_map_ext = NULL; @@ -215,7 +215,7 @@ char *path_base_name(char *path) { } bool path_is_mesh(char *path) { - char *p = to_lower_case(path); + char *p = to_lower_case(path); string_array_t *formats = path_mesh_formats(); for (uint32_t i = 0; i < formats->length; ++i) { char *s = formats->buffer[i]; @@ -228,7 +228,7 @@ bool path_is_mesh(char *path) { } bool path_is_texture(char *path) { - char *p = to_lower_case(path); + char *p = to_lower_case(path); string_array_t *formats = path_texture_formats(); for (uint32_t i = 0; i < formats->length; ++i) { char *s = formats->buffer[i]; diff --git a/base/sources/iron_string.c b/base/sources/iron_string.c index 653b0c05..7800a6e5 100644 --- a/base/sources/iron_string.c +++ b/base/sources/iron_string.c @@ -1,10 +1,10 @@ #include "iron_string.h" #include +#include #include #include #include -#include void *gc_alloc(size_t size); void gc_leaf(void *ptr); @@ -16,18 +16,18 @@ char *string_alloc(int size) { } char *string(char *fmt, ...) { - va_list args; - va_start(args, fmt); + va_list args; + va_start(args, fmt); - va_list args_copy; - va_copy(args_copy, args); - int len = vsnprintf(NULL, 0, fmt, args_copy); - va_end(args_copy); + va_list args_copy; + va_copy(args_copy, args); + int len = vsnprintf(NULL, 0, fmt, args_copy); + va_end(args_copy); - char *str = string_alloc(len + 1); - vsnprintf(str, len + 1, fmt, args); - va_end(args); - return str; + char *str = string_alloc(len + 1); + vsnprintf(str, len + 1, fmt, args); + va_end(args); + return str; } char *string_copy(char *a) { diff --git a/base/sources/iron_string.h b/base/sources/iron_string.h index ac31fa78..08cb035c 100644 --- a/base/sources/iron_string.h +++ b/base/sources/iron_string.h @@ -1,9 +1,9 @@ #pragma once #include "iron_array.h" +#include #include #include -#include char *string_alloc(int size); char *string(char *fmt, ...); diff --git a/base/sources/iron_sys.c b/base/sources/iron_sys.c index b7bce687..d003eb5c 100644 --- a/base/sources/iron_sys.c +++ b/base/sources/iron_sys.c @@ -41,8 +41,8 @@ void iron_set_gamepad_axis_callback(void (*callback)(int, int, float)); void iron_set_gamepad_button_callback(void (*callback)(int, int, float)); #endif -any_map_t *_sys_shaders = NULL; -f32 _sys_start_time = 0.0f; +any_map_t *_sys_shaders = NULL; +f32 _sys_start_time = 0.0f; char _sys_window_title[1024]; any_array_t *_sys_foreground_listeners = NULL; diff --git a/base/sources/iron_sys.h b/base/sources/iron_sys.h index 07d980a4..78cacdcf 100644 --- a/base/sources/iron_sys.h +++ b/base/sources/iron_sys.h @@ -18,10 +18,10 @@ extern i32 _sys_lastw; extern i32 _sys_lasth; extern void (*sys_on_resize)(void); -extern i32 (*sys_on_w)(void); -extern i32 (*sys_on_h)(void); -extern i32 (*sys_on_x)(void); -extern i32 (*sys_on_y)(void); +extern i32 (*sys_on_w)(void); +extern i32 (*sys_on_h)(void); +extern i32 (*sys_on_x)(void); +extern i32 (*sys_on_y)(void); typedef struct sys_callback { void (*f)(void); @@ -114,5 +114,5 @@ typedef struct { void video_unload(video_t *self); -char *sys_buffer_to_string(buffer_t *b); +char *sys_buffer_to_string(buffer_t *b); buffer_t *sys_string_to_buffer(char *str); diff --git a/base/sources/iron_system.c b/base/sources/iron_system.c index 864ea117..7da13b0c 100644 --- a/base/sources/iron_system.c +++ b/base/sources/iron_system.c @@ -40,11 +40,11 @@ void iron_log_args(iron_log_level_t level, const char *format, va_list args) { char buffer[4096]; vsnprintf(buffer, 4090, format, args); strcat(buffer, "\n"); - #ifdef IRON_WASM +#ifdef IRON_WASM printf("%s", buffer); //// - #else +#else fprintf(level == IRON_LOG_LEVEL_INFO ? stdout : stderr, "%s", buffer); - #endif +#endif #endif } @@ -658,7 +658,7 @@ string_array_t *iron_open_dialog(char *filter_list, char *default_path, bool ope nfdresult_t result = open_multiple ? NFD_OpenDialogMultiple(filter_list, default_path, &out_paths) : NFD_OpenDialog(filter_list, default_path, &out_path); if (result == NFD_OKAY) { - int path_count = open_multiple ? (int)NFD_PathSet_GetCount(&out_paths) : 1; + int path_count = open_multiple ? (int)NFD_PathSet_GetCount(&out_paths) : 1; string_array_t *result = any_array_create(path_count); if (open_multiple) { @@ -729,7 +729,7 @@ char *iron_save_dialog(char *filter_list, char *default_path) { #elif defined(IRON_WASM) -__attribute__((import_module("imports"), import_name("js_open_dialog"))) void js_open_dialog(); +__attribute__((import_module("imports"), import_name("js_open_dialog"))) void js_open_dialog(); __attribute__((import_module("imports"), import_name("js_save_dialog"))) char *js_save_dialog(); string_array_t *iron_open_dialog(char *filter_list, char *default_path, bool open_multiple) { diff --git a/base/sources/iron_system.h b/base/sources/iron_system.h index 761386f2..2ba9c76c 100644 --- a/base/sources/iron_system.h +++ b/base/sources/iron_system.h @@ -1,7 +1,7 @@ #pragma once -#include "iron_global.h" #include "iron_array.h" +#include "iron_global.h" #include #include #include @@ -45,7 +45,7 @@ typedef enum { } iron_window_mode_t; typedef enum { - IRON_WINDOW_FEATURES_NONE = 0, + IRON_WINDOW_FEATURES_NONE = 0, IRON_WINDOW_FEATURES_RESIZABLE = 1, IRON_WINDOW_FEATURES_MINIMIZABLE = 2, IRON_WINDOW_FEATURES_MAXIMIZABLE = 4, @@ -338,6 +338,6 @@ void iron_internal_gamepad_trigger_axis(int gamepad, int axis, float valu void iron_internal_gamepad_trigger_button(int gamepad, int button, float value); #endif -i32 iron_sys_command(char *cmd); +i32 iron_sys_command(char *cmd); string_array_t *iron_open_dialog(char *filter_list, char *default_path, bool open_multiple); -char *iron_save_dialog(char *filter_list, char *default_path); +char *iron_save_dialog(char *filter_list, char *default_path); diff --git a/base/sources/iron_thread.h b/base/sources/iron_thread.h index 1ce25cc9..01bdbb02 100644 --- a/base/sources/iron_thread.h +++ b/base/sources/iron_thread.h @@ -12,7 +12,6 @@ #include "backends/posix_thread.h" #endif - typedef struct iron_thread { iron_thread_impl_t impl; } iron_thread_t; diff --git a/base/sources/kong/kong_hlsl.c b/base/sources/kong/kong_hlsl.c index 9c8fde9e..e5f77d02 100644 --- a/base/sources/kong/kong_hlsl.c +++ b/base/sources/kong/kong_hlsl.c @@ -1199,9 +1199,9 @@ static void write_functions(char *hlsl, size_t *offset, shader_stage stage, func } else if (o->op_call.func == add_name("float3x3") && o->op_call.parameters_size == 3) { *offset += sprintf(&hlsl[*offset], - "float3x3 _%" PRIu64 " = float3x3(_%" PRIu64 ".x, _%" PRIu64 ".x, _%" PRIu64 ".x, _%" PRIu64 ".y, _%" PRIu64 ".y, _%" PRIu64 ".y, _%" PRIu64 ".z, _%" PRIu64 ".z, _%" PRIu64 ".z);\n", - o->op_call.var.index, - o->op_call.parameters[0].index, o->op_call.parameters[1].index, o->op_call.parameters[2].index, + "float3x3 _%" PRIu64 " = float3x3(_%" PRIu64 ".x, _%" PRIu64 ".x, _%" PRIu64 ".x, _%" PRIu64 ".y, _%" PRIu64 + ".y, _%" PRIu64 ".y, _%" PRIu64 ".z, _%" PRIu64 ".z, _%" PRIu64 ".z);\n", + o->op_call.var.index, o->op_call.parameters[0].index, o->op_call.parameters[1].index, o->op_call.parameters[2].index, o->op_call.parameters[0].index, o->op_call.parameters[1].index, o->op_call.parameters[2].index, o->op_call.parameters[0].index, o->op_call.parameters[1].index, o->op_call.parameters[2].index); } diff --git a/base/sources/libs/bc7enc.c b/base/sources/libs/bc7enc.c index a5e83fe1..e46852a3 100644 --- a/base/sources/libs/bc7enc.c +++ b/base/sources/libs/bc7enc.c @@ -22,16 +22,16 @@ #include "bc7enc.h" #include "../iron_simd.h" +#include #include #include -#include #include #ifndef IRON_NOSIMD static inline float iron_float32x4_hsum(iron_float32x4_t v) { #if defined(IRON_SSE) iron_float32x4_t t = iron_float32x4_shuffle_custom(v, v, 1, 0, 3, 2); - t = iron_float32x4_add(v, t); + t = iron_float32x4_add(v, t); iron_float32x4_t s = iron_float32x4_shuffle_custom(t, t, 2, 3, 0, 1); return iron_float32x4_get(iron_float32x4_add(t, s), 0); #elif defined(IRON_NEON) @@ -40,146 +40,269 @@ static inline float iron_float32x4_hsum(iron_float32x4_t v) { } #endif -void bc7enc_compress_block_params_init(bc7enc_compress_block_params *p) -{ - p->m_max_partitions_mode = BC7ENC_MAX_PARTITIONS1; - p->m_try_least_squares = BC7ENC_TRUE; +void bc7enc_compress_block_params_init(bc7enc_compress_block_params *p) { + p->m_max_partitions_mode = BC7ENC_MAX_PARTITIONS1; + p->m_try_least_squares = BC7ENC_TRUE; p->m_mode_partition_estimation_filterbank = BC7ENC_TRUE; - p->m_uber_level = 0; - p->m_use_mode5_for_alpha = BC7ENC_TRUE; - p->m_use_mode7_for_alpha = BC7ENC_TRUE; - p->m_perceptual = BC7ENC_TRUE; - p->m_weights[0] = 128; - p->m_weights[1] = 64; - p->m_weights[2] = 16; - p->m_weights[3] = 32; + p->m_uber_level = 0; + p->m_use_mode5_for_alpha = BC7ENC_TRUE; + p->m_use_mode7_for_alpha = BC7ENC_TRUE; + p->m_perceptual = BC7ENC_TRUE; + p->m_weights[0] = 128; + p->m_weights[1] = 64; + p->m_weights[2] = 16; + p->m_weights[3] = 32; } // Helpers -static inline int32_t clampi(int32_t value, int32_t low, int32_t high) { if (value < low) value = low; else if (value > high) value = high; return value; } -static inline float clampf(float value, float low, float high) { if (value < low) value = low; else if (value > high) value = high; return value; } -static inline float saturate(float value) { return clampf(value, 0, 1.0f); } -static inline uint32_t minimumu(uint32_t a, uint32_t b) { return (a < b) ? a : b; } -static inline float minimumf(float a, float b) { return (a < b) ? a : b; } -static inline float maximumf(float a, float b) { return (a > b) ? a : b; } -static inline int squarei(int i) { return i * i; } -static inline float squaref(float i) { return i * i; } - -typedef struct { uint8_t m_c[4]; } color_quad_u8; -typedef struct { float m_c[4]; } vec4F; - -static inline color_quad_u8 *color_quad_u8_set_clamped(color_quad_u8 *pRes, int32_t r, int32_t g, int32_t b, int32_t a) { pRes->m_c[0] = (uint8_t)clampi(r, 0, 255); pRes->m_c[1] = (uint8_t)clampi(g, 0, 255); pRes->m_c[2] = (uint8_t)clampi(b, 0, 255); pRes->m_c[3] = (uint8_t)clampi(a, 0, 255); return pRes; } -static inline color_quad_u8 *color_quad_u8_set(color_quad_u8 *pRes, int32_t r, int32_t g, int32_t b, int32_t a) { pRes->m_c[0] = (uint8_t)r; pRes->m_c[1] = (uint8_t)g; pRes->m_c[2] = (uint8_t)b; pRes->m_c[3] = (uint8_t)a; return pRes; } -static inline bc7enc_bool color_quad_u8_notequals(const color_quad_u8 *pLHS, const color_quad_u8 *pRHS) { return (pLHS->m_c[0] != pRHS->m_c[0]) || (pLHS->m_c[1] != pRHS->m_c[1]) || (pLHS->m_c[2] != pRHS->m_c[2]) || (pLHS->m_c[3] != pRHS->m_c[3]); } -static inline vec4F *vec4F_set_scalar(vec4F *pV, float x) { pV->m_c[0] = x; pV->m_c[1] = x; pV->m_c[2] = x; pV->m_c[3] = x; return pV; } -static inline vec4F *vec4F_set(vec4F *pV, float x, float y, float z, float w) { pV->m_c[0] = x; pV->m_c[1] = y; pV->m_c[2] = z; pV->m_c[3] = w; return pV; } -static inline vec4F vec4F_from_color(const color_quad_u8 *pC) { vec4F res; vec4F_set(&res, pC->m_c[0], pC->m_c[1], pC->m_c[2], pC->m_c[3]); return res; } - -static inline vec4F *vec4F_saturate_in_place(vec4F *pV) { pV->m_c[0] = saturate(pV->m_c[0]); pV->m_c[1] = saturate(pV->m_c[1]); pV->m_c[2] = saturate(pV->m_c[2]); pV->m_c[3] = saturate(pV->m_c[3]); return pV; } -static inline vec4F vec4F_saturate(const vec4F *pV) { vec4F res; res.m_c[0] = saturate(pV->m_c[0]); res.m_c[1] = saturate(pV->m_c[1]); res.m_c[2] = saturate(pV->m_c[2]); res.m_c[3] = saturate(pV->m_c[3]); return res; } -static inline vec4F vec4F_add(const vec4F *pLHS, const vec4F *pRHS) { vec4F res; vec4F_set(&res, pLHS->m_c[0] + pRHS->m_c[0], pLHS->m_c[1] + pRHS->m_c[1], pLHS->m_c[2] + pRHS->m_c[2], pLHS->m_c[3] + pRHS->m_c[3]); return res; } -static inline vec4F vec4F_sub(const vec4F *pLHS, const vec4F *pRHS) { vec4F res; vec4F_set(&res, pLHS->m_c[0] - pRHS->m_c[0], pLHS->m_c[1] - pRHS->m_c[1], pLHS->m_c[2] - pRHS->m_c[2], pLHS->m_c[3] - pRHS->m_c[3]); return res; } -static inline float vec4F_dot(const vec4F *pLHS, const vec4F *pRHS) { return pLHS->m_c[0] * pRHS->m_c[0] + pLHS->m_c[1] * pRHS->m_c[1] + pLHS->m_c[2] * pRHS->m_c[2] + pLHS->m_c[3] * pRHS->m_c[3]; } -static inline vec4F vec4F_mul(const vec4F *pLHS, float s) { vec4F res; vec4F_set(&res, pLHS->m_c[0] * s, pLHS->m_c[1] * s, pLHS->m_c[2] * s, pLHS->m_c[3] * s); return res; } -static inline vec4F *vec4F_normalize_in_place(vec4F *pV) { float s = pV->m_c[0] * pV->m_c[0] + pV->m_c[1] * pV->m_c[1] + pV->m_c[2] * pV->m_c[2] + pV->m_c[3] * pV->m_c[3]; if (s != 0.0f) { s = 1.0f / sqrtf(s); pV->m_c[0] *= s; pV->m_c[1] *= s; pV->m_c[2] *= s; pV->m_c[3] *= s; } return pV; } - -// Various BC7 tables -static const uint32_t g_bc7_weights2[4] = { 0, 21, 43, 64 }; -static const uint32_t g_bc7_weights3[8] = { 0, 9, 18, 27, 37, 46, 55, 64 }; -static const uint32_t g_bc7_weights4[16] = { 0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64 }; -// Precomputed weight constants used during least fit determination. For each entry in g_bc7_weights[]: w * w, (1.0f - w) * w, (1.0f - w) * (1.0f - w), w -static const float g_bc7_weights4x[16 * 4] = { 0.000000f, 0.000000f, 1.000000f, 0.000000f, 0.003906f, 0.058594f, 0.878906f, 0.062500f, 0.019775f, 0.120850f, 0.738525f, 0.140625f, 0.041260f, 0.161865f, 0.635010f, 0.203125f, 0.070557f, 0.195068f, 0.539307f, 0.265625f, 0.107666f, 0.220459f, - 0.451416f, 0.328125f, 0.165039f, 0.241211f, 0.352539f, 0.406250f, 0.219727f, 0.249023f, 0.282227f, 0.468750f, 0.282227f, 0.249023f, 0.219727f, 0.531250f, 0.352539f, 0.241211f, 0.165039f, 0.593750f, 0.451416f, 0.220459f, 0.107666f, 0.671875f, 0.539307f, 0.195068f, 0.070557f, 0.734375f, - 0.635010f, 0.161865f, 0.041260f, 0.796875f, 0.738525f, 0.120850f, 0.019775f, 0.859375f, 0.878906f, 0.058594f, 0.003906f, 0.937500f, 1.000000f, 0.000000f, 0.000000f, 1.000000f }; - -static const uint8_t g_bc7_partition1[16] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; -static const uint8_t g_bc7_partition2[64 * 16] = -{ - 0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1, 0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1, 0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1, 0,0,0,1,0,0,1,1,0,0,1,1,0,1,1,1, 0,0,0,0,0,0,0,1,0,0,0,1,0,0,1,1, 0,0,1,1,0,1,1,1,0,1,1,1,1,1,1,1, 0,0,0,1,0,0,1,1,0,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,1,0,0,1,1,0,1,1,1, - 0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1, 0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,1,0,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1, 0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1, 0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1, - 0,0,0,0,1,0,0,0,1,1,1,0,1,1,1,1, 0,1,1,1,0,0,0,1,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,0,0,1,1,1,0, 0,1,1,1,0,0,1,1,0,0,0,1,0,0,0,0, 0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0, 0,0,0,0,1,0,0,0,1,1,0,0,1,1,1,0, 0,0,0,0,0,0,0,0,1,0,0,0,1,1,0,0, 0,1,1,1,0,0,1,1,0,0,1,1,0,0,0,1, - 0,0,1,1,0,0,0,1,0,0,0,1,0,0,0,0, 0,0,0,0,1,0,0,0,1,0,0,0,1,1,0,0, 0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0, 0,0,1,1,0,1,1,0,0,1,1,0,1,1,0,0, 0,0,0,1,0,1,1,1,1,1,1,0,1,0,0,0, 0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0, 0,1,1,1,0,0,0,1,1,0,0,0,1,1,1,0, 0,0,1,1,1,0,0,1,1,0,0,1,1,1,0,0, - 0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1, 0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1, 0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0, 0,0,1,1,0,0,1,1,1,1,0,0,1,1,0,0, 0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0, 0,1,0,1,0,1,0,1,1,0,1,0,1,0,1,0, 0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1, 0,1,0,1,1,0,1,0,1,0,1,0,0,1,0,1, - 0,1,1,1,0,0,1,1,1,1,0,0,1,1,1,0, 0,0,0,1,0,0,1,1,1,1,0,0,1,0,0,0, 0,0,1,1,0,0,1,0,0,1,0,0,1,1,0,0, 0,0,1,1,1,0,1,1,1,1,0,1,1,1,0,0, 0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0, 0,0,1,1,1,1,0,0,1,1,0,0,0,0,1,1, 0,1,1,0,0,1,1,0,1,0,0,1,1,0,0,1, 0,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0, - 0,1,0,0,1,1,1,0,0,1,0,0,0,0,0,0, 0,0,1,0,0,1,1,1,0,0,1,0,0,0,0,0, 0,0,0,0,0,0,1,0,0,1,1,1,0,0,1,0, 0,0,0,0,0,1,0,0,1,1,1,0,0,1,0,0, 0,1,1,0,1,1,0,0,1,0,0,1,0,0,1,1, 0,0,1,1,0,1,1,0,1,1,0,0,1,0,0,1, 0,1,1,0,0,0,1,1,1,0,0,1,1,1,0,0, 0,0,1,1,1,0,0,1,1,1,0,0,0,1,1,0, - 0,1,1,0,1,1,0,0,1,1,0,0,1,0,0,1, 0,1,1,0,0,0,1,1,0,0,1,1,1,0,0,1, 0,1,1,1,1,1,1,0,1,0,0,0,0,0,0,1, 0,0,0,1,1,0,0,0,1,1,1,0,0,1,1,1, 0,0,0,0,1,1,1,1,0,0,1,1,0,0,1,1, 0,0,1,1,0,0,1,1,1,1,1,1,0,0,0,0, 0,0,1,0,0,0,1,0,1,1,1,0,1,1,1,0, 0,1,0,0,0,1,0,0,0,1,1,1,0,1,1,1 -}; - -static const uint8_t g_bc7_partition3[64 * 16] = -{ - 0,0,1,1,0,0,1,1,0,2,2,1,2,2,2,2, 0,0,0,1,0,0,1,1,2,2,1,1,2,2,2,1, 0,0,0,0,2,0,0,1,2,2,1,1,2,2,1,1, 0,2,2,2,0,0,2,2,0,0,1,1,0,1,1,1, 0,0,0,0,0,0,0,0,1,1,2,2,1,1,2,2, 0,0,1,1,0,0,1,1,0,0,2,2,0,0,2,2, 0,0,2,2,0,0,2,2,1,1,1,1,1,1,1,1, 0,0,1,1,0,0,1,1,2,2,1,1,2,2,1,1, - 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2, 0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2, 0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2, 0,0,1,2,0,0,1,2,0,0,1,2,0,0,1,2, 0,1,1,2,0,1,1,2,0,1,1,2,0,1,1,2, 0,1,2,2,0,1,2,2,0,1,2,2,0,1,2,2, 0,0,1,1,0,1,1,2,1,1,2,2,1,2,2,2, 0,0,1,1,2,0,0,1,2,2,0,0,2,2,2,0, - 0,0,0,1,0,0,1,1,0,1,1,2,1,1,2,2, 0,1,1,1,0,0,1,1,2,0,0,1,2,2,0,0, 0,0,0,0,1,1,2,2,1,1,2,2,1,1,2,2, 0,0,2,2,0,0,2,2,0,0,2,2,1,1,1,1, 0,1,1,1,0,1,1,1,0,2,2,2,0,2,2,2, 0,0,0,1,0,0,0,1,2,2,2,1,2,2,2,1, 0,0,0,0,0,0,1,1,0,1,2,2,0,1,2,2, 0,0,0,0,1,1,0,0,2,2,1,0,2,2,1,0, - 0,1,2,2,0,1,2,2,0,0,1,1,0,0,0,0, 0,0,1,2,0,0,1,2,1,1,2,2,2,2,2,2, 0,1,1,0,1,2,2,1,1,2,2,1,0,1,1,0, 0,0,0,0,0,1,1,0,1,2,2,1,1,2,2,1, 0,0,2,2,1,1,0,2,1,1,0,2,0,0,2,2, 0,1,1,0,0,1,1,0,2,0,0,2,2,2,2,2, 0,0,1,1,0,1,2,2,0,1,2,2,0,0,1,1, 0,0,0,0,2,0,0,0,2,2,1,1,2,2,2,1, - 0,0,0,0,0,0,0,2,1,1,2,2,1,2,2,2, 0,2,2,2,0,0,2,2,0,0,1,2,0,0,1,1, 0,0,1,1,0,0,1,2,0,0,2,2,0,2,2,2, 0,1,2,0,0,1,2,0,0,1,2,0,0,1,2,0, 0,0,0,0,1,1,1,1,2,2,2,2,0,0,0,0, 0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0, 0,1,2,0,2,0,1,2,1,2,0,1,0,1,2,0, 0,0,1,1,2,2,0,0,1,1,2,2,0,0,1,1, - 0,0,1,1,1,1,2,2,2,2,0,0,0,0,1,1, 0,1,0,1,0,1,0,1,2,2,2,2,2,2,2,2, 0,0,0,0,0,0,0,0,2,1,2,1,2,1,2,1, 0,0,2,2,1,1,2,2,0,0,2,2,1,1,2,2, 0,0,2,2,0,0,1,1,0,0,2,2,0,0,1,1, 0,2,2,0,1,2,2,1,0,2,2,0,1,2,2,1, 0,1,0,1,2,2,2,2,2,2,2,2,0,1,0,1, 0,0,0,0,2,1,2,1,2,1,2,1,2,1,2,1, - 0,1,0,1,0,1,0,1,0,1,0,1,2,2,2,2, 0,2,2,2,0,1,1,1,0,2,2,2,0,1,1,1, 0,0,0,2,1,1,1,2,0,0,0,2,1,1,1,2, 0,0,0,0,2,1,1,2,2,1,1,2,2,1,1,2, 0,2,2,2,0,1,1,1,0,1,1,1,0,2,2,2, 0,0,0,2,1,1,1,2,1,1,1,2,0,0,0,2, 0,1,1,0,0,1,1,0,0,1,1,0,2,2,2,2, 0,0,0,0,0,0,0,0,2,1,1,2,2,1,1,2, - 0,1,1,0,0,1,1,0,2,2,2,2,2,2,2,2, 0,0,2,2,0,0,1,1,0,0,1,1,0,0,2,2, 0,0,2,2,1,1,2,2,1,1,2,2,0,0,2,2, 0,0,0,0,0,0,0,0,0,0,0,0,2,1,1,2, 0,0,0,2,0,0,0,1,0,0,0,2,0,0,0,1, 0,2,2,2,1,2,2,2,0,2,2,2,1,2,2,2, 0,1,0,1,2,2,2,2,2,2,2,2,2,2,2,2, 0,1,1,1,2,0,1,1,2,2,0,1,2,2,2,0, -}; - -static const uint8_t g_bc7_table_anchor_index_third_subset_1[64] = -{ - 3, 3,15,15, 8, 3,15,15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8,15, 3, 3, 6,10, 5, 8, 8, 6, 8, 5,15,15, 8,15, 3, 5, 6,10, 8,15, 15, 3,15, 5,15,15,15,15, 3,15, 5, 5, 5, 8, 5,10, 5,10, 8,13,15,12, 3, 3 -}; - -static const uint8_t g_bc7_table_anchor_index_third_subset_2[64] = -{ - 15, 8, 8, 3,15,15, 3, 8, 15,15,15,15,15,15,15, 8, 15, 8,15, 3,15, 8,15, 8, 3,15, 6,10,15,15,10, 8, 15, 3,15,10,10, 8, 9,10, 6,15, 8,15, 3, 6, 6, 8, 15, 3,15,15,15,15,15,15, 15,15,15,15, 3,15,15, 8 -}; - -static const uint8_t g_bc7_table_anchor_index_second_subset[64] = { 15,15,15,15,15,15,15,15, 15,15,15,15,15,15,15,15, 15, 2, 8, 2, 2, 8, 8,15, 2, 8, 2, 2, 8, 8, 2, 2, 15,15, 6, 8, 2, 8,15,15, 2, 8, 2, 2, 2,15,15, 6, 6, 2, 6, 8,15,15, 2, 2, 15,15,15,15,15, 2, 2,15 }; -static const uint8_t g_bc7_num_subsets[8] = { 3, 2, 3, 2, 1, 1, 1, 2 }; -static const uint8_t g_bc7_partition_bits[8] = { 4, 6, 6, 6, 0, 0, 0, 6 }; -static const uint8_t g_bc7_color_index_bitcount[8] = { 3, 3, 2, 2, 2, 2, 4, 2 }; -static int get_bc7_color_index_size(int mode, int index_selection_bit) { return g_bc7_color_index_bitcount[mode] + index_selection_bit; } -static uint8_t g_bc7_alpha_index_bitcount[8] = { 0, 0, 0, 0, 3, 2, 4, 2 }; -static int get_bc7_alpha_index_size(int mode, int index_selection_bit) { return g_bc7_alpha_index_bitcount[mode] - index_selection_bit; } -static const uint8_t g_bc7_mode_has_p_bits[8] = { 1, 1, 0, 1, 0, 0, 1, 1 }; -static const uint8_t g_bc7_mode_has_shared_p_bits[8] = { 0, 1, 0, 0, 0, 0, 0, 0 }; -static const uint8_t g_bc7_color_precision_table[8] = { 4, 6, 5, 7, 5, 7, 7, 5 }; -static const int8_t g_bc7_alpha_precision_table[8] = { 0, 0, 0, 0, 6, 8, 7, 5 }; -static bc7enc_bool get_bc7_mode_has_seperate_alpha_selectors(int mode) { return (mode == 4) || (mode == 5); } - -typedef struct { uint16_t m_error; uint8_t m_lo; uint8_t m_hi; } endpoint_err; - -// Initialize the lookup table used for optimal single color compression in mode 1. Must be called before encoding. -void bc7enc_compress_block_init() -{ +static inline int32_t clampi(int32_t value, int32_t low, int32_t high) { + if (value < low) + value = low; + else if (value > high) + value = high; + return value; +} +static inline float clampf(float value, float low, float high) { + if (value < low) + value = low; + else if (value > high) + value = high; + return value; +} +static inline float saturate(float value) { + return clampf(value, 0, 1.0f); +} +static inline uint32_t minimumu(uint32_t a, uint32_t b) { + return (a < b) ? a : b; +} +static inline float minimumf(float a, float b) { + return (a < b) ? a : b; +} +static inline float maximumf(float a, float b) { + return (a > b) ? a : b; +} +static inline int squarei(int i) { + return i * i; +} +static inline float squaref(float i) { + return i * i; } -typedef struct -{ - uint32_t m_num_pixels; +typedef struct { + uint8_t m_c[4]; +} color_quad_u8; +typedef struct { + float m_c[4]; +} vec4F; + +static inline color_quad_u8 *color_quad_u8_set_clamped(color_quad_u8 *pRes, int32_t r, int32_t g, int32_t b, int32_t a) { + pRes->m_c[0] = (uint8_t)clampi(r, 0, 255); + pRes->m_c[1] = (uint8_t)clampi(g, 0, 255); + pRes->m_c[2] = (uint8_t)clampi(b, 0, 255); + pRes->m_c[3] = (uint8_t)clampi(a, 0, 255); + return pRes; +} +static inline color_quad_u8 *color_quad_u8_set(color_quad_u8 *pRes, int32_t r, int32_t g, int32_t b, int32_t a) { + pRes->m_c[0] = (uint8_t)r; + pRes->m_c[1] = (uint8_t)g; + pRes->m_c[2] = (uint8_t)b; + pRes->m_c[3] = (uint8_t)a; + return pRes; +} +static inline bc7enc_bool color_quad_u8_notequals(const color_quad_u8 *pLHS, const color_quad_u8 *pRHS) { + return (pLHS->m_c[0] != pRHS->m_c[0]) || (pLHS->m_c[1] != pRHS->m_c[1]) || (pLHS->m_c[2] != pRHS->m_c[2]) || (pLHS->m_c[3] != pRHS->m_c[3]); +} +static inline vec4F *vec4F_set_scalar(vec4F *pV, float x) { + pV->m_c[0] = x; + pV->m_c[1] = x; + pV->m_c[2] = x; + pV->m_c[3] = x; + return pV; +} +static inline vec4F *vec4F_set(vec4F *pV, float x, float y, float z, float w) { + pV->m_c[0] = x; + pV->m_c[1] = y; + pV->m_c[2] = z; + pV->m_c[3] = w; + return pV; +} +static inline vec4F vec4F_from_color(const color_quad_u8 *pC) { + vec4F res; + vec4F_set(&res, pC->m_c[0], pC->m_c[1], pC->m_c[2], pC->m_c[3]); + return res; +} + +static inline vec4F *vec4F_saturate_in_place(vec4F *pV) { + pV->m_c[0] = saturate(pV->m_c[0]); + pV->m_c[1] = saturate(pV->m_c[1]); + pV->m_c[2] = saturate(pV->m_c[2]); + pV->m_c[3] = saturate(pV->m_c[3]); + return pV; +} +static inline vec4F vec4F_saturate(const vec4F *pV) { + vec4F res; + res.m_c[0] = saturate(pV->m_c[0]); + res.m_c[1] = saturate(pV->m_c[1]); + res.m_c[2] = saturate(pV->m_c[2]); + res.m_c[3] = saturate(pV->m_c[3]); + return res; +} +static inline vec4F vec4F_add(const vec4F *pLHS, const vec4F *pRHS) { + vec4F res; + vec4F_set(&res, pLHS->m_c[0] + pRHS->m_c[0], pLHS->m_c[1] + pRHS->m_c[1], pLHS->m_c[2] + pRHS->m_c[2], pLHS->m_c[3] + pRHS->m_c[3]); + return res; +} +static inline vec4F vec4F_sub(const vec4F *pLHS, const vec4F *pRHS) { + vec4F res; + vec4F_set(&res, pLHS->m_c[0] - pRHS->m_c[0], pLHS->m_c[1] - pRHS->m_c[1], pLHS->m_c[2] - pRHS->m_c[2], pLHS->m_c[3] - pRHS->m_c[3]); + return res; +} +static inline float vec4F_dot(const vec4F *pLHS, const vec4F *pRHS) { + return pLHS->m_c[0] * pRHS->m_c[0] + pLHS->m_c[1] * pRHS->m_c[1] + pLHS->m_c[2] * pRHS->m_c[2] + pLHS->m_c[3] * pRHS->m_c[3]; +} +static inline vec4F vec4F_mul(const vec4F *pLHS, float s) { + vec4F res; + vec4F_set(&res, pLHS->m_c[0] * s, pLHS->m_c[1] * s, pLHS->m_c[2] * s, pLHS->m_c[3] * s); + return res; +} +static inline vec4F *vec4F_normalize_in_place(vec4F *pV) { + float s = pV->m_c[0] * pV->m_c[0] + pV->m_c[1] * pV->m_c[1] + pV->m_c[2] * pV->m_c[2] + pV->m_c[3] * pV->m_c[3]; + if (s != 0.0f) { + s = 1.0f / sqrtf(s); + pV->m_c[0] *= s; + pV->m_c[1] *= s; + pV->m_c[2] *= s; + pV->m_c[3] *= s; + } + return pV; +} + +// Various BC7 tables +static const uint32_t g_bc7_weights2[4] = {0, 21, 43, 64}; +static const uint32_t g_bc7_weights3[8] = {0, 9, 18, 27, 37, 46, 55, 64}; +static const uint32_t g_bc7_weights4[16] = {0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64}; +// Precomputed weight constants used during least fit determination. For each entry in g_bc7_weights[]: w * w, (1.0f - w) * w, (1.0f - w) * (1.0f - w), w +static const float g_bc7_weights4x[16 * 4] = {0.000000f, 0.000000f, 1.000000f, 0.000000f, 0.003906f, 0.058594f, 0.878906f, 0.062500f, 0.019775f, 0.120850f, + 0.738525f, 0.140625f, 0.041260f, 0.161865f, 0.635010f, 0.203125f, 0.070557f, 0.195068f, 0.539307f, 0.265625f, + 0.107666f, 0.220459f, 0.451416f, 0.328125f, 0.165039f, 0.241211f, 0.352539f, 0.406250f, 0.219727f, 0.249023f, + 0.282227f, 0.468750f, 0.282227f, 0.249023f, 0.219727f, 0.531250f, 0.352539f, 0.241211f, 0.165039f, 0.593750f, + 0.451416f, 0.220459f, 0.107666f, 0.671875f, 0.539307f, 0.195068f, 0.070557f, 0.734375f, 0.635010f, 0.161865f, + 0.041260f, 0.796875f, 0.738525f, 0.120850f, 0.019775f, 0.859375f, 0.878906f, 0.058594f, 0.003906f, 0.937500f, + 1.000000f, 0.000000f, 0.000000f, 1.000000f}; + +static const uint8_t g_bc7_partition1[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; +static const uint8_t g_bc7_partition2[64 * 16] = { + 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, + 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, + 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, + 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, + 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, + 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, + 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, + 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, + 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, + 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, + 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, + 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, + 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, + 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, + 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, + 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1}; + +static const uint8_t g_bc7_partition3[64 * 16] = { + 0, 0, 1, 1, 0, 0, 1, 1, 0, 2, 2, 1, 2, 2, 2, 2, 0, 0, 0, 1, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2, 2, 1, 0, 0, 0, 0, 2, 0, 0, 1, 2, 2, 1, 1, 2, 2, 1, 1, 0, 2, 2, 2, + 0, 0, 2, 2, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2, + 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, + 2, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0, 1, 1, 2, 0, 1, 1, 2, 0, 1, 1, 2, 0, 1, 1, 2, + 0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 2, 0, 0, 1, 1, 0, 1, 1, 2, 1, 1, 2, 2, 1, 2, 2, 2, 0, 0, 1, 1, 2, 0, 0, 1, 2, 2, 0, 0, 2, 2, 2, 0, 0, 0, 0, 1, + 0, 0, 1, 1, 0, 1, 1, 2, 1, 1, 2, 2, 0, 1, 1, 1, 0, 0, 1, 1, 2, 0, 0, 1, 2, 2, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2, + 0, 0, 2, 2, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 2, 2, 2, 0, 2, 2, 2, 0, 0, 0, 1, 0, 0, 0, 1, 2, 2, 2, 1, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 2, 2, + 0, 1, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 1, 0, 2, 2, 1, 0, 0, 1, 2, 2, 0, 1, 2, 2, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 1, 2, 1, 1, 2, 2, 2, 2, 2, 2, + 0, 1, 1, 0, 1, 2, 2, 1, 1, 2, 2, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 2, 2, 1, 1, 2, 2, 1, 0, 0, 2, 2, 1, 1, 0, 2, 1, 1, 0, 2, 0, 0, 2, 2, 0, 1, 1, 0, + 0, 1, 1, 0, 2, 0, 0, 2, 2, 2, 2, 2, 0, 0, 1, 1, 0, 1, 2, 2, 0, 1, 2, 2, 0, 0, 1, 1, 0, 0, 0, 0, 2, 0, 0, 0, 2, 2, 1, 1, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 2, + 1, 1, 2, 2, 1, 2, 2, 2, 0, 2, 2, 2, 0, 0, 2, 2, 0, 0, 1, 2, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 2, 0, 0, 2, 2, 0, 2, 2, 2, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0, + 0, 1, 2, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 0, 1, 2, 0, 2, 0, 1, 2, 1, 2, 0, 1, 0, 1, 2, 0, + 0, 0, 1, 1, 2, 2, 0, 0, 1, 1, 2, 2, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, + 0, 0, 0, 0, 2, 1, 2, 1, 2, 1, 2, 1, 0, 0, 2, 2, 1, 1, 2, 2, 0, 0, 2, 2, 1, 1, 2, 2, 0, 0, 2, 2, 0, 0, 1, 1, 0, 0, 2, 2, 0, 0, 1, 1, 0, 2, 2, 0, 1, 2, 2, 1, + 0, 2, 2, 0, 1, 2, 2, 1, 0, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 0, 1, 0, 1, 0, 0, 0, 0, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, + 2, 2, 2, 2, 0, 2, 2, 2, 0, 1, 1, 1, 0, 2, 2, 2, 0, 1, 1, 1, 0, 0, 0, 2, 1, 1, 1, 2, 0, 0, 0, 2, 1, 1, 1, 2, 0, 0, 0, 0, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, + 0, 2, 2, 2, 0, 1, 1, 1, 0, 1, 1, 1, 0, 2, 2, 2, 0, 0, 0, 2, 1, 1, 1, 2, 1, 1, 1, 2, 0, 0, 0, 2, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 2, 2, 2, 2, 0, 0, 0, 0, + 0, 0, 0, 0, 2, 1, 1, 2, 2, 1, 1, 2, 0, 1, 1, 0, 0, 1, 1, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 2, 2, 0, 0, 2, 2, 1, 1, 2, 2, + 1, 1, 2, 2, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 2, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1, 0, 2, 2, 2, 1, 2, 2, 2, 0, 2, 2, 2, + 1, 2, 2, 2, 0, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 1, 1, 1, 2, 0, 1, 1, 2, 2, 0, 1, 2, 2, 2, 0, +}; + +static const uint8_t g_bc7_table_anchor_index_third_subset_1[64] = {3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, + 6, 10, 5, 8, 8, 6, 8, 5, 15, 15, 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, + 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5, 10, 8, 13, 15, 12, 3, 3}; + +static const uint8_t g_bc7_table_anchor_index_third_subset_2[64] = {15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, + 15, 8, 3, 15, 6, 10, 15, 15, 10, 8, 15, 3, 15, 10, 10, 8, 9, 10, 6, 15, 8, 15, + 3, 6, 6, 8, 15, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8}; + +static const uint8_t g_bc7_table_anchor_index_second_subset[64] = {15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, + 8, 15, 2, 8, 2, 2, 8, 8, 2, 2, 15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, + 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2, 2, 15, 15, 15, 15, 15, 2, 2, 15}; +static const uint8_t g_bc7_num_subsets[8] = {3, 2, 3, 2, 1, 1, 1, 2}; +static const uint8_t g_bc7_partition_bits[8] = {4, 6, 6, 6, 0, 0, 0, 6}; +static const uint8_t g_bc7_color_index_bitcount[8] = {3, 3, 2, 2, 2, 2, 4, 2}; +static int get_bc7_color_index_size(int mode, int index_selection_bit) { + return g_bc7_color_index_bitcount[mode] + index_selection_bit; +} +static uint8_t g_bc7_alpha_index_bitcount[8] = {0, 0, 0, 0, 3, 2, 4, 2}; +static int get_bc7_alpha_index_size(int mode, int index_selection_bit) { + return g_bc7_alpha_index_bitcount[mode] - index_selection_bit; +} +static const uint8_t g_bc7_mode_has_p_bits[8] = {1, 1, 0, 1, 0, 0, 1, 1}; +static const uint8_t g_bc7_mode_has_shared_p_bits[8] = {0, 1, 0, 0, 0, 0, 0, 0}; +static const uint8_t g_bc7_color_precision_table[8] = {4, 6, 5, 7, 5, 7, 7, 5}; +static const int8_t g_bc7_alpha_precision_table[8] = {0, 0, 0, 0, 6, 8, 7, 5}; +static bc7enc_bool get_bc7_mode_has_seperate_alpha_selectors(int mode) { + return (mode == 4) || (mode == 5); +} + +typedef struct { + uint16_t m_error; + uint8_t m_lo; + uint8_t m_hi; +} endpoint_err; + +// Initialize the lookup table used for optimal single color compression in mode 1. Must be called before encoding. +void bc7enc_compress_block_init() {} + +typedef struct { + uint32_t m_num_pixels; const color_quad_u8 *m_pPixels; - uint32_t m_num_selector_weights; - const uint32_t *m_pSelector_weights; - const vec4F *m_pSelector_weightsx; - uint32_t m_comp_bits; - uint32_t m_weights[4]; - bc7enc_bool m_has_alpha; - bc7enc_bool m_has_pbits; - bc7enc_bool m_endpoints_share_pbit; - bc7enc_bool m_perceptual; + uint32_t m_num_selector_weights; + const uint32_t *m_pSelector_weights; + const vec4F *m_pSelector_weightsx; + uint32_t m_comp_bits; + uint32_t m_weights[4]; + bc7enc_bool m_has_alpha; + bc7enc_bool m_has_pbits; + bc7enc_bool m_endpoints_share_pbit; + bc7enc_bool m_perceptual; } color_cell_compressor_params; -typedef struct -{ - uint64_t m_best_overall_err; +typedef struct { + uint64_t m_best_overall_err; color_quad_u8 m_low_endpoint; color_quad_u8 m_high_endpoint; - uint32_t m_pbits[2]; - uint8_t *m_pSelectors; - uint8_t *m_pSelectors_temp; + uint32_t m_pbits[2]; + uint8_t *m_pSelectors; + uint8_t *m_pSelectors_temp; } color_cell_compressor_results; -static inline color_quad_u8 scale_color(const color_quad_u8 *pC, const color_cell_compressor_params *pParams) -{ +static inline color_quad_u8 scale_color(const color_quad_u8 *pC, const color_cell_compressor_params *pParams) { color_quad_u8 results; const uint32_t n = pParams->m_comp_bits + (pParams->m_has_pbits ? 1 : 0); - for (uint32_t i = 0; i < 4; i++) - { + for (uint32_t i = 0; i < 4; i++) { uint32_t v = pC->m_c[i] << (8 - n); v |= (v >> n); results.m_c[i] = (uint8_t)(v); @@ -188,24 +311,21 @@ static inline color_quad_u8 scale_color(const color_quad_u8 *pC, const color_cel return results; } -static inline uint64_t compute_color_distance_rgb(const color_quad_u8 *pE1, const color_quad_u8 *pE2, bc7enc_bool perceptual, const uint32_t weights[4]) -{ +static inline uint64_t compute_color_distance_rgb(const color_quad_u8 *pE1, const color_quad_u8 *pE2, bc7enc_bool perceptual, const uint32_t weights[4]) { int dr, dg, db; - if (perceptual) - { - const int l1 = pE1->m_c[0] * 109 + pE1->m_c[1] * 366 + pE1->m_c[2] * 37; + if (perceptual) { + const int l1 = pE1->m_c[0] * 109 + pE1->m_c[1] * 366 + pE1->m_c[2] * 37; const int cr1 = ((int)pE1->m_c[0] << 9) - l1; const int cb1 = ((int)pE1->m_c[2] << 9) - l1; - const int l2 = pE2->m_c[0] * 109 + pE2->m_c[1] * 366 + pE2->m_c[2] * 37; + const int l2 = pE2->m_c[0] * 109 + pE2->m_c[1] * 366 + pE2->m_c[2] * 37; const int cr2 = ((int)pE2->m_c[0] << 9) - l2; const int cb2 = ((int)pE2->m_c[2] << 9) - l2; - dr = (l1 - l2) >> 8; - dg = (cr1 - cr2) >> 8; - db = (cb1 - cb2) >> 8; + dr = (l1 - l2) >> 8; + dg = (cr1 - cr2) >> 8; + db = (cb1 - cb2) >> 8; } - else - { + else { dr = (int)pE1->m_c[0] - (int)pE2->m_c[0]; dg = (int)pE1->m_c[1] - (int)pE2->m_c[1]; db = (int)pE1->m_c[2] - (int)pE2->m_c[2]; @@ -214,25 +334,22 @@ static inline uint64_t compute_color_distance_rgb(const color_quad_u8 *pE1, cons return weights[0] * (uint32_t)(dr * dr) + weights[1] * (uint32_t)(dg * dg) + weights[2] * (uint32_t)(db * db); } -static inline uint64_t compute_color_distance_rgba(const color_quad_u8 *pE1, const color_quad_u8 *pE2, bc7enc_bool perceptual, const uint32_t weights[4]) -{ +static inline uint64_t compute_color_distance_rgba(const color_quad_u8 *pE1, const color_quad_u8 *pE2, bc7enc_bool perceptual, const uint32_t weights[4]) { int da = (int)pE1->m_c[3] - (int)pE2->m_c[3]; return compute_color_distance_rgb(pE1, pE2, perceptual, weights) + (weights[3] * (uint32_t)(da * da)); } -static uint64_t evaluate_solution(const color_quad_u8 *pLow, const color_quad_u8 *pHigh, const uint32_t pbits[2], const color_cell_compressor_params *pParams, color_cell_compressor_results *pResults) -{ +static uint64_t evaluate_solution(const color_quad_u8 *pLow, const color_quad_u8 *pHigh, const uint32_t pbits[2], const color_cell_compressor_params *pParams, + color_cell_compressor_results *pResults) { color_quad_u8 quantMinColor = *pLow; color_quad_u8 quantMaxColor = *pHigh; - if (pParams->m_has_pbits) - { + if (pParams->m_has_pbits) { uint32_t minPBit, maxPBit; if (pParams->m_endpoints_share_pbit) maxPBit = minPBit = pbits[0]; - else - { + else { minPBit = pbits[0]; maxPBit = pbits[1]; } @@ -254,13 +371,14 @@ static uint64_t evaluate_solution(const color_quad_u8 *pLow, const color_quad_u8 const uint32_t N = pParams->m_num_selector_weights; color_quad_u8 weightedColors[16]; - weightedColors[0] = actualMinColor; + weightedColors[0] = actualMinColor; weightedColors[N - 1] = actualMaxColor; const uint32_t nc = pParams->m_has_alpha ? 4 : 3; for (uint32_t i = 1; i < (N - 1); i++) for (uint32_t j = 0; j < nc; j++) - weightedColors[i].m_c[j] = (uint8_t)((actualMinColor.m_c[j] * (64 - pParams->m_pSelector_weights[i]) + actualMaxColor.m_c[j] * pParams->m_pSelector_weights[i] + 32) >> 6); + weightedColors[i].m_c[j] = + (uint8_t)((actualMinColor.m_c[j] * (64 - pParams->m_pSelector_weights[i]) + actualMaxColor.m_c[j] * pParams->m_pSelector_weights[i] + 32) >> 6); const int lr = actualMinColor.m_c[0]; const int lg = actualMinColor.m_c[1]; @@ -274,9 +392,8 @@ static uint64_t evaluate_solution(const color_quad_u8 *pLow, const color_quad_u8 // Precompute perceptual luma/chroma for all N candidates once. // Values fit exactly in float32 (max luma = 255*512 = 130560 < 2^24). float cand_l_f[16], cand_cr_f[16], cand_cb_f[16], cand_a_f[16]; - for (uint32_t j = 0; j < N; j++) - { - const int l = weightedColors[j].m_c[0] * 109 + weightedColors[j].m_c[1] * 366 + weightedColors[j].m_c[2] * 37; + for (uint32_t j = 0; j < N; j++) { + const int l = weightedColors[j].m_c[0] * 109 + weightedColors[j].m_c[1] * 366 + weightedColors[j].m_c[2] * 37; cand_l_f[j] = (float)l; cand_cr_f[j] = (float)(((int)weightedColors[j].m_c[0] << 9) - l); cand_cb_f[j] = (float)(((int)weightedColors[j].m_c[2] << 9) - l); @@ -286,13 +403,12 @@ static uint64_t evaluate_solution(const color_quad_u8 *pLow, const color_quad_u8 #ifndef IRON_NOSIMD // Precompute pixel luma/chroma so the inner loop is pure SIMD with no branching or extraction. float pix_l_f[16], pix_cr_f[16], pix_cb_f[16]; - for (uint32_t i = 0; i < pParams->m_num_pixels; i++) - { + for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { const color_quad_u8 *pPix = &pParams->m_pPixels[i]; - const int l = pPix->m_c[0] * 109 + pPix->m_c[1] * 366 + pPix->m_c[2] * 37; - pix_l_f[i] = (float)l; - pix_cr_f[i] = (float)(((int)pPix->m_c[0] << 9) - l); - pix_cb_f[i] = (float)(((int)pPix->m_c[2] << 9) - l); + const int l = pPix->m_c[0] * 109 + pPix->m_c[1] * 366 + pPix->m_c[2] * 37; + pix_l_f[i] = (float)l; + pix_cr_f[i] = (float)(((int)pPix->m_c[0] << 9) - l); + pix_cb_f[i] = (float)(((int)pPix->m_c[2] << 9) - l); } // Per-pixel best error and selector stored as floats. @@ -301,8 +417,7 @@ static uint64_t evaluate_solution(const color_quad_u8 *pLow, const color_quad_u8 { const iron_float32x4_t inf4 = iron_float32x4_load_all(1e30f); const iron_float32x4_t zer4 = iron_float32x4_load_all(0.0f); - for (uint32_t i = 0; i < 16; i += 4) - { + for (uint32_t i = 0; i < 16; i += 4) { iron_float32x4_store_unaligned(&best_err_f[i], inf4); iron_float32x4_store_unaligned(&best_sel_f[i], zer4); } @@ -313,57 +428,51 @@ static uint64_t evaluate_solution(const color_quad_u8 *pLow, const color_quad_u8 const iron_float32x4_t w1v = iron_float32x4_load_all((float)pParams->m_weights[1]); const iron_float32x4_t w2v = iron_float32x4_load_all((float)pParams->m_weights[2]); - if (pParams->m_has_alpha) - { + if (pParams->m_has_alpha) { float pix_a_f[16]; for (uint32_t i = 0; i < pParams->m_num_pixels; i++) pix_a_f[i] = (float)pParams->m_pPixels[i].m_c[3]; const iron_float32x4_t w3v = iron_float32x4_load_all((float)pParams->m_weights[3]); - for (uint32_t j = 0; j < N; j++) - { + for (uint32_t j = 0; j < N; j++) { const iron_float32x4_t l1v = iron_float32x4_load_all(cand_l_f[j]); const iron_float32x4_t cr1v = iron_float32x4_load_all(cand_cr_f[j]); const iron_float32x4_t cb1v = iron_float32x4_load_all(cand_cb_f[j]); const iron_float32x4_t a1v = iron_float32x4_load_all(cand_a_f[j]); const iron_float32x4_t jv = iron_float32x4_load_all((float)j); - for (uint32_t i = 0; i < 16; i += 4) - { - const iron_float32x4_t drv = iron_float32x4_mul(iron_float32x4_sub(l1v, iron_float32x4_intrin_load_unaligned(&pix_l_f[i])), inv256); - const iron_float32x4_t dgv = iron_float32x4_mul(iron_float32x4_sub(cr1v, iron_float32x4_intrin_load_unaligned(&pix_cr_f[i])), inv256); - const iron_float32x4_t dbv = iron_float32x4_mul(iron_float32x4_sub(cb1v, iron_float32x4_intrin_load_unaligned(&pix_cb_f[i])), inv256); - const iron_float32x4_t dav = iron_float32x4_sub(a1v, iron_float32x4_intrin_load_unaligned(&pix_a_f[i])); - iron_float32x4_t errv = iron_float32x4_mul(w0v, iron_float32x4_mul(drv, drv)); - errv = iron_float32x4_add(errv, iron_float32x4_mul(w1v, iron_float32x4_mul(dgv, dgv))); - errv = iron_float32x4_add(errv, iron_float32x4_mul(w2v, iron_float32x4_mul(dbv, dbv))); - errv = iron_float32x4_add(errv, iron_float32x4_mul(w3v, iron_float32x4_mul(dav, dav))); - iron_float32x4_t best_v = iron_float32x4_intrin_load_unaligned(&best_err_f[i]); - iron_float32x4_t best_sv = iron_float32x4_intrin_load_unaligned(&best_sel_f[i]); - const iron_float32x4_mask_t better = iron_float32x4_cmplt(errv, best_v); + for (uint32_t i = 0; i < 16; i += 4) { + const iron_float32x4_t drv = iron_float32x4_mul(iron_float32x4_sub(l1v, iron_float32x4_intrin_load_unaligned(&pix_l_f[i])), inv256); + const iron_float32x4_t dgv = iron_float32x4_mul(iron_float32x4_sub(cr1v, iron_float32x4_intrin_load_unaligned(&pix_cr_f[i])), inv256); + const iron_float32x4_t dbv = iron_float32x4_mul(iron_float32x4_sub(cb1v, iron_float32x4_intrin_load_unaligned(&pix_cb_f[i])), inv256); + const iron_float32x4_t dav = iron_float32x4_sub(a1v, iron_float32x4_intrin_load_unaligned(&pix_a_f[i])); + iron_float32x4_t errv = iron_float32x4_mul(w0v, iron_float32x4_mul(drv, drv)); + errv = iron_float32x4_add(errv, iron_float32x4_mul(w1v, iron_float32x4_mul(dgv, dgv))); + errv = iron_float32x4_add(errv, iron_float32x4_mul(w2v, iron_float32x4_mul(dbv, dbv))); + errv = iron_float32x4_add(errv, iron_float32x4_mul(w3v, iron_float32x4_mul(dav, dav))); + iron_float32x4_t best_v = iron_float32x4_intrin_load_unaligned(&best_err_f[i]); + iron_float32x4_t best_sv = iron_float32x4_intrin_load_unaligned(&best_sel_f[i]); + const iron_float32x4_mask_t better = iron_float32x4_cmplt(errv, best_v); iron_float32x4_store_unaligned(&best_err_f[i], iron_float32x4_min(errv, best_v)); iron_float32x4_store_unaligned(&best_sel_f[i], iron_float32x4_sel(jv, best_sv, better)); } } } - else - { - for (uint32_t j = 0; j < N; j++) - { + else { + for (uint32_t j = 0; j < N; j++) { const iron_float32x4_t l1v = iron_float32x4_load_all(cand_l_f[j]); const iron_float32x4_t cr1v = iron_float32x4_load_all(cand_cr_f[j]); const iron_float32x4_t cb1v = iron_float32x4_load_all(cand_cb_f[j]); const iron_float32x4_t jv = iron_float32x4_load_all((float)j); - for (uint32_t i = 0; i < 16; i += 4) - { - const iron_float32x4_t drv = iron_float32x4_mul(iron_float32x4_sub(l1v, iron_float32x4_intrin_load_unaligned(&pix_l_f[i])), inv256); - const iron_float32x4_t dgv = iron_float32x4_mul(iron_float32x4_sub(cr1v, iron_float32x4_intrin_load_unaligned(&pix_cr_f[i])), inv256); - const iron_float32x4_t dbv = iron_float32x4_mul(iron_float32x4_sub(cb1v, iron_float32x4_intrin_load_unaligned(&pix_cb_f[i])), inv256); - iron_float32x4_t errv = iron_float32x4_mul(w0v, iron_float32x4_mul(drv, drv)); - errv = iron_float32x4_add(errv, iron_float32x4_mul(w1v, iron_float32x4_mul(dgv, dgv))); - errv = iron_float32x4_add(errv, iron_float32x4_mul(w2v, iron_float32x4_mul(dbv, dbv))); - iron_float32x4_t best_v = iron_float32x4_intrin_load_unaligned(&best_err_f[i]); - iron_float32x4_t best_sv = iron_float32x4_intrin_load_unaligned(&best_sel_f[i]); - const iron_float32x4_mask_t better = iron_float32x4_cmplt(errv, best_v); + for (uint32_t i = 0; i < 16; i += 4) { + const iron_float32x4_t drv = iron_float32x4_mul(iron_float32x4_sub(l1v, iron_float32x4_intrin_load_unaligned(&pix_l_f[i])), inv256); + const iron_float32x4_t dgv = iron_float32x4_mul(iron_float32x4_sub(cr1v, iron_float32x4_intrin_load_unaligned(&pix_cr_f[i])), inv256); + const iron_float32x4_t dbv = iron_float32x4_mul(iron_float32x4_sub(cb1v, iron_float32x4_intrin_load_unaligned(&pix_cb_f[i])), inv256); + iron_float32x4_t errv = iron_float32x4_mul(w0v, iron_float32x4_mul(drv, drv)); + errv = iron_float32x4_add(errv, iron_float32x4_mul(w1v, iron_float32x4_mul(dgv, dgv))); + errv = iron_float32x4_add(errv, iron_float32x4_mul(w2v, iron_float32x4_mul(dbv, dbv))); + iron_float32x4_t best_v = iron_float32x4_intrin_load_unaligned(&best_err_f[i]); + iron_float32x4_t best_sv = iron_float32x4_intrin_load_unaligned(&best_sel_f[i]); + const iron_float32x4_mask_t better = iron_float32x4_cmplt(errv, best_v); iron_float32x4_store_unaligned(&best_err_f[i], iron_float32x4_min(errv, best_v)); iron_float32x4_store_unaligned(&best_sel_f[i], iron_float32x4_sel(jv, best_sv, better)); } @@ -371,44 +480,46 @@ static uint64_t evaluate_solution(const color_quad_u8 *pLow, const color_quad_u8 } // 16 scalar extractions — only done once per evaluate_solution call. - for (uint32_t i = 0; i < pParams->m_num_pixels; i++) - { + for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { total_err += (uint64_t)best_err_f[i]; pResults->m_pSelectors_temp[i] = (uint8_t)(int)best_sel_f[i]; } #else // IRON_NOSIMD - for (uint32_t i = 0; i < pParams->m_num_pixels; i++) - { - uint64_t best_err = UINT64_MAX; - uint32_t best_sel = 0; - const color_quad_u8 *pPix = &pParams->m_pPixels[i]; - const int l2 = pPix->m_c[0] * 109 + pPix->m_c[1] * 366 + pPix->m_c[2] * 37; - const int cr2 = ((int)pPix->m_c[0] << 9) - l2; - const int cb2 = ((int)pPix->m_c[2] << 9) - l2; - if (pParams->m_has_alpha) - { + for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { + uint64_t best_err = UINT64_MAX; + uint32_t best_sel = 0; + const color_quad_u8 *pPix = &pParams->m_pPixels[i]; + const int l2 = pPix->m_c[0] * 109 + pPix->m_c[1] * 366 + pPix->m_c[2] * 37; + const int cr2 = ((int)pPix->m_c[0] << 9) - l2; + const int cb2 = ((int)pPix->m_c[2] << 9) - l2; + if (pParams->m_has_alpha) { const int a2 = (int)pPix->m_c[3]; - for (uint32_t j = 0; j < N; j++) - { - const int dr = ((int)cand_l_f[j] - l2) >> 8; - const int dg = ((int)cand_cr_f[j] - cr2) >> 8; - const int db = ((int)cand_cb_f[j] - cb2) >> 8; - const int da = (int)cand_a_f[j] - a2; - const uint64_t err = pParams->m_weights[0] * (uint32_t)(dr * dr) + pParams->m_weights[1] * (uint32_t)(dg * dg) + pParams->m_weights[2] * (uint32_t)(db * db) + pParams->m_weights[3] * (uint32_t)(da * da); - if (err < best_err) { best_err = err; best_sel = j; } + for (uint32_t j = 0; j < N; j++) { + const int dr = ((int)cand_l_f[j] - l2) >> 8; + const int dg = ((int)cand_cr_f[j] - cr2) >> 8; + const int db = ((int)cand_cb_f[j] - cb2) >> 8; + const int da = (int)cand_a_f[j] - a2; + const uint64_t err = pParams->m_weights[0] * (uint32_t)(dr * dr) + pParams->m_weights[1] * (uint32_t)(dg * dg) + + pParams->m_weights[2] * (uint32_t)(db * db) + pParams->m_weights[3] * (uint32_t)(da * da); + if (err < best_err) { + best_err = err; + best_sel = j; + } } } - else - { - for (uint32_t j = 0; j < N; j++) - { - const int dr = ((int)cand_l_f[j] - l2) >> 8; - const int dg = ((int)cand_cr_f[j] - cr2) >> 8; - const int db = ((int)cand_cb_f[j] - cb2) >> 8; - const uint64_t err = pParams->m_weights[0] * (uint32_t)(dr * dr) + pParams->m_weights[1] * (uint32_t)(dg * dg) + pParams->m_weights[2] * (uint32_t)(db * db); - if (err < best_err) { best_err = err; best_sel = j; } + else { + for (uint32_t j = 0; j < N; j++) { + const int dr = ((int)cand_l_f[j] - l2) >> 8; + const int dg = ((int)cand_cr_f[j] - cr2) >> 8; + const int db = ((int)cand_cb_f[j] - cb2) >> 8; + const uint64_t err = + pParams->m_weights[0] * (uint32_t)(dr * dr) + pParams->m_weights[1] * (uint32_t)(dg * dg) + pParams->m_weights[2] * (uint32_t)(db * db); + if (err < best_err) { + best_err = err; + best_sel = j; + } } } total_err += best_err; @@ -416,11 +527,10 @@ static uint64_t evaluate_solution(const color_quad_u8 *pLow, const color_quad_u8 } #endif - if (total_err < pResults->m_best_overall_err) - { + if (total_err < pResults->m_best_overall_err) { pResults->m_best_overall_err = total_err; - pResults->m_low_endpoint = *pLow; + pResults->m_low_endpoint = *pLow; pResults->m_high_endpoint = *pHigh; pResults->m_pbits[0] = pbits[0]; @@ -432,53 +542,47 @@ static uint64_t evaluate_solution(const color_quad_u8 *pLow, const color_quad_u8 return total_err; } -static uint64_t find_optimal_solution(uint32_t mode, vec4F xl, vec4F xh, const color_cell_compressor_params *pParams, color_cell_compressor_results *pResults) -{ - vec4F_saturate_in_place(&xl); vec4F_saturate_in_place(&xh); +static uint64_t find_optimal_solution(uint32_t mode, vec4F xl, vec4F xh, const color_cell_compressor_params *pParams, color_cell_compressor_results *pResults) { + vec4F_saturate_in_place(&xl); + vec4F_saturate_in_place(&xh); - if (pParams->m_has_pbits) - { - const int iscalep = (1 << (pParams->m_comp_bits + 1)) - 1; - const float scalep = (float)iscalep; + if (pParams->m_has_pbits) { + const int iscalep = (1 << (pParams->m_comp_bits + 1)) - 1; + const float scalep = (float)iscalep; const int32_t totalComps = pParams->m_has_alpha ? 4 : 3; - uint32_t best_pbits[2]; + uint32_t best_pbits[2]; color_quad_u8 bestMinColor, bestMaxColor; - if (!pParams->m_endpoints_share_pbit) - { + if (!pParams->m_endpoints_share_pbit) { float best_err0 = 1e+9; float best_err1 = 1e+9; - for (int p = 0; p < 2; p++) - { + for (int p = 0; p < 2; p++) { color_quad_u8 xMinColor, xMaxColor; // Notes: The pbit controls which quantization intervals are selected. // total_levels=2^(comp_bits+1), where comp_bits=4 for mode 0, etc. - // pbit 0: v=(b*2)/(total_levels-1), pbit 1: v=(b*2+1)/(total_levels-1) where b is the component bin from [0,total_levels/2-1] and v is the [0,1] component value - // rearranging you get for pbit 0: b=floor(v*(total_levels-1)/2+.5) - // rearranging you get for pbit 1: b=floor((v*(total_levels-1)-1)/2+.5) - for (uint32_t c = 0; c < 4; c++) - { + // pbit 0: v=(b*2)/(total_levels-1), pbit 1: v=(b*2+1)/(total_levels-1) where b is the component bin from [0,total_levels/2-1] and v is the + // [0,1] component value rearranging you get for pbit 0: b=floor(v*(total_levels-1)/2+.5) rearranging you get for pbit 1: + // b=floor((v*(total_levels-1)-1)/2+.5) + for (uint32_t c = 0; c < 4; c++) { xMinColor.m_c[c] = (uint8_t)(clampi(((int)((xl.m_c[c] * scalep - p) / 2.0f + .5f)) * 2 + p, p, iscalep - 1 + p)); xMaxColor.m_c[c] = (uint8_t)(clampi(((int)((xh.m_c[c] * scalep - p) / 2.0f + .5f)) * 2 + p, p, iscalep - 1 + p)); } - color_quad_u8 scaledLow = scale_color(&xMinColor, pParams); + color_quad_u8 scaledLow = scale_color(&xMinColor, pParams); color_quad_u8 scaledHigh = scale_color(&xMaxColor, pParams); float err0 = 0, err1 = 0; - for (int i = 0; i < totalComps; i++) - { + for (int i = 0; i < totalComps; i++) { err0 += squaref(scaledLow.m_c[i] - xl.m_c[i] * 255.0f); err1 += squaref(scaledHigh.m_c[i] - xh.m_c[i] * 255.0f); } - if (err0 < best_err0) - { - best_err0 = err0; + if (err0 < best_err0) { + best_err0 = err0; best_pbits[0] = p; bestMinColor.m_c[0] = xMinColor.m_c[0] >> 1; @@ -487,9 +591,8 @@ static uint64_t find_optimal_solution(uint32_t mode, vec4F xl, vec4F xh, const c bestMinColor.m_c[3] = xMinColor.m_c[3] >> 1; } - if (err1 < best_err1) - { - best_err1 = err1; + if (err1 < best_err1) { + best_err1 = err1; best_pbits[1] = p; bestMaxColor.m_c[0] = xMaxColor.m_c[0] >> 1; @@ -499,34 +602,29 @@ static uint64_t find_optimal_solution(uint32_t mode, vec4F xl, vec4F xh, const c } } } - else - { + else { // Endpoints share pbits float best_err = 1e+9; - for (int p = 0; p < 2; p++) - { + for (int p = 0; p < 2; p++) { color_quad_u8 xMinColor, xMaxColor; - for (uint32_t c = 0; c < 4; c++) - { + for (uint32_t c = 0; c < 4; c++) { xMinColor.m_c[c] = (uint8_t)(clampi(((int)((xl.m_c[c] * scalep - p) / 2.0f + .5f)) * 2 + p, p, iscalep - 1 + p)); xMaxColor.m_c[c] = (uint8_t)(clampi(((int)((xh.m_c[c] * scalep - p) / 2.0f + .5f)) * 2 + p, p, iscalep - 1 + p)); } - color_quad_u8 scaledLow = scale_color(&xMinColor, pParams); + color_quad_u8 scaledLow = scale_color(&xMinColor, pParams); color_quad_u8 scaledHigh = scale_color(&xMaxColor, pParams); float err = 0; for (int i = 0; i < totalComps; i++) err += squaref((scaledLow.m_c[i] / 255.0f) - xl.m_c[i]) + squaref((scaledHigh.m_c[i] / 255.0f) - xh.m_c[i]); - if (err < best_err) - { - best_err = err; + if (err < best_err) { + best_err = err; best_pbits[0] = p; best_pbits[1] = p; - for (uint32_t j = 0; j < 4; j++) - { + for (uint32_t j = 0; j < 4; j++) { bestMinColor.m_c[j] = xMinColor.m_c[j] >> 1; bestMaxColor.m_c[j] = xMaxColor.m_c[j] >> 1; } @@ -534,37 +632,40 @@ static uint64_t find_optimal_solution(uint32_t mode, vec4F xl, vec4F xh, const c } } - if ((pResults->m_best_overall_err == UINT64_MAX) || color_quad_u8_notequals(&bestMinColor, &pResults->m_low_endpoint) || color_quad_u8_notequals(&bestMaxColor, &pResults->m_high_endpoint) || (best_pbits[0] != pResults->m_pbits[0]) || (best_pbits[1] != pResults->m_pbits[1])) + if ((pResults->m_best_overall_err == UINT64_MAX) || color_quad_u8_notequals(&bestMinColor, &pResults->m_low_endpoint) || + color_quad_u8_notequals(&bestMaxColor, &pResults->m_high_endpoint) || (best_pbits[0] != pResults->m_pbits[0]) || + (best_pbits[1] != pResults->m_pbits[1])) evaluate_solution(&bestMinColor, &bestMaxColor, best_pbits, pParams, pResults); } - else - { - const int iscale = (1 << pParams->m_comp_bits) - 1; - const float scale = (float)iscale; + else { + const int iscale = (1 << pParams->m_comp_bits) - 1; + const float scale = (float)iscale; color_quad_u8 trialMinColor, trialMaxColor; - color_quad_u8_set_clamped(&trialMinColor, (int)(xl.m_c[0] * scale + .5f), (int)(xl.m_c[1] * scale + .5f), (int)(xl.m_c[2] * scale + .5f), (int)(xl.m_c[3] * scale + .5f)); - color_quad_u8_set_clamped(&trialMaxColor, (int)(xh.m_c[0] * scale + .5f), (int)(xh.m_c[1] * scale + .5f), (int)(xh.m_c[2] * scale + .5f), (int)(xh.m_c[3] * scale + .5f)); + color_quad_u8_set_clamped(&trialMinColor, (int)(xl.m_c[0] * scale + .5f), (int)(xl.m_c[1] * scale + .5f), (int)(xl.m_c[2] * scale + .5f), + (int)(xl.m_c[3] * scale + .5f)); + color_quad_u8_set_clamped(&trialMaxColor, (int)(xh.m_c[0] * scale + .5f), (int)(xh.m_c[1] * scale + .5f), (int)(xh.m_c[2] * scale + .5f), + (int)(xh.m_c[3] * scale + .5f)); - if ((pResults->m_best_overall_err == UINT64_MAX) || color_quad_u8_notequals(&trialMinColor, &pResults->m_low_endpoint) || color_quad_u8_notequals(&trialMaxColor, &pResults->m_high_endpoint)) + if ((pResults->m_best_overall_err == UINT64_MAX) || color_quad_u8_notequals(&trialMinColor, &pResults->m_low_endpoint) || + color_quad_u8_notequals(&trialMaxColor, &pResults->m_high_endpoint)) evaluate_solution(&trialMinColor, &trialMaxColor, pResults->m_pbits, pParams, pResults); } return pResults->m_best_overall_err; } -static uint64_t color_cell_compression(uint32_t mode, const color_cell_compressor_params *pParams, color_cell_compressor_results *pResults, const bc7enc_compress_block_params *pComp_params) -{ +static uint64_t color_cell_compression(uint32_t mode, const color_cell_compressor_params *pParams, color_cell_compressor_results *pResults, + const bc7enc_compress_block_params *pComp_params) { pResults->m_best_overall_err = UINT64_MAX; // Compute partition's mean color and principle axis. vec4F meanColor, axis; vec4F_set_scalar(&meanColor, 0.0f); - for (uint32_t i = 0; i < pParams->m_num_pixels; i++) - { + for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { vec4F color = vec4F_from_color(&pParams->m_pPixels[i]); - meanColor = vec4F_add(&meanColor, &color); + meanColor = vec4F_add(&meanColor, &color); } vec4F meanColorScaled = vec4F_mul(&meanColor, 1.0f / (float)(pParams->m_num_pixels)); @@ -575,27 +676,24 @@ static uint64_t color_cell_compression(uint32_t mode, const color_cell_compresso #ifndef IRON_NOSIMD // Precompute per-channel float arrays for SIMD covariance and projection loops below. float pix_r_f[16], pix_g_f[16], pix_b_f[16]; - for (uint32_t i = 0; i < pParams->m_num_pixels; i++) - { + for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { pix_r_f[i] = (float)pParams->m_pPixels[i].m_c[0]; pix_g_f[i] = (float)pParams->m_pPixels[i].m_c[1]; pix_b_f[i] = (float)pParams->m_pPixels[i].m_c[2]; } #endif - if (pParams->m_has_alpha) - { + if (pParams->m_has_alpha) { // Use incremental PCA for RGBA PCA, because it's simple. vec4F_set_scalar(&axis, 0.0f); - for (uint32_t i = 0; i < pParams->m_num_pixels; i++) - { + for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { vec4F color = vec4F_from_color(&pParams->m_pPixels[i]); - color = vec4F_sub(&color, &meanColorScaled); - vec4F a = vec4F_mul(&color, color.m_c[0]); - vec4F b = vec4F_mul(&color, color.m_c[1]); - vec4F c = vec4F_mul(&color, color.m_c[2]); - vec4F d = vec4F_mul(&color, color.m_c[3]); - vec4F n = i ? axis : color; + color = vec4F_sub(&color, &meanColorScaled); + vec4F a = vec4F_mul(&color, color.m_c[0]); + vec4F b = vec4F_mul(&color, color.m_c[1]); + vec4F c = vec4F_mul(&color, color.m_c[2]); + vec4F d = vec4F_mul(&color, color.m_c[3]); + vec4F n = i ? axis : color; vec4F_normalize_in_place(&n); axis.m_c[0] += vec4F_dot(&a, &n); axis.m_c[1] += vec4F_dot(&b, &n); @@ -604,78 +702,85 @@ static uint64_t color_cell_compression(uint32_t mode, const color_cell_compresso } vec4F_normalize_in_place(&axis); } - else - { + else { // Use covar technique for RGB PCA, because it doesn't require per-pixel normalization. - float cov[6] = { 0, 0, 0, 0, 0, 0 }; + float cov[6] = {0, 0, 0, 0, 0, 0}; #ifndef IRON_NOSIMD { const iron_float32x4_t mr4 = iron_float32x4_load_all(meanColorScaled.m_c[0]); const iron_float32x4_t mg4 = iron_float32x4_load_all(meanColorScaled.m_c[1]); const iron_float32x4_t mb4 = iron_float32x4_load_all(meanColorScaled.m_c[2]); - iron_float32x4_t c0v = iron_float32x4_load_all(0.0f), c1v = iron_float32x4_load_all(0.0f); - iron_float32x4_t c2v = iron_float32x4_load_all(0.0f), c3v = iron_float32x4_load_all(0.0f); - iron_float32x4_t c4v = iron_float32x4_load_all(0.0f), c5v = iron_float32x4_load_all(0.0f); - for (uint32_t i = 0; i < 16; i += 4) - { + iron_float32x4_t c0v = iron_float32x4_load_all(0.0f), c1v = iron_float32x4_load_all(0.0f); + iron_float32x4_t c2v = iron_float32x4_load_all(0.0f), c3v = iron_float32x4_load_all(0.0f); + iron_float32x4_t c4v = iron_float32x4_load_all(0.0f), c5v = iron_float32x4_load_all(0.0f); + for (uint32_t i = 0; i < 16; i += 4) { const iron_float32x4_t rv = iron_float32x4_sub(iron_float32x4_intrin_load_unaligned(&pix_r_f[i]), mr4); const iron_float32x4_t gv = iron_float32x4_sub(iron_float32x4_intrin_load_unaligned(&pix_g_f[i]), mg4); const iron_float32x4_t bv = iron_float32x4_sub(iron_float32x4_intrin_load_unaligned(&pix_b_f[i]), mb4); - c0v = iron_float32x4_add(c0v, iron_float32x4_mul(rv, rv)); - c1v = iron_float32x4_add(c1v, iron_float32x4_mul(rv, gv)); - c2v = iron_float32x4_add(c2v, iron_float32x4_mul(rv, bv)); - c3v = iron_float32x4_add(c3v, iron_float32x4_mul(gv, gv)); - c4v = iron_float32x4_add(c4v, iron_float32x4_mul(gv, bv)); - c5v = iron_float32x4_add(c5v, iron_float32x4_mul(bv, bv)); + c0v = iron_float32x4_add(c0v, iron_float32x4_mul(rv, rv)); + c1v = iron_float32x4_add(c1v, iron_float32x4_mul(rv, gv)); + c2v = iron_float32x4_add(c2v, iron_float32x4_mul(rv, bv)); + c3v = iron_float32x4_add(c3v, iron_float32x4_mul(gv, gv)); + c4v = iron_float32x4_add(c4v, iron_float32x4_mul(gv, bv)); + c5v = iron_float32x4_add(c5v, iron_float32x4_mul(bv, bv)); } - cov[0] = iron_float32x4_hsum(c0v); cov[1] = iron_float32x4_hsum(c1v); - cov[2] = iron_float32x4_hsum(c2v); cov[3] = iron_float32x4_hsum(c3v); - cov[4] = iron_float32x4_hsum(c4v); cov[5] = iron_float32x4_hsum(c5v); + cov[0] = iron_float32x4_hsum(c0v); + cov[1] = iron_float32x4_hsum(c1v); + cov[2] = iron_float32x4_hsum(c2v); + cov[3] = iron_float32x4_hsum(c3v); + cov[4] = iron_float32x4_hsum(c4v); + cov[5] = iron_float32x4_hsum(c5v); } #else - for (uint32_t i = 0; i < pParams->m_num_pixels; i++) - { + for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { const color_quad_u8 *pV = &pParams->m_pPixels[i]; - float r = pV->m_c[0] - meanColorScaled.m_c[0]; - float g = pV->m_c[1] - meanColorScaled.m_c[1]; - float b = pV->m_c[2] - meanColorScaled.m_c[2]; - cov[0] += r*r; cov[1] += r*g; cov[2] += r*b; cov[3] += g*g; cov[4] += g*b; cov[5] += b*b; + float r = pV->m_c[0] - meanColorScaled.m_c[0]; + float g = pV->m_c[1] - meanColorScaled.m_c[1]; + float b = pV->m_c[2] - meanColorScaled.m_c[2]; + cov[0] += r * r; + cov[1] += r * g; + cov[2] += r * b; + cov[3] += g * g; + cov[4] += g * b; + cov[5] += b * b; } #endif float vfr = .9f, vfg = 1.0f, vfb = .7f; - for (uint32_t iter = 0; iter < 3; iter++) - { - float r = vfr*cov[0] + vfg*cov[1] + vfb*cov[2]; - float g = vfr*cov[1] + vfg*cov[3] + vfb*cov[4]; - float b = vfr*cov[2] + vfg*cov[4] + vfb*cov[5]; + for (uint32_t iter = 0; iter < 3; iter++) { + float r = vfr * cov[0] + vfg * cov[1] + vfb * cov[2]; + float g = vfr * cov[1] + vfg * cov[3] + vfb * cov[4]; + float b = vfr * cov[2] + vfg * cov[4] + vfb * cov[5]; float m = maximumf(maximumf(fabsf(r), fabsf(g)), fabsf(b)); - if (m > 1e-10f) - { + if (m > 1e-10f) { m = 1.0f / m; - r *= m; g *= m; b *= m; + r *= m; + g *= m; + b *= m; } - vfr = r; vfg = g; vfb = b; + vfr = r; + vfg = g; + vfb = b; } - float len = vfr*vfr + vfg*vfg + vfb*vfb; + float len = vfr * vfr + vfg * vfg + vfb * vfb; if (len < 1e-10f) vec4F_set_scalar(&axis, 0.0f); - else - { + else { len = 1.0f / sqrtf(len); - vfr *= len; vfg *= len; vfb *= len; + vfr *= len; + vfg *= len; + vfb *= len; vec4F_set(&axis, vfr, vfg, vfb, 0); } } // TODO: Try picking the 2 colors with the largest projection onto the axis, instead of computing new colors along the axis. - if (vec4F_dot(&axis, &axis) < .5f) - { + if (vec4F_dot(&axis, &axis) < .5f) { if (pParams->m_perceptual) vec4F_set(&axis, .213f, .715f, .072f, pParams->m_has_alpha ? .715f : 0); else @@ -686,8 +791,7 @@ static uint64_t color_cell_compression(uint32_t mode, const color_cell_compresso float l = 1e+9f, h = -1e+9f; #ifndef IRON_NOSIMD - if (!pParams->m_has_alpha) - { + if (!pParams->m_has_alpha) { // RGB path: axis.m_c[3] == 0 so only R,G,B contribute to the dot product. const iron_float32x4_t mr4 = iron_float32x4_load_all(meanColorScaled.m_c[0]); const iron_float32x4_t mg4 = iron_float32x4_load_all(meanColorScaled.m_c[1]); @@ -695,50 +799,45 @@ static uint64_t color_cell_compression(uint32_t mode, const color_cell_compresso const iron_float32x4_t axv = iron_float32x4_load_all(axis.m_c[0]); const iron_float32x4_t ayv = iron_float32x4_load_all(axis.m_c[1]); const iron_float32x4_t azv = iron_float32x4_load_all(axis.m_c[2]); - iron_float32x4_t lv = iron_float32x4_load_all(1e+9f); - iron_float32x4_t hv = iron_float32x4_load_all(-1e+9f); - for (uint32_t i = 0; i < 16; i += 4) - { + iron_float32x4_t lv = iron_float32x4_load_all(1e+9f); + iron_float32x4_t hv = iron_float32x4_load_all(-1e+9f); + for (uint32_t i = 0; i < 16; i += 4) { const iron_float32x4_t rv = iron_float32x4_sub(iron_float32x4_intrin_load_unaligned(&pix_r_f[i]), mr4); const iron_float32x4_t gv = iron_float32x4_sub(iron_float32x4_intrin_load_unaligned(&pix_g_f[i]), mg4); const iron_float32x4_t bv = iron_float32x4_sub(iron_float32x4_intrin_load_unaligned(&pix_b_f[i]), mb4); - iron_float32x4_t dv = iron_float32x4_mul(rv, axv); - dv = iron_float32x4_add(dv, iron_float32x4_mul(gv, ayv)); - dv = iron_float32x4_add(dv, iron_float32x4_mul(bv, azv)); - lv = iron_float32x4_min(lv, dv); - hv = iron_float32x4_max(hv, dv); + iron_float32x4_t dv = iron_float32x4_mul(rv, axv); + dv = iron_float32x4_add(dv, iron_float32x4_mul(gv, ayv)); + dv = iron_float32x4_add(dv, iron_float32x4_mul(bv, azv)); + lv = iron_float32x4_min(lv, dv); + hv = iron_float32x4_max(hv, dv); } - l = minimumf(minimumf(iron_float32x4_get(lv, 0), iron_float32x4_get(lv, 1)), - minimumf(iron_float32x4_get(lv, 2), iron_float32x4_get(lv, 3))); - h = maximumf(maximumf(iron_float32x4_get(hv, 0), iron_float32x4_get(hv, 1)), - maximumf(iron_float32x4_get(hv, 2), iron_float32x4_get(hv, 3))); + l = minimumf(minimumf(iron_float32x4_get(lv, 0), iron_float32x4_get(lv, 1)), minimumf(iron_float32x4_get(lv, 2), iron_float32x4_get(lv, 3))); + h = maximumf(maximumf(iron_float32x4_get(hv, 0), iron_float32x4_get(hv, 1)), maximumf(iron_float32x4_get(hv, 2), iron_float32x4_get(hv, 3))); } else #endif - for (uint32_t i = 0; i < pParams->m_num_pixels; i++) - { - vec4F color = vec4F_from_color(&pParams->m_pPixels[i]); - vec4F q = vec4F_sub(&color, &meanColorScaled); - float d = vec4F_dot(&q, &axis); - l = minimumf(l, d); - h = maximumf(h, d); - } + for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { + vec4F color = vec4F_from_color(&pParams->m_pPixels[i]); + vec4F q = vec4F_sub(&color, &meanColorScaled); + float d = vec4F_dot(&q, &axis); + l = minimumf(l, d); + h = maximumf(h, d); + } l *= (1.0f / 255.0f); h *= (1.0f / 255.0f); - vec4F b0 = vec4F_mul(&axis, l); - vec4F b1 = vec4F_mul(&axis, h); - vec4F c0 = vec4F_add(&meanColor, &b0); - vec4F c1 = vec4F_add(&meanColor, &b1); + vec4F b0 = vec4F_mul(&axis, l); + vec4F b1 = vec4F_mul(&axis, h); + vec4F c0 = vec4F_add(&meanColor, &b0); + vec4F c1 = vec4F_add(&meanColor, &b1); vec4F minColor = vec4F_saturate(&c0); vec4F maxColor = vec4F_saturate(&c1); vec4F whiteVec; vec4F_set_scalar(&whiteVec, 1.0f); - if (vec4F_dot(&minColor, &whiteVec) > vec4F_dot(&maxColor, &whiteVec)) - { + if (vec4F_dot(&minColor, &whiteVec) > vec4F_dot(&maxColor, &whiteVec)) { float a = minColor.m_c[0], b = minColor.m_c[1], c = minColor.m_c[2], d = minColor.m_c[3]; minColor.m_c[0] = maxColor.m_c[0]; minColor.m_c[1] = maxColor.m_c[1]; @@ -757,10 +856,8 @@ static uint64_t color_cell_compression(uint32_t mode, const color_cell_compresso return pResults->m_best_overall_err; } -static void set_block_bits(uint8_t *pBytes, uint32_t val, uint32_t num_bits, uint32_t *pCur_ofs) -{ - while (num_bits) - { +static void set_block_bits(uint8_t *pBytes, uint32_t val, uint32_t num_bits, uint32_t *pCur_ofs) { + while (num_bits) { const uint32_t n = minimumu(8 - (*pCur_ofs & 7), num_bits); pBytes[*pCur_ofs >> 3] |= (uint8_t)(val << (*pCur_ofs & 7)); val >>= n; @@ -769,26 +866,24 @@ static void set_block_bits(uint8_t *pBytes, uint32_t val, uint32_t num_bits, uin } } -typedef struct -{ - uint32_t m_mode; - uint32_t m_partition; - uint8_t m_selectors[16]; - uint8_t m_alpha_selectors[16]; +typedef struct { + uint32_t m_mode; + uint32_t m_partition; + uint8_t m_selectors[16]; + uint8_t m_alpha_selectors[16]; color_quad_u8 m_low[3]; color_quad_u8 m_high[3]; - uint32_t m_pbits[3][2]; - uint32_t m_rotation; - uint32_t m_index_selector; + uint32_t m_pbits[3][2]; + uint32_t m_rotation; + uint32_t m_index_selector; } bc7_optimization_results; -static void encode_bc7_block(void* pBlock, const bc7_optimization_results* pResults) -{ - const uint32_t best_mode = pResults->m_mode; - const uint32_t total_subsets = g_bc7_num_subsets[best_mode]; +static void encode_bc7_block(void *pBlock, const bc7_optimization_results *pResults) { + const uint32_t best_mode = pResults->m_mode; + const uint32_t total_subsets = g_bc7_num_subsets[best_mode]; const uint32_t total_partitions = 1 << g_bc7_partition_bits[best_mode]; - const uint8_t* pPartition; + const uint8_t *pPartition; if (total_subsets == 1) pPartition = &g_bc7_partition1[0]; else if (total_subsets == 2) @@ -809,13 +904,11 @@ static void encode_bc7_block(void* pBlock, const bc7_optimization_results* pResu uint32_t pbits[3][2]; memcpy(pbits, pResults->m_pbits, sizeof(pbits)); - int anchor[3] = { -1, -1, -1 }; + int anchor[3] = {-1, -1, -1}; - for (uint32_t k = 0; k < total_subsets; k++) - { + for (uint32_t k = 0; k < total_subsets; k++) { uint32_t anchor_index = 0; - if (k) - { + if (k) { if ((total_subsets == 3) && (k == 1)) anchor_index = g_bc7_table_anchor_index_third_subset_1[pResults->m_partition]; else if ((total_subsets == 3) && (k == 2)) @@ -826,58 +919,51 @@ static void encode_bc7_block(void* pBlock, const bc7_optimization_results* pResu anchor[k] = anchor_index; - const uint32_t color_index_bits = get_bc7_color_index_size(best_mode, pResults->m_index_selector); + const uint32_t color_index_bits = get_bc7_color_index_size(best_mode, pResults->m_index_selector); const uint32_t num_color_indices = 1 << color_index_bits; - if (color_selectors[anchor_index] & (num_color_indices >> 1)) - { + if (color_selectors[anchor_index] & (num_color_indices >> 1)) { for (uint32_t i = 0; i < 16; i++) if (pPartition[i] == k) color_selectors[i] = (uint8_t)((num_color_indices - 1) - color_selectors[i]); - if (get_bc7_mode_has_seperate_alpha_selectors(best_mode)) - { - for (uint32_t q = 0; q < 3; q++) - { - uint8_t t = low[k].m_c[q]; - low[k].m_c[q] = high[k].m_c[q]; + if (get_bc7_mode_has_seperate_alpha_selectors(best_mode)) { + for (uint32_t q = 0; q < 3; q++) { + uint8_t t = low[k].m_c[q]; + low[k].m_c[q] = high[k].m_c[q]; high[k].m_c[q] = t; } } - else - { + else { color_quad_u8 tmp = low[k]; - low[k] = high[k]; - high[k] = tmp; + low[k] = high[k]; + high[k] = tmp; } - if (!g_bc7_mode_has_shared_p_bits[best_mode]) - { - uint32_t t = pbits[k][0]; + if (!g_bc7_mode_has_shared_p_bits[best_mode]) { + uint32_t t = pbits[k][0]; pbits[k][0] = pbits[k][1]; pbits[k][1] = t; } } - if (get_bc7_mode_has_seperate_alpha_selectors(best_mode)) - { - const uint32_t alpha_index_bits = get_bc7_alpha_index_size(best_mode, pResults->m_index_selector); + if (get_bc7_mode_has_seperate_alpha_selectors(best_mode)) { + const uint32_t alpha_index_bits = get_bc7_alpha_index_size(best_mode, pResults->m_index_selector); const uint32_t num_alpha_indices = 1 << alpha_index_bits; - if (alpha_selectors[anchor_index] & (num_alpha_indices >> 1)) - { + if (alpha_selectors[anchor_index] & (num_alpha_indices >> 1)) { for (uint32_t i = 0; i < 16; i++) if (pPartition[i] == k) alpha_selectors[i] = (uint8_t)((num_alpha_indices - 1) - alpha_selectors[i]); - uint8_t t = low[k].m_c[3]; - low[k].m_c[3] = high[k].m_c[3]; + uint8_t t = low[k].m_c[3]; + low[k].m_c[3] = high[k].m_c[3]; high[k].m_c[3] = t; } } } - uint8_t* pBlock_bytes = (uint8_t*)(pBlock); + uint8_t *pBlock_bytes = (uint8_t *)(pBlock); memset(pBlock_bytes, 0, BC7ENC_BLOCK_SIZE); uint32_t cur_bit_ofs = 0; @@ -887,32 +973,29 @@ static void encode_bc7_block(void* pBlock, const bc7_optimization_results* pResu set_block_bits(pBlock_bytes, pResults->m_partition, (total_partitions == 64) ? 6 : 4, &cur_bit_ofs); const uint32_t total_comps = (best_mode >= 4) ? 4 : 3; - for (uint32_t comp = 0; comp < total_comps; comp++) - { - for (uint32_t subset = 0; subset < total_subsets; subset++) - { - set_block_bits(pBlock_bytes, low[subset].m_c[comp], (comp == 3) ? g_bc7_alpha_precision_table[best_mode] : g_bc7_color_precision_table[best_mode], &cur_bit_ofs); - set_block_bits(pBlock_bytes, high[subset].m_c[comp], (comp == 3) ? g_bc7_alpha_precision_table[best_mode] : g_bc7_color_precision_table[best_mode], &cur_bit_ofs); + for (uint32_t comp = 0; comp < total_comps; comp++) { + for (uint32_t subset = 0; subset < total_subsets; subset++) { + set_block_bits(pBlock_bytes, low[subset].m_c[comp], (comp == 3) ? g_bc7_alpha_precision_table[best_mode] : g_bc7_color_precision_table[best_mode], + &cur_bit_ofs); + set_block_bits(pBlock_bytes, high[subset].m_c[comp], (comp == 3) ? g_bc7_alpha_precision_table[best_mode] : g_bc7_color_precision_table[best_mode], + &cur_bit_ofs); } } - if (g_bc7_mode_has_p_bits[best_mode]) - { - for (uint32_t subset = 0; subset < total_subsets; subset++) - { + if (g_bc7_mode_has_p_bits[best_mode]) { + for (uint32_t subset = 0; subset < total_subsets; subset++) { set_block_bits(pBlock_bytes, pbits[subset][0], 1, &cur_bit_ofs); if (!g_bc7_mode_has_shared_p_bits[best_mode]) set_block_bits(pBlock_bytes, pbits[subset][1], 1, &cur_bit_ofs); } } - for (uint32_t y = 0; y < 4; y++) - { - for (uint32_t x = 0; x < 4; x++) - { + for (uint32_t y = 0; y < 4; y++) { + for (uint32_t x = 0; x < 4; x++) { int idx = x + y * 4; - uint32_t n = pResults->m_index_selector ? get_bc7_alpha_index_size(best_mode, pResults->m_index_selector) : get_bc7_color_index_size(best_mode, pResults->m_index_selector); + uint32_t n = pResults->m_index_selector ? get_bc7_alpha_index_size(best_mode, pResults->m_index_selector) + : get_bc7_color_index_size(best_mode, pResults->m_index_selector); if ((idx == anchor[0]) || (idx == anchor[1]) || (idx == anchor[2])) n--; @@ -921,15 +1004,13 @@ static void encode_bc7_block(void* pBlock, const bc7_optimization_results* pResu } } - if (get_bc7_mode_has_seperate_alpha_selectors(best_mode)) - { - for (uint32_t y = 0; y < 4; y++) - { - for (uint32_t x = 0; x < 4; x++) - { + if (get_bc7_mode_has_seperate_alpha_selectors(best_mode)) { + for (uint32_t y = 0; y < 4; y++) { + for (uint32_t x = 0; x < 4; x++) { int idx = x + y * 4; - uint32_t n = pResults->m_index_selector ? get_bc7_color_index_size(best_mode, pResults->m_index_selector) : get_bc7_alpha_index_size(best_mode, pResults->m_index_selector); + uint32_t n = pResults->m_index_selector ? get_bc7_color_index_size(best_mode, pResults->m_index_selector) + : get_bc7_alpha_index_size(best_mode, pResults->m_index_selector); if ((idx == anchor[0]) || (idx == anchor[1]) || (idx == anchor[2])) n--; @@ -940,18 +1021,18 @@ static void encode_bc7_block(void* pBlock, const bc7_optimization_results* pResu } } -static void handle_alpha_block(void *pBlock, const color_quad_u8 *pPixels, const bc7enc_compress_block_params *pComp_params, color_cell_compressor_params *pParams) -{ - pParams->m_pSelector_weights = g_bc7_weights4; - pParams->m_pSelector_weightsx = (const vec4F *)g_bc7_weights4x; +static void handle_alpha_block(void *pBlock, const color_quad_u8 *pPixels, const bc7enc_compress_block_params *pComp_params, + color_cell_compressor_params *pParams) { + pParams->m_pSelector_weights = g_bc7_weights4; + pParams->m_pSelector_weightsx = (const vec4F *)g_bc7_weights4x; pParams->m_num_selector_weights = 16; - pParams->m_comp_bits = 7; - pParams->m_has_pbits = BC7ENC_TRUE; + pParams->m_comp_bits = 7; + pParams->m_has_pbits = BC7ENC_TRUE; pParams->m_endpoints_share_pbit = BC7ENC_FALSE; - pParams->m_has_alpha = BC7ENC_TRUE; - pParams->m_perceptual = pComp_params->m_perceptual; - pParams->m_num_pixels = 16; - pParams->m_pPixels = pPixels; + pParams->m_has_alpha = BC7ENC_TRUE; + pParams->m_perceptual = pComp_params->m_perceptual; + pParams->m_num_pixels = 16; + pParams->m_pPixels = pPixels; bc7_optimization_results opt_results6, opt_results5, opt_results7; @@ -960,82 +1041,77 @@ static void handle_alpha_block(void *pBlock, const color_quad_u8 *pPixels, const uint8_t selectors_temp[16]; results6.m_pSelectors_temp = selectors_temp; - uint64_t best_err = color_cell_compression(6, pParams, &results6, pComp_params); + uint64_t best_err = color_cell_compression(6, pParams, &results6, pComp_params); uint32_t best_mode = 6; - if (best_mode == 6) - { - opt_results6.m_mode = 6; - opt_results6.m_partition = 0; - opt_results6.m_low[0] = results6.m_low_endpoint; - opt_results6.m_high[0] = results6.m_high_endpoint; - opt_results6.m_pbits[0][0] = results6.m_pbits[0]; - opt_results6.m_pbits[0][1] = results6.m_pbits[1]; - opt_results6.m_rotation = 0; + if (best_mode == 6) { + opt_results6.m_mode = 6; + opt_results6.m_partition = 0; + opt_results6.m_low[0] = results6.m_low_endpoint; + opt_results6.m_high[0] = results6.m_high_endpoint; + opt_results6.m_pbits[0][0] = results6.m_pbits[0]; + opt_results6.m_pbits[0][1] = results6.m_pbits[1]; + opt_results6.m_rotation = 0; opt_results6.m_index_selector = 0; encode_bc7_block(pBlock, &opt_results6); } } -static void handle_opaque_block(void *pBlock, const color_quad_u8 *pPixels, const bc7enc_compress_block_params *pComp_params, color_cell_compressor_params *pParams) -{ +static void handle_opaque_block(void *pBlock, const color_quad_u8 *pPixels, const bc7enc_compress_block_params *pComp_params, + color_cell_compressor_params *pParams) { uint8_t selectors_temp[16]; // Mode 6 bc7_optimization_results opt_results; - pParams->m_pSelector_weights = g_bc7_weights4; - pParams->m_pSelector_weightsx = (const vec4F *)g_bc7_weights4x; + pParams->m_pSelector_weights = g_bc7_weights4; + pParams->m_pSelector_weightsx = (const vec4F *)g_bc7_weights4x; pParams->m_num_selector_weights = 16; - pParams->m_comp_bits = 7; - pParams->m_has_pbits = BC7ENC_TRUE; + pParams->m_comp_bits = 7; + pParams->m_has_pbits = BC7ENC_TRUE; pParams->m_endpoints_share_pbit = BC7ENC_FALSE; - pParams->m_perceptual = pComp_params->m_perceptual; - pParams->m_num_pixels = 16; - pParams->m_pPixels = pPixels; - pParams->m_has_alpha = BC7ENC_FALSE; + pParams->m_perceptual = pComp_params->m_perceptual; + pParams->m_num_pixels = 16; + pParams->m_pPixels = pPixels; + pParams->m_has_alpha = BC7ENC_FALSE; color_cell_compressor_results results6; - results6.m_pSelectors = opt_results.m_selectors; + results6.m_pSelectors = opt_results.m_selectors; results6.m_pSelectors_temp = selectors_temp; uint64_t best_err = color_cell_compression(6, pParams, &results6, pComp_params); - opt_results.m_mode = 6; - opt_results.m_partition = 0; - opt_results.m_low[0] = results6.m_low_endpoint; - opt_results.m_high[0] = results6.m_high_endpoint; - opt_results.m_pbits[0][0] = results6.m_pbits[0]; - opt_results.m_pbits[0][1] = results6.m_pbits[1]; + opt_results.m_mode = 6; + opt_results.m_partition = 0; + opt_results.m_low[0] = results6.m_low_endpoint; + opt_results.m_high[0] = results6.m_high_endpoint; + opt_results.m_pbits[0][0] = results6.m_pbits[0]; + opt_results.m_pbits[0][1] = results6.m_pbits[1]; opt_results.m_index_selector = 0; - opt_results.m_rotation = 0; + opt_results.m_rotation = 0; encode_bc7_block(pBlock, &opt_results); } -bc7enc_bool bc7enc_compress_block(void *pBlock, const void *pPixelsRGBA, const bc7enc_compress_block_params *pComp_params) -{ +bc7enc_bool bc7enc_compress_block(void *pBlock, const void *pPixelsRGBA, const bc7enc_compress_block_params *pComp_params) { const color_quad_u8 *pPixels = (const color_quad_u8 *)(pPixelsRGBA); color_cell_compressor_params params; - if (pComp_params->m_perceptual) - { + if (pComp_params->m_perceptual) { // https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.709_conversion const float pr_weight = (.5f / (1.0f - .2126f)) * (.5f / (1.0f - .2126f)); const float pb_weight = (.5f / (1.0f - .0722f)) * (.5f / (1.0f - .0722f)); - params.m_weights[0] = (int)(pComp_params->m_weights[0] * 4.0f); - params.m_weights[1] = (int)(pComp_params->m_weights[1] * 4.0f * pr_weight); - params.m_weights[2] = (int)(pComp_params->m_weights[2] * 4.0f * pb_weight); - params.m_weights[3] = pComp_params->m_weights[3] * 4; + params.m_weights[0] = (int)(pComp_params->m_weights[0] * 4.0f); + params.m_weights[1] = (int)(pComp_params->m_weights[1] * 4.0f * pr_weight); + params.m_weights[2] = (int)(pComp_params->m_weights[2] * 4.0f * pb_weight); + params.m_weights[3] = pComp_params->m_weights[3] * 4; } else memcpy(params.m_weights, pComp_params->m_weights, sizeof(params.m_weights)); - for (uint32_t i = 0; i < 16; i++) - { - if (pPixels[i].m_c[3] < 255) - { + for (uint32_t i = 0; i < 16; i++) { + if (pPixels[i].m_c[3] < 255) { handle_alpha_block(pBlock, pPixels, pComp_params, ¶ms); return BC7ENC_TRUE; } diff --git a/base/sources/libs/bc7enc.h b/base/sources/libs/bc7enc.h index d841b00e..cd56ee6a 100644 --- a/base/sources/libs/bc7enc.h +++ b/base/sources/libs/bc7enc.h @@ -1,19 +1,19 @@ // File: bc7enc.h - Richard Geldreich, Jr. - MIT license or public domain (see end of bc7enc.c) #pragma once -#include #include +#include -#define BC7ENC_BLOCK_SIZE (16) +#define BC7ENC_BLOCK_SIZE (16) #define BC7ENC_MAX_PARTITIONS1 (64) -#define BC7ENC_MAX_UBER_LEVEL (4) +#define BC7ENC_MAX_UBER_LEVEL (4) typedef uint8_t bc7enc_bool; -#define BC7ENC_TRUE (1) +#define BC7ENC_TRUE (1) #define BC7ENC_FALSE (0) -typedef struct -{ - // m_max_partitions_mode may range from 0 (disables mode 1) to BC7ENC_MAX_PARTITIONS1. The higher this value, the slower the compressor, but the higher the quality. +typedef struct { + // m_max_partitions_mode may range from 0 (disables mode 1) to BC7ENC_MAX_PARTITIONS1. The higher this value, the slower the compressor, but the higher the + // quality. uint32_t m_max_partitions_mode; // Relative RGBA or YCbCrA weights. @@ -28,8 +28,9 @@ typedef struct // Set m_try_least_squares to false for slightly faster/lower quality compression. bc7enc_bool m_try_least_squares; - // When m_mode_partition_estimation_filterbank, the mode1 partition estimator skips lesser used partition patterns unless they are strongly predicted to be potentially useful. - // There's a slight loss in quality with this enabled (around .08 dB RGB PSNR or .05 dB Y PSNR), but up to a 11% gain in speed depending on the other settings. + // When m_mode_partition_estimation_filterbank, the mode1 partition estimator skips lesser used partition patterns unless they are strongly predicted to be + // potentially useful. There's a slight loss in quality with this enabled (around .08 dB RGB PSNR or .05 dB Y PSNR), but up to a 11% gain in speed depending + // on the other settings. bc7enc_bool m_mode_partition_estimation_filterbank; bc7enc_bool m_use_mode5_for_alpha; diff --git a/base/sources/libs/lz4x.h b/base/sources/libs/lz4x.h index a31677a2..6143346b 100644 --- a/base/sources/libs/lz4x.h +++ b/base/sources/libs/lz4x.h @@ -160,7 +160,7 @@ size_t LZ4_compress(const char *source, int sourceSize, char *dest, const int ma tail[p & WINDOW_MASK] = head[h]; // size_t read_offset = 0; // size_t write_offset = 0; - head[h] = p++; + head[h] = p++; } } else { diff --git a/base/sources/libs/nfd.c b/base/sources/libs/nfd.c index 07c411fd..bbf583cb 100644 --- a/base/sources/libs/nfd.c +++ b/base/sources/libs/nfd.c @@ -13,86 +13,76 @@ // 3. This notice may not be removed or altered from any source distribution. // https://github.com/mlabbe/nativefiledialog -#include -#include -#include -#include #include "nfd.h" #include "../iron_global.h" +#include +#include +#include +#include static char g_errorstr[NFD_MAX_STRLEN] = {0}; /* public routines */ -const char *NFD_GetError( void ) -{ +const char *NFD_GetError(void) { return g_errorstr; } -size_t NFD_PathSet_GetCount( const nfdpathset_t *pathset ) -{ +size_t NFD_PathSet_GetCount(const nfdpathset_t *pathset) { assert(pathset); return pathset->count; } -nfdchar_t *NFD_PathSet_GetPath( const nfdpathset_t *pathset, size_t num ) -{ +nfdchar_t *NFD_PathSet_GetPath(const nfdpathset_t *pathset, size_t num) { assert(pathset); assert(num < pathset->count); return pathset->buf + pathset->indices[num]; } -void NFD_PathSet_Free( nfdpathset_t *pathset ) -{ +void NFD_PathSet_Free(nfdpathset_t *pathset) { assert(pathset); - NFDi_Free( pathset->indices ); - NFDi_Free( pathset->buf ); + NFDi_Free(pathset->indices); + NFDi_Free(pathset->buf); } /* internal routines */ -void *NFDi_Malloc( size_t bytes ) -{ +void *NFDi_Malloc(size_t bytes) { void *ptr = malloc(bytes); - if ( !ptr ) + if (!ptr) NFDi_SetError("NFDi_Malloc failed."); return ptr; } -void NFDi_Free( void *ptr ) -{ +void NFDi_Free(void *ptr) { assert(ptr); free(ptr); } -void NFDi_SetError( const char *msg ) -{ - int bTruncate = NFDi_SafeStrncpy( g_errorstr, msg, NFD_MAX_STRLEN ); - assert( !bTruncate ); _NFD_UNUSED(bTruncate); +void NFDi_SetError(const char *msg) { + int bTruncate = NFDi_SafeStrncpy(g_errorstr, msg, NFD_MAX_STRLEN); + assert(!bTruncate); + _NFD_UNUSED(bTruncate); } - -int NFDi_SafeStrncpy( char *dst, const char *src, size_t maxCopy ) -{ +int NFDi_SafeStrncpy(char *dst, const char *src, size_t maxCopy) { size_t n = maxCopy; - char *d = dst; + char *d = dst; - assert( src ); - assert( dst ); + assert(src); + assert(dst); - while ( n > 0 && *src != '\0' ) - { + while (n > 0 && *src != '\0') { *d++ = *src++; --n; } /* Truncation case - terminate string and return true */ - if ( n == 0 ) - { - dst[maxCopy-1] = '\0'; + if (n == 0) { + dst[maxCopy - 1] = '\0'; return 1; } @@ -101,42 +91,35 @@ int NFDi_SafeStrncpy( char *dst, const char *src, size_t maxCopy ) return 0; } - /* adapted from microutf8 */ -int32_t NFDi_UTF8_Strlen( const nfdchar_t *str ) -{ +int32_t NFDi_UTF8_Strlen(const nfdchar_t *str) { /* This function doesn't properly check validity of UTF-8 character sequence, it is supposed to use only with valid UTF-8 strings. */ - int32_t character_count = 0; - int32_t i = 0; /* Counter used to iterate over string. */ + int32_t character_count = 0; + int32_t i = 0; /* Counter used to iterate over string. */ nfdchar_t maybe_bom[4]; /* If there is UTF-8 BOM ignore it. */ - if (strlen(str) > 2) - { + if (strlen(str) > 2) { strncpy(maybe_bom, str, 3); maybe_bom[3] = 0; - if (strcmp(maybe_bom, (nfdchar_t*)NFD_UTF8_BOM) == 0) + if (strcmp(maybe_bom, (nfdchar_t *)NFD_UTF8_BOM) == 0) i += 3; } - while(str[i]) - { - if (str[i] >> 7 == 0) - { + while (str[i]) { + if (str[i] >> 7 == 0) { /* If bit pattern begins with 0 we have ascii character. */ ++character_count; } - else if (str[i] >> 6 == 3) - { - /* If bit pattern begins with 11 it is beginning of UTF-8 byte sequence. */ + else if (str[i] >> 6 == 3) { + /* If bit pattern begins with 11 it is beginning of UTF-8 byte sequence. */ ++character_count; } else if (str[i] >> 6 == 2) - ; /* If bit pattern begins with 10 it is middle of utf-8 byte sequence. */ - else - { + ; /* If bit pattern begins with 10 it is middle of utf-8 byte sequence. */ + else { /* In any other case this is not valid UTF-8. */ return -1; } @@ -146,9 +129,8 @@ int32_t NFDi_UTF8_Strlen( const nfdchar_t *str ) return character_count; } -int NFDi_IsFilterSegmentChar( char ch ) -{ - return (ch==','||ch==';'||ch=='\0'); +int NFDi_IsFilterSegmentChar(char ch) { + return (ch == ',' || ch == ';' || ch == '\0'); } #ifdef IRON_LINUX @@ -159,68 +141,61 @@ const char INIT_FAIL_MSG[] = "gtk_init_check failed to initilaize GTK+"; void iron_gtk_disable_setlocale(); -static void AddTypeToFilterName( const char *typebuf, char *filterName, size_t bufsize ) -{ +static void AddTypeToFilterName(const char *typebuf, char *filterName, size_t bufsize) { const char SEP[] = ", "; size_t len = strlen(filterName); - if ( len != 0 ) - { - strncat( filterName, SEP, bufsize - len - 1 ); + if (len != 0) { + strncat(filterName, SEP, bufsize - len - 1); len += strlen(SEP); } - strncat( filterName, typebuf, bufsize - len - 1 ); + strncat(filterName, typebuf, bufsize - len - 1); } -static void AddFiltersToDialog( GtkWidget *dialog, const char *filterList ) -{ +static void AddFiltersToDialog(GtkWidget *dialog, const char *filterList) { GtkFileFilter *filter; - char typebuf[NFD_MAX_STRLEN] = {0}; - const char *p_filterList = filterList; - char *p_typebuf = typebuf; - char filterName[NFD_MAX_STRLEN] = {0}; + char typebuf[NFD_MAX_STRLEN] = {0}; + const char *p_filterList = filterList; + char *p_typebuf = typebuf; + char filterName[NFD_MAX_STRLEN] = {0}; - if ( !filterList || strlen(filterList) == 0 ) + if (!filterList || strlen(filterList) == 0) return; filter = gtk_file_filter_new(); - while ( 1 ) - { + while (1) { - if ( NFDi_IsFilterSegmentChar(*p_filterList) ) - { + if (NFDi_IsFilterSegmentChar(*p_filterList)) { char typebufWildcard[NFD_MAX_STRLEN]; /* add another type to the filter */ - assert( strlen(typebuf) > 0 ); - assert( strlen(typebuf) < NFD_MAX_STRLEN-1 ); + assert(strlen(typebuf) > 0); + assert(strlen(typebuf) < NFD_MAX_STRLEN - 1); - snprintf( typebufWildcard, NFD_MAX_STRLEN, "*.%s", typebuf ); - AddTypeToFilterName( typebuf, filterName, NFD_MAX_STRLEN ); + snprintf(typebufWildcard, NFD_MAX_STRLEN, "*.%s", typebuf); + AddTypeToFilterName(typebuf, filterName, NFD_MAX_STRLEN); - gtk_file_filter_add_pattern( filter, typebufWildcard ); + gtk_file_filter_add_pattern(filter, typebufWildcard); p_typebuf = typebuf; - memset( typebuf, 0, sizeof(char) * NFD_MAX_STRLEN ); + memset(typebuf, 0, sizeof(char) * NFD_MAX_STRLEN); } - if ( *p_filterList == ';' || *p_filterList == '\0' ) - { + if (*p_filterList == ';' || *p_filterList == '\0') { /* end of filter -- add it to the dialog */ - gtk_file_filter_set_name( filter, filterName ); - gtk_file_chooser_add_filter( GTK_FILE_CHOOSER(dialog), filter ); + gtk_file_filter_set_name(filter, filterName); + gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); filterName[0] = '\0'; - if ( *p_filterList == '\0' ) + if (*p_filterList == '\0') break; filter = gtk_file_filter_new(); } - if ( !NFDi_IsFilterSegmentChar( *p_filterList ) ) - { + if (!NFDi_IsFilterSegmentChar(*p_filterList)) { *p_typebuf = *p_filterList; p_typebuf++; } @@ -231,14 +206,13 @@ static void AddFiltersToDialog( GtkWidget *dialog, const char *filterList ) /* always append a wildcard option to the end*/ filter = gtk_file_filter_new(); - gtk_file_filter_set_name( filter, "*.*" ); - gtk_file_filter_add_pattern( filter, "*" ); - gtk_file_chooser_add_filter( GTK_FILE_CHOOSER(dialog), filter ); + gtk_file_filter_set_name(filter, "*.*"); + gtk_file_filter_add_pattern(filter, "*"); + gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); } -static void SetDefaultPath( GtkWidget *dialog, const char *defaultPath ) -{ - if ( !defaultPath || strlen(defaultPath) == 0 ) +static void SetDefaultPath(GtkWidget *dialog, const char *defaultPath) { + if (!defaultPath || strlen(defaultPath) == 0) return; /* GTK+ manual recommends not specifically setting the default path. @@ -246,89 +220,75 @@ static void SetDefaultPath( GtkWidget *dialog, const char *defaultPath ) If consistency with the native OS is preferred, this is the line to comment out. -ml */ - gtk_file_chooser_set_current_folder( GTK_FILE_CHOOSER(dialog), defaultPath ); + gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), defaultPath); } -static nfdresult_t AllocPathSet( GSList *fileList, nfdpathset_t *pathSet ) -{ - size_t bufSize = 0; - GSList *node; +static nfdresult_t AllocPathSet(GSList *fileList, nfdpathset_t *pathSet) { + size_t bufSize = 0; + GSList *node; nfdchar_t *p_buf; - size_t count = 0; + size_t count = 0; assert(fileList); assert(pathSet); - pathSet->count = (size_t)g_slist_length( fileList ); - assert( pathSet->count > 0 ); + pathSet->count = (size_t)g_slist_length(fileList); + assert(pathSet->count > 0); - pathSet->indices = NFDi_Malloc( sizeof(size_t)*pathSet->count ); - if ( !pathSet->indices ) - { + pathSet->indices = NFDi_Malloc(sizeof(size_t) * pathSet->count); + if (!pathSet->indices) { return NFD_ERROR; } /* count the total space needed for buf */ - for ( node = fileList; node; node = node->next ) - { + for (node = fileList; node; node = node->next) { assert(node->data); - bufSize += strlen( (const gchar*)node->data ) + 1; + bufSize += strlen((const gchar *)node->data) + 1; } - pathSet->buf = NFDi_Malloc( sizeof(nfdchar_t) * bufSize ); + pathSet->buf = NFDi_Malloc(sizeof(nfdchar_t) * bufSize); /* fill buf */ p_buf = pathSet->buf; - for ( node = fileList; node; node = node->next ) - { - nfdchar_t *path = (nfdchar_t*)(node->data); - size_t byteLen = strlen(path)+1; - ptrdiff_t index; + for (node = fileList; node; node = node->next) { + nfdchar_t *path = (nfdchar_t *)(node->data); + size_t byteLen = strlen(path) + 1; + ptrdiff_t index; - memcpy( p_buf, path, byteLen ); + memcpy(p_buf, path, byteLen); g_free(node->data); index = p_buf - pathSet->buf; - assert( index >= 0 ); + assert(index >= 0); pathSet->indices[count] = (size_t)index; p_buf += byteLen; ++count; } - g_slist_free( fileList ); + g_slist_free(fileList); return NFD_OKAY; } -static void WaitForCleanup(void) -{ +static void WaitForCleanup(void) { while (gtk_events_pending()) gtk_main_iteration(); } /* public */ -nfdresult_t NFD_OpenDialog( const nfdchar_t *filterList, - const nfdchar_t *defaultPath, - nfdchar_t **outPath ) -{ - GtkWidget *dialog; +nfdresult_t NFD_OpenDialog(const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdchar_t **outPath) { + GtkWidget *dialog; nfdresult_t result; iron_gtk_disable_setlocale(); - if ( !gtk_init_check( NULL, NULL ) ) - { + if (!gtk_init_check(NULL, NULL)) { NFDi_SetError(INIT_FAIL_MSG); return NFD_ERROR; } - dialog = gtk_file_chooser_dialog_new( "Open File", - NULL, - GTK_FILE_CHOOSER_ACTION_OPEN, - "_Cancel", GTK_RESPONSE_CANCEL, - "_Open", GTK_RESPONSE_ACCEPT, - NULL ); + dialog = gtk_file_chooser_dialog_new("Open File", NULL, GTK_FILE_CHOOSER_ACTION_OPEN, "_Cancel", GTK_RESPONSE_CANCEL, "_Open", GTK_RESPONSE_ACCEPT, NULL); /* Build the filter list */ AddFiltersToDialog(dialog, filterList); @@ -337,125 +297,17 @@ nfdresult_t NFD_OpenDialog( const nfdchar_t *filterList, SetDefaultPath(dialog, defaultPath); result = NFD_CANCEL; - if ( gtk_dialog_run( GTK_DIALOG(dialog) ) == GTK_RESPONSE_ACCEPT ) - { + if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { char *filename; - filename = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER(dialog) ); + filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); { size_t len = strlen(filename); - *outPath = NFDi_Malloc( len + 1 ); - memcpy( *outPath, filename, len + 1 ); - if ( !*outPath ) - { - g_free( filename ); - gtk_widget_destroy(dialog); - return NFD_ERROR; - } - } - g_free( filename ); - - result = NFD_OKAY; - } - - WaitForCleanup(); - gtk_widget_destroy(dialog); - WaitForCleanup(); - - return result; -} - - -nfdresult_t NFD_OpenDialogMultiple( const nfdchar_t *filterList, - const nfdchar_t *defaultPath, - nfdpathset_t *outPaths ) -{ - GtkWidget *dialog; - nfdresult_t result; - - iron_gtk_disable_setlocale(); - if ( !gtk_init_check( NULL, NULL ) ) - { - NFDi_SetError(INIT_FAIL_MSG); - return NFD_ERROR; - } - - dialog = gtk_file_chooser_dialog_new( "Open Files", - NULL, - GTK_FILE_CHOOSER_ACTION_OPEN, - "_Cancel", GTK_RESPONSE_CANCEL, - "_Open", GTK_RESPONSE_ACCEPT, - NULL ); - gtk_file_chooser_set_select_multiple( GTK_FILE_CHOOSER(dialog), TRUE ); - - /* Build the filter list */ - AddFiltersToDialog(dialog, filterList); - - /* Set the default path */ - SetDefaultPath(dialog, defaultPath); - - result = NFD_CANCEL; - if ( gtk_dialog_run( GTK_DIALOG(dialog) ) == GTK_RESPONSE_ACCEPT ) - { - GSList *fileList = gtk_file_chooser_get_filenames( GTK_FILE_CHOOSER(dialog) ); - if ( AllocPathSet( fileList, outPaths ) == NFD_ERROR ) - { - gtk_widget_destroy(dialog); - return NFD_ERROR; - } - - result = NFD_OKAY; - } - - WaitForCleanup(); - gtk_widget_destroy(dialog); - WaitForCleanup(); - - return result; -} - -nfdresult_t NFD_SaveDialog( const nfdchar_t *filterList, - const nfdchar_t *defaultPath, - nfdchar_t **outPath ) -{ - GtkWidget *dialog; - nfdresult_t result; - - iron_gtk_disable_setlocale(); - if ( !gtk_init_check( NULL, NULL ) ) - { - NFDi_SetError(INIT_FAIL_MSG); - return NFD_ERROR; - } - - dialog = gtk_file_chooser_dialog_new( "Save File", - NULL, - GTK_FILE_CHOOSER_ACTION_SAVE, - "_Cancel", GTK_RESPONSE_CANCEL, - "_Save", GTK_RESPONSE_ACCEPT, - NULL ); - gtk_file_chooser_set_do_overwrite_confirmation( GTK_FILE_CHOOSER(dialog), TRUE ); - - /* Build the filter list */ - AddFiltersToDialog(dialog, filterList); - - /* Set the default path */ - SetDefaultPath(dialog, defaultPath); - - result = NFD_CANCEL; - if ( gtk_dialog_run( GTK_DIALOG(dialog) ) == GTK_RESPONSE_ACCEPT ) - { - char *filename; - filename = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER(dialog) ); - - { - size_t len = strlen(filename); - *outPath = NFDi_Malloc( len + 1 ); - memcpy( *outPath, filename, len + 1 ); - if ( !*outPath ) - { - g_free( filename ); + *outPath = NFDi_Malloc(len + 1); + memcpy(*outPath, filename, len + 1); + if (!*outPath) { + g_free(filename); gtk_widget_destroy(dialog); return NFD_ERROR; } @@ -472,44 +324,117 @@ nfdresult_t NFD_SaveDialog( const nfdchar_t *filterList, return result; } -nfdresult_t NFD_PickFolder(const nfdchar_t *defaultPath, - nfdchar_t **outPath) -{ - GtkWidget *dialog; +nfdresult_t NFD_OpenDialogMultiple(const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdpathset_t *outPaths) { + GtkWidget *dialog; nfdresult_t result; iron_gtk_disable_setlocale(); - if (!gtk_init_check(NULL, NULL)) - { + if (!gtk_init_check(NULL, NULL)) { NFDi_SetError(INIT_FAIL_MSG); return NFD_ERROR; } - dialog = gtk_file_chooser_dialog_new( "Select folder", - NULL, - GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, - "_Cancel", GTK_RESPONSE_CANCEL, - "_Select", GTK_RESPONSE_ACCEPT, - NULL ); - gtk_file_chooser_set_do_overwrite_confirmation( GTK_FILE_CHOOSER(dialog), TRUE ); + dialog = gtk_file_chooser_dialog_new("Open Files", NULL, GTK_FILE_CHOOSER_ACTION_OPEN, "_Cancel", GTK_RESPONSE_CANCEL, "_Open", GTK_RESPONSE_ACCEPT, NULL); + gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog), TRUE); + /* Build the filter list */ + AddFiltersToDialog(dialog, filterList); /* Set the default path */ SetDefaultPath(dialog, defaultPath); result = NFD_CANCEL; - if ( gtk_dialog_run( GTK_DIALOG(dialog) ) == GTK_RESPONSE_ACCEPT ) - { + if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { + GSList *fileList = gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(dialog)); + if (AllocPathSet(fileList, outPaths) == NFD_ERROR) { + gtk_widget_destroy(dialog); + return NFD_ERROR; + } + + result = NFD_OKAY; + } + + WaitForCleanup(); + gtk_widget_destroy(dialog); + WaitForCleanup(); + + return result; +} + +nfdresult_t NFD_SaveDialog(const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdchar_t **outPath) { + GtkWidget *dialog; + nfdresult_t result; + + iron_gtk_disable_setlocale(); + if (!gtk_init_check(NULL, NULL)) { + NFDi_SetError(INIT_FAIL_MSG); + return NFD_ERROR; + } + + dialog = gtk_file_chooser_dialog_new("Save File", NULL, GTK_FILE_CHOOSER_ACTION_SAVE, "_Cancel", GTK_RESPONSE_CANCEL, "_Save", GTK_RESPONSE_ACCEPT, NULL); + gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog), TRUE); + + /* Build the filter list */ + AddFiltersToDialog(dialog, filterList); + + /* Set the default path */ + SetDefaultPath(dialog, defaultPath); + + result = NFD_CANCEL; + if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { char *filename; - filename = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER(dialog) ); + filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); { size_t len = strlen(filename); - *outPath = NFDi_Malloc( len + 1 ); - memcpy( *outPath, filename, len + 1 ); - if ( !*outPath ) - { - g_free( filename ); + *outPath = NFDi_Malloc(len + 1); + memcpy(*outPath, filename, len + 1); + if (!*outPath) { + g_free(filename); + gtk_widget_destroy(dialog); + return NFD_ERROR; + } + } + g_free(filename); + + result = NFD_OKAY; + } + + WaitForCleanup(); + gtk_widget_destroy(dialog); + WaitForCleanup(); + + return result; +} + +nfdresult_t NFD_PickFolder(const nfdchar_t *defaultPath, nfdchar_t **outPath) { + GtkWidget *dialog; + nfdresult_t result; + + iron_gtk_disable_setlocale(); + if (!gtk_init_check(NULL, NULL)) { + NFDi_SetError(INIT_FAIL_MSG); + return NFD_ERROR; + } + + dialog = gtk_file_chooser_dialog_new("Select folder", NULL, GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, "_Cancel", GTK_RESPONSE_CANCEL, "_Select", + GTK_RESPONSE_ACCEPT, NULL); + gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog), TRUE); + + /* Set the default path */ + SetDefaultPath(dialog, defaultPath); + + result = NFD_CANCEL; + if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { + char *filename; + filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); + + { + size_t len = strlen(filename); + *outPath = NFDi_Malloc(len + 1); + memcpy(*outPath, filename, len + 1); + if (!*outPath) { + g_free(filename); gtk_widget_destroy(dialog); return NFD_ERROR; } @@ -533,30 +458,28 @@ nfdresult_t NFD_PickFolder(const nfdchar_t *defaultPath, #ifdef __MINGW32__ // Explicitly setting NTDDI version, this is necessary for the MinGW compiler #define NTDDI_VERSION NTDDI_VISTA -#define _WIN32_WINNT _WIN32_WINNT_VISTA +#define _WIN32_WINNT _WIN32_WINNT_VISTA #endif #define _CRTDBG_MAP_ALLOC -#include #include +#include /* only locally define UNICODE in this compilation unit */ #ifndef UNICODE #define UNICODE #endif -#include -#include #include -#include #include +#include +#include +#include #define COM_INITFLAGS COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE -static BOOL COMIsInitialized(HRESULT coResult) -{ - if (coResult == RPC_E_CHANGED_MODE) - { +static BOOL COMIsInitialized(HRESULT coResult) { + if (coResult == RPC_E_CHANGED_MODE) { // If COM was previously initialized with different init flags, // NFD still needs to operate. Eat this warning. return TRUE; @@ -565,13 +488,11 @@ static BOOL COMIsInitialized(HRESULT coResult) return SUCCEEDED(coResult); } -static HRESULT COMInit(void) -{ +static HRESULT COMInit(void) { return CoInitializeEx(NULL, COM_INITFLAGS); } -static void COMUninit(HRESULT coResult) -{ +static void COMUninit(HRESULT coResult) { // do not uninitialize if RPC_E_CHANGED_MODE occurred -- this // case does not refcount COM. if (SUCCEEDED(coResult)) @@ -579,171 +500,141 @@ static void COMUninit(HRESULT coResult) } // allocs the space in outPath -- call free() -static void CopyWCharToNFDChar( const wchar_t *inStr, nfdchar_t **outStr ) -{ +static void CopyWCharToNFDChar(const wchar_t *inStr, nfdchar_t **outStr) { int inStrCharacterCount = (int)(wcslen(inStr)); - int bytesNeeded = WideCharToMultiByte( CP_UTF8, 0, - inStr, inStrCharacterCount, - NULL, 0, NULL, NULL ); - assert( bytesNeeded ); + int bytesNeeded = WideCharToMultiByte(CP_UTF8, 0, inStr, inStrCharacterCount, NULL, 0, NULL, NULL); + assert(bytesNeeded); bytesNeeded += 1; - *outStr = (nfdchar_t*)NFDi_Malloc( bytesNeeded ); - if ( !*outStr ) + *outStr = (nfdchar_t *)NFDi_Malloc(bytesNeeded); + if (!*outStr) return; - int bytesWritten = WideCharToMultiByte( CP_UTF8, 0, - inStr, -1, - *outStr, bytesNeeded, - NULL, NULL ); - assert( bytesWritten ); _NFD_UNUSED( bytesWritten ); + int bytesWritten = WideCharToMultiByte(CP_UTF8, 0, inStr, -1, *outStr, bytesNeeded, NULL, NULL); + assert(bytesWritten); + _NFD_UNUSED(bytesWritten); } /* includes NULL terminator byte in return */ -static size_t GetUTF8ByteCountForWChar( const wchar_t *str ) -{ - size_t bytesNeeded = WideCharToMultiByte( CP_UTF8, 0, - str, -1, - NULL, 0, NULL, NULL ); - assert( bytesNeeded ); - return bytesNeeded+1; +static size_t GetUTF8ByteCountForWChar(const wchar_t *str) { + size_t bytesNeeded = WideCharToMultiByte(CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL); + assert(bytesNeeded); + return bytesNeeded + 1; } // write to outPtr -- no free() necessary. -static int CopyWCharToExistingNFDCharBuffer( const wchar_t *inStr, nfdchar_t *outPtr ) -{ - int bytesNeeded = (int)(GetUTF8ByteCountForWChar( inStr )); +static int CopyWCharToExistingNFDCharBuffer(const wchar_t *inStr, nfdchar_t *outPtr) { + int bytesNeeded = (int)(GetUTF8ByteCountForWChar(inStr)); /* invocation copies null term */ - int bytesWritten = WideCharToMultiByte( CP_UTF8, 0, - inStr, -1, - outPtr, bytesNeeded, - NULL, 0 ); - assert( bytesWritten ); + int bytesWritten = WideCharToMultiByte(CP_UTF8, 0, inStr, -1, outPtr, bytesNeeded, NULL, 0); + assert(bytesWritten); return bytesWritten; - } - // allocs the space in outStr -- call free() -static void CopyNFDCharToWChar( const nfdchar_t *inStr, wchar_t **outStr ) -{ +static void CopyNFDCharToWChar(const nfdchar_t *inStr, wchar_t **outStr) { int inStrByteCount = (int)(strlen(inStr)); - int charsNeeded = MultiByteToWideChar(CP_UTF8, 0, - inStr, inStrByteCount, - NULL, 0 ); - assert( charsNeeded ); - assert( !*outStr ); + int charsNeeded = MultiByteToWideChar(CP_UTF8, 0, inStr, inStrByteCount, NULL, 0); + assert(charsNeeded); + assert(!*outStr); charsNeeded += 1; // terminator - *outStr = (wchar_t*)NFDi_Malloc( charsNeeded * sizeof(wchar_t) ); - if ( !*outStr ) + *outStr = (wchar_t *)NFDi_Malloc(charsNeeded * sizeof(wchar_t)); + if (!*outStr) return; - int ret = MultiByteToWideChar(CP_UTF8, 0, - inStr, inStrByteCount, - *outStr, charsNeeded); - (*outStr)[charsNeeded-1] = '\0'; + int ret = MultiByteToWideChar(CP_UTF8, 0, inStr, inStrByteCount, *outStr, charsNeeded); + (*outStr)[charsNeeded - 1] = '\0'; #ifdef _DEBUG int inStrCharacterCount = (int)(NFDi_UTF8_Strlen(inStr)); - assert( ret == inStrCharacterCount ); + assert(ret == inStrCharacterCount); #else _NFD_UNUSED(ret); #endif } /* ext is in format "jpg", no wildcards or separators */ -static int AppendExtensionToSpecBuf( const char *ext, char *specBuf, size_t specBufLen ) -{ +static int AppendExtensionToSpecBuf(const char *ext, char *specBuf, size_t specBufLen) { const char SEP[] = ";"; - assert( specBufLen > strlen(ext)+3 ); + assert(specBufLen > strlen(ext) + 3); - if ( strlen(specBuf) > 0 ) - { - strncat( specBuf, SEP, specBufLen - strlen(specBuf) - 1 ); + if (strlen(specBuf) > 0) { + strncat(specBuf, SEP, specBufLen - strlen(specBuf) - 1); specBufLen += strlen(SEP); } char extWildcard[NFD_MAX_STRLEN]; - int bytesWritten = sprintf_s( extWildcard, NFD_MAX_STRLEN, "*.%s", ext ); - assert( bytesWritten == (int)(strlen(ext)+2) ); + int bytesWritten = sprintf_s(extWildcard, NFD_MAX_STRLEN, "*.%s", ext); + assert(bytesWritten == (int)(strlen(ext) + 2)); _NFD_UNUSED(bytesWritten); - strncat( specBuf, extWildcard, specBufLen - strlen(specBuf) - 1 ); + strncat(specBuf, extWildcard, specBufLen - strlen(specBuf) - 1); return NFD_OKAY; } -static nfdresult_t AddFiltersToDialog( IFileDialog *fileOpenDialog, const char *filterList ) -{ +static nfdresult_t AddFiltersToDialog(IFileDialog *fileOpenDialog, const char *filterList) { const wchar_t WILDCARD[] = L"*.*"; - if ( !filterList || strlen(filterList) == 0 ) + if (!filterList || strlen(filterList) == 0) return NFD_OKAY; // Count rows to alloc - UINT filterCount = 1; /* guaranteed to have one filter on a correct, non-empty parse */ + UINT filterCount = 1; /* guaranteed to have one filter on a correct, non-empty parse */ const char *p_filterList; - for ( p_filterList = filterList; *p_filterList; ++p_filterList ) - { - if ( *p_filterList == ';' ) + for (p_filterList = filterList; *p_filterList; ++p_filterList) { + if (*p_filterList == ';') ++filterCount; } assert(filterCount); - if ( !filterCount ) - { + if (!filterCount) { NFDi_SetError("Error parsing filters."); return NFD_ERROR; } /* filterCount plus 1 because we hardcode the *.* wildcard after the while loop */ - COMDLG_FILTERSPEC *specList = (COMDLG_FILTERSPEC*)NFDi_Malloc( sizeof(COMDLG_FILTERSPEC) * ((size_t)filterCount + 1) ); - if ( !specList ) - { + COMDLG_FILTERSPEC *specList = (COMDLG_FILTERSPEC *)NFDi_Malloc(sizeof(COMDLG_FILTERSPEC) * ((size_t)filterCount + 1)); + if (!specList) { return NFD_ERROR; } - for (UINT i = 0; i < filterCount+1; ++i ) - { + for (UINT i = 0; i < filterCount + 1; ++i) { specList[i].pszName = NULL; specList[i].pszSpec = NULL; } - size_t specIdx = 0; - p_filterList = filterList; - char typebuf[NFD_MAX_STRLEN] = {0}; /* one per comma or semicolon */ - char *p_typebuf = typebuf; + size_t specIdx = 0; + p_filterList = filterList; + char typebuf[NFD_MAX_STRLEN] = {0}; /* one per comma or semicolon */ + char *p_typebuf = typebuf; char specbuf[NFD_MAX_STRLEN] = {0}; /* one per semicolon */ - while ( 1 ) - { - if ( NFDi_IsFilterSegmentChar(*p_filterList) ) - { + while (1) { + if (NFDi_IsFilterSegmentChar(*p_filterList)) { /* append a type to the specbuf (pending filter) */ - AppendExtensionToSpecBuf( typebuf, specbuf, NFD_MAX_STRLEN ); + AppendExtensionToSpecBuf(typebuf, specbuf, NFD_MAX_STRLEN); p_typebuf = typebuf; - memset( typebuf, 0, sizeof(char)*NFD_MAX_STRLEN ); + memset(typebuf, 0, sizeof(char) * NFD_MAX_STRLEN); } - if ( *p_filterList == ';' || *p_filterList == '\0' ) - { + if (*p_filterList == ';' || *p_filterList == '\0') { /* end of filter -- add it to specList */ - CopyNFDCharToWChar( specbuf, (wchar_t**)&specList[specIdx].pszName ); - CopyNFDCharToWChar( specbuf, (wchar_t**)&specList[specIdx].pszSpec ); + CopyNFDCharToWChar(specbuf, (wchar_t **)&specList[specIdx].pszName); + CopyNFDCharToWChar(specbuf, (wchar_t **)&specList[specIdx].pszSpec); - memset( specbuf, 0, sizeof(char)*NFD_MAX_STRLEN ); + memset(specbuf, 0, sizeof(char) * NFD_MAX_STRLEN); ++specIdx; - if ( specIdx == filterCount ) + if (specIdx == filterCount) break; } - if ( !NFDi_IsFilterSegmentChar( *p_filterList )) - { + if (!NFDi_IsFilterSegmentChar(*p_filterList)) { *p_typebuf = *p_filterList; ++p_typebuf; } @@ -758,48 +649,42 @@ static nfdresult_t AddFiltersToDialog( IFileDialog *fileOpenDialog, const char * fileOpenDialog->lpVtbl->SetFileTypes(fileOpenDialog, filterCount + 1, specList); /* free speclist */ - for ( size_t i = 0; i < filterCount; ++i ) - { - NFDi_Free( (void*)specList[i].pszSpec ); + for (size_t i = 0; i < filterCount; ++i) { + NFDi_Free((void *)specList[i].pszSpec); } - NFDi_Free( specList ); + NFDi_Free(specList); return NFD_OKAY; } -static nfdresult_t AllocPathSet( IShellItemArray *shellItems, nfdpathset_t *pathSet ) -{ +static nfdresult_t AllocPathSet(IShellItemArray *shellItems, nfdpathset_t *pathSet) { const char ERRORMSG[] = "Error allocating pathset."; assert(shellItems); assert(pathSet); // How many items in shellItems? - DWORD numShellItems; - HRESULT result = shellItems->lpVtbl->GetCount(shellItems, & numShellItems); - if ( !SUCCEEDED(result) ) - { + DWORD numShellItems; + HRESULT result = shellItems->lpVtbl->GetCount(shellItems, &numShellItems); + if (!SUCCEEDED(result)) { NFDi_SetError(ERRORMSG); return NFD_ERROR; } pathSet->count = (size_t)(numShellItems); - assert( pathSet->count > 0 ); + assert(pathSet->count > 0); - pathSet->indices = (size_t*)NFDi_Malloc( sizeof(size_t)*pathSet->count ); - if ( !pathSet->indices ) - { + pathSet->indices = (size_t *)NFDi_Malloc(sizeof(size_t) * pathSet->count); + if (!pathSet->indices) { return NFD_ERROR; } /* count the total bytes needed for buf */ size_t bufSize = 0; - for ( DWORD i = 0; i < numShellItems; ++i ) - { + for (DWORD i = 0; i < numShellItems; ++i) { IShellItem *shellItem; result = shellItems->lpVtbl->GetItemAt(shellItems, i, &shellItem); - if ( !SUCCEEDED(result) ) - { + if (!SUCCEEDED(result)) { NFDi_SetError(ERRORMSG); return NFD_ERROR; } @@ -807,36 +692,33 @@ static nfdresult_t AllocPathSet( IShellItemArray *shellItems, nfdpathset_t *path // Confirm SFGAO_FILESYSTEM is true for this shellitem, or ignore it. SFGAOF attribs; result = shellItem->lpVtbl->GetAttributes(shellItem, SFGAO_FILESYSTEM, &attribs); - if ( !SUCCEEDED(result) ) - { + if (!SUCCEEDED(result)) { NFDi_SetError(ERRORMSG); return NFD_ERROR; } - if ( !(attribs & SFGAO_FILESYSTEM) ) + if (!(attribs & SFGAO_FILESYSTEM)) continue; LPWSTR name; shellItem->lpVtbl->GetDisplayName(shellItem, SIGDN_FILESYSPATH, &name); // Calculate length of name with UTF-8 encoding - bufSize += GetUTF8ByteCountForWChar( name ); + bufSize += GetUTF8ByteCountForWChar(name); CoTaskMemFree(name); } assert(bufSize); - pathSet->buf = (nfdchar_t*)NFDi_Malloc( sizeof(nfdchar_t) * bufSize ); - memset( pathSet->buf, 0, sizeof(nfdchar_t) * bufSize ); + pathSet->buf = (nfdchar_t *)NFDi_Malloc(sizeof(nfdchar_t) * bufSize); + memset(pathSet->buf, 0, sizeof(nfdchar_t) * bufSize); /* fill buf */ nfdchar_t *p_buf = pathSet->buf; - for (DWORD i = 0; i < numShellItems; ++i ) - { + for (DWORD i = 0; i < numShellItems; ++i) { IShellItem *shellItem; result = shellItems->lpVtbl->GetItemAt(shellItems, i, &shellItem); - if ( !SUCCEEDED(result) ) - { + if (!SUCCEEDED(result)) { NFDi_SetError(ERRORMSG); return NFD_ERROR; } @@ -844,12 +726,11 @@ static nfdresult_t AllocPathSet( IShellItemArray *shellItems, nfdpathset_t *path // Confirm SFGAO_FILESYSTEM is true for this shellitem, or ignore it. SFGAOF attribs; result = shellItem->lpVtbl->GetAttributes(shellItem, SFGAO_FILESYSTEM, &attribs); - if ( !SUCCEEDED(result) ) - { + if (!SUCCEEDED(result)) { NFDi_SetError(ERRORMSG); return NFD_ERROR; } - if ( !(attribs & SFGAO_FILESYSTEM) ) + if (!(attribs & SFGAO_FILESYSTEM)) continue; LPWSTR name; @@ -859,7 +740,7 @@ static nfdresult_t AllocPathSet( IShellItemArray *shellItems, nfdpathset_t *path CoTaskMemFree(name); ptrdiff_t index = p_buf - pathSet->buf; - assert( index >= 0 ); + assert(index >= 0); pathSet->indices[i] = (size_t)(index); p_buf += bytesWritten; @@ -868,35 +749,32 @@ static nfdresult_t AllocPathSet( IShellItemArray *shellItems, nfdpathset_t *path return NFD_OKAY; } -static nfdresult_t SetDefaultPath( IFileDialog *dialog, const char *defaultPath ) -{ - if ( !defaultPath || strlen(defaultPath) == 0 ) +static nfdresult_t SetDefaultPath(IFileDialog *dialog, const char *defaultPath) { + if (!defaultPath || strlen(defaultPath) == 0) return NFD_OKAY; wchar_t *defaultPathW = {0}; - CopyNFDCharToWChar( defaultPath, &defaultPathW ); + CopyNFDCharToWChar(defaultPath, &defaultPathW); IShellItem *folder; - HRESULT result = SHCreateItemFromParsingName(defaultPathW, NULL, &IID_IShellItem, (void **)&folder); + HRESULT result = SHCreateItemFromParsingName(defaultPathW, NULL, &IID_IShellItem, (void **)&folder); // Valid non results. - if ( result == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) || result == HRESULT_FROM_WIN32(ERROR_INVALID_DRIVE) ) - { - NFDi_Free( defaultPathW ); + if (result == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) || result == HRESULT_FROM_WIN32(ERROR_INVALID_DRIVE)) { + NFDi_Free(defaultPathW); return NFD_OKAY; } - if ( !SUCCEEDED(result) ) - { + if (!SUCCEEDED(result)) { NFDi_SetError("Error creating ShellItem"); - NFDi_Free( defaultPathW ); + NFDi_Free(defaultPathW); return NFD_ERROR; } // Could also call SetDefaultFolder(), but this guarantees defaultPath -- more consistency across API. dialog->lpVtbl->SetFolder(dialog, folder); - NFDi_Free( defaultPathW ); + NFDi_Free(defaultPathW); folder->lpVtbl->Release(folder); return NFD_OKAY; @@ -904,69 +782,55 @@ static nfdresult_t SetDefaultPath( IFileDialog *dialog, const char *defaultPath /* public */ -nfdresult_t NFD_OpenDialog( const nfdchar_t *filterList, - const nfdchar_t *defaultPath, - nfdchar_t **outPath ) -{ +nfdresult_t NFD_OpenDialog(const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdchar_t **outPath) { nfdresult_t nfdResult = NFD_ERROR; - HRESULT coResult = COMInit(); - if (!COMIsInitialized(coResult)) - { + if (!COMIsInitialized(coResult)) { NFDi_SetError("Could not initialize COM."); return nfdResult; } // Create dialog IFileOpenDialog *fileOpenDialog; - HRESULT result = CoCreateInstance(&CLSID_FileOpenDialog, NULL, - CLSCTX_ALL, &IID_IFileOpenDialog, - (void**)(&fileOpenDialog) ); + HRESULT result = CoCreateInstance(&CLSID_FileOpenDialog, NULL, CLSCTX_ALL, &IID_IFileOpenDialog, (void **)(&fileOpenDialog)); - if ( !SUCCEEDED(result) ) - { + if (!SUCCEEDED(result)) { NFDi_SetError("Could not create dialog."); goto end; } // Build the filter list - if ( !AddFiltersToDialog( fileOpenDialog, filterList ) ) - { + if (!AddFiltersToDialog(fileOpenDialog, filterList)) { goto end; } // Set the default path - if ( !SetDefaultPath( fileOpenDialog, defaultPath ) ) - { + if (!SetDefaultPath(fileOpenDialog, defaultPath)) { goto end; } // Show the dialog. result = fileOpenDialog->lpVtbl->Show(fileOpenDialog, NULL); - if ( SUCCEEDED(result) ) - { + if (SUCCEEDED(result)) { // Get the file name IShellItem *shellItem; - result = fileOpenDialog->lpVtbl->GetResult(fileOpenDialog , & shellItem); - if ( !SUCCEEDED(result) ) - { + result = fileOpenDialog->lpVtbl->GetResult(fileOpenDialog, &shellItem); + if (!SUCCEEDED(result)) { NFDi_SetError("Could not get shell item from dialog."); goto end; } wchar_t *filePath; result = shellItem->lpVtbl->GetDisplayName(shellItem, SIGDN_FILESYSPATH, &filePath); - if ( !SUCCEEDED(result) ) - { + if (!SUCCEEDED(result)) { NFDi_SetError("Could not get file path for selected."); shellItem->lpVtbl->Release(shellItem); goto end; } - CopyWCharToNFDChar( filePath, outPath ); + CopyWCharToNFDChar(filePath, outPath); CoTaskMemFree(filePath); - if ( !*outPath ) - { + if (!*outPath) { /* error is malloc-based, error message would be redundant */ shellItem->lpVtbl->Release(shellItem); goto end; @@ -975,12 +839,10 @@ nfdresult_t NFD_OpenDialog( const nfdchar_t *filterList, nfdResult = NFD_OKAY; shellItem->lpVtbl->Release(shellItem); } - else if (result == HRESULT_FROM_WIN32(ERROR_CANCELLED) ) - { + else if (result == HRESULT_FROM_WIN32(ERROR_CANCELLED)) { nfdResult = NFD_CANCEL; } - else - { + else { NFDi_SetError("File dialog box show failed."); nfdResult = NFD_ERROR; } @@ -994,74 +856,59 @@ end: return nfdResult; } -nfdresult_t NFD_OpenDialogMultiple( const nfdchar_t *filterList, - const nfdchar_t *defaultPath, - nfdpathset_t *outPaths ) -{ +nfdresult_t NFD_OpenDialogMultiple(const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdpathset_t *outPaths) { nfdresult_t nfdResult = NFD_ERROR; - HRESULT coResult = COMInit(); - if (!COMIsInitialized(coResult)) - { + if (!COMIsInitialized(coResult)) { NFDi_SetError("Could not initialize COM."); return nfdResult; } // Create dialog IFileOpenDialog *fileOpenDialog; - HRESULT result = CoCreateInstance(&CLSID_FileOpenDialog, NULL, - CLSCTX_ALL, &IID_IFileOpenDialog, - (void**)(&fileOpenDialog) ); + HRESULT result = CoCreateInstance(&CLSID_FileOpenDialog, NULL, CLSCTX_ALL, &IID_IFileOpenDialog, (void **)(&fileOpenDialog)); - if ( !SUCCEEDED(result) ) - { + if (!SUCCEEDED(result)) { fileOpenDialog = NULL; NFDi_SetError("Could not create dialog."); goto end; } // Build the filter list - if ( !AddFiltersToDialog( fileOpenDialog, filterList ) ) - { + if (!AddFiltersToDialog(fileOpenDialog, filterList)) { goto end; } // Set the default path - if ( !SetDefaultPath( fileOpenDialog, defaultPath ) ) - { + if (!SetDefaultPath(fileOpenDialog, defaultPath)) { goto end; } // Set a flag for multiple options DWORD dwFlags; - result = fileOpenDialog->lpVtbl->GetOptions(fileOpenDialog , & dwFlags); - if ( !SUCCEEDED(result) ) - { + result = fileOpenDialog->lpVtbl->GetOptions(fileOpenDialog, &dwFlags); + if (!SUCCEEDED(result)) { NFDi_SetError("Could not get options."); goto end; } result = fileOpenDialog->lpVtbl->SetOptions(fileOpenDialog, dwFlags | FOS_ALLOWMULTISELECT); - if ( !SUCCEEDED(result) ) - { + if (!SUCCEEDED(result)) { NFDi_SetError("Could not set options."); goto end; } // Show the dialog. result = fileOpenDialog->lpVtbl->Show(fileOpenDialog, NULL); - if ( SUCCEEDED(result) ) - { + if (SUCCEEDED(result)) { IShellItemArray *shellItems; - result = fileOpenDialog->lpVtbl->GetResults(fileOpenDialog, & shellItems); - if ( !SUCCEEDED(result) ) - { + result = fileOpenDialog->lpVtbl->GetResults(fileOpenDialog, &shellItems); + if (!SUCCEEDED(result)) { NFDi_SetError("Could not get shell items."); goto end; } - if ( AllocPathSet( shellItems, outPaths ) == NFD_ERROR ) - { + if (AllocPathSet(shellItems, outPaths) == NFD_ERROR) { shellItems->lpVtbl->Release(shellItems); goto end; } @@ -1069,18 +916,16 @@ nfdresult_t NFD_OpenDialogMultiple( const nfdchar_t *filterList, shellItems->lpVtbl->Release(shellItems); nfdResult = NFD_OKAY; } - else if (result == HRESULT_FROM_WIN32(ERROR_CANCELLED) ) - { + else if (result == HRESULT_FROM_WIN32(ERROR_CANCELLED)) { nfdResult = NFD_CANCEL; } - else - { + else { NFDi_SetError("File dialog box show failed."); nfdResult = NFD_ERROR; } end: - if ( fileOpenDialog ) + if (fileOpenDialog) fileOpenDialog->lpVtbl->Release(fileOpenDialog); COMUninit(coResult); @@ -1088,69 +933,56 @@ end: return nfdResult; } -nfdresult_t NFD_SaveDialog( const nfdchar_t *filterList, - const nfdchar_t *defaultPath, - nfdchar_t **outPath ) -{ +nfdresult_t NFD_SaveDialog(const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdchar_t **outPath) { nfdresult_t nfdResult = NFD_ERROR; HRESULT coResult = COMInit(); - if (!COMIsInitialized(coResult)) - { + if (!COMIsInitialized(coResult)) { NFDi_SetError("Could not initialize COM."); return nfdResult; } // Create dialog IFileSaveDialog *fileSaveDialog; - HRESULT result = CoCreateInstance(&CLSID_FileSaveDialog, NULL, - CLSCTX_ALL, &IID_IFileSaveDialog, - (void**)(&fileSaveDialog) ); + HRESULT result = CoCreateInstance(&CLSID_FileSaveDialog, NULL, CLSCTX_ALL, &IID_IFileSaveDialog, (void **)(&fileSaveDialog)); - if ( !SUCCEEDED(result) ) - { + if (!SUCCEEDED(result)) { fileSaveDialog = NULL; NFDi_SetError("Could not create dialog."); goto end; } // Build the filter list - if ( !AddFiltersToDialog( fileSaveDialog, filterList ) ) - { + if (!AddFiltersToDialog(fileSaveDialog, filterList)) { goto end; } // Set the default path - if ( !SetDefaultPath( fileSaveDialog, defaultPath ) ) - { + if (!SetDefaultPath(fileSaveDialog, defaultPath)) { goto end; } // Show the dialog. result = fileSaveDialog->lpVtbl->Show(fileSaveDialog, NULL); - if ( SUCCEEDED(result) ) - { + if (SUCCEEDED(result)) { // Get the file name IShellItem *shellItem; - result = fileSaveDialog->lpVtbl->GetResult(fileSaveDialog , & shellItem); - if ( !SUCCEEDED(result) ) - { + result = fileSaveDialog->lpVtbl->GetResult(fileSaveDialog, &shellItem); + if (!SUCCEEDED(result)) { NFDi_SetError("Could not get shell item from dialog."); goto end; } wchar_t *filePath; result = shellItem->lpVtbl->GetDisplayName(shellItem, SIGDN_FILESYSPATH, &filePath); - if ( !SUCCEEDED(result) ) - { + if (!SUCCEEDED(result)) { shellItem->lpVtbl->Release(shellItem); NFDi_SetError("Could not get file path for selected."); goto end; } - CopyWCharToNFDChar( filePath, outPath ); + CopyWCharToNFDChar(filePath, outPath); CoTaskMemFree(filePath); - if ( !*outPath ) - { + if (!*outPath) { /* error is malloc-based, error message would be redundant */ shellItem->lpVtbl->Release(shellItem); goto end; @@ -1159,18 +991,16 @@ nfdresult_t NFD_SaveDialog( const nfdchar_t *filterList, nfdResult = NFD_OKAY; shellItem->lpVtbl->Release(shellItem); } - else if (result == HRESULT_FROM_WIN32(ERROR_CANCELLED) ) - { + else if (result == HRESULT_FROM_WIN32(ERROR_CANCELLED)) { nfdResult = NFD_CANCEL; } - else - { + else { NFDi_SetError("File dialog box show failed."); nfdResult = NFD_ERROR; } end: - if ( fileSaveDialog ) + if (fileSaveDialog) fileSaveDialog->lpVtbl->Release(fileSaveDialog); COMUninit(coResult); @@ -1178,70 +1008,58 @@ end: return nfdResult; } -nfdresult_t NFD_PickFolder(const nfdchar_t *defaultPath, - nfdchar_t **outPath) -{ +nfdresult_t NFD_PickFolder(const nfdchar_t *defaultPath, nfdchar_t **outPath) { nfdresult_t nfdResult = NFD_ERROR; - DWORD dwOptions = 0; + DWORD dwOptions = 0; HRESULT coResult = COMInit(); - if (!COMIsInitialized(coResult)) - { + if (!COMIsInitialized(coResult)) { NFDi_SetError("CoInitializeEx failed."); return nfdResult; } // Create dialog IFileOpenDialog *fileDialog; - HRESULT result = CoCreateInstance(&CLSID_FileOpenDialog, - NULL, - CLSCTX_ALL, &IID_IFileOpenDialog, (void **)&fileDialog); - if ( !SUCCEEDED(result) ) - { + HRESULT result = CoCreateInstance(&CLSID_FileOpenDialog, NULL, CLSCTX_ALL, &IID_IFileOpenDialog, (void **)&fileDialog); + if (!SUCCEEDED(result)) { NFDi_SetError("CoCreateInstance for CLSID_FileOpenDialog failed."); goto end; } // Set the default path - if (SetDefaultPath(fileDialog, defaultPath) != NFD_OKAY) - { + if (SetDefaultPath(fileDialog, defaultPath) != NFD_OKAY) { NFDi_SetError("SetDefaultPath failed."); goto end; } // Get the dialogs options - if (!SUCCEEDED(fileDialog->lpVtbl->GetOptions(fileDialog , & dwOptions))) - { + if (!SUCCEEDED(fileDialog->lpVtbl->GetOptions(fileDialog, &dwOptions))) { NFDi_SetError("GetOptions for IFileDialog failed."); goto end; } // Add in FOS_PICKFOLDERS which hides files and only allows selection of folders - if (!SUCCEEDED(fileDialog->lpVtbl->SetOptions(fileDialog, dwOptions | FOS_PICKFOLDERS))) - { + if (!SUCCEEDED(fileDialog->lpVtbl->SetOptions(fileDialog, dwOptions | FOS_PICKFOLDERS))) { NFDi_SetError("SetOptions for IFileDialog failed."); goto end; } // Show the dialog to the user result = fileDialog->lpVtbl->Show(fileDialog, NULL); - if ( SUCCEEDED(result) ) - { + if (SUCCEEDED(result)) { // Get the folder name IShellItem *shellItem; - result = fileDialog->lpVtbl->GetResult(fileDialog , & shellItem); - if ( !SUCCEEDED(result) ) - { + result = fileDialog->lpVtbl->GetResult(fileDialog, &shellItem); + if (!SUCCEEDED(result)) { NFDi_SetError("Could not get file path for selected."); shellItem->lpVtbl->Release(shellItem); goto end; } wchar_t *path = NULL; - result = shellItem->lpVtbl->GetDisplayName(shellItem, SIGDN_DESKTOPABSOLUTEPARSING, &path); - if ( !SUCCEEDED(result) ) - { + result = shellItem->lpVtbl->GetDisplayName(shellItem, SIGDN_DESKTOPABSOLUTEPARSING, &path); + if (!SUCCEEDED(result)) { NFDi_SetError("GetDisplayName for IShellItem failed."); shellItem->lpVtbl->Release(shellItem); goto end; @@ -1249,8 +1067,7 @@ nfdresult_t NFD_PickFolder(const nfdchar_t *defaultPath, CopyWCharToNFDChar(path, outPath); CoTaskMemFree(path); - if ( !*outPath ) - { + if (!*outPath) { shellItem->lpVtbl->Release(shellItem); goto end; } @@ -1258,20 +1075,18 @@ nfdresult_t NFD_PickFolder(const nfdchar_t *defaultPath, nfdResult = NFD_OKAY; shellItem->lpVtbl->Release(shellItem); } - else if (result == HRESULT_FROM_WIN32(ERROR_CANCELLED) ) - { + else if (result == HRESULT_FROM_WIN32(ERROR_CANCELLED)) { nfdResult = NFD_CANCEL; } - else - { + else { NFDi_SetError("Show for IFileDialog failed."); nfdResult = NFD_ERROR; } - end: +end: if (fileDialog) - fileDialog->lpVtbl->Release(fileDialog); + fileDialog->lpVtbl->Release(fileDialog); COMUninit(coResult); diff --git a/base/sources/libs/nfd.h b/base/sources/libs/nfd.h index b9e6302f..ebaf728f 100644 --- a/base/sources/libs/nfd.h +++ b/base/sources/libs/nfd.h @@ -21,44 +21,37 @@ typedef char nfdchar_t; typedef struct { - nfdchar_t *buf; - size_t *indices; /* byte offsets into buf */ - size_t count; /* number of indices into buf */ -}nfdpathset_t; + nfdchar_t *buf; + size_t *indices; /* byte offsets into buf */ + size_t count; /* number of indices into buf */ +} nfdpathset_t; typedef enum { - NFD_ERROR, /* programmatic error */ - NFD_OKAY, /* user pressed okay, or successful return */ - NFD_CANCEL /* user pressed cancel */ -}nfdresult_t; + NFD_ERROR, /* programmatic error */ + NFD_OKAY, /* user pressed okay, or successful return */ + NFD_CANCEL /* user pressed cancel */ +} nfdresult_t; -nfdresult_t NFD_OpenDialog( const nfdchar_t *filterList, - const nfdchar_t *defaultPath, - nfdchar_t **outPath ); +nfdresult_t NFD_OpenDialog(const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdchar_t **outPath); -nfdresult_t NFD_OpenDialogMultiple( const nfdchar_t *filterList, - const nfdchar_t *defaultPath, - nfdpathset_t *outPaths ); +nfdresult_t NFD_OpenDialogMultiple(const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdpathset_t *outPaths); -nfdresult_t NFD_SaveDialog( const nfdchar_t *filterList, - const nfdchar_t *defaultPath, - nfdchar_t **outPath ); +nfdresult_t NFD_SaveDialog(const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdchar_t **outPath); -nfdresult_t NFD_PickFolder( const nfdchar_t *defaultPath, - nfdchar_t **outPath); +nfdresult_t NFD_PickFolder(const nfdchar_t *defaultPath, nfdchar_t **outPath); -const char *NFD_GetError( void ); -size_t NFD_PathSet_GetCount( const nfdpathset_t *pathSet ); -nfdchar_t *NFD_PathSet_GetPath( const nfdpathset_t *pathSet, size_t index ); -void NFD_PathSet_Free( nfdpathset_t *pathSet ); +const char *NFD_GetError(void); +size_t NFD_PathSet_GetCount(const nfdpathset_t *pathSet); +nfdchar_t *NFD_PathSet_GetPath(const nfdpathset_t *pathSet, size_t index); +void NFD_PathSet_Free(nfdpathset_t *pathSet); #define NFD_MAX_STRLEN 256 #define _NFD_UNUSED(x) ((void)x) -#define NFD_UTF8_BOM "\xEF\xBB\xBF" +#define NFD_UTF8_BOM "\xEF\xBB\xBF" -void *NFDi_Malloc( size_t bytes ); -void NFDi_Free( void *ptr ); -void NFDi_SetError( const char *msg ); -int NFDi_SafeStrncpy( char *dst, const char *src, size_t maxCopy ); -int32_t NFDi_UTF8_Strlen( const nfdchar_t *str ); -int NFDi_IsFilterSegmentChar( char ch ); +void *NFDi_Malloc(size_t bytes); +void NFDi_Free(void *ptr); +void NFDi_SetError(const char *msg); +int NFDi_SafeStrncpy(char *dst, const char *src, size_t maxCopy); +int32_t NFDi_UTF8_Strlen(const nfdchar_t *str); +int NFDi_IsFilterSegmentChar(char ch); diff --git a/base/sources/libs/nfd.m b/base/sources/libs/nfd.m index 80f126f4..1247c191 100644 --- a/base/sources/libs/nfd.m +++ b/base/sources/libs/nfd.m @@ -13,10 +13,10 @@ // 3. This notice may not be removed or altered from any source distribution. // https://github.com/mlabbe/nativefiledialog -#include #include "nfd.h" +#include -static NSArray *BuildAllowedFileTypes( const char *filterList ) { +static NSArray *BuildAllowedFileTypes(const char *filterList) { // Commas and semicolons are the same thing on this platform NSMutableArray *buildFilterList = [[NSMutableArray alloc] init]; @@ -24,89 +24,80 @@ static NSArray *BuildAllowedFileTypes( const char *filterList ) { char typebuf[NFD_MAX_STRLEN] = {0}; size_t filterListLen = strlen(filterList); - char *p_typebuf = typebuf; - for ( size_t i = 0; i < filterListLen+1; ++i ) - { - if ( filterList[i] == ',' || filterList[i] == ';' || filterList[i] == '\0' ) - { - *p_typebuf = '\0'; - NSString *thisType = [NSString stringWithUTF8String: typebuf]; + char *p_typebuf = typebuf; + for (size_t i = 0; i < filterListLen + 1; ++i) { + if (filterList[i] == ',' || filterList[i] == ';' || filterList[i] == '\0') { + *p_typebuf = '\0'; + NSString *thisType = [NSString stringWithUTF8String:typebuf]; [buildFilterList addObject:thisType]; - p_typebuf = typebuf; + p_typebuf = typebuf; *p_typebuf = '\0'; } - else - { + else { *p_typebuf = filterList[i]; ++p_typebuf; - } } NSArray *returnArray = [NSArray arrayWithArray:buildFilterList]; -// [buildFilterList release]; + // [buildFilterList release]; return returnArray; } -static void AddFilterListToDialog( NSSavePanel *dialog, const char *filterList ) { - if ( !filterList || strlen(filterList) == 0 ) +static void AddFilterListToDialog(NSSavePanel *dialog, const char *filterList) { + if (!filterList || strlen(filterList) == 0) return; - NSArray *allowedFileTypes = BuildAllowedFileTypes( filterList ); - if ( [allowedFileTypes count] != 0 ) - { + NSArray *allowedFileTypes = BuildAllowedFileTypes(filterList); + if ([allowedFileTypes count] != 0) { [dialog setAllowedFileTypes:allowedFileTypes]; } } -static void SetDefaultPath( NSSavePanel *dialog, const nfdchar_t *defaultPath ) { - if ( !defaultPath || strlen(defaultPath) == 0 ) +static void SetDefaultPath(NSSavePanel *dialog, const nfdchar_t *defaultPath) { + if (!defaultPath || strlen(defaultPath) == 0) return; - NSString *defaultPathString = [NSString stringWithUTF8String: defaultPath]; - NSURL *url = [NSURL fileURLWithPath:defaultPathString isDirectory:YES]; + NSString *defaultPathString = [NSString stringWithUTF8String:defaultPath]; + NSURL *url = [NSURL fileURLWithPath:defaultPathString isDirectory:YES]; [dialog setDirectoryURL:url]; } /* fixme: pathset should be pathSet */ -static nfdresult_t AllocPathSet( NSArray *urls, nfdpathset_t *pathset ) { +static nfdresult_t AllocPathSet(NSArray *urls, nfdpathset_t *pathset) { assert(pathset); assert([urls count]); - pathset->count = (size_t)[urls count]; - pathset->indices = NFDi_Malloc( sizeof(size_t)*pathset->count ); - if ( !pathset->indices ) - { + pathset->count = (size_t)[urls count]; + pathset->indices = NFDi_Malloc(sizeof(size_t) * pathset->count); + if (!pathset->indices) { return NFD_ERROR; } // count the total space needed for buf size_t bufsize = 0; - for ( NSURL *url in urls ) - { + for (NSURL *url in urls) { NSString *path = [url path]; bufsize += [path lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1; } - pathset->buf = NFDi_Malloc( sizeof(nfdchar_t) * bufsize ); - if ( !pathset->buf ) - { + pathset->buf = NFDi_Malloc(sizeof(nfdchar_t) * bufsize); + if (!pathset->buf) { return NFD_ERROR; } // fill buf nfdchar_t *p_buf = pathset->buf; - size_t count = 0; - for ( NSURL *url in urls ) - { - NSString *path = [url path]; + size_t count = 0; + for (NSURL *url in urls) { + NSString *path = [url path]; const nfdchar_t *utf8Path = [path UTF8String]; - size_t byteLen = [path lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1; - memcpy( p_buf, utf8Path, byteLen ); + size_t byteLen = [path lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1; + memcpy(p_buf, utf8Path, byteLen); ptrdiff_t index = p_buf - pathset->buf; - assert( index >= 0 ); + assert(index >= 0); pathset->indices[count] = (size_t)index; p_buf += byteLen; @@ -116,13 +107,11 @@ static nfdresult_t AllocPathSet( NSArray *urls, nfdpathset_t *pathset ) { return NFD_OKAY; } -nfdresult_t NFD_OpenDialog( const nfdchar_t *filterList, - const nfdchar_t *defaultPath, - nfdchar_t **outPath ) { -// NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; +nfdresult_t NFD_OpenDialog(const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdchar_t **outPath) { + // NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - NSWindow *keyWindow = [[NSApplication sharedApplication] keyWindow]; - NSOpenPanel *dialog = [NSOpenPanel openPanel]; + NSWindow *keyWindow = [[NSApplication sharedApplication] keyWindow]; + NSOpenPanel *dialog = [NSOpenPanel openPanel]; [dialog setAllowsMultipleSelection:NO]; // Build the filter list @@ -132,34 +121,30 @@ nfdresult_t NFD_OpenDialog( const nfdchar_t *filterList, SetDefaultPath(dialog, defaultPath); nfdresult_t nfdResult = NFD_CANCEL; - if ( [dialog runModal] == NSModalResponseOK ) - { - NSURL *url = [dialog URL]; + if ([dialog runModal] == NSModalResponseOK) { + NSURL *url = [dialog URL]; const char *utf8Path = [[url path] UTF8String]; // byte count, not char count - size_t len = strlen(utf8Path);//NFDi_UTF8_Strlen(utf8Path); + size_t len = strlen(utf8Path); // NFDi_UTF8_Strlen(utf8Path); - *outPath = NFDi_Malloc( len+1 ); - if ( !*outPath ) - { -// [pool release]; + *outPath = NFDi_Malloc(len + 1); + if (!*outPath) { + // [pool release]; [keyWindow makeKeyAndOrderFront:nil]; return NFD_ERROR; } - memcpy( *outPath, utf8Path, len+1 ); /* copy null term */ + memcpy(*outPath, utf8Path, len + 1); /* copy null term */ nfdResult = NFD_OKAY; } -// [pool release]; + // [pool release]; [keyWindow makeKeyAndOrderFront:nil]; return nfdResult; } -nfdresult_t NFD_OpenDialogMultiple( const nfdchar_t *filterList, - const nfdchar_t *defaultPath, - nfdpathset_t *outPaths ) { -// NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; +nfdresult_t NFD_OpenDialogMultiple(const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdpathset_t *outPaths) { + // NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSWindow *keyWindow = [[NSApplication sharedApplication] keyWindow]; NSOpenPanel *dialog = [NSOpenPanel openPanel]; @@ -172,36 +157,31 @@ nfdresult_t NFD_OpenDialogMultiple( const nfdchar_t *filterList, SetDefaultPath(dialog, defaultPath); nfdresult_t nfdResult = NFD_CANCEL; - if ( [dialog runModal] == NSModalResponseOK ) - { + if ([dialog runModal] == NSModalResponseOK) { NSArray *urls = [dialog URLs]; - if ( [urls count] == 0 ) - { -// [pool release]; + if ([urls count] == 0) { + // [pool release]; [keyWindow makeKeyAndOrderFront:nil]; return NFD_CANCEL; } - if ( AllocPathSet( urls, outPaths ) == NFD_ERROR ) - { -// [pool release]; + if (AllocPathSet(urls, outPaths) == NFD_ERROR) { + // [pool release]; [keyWindow makeKeyAndOrderFront:nil]; return NFD_ERROR; } nfdResult = NFD_OKAY; } -// [pool release]; + // [pool release]; [keyWindow makeKeyAndOrderFront:nil]; return nfdResult; } -nfdresult_t NFD_SaveDialog( const nfdchar_t *filterList, - const nfdchar_t *defaultPath, - nfdchar_t **outPath ) { -// NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; +nfdresult_t NFD_SaveDialog(const nfdchar_t *filterList, const nfdchar_t *defaultPath, nfdchar_t **outPath) { + // NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSWindow *keyWindow = [[NSApplication sharedApplication] keyWindow]; NSSavePanel *dialog = [NSSavePanel savePanel]; @@ -214,35 +194,32 @@ nfdresult_t NFD_SaveDialog( const nfdchar_t *filterList, SetDefaultPath(dialog, defaultPath); nfdresult_t nfdResult = NFD_CANCEL; - if ( [dialog runModal] == NSModalResponseOK ) - { - NSURL *url = [dialog URL]; + if ([dialog runModal] == NSModalResponseOK) { + NSURL *url = [dialog URL]; const char *utf8Path = [[url path] UTF8String]; size_t byteLen = [url.path lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1; - *outPath = NFDi_Malloc( byteLen ); - if ( !*outPath ) - { -// [pool release]; + *outPath = NFDi_Malloc(byteLen); + if (!*outPath) { + // [pool release]; [keyWindow makeKeyAndOrderFront:nil]; return NFD_ERROR; } - memcpy( *outPath, utf8Path, byteLen ); + memcpy(*outPath, utf8Path, byteLen); nfdResult = NFD_OKAY; } -// [pool release]; + // [pool release]; [keyWindow makeKeyAndOrderFront:nil]; return nfdResult; } -nfdresult_t NFD_PickFolder(const nfdchar_t *defaultPath, - nfdchar_t **outPath) { -// NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; +nfdresult_t NFD_PickFolder(const nfdchar_t *defaultPath, nfdchar_t **outPath) { + // NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - NSWindow *keyWindow = [[NSApplication sharedApplication] keyWindow]; - NSOpenPanel *dialog = [NSOpenPanel openPanel]; + NSWindow *keyWindow = [[NSApplication sharedApplication] keyWindow]; + NSOpenPanel *dialog = [NSOpenPanel openPanel]; [dialog setAllowsMultipleSelection:NO]; [dialog setCanChooseDirectories:YES]; [dialog setCanCreateDirectories:YES]; @@ -252,25 +229,23 @@ nfdresult_t NFD_PickFolder(const nfdchar_t *defaultPath, SetDefaultPath(dialog, defaultPath); nfdresult_t nfdResult = NFD_CANCEL; - if ( [dialog runModal] == NSModalResponseOK ) - { - NSURL *url = [dialog URL]; + if ([dialog runModal] == NSModalResponseOK) { + NSURL *url = [dialog URL]; const char *utf8Path = [[url path] UTF8String]; // byte count, not char count - size_t len = strlen(utf8Path);//NFDi_UTF8_Strlen(utf8Path); + size_t len = strlen(utf8Path); // NFDi_UTF8_Strlen(utf8Path); - *outPath = NFDi_Malloc( len+1 ); - if ( !*outPath ) - { -// [pool release]; + *outPath = NFDi_Malloc(len + 1); + if (!*outPath) { + // [pool release]; [keyWindow makeKeyAndOrderFront:nil]; return NFD_ERROR; } - memcpy( *outPath, utf8Path, len+1 ); /* copy null term */ + memcpy(*outPath, utf8Path, len + 1); /* copy null term */ nfdResult = NFD_OKAY; } -// [pool release]; + // [pool release]; [keyWindow makeKeyAndOrderFront:nil]; return nfdResult; diff --git a/base/sources/libs/sdefl.h b/base/sources/libs/sdefl.h index 4a47593c..8e3ca430 100644 --- a/base/sources/libs/sdefl.h +++ b/base/sources/libs/sdefl.h @@ -115,54 +115,54 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. extern "C" { #endif -#define SDEFL_MAX_OFF (1 << 15) -#define SDEFL_WIN_SIZ SDEFL_MAX_OFF -#define SDEFL_WIN_MSK (SDEFL_WIN_SIZ-1) +#define SDEFL_MAX_OFF (1 << 15) +#define SDEFL_WIN_SIZ SDEFL_MAX_OFF +#define SDEFL_WIN_MSK (SDEFL_WIN_SIZ - 1) #define SDEFL_HASH_BITS 15 #define SDEFL_HASH_SIZ (1 << SDEFL_HASH_BITS) -#define SDEFL_HASH_MSK (SDEFL_HASH_SIZ-1) +#define SDEFL_HASH_MSK (SDEFL_HASH_SIZ - 1) #define SDEFL_MIN_MATCH 4 -#define SDEFL_BLK_MAX (256*1024) -#define SDEFL_SEQ_SIZ ((SDEFL_BLK_MAX+2)/3) +#define SDEFL_BLK_MAX (256 * 1024) +#define SDEFL_SEQ_SIZ ((SDEFL_BLK_MAX + 2) / 3) -#define SDEFL_SYM_MAX (288) -#define SDEFL_OFF_MAX (32) -#define SDEFL_PRE_MAX (19) +#define SDEFL_SYM_MAX (288) +#define SDEFL_OFF_MAX (32) +#define SDEFL_PRE_MAX (19) -#define SDEFL_LVL_MIN 0 -#define SDEFL_LVL_DEF 5 -#define SDEFL_LVL_MAX 8 +#define SDEFL_LVL_MIN 0 +#define SDEFL_LVL_DEF 5 +#define SDEFL_LVL_MAX 8 struct sdefl_freq { - unsigned lit[SDEFL_SYM_MAX]; - unsigned off[SDEFL_OFF_MAX]; + unsigned lit[SDEFL_SYM_MAX]; + unsigned off[SDEFL_OFF_MAX]; }; struct sdefl_code_words { - unsigned lit[SDEFL_SYM_MAX]; - unsigned off[SDEFL_OFF_MAX]; + unsigned lit[SDEFL_SYM_MAX]; + unsigned off[SDEFL_OFF_MAX]; }; struct sdefl_lens { - unsigned char lit[SDEFL_SYM_MAX]; - unsigned char off[SDEFL_OFF_MAX]; + unsigned char lit[SDEFL_SYM_MAX]; + unsigned char off[SDEFL_OFF_MAX]; }; struct sdefl_codes { - struct sdefl_code_words word; - struct sdefl_lens len; + struct sdefl_code_words word; + struct sdefl_lens len; }; struct sdefl_seqt { - int off, len; + int off, len; }; struct sdefl { - int bits, bitcnt; - int tbl[SDEFL_HASH_SIZ]; - int prv[SDEFL_WIN_SIZ]; + int bits, bitcnt; + int tbl[SDEFL_HASH_SIZ]; + int prv[SDEFL_WIN_SIZ]; - int seq_cnt; - struct sdefl_seqt seq[SDEFL_SEQ_SIZ]; - struct sdefl_freq freq; - struct sdefl_codes cod; + int seq_cnt; + struct sdefl_seqt seq[SDEFL_SEQ_SIZ]; + struct sdefl_freq freq; + struct sdefl_codes cod; }; extern int sdefl_bound(int in_len); extern int sdeflate(struct sdefl *s, void *o, const void *i, int n, int lvl); @@ -177,8 +177,8 @@ extern int zsdeflate(struct sdefl *s, void *o, const void *i, int n, int lvl); #ifdef SDEFL_IMPLEMENTATION #include /* assert */ -#include /* memcpy */ #include /* CHAR_BIT */ +#include /* memcpy */ #ifdef _MSC_VER #include #endif @@ -187,612 +187,599 @@ extern int zsdeflate(struct sdefl *s, void *o, const void *i, int n, int lvl); extern "C" { #endif -#define SDEFL_NIL (-1) -#define SDEFL_MAX_MATCH 258 -#define SDEFL_MAX_CODE_LEN (15) -#define SDEFL_SYM_BITS (10u) -#define SDEFL_SYM_MSK ((1u << SDEFL_SYM_BITS)-1u) -#define SDEFL_RAW_BLK_SIZE (65535) -#define SDEFL_LIT_LEN_CODES (14) -#define SDEFL_OFF_CODES (15) -#define SDEFL_PRE_CODES (7) -#define SDEFL_CNT_NUM(n) ((((n)+3u/4u)+3u)&~3u) -#define SDEFL_EOB (256) +#define SDEFL_NIL (-1) +#define SDEFL_MAX_MATCH 258 +#define SDEFL_MAX_CODE_LEN (15) +#define SDEFL_SYM_BITS (10u) +#define SDEFL_SYM_MSK ((1u << SDEFL_SYM_BITS) - 1u) +#define SDEFL_RAW_BLK_SIZE (65535) +#define SDEFL_LIT_LEN_CODES (14) +#define SDEFL_OFF_CODES (15) +#define SDEFL_PRE_CODES (7) +#define SDEFL_CNT_NUM(n) ((((n) + 3u / 4u) + 3u) & ~3u) +#define SDEFL_EOB (256) -#define sdefl_npow2(n) (1 << (sdefl_ilog2((n)-1) + 1)) -#define sdefl_div_round_up(n,d) (((n)+((d)-1))/(d)) +#define sdefl_npow2(n) (1 << (sdefl_ilog2((n) - 1) + 1)) +#define sdefl_div_round_up(n, d) (((n) + ((d) - 1)) / (d)) -static int -sdefl_ilog2(int n) { - if (!n) return 0; +static int sdefl_ilog2(int n) { + if (!n) + return 0; #ifdef _MSC_VER - unsigned long msbp = 0; - _BitScanReverse(&msbp, (unsigned long)n); - return (int)msbp; + unsigned long msbp = 0; + _BitScanReverse(&msbp, (unsigned long)n); + return (int)msbp; #elif defined(__GNUC__) || defined(__clang__) - return (int)sizeof(unsigned long) * CHAR_BIT - 1 - __builtin_clzl((unsigned long)n); + return (int)sizeof(unsigned long) * CHAR_BIT - 1 - __builtin_clzl((unsigned long)n); #else - #define lt(n) n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n - static const char tbl[256] = { - 0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,lt(4), lt(5), lt(5), lt(6), lt(6), lt(6), lt(6), - lt(7), lt(7), lt(7), lt(7), lt(7), lt(7), lt(7), lt(7)}; - int tt, t; - if ((tt = (n >> 16))) { - return (t = (tt >> 8)) ? 24 + tbl[t] : 16 + tbl[tt]; - } else { - return (t = (n >> 8)) ? 8 + tbl[t] : tbl[n]; - } - #undef lt +#define lt(n) n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n + static const char tbl[256] = {0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, + lt(4), lt(5), lt(5), lt(6), lt(6), lt(6), lt(6), lt(7), lt(7), lt(7), lt(7), lt(7), lt(7), lt(7), lt(7)}; + int tt, t; + if ((tt = (n >> 16))) { + return (t = (tt >> 8)) ? 24 + tbl[t] : 16 + tbl[tt]; + } + else { + return (t = (n >> 8)) ? 8 + tbl[t] : tbl[n]; + } +#undef lt #endif } -static unsigned -sdefl_uload32(const void *p) { - /* hopefully will be optimized to an unaligned read */ - unsigned n = 0; - memcpy(&n, p, sizeof(n)); - return n; +static unsigned sdefl_uload32(const void *p) { + /* hopefully will be optimized to an unaligned read */ + unsigned n = 0; + memcpy(&n, p, sizeof(n)); + return n; } -static unsigned -sdefl_hash32(const void *p) { - unsigned n = sdefl_uload32(p); - return (n * 0x9E377989) >> (32 - SDEFL_HASH_BITS); +static unsigned sdefl_hash32(const void *p) { + unsigned n = sdefl_uload32(p); + return (n * 0x9E377989) >> (32 - SDEFL_HASH_BITS); } -static void -sdefl_put(unsigned char **dst, struct sdefl *s, int code, int bitcnt) { - s->bits |= (code << s->bitcnt); - s->bitcnt += bitcnt; - while (s->bitcnt >= 8) { - unsigned char *tar = *dst; - *tar = (unsigned char)(s->bits & 0xFF); - s->bits >>= 8; - s->bitcnt -= 8; - *dst = *dst + 1; - } +static void sdefl_put(unsigned char **dst, struct sdefl *s, int code, int bitcnt) { + s->bits |= (code << s->bitcnt); + s->bitcnt += bitcnt; + while (s->bitcnt >= 8) { + unsigned char *tar = *dst; + *tar = (unsigned char)(s->bits & 0xFF); + s->bits >>= 8; + s->bitcnt -= 8; + *dst = *dst + 1; + } } -static void -sdefl_heap_sub(unsigned A[], unsigned len, unsigned sub) { - unsigned c, p = sub; - unsigned v = A[sub]; - while ((c = p << 1) <= len) { - if (c < len && A[c + 1] > A[c]) c++; - if (v >= A[c]) break; - A[p] = A[c], p = c; - } - A[p] = v; +static void sdefl_heap_sub(unsigned A[], unsigned len, unsigned sub) { + unsigned c, p = sub; + unsigned v = A[sub]; + while ((c = p << 1) <= len) { + if (c < len && A[c + 1] > A[c]) + c++; + if (v >= A[c]) + break; + A[p] = A[c], p = c; + } + A[p] = v; } -static void -sdefl_heap_array(unsigned *A, unsigned len) { - unsigned sub; - for (sub = len >> 1; sub >= 1; sub--) - sdefl_heap_sub(A, len, sub); +static void sdefl_heap_array(unsigned *A, unsigned len) { + unsigned sub; + for (sub = len >> 1; sub >= 1; sub--) + sdefl_heap_sub(A, len, sub); } -static void -sdefl_heap_sort(unsigned *A, unsigned n) { - A--; - sdefl_heap_array(A, n); - while (n >= 2) { - unsigned tmp = A[n]; - A[n--] = A[1]; - A[1] = tmp; - sdefl_heap_sub(A, n, 1); - } +static void sdefl_heap_sort(unsigned *A, unsigned n) { + A--; + sdefl_heap_array(A, n); + while (n >= 2) { + unsigned tmp = A[n]; + A[n--] = A[1]; + A[1] = tmp; + sdefl_heap_sub(A, n, 1); + } } -static unsigned -sdefl_sort_sym(unsigned sym_cnt, unsigned *freqs, - unsigned char *lens, unsigned *sym_out) { - unsigned cnts[SDEFL_CNT_NUM(SDEFL_SYM_MAX)] = {0}; - unsigned cnt_num = SDEFL_CNT_NUM(sym_cnt); - unsigned used_sym = 0; - unsigned sym, i; - for (sym = 0; sym < sym_cnt; sym++) - cnts[freqs[sym] < cnt_num-1 ? freqs[sym]: cnt_num-1]++; - for (i = 1; i < cnt_num; i++) { - unsigned cnt = cnts[i]; - cnts[i] = used_sym; - used_sym += cnt; - } - for (sym = 0; sym < sym_cnt; sym++) { - unsigned freq = freqs[sym]; - if (freq) { - unsigned idx = freq < cnt_num-1 ? freq : cnt_num-1; - sym_out[cnts[idx]++] = sym | (freq << SDEFL_SYM_BITS); - } else lens[sym] = 0; - } - sdefl_heap_sort(sym_out + cnts[cnt_num-2], cnts[cnt_num-1] - cnts[cnt_num-2]); - return used_sym; +static unsigned sdefl_sort_sym(unsigned sym_cnt, unsigned *freqs, unsigned char *lens, unsigned *sym_out) { + unsigned cnts[SDEFL_CNT_NUM(SDEFL_SYM_MAX)] = {0}; + unsigned cnt_num = SDEFL_CNT_NUM(sym_cnt); + unsigned used_sym = 0; + unsigned sym, i; + for (sym = 0; sym < sym_cnt; sym++) + cnts[freqs[sym] < cnt_num - 1 ? freqs[sym] : cnt_num - 1]++; + for (i = 1; i < cnt_num; i++) { + unsigned cnt = cnts[i]; + cnts[i] = used_sym; + used_sym += cnt; + } + for (sym = 0; sym < sym_cnt; sym++) { + unsigned freq = freqs[sym]; + if (freq) { + unsigned idx = freq < cnt_num - 1 ? freq : cnt_num - 1; + sym_out[cnts[idx]++] = sym | (freq << SDEFL_SYM_BITS); + } + else + lens[sym] = 0; + } + sdefl_heap_sort(sym_out + cnts[cnt_num - 2], cnts[cnt_num - 1] - cnts[cnt_num - 2]); + return used_sym; } -static void -sdefl_build_tree(unsigned *A, unsigned sym_cnt) { - unsigned i = 0, b = 0, e = 0; - do { - unsigned m, n, freq_shift; - if (i != sym_cnt && (b == e || (A[i] >> SDEFL_SYM_BITS) <= (A[b] >> SDEFL_SYM_BITS))) - m = i++; - else m = b++; - if (i != sym_cnt && (b == e || (A[i] >> SDEFL_SYM_BITS) <= (A[b] >> SDEFL_SYM_BITS))) - n = i++; - else n = b++; +static void sdefl_build_tree(unsigned *A, unsigned sym_cnt) { + unsigned i = 0, b = 0, e = 0; + do { + unsigned m, n, freq_shift; + if (i != sym_cnt && (b == e || (A[i] >> SDEFL_SYM_BITS) <= (A[b] >> SDEFL_SYM_BITS))) + m = i++; + else + m = b++; + if (i != sym_cnt && (b == e || (A[i] >> SDEFL_SYM_BITS) <= (A[b] >> SDEFL_SYM_BITS))) + n = i++; + else + n = b++; - freq_shift = (A[m] & ~SDEFL_SYM_MSK) + (A[n] & ~SDEFL_SYM_MSK); - A[m] = (A[m] & SDEFL_SYM_MSK) | (e << SDEFL_SYM_BITS); - A[n] = (A[n] & SDEFL_SYM_MSK) | (e << SDEFL_SYM_BITS); - A[e] = (A[e] & SDEFL_SYM_MSK) | freq_shift; - } while (sym_cnt - ++e > 1); + freq_shift = (A[m] & ~SDEFL_SYM_MSK) + (A[n] & ~SDEFL_SYM_MSK); + A[m] = (A[m] & SDEFL_SYM_MSK) | (e << SDEFL_SYM_BITS); + A[n] = (A[n] & SDEFL_SYM_MSK) | (e << SDEFL_SYM_BITS); + A[e] = (A[e] & SDEFL_SYM_MSK) | freq_shift; + } while (sym_cnt - ++e > 1); } -static void -sdefl_gen_len_cnt(unsigned *A, unsigned root, unsigned *len_cnt, - unsigned max_code_len) { - int n; - unsigned i; - for (i = 0; i <= max_code_len; i++) - len_cnt[i] = 0; - len_cnt[1] = 2; +static void sdefl_gen_len_cnt(unsigned *A, unsigned root, unsigned *len_cnt, unsigned max_code_len) { + int n; + unsigned i; + for (i = 0; i <= max_code_len; i++) + len_cnt[i] = 0; + len_cnt[1] = 2; - A[root] &= SDEFL_SYM_MSK; - for (n = (int)root - 1; n >= 0; n--) { - unsigned p = A[n] >> SDEFL_SYM_BITS; - unsigned pdepth = A[p] >> SDEFL_SYM_BITS; - unsigned depth = pdepth + 1; - unsigned len = depth; + A[root] &= SDEFL_SYM_MSK; + for (n = (int)root - 1; n >= 0; n--) { + unsigned p = A[n] >> SDEFL_SYM_BITS; + unsigned pdepth = A[p] >> SDEFL_SYM_BITS; + unsigned depth = pdepth + 1; + unsigned len = depth; - A[n] = (A[n] & SDEFL_SYM_MSK) | (depth << SDEFL_SYM_BITS); - if (len >= max_code_len) { - len = max_code_len; - do len--; while (!len_cnt[len]); - } - len_cnt[len]--; - len_cnt[len+1] += 2; - } + A[n] = (A[n] & SDEFL_SYM_MSK) | (depth << SDEFL_SYM_BITS); + if (len >= max_code_len) { + len = max_code_len; + do + len--; + while (!len_cnt[len]); + } + len_cnt[len]--; + len_cnt[len + 1] += 2; + } } -static void -sdefl_gen_codes(unsigned *A, unsigned char *lens, const unsigned *len_cnt, - unsigned max_code_word_len, unsigned sym_cnt) { - unsigned i, sym, len, nxt[SDEFL_MAX_CODE_LEN + 1]; - for (i = 0, len = max_code_word_len; len >= 1; len--) { - unsigned cnt = len_cnt[len]; - while (cnt--) lens[A[i++] & SDEFL_SYM_MSK] = (unsigned char)len; - } - nxt[0] = nxt[1] = 0; - for (len = 2; len <= max_code_word_len; len++) - nxt[len] = (nxt[len-1] + len_cnt[len-1]) << 1; - for (sym = 0; sym < sym_cnt; sym++) - A[sym] = nxt[lens[sym]]++; +static void sdefl_gen_codes(unsigned *A, unsigned char *lens, const unsigned *len_cnt, unsigned max_code_word_len, unsigned sym_cnt) { + unsigned i, sym, len, nxt[SDEFL_MAX_CODE_LEN + 1]; + for (i = 0, len = max_code_word_len; len >= 1; len--) { + unsigned cnt = len_cnt[len]; + while (cnt--) + lens[A[i++] & SDEFL_SYM_MSK] = (unsigned char)len; + } + nxt[0] = nxt[1] = 0; + for (len = 2; len <= max_code_word_len; len++) + nxt[len] = (nxt[len - 1] + len_cnt[len - 1]) << 1; + for (sym = 0; sym < sym_cnt; sym++) + A[sym] = nxt[lens[sym]]++; } -static unsigned -sdefl_rev(unsigned c, unsigned char n) { - c = ((c & 0x5555) << 1) | ((c & 0xAAAA) >> 1); - c = ((c & 0x3333) << 2) | ((c & 0xCCCC) >> 2); - c = ((c & 0x0F0F) << 4) | ((c & 0xF0F0) >> 4); - c = ((c & 0x00FF) << 8) | ((c & 0xFF00) >> 8); - return c >> (16-n); +static unsigned sdefl_rev(unsigned c, unsigned char n) { + c = ((c & 0x5555) << 1) | ((c & 0xAAAA) >> 1); + c = ((c & 0x3333) << 2) | ((c & 0xCCCC) >> 2); + c = ((c & 0x0F0F) << 4) | ((c & 0xF0F0) >> 4); + c = ((c & 0x00FF) << 8) | ((c & 0xFF00) >> 8); + return c >> (16 - n); } -static void -sdefl_huff(unsigned char *lens, unsigned *codes, unsigned *freqs, - unsigned num_syms, unsigned max_code_len) { - unsigned c, *A = codes; - unsigned len_cnt[SDEFL_MAX_CODE_LEN + 1]; - unsigned used_syms = sdefl_sort_sym(num_syms, freqs, lens, A); - if (!used_syms) return; - if (used_syms == 1) { - unsigned s = A[0] & SDEFL_SYM_MSK; - unsigned i = s ? s : 1; - codes[0] = 0, lens[0] = 1; - codes[i] = 1, lens[i] = 1; - return; - } - sdefl_build_tree(A, used_syms); - sdefl_gen_len_cnt(A, used_syms-2, len_cnt, max_code_len); - sdefl_gen_codes(A, lens, len_cnt, max_code_len, num_syms); - for (c = 0; c < num_syms; c++) { - codes[c] = sdefl_rev(codes[c], lens[c]); - } +static void sdefl_huff(unsigned char *lens, unsigned *codes, unsigned *freqs, unsigned num_syms, unsigned max_code_len) { + unsigned c, *A = codes; + unsigned len_cnt[SDEFL_MAX_CODE_LEN + 1]; + unsigned used_syms = sdefl_sort_sym(num_syms, freqs, lens, A); + if (!used_syms) + return; + if (used_syms == 1) { + unsigned s = A[0] & SDEFL_SYM_MSK; + unsigned i = s ? s : 1; + codes[0] = 0, lens[0] = 1; + codes[i] = 1, lens[i] = 1; + return; + } + sdefl_build_tree(A, used_syms); + sdefl_gen_len_cnt(A, used_syms - 2, len_cnt, max_code_len); + sdefl_gen_codes(A, lens, len_cnt, max_code_len, num_syms); + for (c = 0; c < num_syms; c++) { + codes[c] = sdefl_rev(codes[c], lens[c]); + } } struct sdefl_symcnt { - int items; - int lit; - int off; + int items; + int lit; + int off; }; -static void -sdefl_precode(struct sdefl_symcnt *cnt, unsigned *freqs, unsigned *items, - const unsigned char *litlen, const unsigned char *offlen) { - unsigned *at = items; - unsigned run_start = 0; +static void sdefl_precode(struct sdefl_symcnt *cnt, unsigned *freqs, unsigned *items, const unsigned char *litlen, const unsigned char *offlen) { + unsigned *at = items; + unsigned run_start = 0; - unsigned total = 0; - unsigned char lens[SDEFL_SYM_MAX + SDEFL_OFF_MAX]; - for (cnt->lit = SDEFL_SYM_MAX; cnt->lit > 257; cnt->lit--) - if (litlen[cnt->lit - 1]) break; - for (cnt->off = SDEFL_OFF_MAX; cnt->off > 1; cnt->off--) - if (offlen[cnt->off - 1]) break; + unsigned total = 0; + unsigned char lens[SDEFL_SYM_MAX + SDEFL_OFF_MAX]; + for (cnt->lit = SDEFL_SYM_MAX; cnt->lit > 257; cnt->lit--) + if (litlen[cnt->lit - 1]) + break; + for (cnt->off = SDEFL_OFF_MAX; cnt->off > 1; cnt->off--) + if (offlen[cnt->off - 1]) + break; - total = (unsigned)(cnt->lit + cnt->off); - memcpy(lens, litlen, sizeof(unsigned char) * (size_t)cnt->lit); - memcpy(lens + cnt->lit, offlen, sizeof(unsigned char) * (size_t)cnt->off); - do { - unsigned len = lens[run_start]; - unsigned run_end = run_start; - do run_end++; while (run_end != total && len == lens[run_end]); - if (!len) { - while ((run_end - run_start) >= 11) { - unsigned n = (run_end - run_start) - 11; - unsigned xbits = n < 0x7f ? n : 0x7f; - freqs[18]++; - *at++ = 18u | (xbits << 5u); - run_start += 11 + xbits; - } - if ((run_end - run_start) >= 3) { - unsigned n = (run_end - run_start) - 3; - unsigned xbits = n < 0x7 ? n : 0x7; - freqs[17]++; - *at++ = 17u | (xbits << 5u); - run_start += 3 + xbits; - } - } else if ((run_end - run_start) >= 4) { - freqs[len]++; - *at++ = len; - run_start++; - do { - unsigned xbits = (run_end - run_start) - 3; - xbits = xbits < 0x03 ? xbits : 0x03; - *at++ = 16 | (xbits << 5); - run_start += 3 + xbits; - freqs[16]++; - } while ((run_end - run_start) >= 3); - } - while (run_start != run_end) { - freqs[len]++; - *at++ = len; - run_start++; - } - } while (run_start != total); - cnt->items = (int)(at - items); + total = (unsigned)(cnt->lit + cnt->off); + memcpy(lens, litlen, sizeof(unsigned char) * (size_t)cnt->lit); + memcpy(lens + cnt->lit, offlen, sizeof(unsigned char) * (size_t)cnt->off); + do { + unsigned len = lens[run_start]; + unsigned run_end = run_start; + do + run_end++; + while (run_end != total && len == lens[run_end]); + if (!len) { + while ((run_end - run_start) >= 11) { + unsigned n = (run_end - run_start) - 11; + unsigned xbits = n < 0x7f ? n : 0x7f; + freqs[18]++; + *at++ = 18u | (xbits << 5u); + run_start += 11 + xbits; + } + if ((run_end - run_start) >= 3) { + unsigned n = (run_end - run_start) - 3; + unsigned xbits = n < 0x7 ? n : 0x7; + freqs[17]++; + *at++ = 17u | (xbits << 5u); + run_start += 3 + xbits; + } + } + else if ((run_end - run_start) >= 4) { + freqs[len]++; + *at++ = len; + run_start++; + do { + unsigned xbits = (run_end - run_start) - 3; + xbits = xbits < 0x03 ? xbits : 0x03; + *at++ = 16 | (xbits << 5); + run_start += 3 + xbits; + freqs[16]++; + } while ((run_end - run_start) >= 3); + } + while (run_start != run_end) { + freqs[len]++; + *at++ = len; + run_start++; + } + } while (run_start != total); + cnt->items = (int)(at - items); } struct sdefl_match_codest { - int ls, lc; - int dc, dx; + int ls, lc; + int dc, dx; }; -static void -sdefl_match_codes(struct sdefl_match_codest *cod, int dist, int len) { - static const short dxmax[] = {0,6,12,24,48,96,192,384,768,1536,3072,6144,12288,24576}; - static const unsigned char lslot[258+1] = { - 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, - 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, - 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, - 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, - 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, - 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, - 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, - 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, - 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, - 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, - 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, - 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, - 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, - 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, - 27, 27, 28 - }; - assert(len <= 258); - assert(dist <= 32768); - cod->ls = lslot[len]; - cod->lc = 257 + cod->ls; - assert(cod->lc <= 285); +static void sdefl_match_codes(struct sdefl_match_codest *cod, int dist, int len) { + static const short dxmax[] = {0, 6, 12, 24, 48, 96, 192, 384, 768, 1536, 3072, 6144, 12288, 24576}; + static const unsigned char lslot[258 + 1] = {0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, + 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, + 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, + 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, + 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, + 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, + 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, + 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, + 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28}; + assert(len <= 258); + assert(dist <= 32768); + cod->ls = lslot[len]; + cod->lc = 257 + cod->ls; + assert(cod->lc <= 285); - cod->dx = sdefl_ilog2(sdefl_npow2(dist) >> 2); - cod->dc = cod->dx ? ((cod->dx + 1) << 1) + (dist > dxmax[cod->dx]) : dist-1; + cod->dx = sdefl_ilog2(sdefl_npow2(dist) >> 2); + cod->dc = cod->dx ? ((cod->dx + 1) << 1) + (dist > dxmax[cod->dx]) : dist - 1; } enum sdefl_blk_type { - SDEFL_BLK_UCOMPR, - SDEFL_BLK_DYN + SDEFL_BLK_UCOMPR, + SDEFL_BLK_DYN }; -static enum sdefl_blk_type -sdefl_blk_type(const struct sdefl *s, int blk_len, int pre_item_len, - const unsigned *pre_freq, const unsigned char *pre_len) { - static const unsigned char x_pre_bits[] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; - static const unsigned char x_len_bits[] = {0,0,0,0,0,0,0,0, 1,1,1,1,2,2,2,2, - 3,3,3,3,4,4,4,4, 5,5,5,5,0}; - static const unsigned char x_off_bits[] = {0,0,0,0,1,1,2,2, 3,3,4,4,5,5,6,6, - 7,7,8,8,9,9,10,10, 11,11,12,12,13,13}; +static enum sdefl_blk_type sdefl_blk_type(const struct sdefl *s, int blk_len, int pre_item_len, const unsigned *pre_freq, const unsigned char *pre_len) { + static const unsigned char x_pre_bits[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7}; + static const unsigned char x_len_bits[] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; + static const unsigned char x_off_bits[] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; - int dyn_cost = 0; - int fix_cost = 0; - int sym = 0; + int dyn_cost = 0; + int fix_cost = 0; + int sym = 0; - dyn_cost += 5 + 5 + 4 + (3 * pre_item_len); - for (sym = 0; sym < SDEFL_PRE_MAX; sym++) - dyn_cost += pre_freq[sym] * (x_pre_bits[sym] + pre_len[sym]); - for (sym = 0; sym < 256; sym++) - dyn_cost += s->freq.lit[sym] * s->cod.len.lit[sym]; - dyn_cost += s->cod.len.lit[SDEFL_EOB]; - for (sym = 257; sym < 286; sym++) - dyn_cost += s->freq.lit[sym] * (x_len_bits[sym - 257] + s->cod.len.lit[sym]); - for (sym = 0; sym < 30; sym++) - dyn_cost += s->freq.off[sym] * (x_off_bits[sym] + s->cod.len.off[sym]); + dyn_cost += 5 + 5 + 4 + (3 * pre_item_len); + for (sym = 0; sym < SDEFL_PRE_MAX; sym++) + dyn_cost += pre_freq[sym] * (x_pre_bits[sym] + pre_len[sym]); + for (sym = 0; sym < 256; sym++) + dyn_cost += s->freq.lit[sym] * s->cod.len.lit[sym]; + dyn_cost += s->cod.len.lit[SDEFL_EOB]; + for (sym = 257; sym < 286; sym++) + dyn_cost += s->freq.lit[sym] * (x_len_bits[sym - 257] + s->cod.len.lit[sym]); + for (sym = 0; sym < 30; sym++) + dyn_cost += s->freq.off[sym] * (x_off_bits[sym] + s->cod.len.off[sym]); - fix_cost += 8*(5 * sdefl_div_round_up(blk_len, SDEFL_RAW_BLK_SIZE) + blk_len + 1 + 2); - return (dyn_cost < fix_cost) ? SDEFL_BLK_DYN : SDEFL_BLK_UCOMPR; + fix_cost += 8 * (5 * sdefl_div_round_up(blk_len, SDEFL_RAW_BLK_SIZE) + blk_len + 1 + 2); + return (dyn_cost < fix_cost) ? SDEFL_BLK_DYN : SDEFL_BLK_UCOMPR; } -static void -sdefl_put16(unsigned char **dst, unsigned short x) { - unsigned char *val = *dst; - val[0] = (unsigned char)(x & 0xff); - val[1] = (unsigned char)(x >> 8); - *dst = val + 2; +static void sdefl_put16(unsigned char **dst, unsigned short x) { + unsigned char *val = *dst; + val[0] = (unsigned char)(x & 0xff); + val[1] = (unsigned char)(x >> 8); + *dst = val + 2; } -static void -sdefl_match(unsigned char **dst, struct sdefl *s, int dist, int len) { - static const char lxn[] = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; - static const short lmin[] = {3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43, - 51,59,67,83,99,115,131,163,195,227,258}; - static const short dmin[] = {1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257, - 385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577}; +static void sdefl_match(unsigned char **dst, struct sdefl *s, int dist, int len) { + static const char lxn[] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; + static const short lmin[] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; + static const short dmin[] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, + 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; - struct sdefl_match_codest cod; - sdefl_match_codes(&cod, dist, len); - sdefl_put(dst, s, (int)s->cod.word.lit[cod.lc], s->cod.len.lit[cod.lc]); - sdefl_put(dst, s, len - lmin[cod.ls], lxn[cod.ls]); - sdefl_put(dst, s, (int)s->cod.word.off[cod.dc], s->cod.len.off[cod.dc]); - sdefl_put(dst, s, dist - dmin[cod.dc], cod.dx); + struct sdefl_match_codest cod; + sdefl_match_codes(&cod, dist, len); + sdefl_put(dst, s, (int)s->cod.word.lit[cod.lc], s->cod.len.lit[cod.lc]); + sdefl_put(dst, s, len - lmin[cod.ls], lxn[cod.ls]); + sdefl_put(dst, s, (int)s->cod.word.off[cod.dc], s->cod.len.off[cod.dc]); + sdefl_put(dst, s, dist - dmin[cod.dc], cod.dx); } -static void -sdefl_flush(unsigned char **dst, struct sdefl *s, int is_last, - const unsigned char *in, int blk_begin, int blk_end) { - int blk_len = blk_end - blk_begin; - int j, i = 0, item_cnt = 0; - struct sdefl_symcnt symcnt = {0}; - unsigned codes[SDEFL_PRE_MAX]; - unsigned char lens[SDEFL_PRE_MAX]; - unsigned freqs[SDEFL_PRE_MAX] = {0}; - unsigned items[SDEFL_SYM_MAX + SDEFL_OFF_MAX]; - static const unsigned char perm[SDEFL_PRE_MAX] = {16,17,18,0,8,7,9,6,10,5,11, - 4,12,3,13,2,14,1,15}; +static void sdefl_flush(unsigned char **dst, struct sdefl *s, int is_last, const unsigned char *in, int blk_begin, int blk_end) { + int blk_len = blk_end - blk_begin; + int j, i = 0, item_cnt = 0; + struct sdefl_symcnt symcnt = {0}; + unsigned codes[SDEFL_PRE_MAX]; + unsigned char lens[SDEFL_PRE_MAX]; + unsigned freqs[SDEFL_PRE_MAX] = {0}; + unsigned items[SDEFL_SYM_MAX + SDEFL_OFF_MAX]; + static const unsigned char perm[SDEFL_PRE_MAX] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - /* calculate huffman codes */ - s->freq.lit[SDEFL_EOB]++; - sdefl_huff(s->cod.len.lit, s->cod.word.lit, s->freq.lit, SDEFL_SYM_MAX, SDEFL_LIT_LEN_CODES); - sdefl_huff(s->cod.len.off, s->cod.word.off, s->freq.off, SDEFL_OFF_MAX, SDEFL_OFF_CODES); - sdefl_precode(&symcnt, freqs, items, s->cod.len.lit, s->cod.len.off); - sdefl_huff(lens, codes, freqs, SDEFL_PRE_MAX, SDEFL_PRE_CODES); - for (item_cnt = SDEFL_PRE_MAX; item_cnt > 4; item_cnt--) { - if (lens[perm[item_cnt - 1]]){ - break; - } - } - /* write block */ - switch (sdefl_blk_type(s, blk_len, item_cnt, freqs, lens)) { - case SDEFL_BLK_UCOMPR: { - /* uncompressed blocks */ - int n = sdefl_div_round_up(blk_len, SDEFL_RAW_BLK_SIZE); - for (i = 0; i < n; ++i) { - int fin = is_last && (i + 1 == n); - int amount = blk_len < SDEFL_RAW_BLK_SIZE ? blk_len : SDEFL_RAW_BLK_SIZE; - sdefl_put(dst, s, !!fin, 1); /* block */ - sdefl_put(dst, s, 0x00, 2); /* stored block */ - if (s->bitcnt) { - sdefl_put(dst, s, 0x00, 8 - s->bitcnt); - } - assert(s->bitcnt == 0); - sdefl_put16(dst, (unsigned short)amount); - sdefl_put16(dst, ~(unsigned short)amount); - memcpy(*dst, in + blk_begin + i * SDEFL_RAW_BLK_SIZE, amount); - *dst = *dst + amount; - blk_len -= amount; - } - } break; - case SDEFL_BLK_DYN: { - /* dynamic huffman block */ - sdefl_put(dst, s, !!is_last, 1); /* block */ - sdefl_put(dst, s, 0x02, 2); /* dynamic huffman */ - sdefl_put(dst, s, symcnt.lit - 257, 5); - sdefl_put(dst, s, symcnt.off - 1, 5); - sdefl_put(dst, s, item_cnt - 4, 4); - for (i = 0; i < item_cnt; ++i) { - sdefl_put(dst, s, lens[perm[i]], 3); - } - for (i = 0; i < symcnt.items; ++i) { - unsigned sym = items[i] & 0x1F; - sdefl_put(dst, s, (int)codes[sym], lens[sym]); - if (sym < 16) continue; - if (sym == 16) sdefl_put(dst, s, items[i] >> 5, 2); - else if(sym == 17) sdefl_put(dst, s, items[i] >> 5, 3); - else sdefl_put(dst, s, items[i] >> 5, 7); - } - /* block sequences */ - for (i = 0; i < s->seq_cnt; ++i) { - if (s->seq[i].off >= 0) { - for (j = 0; j < s->seq[i].len; ++j) { - int c = in[s->seq[i].off + j]; - sdefl_put(dst, s, (int)s->cod.word.lit[c], s->cod.len.lit[c]); - } - } else { - sdefl_match(dst, s, -s->seq[i].off, s->seq[i].len); - } - } - sdefl_put(dst, s, (int)(s)->cod.word.lit[SDEFL_EOB], (s)->cod.len.lit[SDEFL_EOB]); - } break;} - memset(&s->freq, 0, sizeof(s->freq)); - s->seq_cnt = 0; + /* calculate huffman codes */ + s->freq.lit[SDEFL_EOB]++; + sdefl_huff(s->cod.len.lit, s->cod.word.lit, s->freq.lit, SDEFL_SYM_MAX, SDEFL_LIT_LEN_CODES); + sdefl_huff(s->cod.len.off, s->cod.word.off, s->freq.off, SDEFL_OFF_MAX, SDEFL_OFF_CODES); + sdefl_precode(&symcnt, freqs, items, s->cod.len.lit, s->cod.len.off); + sdefl_huff(lens, codes, freqs, SDEFL_PRE_MAX, SDEFL_PRE_CODES); + for (item_cnt = SDEFL_PRE_MAX; item_cnt > 4; item_cnt--) { + if (lens[perm[item_cnt - 1]]) { + break; + } + } + /* write block */ + switch (sdefl_blk_type(s, blk_len, item_cnt, freqs, lens)) { + case SDEFL_BLK_UCOMPR: { + /* uncompressed blocks */ + int n = sdefl_div_round_up(blk_len, SDEFL_RAW_BLK_SIZE); + for (i = 0; i < n; ++i) { + int fin = is_last && (i + 1 == n); + int amount = blk_len < SDEFL_RAW_BLK_SIZE ? blk_len : SDEFL_RAW_BLK_SIZE; + sdefl_put(dst, s, !!fin, 1); /* block */ + sdefl_put(dst, s, 0x00, 2); /* stored block */ + if (s->bitcnt) { + sdefl_put(dst, s, 0x00, 8 - s->bitcnt); + } + assert(s->bitcnt == 0); + sdefl_put16(dst, (unsigned short)amount); + sdefl_put16(dst, ~(unsigned short)amount); + memcpy(*dst, in + blk_begin + i * SDEFL_RAW_BLK_SIZE, amount); + *dst = *dst + amount; + blk_len -= amount; + } + } break; + case SDEFL_BLK_DYN: { + /* dynamic huffman block */ + sdefl_put(dst, s, !!is_last, 1); /* block */ + sdefl_put(dst, s, 0x02, 2); /* dynamic huffman */ + sdefl_put(dst, s, symcnt.lit - 257, 5); + sdefl_put(dst, s, symcnt.off - 1, 5); + sdefl_put(dst, s, item_cnt - 4, 4); + for (i = 0; i < item_cnt; ++i) { + sdefl_put(dst, s, lens[perm[i]], 3); + } + for (i = 0; i < symcnt.items; ++i) { + unsigned sym = items[i] & 0x1F; + sdefl_put(dst, s, (int)codes[sym], lens[sym]); + if (sym < 16) + continue; + if (sym == 16) + sdefl_put(dst, s, items[i] >> 5, 2); + else if (sym == 17) + sdefl_put(dst, s, items[i] >> 5, 3); + else + sdefl_put(dst, s, items[i] >> 5, 7); + } + /* block sequences */ + for (i = 0; i < s->seq_cnt; ++i) { + if (s->seq[i].off >= 0) { + for (j = 0; j < s->seq[i].len; ++j) { + int c = in[s->seq[i].off + j]; + sdefl_put(dst, s, (int)s->cod.word.lit[c], s->cod.len.lit[c]); + } + } + else { + sdefl_match(dst, s, -s->seq[i].off, s->seq[i].len); + } + } + sdefl_put(dst, s, (int)(s)->cod.word.lit[SDEFL_EOB], (s)->cod.len.lit[SDEFL_EOB]); + } break; + } + memset(&s->freq, 0, sizeof(s->freq)); + s->seq_cnt = 0; } -static void -sdefl_seq(struct sdefl *s, int off, int len) { - assert(s->seq_cnt + 2 < SDEFL_SEQ_SIZ); - s->seq[s->seq_cnt].off = off; - s->seq[s->seq_cnt].len = len; - s->seq_cnt++; +static void sdefl_seq(struct sdefl *s, int off, int len) { + assert(s->seq_cnt + 2 < SDEFL_SEQ_SIZ); + s->seq[s->seq_cnt].off = off; + s->seq[s->seq_cnt].len = len; + s->seq_cnt++; } -static void -sdefl_reg_match(struct sdefl *s, int off, int len) { - struct sdefl_match_codest cod; - sdefl_match_codes(&cod, off, len); +static void sdefl_reg_match(struct sdefl *s, int off, int len) { + struct sdefl_match_codest cod; + sdefl_match_codes(&cod, off, len); - assert(cod.lc < SDEFL_SYM_MAX); - assert(cod.dc < SDEFL_OFF_MAX); + assert(cod.lc < SDEFL_SYM_MAX); + assert(cod.dc < SDEFL_OFF_MAX); - s->freq.lit[cod.lc]++; - s->freq.off[cod.dc]++; + s->freq.lit[cod.lc]++; + s->freq.off[cod.dc]++; } struct sdefl_match { - int off; - int len; + int off; + int len; }; -static void -sdefl_fnd(struct sdefl_match *m, const struct sdefl *s, int chain_len, - int max_match, const unsigned char *in, int p, int e) { - int i = s->tbl[sdefl_hash32(in + p)]; - int limit = ((p - SDEFL_WIN_SIZ) < SDEFL_NIL) ? SDEFL_NIL : (p-SDEFL_WIN_SIZ); +static void sdefl_fnd(struct sdefl_match *m, const struct sdefl *s, int chain_len, int max_match, const unsigned char *in, int p, int e) { + int i = s->tbl[sdefl_hash32(in + p)]; + int limit = ((p - SDEFL_WIN_SIZ) < SDEFL_NIL) ? SDEFL_NIL : (p - SDEFL_WIN_SIZ); - assert(p < e); - assert(p + max_match <= e); - while (i > limit) { - assert(i + m->len < e); - assert(p + m->len < e); - assert(i + SDEFL_MIN_MATCH < e); - assert(p + SDEFL_MIN_MATCH < e); + assert(p < e); + assert(p + max_match <= e); + while (i > limit) { + assert(i + m->len < e); + assert(p + m->len < e); + assert(i + SDEFL_MIN_MATCH < e); + assert(p + SDEFL_MIN_MATCH < e); - if (in[i + m->len] == in[p + m->len] && - (sdefl_uload32(&in[i]) == sdefl_uload32(&in[p]))) { - int n = SDEFL_MIN_MATCH; - while (n < max_match && in[i + n] == in[p + n]) { - assert(i + n < e); - assert(p + n < e); - n++; - } - if (n > m->len) { - m->len = n, m->off = p - i; - if (n == max_match) - break; - } - } - if (!(--chain_len)) break; - i = s->prv[i & SDEFL_WIN_MSK]; - } + if (in[i + m->len] == in[p + m->len] && (sdefl_uload32(&in[i]) == sdefl_uload32(&in[p]))) { + int n = SDEFL_MIN_MATCH; + while (n < max_match && in[i + n] == in[p + n]) { + assert(i + n < e); + assert(p + n < e); + n++; + } + if (n > m->len) { + m->len = n, m->off = p - i; + if (n == max_match) + break; + } + } + if (!(--chain_len)) + break; + i = s->prv[i & SDEFL_WIN_MSK]; + } } -static int -sdefl_compr(struct sdefl *s, unsigned char *out, const unsigned char *in, - int in_len, int lvl) { - unsigned char *q = out; - static const unsigned char pref[] = {8,10,14,24,30,48,65,96,130}; - int max_chain = (lvl < 8) ? (1 << (lvl + 1)): (1 << 13); - int n, i = 0, litlen = 0; - for (n = 0; n < SDEFL_HASH_SIZ; ++n) { - s->tbl[n] = SDEFL_NIL; - } - do {int blk_begin = i; - int blk_end = ((i + SDEFL_BLK_MAX) < in_len) ? (i + SDEFL_BLK_MAX) : in_len; - while (i < blk_end) { - struct sdefl_match m = {0}; - int left = blk_end - i; - int max_match = (left > SDEFL_MAX_MATCH) ? SDEFL_MAX_MATCH : left; - int nice_match = pref[lvl] < max_match ? pref[lvl] : max_match; - int run = 1, inc = 1, run_inc = 0; - if (max_match > SDEFL_MIN_MATCH) { - sdefl_fnd(&m, s, max_chain, max_match, in, i, in_len); - } - if (lvl >= 5 && m.len >= SDEFL_MIN_MATCH && m.len + 1 < nice_match){ - struct sdefl_match m2 = {0}; - sdefl_fnd(&m2, s, max_chain, m.len + 1, in, i + 1, in_len); - m.len = (m2.len > m.len) ? 0 : m.len; - } - if (m.len >= SDEFL_MIN_MATCH) { - if (litlen) { - sdefl_seq(s, i - litlen, litlen); - litlen = 0; - } - sdefl_seq(s, -m.off, m.len); - sdefl_reg_match(s, m.off, m.len); - if (lvl < 2 && m.len >= nice_match) { - inc = m.len; - } else { - run = m.len; - } - } else { - s->freq.lit[in[i]]++; - litlen++; - } - run_inc = run * inc; - if (in_len - (i + run_inc) > SDEFL_MIN_MATCH) { - while (run-- > 0) { - unsigned h = sdefl_hash32(&in[i]); - s->prv[i&SDEFL_WIN_MSK] = s->tbl[h]; - s->tbl[h] = i, i += inc; - assert(i <= blk_end); - } - } else { - i += run_inc; - assert(i <= blk_end); - } - } - if (litlen) { - sdefl_seq(s, i - litlen, litlen); - litlen = 0; - } - sdefl_flush(&q, s, blk_end == in_len, in, blk_begin, blk_end); - } while (i < in_len); - if (s->bitcnt) { - sdefl_put(&q, s, 0x00, 8 - s->bitcnt); - } - assert(s->bitcnt == 0); - return (int)(q - out); +static int sdefl_compr(struct sdefl *s, unsigned char *out, const unsigned char *in, int in_len, int lvl) { + unsigned char *q = out; + static const unsigned char pref[] = {8, 10, 14, 24, 30, 48, 65, 96, 130}; + int max_chain = (lvl < 8) ? (1 << (lvl + 1)) : (1 << 13); + int n, i = 0, litlen = 0; + for (n = 0; n < SDEFL_HASH_SIZ; ++n) { + s->tbl[n] = SDEFL_NIL; + } + do { + int blk_begin = i; + int blk_end = ((i + SDEFL_BLK_MAX) < in_len) ? (i + SDEFL_BLK_MAX) : in_len; + while (i < blk_end) { + struct sdefl_match m = {0}; + int left = blk_end - i; + int max_match = (left > SDEFL_MAX_MATCH) ? SDEFL_MAX_MATCH : left; + int nice_match = pref[lvl] < max_match ? pref[lvl] : max_match; + int run = 1, inc = 1, run_inc = 0; + if (max_match > SDEFL_MIN_MATCH) { + sdefl_fnd(&m, s, max_chain, max_match, in, i, in_len); + } + if (lvl >= 5 && m.len >= SDEFL_MIN_MATCH && m.len + 1 < nice_match) { + struct sdefl_match m2 = {0}; + sdefl_fnd(&m2, s, max_chain, m.len + 1, in, i + 1, in_len); + m.len = (m2.len > m.len) ? 0 : m.len; + } + if (m.len >= SDEFL_MIN_MATCH) { + if (litlen) { + sdefl_seq(s, i - litlen, litlen); + litlen = 0; + } + sdefl_seq(s, -m.off, m.len); + sdefl_reg_match(s, m.off, m.len); + if (lvl < 2 && m.len >= nice_match) { + inc = m.len; + } + else { + run = m.len; + } + } + else { + s->freq.lit[in[i]]++; + litlen++; + } + run_inc = run * inc; + if (in_len - (i + run_inc) > SDEFL_MIN_MATCH) { + while (run-- > 0) { + unsigned h = sdefl_hash32(&in[i]); + s->prv[i & SDEFL_WIN_MSK] = s->tbl[h]; + s->tbl[h] = i, i += inc; + assert(i <= blk_end); + } + } + else { + i += run_inc; + assert(i <= blk_end); + } + } + if (litlen) { + sdefl_seq(s, i - litlen, litlen); + litlen = 0; + } + sdefl_flush(&q, s, blk_end == in_len, in, blk_begin, blk_end); + } while (i < in_len); + if (s->bitcnt) { + sdefl_put(&q, s, 0x00, 8 - s->bitcnt); + } + assert(s->bitcnt == 0); + return (int)(q - out); } -extern int -sdeflate(struct sdefl *s, void *out, const void *in, int n, int lvl) { - s->bits = s->bitcnt = 0; - return sdefl_compr(s, (unsigned char*)out, (const unsigned char*)in, n, lvl); +extern int sdeflate(struct sdefl *s, void *out, const void *in, int n, int lvl) { + s->bits = s->bitcnt = 0; + return sdefl_compr(s, (unsigned char *)out, (const unsigned char *)in, n, lvl); } -static unsigned -sdefl_adler32(unsigned adler32, const unsigned char *in, int in_len) { - #define SDEFL_ADLER_INIT (1) - const unsigned ADLER_MOD = 65521; - unsigned s1 = adler32 & 0xffff; - unsigned s2 = adler32 >> 16; - unsigned blk_len, i; +static unsigned sdefl_adler32(unsigned adler32, const unsigned char *in, int in_len) { +#define SDEFL_ADLER_INIT (1) + const unsigned ADLER_MOD = 65521; + unsigned s1 = adler32 & 0xffff; + unsigned s2 = adler32 >> 16; + unsigned blk_len, i; - blk_len = in_len % 5552; - while (in_len) { - for (i = 0; i + 7 < blk_len; i += 8) { - s1 += in[0]; s2 += s1; - s1 += in[1]; s2 += s1; - s1 += in[2]; s2 += s1; - s1 += in[3]; s2 += s1; - s1 += in[4]; s2 += s1; - s1 += in[5]; s2 += s1; - s1 += in[6]; s2 += s1; - s1 += in[7]; s2 += s1; - in += 8; - } - for (; i < blk_len; ++i) { - s1 += *in++, s2 += s1; - } - s1 %= ADLER_MOD; - s2 %= ADLER_MOD; - in_len -= blk_len; - blk_len = 5552; - } - return (unsigned)(s2 << 16) + (unsigned)s1; + blk_len = in_len % 5552; + while (in_len) { + for (i = 0; i + 7 < blk_len; i += 8) { + s1 += in[0]; + s2 += s1; + s1 += in[1]; + s2 += s1; + s1 += in[2]; + s2 += s1; + s1 += in[3]; + s2 += s1; + s1 += in[4]; + s2 += s1; + s1 += in[5]; + s2 += s1; + s1 += in[6]; + s2 += s1; + s1 += in[7]; + s2 += s1; + in += 8; + } + for (; i < blk_len; ++i) { + s1 += *in++, s2 += s1; + } + s1 %= ADLER_MOD; + s2 %= ADLER_MOD; + in_len -= blk_len; + blk_len = 5552; + } + return (unsigned)(s2 << 16) + (unsigned)s1; } -extern int -zsdeflate(struct sdefl *s, void *out, const void *in, int n, int lvl) { - int p = 0; - unsigned a = 0; - unsigned char *q = (unsigned char*)out; +extern int zsdeflate(struct sdefl *s, void *out, const void *in, int n, int lvl) { + int p = 0; + unsigned a = 0; + unsigned char *q = (unsigned char *)out; - s->bits = s->bitcnt = 0; - sdefl_put(&q, s, 0x78, 8); /* deflate, 32k window */ - sdefl_put(&q, s, 0x01, 8); /* fast compression */ - q += sdefl_compr(s, q, (const unsigned char*)in, n, lvl); + s->bits = s->bitcnt = 0; + sdefl_put(&q, s, 0x78, 8); /* deflate, 32k window */ + sdefl_put(&q, s, 0x01, 8); /* fast compression */ + q += sdefl_compr(s, q, (const unsigned char *)in, n, lvl); - /* append adler checksum */ - a = sdefl_adler32(SDEFL_ADLER_INIT, (const unsigned char*)in, n); - for (p = 0; p < 4; ++p) { - sdefl_put(&q, s, (a >> 24) & 0xFF, 8); - a <<= 8; - } - return (int)(q - (unsigned char*)out); + /* append adler checksum */ + a = sdefl_adler32(SDEFL_ADLER_INIT, (const unsigned char *)in, n); + for (p = 0; p < 4; ++p) { + sdefl_put(&q, s, (a >> 24) & 0xFF, 8); + a <<= 8; + } + return (int)(q - (unsigned char *)out); } -extern int -sdefl_bound(int len) { - int max_blocks = 1 + sdefl_div_round_up(len, SDEFL_RAW_BLK_SIZE); - int bound = 5 * max_blocks + len + 1 + 4 + 8 + 3; - return bound; +extern int sdefl_bound(int len) { + int max_blocks = 1 + sdefl_div_round_up(len, SDEFL_RAW_BLK_SIZE); + int bound = 5 * max_blocks + len + 1 + 4 + 8 + 3; + return bound; } #ifdef __cplusplus diff --git a/base/sources/libs/sinfl.h b/base/sources/libs/sinfl.h index d69a95f2..c18d688b 100644 --- a/base/sources/libs/sinfl.h +++ b/base/sources/libs/sinfl.h @@ -121,12 +121,12 @@ extern "C" { #define SINFL_OFF_TBL_SIZE 402 struct sinfl { - const unsigned char *bitptr; - unsigned long long bitbuf; - int bitcnt; + const unsigned char *bitptr; + unsigned long long bitbuf; + int bitcnt; - unsigned lits[SINFL_LIT_TBL_SIZE]; - unsigned dsts[SINFL_OFF_TBL_SIZE]; + unsigned lits[SINFL_LIT_TBL_SIZE]; + unsigned dsts[SINFL_OFF_TBL_SIZE]; }; extern int sinflate(void *out, int cap, const void *in, int size); extern int zsinflate(void *out, int cap, const void *in, int size); @@ -139,481 +139,528 @@ extern int zsinflate(void *out, int cap, const void *in, int size); #ifdef SINFL_IMPLEMENTATION -#include /* memcpy, memset */ #include /* assert */ +#include /* memcpy, memset */ #ifdef __cplusplus extern "C" { #endif #if defined(__GNUC__) || defined(__clang__) -#define sinfl_likely(x) __builtin_expect((x),1) -#define sinfl_unlikely(x) __builtin_expect((x),0) +#define sinfl_likely(x) __builtin_expect((x), 1) +#define sinfl_unlikely(x) __builtin_expect((x), 0) #else -#define sinfl_likely(x) (x) -#define sinfl_unlikely(x) (x) +#define sinfl_likely(x) (x) +#define sinfl_unlikely(x) (x) #endif #ifndef SINFL_NO_SIMD #if defined(__arm__) || defined(__aarch64__) || defined(_M_ARM64) - #include - #define sinfl_char16 uint8x16_t - #define sinfl_char16_ld(p) vld1q_u8((const unsigned char*)(p)) - #define sinfl_char16_str(d, v) vst1q_u8((unsigned char*)(d), v) - #define sinfl_char16_char(c) vdupq_n_u8(c) +#include +#define sinfl_char16 uint8x16_t +#define sinfl_char16_ld(p) vld1q_u8((const unsigned char *)(p)) +#define sinfl_char16_str(d, v) vst1q_u8((unsigned char *)(d), v) +#define sinfl_char16_char(c) vdupq_n_u8(c) #elif defined(__x86_64__) || defined(_WIN32) || defined(_WIN64) - #include - #define sinfl_char16 __m128i - #define sinfl_char16_ld(p) _mm_loadu_si128((const __m128i *)(void*)(p)) - #define sinfl_char16_str(d,v) _mm_storeu_si128((__m128i*)(void*)(d), v) - #define sinfl_char16_char(c) _mm_set1_epi8(c) +#include +#define sinfl_char16 __m128i +#define sinfl_char16_ld(p) _mm_loadu_si128((const __m128i *)(void *)(p)) +#define sinfl_char16_str(d, v) _mm_storeu_si128((__m128i *)(void *)(d), v) +#define sinfl_char16_char(c) _mm_set1_epi8(c) #else - #define SINFL_NO_SIMD +#define SINFL_NO_SIMD #endif #endif -static int -sinfl_bsr(unsigned long n) { +static int sinfl_bsr(unsigned long n) { #ifdef _MSC_VER - unsigned long r = 0; - _BitScanReverse(&r, n); - return (int)(r); + unsigned long r = 0; + _BitScanReverse(&r, n); + return (int)(r); #else // defined(__GNUC__) || defined(__clang__) || defined(__TINYC__) - return 31 - __builtin_clz(n); + return 31 - __builtin_clz(n); #endif } -static unsigned long long -sinfl_read64(const void *p) { - unsigned long long n; - memcpy(&n, p, 8); - return n; +static unsigned long long sinfl_read64(const void *p) { + unsigned long long n; + memcpy(&n, p, 8); + return n; } -static void -sinfl_copy64(unsigned char **dst, unsigned char **src) { - unsigned long long n; - memcpy(&n, *src, 8); - memcpy(*dst, &n, 8); - *dst += 8, *src += 8; +static void sinfl_copy64(unsigned char **dst, unsigned char **src) { + unsigned long long n; + memcpy(&n, *src, 8); + memcpy(*dst, &n, 8); + *dst += 8, *src += 8; } #ifdef SINFL_NO_SIMD -static unsigned char* -sinfl_write64(unsigned char *dst, unsigned long long w) { - memcpy(dst, &w, 8); - return dst + 8; +static unsigned char *sinfl_write64(unsigned char *dst, unsigned long long w) { + memcpy(dst, &w, 8); + return dst + 8; } #endif #ifndef SINFL_NO_SIMD -static unsigned char* -sinfl_write128(unsigned char *dst, sinfl_char16 w) { - sinfl_char16_str(dst, w); - return dst + 8; +static unsigned char *sinfl_write128(unsigned char *dst, sinfl_char16 w) { + sinfl_char16_str(dst, w); + return dst + 8; } -static void -sinfl_copy128(unsigned char **dst, unsigned char **src) { - sinfl_char16 n = sinfl_char16_ld(*src); - sinfl_char16_str(*dst, n); - *dst += 16, *src += 16; +static void sinfl_copy128(unsigned char **dst, unsigned char **src) { + sinfl_char16 n = sinfl_char16_ld(*src); + sinfl_char16_str(*dst, n); + *dst += 16, *src += 16; } #endif -static void -sinfl_refill(struct sinfl *s) { - s->bitbuf |= sinfl_read64(s->bitptr) << s->bitcnt; - s->bitptr += (63 - s->bitcnt) >> 3; - s->bitcnt |= 56; /* bitcount in range [56,63] */ +static void sinfl_refill(struct sinfl *s) { + s->bitbuf |= sinfl_read64(s->bitptr) << s->bitcnt; + s->bitptr += (63 - s->bitcnt) >> 3; + s->bitcnt |= 56; /* bitcount in range [56,63] */ } -static int -sinfl_peek(struct sinfl *s, int cnt) { - assert(cnt >= 0 && cnt <= 56); - assert(cnt <= s->bitcnt); - return s->bitbuf & ((1ull << cnt) - 1); +static int sinfl_peek(struct sinfl *s, int cnt) { + assert(cnt >= 0 && cnt <= 56); + assert(cnt <= s->bitcnt); + return s->bitbuf & ((1ull << cnt) - 1); } -static void -sinfl_eat(struct sinfl *s, int cnt) { - assert(cnt <= s->bitcnt); - s->bitbuf >>= cnt; - s->bitcnt -= cnt; +static void sinfl_eat(struct sinfl *s, int cnt) { + assert(cnt <= s->bitcnt); + s->bitbuf >>= cnt; + s->bitcnt -= cnt; } -static int -sinfl__get(struct sinfl *s, int cnt) { - int res = sinfl_peek(s, cnt); - sinfl_eat(s, cnt); - return res; +static int sinfl__get(struct sinfl *s, int cnt) { + int res = sinfl_peek(s, cnt); + sinfl_eat(s, cnt); + return res; } -static int -sinfl_get(struct sinfl *s, int cnt) { - sinfl_refill(s); - return sinfl__get(s, cnt); +static int sinfl_get(struct sinfl *s, int cnt) { + sinfl_refill(s); + return sinfl__get(s, cnt); } struct sinfl_gen { - int len; - int cnt; - int word; - short* sorted; + int len; + int cnt; + int word; + short *sorted; }; -static int -sinfl_build_tbl(struct sinfl_gen *gen, unsigned *tbl, int tbl_bits, - const int *cnt) { - int tbl_end = 0; - while (!(gen->cnt = cnt[gen->len])) { - ++gen->len; - } - tbl_end = 1 << gen->len; - while (gen->len <= tbl_bits) { - do {unsigned bit = 0; - tbl[gen->word] = (*gen->sorted++ << 16) | gen->len; - if (gen->word == tbl_end - 1) { - for (; gen->len < tbl_bits; gen->len++) { - memcpy(&tbl[tbl_end], tbl, (size_t)tbl_end * sizeof(tbl[0])); - tbl_end <<= 1; - } - return 1; - } - bit = 1 << sinfl_bsr((unsigned)(gen->word ^ (tbl_end - 1))); - gen->word &= bit - 1; - gen->word |= bit; - } while (--gen->cnt); - do { - if (++gen->len <= tbl_bits) { - memcpy(&tbl[tbl_end], tbl, (size_t)tbl_end * sizeof(tbl[0])); - tbl_end <<= 1; - } - } while (!(gen->cnt = cnt[gen->len])); - } - return 0; +static int sinfl_build_tbl(struct sinfl_gen *gen, unsigned *tbl, int tbl_bits, const int *cnt) { + int tbl_end = 0; + while (!(gen->cnt = cnt[gen->len])) { + ++gen->len; + } + tbl_end = 1 << gen->len; + while (gen->len <= tbl_bits) { + do { + unsigned bit = 0; + tbl[gen->word] = (*gen->sorted++ << 16) | gen->len; + if (gen->word == tbl_end - 1) { + for (; gen->len < tbl_bits; gen->len++) { + memcpy(&tbl[tbl_end], tbl, (size_t)tbl_end * sizeof(tbl[0])); + tbl_end <<= 1; + } + return 1; + } + bit = 1 << sinfl_bsr((unsigned)(gen->word ^ (tbl_end - 1))); + gen->word &= bit - 1; + gen->word |= bit; + } while (--gen->cnt); + do { + if (++gen->len <= tbl_bits) { + memcpy(&tbl[tbl_end], tbl, (size_t)tbl_end * sizeof(tbl[0])); + tbl_end <<= 1; + } + } while (!(gen->cnt = cnt[gen->len])); + } + return 0; } -static void -sinfl_build_subtbl(struct sinfl_gen *gen, unsigned *tbl, int tbl_bits, - const int *cnt) { - int sub_bits = 0; - int sub_start = 0; - int sub_prefix = -1; - int tbl_end = 1 << tbl_bits; - while (1) { - unsigned entry; - int bit, stride, i; - /* start new sub-table */ - if ((gen->word & ((1 << tbl_bits)-1)) != sub_prefix) { - int used = 0; - sub_prefix = gen->word & ((1 << tbl_bits)-1); - sub_start = tbl_end; - sub_bits = gen->len - tbl_bits; - used = gen->cnt; - while (used < (1 << sub_bits)) { - sub_bits++; - used = (used << 1) + cnt[tbl_bits + sub_bits]; - } - tbl_end = sub_start + (1 << sub_bits); - tbl[sub_prefix] = (sub_start << 16) | 0x10 | (sub_bits & 0xf); - } - /* fill sub-table */ - entry = (*gen->sorted << 16) | ((gen->len - tbl_bits) & 0xf); - gen->sorted++; - i = sub_start + (gen->word >> tbl_bits); - stride = 1 << (gen->len - tbl_bits); - do { - tbl[i] = entry; - i += stride; - } while (i < tbl_end); - if (gen->word == (1 << gen->len)-1) { - return; - } - bit = 1 << sinfl_bsr(gen->word ^ ((1 << gen->len) - 1)); - gen->word &= bit - 1; - gen->word |= bit; - gen->cnt--; - while (!gen->cnt) { - gen->cnt = cnt[++gen->len]; - } - } +static void sinfl_build_subtbl(struct sinfl_gen *gen, unsigned *tbl, int tbl_bits, const int *cnt) { + int sub_bits = 0; + int sub_start = 0; + int sub_prefix = -1; + int tbl_end = 1 << tbl_bits; + while (1) { + unsigned entry; + int bit, stride, i; + /* start new sub-table */ + if ((gen->word & ((1 << tbl_bits) - 1)) != sub_prefix) { + int used = 0; + sub_prefix = gen->word & ((1 << tbl_bits) - 1); + sub_start = tbl_end; + sub_bits = gen->len - tbl_bits; + used = gen->cnt; + while (used < (1 << sub_bits)) { + sub_bits++; + used = (used << 1) + cnt[tbl_bits + sub_bits]; + } + tbl_end = sub_start + (1 << sub_bits); + tbl[sub_prefix] = (sub_start << 16) | 0x10 | (sub_bits & 0xf); + } + /* fill sub-table */ + entry = (*gen->sorted << 16) | ((gen->len - tbl_bits) & 0xf); + gen->sorted++; + i = sub_start + (gen->word >> tbl_bits); + stride = 1 << (gen->len - tbl_bits); + do { + tbl[i] = entry; + i += stride; + } while (i < tbl_end); + if (gen->word == (1 << gen->len) - 1) { + return; + } + bit = 1 << sinfl_bsr(gen->word ^ ((1 << gen->len) - 1)); + gen->word &= bit - 1; + gen->word |= bit; + gen->cnt--; + while (!gen->cnt) { + gen->cnt = cnt[++gen->len]; + } + } } -static void -sinfl_build(unsigned *tbl, unsigned char *lens, int tbl_bits, int maxlen, - int symcnt) { - int i, used = 0; - short sort[288]; - int cnt[16] = {0}, off[16]= {0}; - struct sinfl_gen gen = {0}; - gen.sorted = sort; - gen.len = 1; +static void sinfl_build(unsigned *tbl, unsigned char *lens, int tbl_bits, int maxlen, int symcnt) { + int i, used = 0; + short sort[288]; + int cnt[16] = {0}, off[16] = {0}; + struct sinfl_gen gen = {0}; + gen.sorted = sort; + gen.len = 1; - for (i = 0; i < symcnt; ++i) - cnt[lens[i]]++; - off[1] = cnt[0]; - for (i = 1; i < maxlen; ++i) { - off[i + 1] = off[i] + cnt[i]; - used = (used << 1) + cnt[i]; - } - used = (used << 1) + cnt[i]; - for (i = 0; i < symcnt; ++i) - gen.sorted[off[lens[i]]++] = (short)i; - gen.sorted += off[0]; + for (i = 0; i < symcnt; ++i) + cnt[lens[i]]++; + off[1] = cnt[0]; + for (i = 1; i < maxlen; ++i) { + off[i + 1] = off[i] + cnt[i]; + used = (used << 1) + cnt[i]; + } + used = (used << 1) + cnt[i]; + for (i = 0; i < symcnt; ++i) + gen.sorted[off[lens[i]]++] = (short)i; + gen.sorted += off[0]; - if (used < (1 << maxlen)){ - for (i = 0; i < 1 << tbl_bits; ++i) - tbl[i] = (0 << 16u) | 1; - return; - } - if (!sinfl_build_tbl(&gen, tbl, tbl_bits, cnt)){ - sinfl_build_subtbl(&gen, tbl, tbl_bits, cnt); - } + if (used < (1 << maxlen)) { + for (i = 0; i < 1 << tbl_bits; ++i) + tbl[i] = (0 << 16u) | 1; + return; + } + if (!sinfl_build_tbl(&gen, tbl, tbl_bits, cnt)) { + sinfl_build_subtbl(&gen, tbl, tbl_bits, cnt); + } } -static int -sinfl_decode(struct sinfl *s, const unsigned *tbl, int bit_len) { - int idx = sinfl_peek(s, bit_len); - unsigned key = tbl[idx]; - if (key & 0x10) { - /* sub-table lookup */ - int len = key & 0x0f; - sinfl_eat(s, bit_len); - idx = sinfl_peek(s, len); - key = tbl[((key >> 16) & 0xffff) + (unsigned)idx]; - } - sinfl_eat(s, key & 0x0f); - return (key >> 16) & 0x0fff; +static int sinfl_decode(struct sinfl *s, const unsigned *tbl, int bit_len) { + int idx = sinfl_peek(s, bit_len); + unsigned key = tbl[idx]; + if (key & 0x10) { + /* sub-table lookup */ + int len = key & 0x0f; + sinfl_eat(s, bit_len); + idx = sinfl_peek(s, len); + key = tbl[((key >> 16) & 0xffff) + (unsigned)idx]; + } + sinfl_eat(s, key & 0x0f); + return (key >> 16) & 0x0fff; } -static int -sinfl_decompress(unsigned char *out, int cap, const unsigned char *in, int size) { - static const unsigned char order[] = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; - static const short dbase[30+2] = {1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, - 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577}; - static const unsigned char dbits[30+2] = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9, - 10,10,11,11,12,12,13,13,0,0}; - static const short lbase[29+2] = {3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35, - 43,51,59,67,83,99,115,131,163,195,227,258,0,0}; - static const unsigned char lbits[29+2] = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4, - 4,4,4,5,5,5,5,0,0,0}; +static int sinfl_decompress(unsigned char *out, int cap, const unsigned char *in, int size) { + static const unsigned char order[] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + static const short dbase[30 + 2] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, + 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; + static const unsigned char dbits[30 + 2] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 0, 0}; + static const short lbase[29 + 2] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; + static const unsigned char lbits[29 + 2] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0}; - const unsigned char *oe = out + cap; - const unsigned char *e = in + size, *o = out; - enum sinfl_states {hdr,stored,fixed,dyn,blk}; - enum sinfl_states state = hdr; - struct sinfl s = {0}; - int last = 0; + const unsigned char *oe = out + cap; + const unsigned char *e = in + size, *o = out; + enum sinfl_states { + hdr, + stored, + fixed, + dyn, + blk + }; + enum sinfl_states state = hdr; + struct sinfl s = {0}; + int last = 0; - s.bitptr = in; - while (1) { - switch (state) { - case hdr: { - /* block header */ - int type = 0; - sinfl_refill(&s); - last = sinfl__get(&s,1); - type = sinfl__get(&s,2); + s.bitptr = in; + while (1) { + switch (state) { + case hdr: { + /* block header */ + int type = 0; + sinfl_refill(&s); + last = sinfl__get(&s, 1); + type = sinfl__get(&s, 2); - switch (type) {default: return (int)(out-o); - case 0x00: state = stored; break; - case 0x01: state = fixed; break; - case 0x02: state = dyn; break;} - } break; - case stored: { - /* uncompressed block */ - unsigned len, nlen; - sinfl__get(&s,s.bitcnt & 7); - len = (unsigned short)sinfl__get(&s,16); - nlen = (unsigned short)sinfl__get(&s,16); - s.bitptr -= s.bitcnt / 8; - s.bitbuf = s.bitcnt = 0; + switch (type) { + default: + return (int)(out - o); + case 0x00: + state = stored; + break; + case 0x01: + state = fixed; + break; + case 0x02: + state = dyn; + break; + } + } break; + case stored: { + /* uncompressed block */ + unsigned len, nlen; + sinfl__get(&s, s.bitcnt & 7); + len = (unsigned short)sinfl__get(&s, 16); + nlen = (unsigned short)sinfl__get(&s, 16); + s.bitptr -= s.bitcnt / 8; + s.bitbuf = s.bitcnt = 0; - if ((unsigned short)len != (unsigned short)~nlen) - return (int)(out-o); - if (len > (e - s.bitptr)) - return (int)(out-o); + if ((unsigned short)len != (unsigned short)~nlen) + return (int)(out - o); + if (len > (e - s.bitptr)) + return (int)(out - o); - if (sinfl_unlikely(out + len > oe)) return -2; - memcpy(out, s.bitptr, (size_t)len); - s.bitptr += len, out += len; - if (last) return (int)(out-o); - state = hdr; - } break; - case fixed: { - /* fixed huffman codes */ - int n; unsigned char lens[288+32]; - for (n = 0; n <= 143; n++) lens[n] = 8; - for (n = 144; n <= 255; n++) lens[n] = 9; - for (n = 256; n <= 279; n++) lens[n] = 7; - for (n = 280; n <= 287; n++) lens[n] = 8; - for (n = 0; n < 32; n++) lens[288+n] = 5; + if (sinfl_unlikely(out + len > oe)) + return -2; + memcpy(out, s.bitptr, (size_t)len); + s.bitptr += len, out += len; + if (last) + return (int)(out - o); + state = hdr; + } break; + case fixed: { + /* fixed huffman codes */ + int n; + unsigned char lens[288 + 32]; + for (n = 0; n <= 143; n++) + lens[n] = 8; + for (n = 144; n <= 255; n++) + lens[n] = 9; + for (n = 256; n <= 279; n++) + lens[n] = 7; + for (n = 280; n <= 287; n++) + lens[n] = 8; + for (n = 0; n < 32; n++) + lens[288 + n] = 5; - /* build lit/dist tables */ - sinfl_build(s.lits, lens, 10, 15, 288); - sinfl_build(s.dsts, lens + 288, 8, 15, 32); - state = blk; - } break; - case dyn: { - /* dynamic huffman codes */ - int n, i; - unsigned hlens[SINFL_PRE_TBL_SIZE]; - unsigned char nlens[19] = {0}, lens[288+32]; + /* build lit/dist tables */ + sinfl_build(s.lits, lens, 10, 15, 288); + sinfl_build(s.dsts, lens + 288, 8, 15, 32); + state = blk; + } break; + case dyn: { + /* dynamic huffman codes */ + int n, i; + unsigned hlens[SINFL_PRE_TBL_SIZE]; + unsigned char nlens[19] = {0}, lens[288 + 32]; - sinfl_refill(&s); - {int nlit = 257 + sinfl__get(&s,5); - int ndist = 1 + sinfl__get(&s,5); - int nlen = 4 + sinfl__get(&s,4); - for (n = 0; n < nlen; n++) - nlens[order[n]] = (unsigned char)sinfl_get(&s,3); - sinfl_build(hlens, nlens, 7, 7, 19); + sinfl_refill(&s); + { + int nlit = 257 + sinfl__get(&s, 5); + int ndist = 1 + sinfl__get(&s, 5); + int nlen = 4 + sinfl__get(&s, 4); + for (n = 0; n < nlen; n++) + nlens[order[n]] = (unsigned char)sinfl_get(&s, 3); + sinfl_build(hlens, nlens, 7, 7, 19); - /* decode code lengths */ - for (n = 0; n < nlit + ndist;) { - int sym = 0; - sinfl_refill(&s); - sym = sinfl_decode(&s, hlens, 7); - switch (sym) {default: lens[n++] = (unsigned char)sym; break; - case 16: for (i=3+sinfl_get(&s,2);i;i--,n++) lens[n]=lens[n-1]; break; - case 17: for (i=3+sinfl_get(&s,3);i;i--,n++) lens[n]=0; break; - case 18: for (i=11+sinfl_get(&s,7);i;i--,n++) lens[n]=0; break;} - } - /* build lit/dist tables */ - sinfl_build(s.lits, lens, 10, 15, nlit); - sinfl_build(s.dsts, lens + nlit, 8, 15, ndist); - state = blk;} - } break; - case blk: { - /* decompress block */ - while (1) { - int sym; - sinfl_refill(&s); - sym = sinfl_decode(&s, s.lits, 10); - if (sym < 256) { - /* literal */ - if (sinfl_unlikely(out >= oe)) return -2; - *out++ = (unsigned char)sym; - sym = sinfl_decode(&s, s.lits, 10); - if (sym < 256) { - if (sinfl_unlikely(out >= oe)) return -2; - *out++ = (unsigned char)sym; - continue; - } - } - if (sinfl_unlikely(sym == 256)) { - /* end of block */ - if (last) return (int)(out-o); - state = hdr; - break; - } - /* match */ - if (sym >= 286) { - /* length codes 286 and 287 must not appear in compressed data */ - return (int)(out-o); - } - sym -= 257; - {int len = sinfl__get(&s, lbits[sym]) + lbase[sym]; - int dsym = sinfl_decode(&s, s.dsts, 8); - int offs = sinfl__get(&s, dbits[dsym]) + dbase[dsym]; - unsigned char *dst = out, *src = out - offs; - out = out + len; - if (sinfl_unlikely(out > oe)) return -2; + /* decode code lengths */ + for (n = 0; n < nlit + ndist;) { + int sym = 0; + sinfl_refill(&s); + sym = sinfl_decode(&s, hlens, 7); + switch (sym) { + default: + lens[n++] = (unsigned char)sym; + break; + case 16: + for (i = 3 + sinfl_get(&s, 2); i; i--, n++) + lens[n] = lens[n - 1]; + break; + case 17: + for (i = 3 + sinfl_get(&s, 3); i; i--, n++) + lens[n] = 0; + break; + case 18: + for (i = 11 + sinfl_get(&s, 7); i; i--, n++) + lens[n] = 0; + break; + } + } + /* build lit/dist tables */ + sinfl_build(s.lits, lens, 10, 15, nlit); + sinfl_build(s.dsts, lens + nlit, 8, 15, ndist); + state = blk; + } + } break; + case blk: { + /* decompress block */ + while (1) { + int sym; + sinfl_refill(&s); + sym = sinfl_decode(&s, s.lits, 10); + if (sym < 256) { + /* literal */ + if (sinfl_unlikely(out >= oe)) + return -2; + *out++ = (unsigned char)sym; + sym = sinfl_decode(&s, s.lits, 10); + if (sym < 256) { + if (sinfl_unlikely(out >= oe)) + return -2; + *out++ = (unsigned char)sym; + continue; + } + } + if (sinfl_unlikely(sym == 256)) { + /* end of block */ + if (last) + return (int)(out - o); + state = hdr; + break; + } + /* match */ + if (sym >= 286) { + /* length codes 286 and 287 must not appear in compressed data */ + return (int)(out - o); + } + sym -= 257; + { + int len = sinfl__get(&s, lbits[sym]) + lbase[sym]; + int dsym = sinfl_decode(&s, s.dsts, 8); + int offs = sinfl__get(&s, dbits[dsym]) + dbase[dsym]; + unsigned char *dst = out, *src = out - offs; + out = out + len; + if (sinfl_unlikely(out > oe)) + return -2; #ifndef SINFL_NO_SIMD - if (sinfl_likely(oe - out >= 16 * 3)) { - if (offs >= 16) { - /* simd copy match */ - sinfl_copy128(&dst, &src); - sinfl_copy128(&dst, &src); - do sinfl_copy128(&dst, &src); - while (dst < out); - } else if (offs >= 8) { - /* word copy match */ - sinfl_copy64(&dst, &src); - sinfl_copy64(&dst, &src); - do sinfl_copy64(&dst, &src); - while (dst < out); - } else if (offs == 1) { - /* rle match copying */ - sinfl_char16 w = sinfl_char16_char(src[0]); - dst = sinfl_write128(dst, w); - dst = sinfl_write128(dst, w); - do dst = sinfl_write128(dst, w); - while (dst < out); - } else { - /* byte copy match */ - *dst++ = *src++; - *dst++ = *src++; - do *dst++ = *src++; - while (dst < out); - } - } + if (sinfl_likely(oe - out >= 16 * 3)) { + if (offs >= 16) { + /* simd copy match */ + sinfl_copy128(&dst, &src); + sinfl_copy128(&dst, &src); + do + sinfl_copy128(&dst, &src); + while (dst < out); + } + else if (offs >= 8) { + /* word copy match */ + sinfl_copy64(&dst, &src); + sinfl_copy64(&dst, &src); + do + sinfl_copy64(&dst, &src); + while (dst < out); + } + else if (offs == 1) { + /* rle match copying */ + sinfl_char16 w = sinfl_char16_char(src[0]); + dst = sinfl_write128(dst, w); + dst = sinfl_write128(dst, w); + do + dst = sinfl_write128(dst, w); + while (dst < out); + } + else { + /* byte copy match */ + *dst++ = *src++; + *dst++ = *src++; + do + *dst++ = *src++; + while (dst < out); + } + } #else - if (sinfl_likely(oe - out >= 3 * 8 - 3)) { - if (offs >= 8) { - /* word copy match */ - sinfl_copy64(&dst, &src); - sinfl_copy64(&dst, &src); - do sinfl_copy64(&dst, &src); - while (dst < out); - } else if (offs == 1) { - /* rle match copying */ - unsigned int c = src[0]; - unsigned int hw = (c << 24u) | (c << 16u) | (c << 8u) | (unsigned)c; - unsigned long long w = (unsigned long long)hw << 32llu | hw; - dst = sinfl_write64(dst, w); - dst = sinfl_write64(dst, w); - do dst = sinfl_write64(dst, w); - while (dst < out); - } else { - /* byte copy match */ - *dst++ = *src++; - *dst++ = *src++; - do *dst++ = *src++; - while (dst < out); - } - } + if (sinfl_likely(oe - out >= 3 * 8 - 3)) { + if (offs >= 8) { + /* word copy match */ + sinfl_copy64(&dst, &src); + sinfl_copy64(&dst, &src); + do + sinfl_copy64(&dst, &src); + while (dst < out); + } + else if (offs == 1) { + /* rle match copying */ + unsigned int c = src[0]; + unsigned int hw = (c << 24u) | (c << 16u) | (c << 8u) | (unsigned)c; + unsigned long long w = (unsigned long long)hw << 32llu | hw; + dst = sinfl_write64(dst, w); + dst = sinfl_write64(dst, w); + do + dst = sinfl_write64(dst, w); + while (dst < out); + } + else { + /* byte copy match */ + *dst++ = *src++; + *dst++ = *src++; + do + *dst++ = *src++; + while (dst < out); + } + } #endif - else { - *dst++ = *src++; - *dst++ = *src++; - do *dst++ = *src++; - while (dst < out); - }} - } - } break;} - } - return (int)(out-o); + else { + *dst++ = *src++; + *dst++ = *src++; + do + *dst++ = *src++; + while (dst < out); + } + } + } + } break; + } + } + return (int)(out - o); } -extern int -sinflate(void *out, int cap, const void *in, int size) { - return sinfl_decompress((unsigned char*)out, cap, (const unsigned char*)in, size); +extern int sinflate(void *out, int cap, const void *in, int size) { + return sinfl_decompress((unsigned char *)out, cap, (const unsigned char *)in, size); } -static unsigned -sinfl_adler32(unsigned adler32, const unsigned char *in, int in_len) { - const unsigned ADLER_MOD = 65521; - unsigned s1 = adler32 & 0xffff; - unsigned s2 = adler32 >> 16; - unsigned blk_len, i; +static unsigned sinfl_adler32(unsigned adler32, const unsigned char *in, int in_len) { + const unsigned ADLER_MOD = 65521; + unsigned s1 = adler32 & 0xffff; + unsigned s2 = adler32 >> 16; + unsigned blk_len, i; - blk_len = in_len % 5552; - while (in_len) { - for (i=0; i + 7 < blk_len; i += 8) { - s1 += in[0]; s2 += s1; - s1 += in[1]; s2 += s1; - s1 += in[2]; s2 += s1; - s1 += in[3]; s2 += s1; - s1 += in[4]; s2 += s1; - s1 += in[5]; s2 += s1; - s1 += in[6]; s2 += s1; - s1 += in[7]; s2 += s1; - in += 8; - } - for (; i < blk_len; ++i) - s1 += *in++, s2 += s1; - s1 %= ADLER_MOD; s2 %= ADLER_MOD; - in_len -= blk_len; - blk_len = 5552; - } return (unsigned)(s2 << 16) + (unsigned)s1; + blk_len = in_len % 5552; + while (in_len) { + for (i = 0; i + 7 < blk_len; i += 8) { + s1 += in[0]; + s2 += s1; + s1 += in[1]; + s2 += s1; + s1 += in[2]; + s2 += s1; + s1 += in[3]; + s2 += s1; + s1 += in[4]; + s2 += s1; + s1 += in[5]; + s2 += s1; + s1 += in[6]; + s2 += s1; + s1 += in[7]; + s2 += s1; + in += 8; + } + for (; i < blk_len; ++i) + s1 += *in++, s2 += s1; + s1 %= ADLER_MOD; + s2 %= ADLER_MOD; + in_len -= blk_len; + blk_len = 5552; + } + return (unsigned)(s2 << 16) + (unsigned)s1; } -extern int -zsinflate(void *out, int cap, const void *mem, int size) { - const unsigned char *in = (const unsigned char*)mem; - if (size >= 6) { - const unsigned char *eob = in + size - 4; - int n = sinfl_decompress((unsigned char*)out, cap, in + 2, size - 6); - if (n < 0) return -2; - unsigned a = sinfl_adler32(1u, (unsigned char*)out, n); - unsigned h = eob[0] << 24 | eob[1] << 16 | eob[2] << 8 | eob[3] << 0; - return a == h ? n : -1; - } else { - return -1; - } +extern int zsinflate(void *out, int cap, const void *mem, int size) { + const unsigned char *in = (const unsigned char *)mem; + if (size >= 6) { + const unsigned char *eob = in + size - 4; + int n = sinfl_decompress((unsigned char *)out, cap, in + 2, size - 6); + if (n < 0) + return -2; + unsigned a = sinfl_adler32(1u, (unsigned char *)out, n); + unsigned h = eob[0] << 24 | eob[1] << 16 | eob[2] << 8 | eob[3] << 0; + return a == h ? n : -1; + } + else { + return -1; + } } #ifdef __cplusplus diff --git a/base/sources/miniclib/math.h b/base/sources/miniclib/math.h index 5f4a58ad..8437a6a8 100644 --- a/base/sources/miniclib/math.h +++ b/base/sources/miniclib/math.h @@ -3,9 +3,9 @@ double fabs(double n); float fabsf(float n); double fmax(double x, double y); -float fmaxf(float x, float y); +float fmaxf(float x, float y); double fmin(double x, double y); -float fminf(float x, float y); +float fminf(float x, float y); double ldexp(double x, int exp); double pow(double base, double exponent); float powf(float base, float exponent); diff --git a/base/sources/miniclib/stdlib.c b/base/sources/miniclib/stdlib.c index 594ad70f..65a90d79 100644 --- a/base/sources/miniclib/stdlib.c +++ b/base/sources/miniclib/stdlib.c @@ -1,8 +1,8 @@ #include "stdlib.h" -#include "string.h" +#include "ctype.h" #include "stddef.h" #include "stdio.h" -#include "ctype.h" +#include "string.h" #define ALIGNMENT 8 #define ALIGN(size) (((size) + (ALIGNMENT - 1)) & ~(ALIGNMENT - 1)) @@ -20,8 +20,7 @@ static block_t *free_list = NULL; #ifdef IRON_WASM __attribute__((export_name("wasm_malloc"))) #endif -void * -malloc(size_t size) { +void *malloc(size_t size) { size = ALIGN(size); block_t **link = &free_list; block_t *curr = free_list;