diff --git a/array.h b/array.h new file mode 100644 index 0000000..5b4f591 --- /dev/null +++ b/array.h @@ -0,0 +1,315 @@ +/* +------------------------------------------------------------------------------ + Licensing information can be found at the end of the file. +------------------------------------------------------------------------------ + +array.h - v0.1 - Dynamic array library for C/C++. + +Do this: + #define ARRAY_IMPLEMENTATION +before you include this file in *one* C/C++ file to create the implementation. +*/ + +#ifndef array_h +#define array_h + +#ifndef ARRAY_BOOL_T + #define _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_SECURE_NO_WARNINGS + #include + #define ARRAY_BOOL_T bool +#endif + +#define array_t( type ) struct { int count; type* items; } +#define array_param_t( type ) void +#define array_create( type ) ARRAY_CAST( (void*)internal_array_create( sizeof( type ), NULL ) ) +#define array_create_memctx( type, memctx ) ARRAY_CAST( (void*)internal_array_create( sizeof( type ), (memctx) ) ) +#define array_destroy( array ) internal_array_destroy( (struct internal_array_t*) (array) ) +#define array_add( array, item ) ARRAY_CAST( internal_array_add( (struct internal_array_t*) (array), (void*) (item) ) ) +#define array_remove( array, index ) internal_array_remove( (struct internal_array_t*) (array), (index) ) +#define array_remove_ordered( array, index ) internal_array_remove_ordered( (struct internal_array_t*) (array), (index) ) +#define array_get( array, index, item ) internal_array_get( (struct internal_array_t*) (array), (index), (void*) (item) ) +#define array_set( array, index, item ) internal_array_set( (struct internal_array_t*) (array), (index), (void*) (item) ) +#define array_count( array ) internal_array_count( (struct internal_array_t*) (array) ) +#define array_sort( array, compare ) internal_array_sort( (struct internal_array_t*) (array), (compare) ) +#define array_bsearch( array, key, compare ) internal_array_bsearch( (struct internal_array_t*) (array), (void*) (key), (compare) ) +#define array_find( array, item ) internal_array_find( (struct internal_array_t*) (array), (void*) (item) ) +#define array_item( array, index ) ARRAY_CAST( internal_array_item( (struct internal_array_t*) (array), (index) ) ) + + +// In C, a void* can be implicitly cast to any other kind of pointer, while in C++ you need an explicit cast. In most +// cases, the explicit cast works for both C and C++, but if we consider the case where we have nested structs, then +// the way you refer to them differs between C and C++ (in C++, `parent_type::nested_type`, in C just `nested_type`). +// In addition, with the automatic cast in C, it is possible to use unnamed nested structs and still dynamically +// allocate arrays of that type - this would be desirable when the code is compiled from C++ as well. +// This VOID_CAST macro allows for automatic cast from void* in C++. In C, it does nothing, but for C++ it uses a +// simple template function to define a cast-to-anything operator. +// Use like this: +// struct { +// struct { +// int x; +// } *nested; +// } parent; +// parent.nested = VOID_CAST( malloc( sizeof( *parent.nested ) * count ) ); +// +#ifndef ARRAY_CAST + #ifdef __cplusplus + struct array_cast { + inline array_cast( void* x_ ) : x( x_ ) { } + inline array_cast( void const* x_ ) : x( (void*) x_ ) { } + template< typename T > inline operator T() { return (T)x; } // cast to whatever requested + void* x; + }; + #define ARRAY_CAST( x ) array_cast( x ) + #else + #define ARRAY_CAST( x ) x + #endif +#endif + + +struct internal_array_t; + +struct internal_array_t* internal_array_create( int item_size, void* memctx ); +void internal_array_destroy( struct internal_array_t* array ); +void* internal_array_add( struct internal_array_t* array, void* item ); +void internal_array_remove( struct internal_array_t* array, int index ); +void internal_array_remove_ordered( struct internal_array_t* array, int index ); +ARRAY_BOOL_T internal_array_get( struct internal_array_t* array, int index, void* item ); +ARRAY_BOOL_T internal_array_set( struct internal_array_t* array, int index, void const* item ); +int internal_array_count( struct internal_array_t* array ); +void internal_array_sort( struct internal_array_t* array, int (*compare)( void const*, void const* ) ); +int internal_array_bsearch( struct internal_array_t* array, void* key, int (*compare)( void const*, void const* ) ); +int internal_array_find( struct internal_array_t* array, void* item ); +void* internal_array_item( struct internal_array_t* array, int index ); + +#endif /* array_h */ + + +/* +---------------------- + IMPLEMENTATION +---------------------- +*/ + +#ifdef ARRAY_IMPLEMENTATION +#undef ARRAY_IMPLEMENTATION + + +#ifndef ARRAY_MALLOC + #define _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_SECURE_NO_WARNINGS + #include + #define ARRAY_MALLOC( ctx, size ) ( malloc( size ) ) + #define ARRAY_FREE( ctx, ptr ) ( free( ptr ) ) +#endif + +#ifndef ARRAY_MEMCPY + #define _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_SECURE_NO_WARNINGS + #include + #define ARRAY_MEMCPY( dst, src, cnt ) ( memcpy( (dst), (src), (cnt) ) ) +#endif + +#ifndef ARRAY_MEMMOVE + #define _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_SECURE_NO_WARNINGS + #include + #define ARRAY_MEMMOVE( dst, src, cnt ) ( memcpy( (dst), (src), (cnt) ) ) +#endif + +#ifndef ARRAY_MEMCMP + #define _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_SECURE_NO_WARNINGS + #include + #define ARRAY_MEMCMP( a, b, cnt ) ( memcmp( (a), (b), (cnt) ) ) +#endif + +#ifndef ARRAY_QSORT + #define _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_SECURE_NO_WARNINGS + #include + #define ARRAY_QSORT( base, num, size, cmp ) ( qsort( (base), (num), (size), (cmp) ) ) +#endif + +#ifndef ARRAY_BSEARCH + #define _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_SECURE_NO_WARNINGS + #include + #define ARRAY_BSEARCH( key, base, num, size, cmp ) ( bsearch( (key), (base), (num), (size), (cmp) ) ) +#endif + + +struct internal_array_t { + int count; + void* items; + void* memctx; + int item_size; + int capacity; +}; + + +struct internal_array_t* internal_array_create( int item_size, void* memctx ) { + struct internal_array_t* array = (struct internal_array_t*) ARRAY_MALLOC( memctx, sizeof( struct internal_array_t ) ); + array->memctx = memctx; + array->item_size = item_size; + array->capacity = 256; + array->count = 0; + array->items = ARRAY_MALLOC( memctx, (size_t) array->capacity * item_size ); + return array; +} + + +void internal_array_destroy( struct internal_array_t* array ) { + ARRAY_FREE( array->memctx, array->items ); + ARRAY_FREE( array->memctx, array ); +} + + +void* internal_array_add( struct internal_array_t* array, void* item ) { + if( array->count >= array->capacity ) { + array->capacity *= 2; + void* items = array->items; + array->items = ARRAY_MALLOC( array->memctx, (size_t) array->capacity * array->item_size ); + ARRAY_MEMCPY( array->items, items, (size_t)array->count * array->item_size ); + ARRAY_FREE( array->memctx, items ); + } + ARRAY_MEMCPY( (void*)( ( (uintptr_t) array->items ) + array->count * array->item_size ), item, + (size_t)array->item_size ); + ++array->count; + return (void*)( ( (uintptr_t) array->items ) + ( array->count - 1 ) * array->item_size ); +} + + +void internal_array_remove( struct internal_array_t* array, int index ) { + if( index >= 0 && index < array->count ) { + --array->count; + ARRAY_MEMMOVE( (void*)( ( (uintptr_t) array->items ) + index * array->item_size ), + (void*)( ( (uintptr_t) array->items ) + array->count * array->item_size ), (size_t) array->item_size ); + } +} + +void internal_array_remove_ordered( struct internal_array_t* array, int index ) { + if( index >= 0 && index < array->count ) { + --array->count; + ARRAY_MEMMOVE( (void*)( ( (uintptr_t) array->items ) + index * array->item_size ), + (void*)( ( (uintptr_t) array->items ) + ( index + 1 ) * array->item_size ), + (size_t)array->item_size * ( array->count - index ) ); + } +} + +ARRAY_BOOL_T internal_array_get( struct internal_array_t* array, int index, void* item ) { + ARRAY_BOOL_T result = index >= 0 && index < array->count; + if( result ) { + ARRAY_MEMCPY( item, (void*)( ( (uintptr_t) array->items ) + index * array->item_size ), + (size_t) array->item_size ); + } + return result; +} + +ARRAY_BOOL_T internal_array_set( struct internal_array_t* array, int index, void const* item ) { + ARRAY_BOOL_T result = index >= 0 && index < array->count; + if( result ) { + ARRAY_MEMCPY( (void*)( ( (uintptr_t) array->items ) + index * array->item_size ), item, + (size_t) array->item_size ); + } + return result; +} + +int internal_array_count( struct internal_array_t* array ) { + int count = array->count; + return count; +} + + +void internal_array_sort( struct internal_array_t* array, int (*compare)( void const*, void const* ) ) { + ARRAY_QSORT( array->items, (size_t) array->count, (size_t) array->item_size, compare ); +} + + +int internal_array_bsearch( struct internal_array_t* array, void* key, int (*compare)( void const*, void const* ) ) { + void* item = ARRAY_BSEARCH( key, array->items, (size_t) array->count, (size_t) array->item_size, compare ); + int result = -1; + if( item ) { + result = (int)( ( ((uintptr_t)item) - ((uintptr_t)array->items) ) / array->item_size ); + } + return result; +} + + +int internal_array_find( struct internal_array_t* array, void* item ) { + for( int i = 0; i < array->count; ++i ) { + if( ARRAY_MEMCMP( (void*)( ( (uintptr_t) array->items ) + i * array->item_size ), item, + (size_t) array->item_size) == 0 ) { + + return i; + } + } + return -1; +} + + +void* internal_array_item( struct internal_array_t* array, int index ) { + if( index >= 0 && index < array->count ) { + return (void*)( ( (uintptr_t) array->items ) + index * array->item_size ); + } else { + return NULL; + } +} + +#endif /* ARRAY_IMPLEMENTATION */ + +/* +------------------------------------------------------------------------------ + +This software is available under 2 licenses - you may choose the one you like. + +------------------------------------------------------------------------------ + +ALTERNATIVE A - MIT License + +Copyright (c) 2022 Mattias Gustavsson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------------------------------------------------------------------ + +ALTERNATIVE B - Public Domain (www.unlicense.org) + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +------------------------------------------------------------------------------ +*/ diff --git a/buffer.h b/buffer.h new file mode 100644 index 0000000..90961c3 --- /dev/null +++ b/buffer.h @@ -0,0 +1,437 @@ +/* +------------------------------------------------------------------------------ + Licensing information can be found at the end of the file. +------------------------------------------------------------------------------ + +buffer.h - v0.1 - Memory buffer with read/write operations, for C/C++. + +Do this: + #define BUFFER_IMPLEMENTATION +before you include this file in *one* C/C++ file to create the implementation. +*/ + +#ifndef buffer_h +#define buffer_h + +// If you want buffer to swap endianness on read/write, do this before include: #define BUFFER_BIG_ENDIAN + +#ifndef BUFFER_I8_T + #define BUFFER_I8_T char +#endif + +#ifndef BUFFER_I16_T + #define BUFFER_I16_T short +#endif + +#ifndef BUFFER_I32_T + #define BUFFER_I32_T int +#endif + +#ifndef BUFFER_I64_T + #define BUFFER_I64_T long long +#endif + +#ifndef BUFFER_U8_T + #define BUFFER_U8_T unsigned char +#endif + +#ifndef BUFFER_U16_T + #define BUFFER_U16_T unsigned short +#endif + +#ifndef BUFFER_U32_T + #define BUFFER_U32_T unsigned int +#endif + +#ifndef BUFFER_U64_T + #define BUFFER_U64_T unsigned long long +#endif + + +typedef struct buffer_t buffer_t; + +buffer_t* buffer_create( void ); +buffer_t* buffer_load( const char* filename ); +buffer_t* buffer_map( void* data, size_t size ); +void buffer_destroy( buffer_t* buffer ); +bool buffer_save( buffer_t* buffer, char const* filename ); +void buffer_resize( buffer_t* buffer, size_t size ); +size_t buffer_position( buffer_t* buffer ); +size_t buffer_position_set( buffer_t* buffer, size_t position ); +size_t buffer_size( buffer_t* buffer ); +void* buffer_data( buffer_t* buffer ); + +int buffer_read_char( buffer_t* buffer, char* value, int count ); +int buffer_read_i8( buffer_t* buffer, BUFFER_I8_T* value, int count ); +int buffer_read_i16( buffer_t* buffer, BUFFER_I16_T* value, int count ); +int buffer_read_i32( buffer_t* buffer, BUFFER_I32_T* value, int count ); +int buffer_read_i64( buffer_t* buffer, BUFFER_I64_T* value, int count ); +int buffer_read_u8( buffer_t* buffer, BUFFER_U8_T* value, int count ); +int buffer_read_u16( buffer_t* buffer, BUFFER_U16_T* value, int count ); +int buffer_read_u32( buffer_t* buffer, BUFFER_U32_T* value, int count ); +int buffer_read_u64( buffer_t* buffer, BUFFER_U64_T* value, int count ); +int buffer_read_float( buffer_t* buffer, float* value, int count ); +int buffer_read_double( buffer_t* buffer, double* value, int count ); +int buffer_read_bool( buffer_t* buffer, bool* value, int count ); + +int buffer_write_char( buffer_t* buffer, char const* value, int count ); +int buffer_write_i8( buffer_t* buffer, BUFFER_I8_T const* value, int count ); +int buffer_write_i16( buffer_t* buffer, BUFFER_I16_T const* value, int count ); +int buffer_write_i32( buffer_t* buffer, BUFFER_I32_T const* value, int count ); +int buffer_write_i64( buffer_t* buffer, BUFFER_I64_T const* value, int count ); +int buffer_write_u8( buffer_t* buffer, BUFFER_U8_T const* value, int count ); +int buffer_write_u16( buffer_t* buffer, BUFFER_U16_T const* value, int count ); +int buffer_write_u32( buffer_t* buffer, BUFFER_U32_T const* value, int count ); +int buffer_write_u64( buffer_t* buffer, BUFFER_U64_T const* value, int count ); +int buffer_write_float( buffer_t* buffer, float const* value, int count ); +int buffer_write_double( buffer_t* buffer, double const* value, int count ); +int buffer_write_bool( buffer_t* buffer, bool const* value, int count ); + +#endif /* buffer_h */ + + +#ifdef BUFFER_IMPLEMENTATION +#undef BUFFER_IMPLEMENTATION + +#include +#include +#include + +static BUFFER_U32_T buffer_pow2ceil( BUFFER_U32_T v ) { + --v; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + ++v; + v += ( v == 0 ); + return v; +} + + +struct buffer_t { + size_t capacity; + size_t size; + size_t position; + void* data; + int is_mapped; +}; + + +buffer_t* buffer_create( void ) { + buffer_t* buffer = (buffer_t*) malloc( sizeof( buffer_t) ); + buffer->capacity = 4096; + buffer->size = 0; + buffer->position = 0; + buffer->data = malloc( buffer->capacity ); + buffer->is_mapped = 0; + return buffer; +} + + +buffer_t* buffer_load( const char* filename ) { + FILE* fp = fopen( filename, "rb" ); + if( !fp ) { + return NULL; + } + fseek( fp, 0, SEEK_END ); + int size = (int) ftell( fp ); + fseek( fp, 0, SEEK_SET ); + if( size == 0 ) { + fclose( fp ); + return NULL; + } + + int pow2size = (int)buffer_pow2ceil( (BUFFER_U32_T) size ); + void* data = malloc( pow2size ); + int read = (int) fread( data, 1, size, fp ); + fclose( fp ); + if( read != size ) { + free( data ); + return NULL; + } + + buffer_t* buffer = (buffer_t*) malloc( sizeof( buffer_t) ); + buffer->capacity = pow2size; + buffer->size = size; + buffer->position = 0; + buffer->data = data; + buffer->is_mapped = 0; + return buffer; +} + + +buffer_t* buffer_map( void* data, size_t size ) { + if( !data ) { + return NULL; + } + buffer_t* buffer = (buffer_t*) malloc( sizeof( buffer_t) ); + buffer->capacity = size; + buffer->size = size; + buffer->position = 0; + buffer->data = data; + buffer->is_mapped = 1; + return buffer; +} + + +void buffer_destroy( buffer_t* buffer ) { + if( !buffer->is_mapped ) { + free( buffer->data ); + } + free( buffer ); +} + + +bool buffer_save( buffer_t* buffer, char const* filename ) { + FILE* fp = fopen( filename, "wb" ); + if( !fp ) { + return false; + } + size_t written = fwrite( buffer->data, 1, buffer->size, fp ); + fclose( fp ); + return written == buffer->size; +} + + +void buffer_resize( buffer_t* buffer, size_t size ) { + if( buffer->is_mapped ) { + return; + } + if( size > buffer->capacity ) { + while( size > buffer->capacity ) { + buffer->capacity *= 2; + } + buffer->data = realloc( buffer->data, buffer->capacity ); + } + buffer->size = size; + if( buffer->position > size ) { + buffer->position = size; + } +} + + +size_t buffer_position( buffer_t* buffer ) { + size_t result = buffer->position; + return result; +} + + +size_t buffer_position_set( buffer_t* buffer, size_t position ) { + buffer->position = position > buffer->size ? buffer->size : position; + size_t result = buffer->position; + return result; +} + + +size_t buffer_size( buffer_t* buffer ) { + size_t result = buffer->size; + return result; +} + + +void* buffer_data( buffer_t* buffer ) { + return buffer->data; +} + +#ifndef BUFFER_BIG_ENDIAN + #define BUFFER_READ_IMPL \ + { \ + int result = 0; \ + for( int i = 0; i < count; ++i ) { \ + if( buffer->position + sizeof( *value ) > buffer->size ) { \ + return result; \ + } \ + memcpy( &value[ i ], (void*)( ( (uintptr_t) buffer->data ) + buffer->position ), sizeof( *value ) ); \ + buffer->position += sizeof( *value ); \ + ++result; \ + } \ + return result; \ + } +#else + #define BUFFER_READ_IMPL \ + { \ + int result = 0; \ + for( int i = 0; i < count; ++i ) { \ + if( buffer->position + sizeof( *value ) > buffer->size ) { \ + return result; \ + } \ + void* x = &value[ i ]; \ + memcpy( x, (void*)( ( (uintptr_t) buffer->data ) + buffer->position ), sizeof( *value ) ); \ + if( sizeof(*value) == 2 ) \ + *(BUFFER_U16_T*)(x) = \ + ((((*(BUFFER_U16_T*)(x)) & 0xFF00) >> 8) | \ + (((*(BUFFER_U16_T*)(x)) & 0x00FF) << 8)); \ + else if( sizeof(*value) == 4 ) \ + *(BUFFER_U32_T*)(x) = \ + ((((*(BUFFER_U32_T*)(x)) & 0xFF000000) >> 24) | \ + (((*(BUFFER_U32_T*)(x)) & 0x00FF0000) >> 8) | \ + (((*(BUFFER_U32_T*)(x)) & 0x0000FF00) << 8) | \ + (((*(BUFFER_U32_T*)(x)) & 0x000000FF) << 24) ); \ + else if( sizeof(*value) == 8 ) \ + *(BUFFER_U64_T*)(x) = \ + ((((*(BUFFER_U64_T*)(x)) & 0xFF00000000000000) >> 56 ) | \ + (((*(BUFFER_U64_T*)(x)) & 0x00FF000000000000) >> 40 ) | \ + (((*(BUFFER_U64_T*)(x)) & 0x0000FF0000000000) >> 24 ) | \ + (((*(BUFFER_U64_T*)(x)) & 0x000000FF00000000) >> 8 ) | \ + (((*(BUFFER_U64_T*)(x)) & 0x00000000FF000000) << 8) | \ + (((*(BUFFER_U64_T*)(x)) & 0x0000000000FF0000) << 24) | \ + (((*(BUFFER_U64_T*)(x)) & 0x000000000000FF00) << 40) | \ + (((*(BUFFER_U64_T*)(x)) & 0x00000000000000FF) << 56)); \ + buffer->position += sizeof( *value ); \ + ++result; \ + } \ + return result; \ + } +#endif + +int buffer_read_char( buffer_t* buffer, char* value, int count ) BUFFER_READ_IMPL +int buffer_read_i8( buffer_t* buffer, BUFFER_I8_T* value, int count ) BUFFER_READ_IMPL +int buffer_read_i16( buffer_t* buffer, BUFFER_I16_T* value, int count ) BUFFER_READ_IMPL +int buffer_read_i32( buffer_t* buffer, BUFFER_I32_T* value, int count ) BUFFER_READ_IMPL +int buffer_read_i64( buffer_t* buffer, BUFFER_I64_T* value, int count ) BUFFER_READ_IMPL +int buffer_read_u8( buffer_t* buffer, BUFFER_U8_T* value, int count ) BUFFER_READ_IMPL +int buffer_read_u16( buffer_t* buffer, BUFFER_U16_T* value, int count ) BUFFER_READ_IMPL +int buffer_read_u32( buffer_t* buffer, BUFFER_U32_T* value, int count ) BUFFER_READ_IMPL +int buffer_read_u64( buffer_t* buffer, BUFFER_U64_T* value, int count ) BUFFER_READ_IMPL +int buffer_read_float( buffer_t* buffer, float* value, int count ) BUFFER_READ_IMPL +int buffer_read_double( buffer_t* buffer, double* value, int count ) BUFFER_READ_IMPL +int buffer_read_bool( buffer_t* buffer, bool* value, int count ) BUFFER_READ_IMPL + +#undef BUFFER_READ_IMPL + + +#ifndef BUFFER_BIG_ENDIAN + #define BUFFER_WRITE_IMPL \ + { \ + int result = 0; \ + for( int i = 0; i < count; ++i ) { \ + if( buffer->position + sizeof( *value ) > buffer->size ) { \ + if( buffer->is_mapped ) break; \ + buffer->size = buffer->position + sizeof( *value ); \ + while( buffer->size > buffer->capacity ) { \ + buffer->capacity *= 2; \ + } \ + buffer->data = realloc( buffer->data, buffer->capacity ); \ + } \ + memcpy( (void*)( ( (uintptr_t) buffer->data ) + buffer->position ), &value[ i ], sizeof( *value ) ); \ + buffer->position += sizeof( *value ); \ + ++result; \ + } \ + return result; \ + } +#else + #define BUFFER_WRITE_IMPL \ + { \ + int result = 0; \ + for( int i = 0; i < count; ++i ) { \ + if( buffer->position + sizeof( *value ) > buffer->size ) { \ + if( buffer->is_mapped ) break; \ + buffer->size = buffer->position + sizeof( *value ); \ + while( buffer->size > buffer->capacity ) { \ + buffer->capacity *= 2; \ + } \ + buffer->data = realloc( buffer->data, buffer->capacity ); \ + } \ + void* x = (void*)( ( (uintptr_t) buffer->data ) + buffer->position ); \ + memcpy( x, &value[ i ], sizeof( *value ) ); \ + if( sizeof(*value) == 2 ) \ + *(BUFFER_U16_T*)(x) = \ + ((((*(BUFFER_U16_T*)(x)) & 0xFF00) >> 8) | \ + (((*(BUFFER_U16_T*)(x)) & 0x00FF) << 8)); \ + else if( sizeof(*value) == 4 ) \ + *(BUFFER_U32_T*)(x) = \ + ((((*(BUFFER_U32_T*)(x)) & 0xFF000000) >> 24) | \ + (((*(BUFFER_U32_T*)(x)) & 0x00FF0000) >> 8) | \ + (((*(BUFFER_U32_T*)(x)) & 0x0000FF00) << 8) | \ + (((*(BUFFER_U32_T*)(x)) & 0x000000FF) << 24) ); \ + else if( sizeof(*value) == 8 ) \ + *(BUFFER_U64_T*)(x) = \ + ((((*(BUFFER_U64_T*)(x)) & 0xFF00000000000000) >> 56 ) | \ + (((*(BUFFER_U64_T*)(x)) & 0x00FF000000000000) >> 40 ) | \ + (((*(BUFFER_U64_T*)(x)) & 0x0000FF0000000000) >> 24 ) | \ + (((*(BUFFER_U64_T*)(x)) & 0x000000FF00000000) >> 8 ) | \ + (((*(BUFFER_U64_T*)(x)) & 0x00000000FF000000) << 8) | \ + (((*(BUFFER_U64_T*)(x)) & 0x0000000000FF0000) << 24) | \ + (((*(BUFFER_U64_T*)(x)) & 0x000000000000FF00) << 40) | \ + (((*(BUFFER_U64_T*)(x)) & 0x00000000000000FF) << 56)); \ + buffer->position += sizeof( *value ); \ + ++result; \ + } \ + return result; \ + } +#endif + +int buffer_write_char( buffer_t* buffer, char const* value, int count ) BUFFER_WRITE_IMPL +int buffer_write_i8( buffer_t* buffer, BUFFER_I8_T const* value, int count ) BUFFER_WRITE_IMPL +int buffer_write_i16( buffer_t* buffer, BUFFER_I16_T const* value, int count ) BUFFER_WRITE_IMPL +int buffer_write_i32( buffer_t* buffer, BUFFER_I32_T const* value, int count ) BUFFER_WRITE_IMPL +int buffer_write_i64( buffer_t* buffer, BUFFER_I64_T const* value, int count ) BUFFER_WRITE_IMPL +int buffer_write_u8( buffer_t* buffer, BUFFER_U8_T const* value, int count ) BUFFER_WRITE_IMPL +int buffer_write_u16( buffer_t* buffer, BUFFER_U16_T const* value, int count ) BUFFER_WRITE_IMPL +int buffer_write_u32( buffer_t* buffer, BUFFER_U32_T const* value, int count ) BUFFER_WRITE_IMPL +int buffer_write_u64( buffer_t* buffer, BUFFER_U64_T const* value, int count ) BUFFER_WRITE_IMPL +int buffer_write_float( buffer_t* buffer, float const* value, int count ) BUFFER_WRITE_IMPL +int buffer_write_double( buffer_t* buffer, double const* value, int count ) BUFFER_WRITE_IMPL +int buffer_write_bool( buffer_t* buffer, bool const* value, int count ) BUFFER_WRITE_IMPL + +#undef BUFFER_WRITE_IMPL + +#endif /* BUFFER_IMPLEMENTATION */ + +/* +------------------------------------------------------------------------------ + +This software is available under 2 licenses - you may choose the one you like. + +------------------------------------------------------------------------------ + +ALTERNATIVE A - MIT License + +Copyright (c) 2022 Mattias Gustavsson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------------------------------------------------------------------ + +ALTERNATIVE B - Public Domain (www.unlicense.org) + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +------------------------------------------------------------------------------ +*/ diff --git a/crtemu.h b/crtemu.h new file mode 100644 index 0000000..a0bfbde --- /dev/null +++ b/crtemu.h @@ -0,0 +1,1381 @@ +/* +------------------------------------------------------------------------------ + Licensing information can be found at the end of the file. +------------------------------------------------------------------------------ + +crtemu.h - v0.1 - Cathode ray tube emulation shader for C/C++. + +Do this: + #define CRTEMU_IMPLEMENTATION +before you include this file in *one* C/C++ file to create the implementation. +*/ + + +#ifndef crtemu_h +#define crtemu_h + +#ifndef CRTEMU_U32 + #define CRTEMU_U32 unsigned int +#endif +#ifndef CRTEMU_U64 + #define CRTEMU_U64 unsigned long long +#endif + +typedef struct crtemu_t crtemu_t; + +crtemu_t* crtemu_create( void* memctx ); + +void crtemu_destroy( crtemu_t* crtemu ); + +typedef struct crtemu_config_t + { + float curvature, scanlines, shadow_mask, separation, ghosting, noise, flicker, vignette, distortion, aspect_lock, + hpos, vpos, hsize, vsize, contrast, brightness, saturation, blur, degauss; // range -1.0f to 1.0f, default=0.0f + } crtemu_config_t; + +void crtemu_config(crtemu_t* crtemu, crtemu_config_t const* config); + +void crtemu_frame( crtemu_t* crtemu, CRTEMU_U32* frame_abgr, int frame_width, int frame_height ); + +void crtemu_present( crtemu_t* crtemu, CRTEMU_U64 time_us, CRTEMU_U32 const* pixels_xbgr, int width, int height, + CRTEMU_U32 mod_xbgr, CRTEMU_U32 border_xbgr ); + +void crtemu_coordinates_window_to_bitmap( crtemu_t* crtemu, int width, int height, int* x, int* y ); +void crtemu_coordinates_bitmap_to_window( crtemu_t* crtemu, int width, int height, int* x, int* y ); + +#endif /* crtemu_h */ + +/* +---------------------- + IMPLEMENTATION +---------------------- +*/ +#ifdef CRTEMU_IMPLEMENTATION +#undef CRTEMU_IMPLEMENTATION + +#define _CRT_NONSTDC_NO_DEPRECATE +#define _CRT_SECURE_NO_WARNINGS +#include +#include + +#ifndef CRTEMU_MALLOC + #include + #if defined(__cplusplus) + #define CRTEMU_MALLOC( ctx, size ) ( ::malloc( size ) ) + #define CRTEMU_FREE( ctx, ptr ) ( ::free( ptr ) ) + #else + #define CRTEMU_MALLOC( ctx, size ) ( malloc( size ) ) + #define CRTEMU_FREE( ctx, ptr ) ( free( ptr ) ) + #endif +#endif + +#ifdef CRTEMU_REPORT_SHADER_ERRORS + #ifndef CRTEMU_REPORT_ERROR + #define _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_SECURE_NO_WARNINGS + #include + #define CRTEMU_REPORT_ERROR( str ) printf( "%s", str ) + #endif +#endif + +#ifndef _WIN32 + #define CRTEMU_SDL +#endif + +#ifdef __wasm__ + #define CRTEMU_WEBGL +#endif + +#ifndef CRTEMU_SDL + + #ifdef __cplusplus + extern "C" { + #endif + + __declspec(dllimport) struct HINSTANCE__* __stdcall LoadLibraryA( char const* lpLibFileName ); + __declspec(dllimport) int __stdcall FreeLibrary( struct HINSTANCE__* hModule ); + #if defined(_WIN64) + typedef __int64 (__stdcall* CRTEMU_PROC)( void ); + __declspec(dllimport) CRTEMU_PROC __stdcall GetProcAddress( struct HINSTANCE__* hModule, char const* lpLibFileName ); + #else + typedef __int32 (__stdcall* CRTEMU_PROC)( void ); + __declspec(dllimport) CRTEMU_PROC __stdcall GetProcAddress( struct HINSTANCE__* hModule, char const* lpLibFileName ); + #endif + + #ifdef __cplusplus + } + #endif + + #define CRTEMU_GLCALLTYPE __stdcall + typedef unsigned int CRTEMU_GLuint; + typedef int CRTEMU_GLsizei; + typedef unsigned int CRTEMU_GLenum; + typedef int CRTEMU_GLint; + typedef float CRTEMU_GLfloat; + typedef char CRTEMU_GLchar; + typedef unsigned char CRTEMU_GLboolean; + typedef size_t CRTEMU_GLsizeiptr; + typedef unsigned int CRTEMU_GLbitfield; + + #define CRTEMU_GL_FLOAT 0x1406 + #define CRTEMU_GL_FALSE 0 + #define CRTEMU_GL_FRAGMENT_SHADER 0x8b30 + #define CRTEMU_GL_VERTEX_SHADER 0x8b31 + #define CRTEMU_GL_COMPILE_STATUS 0x8b81 + #define CRTEMU_GL_LINK_STATUS 0x8b82 + #define CRTEMU_GL_INFO_LOG_LENGTH 0x8b84 + #define CRTEMU_GL_ARRAY_BUFFER 0x8892 + #define CRTEMU_GL_TEXTURE_2D 0x0de1 + #define CRTEMU_GL_TEXTURE0 0x84c0 + #define CRTEMU_GL_TEXTURE1 0x84c1 + #define CRTEMU_GL_TEXTURE2 0x84c2 + #define CRTEMU_GL_TEXTURE3 0x84c3 + #define CRTEMU_GL_TEXTURE_MIN_FILTER 0x2801 + #define CRTEMU_GL_TEXTURE_MAG_FILTER 0x2800 + #define CRTEMU_GL_NEAREST 0x2600 + #define CRTEMU_GL_LINEAR 0x2601 + #define CRTEMU_GL_STATIC_DRAW 0x88e4 + #define CRTEMU_GL_RGBA 0x1908 + #define CRTEMU_GL_UNSIGNED_BYTE 0x1401 + #define CRTEMU_GL_COLOR_BUFFER_BIT 0x00004000 + #define CRTEMU_GL_TRIANGLE_FAN 0x0006 + #define CRTEMU_GL_FRAMEBUFFER 0x8d40 + #define CRTEMU_GL_VIEWPORT 0x0ba2 + #define CRTEMU_GL_RGB 0x1907 + #define CRTEMU_GL_COLOR_ATTACHMENT0 0x8ce0 + #define CRTEMU_GL_TEXTURE_WRAP_S 0x2802 + #define CRTEMU_GL_TEXTURE_WRAP_T 0x2803 + #define CRTEMU_GL_CLAMP_TO_BORDER 0x812D + #define CRTEMU_GL_TEXTURE_BORDER_COLOR 0x1004 + +#else + + #ifndef CRTEMU_WEBGL + #include + #include "SDL_opengl.h" + #else + #include + #endif + #define CRTEMU_GLCALLTYPE GLAPIENTRY + + typedef GLuint CRTEMU_GLuint; + typedef GLsizei CRTEMU_GLsizei; + typedef GLenum CRTEMU_GLenum; + typedef GLint CRTEMU_GLint; + typedef GLfloat CRTEMU_GLfloat; + typedef GLchar CRTEMU_GLchar; + typedef GLboolean CRTEMU_GLboolean; + typedef GLsizeiptr CRTEMU_GLsizeiptr; + typedef GLbitfield CRTEMU_GLbitfield; + + #define CRTEMU_GL_FLOAT GL_FLOAT + #define CRTEMU_GL_FALSE GL_FALSE + #define CRTEMU_GL_FRAGMENT_SHADER GL_FRAGMENT_SHADER + #define CRTEMU_GL_VERTEX_SHADER GL_VERTEX_SHADER + #define CRTEMU_GL_COMPILE_STATUS GL_COMPILE_STATUS + #define CRTEMU_GL_LINK_STATUS GL_LINK_STATUS + #define CRTEMU_GL_INFO_LOG_LENGTH GL_INFO_LOG_LENGTH + #define CRTEMU_GL_ARRAY_BUFFER GL_ARRAY_BUFFER + #define CRTEMU_GL_TEXTURE_2D GL_TEXTURE_2D + #define CRTEMU_GL_TEXTURE0 GL_TEXTURE0 + #define CRTEMU_GL_TEXTURE1 GL_TEXTURE1 + #define CRTEMU_GL_TEXTURE2 GL_TEXTURE2 + #define CRTEMU_GL_TEXTURE3 GL_TEXTURE3 + #define CRTEMU_GL_TEXTURE_MIN_FILTER GL_TEXTURE_MIN_FILTER + #define CRTEMU_GL_TEXTURE_MAG_FILTER GL_TEXTURE_MAG_FILTER + #define CRTEMU_GL_NEAREST GL_NEAREST + #define CRTEMU_GL_LINEAR GL_LINEAR + #define CRTEMU_GL_STATIC_DRAW GL_STATIC_DRAW + #define CRTEMU_GL_RGBA GL_RGBA + #define CRTEMU_GL_UNSIGNED_BYTE GL_UNSIGNED_BYTE + #define CRTEMU_GL_COLOR_BUFFER_BIT GL_COLOR_BUFFER_BIT + #define CRTEMU_GL_TRIANGLE_FAN GL_TRIANGLE_FAN + #define CRTEMU_GL_FRAMEBUFFER GL_FRAMEBUFFER + #define CRTEMU_GL_VIEWPORT GL_VIEWPORT + #define CRTEMU_GL_RGB GL_RGB + #define CRTEMU_GL_COLOR_ATTACHMENT0 GL_COLOR_ATTACHMENT0 + #define CRTEMU_GL_TEXTURE_WRAP_S GL_TEXTURE_WRAP_S + #define CRTEMU_GL_TEXTURE_WRAP_T GL_TEXTURE_WRAP_T + #ifndef CRTEMU_WEBGL + #define CRTEMU_GL_CLAMP_TO_BORDER GL_CLAMP_TO_BORDER + #define CRTEMU_GL_TEXTURE_BORDER_COLOR GL_TEXTURE_BORDER_COLOR + #else + // WebGL does not support GL_CLAMP_TO_BORDER, we have to emulate + // this behavior with code in the fragment shader + #define CRTEMU_GL_CLAMP_TO_BORDER GL_CLAMP_TO_EDGE + #endif +#endif + + +struct crtemu_t + { + void* memctx; + crtemu_config_t config; + + CRTEMU_GLuint vertexbuffer; + CRTEMU_GLuint backbuffer; + + CRTEMU_GLuint accumulatetexture_a; + CRTEMU_GLuint accumulatetexture_b; + CRTEMU_GLuint accumulatebuffer_a; + CRTEMU_GLuint accumulatebuffer_b; + + CRTEMU_GLuint blurtexture_a; + CRTEMU_GLuint blurtexture_b; + CRTEMU_GLuint blurbuffer_a; + CRTEMU_GLuint blurbuffer_b; + + CRTEMU_GLuint frametexture; + float use_frame; + + CRTEMU_GLuint crt_shader; + CRTEMU_GLuint blur_shader; + CRTEMU_GLuint accumulate_shader; + CRTEMU_GLuint blend_shader; + CRTEMU_GLuint copy_shader; + + int last_present_width; + int last_present_height; + + + #ifndef CRTEMU_SDL + struct HINSTANCE__* gl_dll; + CRTEMU_PROC (CRTEMU_GLCALLTYPE *wglGetProcAddress) (char const* ); + #endif + + void (CRTEMU_GLCALLTYPE* TexParameterfv) (CRTEMU_GLenum target, CRTEMU_GLenum pname, CRTEMU_GLfloat const* params); + void (CRTEMU_GLCALLTYPE* DeleteFramebuffers) (CRTEMU_GLsizei n, CRTEMU_GLuint const* framebuffers); + void (CRTEMU_GLCALLTYPE* GetIntegerv) (CRTEMU_GLenum pname, CRTEMU_GLint *data); + void (CRTEMU_GLCALLTYPE* GenFramebuffers) (CRTEMU_GLsizei n, CRTEMU_GLuint *framebuffers); + void (CRTEMU_GLCALLTYPE* BindFramebuffer) (CRTEMU_GLenum target, CRTEMU_GLuint framebuffer); + void (CRTEMU_GLCALLTYPE* Uniform1f) (CRTEMU_GLint location, CRTEMU_GLfloat v0); + void (CRTEMU_GLCALLTYPE* Uniform2f) (CRTEMU_GLint location, CRTEMU_GLfloat v0, CRTEMU_GLfloat v1); + void (CRTEMU_GLCALLTYPE* FramebufferTexture2D) (CRTEMU_GLenum target, CRTEMU_GLenum attachment, CRTEMU_GLenum textarget, CRTEMU_GLuint texture, CRTEMU_GLint level); + CRTEMU_GLuint (CRTEMU_GLCALLTYPE* CreateShader) (CRTEMU_GLenum type); + void (CRTEMU_GLCALLTYPE* ShaderSource) (CRTEMU_GLuint shader, CRTEMU_GLsizei count, CRTEMU_GLchar const* const* string, CRTEMU_GLint const* length); + void (CRTEMU_GLCALLTYPE* CompileShader) (CRTEMU_GLuint shader); + void (CRTEMU_GLCALLTYPE* GetShaderiv) (CRTEMU_GLuint shader, CRTEMU_GLenum pname, CRTEMU_GLint *params); + CRTEMU_GLuint (CRTEMU_GLCALLTYPE* CreateProgram) (void); + void (CRTEMU_GLCALLTYPE* AttachShader) (CRTEMU_GLuint program, CRTEMU_GLuint shader); + void (CRTEMU_GLCALLTYPE* BindAttribLocation) (CRTEMU_GLuint program, CRTEMU_GLuint index, CRTEMU_GLchar const* name); + void (CRTEMU_GLCALLTYPE* LinkProgram) (CRTEMU_GLuint program); + void (CRTEMU_GLCALLTYPE* GetProgramiv) (CRTEMU_GLuint program, CRTEMU_GLenum pname, CRTEMU_GLint *params); + void (CRTEMU_GLCALLTYPE* GenBuffers) (CRTEMU_GLsizei n, CRTEMU_GLuint *buffers); + void (CRTEMU_GLCALLTYPE* BindBuffer) (CRTEMU_GLenum target, CRTEMU_GLuint buffer); + void (CRTEMU_GLCALLTYPE* EnableVertexAttribArray) (CRTEMU_GLuint index); + void (CRTEMU_GLCALLTYPE* VertexAttribPointer) (CRTEMU_GLuint index, CRTEMU_GLint size, CRTEMU_GLenum type, CRTEMU_GLboolean normalized, CRTEMU_GLsizei stride, void const* pointer); + void (CRTEMU_GLCALLTYPE* GenTextures) (CRTEMU_GLsizei n, CRTEMU_GLuint* textures); + void (CRTEMU_GLCALLTYPE* Enable) (CRTEMU_GLenum cap); + void (CRTEMU_GLCALLTYPE* ActiveTexture) (CRTEMU_GLenum texture); + void (CRTEMU_GLCALLTYPE* BindTexture) (CRTEMU_GLenum target, CRTEMU_GLuint texture); + void (CRTEMU_GLCALLTYPE* TexParameteri) (CRTEMU_GLenum target, CRTEMU_GLenum pname, CRTEMU_GLint param); + void (CRTEMU_GLCALLTYPE* DeleteBuffers) (CRTEMU_GLsizei n, CRTEMU_GLuint const* buffers); + void (CRTEMU_GLCALLTYPE* DeleteTextures) (CRTEMU_GLsizei n, CRTEMU_GLuint const* textures); + void (CRTEMU_GLCALLTYPE* BufferData) (CRTEMU_GLenum target, CRTEMU_GLsizeiptr size, void const *data, CRTEMU_GLenum usage); + void (CRTEMU_GLCALLTYPE* UseProgram) (CRTEMU_GLuint program); + void (CRTEMU_GLCALLTYPE* Uniform1i) (CRTEMU_GLint location, CRTEMU_GLint v0); + void (CRTEMU_GLCALLTYPE* Uniform3f) (CRTEMU_GLint location, CRTEMU_GLfloat v0, CRTEMU_GLfloat v1, CRTEMU_GLfloat v2); + CRTEMU_GLint (CRTEMU_GLCALLTYPE* GetUniformLocation) (CRTEMU_GLuint program, CRTEMU_GLchar const* name); + void (CRTEMU_GLCALLTYPE* TexImage2D) (CRTEMU_GLenum target, CRTEMU_GLint level, CRTEMU_GLint internalformat, CRTEMU_GLsizei width, CRTEMU_GLsizei height, CRTEMU_GLint border, CRTEMU_GLenum format, CRTEMU_GLenum type, void const* pixels); + void (CRTEMU_GLCALLTYPE* ClearColor) (CRTEMU_GLfloat red, CRTEMU_GLfloat green, CRTEMU_GLfloat blue, CRTEMU_GLfloat alpha); + void (CRTEMU_GLCALLTYPE* Clear) (CRTEMU_GLbitfield mask); + void (CRTEMU_GLCALLTYPE* DrawArrays) (CRTEMU_GLenum mode, CRTEMU_GLint first, CRTEMU_GLsizei count); + void (CRTEMU_GLCALLTYPE* Viewport) (CRTEMU_GLint x, CRTEMU_GLint y, CRTEMU_GLsizei width, CRTEMU_GLsizei height); + void (CRTEMU_GLCALLTYPE* DeleteShader) (CRTEMU_GLuint shader); + void (CRTEMU_GLCALLTYPE* DeleteProgram) (CRTEMU_GLuint program); + #ifdef CRTEMU_REPORT_SHADER_ERRORS + void (CRTEMU_GLCALLTYPE* GetShaderInfoLog) (CRTEMU_GLuint shader, CRTEMU_GLsizei bufSize, CRTEMU_GLsizei *length, CRTEMU_GLchar *infoLog); + #endif + }; + + +static CRTEMU_GLuint crtemu_internal_build_shader( crtemu_t* crtemu, char const* vs_source, char const* fs_source ) + { + #ifdef CRTEMU_REPORT_SHADER_ERRORS + char error_message[ 1024 ]; + #endif + + CRTEMU_GLuint vs = crtemu->CreateShader( CRTEMU_GL_VERTEX_SHADER ); + crtemu->ShaderSource( vs, 1, (char const**) &vs_source, NULL ); + crtemu->CompileShader( vs ); + CRTEMU_GLint vs_compiled; + crtemu->GetShaderiv( vs, CRTEMU_GL_COMPILE_STATUS, &vs_compiled ); + if( !vs_compiled ) + { + #ifdef CRTEMU_REPORT_SHADER_ERRORS + char const* prefix = "Vertex Shader Error: "; + strcpy( error_message, prefix ); + int len = 0, written = 0; + crtemu->GetShaderiv( vs, CRTEMU_GL_INFO_LOG_LENGTH, &len ); + crtemu->GetShaderInfoLog( vs, (CRTEMU_GLsizei)( sizeof( error_message ) - strlen( prefix ) ), &written, + error_message + strlen( prefix ) ); + CRTEMU_REPORT_ERROR( error_message ); + #endif + return 0; + } + + CRTEMU_GLuint fs = crtemu->CreateShader( CRTEMU_GL_FRAGMENT_SHADER ); + crtemu->ShaderSource( fs, 1, (char const**) &fs_source, NULL ); + crtemu->CompileShader( fs ); + CRTEMU_GLint fs_compiled; + crtemu->GetShaderiv( fs, CRTEMU_GL_COMPILE_STATUS, &fs_compiled ); + if( !fs_compiled ) + { + #ifdef CRTEMU_REPORT_SHADER_ERRORS + char const* prefix = "Fragment Shader Error: "; + strcpy( error_message, prefix ); + int len = 0, written = 0; + crtemu->GetShaderiv( vs, CRTEMU_GL_INFO_LOG_LENGTH, &len ); + crtemu->GetShaderInfoLog( fs, (CRTEMU_GLsizei)( sizeof( error_message ) - strlen( prefix ) ), &written, + error_message + strlen( prefix ) ); + CRTEMU_REPORT_ERROR( error_message ); + #endif + return 0; + } + + + CRTEMU_GLuint prg = crtemu->CreateProgram(); + crtemu->AttachShader( prg, fs ); + crtemu->AttachShader( prg, vs ); + crtemu->BindAttribLocation( prg, 0, "pos" ); + crtemu->LinkProgram( prg ); + + CRTEMU_GLint linked; + crtemu->GetProgramiv( prg, CRTEMU_GL_LINK_STATUS, &linked ); + if( !linked ) + { + #ifdef CRTEMU_REPORT_SHADER_ERRORS + char const* prefix = "Shader Link Error: "; + strcpy( error_message, prefix ); + int len = 0, written = 0; + crtemu->GetShaderiv( vs, CRTEMU_GL_INFO_LOG_LENGTH, &len ); + crtemu->GetShaderInfoLog( prg, (CRTEMU_GLsizei)( sizeof( error_message ) - strlen( prefix ) ), &written, + error_message + strlen( prefix ) ); + CRTEMU_REPORT_ERROR( error_message ); + #endif + return 0; + } + + return prg; + } + + +crtemu_t* crtemu_create( void* memctx ) + { + + char const* vs_source = + #ifdef CRTEMU_WEBGL + "precision highp float;\n\n" + #else + "#version 120\n\n" + #endif + "" + "attribute vec4 pos;" + "varying vec2 uv;" + "" + "void main( void )" + " {" + " gl_Position = vec4( pos.xy, 0.0, 1.0 );" + " uv = pos.zw;" + " }"; + + char const* crt_fs_source = + #ifdef CRTEMU_WEBGL + "precision highp float;\n\n" + #else + "#version 120\n\n" + #endif + "\n" + "varying vec2 uv;\n" + "\n" + "uniform vec3 modulate;\n" + "uniform vec2 resolution;\n" + "uniform vec2 size;\n" + "uniform float time;\n" + "uniform sampler2D backbuffer;\n" + "uniform sampler2D blurbuffer;\n" + "uniform sampler2D frametexture;\n" + "uniform float use_frame;\n" + "\n" + #ifdef CRTEMU_WEBGL + // WebGL does not support GL_CLAMP_TO_BORDER so we overwrite texture2D + // with this function which emulates the clamp-to-border behavior + "vec4 texture2Dborder(sampler2D samp, vec2 tc)\n" + " {\n" + " float borderdist = .502-max(abs(.5-tc.x), abs(.5-tc.y));\n" + " float borderfade = clamp(borderdist * 400.0, 0.0, 1.0);\n" + " return texture2D( samp, tc ) * borderfade;\n" + " }\n" + "#define texture2D texture2Dborder\n" + #endif + "vec3 tsample( sampler2D samp, vec2 tc, float offs, vec2 resolution )\n" + " {\n" + " tc = tc * vec2(1.025, 0.92) + vec2(-0.0125, 0.04);\n" + " vec3 s = pow( abs( texture2D( samp, vec2( tc.x, 1.0-tc.y ) ).rgb), vec3( 2.2 ) );\n" + " return s*vec3(1.25);\n" + " }" + "\n" + "vec3 filmic( vec3 LinearColor )\n" + " {\n" + " vec3 x = max( vec3(0.0), LinearColor-vec3(0.004));\n" + " return (x*(6.2*x+0.5))/(x*(6.2*x+1.7)+0.06);\n" + " }\n" + "\n" + "vec2 curve( vec2 uv )\n" + " {\n" + " uv = (uv - 0.5) * 2.0;\n" + " uv *= 1.1; \n" + " uv.x *= 1.0 + pow((abs(uv.y) / 5.0), 2.0);\n" + " uv.y *= 1.0 + pow((abs(uv.x) / 4.0), 2.0);\n" + " uv = (uv / 2.0) + 0.5;\n" + " uv = uv *0.92 + 0.04;\n" + " return uv;\n" + " }\n" + "\n" + "float rand(vec2 co)\n" + " {\n" + " return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);\n" + " }\n" + " \n" + "void main(void)\n" + " {\n" + " /* Curve */\n" + " vec2 curved_uv = mix( curve( uv ), uv, 0.4 );\n" + " float scale = 0.04;\n" + " vec2 scuv = curved_uv*(1.0-scale)+scale/2.0+vec2(0.003, -0.001);\n" + "\n" + " /* Main color, Bleed */\n" + " vec3 col;\n" + " float x = sin(0.1*time+curved_uv.y*13.0)*sin(0.23*time+curved_uv.y*19.0)*sin(0.3+0.11*time+curved_uv.y*23.0)*0.0012;\n" + " float o =sin(gl_FragCoord.y*1.5)/resolution.x;\n" + " x=x*0.25+o*0.25;\n" + " col.r = tsample(backbuffer,vec2(x+scuv.x+0.0009,scuv.y+0.0009),resolution.y/800.0, resolution ).x+0.02;\n" + " col.g = tsample(backbuffer,vec2(x+scuv.x+0.0000,scuv.y-0.0011),resolution.y/800.0, resolution ).y+0.02;\n" + " col.b = tsample(backbuffer,vec2(x+scuv.x-0.0015,scuv.y+0.0000),resolution.y/800.0, resolution ).z+0.02;\n" + " float i = clamp(col.r*0.299 + col.g*0.587 + col.b*0.114, 0.0, 1.0 ); \n" + " i = pow( 1.0 - pow(i,2.0), 1.0 );\n" + " i = (1.0-i) * 0.85 + 0.15; \n" + "\n" + " /* Ghosting */\n" + " float ghs = 0.15;\n" + " vec3 r = tsample(blurbuffer, vec2(x-0.014*1.0, -0.027)*0.85+0.007*vec2( 0.35*sin(1.0/7.0 + 15.0*curved_uv.y + 0.9*time), \n" + " 0.35*sin( 2.0/7.0 + 10.0*curved_uv.y + 1.37*time) )+vec2(scuv.x+0.001,scuv.y+0.001),\n" + " 5.5+1.3*sin( 3.0/9.0 + 31.0*curved_uv.x + 1.70*time),resolution).xyz*vec3(0.5,0.25,0.25);\n" + " vec3 g = tsample(blurbuffer, vec2(x-0.019*1.0, -0.020)*0.85+0.007*vec2( 0.35*cos(1.0/9.0 + 15.0*curved_uv.y + 0.5*time), \n" + " 0.35*sin( 2.0/9.0 + 10.0*curved_uv.y + 1.50*time) )+vec2(scuv.x+0.000,scuv.y-0.002),\n" + " 5.4+1.3*sin( 3.0/3.0 + 71.0*curved_uv.x + 1.90*time),resolution).xyz*vec3(0.25,0.5,0.25);\n" + " vec3 b = tsample(blurbuffer, vec2(x-0.017*1.0, -0.003)*0.85+0.007*vec2( 0.35*sin(2.0/3.0 + 15.0*curved_uv.y + 0.7*time), \n" + " 0.35*cos( 2.0/3.0 + 10.0*curved_uv.y + 1.63*time) )+vec2(scuv.x-0.002,scuv.y+0.000),\n" + " 5.3+1.3*sin( 3.0/7.0 + 91.0*curved_uv.x + 1.65*time),resolution).xyz*vec3(0.25,0.25,0.5);\n" + "\n" + " col += vec3(ghs*(1.0-0.299))*pow(clamp(vec3(3.0)*r,vec3(0.0),vec3(1.0)),vec3(2.0))*vec3(i);\n" + " col += vec3(ghs*(1.0-0.587))*pow(clamp(vec3(3.0)*g,vec3(0.0),vec3(1.0)),vec3(2.0))*vec3(i);\n" + " col += vec3(ghs*(1.0-0.114))*pow(clamp(vec3(3.0)*b,vec3(0.0),vec3(1.0)),vec3(2.0))*vec3(i);\n" + "\n" + " /* Level adjustment (curves) */\n" + " col *= vec3(0.95,1.05,0.95);\n" + " col = clamp(col*1.3 + 0.75*col*col + 1.25*col*col*col*col*col,vec3(0.0),vec3(10.0));\n" + "\n" + " /* Vignette */\n" + " float vig = (0.1 + 1.0*16.0*curved_uv.x*curved_uv.y*(1.0-curved_uv.x)*(1.0-curved_uv.y));\n" + " vig = 1.3*pow(vig,0.5);\n" + " col *= vig;\n" + "\n" + " /* Scanlines */\n" + " float scans = clamp( 0.35+0.18*sin(4.0*time+curved_uv.y*size.y*1.5), 0.0, 1.0);\n" + " float s = pow(scans,0.9);\n" + " col = col * vec3(s);\n" + "\n" + " /* Vertical lines (shadow mask) */\n" + " col*=1.0-0.23*(clamp((mod(gl_FragCoord.xy.x, 3.0))/2.0,0.0,1.0));\n" + "\n" + " /* Tone map */\n" + " col = filmic( col );\n" + "\n" + " /* Noise */\n" + " /*vec2 seed = floor(curved_uv*resolution.xy*vec2(0.5))/resolution.xy;*/\n" + " vec2 seed = curved_uv*resolution.xy;;\n" + " /* seed = curved_uv; */\n" + " col -= 0.015*pow(vec3(rand( seed +time ), rand( seed +time*2.0 ), rand( seed +time * 3.0 ) ), vec3(1.5) );\n" + "\n" + " /* Flicker */\n" + " col *= (1.0-0.004*(sin(50.0*time+curved_uv.y*2.0)*0.5+0.5));\n" + "\n" + " /* Clamp */\n" + " if (curved_uv.x < 0.0 || curved_uv.x > 1.0)\n" + " col *= 0.0;\n" + " if (curved_uv.y < 0.0 || curved_uv.y > 1.0)\n" + " col *= 0.0;\n" + " col *= modulate;\n" + " /* Frame */\n" + " vec2 fuv=vec2( uv.x, 1.0 - uv.y);\n" + " vec4 f=texture2D(frametexture,fuv);\n" + " vec3 fr = mix( max( col, 0.0), f.xyz, f.w);\n" + " col = mix( col, fr, vec3( use_frame ) );\n" + " \n" + " gl_FragColor = vec4( col, 1.0 );\n" + " }\n" + "\n"; + + char const* blur_fs_source = + #ifdef CRTEMU_WEBGL + "precision highp float;\n\n" + #else + "#version 120\n\n" + #endif + "" + "varying vec2 uv;" + "" + "uniform vec2 blur;" + "uniform sampler2D texture;" + "" + "void main( void )" + " {" + " vec4 sum = texture2D( texture, uv ) * 0.2270270270;" + " sum += texture2D(texture, vec2( uv.x - 4.0 * blur.x, uv.y - 4.0 * blur.y ) ) * 0.0162162162;" + " sum += texture2D(texture, vec2( uv.x - 3.0 * blur.x, uv.y - 3.0 * blur.y ) ) * 0.0540540541;" + " sum += texture2D(texture, vec2( uv.x - 2.0 * blur.x, uv.y - 2.0 * blur.y ) ) * 0.1216216216;" + " sum += texture2D(texture, vec2( uv.x - 1.0 * blur.x, uv.y - 1.0 * blur.y ) ) * 0.1945945946;" + " sum += texture2D(texture, vec2( uv.x + 1.0 * blur.x, uv.y + 1.0 * blur.y ) ) * 0.1945945946;" + " sum += texture2D(texture, vec2( uv.x + 2.0 * blur.x, uv.y + 2.0 * blur.y ) ) * 0.1216216216;" + " sum += texture2D(texture, vec2( uv.x + 3.0 * blur.x, uv.y + 3.0 * blur.y ) ) * 0.0540540541;" + " sum += texture2D(texture, vec2( uv.x + 4.0 * blur.x, uv.y + 4.0 * blur.y ) ) * 0.0162162162;" + " gl_FragColor = sum;" + " } " + ""; + + + char const* accumulate_fs_source = + #ifdef CRTEMU_WEBGL + "precision highp float;\n\n" + #else + "#version 120\n\n" + #endif + "" + "varying vec2 uv;" + "" + "uniform sampler2D tex0;" + "uniform sampler2D tex1;" + "uniform float modulate;" + "" + "void main( void )" + " {" + " vec4 a = texture2D( tex0, uv ) * vec4( modulate );" + " vec4 b = texture2D( tex1, uv );" + "" + " gl_FragColor = max( a, b * 0.96 );" + " } " + ""; + + char const* blend_fs_source = + #ifdef CRTEMU_WEBGL + "precision highp float;\n\n" + #else + "#version 120\n\n" + #endif + "" + "varying vec2 uv;" + "" + "uniform sampler2D tex0;" + "uniform sampler2D tex1;" + "uniform float modulate;" + "" + "void main( void )" + " {" + " vec4 a = texture2D( tex0, uv ) * vec4( modulate );" + " vec4 b = texture2D( tex1, uv );" + "" + " gl_FragColor = max( a, b * 0.32 );" + " } " + ""; + + char const* copy_fs_source = + #ifdef CRTEMU_WEBGL + "precision highp float;\n\n" + #else + "#version 120\n\n" + #endif + "" + "varying vec2 uv;" + "" + "uniform sampler2D tex0;" + "" + "void main( void )" + " {" + " gl_FragColor = texture2D( tex0, uv );" + " } " + ""; + + crtemu_t* crtemu = (crtemu_t*) CRTEMU_MALLOC( memctx, sizeof( crtemu_t ) ); + memset( crtemu, 0, sizeof( crtemu_t ) ); + crtemu->memctx = memctx; + + crtemu->config.curvature = 0.0f; + crtemu->config.scanlines = 0.0f; + crtemu->config.shadow_mask = 0.0f; + crtemu->config.separation = 0.0f; + crtemu->config.ghosting = 0.0f; + crtemu->config.noise = 0.0f; + crtemu->config.flicker = 0.0f; + crtemu->config.vignette = 0.0f; + crtemu->config.distortion = 0.0f; + crtemu->config.aspect_lock = 0.0f; + crtemu->config.hpos = 0.0f; + crtemu->config.vpos = 0.0f; + crtemu->config.hsize = 0.0f; + crtemu->config.vsize = 0.0f; + crtemu->config.contrast = 0.0f; + crtemu->config.brightness = 0.0f; + crtemu->config.saturation = 0.0f; + crtemu->config.blur = 0.0f; + crtemu->config.degauss = 0.0f; + + crtemu->use_frame = 0.0f; + + crtemu->last_present_width = 0; + crtemu->last_present_height = 0; + + #ifndef CRTEMU_SDL + + crtemu->gl_dll = LoadLibraryA( "opengl32.dll" ); + if( !crtemu->gl_dll ) goto failed; + + crtemu->wglGetProcAddress = (CRTEMU_PROC (CRTEMU_GLCALLTYPE*)(char const*)) (uintptr_t) GetProcAddress( crtemu->gl_dll, "wglGetProcAddress" ); + if( !crtemu->gl_dll ) goto failed; + + // Attempt to bind opengl functions using GetProcAddress + crtemu->TexParameterfv = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLenum, CRTEMU_GLfloat const*) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glTexParameterfv" ); + crtemu->DeleteFramebuffers = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLsizei, CRTEMU_GLuint const*) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glDeleteFramebuffers" ); + crtemu->GetIntegerv = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLint *) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glGetIntegerv" ); + crtemu->GenFramebuffers = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLsizei, CRTEMU_GLuint *) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glGenFramebuffers" ); + crtemu->BindFramebuffer = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLuint) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glBindFramebuffer" ); + crtemu->Uniform1f = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLint, CRTEMU_GLfloat) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glUniform1f" ); + crtemu->Uniform2f = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLint, CRTEMU_GLfloat, CRTEMU_GLfloat) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glUniform2f" ); + crtemu->FramebufferTexture2D = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLenum, CRTEMU_GLenum, CRTEMU_GLuint, CRTEMU_GLint) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glFramebufferTexture2D" ); + crtemu->CreateShader = ( CRTEMU_GLuint (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glCreateShader" ); + crtemu->ShaderSource = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint, CRTEMU_GLsizei, CRTEMU_GLchar const* const*, CRTEMU_GLint const*) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glShaderSource" ); + crtemu->CompileShader = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glCompileShader" ); + crtemu->GetShaderiv = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint, CRTEMU_GLenum, CRTEMU_GLint*) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glGetShaderiv" ); + crtemu->CreateProgram = ( CRTEMU_GLuint (CRTEMU_GLCALLTYPE*) (void) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glCreateProgram" ); + crtemu->AttachShader = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint, CRTEMU_GLuint) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glAttachShader" ); + crtemu->BindAttribLocation = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint, CRTEMU_GLuint, CRTEMU_GLchar const*) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glBindAttribLocation" ); + crtemu->LinkProgram = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glLinkProgram" ); + crtemu->GetProgramiv = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint, CRTEMU_GLenum, CRTEMU_GLint*) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glGetProgramiv" ); + crtemu->GenBuffers = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLsizei, CRTEMU_GLuint*) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glGenBuffers" ); + crtemu->BindBuffer = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLuint) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glBindBuffer" ); + crtemu->EnableVertexAttribArray = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glEnableVertexAttribArray" ); + crtemu->VertexAttribPointer = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint, CRTEMU_GLint, CRTEMU_GLenum, CRTEMU_GLboolean, CRTEMU_GLsizei, void const*) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glVertexAttribPointer" ); + crtemu->GenTextures = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLsizei, CRTEMU_GLuint*) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glGenTextures" ); + crtemu->Enable = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glEnable" ); + crtemu->ActiveTexture = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glActiveTexture" ); + crtemu->BindTexture = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLuint) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glBindTexture" ); + crtemu->TexParameteri = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLenum, CRTEMU_GLint) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glTexParameteri" ); + crtemu->DeleteBuffers = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLsizei, CRTEMU_GLuint const*) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glDeleteBuffers" ); + crtemu->DeleteTextures = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLsizei, CRTEMU_GLuint const*) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glDeleteTextures" ); + crtemu->BufferData = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLsizeiptr, void const *, CRTEMU_GLenum) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glBufferData" ); + crtemu->UseProgram = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glUseProgram" ); + crtemu->Uniform1i = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLint, CRTEMU_GLint) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glUniform1i" ); + crtemu->Uniform3f = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLint, CRTEMU_GLfloat, CRTEMU_GLfloat, CRTEMU_GLfloat) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glUniform3f" ); + crtemu->GetUniformLocation = ( CRTEMU_GLint (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint, CRTEMU_GLchar const*) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glGetUniformLocation" ); + crtemu->TexImage2D = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLint, CRTEMU_GLint, CRTEMU_GLsizei, CRTEMU_GLsizei, CRTEMU_GLint, CRTEMU_GLenum, CRTEMU_GLenum, void const*) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glTexImage2D" ); + crtemu->ClearColor = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLfloat, CRTEMU_GLfloat, CRTEMU_GLfloat, CRTEMU_GLfloat) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glClearColor" ); + crtemu->Clear = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLbitfield) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glClear" ); + crtemu->DrawArrays = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLint, CRTEMU_GLsizei) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glDrawArrays" ); + crtemu->Viewport = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLint, CRTEMU_GLint, CRTEMU_GLsizei, CRTEMU_GLsizei) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glViewport" ); + crtemu->DeleteShader = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glDeleteShader" ); + crtemu->DeleteProgram = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glDeleteProgram" ); + #ifdef CRTEMU_REPORT_SHADER_ERRORS + crtemu->GetShaderInfoLog = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint, CRTEMU_GLsizei, CRTEMU_GLsizei*, CRTEMU_GLchar*) ) (uintptr_t) GetProcAddress( crtemu->gl_dll, "glGetShaderInfoLog" ); + #endif + + // Any opengl functions which didn't bind, try binding them using wglGetProcAddrss + if( !crtemu->TexParameterfv ) crtemu->TexParameterfv = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLenum, CRTEMU_GLfloat const*) ) (uintptr_t) crtemu->wglGetProcAddress( "glTexParameterfv" ); + if( !crtemu->DeleteFramebuffers ) crtemu->DeleteFramebuffers = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLsizei, CRTEMU_GLuint const*) ) (uintptr_t) crtemu->wglGetProcAddress( "glDeleteFramebuffers" ); + if( !crtemu->GetIntegerv ) crtemu->GetIntegerv = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLint *) ) (uintptr_t) crtemu->wglGetProcAddress( "glGetIntegerv" ); + if( !crtemu->GenFramebuffers ) crtemu->GenFramebuffers = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLsizei, CRTEMU_GLuint *) ) (uintptr_t) crtemu->wglGetProcAddress( "glGenFramebuffers" ); + if( !crtemu->BindFramebuffer ) crtemu->BindFramebuffer = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLuint) ) (uintptr_t) crtemu->wglGetProcAddress( "glBindFramebuffer" ); + if( !crtemu->Uniform1f ) crtemu->Uniform1f = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLint, CRTEMU_GLfloat) ) (uintptr_t) crtemu->wglGetProcAddress( "glUniform1f" ); + if( !crtemu->Uniform2f ) crtemu->Uniform2f = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLint, CRTEMU_GLfloat, CRTEMU_GLfloat) ) (uintptr_t) crtemu->wglGetProcAddress( "glUniform2f" ); + if( !crtemu->FramebufferTexture2D ) crtemu->FramebufferTexture2D = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLenum, CRTEMU_GLenum, CRTEMU_GLuint, CRTEMU_GLint) ) (uintptr_t) crtemu->wglGetProcAddress( "glFramebufferTexture2D" ); + if( !crtemu->CreateShader ) crtemu->CreateShader = ( CRTEMU_GLuint (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum) ) (uintptr_t) crtemu->wglGetProcAddress( "glCreateShader" ); + if( !crtemu->ShaderSource ) crtemu->ShaderSource = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint, CRTEMU_GLsizei, CRTEMU_GLchar const* const*, CRTEMU_GLint const*) ) (uintptr_t) crtemu->wglGetProcAddress( "glShaderSource" ); + if( !crtemu->CompileShader ) crtemu->CompileShader = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint) ) (uintptr_t) crtemu->wglGetProcAddress( "glCompileShader" ); + if( !crtemu->GetShaderiv ) crtemu->GetShaderiv = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint, CRTEMU_GLenum, CRTEMU_GLint*) ) (uintptr_t) crtemu->wglGetProcAddress( "glGetShaderiv" ); + if( !crtemu->CreateProgram ) crtemu->CreateProgram = ( CRTEMU_GLuint (CRTEMU_GLCALLTYPE*) (void) ) (uintptr_t) crtemu->wglGetProcAddress( "glCreateProgram" ); + if( !crtemu->AttachShader ) crtemu->AttachShader = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint, CRTEMU_GLuint) ) (uintptr_t) crtemu->wglGetProcAddress( "glAttachShader" ); + if( !crtemu->BindAttribLocation ) crtemu->BindAttribLocation = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint, CRTEMU_GLuint, CRTEMU_GLchar const*) ) (uintptr_t) crtemu->wglGetProcAddress( "glBindAttribLocation" ); + if( !crtemu->LinkProgram ) crtemu->LinkProgram = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint) ) (uintptr_t) crtemu->wglGetProcAddress( "glLinkProgram" ); + if( !crtemu->GetProgramiv ) crtemu->GetProgramiv = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint, CRTEMU_GLenum, CRTEMU_GLint*) ) (uintptr_t) crtemu->wglGetProcAddress( "glGetProgramiv" ); + if( !crtemu->GenBuffers ) crtemu->GenBuffers = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLsizei, CRTEMU_GLuint*) ) (uintptr_t) crtemu->wglGetProcAddress( "glGenBuffers" ); + if( !crtemu->BindBuffer ) crtemu->BindBuffer = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLuint) ) (uintptr_t) crtemu->wglGetProcAddress( "glBindBuffer" ); + if( !crtemu->EnableVertexAttribArray ) crtemu->EnableVertexAttribArray = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint) ) (uintptr_t) crtemu->wglGetProcAddress( "glEnableVertexAttribArray" ); + if( !crtemu->VertexAttribPointer ) crtemu->VertexAttribPointer = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint, CRTEMU_GLint, CRTEMU_GLenum, CRTEMU_GLboolean, CRTEMU_GLsizei, void const*) ) (uintptr_t) crtemu->wglGetProcAddress( "glVertexAttribPointer" ); + if( !crtemu->GenTextures ) crtemu->GenTextures = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLsizei, CRTEMU_GLuint*) ) (uintptr_t) crtemu->wglGetProcAddress( "glGenTextures" ); + if( !crtemu->Enable ) crtemu->Enable = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum) ) (uintptr_t) crtemu->wglGetProcAddress( "glEnable" ); + if( !crtemu->ActiveTexture ) crtemu->ActiveTexture = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum) ) (uintptr_t) crtemu->wglGetProcAddress( "glActiveTexture" ); + if( !crtemu->BindTexture ) crtemu->BindTexture = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLuint) ) (uintptr_t) crtemu->wglGetProcAddress( "glBindTexture" ); + if( !crtemu->TexParameteri ) crtemu->TexParameteri = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLenum, CRTEMU_GLint) ) (uintptr_t) crtemu->wglGetProcAddress( "glTexParameteri" ); + if( !crtemu->DeleteBuffers ) crtemu->DeleteBuffers = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLsizei, CRTEMU_GLuint const*) ) (uintptr_t) crtemu->wglGetProcAddress( "glDeleteBuffers" ); + if( !crtemu->DeleteTextures ) crtemu->DeleteTextures = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLsizei, CRTEMU_GLuint const*) ) (uintptr_t) crtemu->wglGetProcAddress( "glDeleteTextures" ); + if( !crtemu->BufferData ) crtemu->BufferData = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLsizeiptr, void const *, CRTEMU_GLenum) ) (uintptr_t) crtemu->wglGetProcAddress( "glBufferData" ); + if( !crtemu->UseProgram ) crtemu->UseProgram = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint) ) (uintptr_t) crtemu->wglGetProcAddress( "glUseProgram" ); + if( !crtemu->Uniform1i ) crtemu->Uniform1i = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLint, CRTEMU_GLint) ) (uintptr_t) crtemu->wglGetProcAddress( "glUniform1i" ); + if( !crtemu->Uniform3f ) crtemu->Uniform3f = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLint, CRTEMU_GLfloat, CRTEMU_GLfloat, CRTEMU_GLfloat) ) (uintptr_t) crtemu->wglGetProcAddress( "glUniform3f" ); + if( !crtemu->GetUniformLocation ) crtemu->GetUniformLocation = ( CRTEMU_GLint (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint, CRTEMU_GLchar const*) ) (uintptr_t) crtemu->wglGetProcAddress( "glGetUniformLocation" ); + if( !crtemu->TexImage2D ) crtemu->TexImage2D = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLint, CRTEMU_GLint, CRTEMU_GLsizei, CRTEMU_GLsizei, CRTEMU_GLint, CRTEMU_GLenum, CRTEMU_GLenum, void const*) ) (uintptr_t) crtemu->wglGetProcAddress( "glTexImage2D" ); + if( !crtemu->ClearColor ) crtemu->ClearColor = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLfloat, CRTEMU_GLfloat, CRTEMU_GLfloat, CRTEMU_GLfloat) ) (uintptr_t) crtemu->wglGetProcAddress( "glClearColor" ); + if( !crtemu->Clear ) crtemu->Clear = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLbitfield) ) (uintptr_t) crtemu->wglGetProcAddress( "glClear" ); + if( !crtemu->DrawArrays ) crtemu->DrawArrays = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLenum, CRTEMU_GLint, CRTEMU_GLsizei) ) (uintptr_t) crtemu->wglGetProcAddress( "glDrawArrays" ); + if( !crtemu->Viewport ) crtemu->Viewport = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLint, CRTEMU_GLint, CRTEMU_GLsizei, CRTEMU_GLsizei) ) (uintptr_t) crtemu->wglGetProcAddress( "glViewport" ); + if( !crtemu->DeleteShader ) crtemu->DeleteShader = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint) ) (uintptr_t) crtemu->wglGetProcAddress( "glDeleteShader" ); + if( !crtemu->DeleteProgram ) crtemu->DeleteProgram = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint) ) (uintptr_t) crtemu->wglGetProcAddress( "glDeleteProgram" ); + #ifdef CRTEMU_REPORT_SHADER_ERRORS + if( !crtemu->GetShaderInfoLog ) crtemu->GetShaderInfoLog = ( void (CRTEMU_GLCALLTYPE*) (CRTEMU_GLuint, CRTEMU_GLsizei, CRTEMU_GLsizei*, CRTEMU_GLchar*) ) (uintptr_t) crtemu->wglGetProcAddress( "glGetShaderInfoLog" ); + #endif + + #else + + crtemu->TexParameterfv = glTexParameterfv; + crtemu->DeleteFramebuffers = glDeleteFramebuffers; + crtemu->GetIntegerv = glGetIntegerv; + crtemu->GenFramebuffers = glGenFramebuffers; + crtemu->BindFramebuffer = glBindFramebuffer; + crtemu->Uniform1f = glUniform1f; + crtemu->Uniform2f = glUniform2f; + crtemu->FramebufferTexture2D = glFramebufferTexture2D; + crtemu->CreateShader = glCreateShader; + crtemu->ShaderSource = glShaderSource; + crtemu->CompileShader = glCompileShader; + crtemu->GetShaderiv = glGetShaderiv; + crtemu->CreateProgram = glCreateProgram; + crtemu->AttachShader = glAttachShader; + crtemu->BindAttribLocation = glBindAttribLocation; + crtemu->LinkProgram = glLinkProgram; + crtemu->GetProgramiv = glGetProgramiv; + crtemu->GenBuffers = glGenBuffers; + crtemu->BindBuffer = glBindBuffer; + crtemu->EnableVertexAttribArray = glEnableVertexAttribArray; + crtemu->VertexAttribPointer = glVertexAttribPointer; + crtemu->GenTextures = glGenTextures; + crtemu->Enable = glEnable; + crtemu->ActiveTexture = glActiveTexture; + crtemu->BindTexture = glBindTexture; + crtemu->TexParameteri = glTexParameteri; + crtemu->DeleteBuffers = glDeleteBuffers; + crtemu->DeleteTextures = glDeleteTextures; + crtemu->BufferData = glBufferData; + crtemu->UseProgram = glUseProgram; + crtemu->Uniform1i = glUniform1i; + crtemu->Uniform3f = glUniform3f; + crtemu->GetUniformLocation = glGetUniformLocation; + crtemu->TexImage2D = glTexImage2D; + crtemu->ClearColor = glClearColor; + crtemu->Clear = glClear; + crtemu->DrawArrays = glDrawArrays; + crtemu->Viewport = glViewport; + crtemu->DeleteShader = glDeleteShader; + crtemu->DeleteProgram = glDeleteProgram; + #ifdef CRTEMU_REPORT_SHADER_ERRORS + crtemu->GetShaderInfoLog = glGetShaderInfoLog; + #endif + + #endif + + // Report error if any gl function was not found. + if( !crtemu->TexParameterfv ) goto failed; + if( !crtemu->DeleteFramebuffers ) goto failed; + if( !crtemu->GetIntegerv ) goto failed; + if( !crtemu->GenFramebuffers ) goto failed; + if( !crtemu->BindFramebuffer ) goto failed; + if( !crtemu->Uniform1f ) goto failed; + if( !crtemu->Uniform2f ) goto failed; + if( !crtemu->FramebufferTexture2D ) goto failed; + if( !crtemu->CreateShader ) goto failed; + if( !crtemu->ShaderSource ) goto failed; + if( !crtemu->CompileShader ) goto failed; + if( !crtemu->GetShaderiv ) goto failed; + if( !crtemu->CreateProgram ) goto failed; + if( !crtemu->AttachShader ) goto failed; + if( !crtemu->BindAttribLocation ) goto failed; + if( !crtemu->LinkProgram ) goto failed; + if( !crtemu->GetProgramiv ) goto failed; + if( !crtemu->GenBuffers ) goto failed; + if( !crtemu->BindBuffer ) goto failed; + if( !crtemu->EnableVertexAttribArray ) goto failed; + if( !crtemu->VertexAttribPointer ) goto failed; + if( !crtemu->GenTextures ) goto failed; + if( !crtemu->Enable ) goto failed; + if( !crtemu->ActiveTexture ) goto failed; + if( !crtemu->BindTexture ) goto failed; + if( !crtemu->TexParameteri ) goto failed; + if( !crtemu->DeleteBuffers ) goto failed; + if( !crtemu->DeleteTextures ) goto failed; + if( !crtemu->BufferData ) goto failed; + if( !crtemu->UseProgram ) goto failed; + if( !crtemu->Uniform1i ) goto failed; + if( !crtemu->Uniform3f ) goto failed; + if( !crtemu->GetUniformLocation ) goto failed; + if( !crtemu->TexImage2D ) goto failed; + if( !crtemu->ClearColor ) goto failed; + if( !crtemu->Clear ) goto failed; + if( !crtemu->DrawArrays ) goto failed; + if( !crtemu->Viewport ) goto failed; + if( !crtemu->DeleteShader ) goto failed; + if( !crtemu->DeleteProgram ) goto failed; + #ifdef CRTEMU_REPORT_SHADER_ERRORS + if( !crtemu->GetShaderInfoLog ) goto failed; + #endif + + crtemu->crt_shader = crtemu_internal_build_shader( crtemu, vs_source, crt_fs_source ); + if( crtemu->crt_shader == 0 ) goto failed; + + crtemu->blur_shader = crtemu_internal_build_shader( crtemu, vs_source, blur_fs_source ); + if( crtemu->blur_shader == 0 ) goto failed; + + crtemu->accumulate_shader = crtemu_internal_build_shader( crtemu, vs_source, accumulate_fs_source ); + if( crtemu->accumulate_shader == 0 ) goto failed; + + crtemu->blend_shader = crtemu_internal_build_shader( crtemu, vs_source, blend_fs_source ); + if( crtemu->blend_shader == 0 ) goto failed; + + crtemu->copy_shader = crtemu_internal_build_shader( crtemu, vs_source, copy_fs_source ); + if( crtemu->copy_shader == 0 ) goto failed; + + + crtemu->GenTextures( 1, &crtemu->accumulatetexture_a ); + crtemu->GenFramebuffers( 1, &crtemu->accumulatebuffer_a ); + + crtemu->GenTextures( 1, &crtemu->accumulatetexture_b ); + crtemu->GenFramebuffers( 1, &crtemu->accumulatebuffer_b ); + + crtemu->GenTextures( 1, &crtemu->blurtexture_a ); + crtemu->GenFramebuffers( 1, &crtemu->blurbuffer_a ); + + crtemu->GenTextures( 1, &crtemu->blurtexture_b ); + crtemu->GenFramebuffers( 1, &crtemu->blurbuffer_b ); + + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, 0 ); + + crtemu->GenTextures( 1, &crtemu->frametexture ); + #ifndef CRTEMU_WEBGL + // This enable call is not necessary when using fragment shaders, avoid logged warnings in WebGL + crtemu->Enable( CRTEMU_GL_TEXTURE_2D ); + #endif + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE2 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->frametexture ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MIN_FILTER, CRTEMU_GL_LINEAR ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MAG_FILTER, CRTEMU_GL_LINEAR ); + + crtemu->GenTextures( 1, &crtemu->backbuffer ); + #ifndef CRTEMU_WEBGL + // This enable call is not necessary when using fragment shaders, avoid logged warnings in WebGL + crtemu->Enable( CRTEMU_GL_TEXTURE_2D ); + #endif + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE0 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->backbuffer ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MIN_FILTER, CRTEMU_GL_NEAREST ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MAG_FILTER, CRTEMU_GL_NEAREST ); + + crtemu->GenBuffers( 1, &crtemu->vertexbuffer ); + crtemu->BindBuffer( CRTEMU_GL_ARRAY_BUFFER, crtemu->vertexbuffer ); + crtemu->EnableVertexAttribArray( 0 ); + crtemu->VertexAttribPointer( 0, 4, CRTEMU_GL_FLOAT, CRTEMU_GL_FALSE, 4 * sizeof( CRTEMU_GLfloat ), 0 ); + + #ifdef CRTEMU_WEBGL + // Avoid WebGL error "TEXTURE_2D at unit 0 is incomplete: Non-power-of-two textures must have a wrap mode of CLAMP_TO_EDGE." + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->accumulatetexture_a ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->accumulatetexture_b ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->blurtexture_a ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->blurtexture_b ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->frametexture ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->backbuffer ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); + #endif + + return crtemu; + +failed: + if( crtemu->accumulatetexture_a ) crtemu->DeleteTextures( 1, &crtemu->accumulatetexture_a ); + if( crtemu->accumulatebuffer_a ) crtemu->DeleteFramebuffers( 1, &crtemu->accumulatebuffer_a ); + if( crtemu->accumulatetexture_b ) crtemu->DeleteTextures( 1, &crtemu->accumulatetexture_b ); + if( crtemu->accumulatebuffer_b ) crtemu->DeleteFramebuffers( 1, &crtemu->accumulatebuffer_b ); + if( crtemu->blurtexture_a ) crtemu->DeleteTextures( 1, &crtemu->blurtexture_a ); + if( crtemu->blurbuffer_a ) crtemu->DeleteFramebuffers( 1, &crtemu->blurbuffer_a ); + if( crtemu->blurtexture_b ) crtemu->DeleteTextures( 1, &crtemu->blurtexture_b ); + if( crtemu->blurbuffer_b ) crtemu->DeleteFramebuffers( 1, &crtemu->blurbuffer_b ); + if( crtemu->frametexture ) crtemu->DeleteTextures( 1, &crtemu->frametexture ); + if( crtemu->backbuffer ) crtemu->DeleteTextures( 1, &crtemu->backbuffer ); + if( crtemu->vertexbuffer ) crtemu->DeleteBuffers( 1, &crtemu->vertexbuffer ); + + #ifndef CRTEMU_SDL + if( crtemu->gl_dll ) FreeLibrary( crtemu->gl_dll ); + #endif + CRTEMU_FREE( crtemu->memctx, crtemu ); + return 0; + } + + +void crtemu_destroy( crtemu_t* crtemu ) + { + crtemu->DeleteTextures( 1, &crtemu->accumulatetexture_a ); + crtemu->DeleteFramebuffers( 1, &crtemu->accumulatebuffer_a ); + crtemu->DeleteTextures( 1, &crtemu->accumulatetexture_b ); + crtemu->DeleteFramebuffers( 1, &crtemu->accumulatebuffer_b ); + crtemu->DeleteTextures( 1, &crtemu->blurtexture_a ); + crtemu->DeleteFramebuffers( 1, &crtemu->blurbuffer_a ); + crtemu->DeleteTextures( 1, &crtemu->blurtexture_b ); + crtemu->DeleteFramebuffers( 1, &crtemu->blurbuffer_b ); + crtemu->DeleteTextures( 1, &crtemu->frametexture ); + crtemu->DeleteTextures( 1, &crtemu->backbuffer ); + crtemu->DeleteBuffers( 1, &crtemu->vertexbuffer ); + #ifndef CRTEMU_SDL + FreeLibrary( crtemu->gl_dll ); + #endif + CRTEMU_FREE( crtemu->memctx, crtemu ); + } + + +void crtemu_config(crtemu_t* crtemu, crtemu_config_t const* config) + { + crtemu->config = *config; + } + + +void crtemu_frame( crtemu_t* crtemu, CRTEMU_U32* frame_abgr, int frame_width, int frame_height ) + { + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE3 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->frametexture ); + crtemu->TexImage2D( CRTEMU_GL_TEXTURE_2D, 0, CRTEMU_GL_RGBA, frame_width, frame_height, 0, CRTEMU_GL_RGBA, CRTEMU_GL_UNSIGNED_BYTE, frame_abgr ); + if( frame_abgr ) + crtemu->use_frame = 1.0f; + else + crtemu->use_frame = 0.0f; + } + + +static void crtemu_internal_blur( crtemu_t* crtemu, CRTEMU_GLuint source, CRTEMU_GLuint blurbuffer_a, CRTEMU_GLuint blurbuffer_b, + CRTEMU_GLuint blurtexture_b, float r, int width, int height ) + { + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, blurbuffer_b ); + crtemu->UseProgram( crtemu->blur_shader ); + crtemu->Uniform2f( crtemu->GetUniformLocation( crtemu->blur_shader, "blur" ), r / (float) width, 0 ); + crtemu->Uniform1i( crtemu->GetUniformLocation( crtemu->blur_shader, "texture" ), 0 ); + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE0 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, source ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MIN_FILTER, CRTEMU_GL_LINEAR ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MAG_FILTER, CRTEMU_GL_LINEAR ); + crtemu->DrawArrays( CRTEMU_GL_TRIANGLE_FAN, 0, 4 ); + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE0 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, 0 ); + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, 0 ); + + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, blurbuffer_a ); + crtemu->UseProgram( crtemu->blur_shader ); + crtemu->Uniform2f( crtemu->GetUniformLocation( crtemu->blur_shader, "blur" ), 0, r / (float) height ); + crtemu->Uniform1i( crtemu->GetUniformLocation( crtemu->blur_shader, "texture" ), 0 ); + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE0 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, blurtexture_b ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MIN_FILTER, CRTEMU_GL_LINEAR ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MAG_FILTER, CRTEMU_GL_LINEAR ); + crtemu->DrawArrays( CRTEMU_GL_TRIANGLE_FAN, 0, 4 ); + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE0 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, 0 ); + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, 0 ); + } + + +void crtemu_present( crtemu_t* crtemu, CRTEMU_U64 time_us, CRTEMU_U32 const* pixels_xbgr, int width, int height, + CRTEMU_U32 mod_xbgr, CRTEMU_U32 border_xbgr ) + { + int viewport[ 4 ]; + crtemu->GetIntegerv( CRTEMU_GL_VIEWPORT, viewport ); + + if( width != crtemu->last_present_width || height != crtemu->last_present_height ) + { + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE0 ); + + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->accumulatetexture_a ); + crtemu->TexImage2D( CRTEMU_GL_TEXTURE_2D, 0, CRTEMU_GL_RGB, width, height, 0, CRTEMU_GL_RGB, CRTEMU_GL_UNSIGNED_BYTE, 0 ); + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, crtemu->accumulatebuffer_a ); + crtemu->FramebufferTexture2D( CRTEMU_GL_FRAMEBUFFER, CRTEMU_GL_COLOR_ATTACHMENT0, CRTEMU_GL_TEXTURE_2D, crtemu->accumulatetexture_a, 0 ); + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, 0 ); + + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->accumulatetexture_b ); + crtemu->TexImage2D( CRTEMU_GL_TEXTURE_2D, 0, CRTEMU_GL_RGB, width, height, 0, CRTEMU_GL_RGB, CRTEMU_GL_UNSIGNED_BYTE, 0 ); + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, crtemu->accumulatebuffer_b ); + crtemu->FramebufferTexture2D( CRTEMU_GL_FRAMEBUFFER, CRTEMU_GL_COLOR_ATTACHMENT0, CRTEMU_GL_TEXTURE_2D, crtemu->accumulatetexture_b, 0 ); + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, 0 ); + + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->blurtexture_a ); + crtemu->TexImage2D( CRTEMU_GL_TEXTURE_2D, 0, CRTEMU_GL_RGB, width, height, 0, CRTEMU_GL_RGB, CRTEMU_GL_UNSIGNED_BYTE, 0 ); + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, crtemu->blurbuffer_a ); + crtemu->FramebufferTexture2D( CRTEMU_GL_FRAMEBUFFER, CRTEMU_GL_COLOR_ATTACHMENT0, CRTEMU_GL_TEXTURE_2D, crtemu->blurtexture_a, 0 ); + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, 0 ); + + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->blurtexture_b ); + crtemu->TexImage2D( CRTEMU_GL_TEXTURE_2D, 0, CRTEMU_GL_RGB, width, height, 0, CRTEMU_GL_RGB, CRTEMU_GL_UNSIGNED_BYTE, 0 ); + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, crtemu->blurbuffer_b ); + crtemu->FramebufferTexture2D( CRTEMU_GL_FRAMEBUFFER, CRTEMU_GL_COLOR_ATTACHMENT0, CRTEMU_GL_TEXTURE_2D, crtemu->blurtexture_b, 0 ); + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, 0 ); + } + + + crtemu->last_present_width = width; + crtemu->last_present_height = height; + + CRTEMU_GLfloat vertices[] = + { + -1.0f, -1.0f, 0.0f, 0.0f, + 1.0f, -1.0f, 1.0f, 0.0f, + 1.0f, 1.0f, 1.0f, 1.0f, + -1.0f, 1.0f, 0.0f, 1.0f, + }; + crtemu->BufferData( CRTEMU_GL_ARRAY_BUFFER, 4 * 4 * sizeof( CRTEMU_GLfloat ), vertices, CRTEMU_GL_STATIC_DRAW ); + crtemu->BindBuffer( CRTEMU_GL_ARRAY_BUFFER, crtemu->vertexbuffer ); + + // Copy to backbuffer + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE0 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->backbuffer ); + crtemu->TexImage2D( CRTEMU_GL_TEXTURE_2D, 0, CRTEMU_GL_RGBA, width, height, 0, CRTEMU_GL_RGBA, CRTEMU_GL_UNSIGNED_BYTE, pixels_xbgr ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, 0 ); + + crtemu->Viewport( 0, 0, width, height ); + + // Blur the previous accumulation buffer + crtemu_internal_blur( crtemu, crtemu->accumulatetexture_b, crtemu->blurbuffer_a, crtemu->blurbuffer_b, crtemu->blurtexture_b, 1.0f, width, height ); + + // Update accumulation buffer + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, crtemu->accumulatebuffer_a ); + crtemu->UseProgram( crtemu->accumulate_shader ); + crtemu->Uniform1i( crtemu->GetUniformLocation( crtemu->accumulate_shader, "tex0" ), 0 ); + crtemu->Uniform1i( crtemu->GetUniformLocation( crtemu->accumulate_shader, "tex1" ), 1 ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->accumulate_shader, "modulate" ), 1.0f ); + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE0 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->backbuffer ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MIN_FILTER, CRTEMU_GL_LINEAR ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MAG_FILTER, CRTEMU_GL_LINEAR ); + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE1 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->blurtexture_a ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MIN_FILTER, CRTEMU_GL_LINEAR ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MAG_FILTER, CRTEMU_GL_LINEAR ); + crtemu->DrawArrays( CRTEMU_GL_TRIANGLE_FAN, 0, 4 ); + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE0 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, 0 ); + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE1 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, 0 ); + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, 0 ); + + + // Store a copy of the accumulation buffer + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, crtemu->accumulatebuffer_b ); + crtemu->UseProgram( crtemu->copy_shader ); + crtemu->Uniform1i( crtemu->GetUniformLocation( crtemu->copy_shader, "tex0" ), 0 ); + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE0 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->accumulatetexture_a ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MIN_FILTER, CRTEMU_GL_LINEAR ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MAG_FILTER, CRTEMU_GL_LINEAR ); + crtemu->DrawArrays( CRTEMU_GL_TRIANGLE_FAN, 0, 4 ); + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE0 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, 0 ); + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, 0 ); + + // Blend accumulation and backbuffer + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, crtemu->accumulatebuffer_a ); + crtemu->UseProgram( crtemu->blend_shader ); + crtemu->Uniform1i( crtemu->GetUniformLocation( crtemu->blend_shader, "tex0" ), 0 ); + crtemu->Uniform1i( crtemu->GetUniformLocation( crtemu->blend_shader, "tex1" ), 1 ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->blend_shader, "modulate" ), 1.0f ); + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE0 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->backbuffer ); + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE1 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->accumulatetexture_b ); + crtemu->DrawArrays( CRTEMU_GL_TRIANGLE_FAN, 0, 4 ); + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE0 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, 0 ); + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE1 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, 0 ); + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, 0 ); + + + // Add slight blur to backbuffer + crtemu_internal_blur( crtemu, crtemu->accumulatetexture_a, crtemu->accumulatebuffer_a, crtemu->blurbuffer_b, crtemu->blurtexture_b, 0.17f, width, height ); + + // Create fully blurred version of backbuffer + crtemu_internal_blur( crtemu, crtemu->accumulatetexture_a, crtemu->blurbuffer_a, crtemu->blurbuffer_b, crtemu->blurtexture_b, 1.0f, width, height ); + + + // Present to screen with CRT shader + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, 0 ); + + crtemu->Viewport( viewport[ 0 ], viewport[ 1 ], viewport[ 2 ], viewport[ 3 ] ); + + int window_width = viewport[ 2 ] - viewport[ 0 ]; + int window_height = viewport[ 3 ] - viewport[ 1 ]; + + int aspect_width = (int)( ( window_height * 4 ) / 3 ); + int aspect_height= (int)( ( window_width * 3 ) / 4 ); + int target_width, target_height; + if( aspect_height <= window_height ) + { + target_width = window_width; + target_height = aspect_height; + } + else + { + target_width = aspect_width; + target_height = window_height; + } + + float hscale = target_width / (float) width; + float vscale = target_height / (float) height; + + float hborder = ( window_width - hscale * width ) / 2.0f; + float vborder = ( window_height - vscale * height ) / 2.0f; + float x1 = hborder; + float y1 = vborder; + float x2 = x1 + hscale * width; + float y2 = y1 + vscale * height; + + x1 = ( x1 / window_width ) * 2.0f - 1.0f; + x2 = ( x2 / window_width ) * 2.0f - 1.0f; + y1 = ( y1 / window_height ) * 2.0f - 1.0f; + y2 = ( y2 / window_height ) * 2.0f - 1.0f; + + CRTEMU_GLfloat screen_vertices[] = + { + 0.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 1.0f, + 0.0f, 0.0f, 0.0f, 1.0f, + }; + screen_vertices[ 0 ] = x1; + screen_vertices[ 1 ] = y1; + screen_vertices[ 4 ] = x2; + screen_vertices[ 5 ] = y1; + screen_vertices[ 8 ] = x2; + screen_vertices[ 9 ] = y2; + screen_vertices[ 12 ] = x1; + screen_vertices[ 13 ] = y2; + + crtemu->BufferData( CRTEMU_GL_ARRAY_BUFFER, 4 * 4 * sizeof( CRTEMU_GLfloat ), screen_vertices, CRTEMU_GL_STATIC_DRAW ); + crtemu->BindBuffer( CRTEMU_GL_ARRAY_BUFFER, crtemu->vertexbuffer ); + + float r = ( ( border_xbgr >> 16 ) & 0xff ) / 255.0f; + float g = ( ( border_xbgr >> 8 ) & 0xff ) / 255.0f; + float b = ( ( border_xbgr ) & 0xff ) / 255.0f; + crtemu->ClearColor( r, g, b, 1.0f ); + crtemu->Clear( CRTEMU_GL_COLOR_BUFFER_BIT ); + + crtemu->UseProgram( crtemu->crt_shader ); + + crtemu->Uniform1i( crtemu->GetUniformLocation( crtemu->crt_shader, "backbuffer" ), 0 ); + crtemu->Uniform1i( crtemu->GetUniformLocation( crtemu->crt_shader, "blurbuffer" ), 1 ); + crtemu->Uniform1i( crtemu->GetUniformLocation( crtemu->crt_shader, "frametexture" ), 2 ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "use_frame" ), crtemu->use_frame ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "time" ), 1.5f * (CRTEMU_GLfloat)( ( (double) time_us ) / 1000000.0 ) ); + crtemu->Uniform2f( crtemu->GetUniformLocation( crtemu->crt_shader, "resolution" ), (float) window_width, (float) window_height ); + crtemu->Uniform2f( crtemu->GetUniformLocation( crtemu->crt_shader, "size" ), (float) target_width, (float) target_height ); + + float mod_r = ( ( mod_xbgr >> 16 ) & 0xff ) / 255.0f; + float mod_g = ( ( mod_xbgr >> 8 ) & 0xff ) / 255.0f; + float mod_b = ( ( mod_xbgr ) & 0xff ) / 255.0f; + crtemu->Uniform3f( crtemu->GetUniformLocation( crtemu->crt_shader, "modulate" ), mod_r, mod_g, mod_b ); + + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "cfg_curvature" ), crtemu->config.curvature ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "cfg_scanlines" ), crtemu->config.scanlines ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "cfg_shadow_mask" ), crtemu->config.shadow_mask ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "cfg_separation" ), crtemu->config.separation ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "cfg_ghosting" ), crtemu->config.ghosting ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "cfg_noise" ), crtemu->config.noise ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "cfg_flicker" ), crtemu->config.flicker ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "cfg_vignette" ), crtemu->config.vignette ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "cfg_distortion" ), crtemu->config.distortion ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "cfg_aspect_lock" ), crtemu->config.aspect_lock ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "cfg_hpos" ), crtemu->config.hpos ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "cfg_vpos" ), crtemu->config.vpos ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "cfg_hsize" ), crtemu->config.hsize ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "cfg_vsize" ), crtemu->config.vsize ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "cfg_contrast" ), crtemu->config.contrast ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "cfg_brightness" ), crtemu->config.brightness ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "cfg_saturation" ), crtemu->config.saturation ); + crtemu->Uniform1f( crtemu->GetUniformLocation( crtemu->crt_shader, "cfg_degauss" ), crtemu->config.degauss ); + + float color[] = { 0.0f, 0.0f, 0.0f, 0.0f }; + + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE0 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->accumulatetexture_a ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MIN_FILTER, CRTEMU_GL_LINEAR ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MAG_FILTER, CRTEMU_GL_LINEAR ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_WRAP_S, CRTEMU_GL_CLAMP_TO_BORDER ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_WRAP_T, CRTEMU_GL_CLAMP_TO_BORDER ); + #ifndef CRTEMU_WEBGL + crtemu->TexParameterfv( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_BORDER_COLOR, color ); + #endif + + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE1 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->blurtexture_a ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MIN_FILTER, CRTEMU_GL_LINEAR ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MAG_FILTER, CRTEMU_GL_LINEAR ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_WRAP_S, CRTEMU_GL_CLAMP_TO_BORDER ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_WRAP_T, CRTEMU_GL_CLAMP_TO_BORDER ); + #ifndef CRTEMU_WEBGL + crtemu->TexParameterfv( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_BORDER_COLOR, color ); + #endif + + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE3 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, crtemu->frametexture ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MIN_FILTER, CRTEMU_GL_LINEAR ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_MAG_FILTER, CRTEMU_GL_LINEAR ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_WRAP_S, CRTEMU_GL_CLAMP_TO_BORDER ); + crtemu->TexParameteri( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_WRAP_T, CRTEMU_GL_CLAMP_TO_BORDER ); + #ifndef CRTEMU_WEBGL + crtemu->TexParameterfv( CRTEMU_GL_TEXTURE_2D, CRTEMU_GL_TEXTURE_BORDER_COLOR, color ); + #endif + + crtemu->DrawArrays( CRTEMU_GL_TRIANGLE_FAN, 0, 4 ); + + crtemu->ActiveTexture( CRTEMU_GL_TEXTURE0 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, 0 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, 1 ); + crtemu->BindTexture( CRTEMU_GL_TEXTURE_2D, 2 ); + crtemu->BindFramebuffer( CRTEMU_GL_FRAMEBUFFER, 0 ); + } + + +void crtemu_coordinates_window_to_bitmap( crtemu_t* crtemu, int width, int height, int* x, int* y ) + { + CRTEMU_GLint viewport[ 4 ]; + crtemu->GetIntegerv( CRTEMU_GL_VIEWPORT, viewport ); + + int window_width = viewport[ 2 ] - viewport[ 0 ]; + int window_height = viewport[ 3 ] - viewport[ 1 ]; + + int aspect_width = (int)( ( window_height * 4 ) / 3 ); + int aspect_height= (int)( ( window_width * 3 ) / 4 ); + int target_width, target_height; + if( aspect_height <= window_height ) + { + target_width = window_width; + target_height = aspect_height; + } + else + { + target_width = aspect_width; + target_height = window_height; + } + + float hscale = target_width / (float) width; + float vscale = target_height / (float) height; + + float hborder = ( window_width - hscale * width ) / 2.0f; + float vborder = ( window_height - vscale * height ) / 2.0f; + + float xp = ( ( *x - hborder ) / hscale ) / (float) width; + float yp = ( ( *y - vborder ) / vscale ) / (float) height; + + /* TODO: Common params for shader and this */ + float xc = ( xp - 0.5f ) * 2.0f; + float yc = ( yp - 0.5f ) * 2.0f; + xc *= 1.1f; + yc *= 1.1f; + //xc *= 1.0f + powf( ( fabsf( yc ) / 5.0f ), 2.0f); + //yc *= 1.0f + powf( ( fabsf( xc ) / 4.0f ), 2.0f); + float yt = ( yc >= 0.0f ? yc : -yc ) / 5.0f; + float xt = ( xc >= 0.0f ? xc : -xc ) / 4.0f; + xc *= 1.0f + ( yt * yt ); + yc *= 1.0f + ( xt * xt ); + xc = ( xc / 2.0f ) + 0.5f; + yc = ( yc / 2.0f ) + 0.5f; + xc = xc * 0.92f + 0.04f; + yc = yc * 0.92f + 0.04f; + xp = xc * 0.6f + xp * 0.4f; + yp = yc * 0.6f + yp * 0.4f; + + xp = xp * ( 1.0f - 0.04f ) + 0.04f / 2.0f + 0.003f; + yp = yp * ( 1.0f - 0.04f ) + 0.04f / 2.0f - 0.001f; + + xp = xp * 1.025f - 0.0125f; + yp = yp * 0.92f + 0.04f; + + xp *= width; + yp *= height; + + *x = (int) ( xp ); + *y = (int) ( yp ); + } + + +void crtemu_coordinates_bitmap_to_window( crtemu_t* crtemu, int width, int height, int* x, int* y ) + { + (void) crtemu, (void) width, (void) height, (void) x, (void) y; // TODO: implement + } + + +#endif /* CRTEMU_IMPLEMENTATION */ + +/* +------------------------------------------------------------------------------ + +This software is available under 2 licenses - you may choose the one you like. + +------------------------------------------------------------------------------ + +ALTERNATIVE A - MIT License + +Copyright (c) 2016 Mattias Gustavsson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------------------------------------------------------------------ + +ALTERNATIVE B - Public Domain (www.unlicense.org) + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +------------------------------------------------------------------------------ +*/ diff --git a/dialog.h b/dialog.h new file mode 100644 index 0000000..1900789 --- /dev/null +++ b/dialog.h @@ -0,0 +1,1086 @@ +/* +------------------------------------------------------------------------------ + Licensing information can be found at the end of the file. +------------------------------------------------------------------------------ + +dialog.h - v0.1 - Loading and management of dialog definitions. + +This library provides functionality to load and manage dialogs written in a +custom markup language designed for simplicity and readability. + +The dialog definition files contain any number of "conversations". Each +conversation is made up of any number of entries. An entry can be any of the +following: a line of speech, an option, a redirect command, or an event +command. + +A conversation is defined by giving it an ID within square brackets ( [, ] ). +Two conversation IDs should be considered reserved: EXIT and RETURN. The +first of these means that the dialog is over for now and should be stopped, +and the second means to return to the conversation from which we came (if +there is no conversation to return to, the dialog should be stopped). + +A line of speech consists of an actor name within angled brackets ( <, > ) +followed by the actual ine. + +An option (as may be selected by a player) starts with the character ^. If it +starts with two of that character, ^^, it means that the option is persistent +and thus shall not be removed (the normal behaviour is that options are +removed from the list after being chosen once). After the ^ or ^^ is the line +which will be spoken if the option is chosen. Last, the line has the +character @ followed by the ID of the conversation to jump to should that +option be chosen. + +A redirect command is simply the @ character followed by the ID of the +conversation to jump to when execution reaches this command. + +Finally, an event command is any string surrounded by # characters. This can +be used to send a custom message to the game engine, to signal that something +should happen. + +Here follows an example dialog file from "The Strangler": + + [TalkToBambi] + ^ Sorry to *bother* you, ma'am. I need to ask you some *questions*. @YouAcop + ^ Well well well... ain't you a *classy* one. @Classy + ^ Excuse me, do you know a woman by the name of Amber? @Amber + ^^ I don't have any more questions right now. @EXIT + + [YouAcop] + You a *cop* or something? Fuck off. + *Believe* me, I hate those *bastards* just as much as you do. + @RETURN + + [Classy] + Errr.. No *offense*, pal, but you're not exactly one to *talk*. + @RETURN + + [Amber] + I knew Amber. But Amber is *dead*. + @RETURN + + [ShowPicture] + Have you seen this man around? + Yeah, I've seen him with some of the *girls*. + Did you see him with Amber last night? + I *did*, now that you *mention* it... + Any idea where he might have taken her? + Probably to this *motel*... that's where he'd usually go.... + #UnlockMotel# + +*/ + +#ifndef dialog_h +#define dialog_h + +typedef struct dialog_t dialog_t; + +dialog_t* dialog_create( char const* input, int input_size ); +void dialog_destroy( dialog_t* dialog ); + +int dialog_save( dialog_t const* dialog, void* data, int capacity ); +dialog_t* dialog_load( void const* data, int size ); +void dialog_unload( dialog_t* dialog ); + +typedef struct dialog_conversation_t { int handle; } dialog_conversation_t; +typedef struct dialog_entry_t { int handle; } dialog_entry_t; +typedef struct dialog_line_t { int handle; } dialog_line_t; +typedef struct dialog_option_t { int handle; } dialog_option_t; +typedef struct dialog_redirect_t { int handle; } dialog_redirect_t; +typedef struct dialog_event_t { int handle; } dialog_event_t; + +typedef enum dialog_entry_type_t { + DIALOG_ENTRY_TYPE_INVALID = -1, + DIALOG_ENTRY_TYPE_LINE, + DIALOG_ENTRY_TYPE_OPTION, + DIALOG_ENTRY_TYPE_REDIRECT, + DIALOG_ENTRY_TYPE_EVENT, +} dialog_entry_type_t; + +int dialog_find_conversation( dialog_t const* dialog, char const* id ); + +int dialog_conversation_count( dialog_t const* dialog ); +dialog_conversation_t dialog_conversation( dialog_t const* dialog, int index ); + +char const* dialog_conversation_id( dialog_t const* dialog, dialog_conversation_t conversation ); +int dialog_conversation_entry_count( dialog_t const* dialog, dialog_conversation_t conversation ); +dialog_entry_t dialog_conversation_entry( dialog_t const* dialog, dialog_conversation_t conversation, int index ); + +char const* dialog_entry_id( dialog_t const* dialog, dialog_entry_t entry ); +dialog_entry_type_t dialog_entry_type( dialog_t const* dialog, dialog_entry_t entry ); +dialog_line_t dialog_entry_line( dialog_t const* dialog, dialog_entry_t entry ); +dialog_option_t dialog_entry_option( dialog_t const* dialog, dialog_entry_t entry ); +dialog_redirect_t dialog_entry_redirect( dialog_t const* dialog, dialog_entry_t entry ); +dialog_event_t dialog_entry_event( dialog_t const* dialog, dialog_entry_t entry ); + +char const* dialog_line_actor( dialog_t const* dialog, dialog_line_t line ); +char const* dialog_line_text( dialog_t const* dialog, dialog_line_t line ); + +char const* dialog_option_text( dialog_t const* dialog, dialog_option_t option ); +char const* dialog_option_target( dialog_t const* dialog, dialog_option_t option ); +int dialog_option_is_persistent( dialog_t const* dialog, dialog_option_t option ); + +char const* dialog_redirect_target( dialog_t const* dialog, dialog_redirect_t redirect ); + +char const* dialog_event_event( dialog_t const* dialog, dialog_event_t event ); + + +#endif /* dialog_h */ + + +/* +void test_dialog( dialog_t* dialog ) { + for( int i = 0; i < dialog_conversation_count( dialog ); ++i ) { + dialog_conversation_t conversation = dialog_conversation( dialog, i ); + printf( "\n[%s]\n", dialog_conversation_id( dialog, conversation ) ); + for( int j = 0; j < dialog_conversation_entry_count( dialog, conversation ); ++j ) { + dialog_entry_t entry = dialog_conversation_entry( dialog, conversation, j ); + dialog_entry_type_t type = dialog_entry_type( dialog, entry ); + char const* id = dialog_entry_id( dialog, entry ); + if( id ) { + printf( "{%s}", id ); + } + + if( type == DIALOG_ENTRY_TYPE_LINE ) { + dialog_line_t line = dialog_entry_line( dialog, entry ); + printf("<%s>%s", dialog_line_actor( dialog, line ), dialog_line_text( dialog, line ) ); + } else if( type == DIALOG_ENTRY_TYPE_OPTION ) { + dialog_option_t option = dialog_entry_option( dialog, entry ); + if( dialog_option_is_persistent( dialog, option ) ) { + printf( "^" ); + } + printf("^%s@%s", dialog_option_text( dialog, option ), dialog_option_target( dialog, option ) ); + } else if( type == DIALOG_ENTRY_TYPE_REDIRECT ) { + dialog_redirect_t redirect = dialog_entry_redirect( dialog, entry ); + printf("@%s", dialog_redirect_target( dialog, redirect ) ); + } else if( type == DIALOG_ENTRY_TYPE_EVENT ) { + dialog_event_t event = dialog_entry_event( dialog, entry ); + printf("#%s#", dialog_event_event( dialog, event ) ); + } + printf( "|\n" ); + } + } +} +*/ +/* +---------------------- + IMPLEMENTATION +---------------------- +*/ + + +#ifdef DIALOG_IMPLEMENTATION + +#define _CRT_NONSTDC_NO_DEPRECATE +#define _CRT_SECURE_NO_WARNINGS +#define wait PIXIE_STD_WAIT /* osx defines a conflicting "wait" */ +#include +#undef wait +#include + + +typedef struct dialog_parse_line_t { + char* actor; + char* text; +} dialog_parse_line_t; + + +typedef struct dialog_parse_option_t { + char* text; + char* target; + int is_persistant; +} dialog_parse_option_t; + + +typedef struct dialog_parse_redirect_t { + char* target; +} dialog_parse_redirect_t; + + +typedef struct dialog_parse_event_t { + char* event; +} dialog_parse_event_t; + + +typedef struct dialog_parse_entry_t { + char* id; // TODO: change this to "condition", which should work similar to events - the player will be in a "waiting for condition" state, and once it gets the result, either do the line or not + dialog_entry_type_t type; + union { + struct dialog_parse_line_t line; + struct dialog_parse_option_t option; + struct dialog_parse_redirect_t redirect; + struct dialog_parse_event_t event; + } data; +} dialog_parse_entry_t; + + +typedef struct dialog_parse_convo_t { + char* id; + int entries_count; + int entries_capacity; + dialog_parse_entry_t* entries; +} dialog_parse_convo_t; + + +typedef struct dialog_parse_t { + int conversations_count; + int conversations_capacity; + dialog_parse_convo_t* conversations; +} dialog_parse_t; + + +int dialog_parse_line( dialog_parse_line_t* parse, char const* start, char const* end ) { + // A Line is defined like this: + // LineText + + // If the row doesn't start with '<', it's not a valid line + if( *start != '<' ) return 0; + ++start; // Skip leading bracket + + // Find end bracket + char const* actor_end = start; + while( *actor_end != '>' && actor_end < end ) ++actor_end; + + // If there's no ending '>', it's not a valid line + if( (*actor_end) != '>' ) return 0; + + // Store actor name + parse->actor = (char*) malloc( (size_t)( actor_end - start + 1 ) ); + strncpy( parse->actor, start, (size_t)( actor_end - start ) ); + parse->actor[ actor_end - start ] = '\0'; + + // Parse line text + start = actor_end + 1; // Skip past the ending bracket of the actor name + while( start < end && *start <= ' ' ) ++start; // Skip leading whitespace + + // Store line text + parse->text = (char*) malloc( (size_t)( end - start + 1 ) ); + strncpy( parse->text, start, (size_t)( end - start ) ); + parse->text[ end - start ] = '\0'; + + // Respect escape codes for line breaks + char* str = parse->text; + char* out = parse->text; + while( *str ) { + if( *str == '\\' && *( str + 1 ) == 'n' ) { + *out++ = '\n'; + str += 2; + } else { + *out++ = *str++; + } + } + + // If we don't have both a valid actor and a valid line, this row is invalid + if( !parse->actor || *parse->actor == '\0' || !parse->text || *parse->text == '\0' ) { + if( parse->actor ) free( parse->actor ); + if( parse->text ) free( parse->text ); + parse->actor = NULL; + parse->text = NULL; + return 0; + } + + // This is a valid row + return 1; +} + + +int dialog_parse_option( dialog_parse_option_t* parse, char const* start, char const* end ) { + // An Option is defined like this: + // ^OptionText@TargetId + // + // Or, for a persistent option: + // ^^OptionText@TargetId + + // If the row doesn't start with '^', it's not a valid option + if( *start != '^' ) return 0; + ++start; // Skip leading '^' + + // If the second character is also '^', this is a persistent option + if( *start == '^' ) { + parse->is_persistant = 1; + ++start; // Skip second '^' + } + else { + parse->is_persistant = 0; // This is not a persistent option + } + + // Skip leading whitespace + while( start < end && *start <= ' ' ) ++start; + + // If the rest of the row is empty, it is not a valid option + if( start == end ) return 0; + + // Find the '@' character + char const* target = start; + while( *target != '@' && target < end ) ++target; + + // If there isn't an '@' character, this is not a valid option + if( *target != '@' ) return 0; + + // Trim trailing whitespace + char const* trim = target - 1; + while( trim > start && *trim <= ' ' ) --trim; + + // Store option text + parse->text = (char*) malloc( (size_t)( trim - start + 1 ) ); + strncpy( parse->text, start, (size_t)( trim - start ) ); + parse->text[ trim - start ] = '\0'; + + // Parse target id + ++target; // Skip the '@' character + + // Skip leading whitespace + while( target < end && *target <= ' ' ) ++target; + + // Store target id + parse->target = (char*) malloc( (size_t)( end - target + 1 ) ); + strncpy( parse->target, target, (size_t)( end - target ) ); + parse->target[ end - target ] = '\0'; + + // If option text or target id are empty, this is not a valid option + // If we don't have both a valid actor and a valid line, this row is invalid + if( !parse->text || *parse->text == '\0' || !parse->target || *parse->target == '\0' ) { + if( parse->text ) free( parse->text ); + if( parse->target ) free( parse->target ); + parse->text = NULL; + parse->target = NULL; + return 0; + } + + return 1; +} + + +int dialog_parse_redirect( dialog_parse_redirect_t* parse, char const* start, char const* end ) { + // A Redirect is defined like this: + // @TargetId + + // If row doesn't start with '@', it is not a valid redirect + if( *start != '@' ) return 0; + ++start; // Skip the '@' character + + // Skip leading whitespace + while( start < end && *start <= ' ' ) ++start; + + // Store target id + parse->target = (char*) malloc( (size_t)( end - start + 1 ) ); + strncpy( parse->target, start, (size_t)( end - start ) ); + parse->target[ end - start ] = '\0'; + + // If we don't have a valid target id, this is not a valid redirect + if( !parse->target || *parse->target == '\0' ) { + if( parse->target ) free( parse->target ); + parse->target = NULL; + return 0; + } + + return 1; +} + + +int dialog_parse_event( dialog_parse_event_t* parse, char const* start, char const* end ) { + // An Event is defined like this: + // #eventName# + + // If the row doesn't start with '#', it's not a valid event + if( *start != '#' ) return 0; + ++start; // Skip leading '#' + + // If there's no trailing '#', this is not a valid event + if( *--end != '#' ) return 0; + + // Store event string + parse->event = (char*) malloc( (size_t)( end - start + 1 ) ); + strncpy( parse->event, start, (size_t)( end - start ) ); + parse->event[ end - start ] = '\0'; + + // If we don't have a valid event name, it's not a valid event + if( !parse->event || *parse->event == '\0' ) { + if( parse->event ) free( parse->event ); + parse->event = NULL; + return 0; + } + + // Indicate that this is a valid event + return 1; +} + + +int dialog_parse_entry( dialog_parse_entry_t* parse, char const* start, char const* end ) { + char const* row = start; + + // Strip id (text defined {like_this} is an id) from the start of the row + if( *row == '{' && strchr( row, '}' ) != 0 ) + { + const char* id = ++row; + while( row < end && *row != '}' ) ++row; + parse->id = (char*) malloc( (size_t)( row - id + 1 ) ); + strncpy( parse->id, id, (size_t)( row - id ) ); + parse->id[ row - id ] = '\0'; + ++row; + while( row < end && *row <= ' ' ) ++row; + } + + if( *row == '<' ) { // Check if this is a line + parse->type = DIALOG_ENTRY_TYPE_LINE; + return dialog_parse_line( &parse->data.line, row, end ); + } else if( *row == '^' ) { // Check if this is an option + parse->type = DIALOG_ENTRY_TYPE_OPTION; + return dialog_parse_option( &parse->data.option, row, end ); + } else if( *row == '@' ) { // Check if this is a redirect + parse->type = DIALOG_ENTRY_TYPE_REDIRECT; + return dialog_parse_redirect( &parse->data.redirect, row, end ); + } else if( *row == '#' && *( end - 1 ) == '#' && ( end - row ) > 2 ) { // Check if this is an event + parse->type = DIALOG_ENTRY_TYPE_EVENT; + return dialog_parse_event( &parse->data.event, row, end ); + } else { // Not a valid row + return 0; + } +} + + +static int dialog_parse_row( dialog_parse_convo_t* parse, char const* start, char const* end ) { + // Block definition? + size_t length = (size_t)( end - start ); + if( *start == '[' && start[ length - 1 ] == ']' ) + { + if( !parse->id ) // We only deal with the id if this is a new block + { + parse->id = (char*) malloc( (size_t)( length - 1 ) ); + strncpy( parse->id, start + 1, length - 2 ); + parse->id[ length - 2 ] = '\0'; + return 1; // Indicate that row was parsed ok + } + + // We have reached the end of the conversation + return 0; // Indicate that row has not been parsed (new conversation) + } + + // Entry + dialog_parse_entry_t entry; + memset( &entry, 0, sizeof( entry ) ); + if( dialog_parse_entry( &entry, start, end ) ) { // Parse the row as an entry + if( parse->entries_count >= parse->entries_capacity ) { + parse->entries_capacity *= 2; + parse->entries = (dialog_parse_entry_t*) realloc( parse->entries, + sizeof( dialog_parse_entry_t ) * parse->entries_capacity ); + } + parse->entries[ parse->entries_count++ ] = entry; + } else { + // TODO: Warn about failed parse + if( entry.id ) free( entry.id ); + } + + return 1; // Indicate that row was parsed ok +} + + +static void dialog_parse( dialog_parse_t* parse, char const* buffer, int size ) { + dialog_parse_convo_t current = { 0 }; + current.entries_count = 0; + current.entries_capacity = 256; + current.entries = (dialog_parse_entry_t*) malloc( sizeof( dialog_parse_entry_t ) * current.entries_capacity ); + + // extract rows + for( char const* ptr = buffer; ptr - buffer < size; ++ptr ) { + char const* row_start = ptr; + + // skip forward until next line break + while( *ptr != '\n' && ptr - buffer < size ) ++ptr; + + // only bother with non-zero length rows + if( ptr - row_start > 1 ) { + char const* row = row_start; + char const* row_end = ptr; + + // skip leading whitespace + char const* start = row; + while ( start < row_end && *start <= ' ' ) ++start; + row = start; + + // skip trailing whitespace + start = row; + char const* end = row_end; + while( *end <= ' ' && end > start ) --end; + ++end; + + // only bother with non-zero length rows + if( end - start > 0 ) { + // parse row + int parse_result = dialog_parse_row( ¤t, start, end ); + if( !parse_result ) { // if we're on a new conversation + // new conversation, so insert the current one into the list if it is valid + if( current.id ) { + if( parse->conversations_count >= parse->conversations_capacity ) { + parse->conversations_capacity *= 2; + parse->conversations = (dialog_parse_convo_t*) realloc( parse->conversations, + sizeof( dialog_parse_convo_t ) * parse->conversations_capacity ); + } + parse->conversations[ parse->conversations_count++ ] = current; + } else { + free( current.entries ); + } + + // and then start a new conversation + current.id = 0; + current.entries_count = 0; + current.entries_capacity = 256; + current.entries = (dialog_parse_entry_t*) malloc( sizeof( dialog_parse_entry_t ) * current.entries_capacity ); + dialog_parse_row( ¤t, start, end ); + } + } + } + } + + // if the current conversation is valid, add it to the list + if( current.id ) { + if( parse->conversations_count >= parse->conversations_capacity ) { + parse->conversations_capacity *= 2; + parse->conversations = (dialog_parse_convo_t*) realloc( parse->conversations, + sizeof( dialog_parse_convo_t ) * parse->conversations_capacity ); + } + parse->conversations[ parse->conversations_count++ ] = current; + } else { + free( current.entries ); + } +} + + +typedef struct dialog_data_t { + int type; + union { + struct { + int actor_offset; + int text_offset; + } line; + + struct { + int text_offset; + int target_offset; + int is_persistant; + } option; + + struct { + int target_offset; + } redirect; + + struct { + int event_offset; + } event; + + struct { + int id_offset; + int entries_count; + int entry_list_start_index; + } conversation; + + struct { + int id_offset; + int entry_index; + int entry_list_next_index; + } entry_list; + + } data; +} dialog_data_t; + + +struct dialog_t { + int size_in_bytes; + int conversation_count; + int data_count; + dialog_data_t data[ 1 ]; +}; + + +#define DIALOG_ENTRY_TYPE_CONVERSATION 4 +#define DIALOG_ENTRY_TYPE_ENTRY_LIST 5 + + +dialog_t* dialog_create( char const* input, int input_size ) { + dialog_parse_t parse; + parse.conversations_count = 0; + parse.conversations_capacity = 256; + parse.conversations = (dialog_parse_convo_t*) malloc( sizeof( dialog_parse_convo_t ) * parse.conversations_capacity ); + dialog_parse( &parse, input, input_size ); + int total_size = sizeof( dialog_t ) - sizeof( dialog_data_t ); + total_size += parse.conversations_count * sizeof( dialog_data_t ); + int entry_list_count = 0; + int entries_count = 0; + for( int i = 0; i < parse.conversations_count; ++i ) { + total_size += (int)strlen( parse.conversations[ i ].id ) + 1; + total_size += parse.conversations[ i ].entries_count * sizeof( dialog_data_t ); + entry_list_count += parse.conversations[ i ].entries_count; + for( int j = 0; j < parse.conversations[ i ].entries_count; ++j ) { + ++entries_count; + total_size += sizeof( dialog_data_t ); + if( parse.conversations[ i ].entries[ j ].id ) { + total_size += (int)strlen( parse.conversations[ i ].entries[ j ].id ) + 1; + } + if( parse.conversations[ i ].entries[ j ].type == DIALOG_ENTRY_TYPE_LINE ) { + total_size += (int)strlen( parse.conversations[ i ].entries[ j ].data.line.actor ) + 1; + total_size += (int)strlen( parse.conversations[ i ].entries[ j ].data.line.text ) + 1; + } else if( parse.conversations[ i ].entries[ j ].type == DIALOG_ENTRY_TYPE_OPTION ) { + total_size += (int)strlen( parse.conversations[ i ].entries[ j ].data.option.text ) + 1; + total_size += (int)strlen( parse.conversations[ i ].entries[ j ].data.option.target ) + 1; + } else if( parse.conversations[ i ].entries[ j ].type == DIALOG_ENTRY_TYPE_REDIRECT ) { + total_size += (int)strlen( parse.conversations[ i ].entries[ j ].data.redirect.target ) + 1; + } else if( parse.conversations[ i ].entries[ j ].type == DIALOG_ENTRY_TYPE_EVENT ) { + total_size += (int)strlen( parse.conversations[ i ].entries[ j ].data.event.event ) + 1; + } + } + } + + dialog_t* dialog = (dialog_t*) malloc( (size_t) total_size ); + dialog->size_in_bytes = total_size; + dialog->conversation_count = parse.conversations_count; + int next_index = parse.conversations_count; + char* text_data = (char*)( dialog->data + parse.conversations_count + entry_list_count + entries_count ); + int text_offset = (int)( text_data - (char*)dialog ); + for( int i = 0; i < parse.conversations_count; ++i ) { + dialog_data_t* conversation = &dialog->data[ i ]; + conversation->type = DIALOG_ENTRY_TYPE_CONVERSATION; + conversation->data.conversation.id_offset = text_offset; + conversation->data.conversation.entries_count = parse.conversations[ i ].entries_count; + conversation->data.conversation.entry_list_start_index = next_index++; + + strcpy( text_data, parse.conversations[ i ].id ); + text_data += strlen( parse.conversations[ i ].id ) + 1; + text_offset += (int)strlen( parse.conversations[ i ].id ) + 1; + + int index = conversation->data.conversation.entry_list_start_index; + for( int j = 0; j < parse.conversations[ i ].entries_count; ++j ) { + dialog_data_t* entry_list = &dialog->data[ index ]; + entry_list->type = DIALOG_ENTRY_TYPE_ENTRY_LIST; + entry_list->data.entry_list.entry_index = next_index++; + index = j >= parse.conversations[ i ].entries_count - 1 ? 0 : next_index++; + entry_list->data.entry_list.entry_list_next_index = index; + if( parse.conversations[ i ].entries[ j ].id ) { + entry_list->data.entry_list.id_offset = text_offset; + strcpy( text_data, parse.conversations[ i ].entries[ j ].id ); + text_data += strlen( parse.conversations[ i ].entries[ j ].id ) + 1; + text_offset += (int)strlen( parse.conversations[ i ].entries[ j ].id ) + 1; + } else { + entry_list->data.entry_list.id_offset = 0; + } + + dialog_data_t* entry = &dialog->data[ entry_list->data.entry_list.entry_index ]; + if( parse.conversations[ i ].entries[ j ].type == DIALOG_ENTRY_TYPE_LINE ) { + entry->type = DIALOG_ENTRY_TYPE_LINE; + + entry->data.line.actor_offset = text_offset; + strcpy( text_data, parse.conversations[ i ].entries[ j ].data.line.actor ); + text_data += strlen( parse.conversations[ i ].entries[ j ].data.line.actor ) + 1; + text_offset += (int)strlen( parse.conversations[ i ].entries[ j ].data.line.actor ) + 1; + + entry->data.line.text_offset = text_offset; + strcpy( text_data, parse.conversations[ i ].entries[ j ].data.line.text ); + text_data += strlen( parse.conversations[ i ].entries[ j ].data.line.text ) + 1; + text_offset += (int)strlen( parse.conversations[ i ].entries[ j ].data.line.text ) + 1; + } else if( parse.conversations[ i ].entries[ j ].type == DIALOG_ENTRY_TYPE_OPTION ) { + entry->type = DIALOG_ENTRY_TYPE_OPTION; + entry->data.option.text_offset = text_offset; + strcpy( text_data, parse.conversations[ i ].entries[ j ].data.option.text ); + text_data += strlen( parse.conversations[ i ].entries[ j ].data.option.text ) + 1; + text_offset += (int)strlen( parse.conversations[ i ].entries[ j ].data.option.text ) + 1; + + entry->data.option.target_offset = text_offset; + strcpy( text_data, parse.conversations[ i ].entries[ j ].data.option.target ); + text_data += strlen( parse.conversations[ i ].entries[ j ].data.option.target ) + 1; + text_offset += (int)strlen( parse.conversations[ i ].entries[ j ].data.option.target ) + 1; + + entry->data.option.is_persistant = parse.conversations[ i ].entries[ j ].data.option.is_persistant; + } else if( parse.conversations[ i ].entries[ j ].type == DIALOG_ENTRY_TYPE_REDIRECT ) { + entry->type = DIALOG_ENTRY_TYPE_REDIRECT; + entry->data.redirect.target_offset = text_offset; + strcpy( text_data, parse.conversations[ i ].entries[ j ].data.redirect.target ); + text_data += strlen( parse.conversations[ i ].entries[ j ].data.redirect.target ) + 1; + text_offset += (int)strlen( parse.conversations[ i ].entries[ j ].data.redirect.target ) + 1; + } else if( parse.conversations[ i ].entries[ j ].type == DIALOG_ENTRY_TYPE_EVENT ) { + entry->type = DIALOG_ENTRY_TYPE_EVENT; + entry->data.event.event_offset = text_offset; + strcpy( text_data, parse.conversations[ i ].entries[ j ].data.event.event ); + text_data += strlen( parse.conversations[ i ].entries[ j ].data.event.event ) + 1; + text_offset += (int)strlen( parse.conversations[ i ].entries[ j ].data.event.event ) + 1; + } + } + } + dialog->data_count = next_index; + + for( int i = 0; i < parse.conversations_count; ++i ) { + free( parse.conversations[ i ].id ); + for( int j = 0; j < parse.conversations[ i ].entries_count; ++j ) { + if( parse.conversations[ i ].entries[ j ].id ) { + free( parse.conversations[ i ].entries[ j ].id ); + } + if( parse.conversations[ i ].entries[ j ].type == DIALOG_ENTRY_TYPE_LINE ) { + free( parse.conversations[ i ].entries[ j ].data.line.actor ); + free( parse.conversations[ i ].entries[ j ].data.line.text ); + } else if( parse.conversations[ i ].entries[ j ].type == DIALOG_ENTRY_TYPE_OPTION ) { + free( parse.conversations[ i ].entries[ j ].data.option.text ); + free( parse.conversations[ i ].entries[ j ].data.option.target ); + } else if( parse.conversations[ i ].entries[ j ].type == DIALOG_ENTRY_TYPE_REDIRECT ) { + free( parse.conversations[ i ].entries[ j ].data.redirect.target ); + } else if( parse.conversations[ i ].entries[ j ].type == DIALOG_ENTRY_TYPE_EVENT ) { + free( parse.conversations[ i ].entries[ j ].data.event.event ); + } + } + free( parse.conversations[ i ].entries ); + } + free( parse.conversations ); + + return dialog; +} + + +void dialog_destroy( dialog_t* dialog ) { + free( dialog ); +} + + +int dialog_save( dialog_t const* dialog, void* data, int capacity ) { + if( data && capacity >= dialog->size_in_bytes ) { + memcpy( data, dialog, (size_t)( dialog->size_in_bytes ) ); + } + return dialog->size_in_bytes; +} + + +dialog_t* dialog_load( void const* data, int size ) { + dialog_t* dialog = (dialog_t*) malloc( (size_t) size ); + memcpy( dialog, data, (size_t) size ); + return dialog; +} + + +void dialog_unload( dialog_t* dialog ) { + free( dialog ); +} + + +int dialog_find_conversation( dialog_t const* dialog, char const* id ) { + for( int i = 0; i < dialog->conversation_count; ++i ) { + char const* conv_id = ( (char const*) dialog ) + dialog->data[ i ].data.conversation.id_offset; + #ifdef _WIN32 + if( stricmp( id, conv_id ) == 0 ) { + #else + if( strcasecmp( id, conv_id ) == 0 ) { + #endif + return i; + } + } + + return -1; +} + + +int dialog_conversation_count( dialog_t const* dialog ) { + return dialog->conversation_count; +} + + +dialog_conversation_t dialog_conversation( dialog_t const* dialog, int index ) { + dialog_conversation_t conversation; + conversation.handle = index >= 0 && index < dialog->conversation_count ? index : -1; + return conversation; +} + + +char const* dialog_conversation_id( dialog_t const* dialog, dialog_conversation_t conversation ) { + if( conversation.handle >= 0 && conversation.handle < dialog->conversation_count ) { + return ( (char*) dialog ) + dialog->data[ conversation.handle ].data.conversation.id_offset; + } else { + return NULL; + } +} + + +int dialog_conversation_entry_count( dialog_t const* dialog, dialog_conversation_t conversation ) { + if( conversation.handle >= 0 && conversation.handle < dialog->conversation_count ) { + return dialog->data[ conversation.handle ].data.conversation.entries_count; + } else { + return 0; + } +} + + +dialog_entry_t dialog_conversation_entry( dialog_t const* dialog, dialog_conversation_t conversation, int index ) { + dialog_entry_t entry; + entry.handle = -1; + if( conversation.handle >= 0 && conversation.handle < dialog->conversation_count ) { + if( index < 0 || index >= dialog->data[ conversation.handle ].data.conversation.entries_count ) { + return entry; + } + int entry_index = dialog->data[ conversation.handle ].data.conversation.entry_list_start_index; + for( int i = 0; i < index; ++i ) { + entry_index = dialog->data[ entry_index ].data.entry_list.entry_list_next_index; + } + if( !entry_index ) { + return entry; + } + entry.handle = entry_index; + return entry; + } else { + return entry; + } +} + + +char const* dialog_entry_id( dialog_t const* dialog, dialog_entry_t entry ) { + if( entry.handle < 0 || entry.handle >= dialog->data_count ) { + return NULL; + } + if( dialog->data[ entry.handle ].type != DIALOG_ENTRY_TYPE_ENTRY_LIST ) { + return NULL; + } + if( dialog->data[ entry.handle ].data.entry_list.id_offset ) { + return ( (char*) dialog ) + dialog->data[ entry.handle ].data.entry_list.id_offset; + } else { + return NULL; + } +} + + +dialog_entry_type_t dialog_entry_type( dialog_t const* dialog, dialog_entry_t entry ) { + if( entry.handle < 0 || entry.handle >= dialog->data_count ) { + return DIALOG_ENTRY_TYPE_INVALID; + } + if( dialog->data[ entry.handle ].type != DIALOG_ENTRY_TYPE_ENTRY_LIST ) { + return DIALOG_ENTRY_TYPE_INVALID; + } + int entry_index = dialog->data[ entry.handle ].data.entry_list.entry_index; + if( entry_index < 0 || entry_index >= dialog->data_count ) { + return DIALOG_ENTRY_TYPE_INVALID; + } + dialog_entry_type_t type = (dialog_entry_type_t) dialog->data[ entry_index ].type; + if( type == DIALOG_ENTRY_TYPE_LINE || type == DIALOG_ENTRY_TYPE_OPTION || type == DIALOG_ENTRY_TYPE_REDIRECT || + type == DIALOG_ENTRY_TYPE_EVENT ) { + return type; + } + return DIALOG_ENTRY_TYPE_INVALID; +} + + +dialog_line_t dialog_entry_line( dialog_t const* dialog, dialog_entry_t entry ) { + dialog_line_t line; + line.handle = -1; + if( entry.handle < 0 || entry.handle >= dialog->data_count ) { + return line; + } + if( dialog->data[ entry.handle ].type != DIALOG_ENTRY_TYPE_ENTRY_LIST ) { + return line; + } + int entry_index = dialog->data[ entry.handle ].data.entry_list.entry_index; + if( entry_index < 0 || entry_index >= dialog->data_count ) { + return line; + } + if( dialog->data[ entry_index ].type != DIALOG_ENTRY_TYPE_LINE ) { + return line; + } + line.handle = entry_index; + return line; +} + + +dialog_option_t dialog_entry_option( dialog_t const* dialog, dialog_entry_t entry ) { + dialog_option_t option; + option.handle = -1; + if( entry.handle < 0 || entry.handle >= dialog->data_count ) { + return option; + } + if( dialog->data[ entry.handle ].type != DIALOG_ENTRY_TYPE_ENTRY_LIST ) { + return option; + } + int entry_index = dialog->data[ entry.handle ].data.entry_list.entry_index; + if( entry_index < 0 || entry_index >= dialog->data_count ) { + return option; + } + if( dialog->data[ entry_index ].type != DIALOG_ENTRY_TYPE_OPTION ) { + return option; + } + option.handle = entry_index; + return option; +} + + +dialog_redirect_t dialog_entry_redirect( dialog_t const* dialog, dialog_entry_t entry ) { + dialog_redirect_t redirect; + redirect.handle = -1; + if( entry.handle < 0 || entry.handle >= dialog->data_count ) { + return redirect; + } + if( dialog->data[ entry.handle ].type != DIALOG_ENTRY_TYPE_ENTRY_LIST ) { + return redirect; + } + int entry_index = dialog->data[ entry.handle ].data.entry_list.entry_index; + if( entry_index < 0 || entry_index >= dialog->data_count ) { + return redirect; + } + if( dialog->data[ entry_index ].type != DIALOG_ENTRY_TYPE_REDIRECT ) { + return redirect; + } + redirect.handle = entry_index; + return redirect; +} + + +dialog_event_t dialog_entry_event( dialog_t const* dialog, dialog_entry_t entry ) { + dialog_event_t event; + event.handle = -1; + if( entry.handle < 0 || entry.handle >= dialog->data_count ) { + return event; + } + if( dialog->data[ entry.handle ].type != DIALOG_ENTRY_TYPE_ENTRY_LIST ) { + return event; + } + int entry_index = dialog->data[ entry.handle ].data.entry_list.entry_index; + if( entry_index < 0 || entry_index >= dialog->data_count ) { + return event; + } + if( dialog->data[ entry_index ].type != DIALOG_ENTRY_TYPE_EVENT ) { + return event; + } + event.handle = entry_index; + return event; +} + + +char const* dialog_line_actor( dialog_t const* dialog, dialog_line_t line ) { + if( line.handle < 0 || line.handle >= dialog->data_count ) { + return NULL; + } + if( dialog->data[ line.handle ].type != DIALOG_ENTRY_TYPE_LINE ) { + return NULL; + } + + return ( (char*) dialog ) + dialog->data[ line.handle ].data.line.actor_offset; +} + + +char const* dialog_line_text( dialog_t const* dialog, dialog_line_t line ) { + if( line.handle < 0 || line.handle >= dialog->data_count ) { + return NULL; + } + if( dialog->data[ line.handle ].type != DIALOG_ENTRY_TYPE_LINE ) { + return NULL; + } + + return ( (char*) dialog ) + dialog->data[ line.handle ].data.line.text_offset; +} + + +char const* dialog_option_text( dialog_t const* dialog, dialog_option_t option ) { + if( option.handle < 0 || option.handle >= dialog->data_count ) { + return NULL; + } + if( dialog->data[ option.handle ].type != DIALOG_ENTRY_TYPE_OPTION ) { + return NULL; + } + + return ( (char*) dialog ) + dialog->data[ option.handle ].data.option.text_offset; +} + + +char const* dialog_option_target( dialog_t const* dialog, dialog_option_t option ) { + if( option.handle < 0 || option.handle >= dialog->data_count ) { + return NULL; + } + if( dialog->data[ option.handle ].type != DIALOG_ENTRY_TYPE_OPTION ) { + return NULL; + } + + return ( (char*) dialog ) + dialog->data[ option.handle ].data.option.target_offset; +} + + +int dialog_option_is_persistent( dialog_t const* dialog, dialog_option_t option ) { + if( option.handle < 0 || option.handle >= dialog->data_count ) { + return 0; + } + if( dialog->data[ option.handle ].type != DIALOG_ENTRY_TYPE_OPTION ) { + return 0; + } + + return dialog->data[ option.handle ].data.option.is_persistant; +} + + +char const* dialog_redirect_target( dialog_t const* dialog, dialog_redirect_t redirect ) { + if( redirect.handle < 0 || redirect.handle >= dialog->data_count ) { + return NULL; + } + if( dialog->data[ redirect.handle ].type != DIALOG_ENTRY_TYPE_REDIRECT ) { + return NULL; + } + + return ( (char*) dialog ) + dialog->data[ redirect.handle ].data.redirect.target_offset; +} + + +char const* dialog_event_event( dialog_t const* dialog, dialog_event_t event ) { + if( event.handle < 0 || event.handle >= dialog->data_count ) { + return NULL; + } + if( dialog->data[ event.handle ].type != DIALOG_ENTRY_TYPE_EVENT ) { + return NULL; + } + + return ( (char*) dialog ) + dialog->data[ event.handle ].data.event.event_offset; +} + + +#endif /* DIALOG_IMPLEMENTATION */ + +/* +------------------------------------------------------------------------------ + +This software is available under 2 licenses - you may choose the one you like. + +------------------------------------------------------------------------------ + +ALTERNATIVE A - MIT License + +Copyright (c) 2019 Mattias Gustavsson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------------------------------------------------------------------ + +ALTERNATIVE B - Public Domain (www.unlicense.org) + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +------------------------------------------------------------------------------ +*/ diff --git a/dir.h b/dir.h new file mode 100644 index 0000000..a1fb9db --- /dev/null +++ b/dir.h @@ -0,0 +1,295 @@ + +/* +------------------------------------------------------------------------------ + Licensing information can be found at the end of the dir. +------------------------------------------------------------------------------ + +dir.h - v0.1 - Directory listing functions for C/C++ + +Do this: + #define DIR_IMPLEMENTATION +before you include this file in *one* C/C++ dir to create the implementation. +*/ + +#ifndef dir_h +#define dir_h + +typedef struct dir_t dir_t; +typedef struct dir_entry_t dir_entry_t; + +dir_t* dir_open( char const* path ); +void dir_close( dir_t* dir ); +char const* dir_path( dir_t* dir ); +dir_entry_t* dir_read( dir_t* dir ); + +char const* dir_name( dir_entry_t* entry ); +int dir_is_file( dir_entry_t* entry ); +int dir_is_folder( dir_entry_t* entry ); + +#endif /* dir_h */ + +/* +---------------------- + IMPLEMENTATION +---------------------- +*/ + +#ifdef DIR_IMPLEMENTATION +#undef DIR_IMPLEMENTATION + +#ifndef DIR_MALLOC + #define _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_SECURE_NO_WARNINGS + #include + #if defined(__cplusplus) + #define DIR_MALLOC( size ) ( ::malloc( size ) ) + #define DIR_FREE( ptr ) ( ::free( ptr ) ) + #else + #define DIR_MALLOC( size ) ( malloc( size ) ) + #define DIR_FREE( ptr ) ( free( ptr ) ) + #endif +#endif + + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// WINDOWS +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +#if defined( DIR_WINDOWS ) + +#define _CRT_NONSTDC_NO_DEPRECATE +#define _CRT_SECURE_NO_WARNINGS +#if !defined( _WIN32_WINNT ) || _WIN32_WINNT < 0x0501 + #undef _WIN32_WINNT + #define _WIN32_WINNT 0x0501 // requires Windows XP minimum +#endif +// 0x0400=Windows NT 4.0, 0x0500=Windows 2000, 0x0501=Windows XP, 0x0502=Windows Server 2003, 0x0600=Windows Vista, +// 0x0601=Windows 7, 0x0602=Windows 8, 0x0603=Windows 8.1, 0x0A00=Windows 10, +#define _WINSOCKAPI_ +#pragma warning( push ) +#pragma warning( disable: 4365 ) +#pragma warning( disable: 4619 ) +#pragma warning( disable: 4668 ) // 'symbol' is not defined as a preprocessor macro, replacing with '0' for 'directives' +#pragma warning( disable: 4768 ) // __declspec attributes before linkage specification are ignored +#pragma warning( disable: 4255 ) // 'function' : no function prototype given: converting '()' to '(void)' +#define _NTDDSCM_H_ +#include +#pragma warning( pop ) + +struct dir_entry_t + { + char name[ MAX_PATH ]; + BOOL is_folder; + }; + + +struct dir_t + { + char path[ MAX_PATH ]; + HANDLE handle; + WIN32_FIND_DATAA data; + dir_entry_t entry; + }; + + +dir_t* dir_open( char const* path ) + { + if( !path ) return 0; + + size_t path_len = strlen( path ); + BOOL trailing_path_separator = path[ path_len - 1 ] == '\\' || path[ path_len - 1 ] == '/'; + const char* string_to_append = "*.*"; + if( path_len + strlen( string_to_append ) + ( trailing_path_separator ? 0 : 1 ) >= MAX_PATH ) return NULL; + char search_pattern[ MAX_PATH ]; + strcpy( search_pattern, path ); + if( !trailing_path_separator ) strcat( search_pattern, "\\" ); + strcat( search_pattern, string_to_append ); + + WIN32_FIND_DATAA data; + HANDLE handle = FindFirstFileA( search_pattern, &data ); + if( handle == INVALID_HANDLE_VALUE ) return NULL; + + dir_t* dir = (dir_t*) DIR_MALLOC( sizeof( dir_t ) ); + strcpy( dir->path, path ); + dir->handle = handle; + dir->data = data; + + return dir; + } + + +void dir_close( dir_t* dir ) + { + if( !dir ) return; + + if( dir->handle != INVALID_HANDLE_VALUE ) FindClose( dir->handle ); + DIR_FREE( dir ); + } + + +char const* dir_path( dir_t* dir ) + { + if( !dir ) return NULL; + return dir->path; + } + + +dir_entry_t* dir_read( dir_t* dir ) + { + if( !dir ) return NULL; + if( dir->handle == INVALID_HANDLE_VALUE ) return NULL; + + strcpy( dir->entry.name, dir->data.cFileName ); + dir->entry.is_folder = ( dir->data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0; + + BOOL result = FindNextFileA( dir->handle, &dir->data ); + if( !result ) + { + FindClose( dir->handle ); + dir->handle = INVALID_HANDLE_VALUE; + } + + return &dir->entry; + } + + +char const* dir_name( dir_entry_t* entry ) + { + if( !entry ) return NULL; + return entry->name; + } + + +int dir_is_file( dir_entry_t* entry ) + { + if( !entry ) return 0; + return entry->is_folder == FALSE; + } + + +int dir_is_folder( dir_entry_t* entry ) + { + if( !entry ) return 0; + return entry->is_folder == TRUE; + } + + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// POSIX +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +#elif defined( DIR_POSIX ) + +#include + + +dir_t* dir_open( char const* path ) + { + DIR* dir = opendir( path ); + return (dir_t*) dir; + } + + +void dir_close( dir_t* dir ) + { + if( !dir ) return; + closedir( (DIR*) dir ); + } + + +dir_entry_t* dir_read( dir_t* dir ) + { + if( !dir ) return NULL; + return (dir_entry_t*)readdir( (DIR*) dir ); + } + + +char const* dir_name( dir_entry_t* entry ) + { + if( !entry ) return NULL; + return ( (struct dirent*)entry )->d_name; + } + + +int dir_is_file( dir_entry_t* entry ) + { + if( !entry ) return 0; + return ( (struct dirent*)entry )->d_type == DT_REG; + } + + +int dir_is_folder( dir_entry_t* entry ) + { + if( !entry ) return 0; + return ( (struct dirent*)entry )->d_type == DT_DIR; + } + + + + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// PLATFORM ERROR +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +#else + + #error Undefined platform. Define DIR_WINDOWS or DIR_POSIX. + +#endif + + +#endif /* DIR_IMPLEMENTATION */ + +/* +------------------------------------------------------------------------------ + +This software is available under 2 licenses - you may choose the one you like. + +------------------------------------------------------------------------------ + +ALTERNATIVE A - MIT License + +Copyright (c) 2017 Mattias Gustavsson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------------------------------------------------------------------ + +ALTERNATIVE B - Public Domain (www.unlicense.org) + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +------------------------------------------------------------------------------ +*/ diff --git a/frametimer.h b/frametimer.h new file mode 100644 index 0000000..4d63b3e --- /dev/null +++ b/frametimer.h @@ -0,0 +1,317 @@ +/* +------------------------------------------------------------------------------ + Licensing information can be found at the end of the file. +------------------------------------------------------------------------------ + +frametimer.h - v0.1 - Framerate timer functionality. + +Do this: + #define FRAMETIMER_IMPLEMENTATION +before you include this file in *one* C/C++ file to create the implementation. +*/ + +#ifndef frametimer_h +#define frametimer_h + +typedef struct frametimer_t frametimer_t; + +frametimer_t* frametimer_create( void* memxtx ); + +void frametimer_destroy( frametimer_t* frametimer ); + +void frametimer_lock_rate( frametimer_t* frametimer, int fps ); + +float frametimer_update( frametimer_t* frametimer ); + +float frametimer_delta_time( frametimer_t* frametimer ); + +int frametimer_frame_counter( frametimer_t* frametimer ); + +#endif /* frametimer_h */ + +/* +---------------------- + IMPLEMENTATION +---------------------- +*/ + +#ifdef FRAMETIMER_IMPLEMENTATION +#undef FRAMETIMER_IMPLEMENTATION + +#define _CRT_NONSTDC_NO_DEPRECATE +#ifndef _CRT_SECURE_NO_WARNINGS + #define _CRT_SECURE_NO_WARNINGS +#endif +#ifdef _WIN32 + #if !defined( _WIN32_WINNT ) || _WIN32_WINNT < 0x0501 + #undef _WIN32_WINNT + #define _WIN32_WINNT 0x0501 // requires Windows XP minimum + #endif + // 0x0400=Windows NT 4.0, 0x0500=Windows 2000, 0x0501=Windows XP, 0x0502=Windows Server 2003, 0x0600=Windows Vista, + // 0x0601=Windows 7, 0x0602=Windows 8, 0x0603=Windows 8.1, 0x0A00=Windows 10, + #define _WINSOCKAPI_ + #pragma warning( push ) + #pragma warning( disable: 4619 ) + #pragma warning( disable: 4668 ) // 'symbol' is not defined as a preprocessor macro, replacing with '0' for 'directives' + #pragma warning( disable: 4768 ) // __declspec attributes before linkage specification are ignored + #pragma warning( disable: 4255 ) // 'function' : no function prototype given: converting '()' to '(void)' + #include + #pragma warning( pop ) + #ifndef __TINYC__ + #pragma comment(lib, "winmm.lib") + #else + typedef struct timecaps_tag { UINT wPeriodMin; UINT wPeriodMax; } TIMECAPS, *PTIMECAPS, NEAR *NPTIMECAPS, FAR *LPTIMECAPS; + typedef UINT MMRESULT; + #define TIMERR_NOERROR (0) + static MMRESULT (*timeGetDevCaps)( LPTIMECAPS ptc, UINT cbtc ); + static MMRESULT (*timeBeginPeriod)( UINT uPeriod ); + static MMRESULT (*timeEndPeriod)( UINT uPeriod ); + #endif +#elif defined( __APPLE__ ) + #include +#elif defined( __wasm__ ) + #define WA_CORO_IMPLEMENT_NANOSLEEP + #include +#else + #include +#endif + +#ifndef FRAMETIMER_MALLOC + #include + #if defined(__cplusplus) + #define FRAMETIMER_MALLOC( ctx, size ) ( ::malloc( size ) ) + #define FRAMETIMER_FREE( ctx, ptr ) ( ::free( ptr ) ) + #else + #define FRAMETIMER_MALLOC( ctx, size ) ( malloc( size ) ) + #define FRAMETIMER_FREE( ctx, ptr ) ( free( ptr ) ) + #endif +#endif + +#ifndef FRAMETIMER_U64 + #define FRAMETIMER_U64 unsigned long long +#endif + +struct frametimer_t + { + FRAMETIMER_U64 clock_freq; + FRAMETIMER_U64 prev_clock; + void* memctx; + float delta_time; + int initialized; + int frame_counter; + int frame_rate_lock; + #ifdef _WIN32 + HANDLE waitable_timer; + #endif + }; + + +frametimer_t* frametimer_create( void* memctx ) + { + frametimer_t* frametimer = (frametimer_t*) FRAMETIMER_MALLOC( memctx, sizeof( frametimer_t ) ); + #ifdef _WIN32 + #ifdef __TINYC__ + HMODULE winmm = LoadLibrary( "winmm" ); + timeGetDevCaps = GetProcAddress( winmm, "timeGetDevCaps"); + timeBeginPeriod = GetProcAddress( winmm, "timeBeginPeriod"); + timeEndPeriod = GetProcAddress( winmm, "timeEndPeriod"); + #endif + TIMECAPS tc; + if( timeGetDevCaps( &tc, sizeof( TIMECAPS ) ) == TIMERR_NOERROR ) + timeBeginPeriod( tc.wPeriodMin ); + frametimer->waitable_timer = CreateWaitableTimer(NULL, TRUE, NULL); + #endif + + frametimer->memctx = memctx; + frametimer->initialized = 0; + + #ifdef _WIN32 + LARGE_INTEGER f; + QueryPerformanceFrequency( &f ); + frametimer->clock_freq = (FRAMETIMER_U64) f.QuadPart; + #else + frametimer->clock_freq = 1000000000ull; + #endif + + frametimer->prev_clock = 0; + frametimer->delta_time = 0.0f; + frametimer->frame_counter = 0; + frametimer->frame_rate_lock = 0; + return frametimer; + } + + +void frametimer_destroy( frametimer_t* frametimer ) + { + #ifdef _WIN32 + CloseHandle( frametimer->waitable_timer ); + TIMECAPS tc; + if( timeGetDevCaps( &tc, sizeof( TIMECAPS ) ) == TIMERR_NOERROR ) + timeEndPeriod( tc.wPeriodMin ); + #endif + FRAMETIMER_FREE( frametimer->memctx, frametimer ); + } + + +void frametimer_lock_rate( frametimer_t* frametimer, int fps ) + { + frametimer->frame_rate_lock = ( fps > 0 && fps < 5 ) ? 5 : fps < 0 ? 0 : fps; + } + + +float frametimer_update( frametimer_t* frametimer ) + { + if( !frametimer->initialized ) + { + #ifdef _WIN32 + LARGE_INTEGER c; + QueryPerformanceCounter( &c ); + frametimer->prev_clock = (FRAMETIMER_U64) c.QuadPart; + #elif defined( __APPLE__ ) + frametimer->prev_clock = clock_gettime_nsec_np( CLOCK_UPTIME_RAW ); + #else + struct timespec t; + clock_gettime( CLOCK_MONOTONIC_RAW, &t ); + frametimer->prev_clock = (FRAMETIMER_U64)t.tv_sec; + frametimer->prev_clock *= 1000000000ull; + frametimer->prev_clock += (FRAMETIMER_U64)t.tv_nsec; + #endif + frametimer->initialized = 1; + } + + ++frametimer->frame_counter; + + + FRAMETIMER_U64 curr_clock = 0ULL; + #ifdef _WIN32 + LARGE_INTEGER c; + QueryPerformanceCounter( &c ); + curr_clock = (FRAMETIMER_U64) c.QuadPart; + #elif defined( __APPLE__ ) + curr_clock = (FRAMETIMER_U64) clock_gettime_nsec_np( CLOCK_UPTIME_RAW ); + #else + struct timespec t; + clock_gettime( CLOCK_MONOTONIC_RAW, &t ); + curr_clock = (FRAMETIMER_U64)t.tv_sec; + curr_clock *= 1000000000ull; + curr_clock += (FRAMETIMER_U64)t.tv_nsec; + #endif + + if( frametimer->frame_rate_lock > 0 ) + { + FRAMETIMER_U64 delta = 0ULL; + if( curr_clock > frametimer->prev_clock ) + delta = curr_clock - frametimer->prev_clock - 1ULL; + if( delta < frametimer->clock_freq / frametimer->frame_rate_lock ) + { + FRAMETIMER_U64 wait = ( frametimer->clock_freq / frametimer->frame_rate_lock ) - delta; + #ifdef _WIN32 + if( wait > 0 ) + { + LARGE_INTEGER due_time; + due_time.QuadPart = - (LONGLONG) ( ( 10000000ULL * wait ) / frametimer->clock_freq ) ; + + SetWaitableTimer( frametimer->waitable_timer, &due_time, 0, 0, 0, FALSE ); + WaitForSingleObject( frametimer->waitable_timer, 200 ); // wait long enough for timer to trigger ( 200ms == 5fps ) + CancelWaitableTimer( frametimer->waitable_timer ); // in case we timed out + } + #else + struct timespec t = { 0, 0 }; + t.tv_nsec = wait; + while( t.tv_nsec > 0 ) + { + struct timespec r = { 0, 0 }; + if( nanosleep( &t, &r ) >= 0 ) break; + t = r; + } + #endif + curr_clock += wait; + } + } + + FRAMETIMER_U64 delta_clock = 0ULL; + if( curr_clock > frametimer->prev_clock ) delta_clock = curr_clock - frametimer->prev_clock; + + // Cap delta time if it is too high (running at less than 5 fps ) or things will jump + // like crazy on occasional long stalls. + if( delta_clock > frametimer->clock_freq / 5ULL ) delta_clock = frametimer->clock_freq / 5ULL; // Cap to 5 fps + + float delta_time = (float) ( ( (double) delta_clock ) / ( (double) frametimer->clock_freq ) ); + + frametimer->delta_time = delta_time; + frametimer->prev_clock = curr_clock; + + return delta_time; + } + + +float frametimer_delta_time( frametimer_t* frametimer ) + { + return frametimer->delta_time; + } + + +int frametimer_frame_counter( frametimer_t* frametimer ) + { + return frametimer->frame_counter; + } + + +#endif /* FRAMETIMER_IMPLEMENTATION */ + + +/* +------------------------------------------------------------------------------ + +This software is available under 2 licenses - you may choose the one you like. + +------------------------------------------------------------------------------ + +ALTERNATIVE A - MIT License + +Copyright (c) 2015 Mattias Gustavsson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------------------------------------------------------------------ + +ALTERNATIVE B - Public Domain (www.unlicense.org) + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +------------------------------------------------------------------------------ +*/ diff --git a/id3tag.h b/id3tag.h new file mode 100644 index 0000000..1dc03be --- /dev/null +++ b/id3tag.h @@ -0,0 +1,797 @@ +/* +------------------------------------------------------------------------------ + Licensing information can be found at the end of the file. +------------------------------------------------------------------------------ + +id3tag.h - v0.1 - Read/write ID3 tags from/to mp3 files in C/C++. + +Do this: + #define ID3TAG_IMPLEMENTATION +before you include this file in *one* C/C++ file to create the implementation. +*/ + +#ifndef id3tag_h +#define id3tag_h + +#ifndef ID3TAG_U32 + #define ID3TAG_U32 unsigned int +#endif + +#define ID3TAG_PIC_TYPE_COVER_FRONT 3 +#define ID3TAG_PIC_TYPE_COVER_BACK 4 +#define ID3TAG_PIC_TYPE_LEAFLET_PAGE 5 +#define ID3TAG_PIC_TYPE_MEDIA 6 +#define ID3TAG_PIC_TYPE_ARTIST 8 +#define ID3TAG_PIC_TYPE_ARTIST_LOGO 13 + + +typedef struct id3tag_pic_t + { + int pic_type; + char const* description; + char const* mime_type; + void const* data; + size_t size; + } id3tag_pic_t; + + +typedef struct id3tag_t + { + char const* title; + char const* artist; + char const* album_artist; + char const* album; + char const* sort_title; + char const* sort_artist; + char const* sort_album_artist; + char const* sort_album; + char const* genre; + char const* year; + char const* track; + char const* tracks; + char const* disc; + char const* discs; + char const* compilation; + int track_length; + + int play_counter; + + int pics_count; + id3tag_pic_t const* pics; + } id3tag_t; + +#define ID3TAG_ALL_FIELDS ( 0xFFFFFFFF ) +#define ID3TAG_FIELD_TITLE ( 1U ) +#define ID3TAG_FIELD_ARTIST ( 1U << 1U ) +#define ID3TAG_FIELD_ALBUM_ARTIST ( 1U << 2U ) +#define ID3TAG_FIELD_ALBUM ( 1U << 3U ) +#define ID3TAG_FIELD_SORT_TITLE ( 1U << 4U ) +#define ID3TAG_FIELD_SORT_ARTIST ( 1U << 5U ) +#define ID3TAG_FIELD_SORT_ALBUM_ARTIST ( 1U << 6U ) +#define ID3TAG_FIELD_SORT_ALBUM ( 1U << 7U ) +#define ID3TAG_FIELD_GENRE ( 1U << 8U ) +#define ID3TAG_FIELD_YEAR ( 1U << 9U ) +#define ID3TAG_FIELD_TRACK ( 1U << 10U ) +#define ID3TAG_FIELD_TRACKS ( 1U << 11U ) +#define ID3TAG_FIELD_DISC ( 1U << 12U ) +#define ID3TAG_FIELD_DISCS ( 1U << 13U ) +#define ID3TAG_FIELD_COMPILATION ( 1U << 14U ) +#define ID3TAG_FIELD_PLAY_COUNTER ( 1U << 15U ) +#define ID3TAG_FIELD_PICS ( 1U << 16U ) +#define ID3TAG_FIELD_TRACK_LENGTH ( 1U << 17U ) + +size_t id3tag_size( void const* first_ten_bytes ); + +id3tag_t* id3tag_load( void const* data, size_t size, ID3TAG_U32 fields, void* memctx ); +id3tag_t* id3tag_load_id3v1( void const* data, size_t size, void* memctx ); +void id3tag_free( id3tag_t* id3tag ); + +size_t id3tag_save( id3tag_t const* id3tag, ID3TAG_U32 fields, void const* data, size_t capacity ); + + +#endif /* id3tag_h */ + + +/* +---------------------- + IMPLEMENTATION +---------------------- +*/ + +#ifdef ID3TAG_IMPLEMENTATION +#undef ID3TAG_IMPLEMENTATION + +#ifndef ID3TAG_U8 + #define ID3TAG_U8 unsigned char +#endif + +#ifndef ID3TAG_U16 + #define ID3TAG_U16 unsigned short +#endif + + +#ifndef ID3TAG_MALLOC + #define _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_SECURE_NO_WARNINGS + #include + #define ID3TAG_MALLOC( ctx, size ) ( malloc( size ) ) + #define ID3TAG_FREE( ctx, ptr ) ( free( ptr ) ) +#endif + + +typedef struct id3tag_internal_t +{ + id3tag_t tag; + void* memctx; + int pics_capacity; +} id3tag_internal_t; + + +int id3tag_internal_utf16_to_utf8( ID3TAG_U16* str, int len, char* out, int capacity, int endian_swap ) + { + ID3TAG_U16* in_ptr = str; + char* out_ptr = out; + char* out_end = out + capacity; + + for( int i = 0; i < len; ++i ) + { + ID3TAG_U32 cp = (ID3TAG_U32) *in_ptr++; + if( endian_swap ) cp = ( ( cp & 0xff00 ) >> 8 ) | ( ( cp & 0x00ff ) << 8 ); + + if( cp == 0x0000 ) break; + + if( cp >= 0xd800u && cp <= 0xdbffu ) + cp = ( cp << 10 ) + (*in_ptr++) + ( 0x10000u - ( 0xd800u << 10 ) - 0xdc00u ); + + if( cp < 0x80 ) + { + if( out && out_ptr < out_end ) *out_ptr++ = (char)( (ID3TAG_U8) cp ); else ++out_ptr; + } + else if( cp < 0x800 ) + { + if( out && out_ptr < out_end ) *out_ptr++ = (char)( (ID3TAG_U8) ( ( cp >> 6) | 0xc0 ) ); else ++out_ptr; + if( out && out_ptr < out_end ) *out_ptr++ = (char)( (ID3TAG_U8) ( ( cp & 0x3f ) | 0x80 ) ); else ++out_ptr; + } + else if (cp < 0x10000) + { + if( out && out_ptr < out_end ) *out_ptr++ = (char)( (ID3TAG_U8) ( ( cp >> 12 ) | 0xe0 ) ); else ++out_ptr; + if( out && out_ptr < out_end ) *out_ptr++ = (char)( (ID3TAG_U8) ( ( ( cp >> 6 ) & 0x3f ) | 0x80 ) ); else ++out_ptr; + if( out && out_ptr < out_end ) *out_ptr++ = (char)( (ID3TAG_U8) ( ( cp & 0x3f ) | 0x80 ) ); else ++out_ptr; + } + else + { + if( out && out_ptr < out_end ) *out_ptr++ = (char)( (ID3TAG_U8) ( ( cp >> 18 ) | 0xf0 ) ); else ++out_ptr; + if( out && out_ptr < out_end ) *out_ptr++ = (char)( (ID3TAG_U8) ( ( ( cp >> 12 ) & 0x3f ) | 0x80 ) ); else ++out_ptr; + if( out && out_ptr < out_end ) *out_ptr++ = (char)( (ID3TAG_U8) ( ( ( cp >> 6 ) & 0x3f ) | 0x80 ) ); else ++out_ptr; + if( out && out_ptr < out_end ) *out_ptr++ = (char)( (ID3TAG_U8) ( ( cp & 0x3f ) | 0x80 ) ); else ++out_ptr; + } + } + if( out && out_ptr < out_end ) *out_ptr++ = '\0'; else ++out_ptr; + + int out_len = out ? (int)( out_ptr - out ) : (int)(uintptr_t)( out_ptr ); + return out_len; + } + + +// TODO: Proper unicode support with a font that can handle it, instead of doing this +char* utf8_to_latin1( char* s ) + { + for( int readIndex = 0, writeIndex = 0 ; ; writeIndex++ ) + { + if( s[ readIndex ] == 0 ) { s[ writeIndex ] = 0; break; } + + int len; + if ( (ID3TAG_U8) s[ readIndex ] < 0x80 ) len = 1; + else if ( ( (ID3TAG_U8) s[ readIndex ] & 0x20 ) == 0 ) len = 2; + else if ( ( (ID3TAG_U8) s[ readIndex ] & 0x10 ) == 0 ) len = 3; + else if ( ( (ID3TAG_U8) s[ readIndex ] & 0x08 ) == 0 ) len = 4; + else if ( ( (ID3TAG_U8) s[ readIndex ] & 0x04 ) == 0 ) len = 5; + else len = 6; + + char c = '\0'; + if( len == 1 ) + { + s[ writeIndex ] = s[ readIndex++ ]; + } + else + { + int v = ( s[ readIndex++ ] & ( 0xff >> ( len + 1 ) ) ) << ( ( len - 1 ) * 6 ); + for( len-- ; len > 0 ; len-- ) v |= ( (ID3TAG_U8)( s[ readIndex++ ] ) - 0x80 ) << ( ( len - 1 ) * 6 ); + if( v == 8216 ) v = '\''; + if( v == 8217 ) v = '\''; + if( v == 9733 ) v = '*'; + if( v == 8208 ) v = '-'; + if( v == 8211 ) v = '-'; + if( v == 8220 ) v = '"'; + if( v == 8221 ) v = 'r'; + if( v == 8482 ) + v = ' '; // TM + if( v == 263 ) v = 'c'; + if( v == 65533 ) v = '?'; + if( v == 8230 ) { // '...' + s[ writeIndex++ ] = '.'; + s[ writeIndex++ ] = '.'; + v = '.'; + } + if( v == 339 ) { + s[ writeIndex++ ] = 'o'; + v = 'e'; + } + if( v > 0xff ) { + v = ' '; + } + c = (char) v; + s[ writeIndex ] = c; + } + } + + return s; + } + + +size_t id3tag_size( void const* first_ten_bytes ) + { + ID3TAG_U8* ptr = (ID3TAG_U8*) first_ten_bytes; + + // verify the header to see if this is a valid ID3 tag + if( *ptr++ != 0x49 || *ptr++ != 0x44 || *ptr++ != 0x33 || *ptr++ >= 0xff || *ptr++ >= 0xff ) return 0; + + ++ptr; // skip flags field + + ID3TAG_U32 size = 0; + for( int i = 0; i < 4; ++i ) + { + ID3TAG_U8 b = *ptr++; + if( b >= 0x80 ) return 0; // Not a valid ID3 + size |= ( (ID3TAG_U32) b ) << ( 7 * ( 3 - i ) ); + } + + return (size_t) size + 10; + } + + +char* id3tag_internal_get_string( int encoding, ID3TAG_U8* ptr, int size, void* memctx, int* bytes_consumed ) + { + (void) memctx; + if( encoding == 0) // Latin1 + { + char* str = (char*)ID3TAG_MALLOC( memctx, (size_t)( size + 1 ) ); + memcpy( str, ptr, (size_t) size ); + str[ size ] = '\0'; + if( bytes_consumed ) *bytes_consumed = (int) strlen( str ) + 1; + return str; + } + else if( encoding == 1 ) // UTF16 with BOM + { + ID3TAG_U16 bom = *( (ID3TAG_U16*) ptr ); + if( bom == 0xfffe || bom == 0xfeff ) { ptr += 2; size -= 2; } + int endian_swap = ( bom == 0xfffe ); + + int len = id3tag_internal_utf16_to_utf8( (ID3TAG_U16*) ptr, size / 2, 0, 0, endian_swap ); + char* str = (char*)ID3TAG_MALLOC( memctx, (size_t) len ); + id3tag_internal_utf16_to_utf8( (ID3TAG_U16*) ptr, size / 2, str, len, endian_swap ); + + if( bytes_consumed ) + { + *bytes_consumed = ( ( bom == 0xfffe || bom == 0xfeff ) ? 2 : 0 ); + ID3TAG_U16* s = (ID3TAG_U16*) ptr; + while( *s++ ) *bytes_consumed = ( *bytes_consumed ) + 2; + *bytes_consumed = ( *bytes_consumed ) + 2; + } + + utf8_to_latin1( str ); + return str; + } + else if( encoding == 2 ) // UTF16BE without BOM + { + int endian_swap = 1; + + int len = id3tag_internal_utf16_to_utf8( (ID3TAG_U16*) ptr, size / 2, 0, 0, endian_swap ); + char* str = (char*)ID3TAG_MALLOC( memctx, (size_t) len ); + id3tag_internal_utf16_to_utf8( (ID3TAG_U16*) ptr, size / 2, str, len, endian_swap ); + + if( bytes_consumed ) + { + *bytes_consumed = 0; + ID3TAG_U16* s = (ID3TAG_U16*) ptr; + while( *s++ ) *bytes_consumed = ( *bytes_consumed ) + 2; + *bytes_consumed = ( *bytes_consumed ) + 2; + } + + utf8_to_latin1( str ); + return str; + } + else if( encoding == 3 ) // UTF8 + { + char* str = (char*)ID3TAG_MALLOC( memctx, (size_t) size + 1 ); + memcpy( str, ptr, (size_t) size ); + str[ size ] = '\0'; + if( bytes_consumed ) *bytes_consumed = (int) strlen( str ) + 1; + + utf8_to_latin1( str ); + return str; + } + else + { + return 0; + } + } + + +id3tag_t* id3tag_load_id3v1( void const* data, size_t size, void* memctx ) + { + if( size != 128 ) return NULL; + char const* ptr = (char const*) data; + if( strncmp( ptr, "TAG", 3 ) != 0 ) return NULL; + ptr += 3; + + id3tag_internal_t* tag = (id3tag_internal_t*) ID3TAG_MALLOC( memctx, sizeof( id3tag_internal_t ) + size ); + memset( tag, 0, sizeof( id3tag_internal_t ) ); + memcpy( tag + 1, data, size ); + tag->memctx = memctx; + + tag->tag.title = (char*) ID3TAG_MALLOC( memctx, 31 ); + strncpy( (char*) tag->tag.title, ptr, 30 ); + ( (char*) tag->tag.title )[ 30 ] = '\0'; + ptr += 30; + + tag->tag.artist = (char*) ID3TAG_MALLOC( memctx, 31 ); + strncpy( (char*) tag->tag.artist, ptr, 30 ); + ( (char*) tag->tag.artist )[ 30 ] = '\0'; + ptr += 30; + + tag->tag.album = (char*) ID3TAG_MALLOC( memctx, 31 ); + strncpy( (char*) tag->tag.album, ptr, 30 ); + ( (char*) tag->tag.album )[ 30 ] = '\0'; + ptr += 30; + + tag->tag.year = (char*) ID3TAG_MALLOC( memctx, 5 ); + strncpy( (char*) tag->tag.year, ptr, 4 ); + ( (char*) tag->tag.year)[ 4 ] = '\0'; + ptr += 4; + + char const* comment = ptr; + if( comment[ 28 ] == 0 && (int)(ID3TAG_U8)( ptr[ 29 ] ) > 0 ) + { + tag->tag.track = (char*) ID3TAG_MALLOC( memctx, 30 ); + sprintf( (char*) tag->tag.track, "%d", (int)(ID3TAG_U8)( ptr[ 29 ] ) ); + } + ptr += 30; + + int genre = (int)(ID3TAG_U8)( *ptr ); + if( genre != 255 ) + { + tag->tag.genre = (char*) ID3TAG_MALLOC( memctx, 30 ); + sprintf( (char*) tag->tag.genre, "(%d)", genre ); + } + + return (id3tag_t*) tag; + } + + +id3tag_t* id3tag_load( void const* data, size_t size, ID3TAG_U32 fields, void* memctx ) + { + enum fields_t + { + FIELD_TITLE, + FIELD_ARTIST, + FIELD_ALBUM_ARTIST, + FIELD_ALBUM, + FIELD_SORT_TITLE, + FIELD_SORT_ARTIST, + FIELD_SORT_ALBUM_ARTIST, + FIELD_SORT_ALBUM, + FIELD_GENRE, + FIELD_YEAR, + FIELD_TRACK, + FIELD_TRACKS, + FIELD_DISC, + FIELD_DISCS, + FIELD_COMPILATION, + FIELD_PLAY_COUNTER, + FIELD_TRACK_LENGTH, + + FIELDCOUNT, + }; + bool fields_found[ FIELDCOUNT ] = { false }; + + int fields_requested = 0; + if( fields & ID3TAG_FIELD_TITLE ) ++fields_requested; + if( fields & ID3TAG_FIELD_ARTIST ) ++fields_requested; + if( fields & ID3TAG_FIELD_ALBUM_ARTIST ) ++fields_requested; + if( fields & ID3TAG_FIELD_ALBUM ) ++fields_requested; + if( fields & ID3TAG_FIELD_SORT_TITLE ) ++fields_requested; + if( fields & ID3TAG_FIELD_SORT_ARTIST ) ++fields_requested; + if( fields & ID3TAG_FIELD_SORT_ALBUM_ARTIST ) ++fields_requested; + if( fields & ID3TAG_FIELD_SORT_ALBUM ) ++fields_requested; + if( fields & ID3TAG_FIELD_GENRE ) ++fields_requested; + if( fields & ID3TAG_FIELD_YEAR ) ++fields_requested; + if( fields & ID3TAG_FIELD_TRACK ) ++fields_requested; + if( fields & ID3TAG_FIELD_TRACKS ) ++fields_requested; + if( fields & ID3TAG_FIELD_DISC ) ++fields_requested; + if( fields & ID3TAG_FIELD_DISCS ) ++fields_requested; + if( fields & ID3TAG_FIELD_COMPILATION ) ++fields_requested; + if( fields & ID3TAG_FIELD_PLAY_COUNTER ) ++fields_requested; + if( fields & ID3TAG_FIELD_TRACK_LENGTH ) ++fields_requested; + + ID3TAG_U8* ptr = (ID3TAG_U8*) data; + + // validate data + if( size < 10 ) return NULL; // Not a valid ID3 + size_t tag_size = id3tag_size( data ); + if( tag_size == 0 ) return NULL; // Not a valid ID3 + if( size < tag_size ) return NULL; // Not enough data + + id3tag_internal_t* tag = (id3tag_internal_t*) ID3TAG_MALLOC( memctx, sizeof( id3tag_internal_t ) + size ); + memset( tag, 0, sizeof( id3tag_internal_t ) ); + memcpy( tag + 1, data, size ); + tag->memctx = memctx; + + ptr += 3; // skip past "ID3" marker + + // read version and flags + int version = *ptr++; + int revision = *ptr++; (void) revision; + ID3TAG_U8 header_flags = *ptr++; + (void) header_flags; // TODO: inspect flags + + ptr += 4; // skip past size field + + ID3TAG_U8* end = ( (ID3TAG_U8*) data ) + tag_size; + + while( ptr <= ( end - 10 ) ) + { + if( ( fields & ID3TAG_FIELD_PICS ) == 0 ) + { + int fields_found_count = 0; + for( int i = 0; i < FIELDCOUNT; ++i ) if( fields_found[ i ] ) ++fields_found_count; + if( fields_found_count == fields_requested ) break; + } + + if( version >= 3 && ptr[ 0 ] == 0 && ptr[ 1 ] == 0 && ptr[ 2 ] == 0 && ptr[ 3 ] == 0 ) break; // end of frames (in padding) + if( version < 3 && ptr[ 0 ] == 0 && ptr[ 1 ] == 0 && ptr[ 2 ] == 0 ) break; // end of frames (in padding) + + char frame_id[ 5 ]= { (char) *ptr++, (char) *ptr++, (char) *ptr++, '\0', '\0' }; + if( version >= 3 ) frame_id[ 3 ] = (char) *ptr++; + int frame_size = 0; + if( version >= 4 ) + for( int i = 3; i >= 0 ; --i ) frame_size |= ( (ID3TAG_U32) ( ( *ptr++ ) ) ) << ( 7 * i ); + else if( version >= 3 ) + for( int i = 3; i >= 0 ; --i ) frame_size |= ( (ID3TAG_U32) ( ( *ptr++ ) ) ) << ( 8 * i ); + else + for( int i = 2; i >= 0 ; --i ) frame_size |= ( (ID3TAG_U32) ( ( *ptr++ ) ) ) << ( 8 * i ); + if( frame_size <= 0 ) break; // end of frames + if( frame_size >= ( end - ptr ) ) break; // invalid frame + ID3TAG_U16 flags = 0; + if( version >= 3 ) flags = (ID3TAG_U16)( ( ( (ID3TAG_U16)( *ptr++ ) ) << 8 ) | ( *ptr++ ) ); + + + if( ( fields & ID3TAG_FIELD_TITLE ) && ( strcmp( frame_id , "TIT2" ) == 0 || strcmp( frame_id , "TT2" ) == 0 ) ) + { + if( !tag->tag.title ) tag->tag.title = id3tag_internal_get_string( *ptr, ptr + 1, frame_size - 1, memctx, NULL ); + fields_found[ FIELD_TITLE ] = true; + } + + if( ( fields & ID3TAG_FIELD_ARTIST ) && ( strcmp( frame_id , "TPE1" ) == 0 || strcmp( frame_id , "TP1" ) == 0 ) ) + { + if( !tag->tag.artist ) tag->tag.artist = id3tag_internal_get_string( *ptr, ptr + 1, frame_size - 1, memctx, NULL ); + fields_found[ FIELD_ARTIST ] = true; + } + + if( ( fields & ID3TAG_FIELD_ALBUM_ARTIST) && ( strcmp( frame_id , "TPE2" ) == 0 || strcmp( frame_id , "TP2" ) == 0 ) ) + { + if( !tag->tag.album_artist ) tag->tag.album_artist = id3tag_internal_get_string( *ptr, ptr + 1, frame_size - 1, memctx, NULL ); + fields_found[ FIELD_ALBUM_ARTIST ] = true; + } + + if( ( fields & ID3TAG_FIELD_ALBUM ) && ( strcmp( frame_id , "TALB" ) == 0 || strcmp( frame_id , "TAL" ) == 0 ) ) + { + if( !tag->tag.album ) tag->tag.album = id3tag_internal_get_string( *ptr, ptr + 1, frame_size - 1, memctx, NULL ); + fields_found[ FIELD_ALBUM ] = true; + } + + if( ( fields & ID3TAG_FIELD_GENRE ) && ( strcmp( frame_id , "TCON" ) == 0 || strcmp( frame_id , "TCO" ) == 0 ) ) + { + if( !tag->tag.genre ) tag->tag.genre = id3tag_internal_get_string( *ptr, ptr + 1, frame_size - 1, memctx, NULL ); + fields_found[ FIELD_GENRE ] = true; + } + + if( ( fields & ID3TAG_FIELD_YEAR ) && ( strcmp( frame_id , "TYER" ) == 0 || strcmp( frame_id , "TYE" ) == 0 ) ) + { + if( !tag->tag.year ) tag->tag.year = id3tag_internal_get_string( *ptr, ptr + 1, frame_size - 1, memctx, NULL ); + fields_found[ FIELD_YEAR ] = true; + } + + if( ( fields & ID3TAG_FIELD_COMPILATION ) && ( strcmp( frame_id , "TCMP" ) == 0 || strcmp( frame_id , "TCP" ) == 0 ) ) + { + if( !tag->tag.compilation ) tag->tag.compilation = id3tag_internal_get_string( *ptr, ptr + 1, frame_size - 1, memctx, NULL ); + fields_found[ FIELD_COMPILATION ] = true; + } + + if( ( fields & ID3TAG_FIELD_SORT_TITLE ) && ( strcmp( frame_id , "TSOT" ) == 0 || strcmp( frame_id , "TST" ) == 0 ) ) + { + if( !tag->tag.sort_title ) tag->tag.sort_title = id3tag_internal_get_string( *ptr, ptr + 1, frame_size - 1, memctx, NULL ); + fields_found[ FIELD_SORT_TITLE ] = true; + } + + if( ( fields & ID3TAG_FIELD_SORT_ARTIST ) && ( strcmp( frame_id , "TSOP" ) == 0 || strcmp( frame_id , "TSP" ) == 0 ) ) + { + if( !tag->tag.sort_artist ) tag->tag.sort_artist = id3tag_internal_get_string( *ptr, ptr + 1, frame_size - 1, memctx, NULL ); + fields_found[ FIELD_SORT_ARTIST ] = true; + } + + if( ( fields & ID3TAG_FIELD_SORT_ALBUM ) && ( strcmp( frame_id , "TSOA" ) == 0 || strcmp( frame_id , "TSA" ) == 0 ) ) + { + if( !tag->tag.sort_album ) tag->tag.sort_album = id3tag_internal_get_string( *ptr, ptr + 1, frame_size - 1, memctx, NULL ); + fields_found[ FIELD_SORT_ALBUM ] = true; + } + + if( ( fields & ID3TAG_FIELD_SORT_ALBUM_ARTIST ) && ( strcmp( frame_id , "TSO2" ) == 0 || strcmp( frame_id , "TS2" ) == 0 ) ) + { + if( !tag->tag.sort_album_artist ) tag->tag.sort_album_artist = id3tag_internal_get_string( *ptr, ptr + 1, frame_size - 1, memctx, NULL ); + fields_found[ FIELD_SORT_ALBUM_ARTIST ] = true; + } + + if( ( fields & ID3TAG_FIELD_TRACK_LENGTH ) && ( strcmp( frame_id , "TLEN" ) == 0 || strcmp( frame_id , "TLE" ) == 0 ) ) + { + char* str = id3tag_internal_get_string( *ptr, ptr + 1, frame_size - 1, memctx, NULL ); + if( tag->tag.track_length == 0 ) tag->tag.track_length = atoi( str ); + ID3TAG_FREE( memctx, str ); + if( tag->tag.track_length > 0 ) fields_found[ FIELD_TRACK_LENGTH ] = true; + } + + if( ( ( fields & ID3TAG_FIELD_TRACK ) || ( fields & ID3TAG_FIELD_TRACKS ) ) && + ( strcmp( frame_id , "TRCK" ) == 0 || strcmp( frame_id , "TRK" ) == 0 ) ) + { + char* first_str = id3tag_internal_get_string( *ptr, ptr + 1, frame_size - 1, memctx, NULL ); + char* separator = strchr( first_str, '/' ); + if( separator ) *separator = '\0'; + char* second_str = separator ? ( separator + 1 ) : NULL; + + int first = atoi( first_str ); + int second = second_str ? atoi( second_str ) : 0; + ID3TAG_FREE( memctx, first_str ); + + char buf[ 64 ]; + + if( first > 0 ) + { + sprintf( buf, "%d", first ); + if( strlen( buf ) > 0 && !tag->tag.track ) + { + tag->tag.track = (char*) ID3TAG_MALLOC( memctx, strlen( buf ) + 1 ); + strcpy( (char*) tag->tag.track, buf ); + fields_found[ FIELD_TRACK ] = true; + } + } + + if( second > 0 ) + { + sprintf( buf, "%d", second ); + if( strlen( buf ) > 0 && !tag->tag.tracks ) + { + tag->tag.tracks = (char*) ID3TAG_MALLOC( memctx, strlen( buf ) + 1 ); + strcpy( (char*) tag->tag.tracks, buf ); + fields_found[ FIELD_TRACKS ] = true; + } + } + } + + if( ( ( fields & ID3TAG_FIELD_DISC ) || ( fields & ID3TAG_FIELD_DISCS ) ) && + ( strcmp( frame_id , "TPOS" ) == 0 || strcmp( frame_id , "TPA" ) == 0 ) ) + { + char* first_str = id3tag_internal_get_string( *ptr, ptr + 1, frame_size - 1, memctx, NULL ); + char* separator = strchr( first_str, '/' ); + if( separator ) *separator = '\0'; + char* second_str = separator ? ( separator + 1 ) : NULL; + + int first = atoi( first_str ); + int second = second_str ? atoi( second_str ) : 0; + ID3TAG_FREE( memctx, first_str ); + + char buf[ 64 ]; + + if( first > 0 ) + { + sprintf( buf, "%d", first ); + if( strlen( buf ) > 0 && !tag->tag.disc ) + { + tag->tag.disc = (char*) ID3TAG_MALLOC( memctx, strlen( buf ) + 1 ); + strcpy( (char*) tag->tag.disc, buf ); + fields_found[ FIELD_DISC ] = true; + } + } + + if( second > 0 ) + { + sprintf( buf, "%d", second ); + if( strlen( buf ) > 0 && !tag->tag.discs ) + { + tag->tag.discs = (char*) ID3TAG_MALLOC( memctx, strlen( buf ) + 1 ); + strcpy( (char*) tag->tag.discs, buf ); + fields_found[ FIELD_DISCS ] = true; + } + } + } + + + if( ( fields & ID3TAG_FIELD_PICS ) && ( strcmp( frame_id , "APIC" ) == 0 || strcmp( frame_id , "PIC" ) == 0 ) ) + { + if( !tag->tag.pics ) + { + tag->pics_capacity = 16; + tag->tag.pics = (id3tag_pic_t*) ID3TAG_MALLOC( memctx, sizeof( id3tag_pic_t ) * tag->pics_capacity ); + tag->tag.pics_count = 0; + } + if( tag->tag.pics_count >= tag->pics_capacity ) + { + tag->pics_capacity *= 2; + id3tag_pic_t* new_pics = (id3tag_pic_t*) ID3TAG_MALLOC( memctx, sizeof( id3tag_pic_t ) * tag->pics_capacity ); + memcpy( new_pics, tag->tag.pics, sizeof( id3tag_pic_t ) * tag->tag.pics_count ); + ID3TAG_FREE( memctx, (id3tag_pic_t*)tag->tag.pics ); + tag->tag.pics = new_pics; + } + + int encoding = *ptr++; + --frame_size; + + id3tag_pic_t* pic = (id3tag_pic_t*) &tag->tag.pics[ tag->tag.pics_count++ ]; + memset( pic, 0, sizeof( *pic ) ); + + if( version < 3 ) + { + char str[ 4 ] = { (char) *ptr++, (char) *ptr++, (char) *ptr++, '\0' }; + frame_size -= 3; + + pic->mime_type = (char*) ID3TAG_MALLOC( memctx, 32 ); + if( strcmp( str, "JPG" ) == 0 ) + strcpy( (char*) pic->mime_type, "image/jpeg" ); + else if( strcmp( str, "PNG" ) == 0 ) + strcpy( (char*) pic->mime_type, "image/png" ); + else if( strcmp( str, "GIF" ) == 0 ) + strcpy( (char*) pic->mime_type, "image/gif" ); + else if( strcmp( str, "BMP" ) == 0 ) + strcpy( (char*) pic->mime_type, "image/bmp" ); + else + strcpy( (char*) pic->mime_type, str ); + } + else + { + int bytes = 0; + pic->mime_type = id3tag_internal_get_string( encoding, ptr, frame_size, memctx, &bytes ); + ptr += bytes; + frame_size -= bytes; + } + + pic->pic_type = *ptr++; + --frame_size; + + if( pic->pic_type != 0 ) + ptr = ptr; + + int bytes = 0; + pic->description = id3tag_internal_get_string( encoding, ptr, frame_size, memctx, &bytes ); + ptr += bytes; + frame_size -= bytes; + + if( frame_size ) + { + pic->data = ID3TAG_MALLOC( memctx, (size_t) frame_size ); + memcpy( (void*) pic->data, ptr, (size_t) frame_size ); + pic->size = (size_t) frame_size; + } + else + { + if( pic->mime_type ) ID3TAG_FREE( memctx, (char*) pic->mime_type ); + if( pic->description ) ID3TAG_FREE( memctx, (char*) pic->description ); + --tag->tag.pics_count; + } + } + + ptr += frame_size; + } + + return (id3tag_t*) tag; + } + + +void id3tag_free( id3tag_t* id3tag ) + { + id3tag_internal_t* internal = (id3tag_internal_t*) id3tag; + + if( internal->tag.title) ID3TAG_FREE( internal->memctx, (char*) internal->tag.title ); + if( internal->tag.artist ) ID3TAG_FREE( internal->memctx, (char*) internal->tag.artist ); + if( internal->tag.album_artist ) ID3TAG_FREE( internal->memctx, (char*) internal->tag.album_artist ); + if( internal->tag.album ) ID3TAG_FREE( internal->memctx, (char*) internal->tag.album ); + if( internal->tag.sort_title) ID3TAG_FREE( internal->memctx, (char*) internal->tag.sort_title ); + if( internal->tag.sort_artist ) ID3TAG_FREE( internal->memctx, (char*) internal->tag.sort_artist ); + if( internal->tag.sort_album_artist ) ID3TAG_FREE( internal->memctx, (char*) internal->tag.sort_album_artist ); + if( internal->tag.sort_album ) ID3TAG_FREE( internal->memctx, (char*) internal->tag.sort_album ); + if( internal->tag.genre ) ID3TAG_FREE( internal->memctx, (char*) internal->tag.genre ); + if( internal->tag.year ) ID3TAG_FREE( internal->memctx, (char*) internal->tag.year ); + if( internal->tag.track ) ID3TAG_FREE( internal->memctx, (char*) internal->tag.track ); + if( internal->tag.tracks ) ID3TAG_FREE( internal->memctx, (char*) internal->tag.tracks ); + if( internal->tag.disc ) ID3TAG_FREE( internal->memctx, (char*) internal->tag.disc ); + if( internal->tag.discs ) ID3TAG_FREE( internal->memctx, (char*) internal->tag.discs ); + if( internal->tag.compilation ) ID3TAG_FREE( internal->memctx, (char*) internal->tag.compilation ); + + if( internal->tag.pics ) + { + for( int i = 0; i < internal->tag.pics_count; ++i ) + { + if( internal->tag.pics[ i ].description ) ID3TAG_FREE( internal->memctx, (char*) internal->tag.pics[ i ].description ); + if( internal->tag.pics[ i ].mime_type ) ID3TAG_FREE( internal->memctx, (char*) internal->tag.pics[ i ].mime_type ); + if( internal->tag.pics[ i ].data ) ID3TAG_FREE( internal->memctx, (void*) internal->tag.pics[ i ].data ); + } + + if( internal->tag.pics ) ID3TAG_FREE( internal->memctx, (id3tag_pic_t*) internal->tag.pics ); + } + + ID3TAG_FREE( internal->memctx, id3tag ); + } + + +size_t id3tag_save( id3tag_t const* id3tag, ID3TAG_U32 fields, void const* data, size_t capacity ) + { + (void) id3tag, fields, data, capacity; + return 0; + } + + +#endif /* ID3TAG_IMPLEMENTATION */ + +/* +------------------------------------------------------------------------------ + +This software is available under 2 licenses - you may choose the one you like. + +------------------------------------------------------------------------------ + +ALTERNATIVE A - MIT License + +Copyright (c) 2018 Mattias Gustavsson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------------------------------------------------------------------ + +ALTERNATIVE B - Public Domain (www.unlicense.org) + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +------------------------------------------------------------------------------ +*/ \ No newline at end of file diff --git a/img.h b/img.h new file mode 100644 index 0000000..9067df7 --- /dev/null +++ b/img.h @@ -0,0 +1,412 @@ +/* +------------------------------------------------------------------------------ + Licensing information can be found at the end of the file. +------------------------------------------------------------------------------ + +img.h - v0.1 - Image processing functions for C/C++. + +Do this: + #define IMG_IMPLEMENTATION +before you include this file in *one* C/C++ file to create the implementation. +*/ + +#ifndef img_h +#define img_h + +#ifndef IMG_U32 + #define IMG_U32 unsigned int +#endif + + +typedef struct img_rgba_t { + float r; + float g; + float b; + float a; +} img_rgba_t; + +typedef struct img_t { + int width; + int height; + img_rgba_t* pixels; +} img_t; + +typedef struct img_hsva_t { + float h; + float s; + float v; + float a; +} img_hsva_t; + +img_t img_create( int width, int height ); +img_t img_from_abgr32( IMG_U32* abgr, int width, int height ); +void img_free( img_t* img ); + +void img_to_argb32( img_t* img, IMG_U32* abgr ); +img_rgba_t img_sample_clamp( img_t* img, float u, float v ); + +img_rgba_t img_rgba_lerp( img_rgba_t a, img_rgba_t b, float s ); +img_hsva_t img_rgba_to_hsva( img_rgba_t rgb ); +img_rgba_t img_hsva_to_rgba( img_hsva_t hsv ); + +void img_adjust_brightness( img_t* img, float value ); +void img_adjust_contrast( img_t* img, float value ); +void img_adjust_saturation( img_t* img, float value ); +void img_sharpen( img_t* img, float radius, float blend ); + + +#endif /* img_h */ + +/* +---------------------- + IMPLEMENTATION +---------------------- +*/ + +#ifdef IMG_IMPLEMENTATION +#undef IMG_IMPLEMENTATION + +#define _CRT_NONSTDC_NO_DEPRECATE +#define _CRT_SECURE_NO_WARNINGS +#include + + +#if !defined( IMG_POW ) || !defined( IMG_FLOOR ) + #define _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_SECURE_NO_WARNINGS + #pragma warning( push ) + #pragma warning( disable: 4668 ) // 'symbol' is not defined as a preprocessor macro, replacing with '0' for 'directives' + #include + #pragma warning( pop ) +#endif + + +#ifndef IMG_POW + #ifdef __TINYC__ + #define IMG_POW( x, y ) ( (float) pow( (double) x, (double) y ) ) + #else + #define IMG_POW( x, y ) powf( x, y ) + #endif +#endif + +#ifndef IMG_FLOOR + #ifdef __TINYC__ + #define IMG_FLOOR( x ) ( (float) floor( (double) x ) ) + #else + #define IMG_FLOOR( x ) floorf( x ) + #endif +#endif + + +img_t img_create( int width, int height ) { + img_t img; + img.width = width; + img.height = height; + img.pixels = (img_rgba_t*) malloc( sizeof( img_rgba_t ) * width * height ); + memset( img.pixels, 0, sizeof( img_rgba_t ) * width * height ); + return img; +} + + +img_t img_from_abgr32( IMG_U32* abgr, int width, int height ) { + img_t img; + img.width = width; + img.height = height; + img.pixels = (img_rgba_t*) malloc( sizeof( img_rgba_t ) * width * height ); + for( int i = 0; i < width * height; ++i ) { + IMG_U32 p = abgr[ i ]; + IMG_U32 b = ( p ) & 0xff; + IMG_U32 g = ( p >> 8 ) & 0xff; + IMG_U32 r = ( p >> 16 ) & 0xff; + IMG_U32 a = ( p >> 24 ) & 0xff; + img_rgba_t* f = &img.pixels[ i ]; + f->r = ( (float) r ) / 255.0f; + f->g = ( (float) g ) / 255.0f; + f->b = ( (float) b ) / 255.0f; + f->a = ( (float) a ) / 255.0f; + } + return img; +} + + +void img_free( img_t* img ) { + free( img->pixels ); + img->pixels = NULL; +} + + +float img_clamp( float x, float low, float high ) { + return x < low ? low : x > high ? high : x; +} + + +void img_to_argb32( img_t* img, IMG_U32* abgr ) { + for( int i = 0; i < img->width * img->height; ++i ) { + img_rgba_t p = img->pixels[ i ]; + p.r = img_clamp( p.r, 0.0f, 1.0f ); + p.g = img_clamp( p.g, 0.0f, 1.0f ); + p.b = img_clamp( p.b, 0.0f, 1.0f ); + p.a = img_clamp( p.a, 0.0f, 1.0f ); + IMG_U32 r = (IMG_U32)( p.r * 256.0f ); + IMG_U32 g = (IMG_U32)( p.g * 256.0f ); + IMG_U32 b = (IMG_U32)( p.b * 256.0f ); + IMG_U32 a = (IMG_U32)( p.a * 256.0f ); + r = r > 255 ? 255 : r; + g = g > 255 ? 255 : g; + b = b > 255 ? 255 : b; + a = a > 255 ? 255 : a; + abgr[ i ] = ( a << 24 ) | ( r << 16 ) | ( g << 8 ) | ( b ); + } +} + + + +img_rgba_t img_rgba_lerp( img_rgba_t a, img_rgba_t b, float s ) { + img_rgba_t c; + c.r = a.r + ( b.r - a.r ) * s; + c.g = a.g + ( b.g - a.g ) * s; + c.b = a.b + ( b.b - a.b ) * s; + c.a = a.a + ( b.a - a.a ) * s; + return c; +} + + +img_rgba_t img_sample_clamp( img_t* img, float u, float v ) { + int maxw = ( img->width - 1 ); + int maxh = ( img->height - 1 ); + + float fu = IMG_FLOOR( u ); + float du = u - fu; + float fv = IMG_FLOOR( v ); + float dv = v - fv; + + int x1 = (int) ( fu ); + int y1 = (int) ( fv ); + int x2 = (int) ( fu + 1.0f ); + int y2 = (int) ( fv + 1.0f ); + + x1 = x1 < 0 ? 0 : x1 > maxw ? maxw : x1; + x2 = x2 < 0 ? 0 : x2 > maxw ? maxw : x2; + y1 = y1 < 0 ? 0 : y1 > maxh ? maxh : y1; + y2 = y2 < 0 ? 0 : y2 > maxh ? maxh : y2; + + img_rgba_t c1 = img->pixels[ x1 + y1 * img->width ]; + img_rgba_t c2 = img->pixels[ x2 + y1 * img->width ]; + img_rgba_t c3 = img->pixels[ x1 + y2 * img->width ]; + img_rgba_t c4 = img->pixels[ x2 + y2 * img->width ]; + + return img_rgba_lerp( img_rgba_lerp( c1, c2, du ), img_rgba_lerp( c3, c4, du ), dv ); +} + + +void img_adjust_brightness( img_t* img, float value ) { + if( value == 0.0f ) return; + for( int i = 0; i < img->width * img->height; ++i ) { + img_rgba_t* p = &img->pixels[ i ]; + p->r = p->r + value; + p->g = p->g + value; + p->b = p->b + value; + } +} + +void img_adjust_contrast( img_t* img, float value ) { + if( value == 0.0f ) return; + for( int i = 0; i < img->width * img->height; ++i ) { + img_rgba_t* p = &img->pixels[ i ]; + p->r = ( p->r - 0.5f ) * value + 0.5f; + p->g = ( p->g - 0.5f ) * value + 0.5f; + p->b = ( p->b - 0.5f ) * value + 0.5f; + } +} + +#define img_min( x, y ) ( (x) < (y) ? (x) : (y) ) +#define img_max( x, y ) ( (x) > (y) ? (x) : (y) ) + +img_hsva_t img_rgba_to_hsva( img_rgba_t rgb ) { + img_hsva_t hsv; + hsv.a = rgb.a; + + float cmin = img_min( rgb.r, img_min( rgb.g, rgb.b ) ); //Min. value of RGB + float cmax = img_max( rgb.r, img_max( rgb.g, rgb.b ) ); //Max. value of RGB + float cdel = cmax - cmin; //Delta RGB value + + hsv.v = cmax; + + if( cdel == 0 ) { //This is a gray, no chroma... + hsv.h = 0; //HSV results from 0 to 1 + hsv.s = 0; + } else { //Chromatic data... + hsv.s = cdel / cmax; + + float rdel = ( ( ( cmax - rgb.r ) / 6.0f ) + ( cdel / 2.0f ) ) / cdel; + float gdel = ( ( ( cmax - rgb.g ) / 6.0f ) + ( cdel / 2.0f ) ) / cdel; + float bdel = ( ( ( cmax - rgb.b ) / 6.0f ) + ( cdel / 2.0f ) ) / cdel; + + if( rgb.r == cmax ) { + hsv.h = bdel - gdel; + } else if( rgb.g == cmax ) { + hsv.h = ( 1.0f / 3.0f ) + rdel - bdel; + } else { + hsv.h = ( 2.0f / 3.0f ) + gdel - rdel; + } + + if ( hsv.h < 0.0f ) { + hsv.h += 1.0f; + } + if ( hsv.h > 1.0f ) { + hsv.h -= 1.0f; + } + } + + hsv.h = hsv.h; + hsv.s = hsv.s; + hsv.v = hsv.v; + return hsv; +} + + +img_rgba_t img_hsva_to_rgba( img_hsva_t hsv ) { + img_rgba_t rgb; + rgb.a = hsv.a; + + if( hsv.s == 0.0f ) { // HSV from 0 to 1 + rgb.r = hsv.v; + rgb.g = hsv.v; + rgb.b = hsv.v; + } else { + float h = hsv.h * 6.0f; + if( h == 6.0f ) { + h = 0.0f; //H must be < 1 + } + float i = IMG_FLOOR( h ); + float v1 = hsv.v * ( 1.0f - hsv.s ); + float v2 = hsv.v * ( 1.0f - hsv.s * ( h - i ) ); + float v3 = hsv.v * ( 1.0f - hsv.s * ( 1.0f - ( h - i ) ) ); + + switch( (int) i ) { + case 0: { rgb.r = hsv.v; rgb.g = v3 ; rgb.b = v1 ; } break; + case 1: { rgb.r = v2 ; rgb.g = hsv.v; rgb.b = v1 ; } break; + case 2: { rgb.r = v1 ; rgb.g = hsv.v; rgb.b = v3 ; } break; + case 3: { rgb.r = v1 ; rgb.g = v2 ; rgb.b = hsv.v; } break; + case 4: { rgb.r = v3 ; rgb.g = v1 ; rgb.b = hsv.v; } break; + default:{ rgb.r = hsv.v; rgb.g = v1 ; rgb.b = v2 ; } break; + } + } + + rgb.r = rgb.r; + rgb.g = rgb.g; + rgb.b = rgb.b; + return rgb; +} + + +void img_adjust_saturation( img_t* img, float value ) { + if( value == 0.0f ) return; + for( int i = 0; i < img->width * img->height; ++i ) { + img_rgba_t* p = &img->pixels[ i ]; + img_hsva_t hsv = img_rgba_to_hsva( *p ); + hsv.s = img_clamp( hsv.s + value, 0.0f, 1.0f ); + *p = img_hsva_to_rgba( hsv ); + } +} + + +void img_sharpen( img_t* img, float radius, float blend ) { + float filter[ 9 ] = { + -1.0f, -1.0f, -1.0f, + -1.0f, 9.0f, -1.0f, + -1.0f, -1.0f, -1.0f, + }; + + img_rgba_t* result = (img_rgba_t*) malloc( img->width * img->height * sizeof( img_rgba_t ) ); + + img_rgba_t* src = img->pixels; + img_rgba_t* dst = result; + for( int y = 0; y < img->height; ++y ) { + for( int x = 0; x < img->width; ++x ) { + if( src->a > 0.0f ) { + img_rgba_t acc = { 0.0f, 0.0f, 0.0f, 0.0f }; + for( int fx = -1; fx <= 1; ++fx ) { + for( int fy = -1; fy <= 1; ++fy ) { + float u = ( (float) x ) + ( (float) fx ) * radius; + float v = ( (float) y ) + ( (float) fy ) * radius; + img_rgba_t s = img_sample_clamp( img, u, v ); + if( s.a < 0.0001f ) { + s = *src; + } + acc.r += s.r * ( filter[ ( 1 + fx ) + ( 1 + fy ) * 3 ] ); + acc.g += s.g * ( filter[ ( 1 + fx ) + ( 1 + fy ) * 3 ] ); + acc.b += s.b * ( filter[ ( 1 + fx ) + ( 1 + fy ) * 3 ] ); + } + } + *dst = img_rgba_lerp( *src, acc, blend ); + dst->a = src->a; + } else { + *dst = *src; + } + ++src; + ++dst; + } + } + + free( img->pixels ); + img->pixels = result; +} + +#endif /* IMG_IMPLEMENTATION */ + +/* +------------------------------------------------------------------------------ + +This software is available under 2 licenses - you may choose the one you like. + +------------------------------------------------------------------------------ + +ALTERNATIVE A - MIT License + +Copyright (c) 2019 Mattias Gustavsson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------------------------------------------------------------------ + +ALTERNATIVE B - Public Domain (www.unlicense.org) + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +------------------------------------------------------------------------------ +*/ diff --git a/mus.h b/mus.h new file mode 100644 index 0000000..fd466dc --- /dev/null +++ b/mus.h @@ -0,0 +1,339 @@ +/* +------------------------------------------------------------------------------ + Licensing information can be found at the end of the file. +------------------------------------------------------------------------------ + +mus.h - v0.1 - Parsing library for MUS music files (as used in DOS games). + +Do this: + #define MUS_IMPLEMENTATION +before you include this file in *one* C/C++ file to create the implementation. +*/ + +#ifndef mus_h +#define mus_h + +#include + +typedef struct mus_t mus_t; + +mus_t* mus_create( void const* data, size_t size, void* memctx ); +void mus_destroy( mus_t* mus ); + +typedef enum mus_cmd_t { + MUS_CMD_RELEASE_NOTE, + MUS_CMD_PLAY_NOTE, + MUS_CMD_PITCH_BEND, + MUS_CMD_SYSTEM_EVENT, + MUS_CMD_CONTROLLER, + MUS_CMD_END_OF_MEASURE, + MUS_CMD_FINISH, + MUS_CMD_RENDER_SAMPLES, +} mus_cmd_t; + +struct mus_cmd_release_note_t { + int note; +}; + +struct mus_cmd_play_note_t { + int note; + int volume; +}; + +struct mus_cmd_pitch_bend_t { + int bend_amount; +}; + +enum mus_system_event_t { + MUS_SYSTEM_EVENT_ALL_SOUNDS_OFF, + MUS_SYSTEM_EVENT_ALL_NOTES_OFF, + MUS_SYSTEM_EVENT_MONO, + MUS_SYSTEM_EVENT_POLY, + MUS_SYSTEM_EVENT_RESET_ALL_CONTROLLERS, +}; + +struct mus_cmd_system_event_t { + enum mus_system_event_t event; +}; + +enum mus_controller_t { + MUS_CONTROLLER_CHANGE_INSTRUMENT, + MUS_CONTROLLER_BANK_SELECT, + MUS_CONTROLLER_MODULATION, + MUS_CONTROLLER_VOLUME, + MUS_CONTROLLER_PAN, + MUS_CONTROLLER_EXPRESSION, + MUS_CONTROLLER_REVERB_DEPTH, + MUS_CONTROLLER_CHORUS_DEPTH, + MUS_CONTROLLER_SUSTAIN_PEDAL, + MUS_CONTROLLER_SOFT_PEDAL, +}; + +struct mus_cmd_controller_t { + enum mus_controller_t controller; + int value; +}; + +struct mus_cmd_render_samples_t { + int samples_count; +}; + +union mus_cmd_data_t { + struct mus_cmd_release_note_t release_note; + struct mus_cmd_play_note_t play_note; + struct mus_cmd_pitch_bend_t pitch_bend; + struct mus_cmd_system_event_t system_event; + struct mus_cmd_controller_t controller; + struct mus_cmd_render_samples_t render_samples; +}; + +typedef struct mus_event_t { + int channel; + enum mus_cmd_t cmd; + union mus_cmd_data_t data; +} mus_event_t; + + +void mus_next_event( mus_t* mus, mus_event_t* event ); + +void mus_restart( mus_t* mus ); + +#endif /* mus_h */ + + +/* +---------------------- + IMPLEMENTATION +---------------------- +*/ + +#ifdef MUS_IMPLEMENTATION +#undef MUS_IMPLEMENTATION + +#if !defined( MUS_MALLOC ) || !defined( MUS_FREE ) + #include + #define MUS_MALLOC malloc + #define MUS_FREE free +#endif + +struct mus_t { + int note_volume[ 16 ]; + int accumulated_delay; + int pos; + int length; + uint8_t data[ 1 ]; // "open" array +}; + +mus_t* mus_create( void const* data, size_t size, void* memctx ) { + (void) memctx, (void) size; + uintptr_t ptr = (uintptr_t) data; + uint32_t sig = *(uint32_t*) ptr; + ptr += 4; + if( sig != 0x1a53554d ) { // Identifier "MUS" followed by 0x1A + return NULL; + } + int length = *(uint16_t*) ptr; + ptr += 2; + + int offset = *(uint16_t*) ptr; + ptr += 2; + + if( (size_t)( length + offset ) > size ) { + return NULL; + } + + mus_t* mus = (mus_t*) MUS_MALLOC( sizeof( mus_t ) + length - 1 ); + mus->length = length; + memcpy( mus->data, (void*)( ((uintptr_t)data) + offset ), length ); + mus_restart( mus ); + return mus; +} + + +void mus_destroy( mus_t* mus ) { + MUS_FREE( mus ); +} + + +void mus_next_event( mus_t* mus, mus_event_t* event ) { + if( mus->accumulated_delay ) { + int samples_count = ( mus->accumulated_delay * 44100 ) / 140; + event->channel = 0; + event->cmd = MUS_CMD_RENDER_SAMPLES; + event->data.render_samples.samples_count = samples_count; + mus->accumulated_delay = 0; + return; + } + while( mus->pos < mus->length ) { + uint8_t data = mus->data[ mus->pos++ ]; + int channel = data & 15; + int type = ( data >> 4 ) & 7; + int last = ( data >> 7 ) & 1; + int event_valid = 0; + switch( type ) { + case 0: { // Release Note + data = mus->data[ mus->pos++ ]; + int note = data & 127; + event->channel = channel; + event->cmd = MUS_CMD_RELEASE_NOTE; + event->data.release_note.note = note; + event_valid = 1; + } break; + + case 1: { // Play Note + data = mus->data[ mus->pos++ ]; + int note = data & 127; + int has_vol = ( data >> 7 ); + if( has_vol ) { + data = mus->data[ mus->pos++ ]; + mus->note_volume[ channel ] = data; + } + event->channel = channel; + event->cmd = MUS_CMD_PLAY_NOTE; + event->data.play_note.note = note; + event->data.play_note.volume = mus->note_volume[ channel ]; + event_valid = 1; + } break; + + case 2: { // Pitch Bend + data = mus->data[ mus->pos++ ]; + int bend_amount = data; + event->channel = channel; + event->cmd = MUS_CMD_PITCH_BEND; + event->data.pitch_bend.bend_amount = bend_amount; + event_valid = 1; + } break; + + case 3: { // System Event + data = mus->data[ mus->pos++ ]; + int sysevent = data & 127; + event->channel = channel; + event->cmd = MUS_CMD_SYSTEM_EVENT; + event->data.system_event.event = (enum mus_system_event_t)sysevent; + event_valid = 1; + } break; + + case 4: { // Controller + data = mus->data[ mus->pos++ ]; + int controller = data & 127; + data = mus->data[ mus->pos++ ]; + int value = data & 127; + event->channel = channel; + event->cmd = MUS_CMD_CONTROLLER; + event->data.controller.controller = (enum mus_controller_t)controller; + event->data.controller.value = value; + event_valid = 1; + } break; + + case 5: { // End of Measure + event->channel = channel; + event->cmd = MUS_CMD_END_OF_MEASURE; + event_valid = 1; + } break; + + case 6: { // Finish + event->channel = channel; + event->cmd = MUS_CMD_END_OF_MEASURE; + event_valid = 1; + } break; + + case 7: { // Unused + data = mus->data[ mus->pos++ ]; + } break; + } + + if( last ) { + int delay = 0; + for( ; ; ) { + data = mus->data[ mus->pos++ ]; + delay = delay * 128 + ( data & 127 ); + if( ( data >> 7 ) == 0 ) { + if( event_valid ) { + mus->accumulated_delay = delay; + } else { + int samples_count = ( delay * 44100 ) / 140; + event->channel = 0; + event->cmd = MUS_CMD_RENDER_SAMPLES; + event->data.render_samples.samples_count = samples_count; + event_valid = 1; + } + break; + } + } + } + if( event_valid ) { + return; + } + } + + event->channel = 0; + event->cmd = MUS_CMD_FINISH; +} + + +void mus_restart( mus_t* mus ) { + mus->accumulated_delay = 0; + for( int i = 0; i < sizeof( mus->note_volume ) / sizeof( *mus->note_volume ); ++i ){ + mus->note_volume[ i ] = 127; + } + mus->pos = 0; +} + + +#endif /* MUS_IMPLEMENTATION */ + +/* +------------------------------------------------------------------------------ + +This software is available under 2 licenses - you may choose the one you like. + +------------------------------------------------------------------------------ + +ALTERNATIVE A - MIT License + +Copyright (c) 2021 Mattias Gustavsson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------------------------------------------------------------------ + +ALTERNATIVE B - Public Domain (www.unlicense.org) + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +------------------------------------------------------------------------------ +*/ diff --git a/paldither.h b/paldither.h new file mode 100644 index 0000000..fd616cd --- /dev/null +++ b/paldither.h @@ -0,0 +1,682 @@ +/* +------------------------------------------------------------------------------ + Licensing information can be found at the end of the file. +------------------------------------------------------------------------------ + +paldither.h - v0.1 - Convert true-color image to custom palette, with dither. + +Do this: + #define PALDITHER_IMPLEMENTATION +before you include this file in *one* C/C++ file to create the implementation. +*/ + +#ifndef paldither_h +#define paldither_h + +#define _CRT_NONSTDC_NO_DEPRECATE +#define _CRT_SECURE_NO_WARNINGS +#include + +#ifndef PALDITHER_U32 + #define PALDITHER_U32 unsigned int +#endif + +#ifndef PALDITHER_U8 + #define PALDITHER_U8 unsigned char +#endif + + +typedef enum paldither_type_t + { + PALDITHER_TYPE_DEFAULT, + PALDITHER_TYPE_BAYER, + PALDITHER_TYPE_NONE, + } paldither_type_t; + + +typedef struct paldither_palette_t + { + void* memctx; + int color_count; + PALDITHER_U32 colortable[ 256 ]; + } paldither_palette_t; + +paldither_palette_t* paldither_palette_create( PALDITHER_U32 const* xbgr, int count, size_t* palette_size, void* memctx ); +paldither_palette_t* paldither_palette_create_from_data( void const* data, size_t size, void* memctx ); + +void paldither_palette_destroy( paldither_palette_t* palette ); + +void paldither_palettize( PALDITHER_U32* abgr, int width, int height, paldither_palette_t const* palette, + paldither_type_t dither_type, PALDITHER_U8* output ); + +#endif /* paldither_h */ + + +/* +---------------------- + IMPLEMENTATION +---------------------- +*/ + +#ifdef PALDITHER_IMPLEMENTATION +#undef PALDITHER_IMPLEMENTATION + +#ifndef PALDITHER_MALLOC + #define _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_SECURE_NO_WARNINGS + #include + #if defined(__cplusplus) + #define PALDITHER_MALLOC( ctx, size ) ( ::malloc( size ) ) + #define PALDITHER_FREE( ctx, ptr ) ( ::free( ptr ) ) + #else + #define PALDITHER_MALLOC( ctx, size ) ( malloc( size ) ) + #define PALDITHER_FREE( ctx, ptr ) ( free( ptr ) ) + #endif +#endif + +#ifndef PALDITHER_ASSERT + #undef _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_NONSTDC_NO_DEPRECATE + #undef _CRT_SECURE_NO_WARNINGS + #define _CRT_SECURE_NO_WARNINGS + #include + #define PALDITHER_ASSERT( expression, message ) assert( ( expression ) && ( message ) ) +#endif + +#include + + +typedef struct paldither_mix_t + { + int first; + int second; + int d; + unsigned char ratio; + unsigned char r; + unsigned char g; + unsigned char b; + unsigned char l; + } paldither_mix_t; + + +static void paldither_internal_mix( void* memctx, PALDITHER_U32 const* xbgr, int count, int mix_levels, + paldither_mix_t** out_mix, int* out_mix_count ) + { + (void) memctx; + + int mix_count = ( ( count / 2 ) * ( count + 1 ) ) * mix_levels; + paldither_mix_t* mix = (paldither_mix_t*) PALDITHER_MALLOC( memctx, mix_count * sizeof( paldither_mix_t ) ); + + int c = 0; + for( int i = 0; i < count; ++i ) + { + PALDITHER_U32 fcolor = xbgr[ i ] & 0x00ffffff; + int fr = (int)( ( fcolor & 0x000000ff ) ); + int fg = (int)( ( fcolor & 0x0000ff00 ) >> 8 ); + int fb = (int)( ( fcolor & 0x00ff0000 ) >> 16 ); + int fl = (int)( ( 54 * fr + 183 * fg + 19 * fb + 127 ) >> 8 ); + PALDITHER_ASSERT( fl <= 0xff && fl >= 0, "Value out of range" ); + + for( int j = i + 1; j < count; ++j ) + { + PALDITHER_U32 scolor = xbgr[ j ] & 0x00ffffff; + int sr = (int)( ( scolor & 0x000000ff ) ); + int sg = (int)( ( scolor & 0x0000ff00 ) >> 8 ); + int sb = (int)( ( scolor & 0x00ff0000 ) >> 16 ); + int sl = (int)( ( 54 * sr + 183 * sg + 19 * sb + 127 ) >> 8 ); + PALDITHER_ASSERT( sl <= 0xff && sl >= 0, "Value out of range" ); + + int dr = fr - sr; + int dg = fg - sg; + int db = fb - sb; + int dl = fl - sl; + int d = ( ( ( ( dr*dr + dg*dg + db*db ) >> 1 ) + dl*dl ) + 127 ) >> 8; + + for( int k = 0; k < mix_levels; ++k ) + { + int r = fr; + int g = fg; + int b = fb; + int l = fl; + if( mix_levels > 1 ) + { + int s = mix_levels - 1; + int ik = s - k; + r = ( r * ik + sr * k + ( mix_levels / 2 ) ) / s; + g = ( g * ik + sg * k + ( mix_levels / 2 ) ) / s; + b = ( b * ik + sb * k + ( mix_levels / 2 ) ) / s; + l = ( 54 * r + 183 * g + 19 * b + 127 ) >> 8; + PALDITHER_ASSERT( r <= 0xff && g <= 0xff && b <= 0xff && r >= 0 && g >= 0 && b >= 0 && l <= 0xff && l >= 0, "Value out of range" ); + } + + mix[ c ].first = i; + mix[ c ].second = j; + mix[ c ].ratio = (unsigned char) k; + mix[ c ].r = (unsigned char) r; + mix[ c ].g = (unsigned char) g; + mix[ c ].b = (unsigned char) b; + mix[ c ].l = (unsigned char) l; + mix[ c ].d = d; + ++c; + PALDITHER_ASSERT( mix_count >= c, "Out of range" ); + } + } + } + + *out_mix = mix; + *out_mix_count = c; + } + + +static void paldither_internal_list( void* memctx, paldither_mix_t* mix, int mix_count, + int out_map[ 16 * 16 * 16 ], int** out_list, int* out_list_count ) + { + (void) memctx; + int cube[ 17 * 17 * 17 ]; + for( int r = 0; r < 17; ++r ) + { + for( int g = 0; g < 17; ++g ) + { + for( int b = 0; b < 17; ++b ) + { + int best_diff = 0x7FFFFFFF; + int best_mix = 0; + paldither_mix_t const* m = mix; + int l = ( 54 * (r * 16) + 183 * (g * 16) + 19 * (b * 16) + 127 ) >> 8; + for( int i = 0; i < mix_count; ++i, ++m ) + { + int dr = r * 16 - m->r; + int dg = g * 16 - m->g; + int db = b * 16 - m->b; + int dl = l - m->l; + int d = ( ( ( dr*dr + dg*dg + db*db ) >> 1 ) + dl*dl) + ( m->d * 3 ); + if( i == 0 || d < best_diff ) { best_diff = d; best_mix = i; } + } + cube[ r * 17 * 17 + g * 17 + b ] = best_mix; + } + } + } + + int map[ 16 * 16 * 16 ]; + int list_capacity = mix_count * 256; + int* list = (int*) PALDITHER_MALLOC( memctx, list_capacity * sizeof( int ) ); + int list_count = 0; + + int* mapptr = map; + for( int r = 0; r < 16; ++r ) + { + for( int g = 0; g < 16; ++g ) + { + for( int b = 0; b < 16; ++b ) + { + paldither_mix_t const* m = mix; + *mapptr++ = list_count; + if( list_count == list_capacity ) + { + list_capacity *= 2; + int* new_list = (int*) PALDITHER_MALLOC( memctx, list_capacity * sizeof( int ) ); + memcpy( new_list, list, list_count * sizeof( int ) ); + PALDITHER_FREE( memctx, list ); + list = new_list; + } + int count_index = list_count++; + list[ count_index ] = 0; + for( int i = 0; i < mix_count; ++i, ++m ) + { + paldither_mix_t const* best_mix = &mix[ cube[ ( r ) * 17 * 17 + ( g ) * 17 + ( b ) ] ]; + paldither_mix_t const* best_mix2 = &mix[ cube[ ( r + 1 ) * 17 * 17 + ( g + 1 ) * 17 + ( b + 1 ) ] ]; + int pass = + ( m->r >= best_mix->r && m->r <= best_mix2->r ) + && ( m->g >= best_mix->g && m->g <= best_mix2->g ) + && ( m->b >= best_mix->b && m->b <= best_mix2->b ); + if( pass ) + { + list[ count_index ]++; + if( list_count == list_capacity ) + { + list_capacity *= 2; + int* new_list = (int*) PALDITHER_MALLOC( memctx, list_capacity * sizeof( int ) ); + memcpy( new_list, list, list_count * sizeof( int ) ); + PALDITHER_FREE( memctx, list ); + list = new_list; + } + list[ list_count++ ] = i; + } + + } + } + } + } + + memcpy( out_map, map, sizeof( map ) ); + *out_list = list; + *out_list_count = list_count; + } + + +paldither_palette_t* paldither_palette_create( PALDITHER_U32 const* xbgr, int count, size_t* palette_size, void* memctx ) + { + (void) memctx; + + int default_mix_count; + paldither_mix_t* default_mix; + paldither_internal_mix( memctx, xbgr, count, 11, &default_mix, &default_mix_count ); + + int default_map[ 16 * 16 * 16 ]; + int* default_list; + int default_list_count = 0; + paldither_internal_list( memctx, default_mix, default_mix_count, default_map, &default_list, &default_list_count ); + + int bayer_mix_count; + paldither_mix_t* bayer_mix; + paldither_internal_mix( memctx, xbgr, count, 17, &bayer_mix, &bayer_mix_count ); + + int bayer_map[ 16 * 16 * 16 ]; + int* bayer_list; + int bayer_list_count = 0; + paldither_internal_list( memctx, bayer_mix, bayer_mix_count, bayer_map, &bayer_list, &bayer_list_count ); + + int nodither_mix_count; + paldither_mix_t* nodither_mix; + paldither_internal_mix( memctx, xbgr, count, 1, &nodither_mix, &nodither_mix_count ); + + int nodither_map[ 16 * 16 * 16 ]; + int* nodither_list; + int nodither_list_count = 0; + paldither_internal_list( memctx, nodither_mix, nodither_mix_count, nodither_map, &nodither_list, &nodither_list_count ); + + size_t size = sizeof( paldither_palette_t ) + + sizeof( int ) + default_list_count * sizeof( int ) + + sizeof( int ) + default_mix_count * sizeof( paldither_mix_t ) + + sizeof( default_map ) + + sizeof( int ) + bayer_list_count * sizeof( int ) + + sizeof( int ) + bayer_mix_count * sizeof( paldither_mix_t ) + + sizeof( bayer_map ) + + sizeof( int ) + nodither_list_count * sizeof( int ) + + sizeof( int ) + nodither_mix_count * sizeof( paldither_mix_t ) + + sizeof( nodither_map ); + paldither_palette_t* palette = (paldither_palette_t*) PALDITHER_MALLOC( memctx, size ); + palette->memctx = memctx; + + palette->color_count = count; + memcpy( palette->colortable, xbgr, sizeof( *xbgr ) * count ); + + uintptr_t dest = (uintptr_t)( palette + 1) ; + + *(int*) dest = default_mix_count; dest += sizeof( int ); + memcpy( (void*)dest, default_mix, default_mix_count * sizeof( paldither_mix_t ) ); + dest += default_mix_count * sizeof( paldither_mix_t ); + + memcpy( (void*)dest, default_map, sizeof( default_map ) ); + dest += sizeof( default_map ); + + *(int*) dest = default_list_count; dest += sizeof( int ); + memcpy( (void*)dest, default_list, default_list_count * sizeof( int ) ); + dest += default_list_count * sizeof( int ); + + PALDITHER_FREE( memctx, default_list ); + PALDITHER_FREE( memctx, default_mix ); + + *(int*) dest = bayer_mix_count; dest += sizeof( int ); + memcpy( (void*)dest, bayer_mix, bayer_mix_count * sizeof( paldither_mix_t ) ); + dest += bayer_mix_count * sizeof( paldither_mix_t ); + + memcpy( (void*)dest, bayer_map, sizeof( bayer_map ) ); + dest += sizeof( bayer_map ); + + *(int*) dest = bayer_list_count; dest += sizeof( int ); + memcpy( (void*)dest, bayer_list, bayer_list_count * sizeof( int ) ); + dest += bayer_list_count * sizeof( int ); + + PALDITHER_FREE( memctx, bayer_list ); + PALDITHER_FREE( memctx, bayer_mix ); + + *(int*) dest = nodither_mix_count; dest += sizeof( int ); + memcpy( (void*)dest, nodither_mix, nodither_mix_count * sizeof( paldither_mix_t ) ); + dest += nodither_mix_count * sizeof( paldither_mix_t ); + + memcpy( (void*)dest, nodither_map, sizeof( nodither_map ) ); + dest += sizeof( nodither_map ); + + *(int*) dest = nodither_list_count; dest += sizeof( int ); + memcpy( (void*)dest, nodither_list, nodither_list_count * sizeof( int ) ); + dest += nodither_list_count * sizeof( int ); + + PALDITHER_FREE( memctx, nodither_list ); + PALDITHER_FREE( memctx, nodither_mix ); + + if( palette_size ) *palette_size = size; + return palette; + } + + +paldither_palette_t* paldither_palette_create_from_data( void const* data, size_t size, void* memctx ) + { + paldither_palette_t* palette = (paldither_palette_t*)PALDITHER_MALLOC( memctx, size ); + palette->memctx = memctx; + memcpy( &palette->color_count, data, size ); + return palette; + } + + +void paldither_palette_destroy( paldither_palette_t* palette ) + { + PALDITHER_FREE( palette->memctx, palette ); + } + + +void paldither_palettize( PALDITHER_U32* abgr, int width, int height, paldither_palette_t const* palette, + paldither_type_t dither_type, PALDITHER_U8* output ) + { + unsigned char default_dither_pattern[ 4 * 4 * 11 ] = + { + 0,0,0,0, + 0,0,0,0, + 0,0,0,0, + 0,0,0,0, + + 0,0,0,0, + 0,0,0,0, + 0,0,0,0, + 0,0,0,0, + + 0,0,0,0, + 0,0,0,0, + 0,0,0,0, + 0,0,0,0, + + 0,0,0,0, + 0,0,0,0, + 0,0,0,0, + 0,0,0,1, + + 1,0,1,0, + 0,1,0,0, + 1,0,1,0, + 0,0,0,1, + + 1,0,1,0, + 0,1,0,1, + 1,0,1,0, + 0,1,0,1, + + 1,0,1,0, + 1,1,0,1, + 1,0,1,0, + 0,1,1,1, + + 1,1,1,1, + 1,1,1,1, + 1,1,1,1, + 1,1,1,1, + + 1,1,1,1, + 1,1,1,1, + 1,1,1,1, + 1,1,1,1, + + 1,1,1,1, + 1,1,1,1, + 1,1,1,1, + 1,1,1,1, + + 1,1,1,1, + 1,1,1,1, + 1,1,1,1, + 1,1,1,1, + + }; + + unsigned char bayer_dither_pattern[ 4 * 4 * 17 ] = + { + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + + 1, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + + 1, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 0, + + 1, 0, 1, 0, + 0, 0, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 0, + + 1, 0, 1, 0, + 0, 0, 0, 0, + 1, 0, 1, 0, + 0, 0, 0, 0, + + 1, 0, 1, 0, + 0, 1, 0, 0, + 1, 0, 1, 0, + 0, 0, 0, 0, + + 1, 0, 1, 0, + 0, 1, 0, 0, + 1, 0, 1, 0, + 0, 0, 0, 1, + + 1, 0, 1, 0, + 0, 1, 0, 1, + 1, 0, 1, 0, + 0, 0, 0, 1, + + 1, 0, 1, 0, + 0, 1, 0, 1, + 1, 0, 1, 0, + 0, 1, 0, 1, + + 1, 1, 1, 0, + 0, 1, 0, 1, + 1, 0, 1, 0, + 0, 1, 0, 1, + + 1, 1, 1, 0, + 0, 1, 0, 1, + 1, 0, 1, 1, + 0, 1, 0, 1, + + 1, 1, 1, 1, + 0, 1, 0, 1, + 1, 0, 1, 1, + 0, 1, 0, 1, + + 1, 1, 1, 1, + 0, 1, 0, 1, + 1, 1, 1, 1, + 0, 1, 0, 1, + + 1, 1, 1, 1, + 1, 1, 0, 1, + 1, 1, 1, 1, + 0, 1, 0, 1, + + 1, 1, 1, 1, + 1, 1, 0, 1, + 1, 1, 1, 1, + 0, 1, 1, 1, + + 1, 1, 1, 1, + 1, 1, 1, 1, + 1, 1, 1, 1, + 0, 1, 1, 1, + + 1, 1, 1, 1, + 1, 1, 1, 1, + 1, 1, 1, 1, + 1, 1, 1, 1, + }; + + unsigned char none_dither_pattern[ 4 * 4 * 2 ] = + { + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + }; + + + uintptr_t ptr = (uintptr_t)( palette + 1 ); + + int default_pal_mix_count = *(int*)ptr; ptr += sizeof( int ); + paldither_mix_t const* default_pal_mix = (paldither_mix_t*) ptr; ptr += default_pal_mix_count * sizeof( paldither_mix_t ); + int const* default_pal_map = (int*) ptr; ptr += 16 * 16 * 16 * sizeof( int ); + int default_pal_list_count = *(int*)ptr; ptr += sizeof( int ); + int const* default_pal_list = (int*) ptr; ptr += default_pal_list_count * sizeof( int ); + + int bayer_pal_mix_count = *(int*)ptr; ptr += sizeof( int ); + paldither_mix_t const* bayer_pal_mix = (paldither_mix_t*) ptr; ptr += bayer_pal_mix_count * sizeof( paldither_mix_t ); + int const* bayer_pal_map = (int*) ptr; ptr += 16 * 16 * 16 * sizeof( int ); + int bayer_pal_list_count = *(int*)ptr; ptr += sizeof( int ); + int const* bayer_pal_list = (int*) ptr; ptr += bayer_pal_list_count * sizeof( int ); + + int nodither_pal_mix_count = *(int*)ptr; ptr += sizeof( int ); + paldither_mix_t const* nodither_pal_mix = (paldither_mix_t*) ptr; ptr += nodither_pal_mix_count * sizeof( paldither_mix_t ); + int const* nodither_pal_map = (int*) ptr; ptr += 16 * 16 * 16 * sizeof( int ); + int nodither_pal_list_count = *(int*)ptr; ptr += sizeof( int ); + int const* nodither_pal_list = (int*) ptr; ptr += nodither_pal_list_count * sizeof( int ); + + unsigned char* dither_pattern = default_dither_pattern; + int pal_mix_count = default_pal_mix_count; + paldither_mix_t const* pal_mix = default_pal_mix; + int const* pal_map = default_pal_map; + int const* pal_list = default_pal_list; + + if( dither_type == PALDITHER_TYPE_BAYER ) + { + dither_pattern = bayer_dither_pattern; + pal_mix_count = bayer_pal_mix_count; + pal_mix = bayer_pal_mix; + pal_map = bayer_pal_map; + pal_list = bayer_pal_list; + } + else if( dither_type == PALDITHER_TYPE_NONE ) + { + dither_pattern = none_dither_pattern; + pal_mix_count = nodither_pal_mix_count; + pal_mix = nodither_pal_mix; + pal_map = nodither_pal_map; + pal_list = nodither_pal_list; + } + + for( int y = 0; y < height; ++y ) + { + for( int x = 0; x < width; ++x ) + { + PALDITHER_U32 color = abgr[ x + y * width ]; + int r = (int)( ( color & 0x000000ff ) ); + int g = (int)( ( color & 0x0000ff00 ) >> 8 ); + int b = (int)( ( color & 0x00ff0000 ) >> 16 ); + int l = (int)( ( 54 * r + 183 * g + 19 * b + 127 ) >> 8 ); + PALDITHER_ASSERT( l <= 0xff && l >= 0, "Value out of range" ); + + paldither_mix_t const* best_mix = 0; + int pal_index = pal_map[ ( r >> 4 ) * 16 * 16 + ( g >> 4 ) * 16 + ( b >> 4 ) ]; + int count = pal_list[ pal_index++ ]; + if( count != 0 ) + { + int best_diff = 0x7FFFFFFF; + int const* index = &pal_list[ pal_index ]; + for( int i = 0; i < count; ++i, ++index ) + { + paldither_mix_t const* m = &pal_mix[ *index ]; + int dr = r - m->r; + int dg = g - m->g; + int db = b - m->b; + int dl = l - m->l; + int d = ( ( ( dr*dr + dg*dg + db*db ) >> 1 ) + dl*dl) + ( m->d * 3 ); + if( i == 0 || d < best_diff ) { best_diff = d; best_mix = m; } + } + } + else + { + int best_diff = 0x7FFFFFFF; + paldither_mix_t const* m = pal_mix; + for( int i = 0; i < pal_mix_count; ++i, ++m ) + { + int dr = r - m->r; + int dg = g - m->g; + int db = b - m->b; + int dl = l - m->l; + int d = ( ( ( dr*dr + dg*dg + db*db ) >> 1 ) + dl*dl) + ( m->d * 3 ); + if( i == 0 || d < best_diff ) { best_diff = d; best_mix = m; } + } + } + + int index = dither_pattern[ best_mix->ratio * 4 * 4 + ( x & 3 ) + ( y & 3 ) * 4 ] ? + best_mix->second : best_mix->first; + + if( output) output[ x + y * width ] = (PALDITHER_U8) index; + abgr[ x + y * width ] = ( abgr[ x + y * width ] & 0xff000000 ) | ( palette->colortable[ index ] & 0x00ffffff ); + } + } + } + + +#endif /* PALDITHER_IMPLEMENTATION */ + + + +/* +------------------------------------------------------------------------------ + +This software is available under 2 licenses - you may choose the one you like. + +------------------------------------------------------------------------------ + +ALTERNATIVE A - MIT License + +Copyright (c) 2015 Mattias Gustavsson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------------------------------------------------------------------ + +ALTERNATIVE B - Public Domain (www.unlicense.org) + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +------------------------------------------------------------------------------ +*/ diff --git a/palettize.h b/palettize.h new file mode 100644 index 0000000..35f13fa --- /dev/null +++ b/palettize.h @@ -0,0 +1,718 @@ +/* +------------------------------------------------------------------------------ + Licensing information can be found at the end of the file. +------------------------------------------------------------------------------ + +palettize.h - v0.1 - Median-cut palette generation and remapping for C/C++. + +Do this: + #define PALETTIZE_IMPLEMENTATION +before you include this file in *one* C/C++ file to create the implementation. +*/ + +#ifndef palettize_h +#define palettize_h + + +#ifndef PALETTIZE_U32 + #define PALETTIZE_U32 unsigned int +#endif + +#ifndef PALETTIZE_U16 + #define PALETTIZE_U16 unsigned short +#endif + +#ifndef PALETTIZE_U8 + #define PALETTIZE_U8 unsigned char +#endif + + +int palettize_generate_palette_xbgr32( PALETTIZE_U32 const* xbgr, int width, int height, + PALETTIZE_U32* palette, int palette_size, void* memctx ); + +void palettize_remap_xbgr32( PALETTIZE_U32 const* xbgr, int width, int height, + PALETTIZE_U32 const* palette, int palette_size, PALETTIZE_U8* output ); + + +int palettize_generate_palette_rgb16( PALETTIZE_U16 const* rgb, int width, int height, + PALETTIZE_U16* palette, int palette_size, void* memctx ); + +void palettize_remap_rgb16( PALETTIZE_U16 const* rgb, int width, int height, + PALETTIZE_U16 const* palette, int palette_size, PALETTIZE_U8* output ); + + +int palettize_generate_rgb16_palette_xbgr32( PALETTIZE_U32 const* xbgr, int width, int height, + PALETTIZE_U16* palette, int palette_size, void* memctx ); + +void palettize_remap_xbgr32_pal16( PALETTIZE_U32 const* xbgr, int width, int height, + PALETTIZE_U16 const* palette, int palette_size, PALETTIZE_U8* output ); + + +#endif /* palettize_h */ + +/** + +Example +======= + +An example which loads a bitmap, generate a palette from it, and remap the image to that palette: + + #define PALETTIZE_IMPLEMENTATION + #include "palettize.h + + #define STB_IMAGE_IMPLEMENTATION + #include "stb_image.h" + + #define STB_IMAGE_WRITE_IMPLEMENTATION + #include "stb_image_write.h" + + int main( int argc, char** argv ) + { + (void) argc, argv; + + int w, h, c; + PALETTIZE_U32* img = (PALETTIZE_U32*) stbi_load( "test.png", &w, &h, &c, 4 ); + + PALETTIZE_U32 pal[ 256 ]; + int pal_count = palettize_generate_palette_xbgr32( img, w, h, pal, 256, 0 ); + + PALETTIZE_U8* palimg = (PALETTIZE_U8*) malloc( w * h ); + palettize_remap_xbgr32( img, w, h, pal, pal_count, palimg ); + + for( int i = 0; i < w * h; ++i ) img[ i ] = pal[ palimg[ i ] ]; + stbi_write_png( "palettized.png", w, h, 4, img, w * 4 ); + free( palimg ); + stbi_image_free( img ); + } + + // pass-through so the program will build with either /SUBSYSTEM:WINDOWS or /SUBSYSTEN:CONSOLE + extern "C" int __stdcall WinMain( struct HINSTANCE__*, struct HINSTANCE__*, char*, int ) { return main( __argc, __argv ); } + +**/ + + + +/* +---------------------- + IMPLEMENTATION +---------------------- +*/ + +#ifdef PALETTIZE_IMPLEMENTATION +#undef PALETTIZE_IMPLEMENTATION + + +#ifndef PALETTIZE_MALLOC + #define _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_SECURE_NO_WARNINGS + #include + #if defined(__cplusplus) + #define PALETTIZE_MALLOC( ctx, size ) ( ::malloc( size ) ) + #define PALETTIZE_FREE( ctx, ptr ) ( ::free( ptr ) ) + #else + #define PALETTIZE_MALLOC( ctx, size ) ( malloc( size ) ) + #define PALETTIZE_FREE( ctx, ptr ) ( free( ptr ) ) + #endif +#endif + + +typedef struct palettize_internal_rgb_t { PALETTIZE_U8 rgb[ 3 ]; } palettize_internal_rgb_t; + + +typedef struct palettize_internal_bucket_t + { + palettize_internal_rgb_t* points; + int points_count; + palettize_internal_rgb_t min_val; + palettize_internal_rgb_t max_val; + } palettize_internal_bucket_t; + + +static void palettize_internal_bucket_init( palettize_internal_bucket_t* bucket, palettize_internal_rgb_t* points, + int points_count ) + { + bucket->points = points; + bucket->points_count = points_count; + + for( int j = 0; j < 3; ++j ) bucket->min_val.rgb[ j ] = bucket->max_val.rgb[ j ] = bucket->points[ 0 ].rgb[ j ]; + + for( int i = 1; i < bucket->points_count; ++i ) + { + for( int j = 0; j < 3; ++j ) + { + bucket->min_val.rgb[ j ] = bucket->min_val.rgb[ j ] < bucket->points[ i ].rgb[ j ] ? + bucket->min_val.rgb[ j ] : bucket->points[ i ].rgb[ j ]; + bucket->max_val.rgb[ j ] = bucket->max_val.rgb[ j ] > bucket->points[ i ].rgb[ j ] ? + bucket->max_val.rgb[ j ] : bucket->points[ i ].rgb[ j ]; + } + } + } + + +static int palettize_internal_bucket_largest_range( palettize_internal_bucket_t const* bucket ) + { + int m = bucket->max_val.rgb[ 0 ] - bucket->min_val.rgb[ 0 ]; + int max_index = 0; + for( int i = 1; i < 3; ++i ) + { + int diff = bucket->max_val.rgb[ i ] - bucket->min_val.rgb[ i ]; + if( diff > m ) { m = diff; max_index = i; } + } + return max_index; + } + + +static int palettize_internal_bucket_compare( palettize_internal_bucket_t const* a, + palettize_internal_bucket_t const* b ) + { + int i = palettize_internal_bucket_largest_range( a ); + int j = palettize_internal_bucket_largest_range( b ); + int ra = a->max_val.rgb[ i ] - a->min_val.rgb[ i ]; + int rb = b->max_val.rgb[ j ] - b->min_val.rgb[ j ]; + return ra < rb ? -1 : ra > rb ? 1 : 0; + } + + +typedef struct palettize_internal_priority_queue_t + { + palettize_internal_bucket_t* elements; + int capacity; + int count; + } palettize_internal_priority_queue_t; + + +static void priority_queue_push( palettize_internal_priority_queue_t* queue, palettize_internal_bucket_t const* value ) + { + PALDITHER_ASSERT( queue->count < queue->capacity, "Priority queue overflow" ); + if( queue->count >= queue->capacity ) return; + queue->elements[ queue->count++ ] = *value; + int index = queue->count; + while( index > 1 && + palettize_internal_bucket_compare( &queue->elements[ index - 1 ], &queue->elements[ index / 2 - 1 ] ) > 0 ) + { + palettize_internal_bucket_t temp = queue->elements[ index / 2 - 1 ]; + queue->elements[ index / 2 - 1 ] = queue->elements[ index - 1 ]; + queue->elements[ index - 1 ] = temp; + index /=2; + } + } + + +static void priority_queue_pop( palettize_internal_priority_queue_t* queue ) + { + if( queue->count == 0 ) return; + queue->elements[ 0 ] = queue->elements[ --queue->count ]; + int v = 1; + int u = 0; + while( u != v) + { + u = v; + if( 2 * u + 1 <= queue->count ) + { + if( palettize_internal_bucket_compare( &queue->elements[ u - 1 ], &queue->elements[ 2 * u - 1 ] ) <= 0 ) + v = 2 * u; + if( palettize_internal_bucket_compare( &queue->elements[ v - 1 ], &queue->elements[ 2 * u + 1 - 1 ] ) <= 0 ) + v = 2 * u + 1; + } + else if ( 2 * u <= queue->count ) + { + if( palettize_internal_bucket_compare( &queue->elements[ u - 1 ], &queue->elements[ 2 * u - 1 ] ) <= 0 ) + v = 2 * u; + } + + if( u != v ) + { + palettize_internal_bucket_t temp = queue->elements[ u - 1 ]; + queue->elements[ u - 1 ] = queue->elements[ v - 1 ]; + queue->elements[ v - 1 ] = temp; + } + } + } + + +static void palettize_internal_nth_element(palettize_internal_rgb_t* first, palettize_internal_rgb_t* nth, + palettize_internal_rgb_t* last, int index) + { + while( last - first > 3 ) + { + palettize_internal_rgb_t const* a = first; + palettize_internal_rgb_t const* b = first + ( last - first ) / 2; + palettize_internal_rgb_t const* c = last - 1; + palettize_internal_rgb_t const* pivot; + if( a->rgb[ index ] < b->rgb[ index ] ) + pivot = b->rgb[ index ] < c->rgb[ index ] ? b : a->rgb[ index ] < c->rgb[ index ] ? c : a; + else + pivot = a->rgb[ index ] < c->rgb[ index ] ? a : b->rgb[ index ] < c->rgb[ index ] ? c : b; + + palettize_internal_rgb_t* part_first = first; + palettize_internal_rgb_t* part_last = last; + palettize_internal_rgb_t* cut; + for( ; ; ) + { + while( part_first->rgb[ index ] < pivot->rgb[ index ] ) ++part_first; + --part_last; + while( pivot->rgb[ index ] < part_last->rgb[ index ] ) --part_last; + if( part_first >= part_last ) { cut = part_first; break; } + palettize_internal_rgb_t tmp = *part_first; *part_first = *part_last; *part_last = tmp; + ++part_first; + } + if( cut <= nth ) first = cut; else last = cut; + } + + if( first == last ) return; + for( palettize_internal_rgb_t* i = first + 1; i != last; ++i ) + { + if( i->rgb[ index ] < first->rgb[ index ] ) + { + palettize_internal_rgb_t* copy_last = i; + palettize_internal_rgb_t* copy_result = i + 1; + while( first != copy_last ) *( --copy_result ) = *( --copy_last ); + *first = *i; + } + else + { + palettize_internal_rgb_t* ins_last = i; + palettize_internal_rgb_t* next = ins_last; + --next; + while( i->rgb[ index ] < next->rgb[ index ] ) { *ins_last = *next; ins_last = next; --next; } + *ins_last = *i; + } + } + } + + +static int palettize_internal_median_cut(palettize_internal_rgb_t* image, int points_count, + palettize_internal_bucket_t* work_mem, int desired_size, palettize_internal_rgb_t* output ) + { + palettize_internal_priority_queue_t bucket_queue; + bucket_queue.count = 0; + bucket_queue.capacity = desired_size; + bucket_queue.elements = work_mem; + + palettize_internal_bucket_t initial_bucket; + palettize_internal_bucket_init( &initial_bucket, image, points_count ); + + priority_queue_push( &bucket_queue, &initial_bucket ); + while( bucket_queue.count > 0 && bucket_queue.elements[ 0 ].points_count > 1 ) + { + if( bucket_queue.count >= desired_size ) break; + palettize_internal_bucket_t largest_range_bucket = bucket_queue.elements[ 0 ]; + + priority_queue_pop( &bucket_queue ); + palettize_internal_rgb_t * begin = largest_range_bucket.points; + palettize_internal_rgb_t * median = largest_range_bucket.points + ( largest_range_bucket.points_count + 1 ) / 2; + palettize_internal_rgb_t * end = largest_range_bucket.points + largest_range_bucket.points_count; + + switch( palettize_internal_bucket_largest_range( &largest_range_bucket ) ) + { + case 0: palettize_internal_nth_element( begin, median, end, 0 ); break; + case 1: palettize_internal_nth_element( begin, median, end, 1 ); break; + case 2: palettize_internal_nth_element( begin, median, end, 2 ); break; + } + + palettize_internal_bucket_t bucket1; + palettize_internal_bucket_init( &bucket1, begin, (int)( median-begin ) ); + priority_queue_push( &bucket_queue, &bucket1); + + palettize_internal_bucket_t bucket2; + palettize_internal_bucket_init( &bucket2, median, (int)( end-median ) ); + priority_queue_push( &bucket_queue, &bucket2); + } + + int result = 0; + while( bucket_queue.count > 0 ) + { + palettize_internal_bucket_t bucket = bucket_queue.elements[ 0 ]; + priority_queue_pop( &bucket_queue ); + + int sum[ 3 ] = { 0, 0, 0 }; + for( int i = 0; i < bucket.points_count; ++i ) + for( int j = 0; j < 3; ++j ) + sum[ j ] += bucket.points[ i ].rgb[ j ]; + + if( bucket.points_count ) + { + palettize_internal_rgb_t average; + for( int j = 0; j < 3; ++j ) average.rgb[ j ] = (PALETTIZE_U8) ( sum[ j ] / bucket.points_count ); + + output[ result++ ] = average; + } + } + + return result; + } + + +int palettize_generate_palette_xbgr32( PALETTIZE_U32 const* xbgr, int width, int height, + PALETTIZE_U32* palette, int palette_size, void* memctx ) + { + (void) memctx; + int pixel_count = width * height; + + int count = 0; + for( int i = 0; i < pixel_count; ++i ) + { + if( ( xbgr[ i ] >> 24 ) == 0 ) continue; + int found = 0; + for( int j = 0; j < count; ++j ) + { + if( ( palette[ j ] & 0x00ffffff ) == ( xbgr[ i ] & 0x00ffffff ) ) + { + found = 1; + break; + } + } + if( !found ) + { + if( count >= palette_size ) goto skip; + palette[ count++ ] = xbgr[ i ]; + } + } + + return count; + +skip: ; + size_t malloc_size = sizeof( palettize_internal_rgb_t ) * ( pixel_count + palette_size ); + malloc_size += sizeof( palettize_internal_bucket_t ) * palette_size; + palettize_internal_rgb_t* data = (palettize_internal_rgb_t*) PALETTIZE_MALLOC( memctx, malloc_size ); + + int data_size = 0; + for( int p = 0; p < pixel_count; ++p ) + { + PALETTIZE_U32 color = *xbgr++; + PALETTIZE_U8 a = (PALETTIZE_U8 ) ( ( color & 0xff000000 ) >> 24 ); + if( a > 0 ) + { + PALETTIZE_U8 b = (PALETTIZE_U8) ( ( color & 0x00ff0000 ) >> 16 ); + PALETTIZE_U8 g = (PALETTIZE_U8) ( ( color & 0x0000ff00 ) >> 8 ); + PALETTIZE_U8 r = (PALETTIZE_U8) ( ( color & 0x000000ff ) ); + data[ data_size ].rgb[ 0 ] = r; + data[ data_size ].rgb[ 1 ] = g; + data[ data_size ].rgb[ 2 ] = b; + ++data_size; + } + } + palettize_internal_rgb_t* result = data + pixel_count; + palettize_internal_bucket_t* work_mem = (palettize_internal_bucket_t*) ( data + pixel_count + palette_size ); + int result_count = palettize_internal_median_cut( data, data_size, work_mem, palette_size, result ); + + count = 0; + for( int i = 0; i < result_count; ++i ) + { + palettize_internal_rgb_t p = result[ i ]; + PALETTIZE_U32 c = 0xff000000 | ( p.rgb[ 2 ] << 16 ) | ( p.rgb[ 1 ] << 8 ) | p.rgb[ 0 ]; + int found = 0; + for( int j = 0; j < count; ++j ) if( palette[ j ] == c ) { found = 1; break; } + if( !found ) palette[ count++ ] = c; + if( count >= palette_size ) break; + } + + PALETTIZE_FREE( memctx, data ); + return count; + } + + +void palettize_remap_xbgr32( PALETTIZE_U32 const* xbgr, int width, int height, + PALETTIZE_U32 const* palette, int palette_size, PALETTIZE_U8* output ) + { + for( int y = 0; y < height; ++y ) + { + for( int x = 0; x < width; ++x ) + { + PALETTIZE_U32 color = *xbgr++; + int best_index = 0; + int mindist_sq = 255 * 255 + 255 * 255 + 255 * 255 + 1; + for( int i = 0; i < palette_size; ++i ) + { + PALETTIZE_U8 cr = ( (PALETTIZE_U8) ( ( color & 0x00ff0000 ) >> 16 ) ); + PALETTIZE_U8 cg = ( (PALETTIZE_U8) ( ( color & 0x0000ff00 ) >> 8 ) ); + PALETTIZE_U8 cb = ( (PALETTIZE_U8) ( ( color & 0x000000ff ) ) ); + PALETTIZE_U8 pr = ( (PALETTIZE_U8) ( ( palette[ i ] & 0x00ff0000 ) >> 16 ) ); + PALETTIZE_U8 pg = ( (PALETTIZE_U8) ( ( palette[ i ] & 0x0000ff00 ) >> 8 ) ); + PALETTIZE_U8 pb = ( (PALETTIZE_U8) ( ( palette[ i ] & 0x000000ff ) ) ); + int dr = ( (int) cr ) - ( (int) pr ); + int dg = ( (int) cg ) - ( (int) pg ); + int db = ( (int) cb ) - ( (int) pb ); + int dist_sq = dr * dr + dg * dg + db * db; + if( dist_sq < mindist_sq ) { mindist_sq = dist_sq; best_index = i; } + } + *output++ = (PALETTIZE_U8) best_index; + } + } + } + + +static PALETTIZE_U16 palettize_internal_rgb32_to_rgb16( PALETTIZE_U32 color ) + { + return ((PALETTIZE_U16) ( ((color & 0x00f80000)>>8) | ((color & 0x0000fc00)>>5) | ((color & 0x000000f8)>>3) )); + } + + +static PALETTIZE_U32 palettize_internal_rgb16_to_rgb32( PALETTIZE_U16 color ) + { + return (((PALETTIZE_U32)color & 0xf800)<<8) | (((PALETTIZE_U32)color & 0x07e0)<<5) | + (((PALETTIZE_U32)color & 0x001f)<<3) | (0xff000000); + } + + +int palettize_generate_palette_rgb16( PALETTIZE_U16 const* rgb, int width, int height, + PALETTIZE_U16* palette, int palette_size, void* memctx ) + { + (void) memctx; + int pixel_count = width * height; + + int count = 0; + for( int i = 0; i < pixel_count; ++i ) + { + int found = 0; + for( int j = 0; j < count; ++j ) + { + if( ( palette[ j ] ) == ( rgb[ i ] & 0x00ffffff ) ) + { + found = 1; + break; + } + } + if( !found ) + { + if( count >= palette_size ) goto skip; + palette[ count++ ] = rgb[ i ]; + } + } + + return count; + +skip: ; + size_t malloc_size = sizeof( palettize_internal_rgb_t ) * ( pixel_count + palette_size ); + malloc_size += sizeof( palettize_internal_bucket_t ) * palette_size; + palettize_internal_rgb_t* data = (palettize_internal_rgb_t*) PALETTIZE_MALLOC( memctx, malloc_size ); + + int data_size = 0; + for( int p = 0; p < pixel_count; ++p ) + { + PALETTIZE_U32 color = palettize_internal_rgb16_to_rgb32( *rgb++ ); + PALETTIZE_U8 a = (PALETTIZE_U8) ( ( color & 0xff000000 ) >> 24 ); + if( a > 0 ) + { + PALETTIZE_U8 b = (PALETTIZE_U8) ( ( color & 0x00ff0000 ) >> 16 ); + PALETTIZE_U8 g = (PALETTIZE_U8) ( ( color & 0x0000ff00 ) >> 8 ); + PALETTIZE_U8 r = (PALETTIZE_U8) ( ( color & 0x000000ff ) ); + data[ data_size ].rgb[ 0 ] = r; + data[ data_size ].rgb[ 1 ] = g; + data[ data_size ].rgb[ 2 ] = b; + ++data_size; + } + } + + palettize_internal_rgb_t* result = data + pixel_count; + palettize_internal_bucket_t* work_mem = (palettize_internal_bucket_t*) ( data + pixel_count + palette_size ); + int result_count = palettize_internal_median_cut( data, data_size, work_mem, palette_size, result ); + + count = 0; + for( int i = 0; i < result_count; ++i ) + { + palettize_internal_rgb_t p = result[ i ]; + PALETTIZE_U16 c = palettize_internal_rgb32_to_rgb16( + (PALETTIZE_U32)( ( p.rgb[ 2 ] << 16 ) | ( p.rgb[ 1 ] << 8 ) | p.rgb[ 0 ] ) ); + int found = 0; + for( int j = 0; j < count; ++j ) if( palette[ j ] == c ) { found = 1; break; } + if( !found ) palette[ count++ ] = c; + if( count >= palette_size ) break; + } + + PALETTIZE_FREE( memctx, data ); + return count; + } + + +void palettize_remap_rgb16( PALETTIZE_U16 const* rgb, int width, int height, + PALETTIZE_U16 const* palette, int palette_size, PALETTIZE_U8* output ) + { + for( int y = 0; y < height; ++y ) + { + for( int x = 0; x < width; ++x ) + { + PALETTIZE_U32 color = palettize_internal_rgb16_to_rgb32( *rgb++ ); + int best_index = 0; + int mindist_sq = 255 * 255 + 255 * 255 + 255 * 255 + 1; + for( int i = 0; i < palette_size; ++i ) + { + PALETTIZE_U8 cr = ( (PALETTIZE_U8) ( ( color & 0x00ff0000 ) >> 16 ) ); + PALETTIZE_U8 cg = ( (PALETTIZE_U8) ( ( color & 0x0000ff00 ) >> 8 ) ); + PALETTIZE_U8 cb = ( (PALETTIZE_U8) ( ( color & 0x000000ff ) ) ); + PALETTIZE_U32 pal = palettize_internal_rgb16_to_rgb32( palette[ i ] ); + PALETTIZE_U8 pr = ( (PALETTIZE_U8) ( ( pal & 0x00ff0000 ) >> 16 ) ); + PALETTIZE_U8 pg = ( (PALETTIZE_U8) ( ( pal & 0x0000ff00 ) >> 8 ) ); + PALETTIZE_U8 pb = ( (PALETTIZE_U8) ( ( pal & 0x000000ff ) ) ); + int dr = ( (int) cr) - ( (int) pr ); + int dg = ( (int) cg) - ( (int) pg ); + int db = ( (int) cb) - ( (int) pb ); + int dist_sq = dr * dr + dg * dg + db * db; + if( dist_sq < mindist_sq ) { mindist_sq = dist_sq; best_index = i; } + } + *output++ = (PALETTIZE_U8) best_index; + } + } + } + + +int palettize_generate_rgb16_palette_xbgr32( PALETTIZE_U32 const* xbgr, int width, int height, + PALETTIZE_U16* palette, int palette_size, void* memctx ) + { + (void) memctx; + int pixel_count = width * height; + + int count = 0; + for( int i = 0; i < pixel_count; ++i ) + { + if( ( xbgr[ i ] >> 24 ) == 0 ) continue; + PALETTIZE_U16 c = palettize_internal_rgb32_to_rgb16( xbgr[ i ] ); + int found = 0; + for( int j = 0; j < count; ++j ) + { + if( palette[ j ] == c ) + { + found = 1; + break; + } + } + if( !found ) + { + if( count >= palette_size ) goto skip; + palette[ count++ ] = c; + } + } + + return count; + +skip: ; + size_t malloc_size = sizeof( palettize_internal_rgb_t ) * ( pixel_count + palette_size ); + malloc_size += sizeof( palettize_internal_bucket_t ) * palette_size; + palettize_internal_rgb_t* data = (palettize_internal_rgb_t*) PALETTIZE_MALLOC( memctx, malloc_size ); + + int data_size = 0; + for( int p = 0; p < pixel_count; ++p ) + { + PALETTIZE_U32 color = *xbgr++; + PALETTIZE_U8 a = (PALETTIZE_U8) ( ( color & 0xff000000 ) >>24 ); + if( a > 0 ) + { + color = palettize_internal_rgb16_to_rgb32( palettize_internal_rgb32_to_rgb16( color ) ); + PALETTIZE_U8 b = (PALETTIZE_U8) ( ( color & 0x00ff0000 ) >> 16 ); + PALETTIZE_U8 g = (PALETTIZE_U8) ( ( color & 0x0000ff00 ) >> 8 ); + PALETTIZE_U8 r = (PALETTIZE_U8) ( ( color & 0x000000ff ) ); + data[ data_size ].rgb[ 0 ] = r; + data[ data_size ].rgb[ 1 ] = g; + data[ data_size ].rgb[ 2 ] = b; + ++data_size; + } + } + palettize_internal_rgb_t* result = data + pixel_count; + palettize_internal_bucket_t* work_mem = (palettize_internal_bucket_t*) ( data + pixel_count + palette_size ); + int result_count = palettize_internal_median_cut( data, data_size, work_mem, palette_size, result ); + + count = 0; + for( int i = 0; i < result_count; ++i ) + { + palettize_internal_rgb_t p = result[ i ]; + PALETTIZE_U16 c = palettize_internal_rgb32_to_rgb16( + (PALETTIZE_U32)( ( p.rgb[ 2 ] << 16 ) | ( p.rgb[ 1 ] << 8 ) | p.rgb[ 0 ] ) ); + int found = 0; + for( int j= 0; j < count; ++j ) if( palette[ j ] == c ) { found = 1; break; } + if( !found ) palette[ count++ ] = c; + if( count >= palette_size ) break; + } + + PALETTIZE_FREE( memctx, data ); + return count; + } + + +void palettize_remap_xbgr32_pal16( PALETTIZE_U32 const* xbgr, int width, int height, + PALETTIZE_U16 const* palette, int palette_size, PALETTIZE_U8* output ) + { + for( int y = 0; y < height; ++y ) + { + for( int x = 0; x < width; ++x ) + { + PALETTIZE_U32 color = *xbgr++; + int best_index = 0; + int mindist_sq = 255 * 255 + 255 * 255 + 255 * 255 + 1; + for( int i = 0; i < palette_size; ++i ) + { + PALETTIZE_U8 cr = ( (PALETTIZE_U8) ( ( color & 0x00ff0000 ) >> 16 ) ); + PALETTIZE_U8 cg = ( (PALETTIZE_U8) ( ( color & 0x0000ff00 ) >> 8 ) ); + PALETTIZE_U8 cb = ( (PALETTIZE_U8) ( ( color & 0x000000ff ) ) ); + PALETTIZE_U32 pal = palettize_internal_rgb16_to_rgb32( palette[ i ] ); + PALETTIZE_U8 pr = ( (PALETTIZE_U8) ( ( pal & 0x00ff0000 ) >> 16) ); + PALETTIZE_U8 pg = ( (PALETTIZE_U8) ( ( pal & 0x0000ff00 ) >> 8 ) ); + PALETTIZE_U8 pb = ( (PALETTIZE_U8) ( ( pal & 0x000000ff ) ) ); + int dr = ( (int) cr) - ( (int) pr ); + int db = ( (int) cb) - ( (int) pb ); + int dg = ( (int) cg) - ( (int) pg ); + int dist_sq = dr * dr + dg * dg + db * db; + if( dist_sq < mindist_sq ) { mindist_sq = dist_sq; best_index = i; } + } + *output++ = (PALETTIZE_U8) best_index; + } + } + } + +#endif /* PALETTIZE_IMPLEMENTATION */ + + +/* +------------------------------------------------------------------------------ + +This software is available under 2 licenses - you may choose the one you like. + +------------------------------------------------------------------------------ + +ALTERNATIVE A - MIT License + +Copyright (c) 2017 Mattias Gustavsson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------------------------------------------------------------------ + +ALTERNATIVE B - Public Domain (www.unlicense.org) + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +------------------------------------------------------------------------------ +*/ diff --git a/palrle.h b/palrle.h new file mode 100644 index 0000000..f2aaaad --- /dev/null +++ b/palrle.h @@ -0,0 +1,444 @@ +/* +------------------------------------------------------------------------------ + Licensing information can be found at the end of the file. +------------------------------------------------------------------------------ + +palrle.h - v0.1 - Run-length encoding of palettized bitmaps, for C/C++. + +Do this: + #define PALRLE_IMPLEMENTATION +before you include this file in *one* C/C++ file to create the implementation. +*/ + +#ifndef palrle_h +#define palrle_h + +#ifndef PALRLE_U8 + #define PALRLE_U8 unsigned char +#endif +#ifndef PALRLE_U16 + #define PALRLE_U16 unsigned short +#endif +#ifndef PALRLE_U32 + #define PALRLE_U32 unsigned int +#endif + +typedef struct palrle_data_t { + PALRLE_U32 size; + PALRLE_U16 width; + PALRLE_U16 height; + PALRLE_U16 xoffset; + PALRLE_U16 yoffset; + PALRLE_U16 hpitch; + PALRLE_U16 vpitch; + PALRLE_U16 palette_count; + PALRLE_U8 data[ 1 ]; // "open" array +} palrle_data_t; + +palrle_data_t* palrle_encode( PALRLE_U8* pixels, int width, int height, PALRLE_U32* palette, int palette_count, void* memctx ); +palrle_data_t* palrle_encode_mask( PALRLE_U8* pixels, PALRLE_U8* mask, int width, int height, PALRLE_U32* palette, int palette_count, void* memctx ); +//palrle_data_t* palrle_encode_transparency_index( PALRLE_U8* pixels, PALRLE_U8 transparency_index, int width, int height, PALRLE_U32* palette, int palette_count, void* memctx ); + +void palrle_decode( palrle_data_t* rle_data, PALRLE_U8* pixels, PALRLE_U8* mask ); + +void palrle_blit( palrle_data_t* rle_data, int x, int y, PALRLE_U8* pixels, int width, int height ); + +void palrle_free( palrle_data_t* rle_data, void* memctx ); + + +#endif /* palrle_h */ + +/* +---------------------- + IMPLEMENTATION +---------------------- +*/ + +#ifdef PALRLE_IMPLEMENTATION +#undef PALRLE_IMPLEMENTATION + +#ifndef PALRLE_MALLOC + #define _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_SECURE_NO_WARNINGS + #include + #define PALRLE_MALLOC( ctx, size ) ( malloc( size ) ) + #define PALRLE_FREE( ctx, ptr ) ( free( ptr ) ) +#endif + + +palrle_data_t* palrle_encode( PALRLE_U8* pixels, int width, int height, PALRLE_U32* palette, int palette_count, void* memctx ) { + (void) memctx; + + int xmin = 0; + int xmax = width - 1; + int ymin = 0; + int ymax = height - 1; + int hpitch = xmax - xmin + 1; + int vpitch = ymax - ymin + 1; + + // Bitmap is completely empty, so just store the palette and dimensions + if( hpitch <= 0 || vpitch <= 0 ) { + size_t size = sizeof( palrle_data_t ) - sizeof( PALRLE_U8 ) + sizeof( PALRLE_U32 ) * palette_count; + palrle_data_t* data = (palrle_data_t*) PALRLE_MALLOC( memctx, size ); + data->size = (PALRLE_U32) size; + data->width = (PALRLE_U16) width; + data->height = (PALRLE_U16) height; + data->xoffset = 0; + data->yoffset = 0; + data->hpitch = 0; + data->vpitch = 0; + data->palette_count = (PALRLE_U16) palette_count; + if( palette ) memcpy( data->data, palette, sizeof( PALRLE_U32 ) * palette_count ); + return data; + } + + palrle_data_t* data = (palrle_data_t*) PALRLE_MALLOC( memctx, + sizeof( palrle_data_t ) + // size for the struct itself + sizeof( PALRLE_U32 ) * palette_count + // size for storing palette entries + sizeof( PALRLE_U32 ) * vpitch + // size for storing the offset for each row + hpitch * vpitch * 2 ); // assume worst case - we should never need more than twice the number of pixels + memset( data, 0, sizeof( palrle_data_t ) + sizeof( PALRLE_U32 ) * palette_count + sizeof( PALRLE_U32 ) * vpitch + + hpitch * vpitch * 2 ); + + + data->size = (PALRLE_U32) ( sizeof( palrle_data_t ) - sizeof( PALRLE_U8 ) ); + data->width = (PALRLE_U16) width; + data->height = (PALRLE_U16) height; + data->xoffset = (PALRLE_U16) xmin; + data->yoffset = (PALRLE_U16) ymin; + data->hpitch = (PALRLE_U16) hpitch; + data->vpitch = (PALRLE_U16) vpitch; + data->palette_count = (PALRLE_U16) palette_count; + if( palette ) memcpy( data->data, palette, sizeof( PALRLE_U32 ) * palette_count ); + + int row_offset = (int)( sizeof( PALRLE_U32 ) * palette_count ); + int rle_offset = (int)( row_offset + sizeof( PALRLE_U32 ) * vpitch ); + for( int y = 0; y < vpitch; ++y ) { + *( (PALRLE_U32*)&data->data[ row_offset ] ) = (PALRLE_U32) rle_offset; + row_offset += sizeof( PALRLE_U32 ); + int x = 0; + while( x < hpitch ) { + // add empty pixel count + data->data[ rle_offset++ ] = (PALRLE_U8) 0; + + // add non-empty pixels + int color = pixels[ x + xmin + ( y + ymin ) * width ]; + int count = 0; + int tx = x; + while( tx < hpitch ) { + if( pixels[ tx + xmin + ( y + ymin ) * width ] != color ) break; + if( count >= 127 ) break; + ++count; + ++tx; + } + + if( count == 0 ) { + data->data[ rle_offset++ ] = 0; + continue; + } + + if( count > 2 ) { // store as a run + data->data[ rle_offset++ ] = (PALRLE_U8) count; // number of pixels + data->data[ rle_offset++ ] = (PALRLE_U8) color; // of palette index `color` + x = tx; + } else { // store as unique values + PALRLE_U8* uniques_out = &data->data[ rle_offset++ ]; + int uniques = 1; + data->data[ rle_offset++ ] = (PALRLE_U8) color; + ++x; + + // add pixexls until we encounter a run + while( x < hpitch ) { + // check the length of the next run + color = pixels[ x + xmin + ( y + ymin ) * width ]; + count = 0; + tx = x; + while( tx < hpitch ) { + if( pixels[ tx + xmin + ( y + ymin ) * width ] != color ) break; + if( count > 2 ) break; // No need to keep counting, we know this is a run + ++count; + ++tx; + } + if( count > 2 || count == 0 ) { + break; + } else { + if( uniques >= 128 ) break; + ++uniques; + data->data[ rle_offset++ ] = (PALRLE_U8) color; + ++x; + } + } + *uniques_out = (PALRLE_U8)( (char) -uniques ); + } + } + } + data->size += rle_offset; + + return data; +} + + +palrle_data_t* palrle_encode_mask( PALRLE_U8* pixels, PALRLE_U8* mask, int width, int height, PALRLE_U32* palette, int palette_count, void* memctx ) { + (void) memctx; + // Crop to smallest non-empty region + int xmin = width; + int xmax = 0; + int ymin = height; + int ymax = 0; + for( int y = 0; y < height; ++y ) { + for( int x = 0; x < width; ++x ) { + if( mask[ x + y * width ] ) { + if( x < xmin ) xmin = x; + if( y < ymin ) ymin = y; + if( x > xmax ) xmax = x; + if( y > ymax ) ymax = y; + } + } + } + int hpitch = xmax - xmin + 1; + int vpitch = ymax - ymin + 1; + + // Bitmap is completely empty, so just store the palette and dimensions + if( hpitch <= 0 || vpitch <= 0 ) { + size_t size = sizeof( palrle_data_t ) - sizeof( PALRLE_U8 ) + sizeof( PALRLE_U32 ) * palette_count; + palrle_data_t* data = (palrle_data_t*) PALRLE_MALLOC( memctx, size ); + data->size = (PALRLE_U32) size; + data->width = (PALRLE_U16) width; + data->height = (PALRLE_U16) height; + data->xoffset = 0; + data->yoffset = 0; + data->hpitch = 0; + data->vpitch = 0; + data->palette_count = (PALRLE_U16) palette_count; + if( palette ) memcpy( data->data, palette, sizeof( PALRLE_U32 ) * palette_count ); + return data; + } + + palrle_data_t* data = (palrle_data_t*) PALRLE_MALLOC( memctx, + sizeof( palrle_data_t ) + // size for the struct itself + sizeof( PALRLE_U32 ) * palette_count + // size for storing palette entries + sizeof( PALRLE_U32 ) * vpitch + // size for storing the offset for each row + hpitch * vpitch * 2 ); // assume worst case - we should never need more than twice the number of pixels + memset( data, 0, sizeof( palrle_data_t ) + sizeof( PALRLE_U32 ) * palette_count + sizeof( PALRLE_U32 ) * vpitch + + hpitch * vpitch * 2 ); + + + data->size = (PALRLE_U32) ( sizeof( palrle_data_t ) - sizeof( PALRLE_U8 ) ); + data->width = (PALRLE_U16) width; + data->height = (PALRLE_U16) height; + data->xoffset = (PALRLE_U16) xmin; + data->yoffset = (PALRLE_U16) ymin; + data->hpitch = (PALRLE_U16) hpitch; + data->vpitch = (PALRLE_U16) vpitch; + data->palette_count = (PALRLE_U16) palette_count; + if( palette ) memcpy( data->data, palette, sizeof( PALRLE_U32 ) * palette_count ); + + int row_offset = (int)( sizeof( PALRLE_U32 ) * palette_count ); + int rle_offset = (int)( row_offset + sizeof( PALRLE_U32 ) * vpitch ); + for( int y = 0; y < vpitch; ++y ) { + *( (PALRLE_U32*)&data->data[ row_offset ] ) = (PALRLE_U32) rle_offset; + row_offset += sizeof( PALRLE_U32 ); + int x = 0; + while( x < hpitch ) { + // add empty pixel count + int empty = 0; + while( x < hpitch ) { + if( mask[ x + xmin + ( y + ymin ) * width ] != 0 ) break; + if( empty >= 255 ) { + data->data[ rle_offset++ ] = 255; // 255 empty pixels + data->data[ rle_offset++ ] = 0; // 0 non-empty pixels + empty = 0; + } + ++empty; + ++x; + } + data->data[ rle_offset++ ] = (PALRLE_U8) empty; + + // add non-empty pixels + int color = pixels[ x + xmin + ( y + ymin ) * width ]; + int count = 0; + int tx = x; + while( tx < hpitch ) { + if( mask[ tx + xmin + ( y + ymin ) * width ] == 0 ) break; + if( pixels[ tx + xmin + ( y + ymin ) * width ] != color ) break; + if( count >= 127 ) break; + ++count; + ++tx; + } + + if( count == 0 ) { + data->data[ rle_offset++ ] = 0; + continue; + } + + if( count > 2 ) { // store as a run + data->data[ rle_offset++ ] = (PALRLE_U8) count; // number of pixels + data->data[ rle_offset++ ] = (PALRLE_U8) color; // of palette index `color` + x = tx; + } else { // store as unique values + PALRLE_U8* uniques_out = &data->data[ rle_offset++ ]; + int uniques = 1; + data->data[ rle_offset++ ] = (PALRLE_U8) color; + ++x; + + // add pixexls until we encounter a run + while( x < hpitch ) { + // check the length of the next run + color = pixels[ x + xmin + ( y + ymin ) * width ]; + count = 0; + tx = x; + while( tx < hpitch ) { + if( mask[ tx + xmin + ( y + ymin ) * width ] == 0 ) break; + if( pixels[ tx + xmin + ( y + ymin ) * width ] != color ) break; + if( count > 2 ) break; // No need to keep counting, we know this is a run + ++count; + ++tx; + } + if( count > 2 || count == 0 ) { + break; + } else { + if( uniques >= 128 ) break; + ++uniques; + data->data[ rle_offset++ ] = (PALRLE_U8) color; + ++x; + } + } + *uniques_out = (PALRLE_U8)( (char) -uniques ); + } + } + } + data->size += rle_offset; + + return data; +} + + +/* +palrle_data_t* palrle_encode_transparency_index( PALRLE_U8* pixels, PALRLE_U8 transparency_index, int width, int height, PALRLE_U32* palette, int palette_count, void* memctx ) { + (void) pixels, transparency_index, width, height, memctx; + return 0; +} +*/ + + + +void palrle_decode( palrle_data_t* rle_data, PALRLE_U8* pixels, PALRLE_U8* mask ) { + memset( pixels, 0, rle_data->width * rle_data->height * sizeof( PALRLE_U8 ) ); + if( mask ) memset( mask, 0, rle_data->width * rle_data->height * sizeof( PALRLE_U8 ) ); + PALRLE_U8* data = &rle_data->data[ sizeof( PALRLE_U32 ) * ( rle_data->palette_count + rle_data->vpitch ) ]; + for( int y = 0; y < rle_data->vpitch; ++y ) { + int x = 0; + while( x < rle_data->hpitch ) { + x += *data++; + char count = (char)( *data++ ); + if( count > 0 ) { + PALRLE_U8 color = *data++; + for( int i = 0; i < count; ++i ) { + pixels[ rle_data->xoffset + x + ( rle_data->yoffset + y ) * rle_data->width ] = color; + if( mask ) mask[ rle_data->xoffset + x + ( rle_data->yoffset + y ) * rle_data->width ] = 255; + ++x; + } + } else { + for( int i = 0; i < -count; ++i ) { + pixels[ rle_data->xoffset + x + ( rle_data->yoffset + y ) * rle_data->width ] = *data++; + if( mask ) mask[ rle_data->xoffset + x + ( rle_data->yoffset + y ) * rle_data->width ] = 255; + ++x; + } + } + } + } +} + + +void palrle_blit( palrle_data_t* rle_data, int x, int y, PALRLE_U8* pixels, int width, int height ) { + PALRLE_U8* data = &rle_data->data[ sizeof( PALRLE_U32 ) * ( rle_data->palette_count + rle_data->vpitch ) ]; + for( int iy = 0; iy < rle_data->vpitch; ++iy ) { + int ix = 0; + while( ix < rle_data->hpitch ) { + ix += *data++; + char count = (char)( *data++ ); + if( count > 0 ) { + PALRLE_U8 color = *data++; + for( int i = 0; i < count; ++i ) { + int xp = rle_data->xoffset + ix + x; + int yp = rle_data->yoffset + iy + y; + if( xp > 0 && yp > 0 && xp < width && yp < height ) pixels[ xp + yp * width ] = color; + ++ix; + } + } else { + for( int i = 0; i < -count; ++i ) { + PALRLE_U8 color = *data++; + int xp = rle_data->xoffset + ix + x; + int yp = rle_data->yoffset + iy + y; + if( xp > 0 && yp > 0 && xp < width && yp < height ) pixels[ xp + yp * width ] = color; + ++ix; + } + } + } + } +} + + +void palrle_free( palrle_data_t* rle_data, void* memctx ) { + (void) rle_data, (void) memctx; + PALRLE_FREE( memctx, rle_data ); +} + +#endif /* PALRLE_IMPLEMENTATION */ + + +/* +------------------------------------------------------------------------------ + +This software is available under 2 licenses - you may choose the one you like. + +------------------------------------------------------------------------------ + +ALTERNATIVE A - MIT License + +Copyright (c) 2019 Mattias Gustavsson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------------------------------------------------------------------ + +ALTERNATIVE B - Public Domain (www.unlicense.org) + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +------------------------------------------------------------------------------ +*/ diff --git a/pixelfont.h b/pixelfont.h new file mode 100644 index 0000000..8a7d5be --- /dev/null +++ b/pixelfont.h @@ -0,0 +1,523 @@ +/* +------------------------------------------------------------------------------ + Licensing information can be found at the end of the file. +------------------------------------------------------------------------------ + +pixelfont.h - v0.1 - Custom pixel font format builder and renderer. + +Do this: + #define PIXELFONT_IMPLEMENTATION +before you include this file in *one* C/C++ file to create the implementation. + +If you want to generate pixelfonts through the pixelfont_builder api, do this: + #define PIXELFONT_BUILDER_IMPLEMENTATION +before include the file to create the implementation. + +*/ + +#ifndef pixelfont_h +#define pixelfont_h + +#ifndef PIXELFONT_I8 + #define PIXELFONT_I8 signed char +#endif + +#ifndef PIXELFONT_U8 + #define PIXELFONT_U8 unsigned char +#endif + +#ifndef PIXELFONT_U32 + #define PIXELFONT_U32 unsigned int +#endif + +typedef struct pixelfont_t + { + PIXELFONT_U32 size_in_bytes; + PIXELFONT_U8 height; + PIXELFONT_U8 line_spacing; + PIXELFONT_U8 baseline; + PIXELFONT_U32 offsets[ 256 ]; + PIXELFONT_U8 glyphs[ 1 ]; // "open" array - ok to access out of bounds (use size_in_bytes to determine the end) + } pixelfont_t; + + +typedef enum pixelfont_align_t + { + PIXELFONT_ALIGN_LEFT, + PIXELFONT_ALIGN_RIGHT, + PIXELFONT_ALIGN_CENTER, + } pixelfont_align_t; + + +typedef enum pixelfont_bold_t + { + PIXELFONT_BOLD_OFF, + PIXELFONT_BOLD_ON, + } pixelfont_bold_t; + + +typedef enum pixelfont_italic_t + { + PIXELFONT_ITALIC_OFF, + PIXELFONT_ITALIC_ON, + } pixelfont_italic_t; + + +typedef enum pixelfont_underline_t + { + PIXELFONT_UNDERLINE_OFF, + PIXELFONT_UNDERLINE_ON, + } pixelfont_underline_t; + + +typedef struct pixelfont_bounds_t + { + int width; + int height; + } pixelfont_bounds_t; + + + +typedef struct pixelfont_builder_t pixelfont_builder_t; + +pixelfont_builder_t* pixelfont_builder_create( int height, int baseline, int line_spacing, void* memctx ); +void pixelfont_builder_destroy( pixelfont_builder_t* builder ); + +void pixelfont_builder_glyph( pixelfont_builder_t* builder, int glyph, int pixels_stride, PIXELFONT_U8* pixels, int width, int lead, int trail ); +void pixelfont_builder_kerning( pixelfont_builder_t* builder, int glyph, int follower, int adjust ); + +pixelfont_t* pixelfont_builder_font( pixelfont_builder_t* builder ); + +#endif /* pixelfont_h */ + + +// The following will be defined each time the file is included. By defining PIXELFONT_COLOR and PIXELFONT_FUNC_NAME +// it is possible to create declarations for different pixel formats. By defining the same ones, and the additional +// PIXELFONT_PIXEL_FUNC before including the implementation part, the corresponding definition can be created. + +#ifndef PIXELFONT_COLOR + #define PIXELFONT_COLOR PIXELFONT_U8 +#endif + +#ifndef PIXELFONT_FUNC_NAME + #define PIXELFONT_FUNC_NAME pixelfont_blit +#endif + +void PIXELFONT_FUNC_NAME( pixelfont_t const* font, int x, int y, char const* text, PIXELFONT_COLOR color, + PIXELFONT_COLOR* target, int width, int height, pixelfont_align_t align, int wrap_width, int hspacing, + int vspacing, int limit, pixelfont_bold_t bold, pixelfont_italic_t italic, pixelfont_underline_t underline, + pixelfont_bounds_t* bounds ); + + +/* +---------------------- + IMPLEMENTATION +---------------------- +*/ + +#ifdef PIXELFONT_IMPLEMENTATION +#undef PIXELFONT_IMPLEMENTATION + +#ifndef PIXELFONT_PIXEL_FUNC + #define PIXELFONT_PIXEL_FUNC( dst, fnt, col ) *(dst) = (col); +#endif + +void PIXELFONT_FUNC_NAME( pixelfont_t const* font, int x, int y, char const* text, PIXELFONT_COLOR color, + PIXELFONT_COLOR* target, int width, int height, pixelfont_align_t align, int wrap_width, int hspacing, + int vspacing, int limit, pixelfont_bold_t bold, pixelfont_italic_t italic, pixelfont_underline_t underline, + pixelfont_bounds_t* bounds ) + { + int xp = x; + int yp = y; + int max_x = x; + int last_x_on_line = xp; + int count = 0; + char const* str = text; + while( *str ) + { + int line_char_count = 0; + int line_width = 0; + int last_space_char_count = 0; + int last_space_width = 0; + char const* tstr = str; + while( *tstr != '\n' && *tstr != '\0' && ( wrap_width <= 0 || line_width <= wrap_width ) ) + { + if( *tstr <= ' ' ) + { + last_space_char_count = line_char_count; + last_space_width = line_width; + } + PIXELFONT_U8 const* g = font->glyphs + font->offsets[ (int) *tstr ]; + line_width += (PIXELFONT_I8) *g++; + int w = *g++; + g += font->height * w; + line_width += (PIXELFONT_I8) *g++; + line_width += hspacing + ( bold ? 1 : 0 ); + ++tstr; + int kern = *g++; + for( int k = 0; k < kern; ++k ) + if( *g++ == *tstr ) { line_width += (PIXELFONT_I8) *g++; break; } else ++g; + ++line_char_count; + } + + int skip_space = 0; + if( wrap_width > 0 && line_width > wrap_width ) + { + if( last_space_char_count > 0 ) line_char_count = last_space_char_count; + line_width = last_space_width; + skip_space = 1; + } + + if( wrap_width > 0 ) + { + if( align == PIXELFONT_ALIGN_RIGHT ) x += wrap_width - line_width; + if( align == PIXELFONT_ALIGN_CENTER ) x += ( wrap_width - line_width ) / 2; + } + else + { + if( align == PIXELFONT_ALIGN_RIGHT ) x -= line_width; + if( align == PIXELFONT_ALIGN_CENTER ) x -= line_width / 2; + } + + for( int c = 0; c < line_char_count; ++c ) + { + PIXELFONT_U8 const* g = font->glyphs + font->offsets[ (int) *str ]; + x += (PIXELFONT_I8) *g++; + int w = *g++; + int h = font->height; + for( int iy = y; iy < y + h; ++iy ) + { + int xs = x + ( italic ? ( h - ( iy - y ) ) / 2 - 1 : 0 ); + for( int ix = xs; ix < xs + w; ++ix ) + { + int p = *g++; + if( p && target ) + if( limit < 0 || count < limit ) + if( ix >= 0 && iy >= 0 && ix < width && iy < height ) + { + last_x_on_line = ix >= last_x_on_line ? ix + ( bold ? 1 : 0 ) : last_x_on_line; + PIXELFONT_PIXEL_FUNC( ( &target[ ix + iy * width ] ), (PIXELFONT_U8)p, color ); + if( bold && ix + 1 < width ) + PIXELFONT_PIXEL_FUNC( ( &target[ ix + 1 + iy * width ] ), (PIXELFONT_U8)p, color ); + } + } + } + + x += (PIXELFONT_I8) *g++; + x += hspacing + ( bold ? 1 : 0 ); + ++str; + ++count; + + int kern = *g++; + for( int k = 0; k < kern; ++k ) + if( *g++ == *str ) { x += (PIXELFONT_I8) *g++; break; } else ++g; + + } + + if( underline && target && y + font->baseline + 1 >= 0 && y + font->baseline + 1 < height && last_x_on_line > xp ) + for( int ix = xp; ix <= last_x_on_line; ++ix ) + if( ix >= 0 && ix < width ) + PIXELFONT_PIXEL_FUNC( ( &target[ ix + ( y + font->baseline + 1 ) * width ] ), (PIXELFONT_U8)255, color ); + last_x_on_line = xp; + max_x = x > max_x ? x : max_x; + x = xp; + y += font->line_spacing + vspacing; + if( *str == '\n' ) ++str; + if( *str && skip_space && *str <= ' ' ) ++str; + } + + if( bounds ) + { + bounds->width = wrap_width > 0 ? wrap_width : ( max_x - xp ); + bounds->height = y - yp; + } + } + + +#undef PIXELFONT_COLOR +#undef PIXELFONT_FUNC_NAME + +#endif /* PIXELFONT_IMPLEMENTATION */ + + + +#ifdef PIXELFONT_BUILDER_IMPLEMENTATION +#undef PIXELFONT_BUILDER_IMPLEMENTATION + + +#ifndef PIXELFONT_MALLOC + #undef _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_NONSTDC_NO_DEPRECATE + #undef _CRT_SECURE_NO_WARNINGS + #define _CRT_SECURE_NO_WARNINGS + #include + #define PIXELFONT_MALLOC( ctx, size ) ( malloc( size ) ) + #define PIXELFONT_FREE( ctx, ptr ) ( free( ptr ) ) +#endif + + +#ifndef PIXELFONT_MEMCPY + #undef _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_NONSTDC_NO_DEPRECATE + #undef _CRT_SECURE_NO_WARNINGS + #define _CRT_SECURE_NO_WARNINGS + #include + #define PIXELFONT_MEMCPY( dst, src, cnt ) ( memcpy( dst, src, cnt ) ) +#endif + + +typedef struct pixelfont_builder_glyph_t + { + int lead; + int trail; + int width; + PIXELFONT_U8* pixels; + } pixelfont_builder_glyph_t; + + +typedef struct pixelfont_builder_kerning_t + { + int glyph; + int follower; + int adjust; + } pixelfont_builder_kerning_t; + + +struct pixelfont_builder_t + { + void* memctx; + pixelfont_t* font; + int height; + int baseline; + int line_spacing; + + pixelfont_builder_glyph_t glyphs[ 256 ]; + + int kernings_capacity; + int kernings_count; + pixelfont_builder_kerning_t* kernings; + }; + + +pixelfont_builder_t* pixelfont_builder_create( int height, int baseline, int line_spacing, void* memctx ) + { + pixelfont_builder_t* builder = (pixelfont_builder_t*) PIXELFONT_MALLOC( memctx, sizeof( pixelfont_builder_t ) ) ; + memset( builder, 0, sizeof( *builder ) ); + builder->memctx = memctx; + builder->font = 0; + builder->height = height < 0 ? 0 : height > 255 ? 255 : height; + builder->baseline = baseline < 0 ? 0 : baseline > 255 ? 255 : baseline; + builder->line_spacing = line_spacing < 0 ? 0 : line_spacing > 255 ? 255 : line_spacing; + builder->kernings_capacity = 0; + builder->kernings_count = 0; + builder->kernings = 0; + return builder; + } + + +void pixelfont_builder_destroy( pixelfont_builder_t* builder ) + { + for( int i = 0; i < sizeof( builder->glyphs ) / sizeof( *builder->glyphs ); ++i ) + if( builder->glyphs[ i ].pixels ) PIXELFONT_FREE( builder->memctx, builder->glyphs[ i ].pixels ); + + if( builder->kernings ) PIXELFONT_FREE( builder->memctx, builder->kernings ); + if( builder->font ) PIXELFONT_FREE( builder->memctx, builder->font ); + PIXELFONT_FREE( builder->memctx, builder ); + } + + +void pixelfont_builder_glyph( pixelfont_builder_t* builder, int glyph, int pixels_stride, PIXELFONT_U8* pixels, int width, int lead, int trail ) + { + if( glyph < 0 || glyph > 255 ) return; + + if( builder->glyphs[ glyph ].pixels ) PIXELFONT_FREE( builder->memctx, builder->glyphs[ glyph ].pixels ); + builder->glyphs[ glyph ].pixels = 0; + builder->glyphs[ glyph ].lead = 0; + builder->glyphs[ glyph ].trail = 0; + builder->glyphs[ glyph ].width = 0; + + if( pixels && width > 0 ) + { + builder->glyphs[ glyph ].pixels = (PIXELFONT_U8*) PIXELFONT_MALLOC( builder->memctx, width * builder->height * sizeof( PIXELFONT_U8 ) ); + for( int y = 0; y < builder->height; ++y ) + for( int x = 0; x < width; ++x ) + builder->glyphs[ glyph ].pixels[ x + y * width ] = pixels[ x + y * pixels_stride ]; + builder->glyphs[ glyph ].lead = lead < -127 ? -127 : lead > 127 ? 127 : lead; + builder->glyphs[ glyph ].trail = trail < -127 ? -127 : trail > 127 ? 127 : trail; + builder->glyphs[ glyph ].width = width < 0 ? 0 : width > 255 ? 255 : width; + } + else if( lead || trail ) + { + builder->glyphs[ glyph ].pixels = (PIXELFONT_U8*) PIXELFONT_MALLOC( builder->memctx, 1 ); + builder->glyphs[ glyph ].lead = lead < -127 ? -127 : lead > 127 ? 127 : lead; + builder->glyphs[ glyph ].trail = trail < -127 ? -127 : trail > 127 ? 127 : trail; + builder->glyphs[ glyph ].width = 0; + } + } + + +void pixelfont_builder_kerning( pixelfont_builder_t* builder, int glyph, int follower, int adjust ) + { + adjust = adjust < -127 ? -127 : adjust > 127 ? 127 : adjust; + + for( int i = 0; i < builder->kernings_count; ++i ) + { + if( builder->kernings[ i ].glyph == glyph && builder->kernings[ i ].follower == follower ) + { + if( adjust ) + builder->kernings[ i ].adjust = adjust; + else + builder->kernings[ i ] = builder->kernings[ --builder->kernings_count ]; + return; + } + } + + if( adjust ) + { + if( !builder->kernings || builder->kernings_count >= builder->kernings_capacity ) + { + builder->kernings_capacity = builder->kernings_capacity ? builder->kernings_capacity * 2 : 256; + pixelfont_builder_kerning_t* kernings = (pixelfont_builder_kerning_t*) PIXELFONT_MALLOC( builder->memctx, + sizeof( pixelfont_builder_kerning_t ) * builder->kernings_capacity ); + if( builder->kernings ) + { + PIXELFONT_MEMCPY( kernings, builder->kernings, sizeof( pixelfont_builder_kerning_t ) * builder->kernings_count ); + PIXELFONT_FREE( builder->memctx, builder->kernings ); + } + builder->kernings = kernings; + } + + builder->kernings[ builder->kernings_count ].glyph = glyph; + builder->kernings[ builder->kernings_count ].follower = follower; + builder->kernings[ builder->kernings_count ].adjust = adjust; + ++builder->kernings_count; + } + } + + +pixelfont_t* pixelfont_builder_font( pixelfont_builder_t* builder ) + { + if( builder->font ) PIXELFONT_FREE( builder->memctx, builder->font ); + + PIXELFONT_U8 kerning_counts[ 256 ]; + memset( kerning_counts, 0, sizeof( kerning_counts ) ); + for( int i = 0; i < builder->kernings_count; ++i ) + ++kerning_counts[ builder->kernings[ i ].glyph ]; + + PIXELFONT_U32 offsets[ 256 ]; + memset( offsets, 0, sizeof( offsets ) ); + PIXELFONT_U32 current_offset = 0; + int total_width = 0; + int glyph_count = 0; + for( int i = 0; i < sizeof( builder->glyphs ) / sizeof( *builder->glyphs ); ++i ) + { + if( builder->glyphs[ i ].pixels ) + { + ++glyph_count; + total_width += builder->glyphs[ i ].width; + offsets[ i ] = current_offset; + current_offset += 1 + kerning_counts[ i ] + 3 + builder->glyphs[ i ].width * builder->height; + } + } + + size_t size_in_bytes = sizeof( pixelfont_t ) - sizeof( PIXELFONT_U8 ); // base size excluding final placeholder byte + size_in_bytes += glyph_count + 2 * builder->kernings_count; // kerning pair count for each glyph + all kerning data + size_in_bytes += 3 * glyph_count; // lead, trail and width for each glyph + size_in_bytes += total_width * builder->height; // pixel data for all glyphs + + pixelfont_t* font = (pixelfont_t*) PIXELFONT_MALLOC( builder->memctx, size_in_bytes ); + memset( font, 0, sizeof( *font ) ); + font->size_in_bytes = (PIXELFONT_U32) size_in_bytes; + font->height = (PIXELFONT_U8) builder->height; + font->line_spacing = (PIXELFONT_U8) builder->line_spacing; + font->baseline = (PIXELFONT_U8) builder->baseline; + memcpy( font->offsets, offsets, sizeof( font->offsets ) ); + + for( int i = 0; i < sizeof( builder->glyphs ) / sizeof( *builder->glyphs ); ++i ) + { + if( builder->glyphs[ i ].pixels ) + { + PIXELFONT_U8* src = builder->glyphs[ i ].pixels; + PIXELFONT_U8* out = font->glyphs + offsets[ i ]; + *out++ = (PIXELFONT_U8) builder->glyphs[ i ].lead; + *out++ = (PIXELFONT_U8) builder->glyphs[ i ].width; + for( int y = 0; y < builder->height; ++y ) + for( int x = 0; x < builder->glyphs[ i ].width; ++x ) + *out++ = *src++; + *out++ = (PIXELFONT_U8) builder->glyphs[ i ].trail; + + *out++ = kerning_counts[ i ]; + for( int j = 0; j < builder->kernings_count; ++j ) + { + if( builder->kernings[ j ].glyph == i ) + { + *out++ = (PIXELFONT_U8) builder->kernings[ j ].follower; + *out++ = (PIXELFONT_U8) builder->kernings[ j ].adjust; + } + } + } + } + + builder->font = font; + return builder->font; + } + + +#endif /* PIXELFONT_BUILDER_IMPLEMENTATION */ + + +/* +------------------------------------------------------------------------------ + +This software is available under 2 licenses - you may choose the one you like. + +------------------------------------------------------------------------------ + +ALTERNATIVE A - MIT License + +Copyright (c) 2017 Mattias Gustavsson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------------------------------------------------------------------ + +ALTERNATIVE B - Public Domain (www.unlicense.org) + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +------------------------------------------------------------------------------ +*/