Reformat code

This commit is contained in:
2023-09-24 21:15:57 +02:00
parent 456b873de0
commit 584b0cffc5
23 changed files with 5711 additions and 6018 deletions

View File

@@ -1,33 +1,31 @@
--- ---
Language: Cpp Language: Cpp
# BasedOnStyle: LLVM # BasedOnStyle: LLVM
AccessModifierOffset: -2 AccessModifierOffset: -2
AlignAfterOpenBracket: true AlignAfterOpenBracket: AlwaysBreak
AlignEscapedNewlinesLeft: false AlignOperands: true
AlignOperands: true
AlignTrailingComments: true AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: false AllowShortBlocksOnASingleLine: Always
AllowShortCaseLabelsOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: false AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false AllowShortLoopsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All AllowShortFunctionsOnASingleLine: All
AlwaysBreakAfterDefinitionReturnType: false AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakTemplateDeclarations: false AlwaysBreakTemplateDeclarations: No
AlwaysBreakBeforeMultilineStrings: false AlwaysBreakBeforeMultilineStrings: false
BreakBeforeBinaryOperators: None BreakBeforeBinaryOperators: None
BreakBeforeTernaryOperators: true BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false BreakConstructorInitializersBeforeComma: false
BinPackParameters: true BinPackParameters: true
BinPackArguments: true BinPackArguments: false
ColumnLimit: 80 ColumnLimit: 120
ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4 ConstructorInitializerIndentWidth: 4
DerivePointerAlignment: false DerivePointerAlignment: false
ExperimentalAutoDetectBinPacking: false ExperimentalAutoDetectBinPacking: false
IndentCaseLabels: false IndentCaseLabels: false
IndentWrappedFunctionNames: false IndentWrappedFunctionNames: false
IndentFunctionDeclarationAfterType: false
MaxEmptyLinesToKeep: 1 MaxEmptyLinesToKeep: 1
KeepEmptyLinesAtTheStartOfBlocks: true KeepEmptyLinesAtTheStartOfBlocks: true
NamespaceIndentation: None NamespaceIndentation: None
@@ -43,23 +41,23 @@ PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right PointerAlignment: Right
SpacesBeforeTrailingComments: 1 SpacesBeforeTrailingComments: 1
Cpp11BracedListStyle: true Cpp11BracedListStyle: true
Standard: Cpp11 Standard: c++11
IndentWidth: 4 IndentWidth: 4
TabWidth: 4 TabWidth: 4
UseTab: true UseTab: AlignWithSpaces
BreakBeforeBraces: Attach BreakBeforeBraces: Attach
SpacesInParentheses: false SpacesInParentheses: false
SpacesInSquareBrackets: false SpacesInSquareBrackets: false
SpacesInAngles: false SpacesInAngles: false
SpaceInEmptyParentheses: false SpaceInEmptyParentheses: false
SpacesInCStyleCastParentheses: false SpacesInCStyleCastParentheses: false
SpaceAfterCStyleCast: false SpaceAfterCStyleCast: false
SpacesInContainerLiterals: true SpacesInContainerLiterals: true
SpaceBeforeAssignmentOperators: true SpaceBeforeAssignmentOperators: true
ContinuationIndentWidth: 4 ContinuationIndentWidth: 4
CommentPragmas: '^ IWYU pragma:' ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
SpaceBeforeParens: ControlStatements SpaceBeforeParens: ControlStatements
DisableFormat: false DisableFormat: false
AlignConsecutiveAssignments: Consecutive
... ...

View File

@@ -1,33 +1,31 @@
--- ---
Language: Cpp Language: Cpp
# BasedOnStyle: LLVM # BasedOnStyle: LLVM
AccessModifierOffset: -2 AccessModifierOffset: -2
AlignAfterOpenBracket: true AlignAfterOpenBracket: AlwaysBreak
AlignEscapedNewlinesLeft: false AlignOperands: true
AlignOperands: true
AlignTrailingComments: true AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: false AllowShortBlocksOnASingleLine: Always
AllowShortCaseLabelsOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: false AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false AllowShortLoopsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All AllowShortFunctionsOnASingleLine: All
AlwaysBreakAfterDefinitionReturnType: false AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakTemplateDeclarations: false AlwaysBreakTemplateDeclarations: No
AlwaysBreakBeforeMultilineStrings: false AlwaysBreakBeforeMultilineStrings: false
BreakBeforeBinaryOperators: None BreakBeforeBinaryOperators: None
BreakBeforeTernaryOperators: true BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false BreakConstructorInitializersBeforeComma: false
BinPackParameters: true BinPackParameters: true
BinPackArguments: true BinPackArguments: false
ColumnLimit: 80 ColumnLimit: 120
ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4 ConstructorInitializerIndentWidth: 4
DerivePointerAlignment: false DerivePointerAlignment: false
ExperimentalAutoDetectBinPacking: false ExperimentalAutoDetectBinPacking: false
IndentCaseLabels: false IndentCaseLabels: false
IndentWrappedFunctionNames: false IndentWrappedFunctionNames: false
IndentFunctionDeclarationAfterType: false
MaxEmptyLinesToKeep: 1 MaxEmptyLinesToKeep: 1
KeepEmptyLinesAtTheStartOfBlocks: true KeepEmptyLinesAtTheStartOfBlocks: true
NamespaceIndentation: None NamespaceIndentation: None
@@ -43,23 +41,23 @@ PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right PointerAlignment: Right
SpacesBeforeTrailingComments: 1 SpacesBeforeTrailingComments: 1
Cpp11BracedListStyle: true Cpp11BracedListStyle: true
Standard: Cpp11 Standard: c++11
IndentWidth: 4 IndentWidth: 4
TabWidth: 4 TabWidth: 4
UseTab: true UseTab: AlignWithSpaces
BreakBeforeBraces: Attach BreakBeforeBraces: Attach
SpacesInParentheses: false SpacesInParentheses: false
SpacesInSquareBrackets: false SpacesInSquareBrackets: false
SpacesInAngles: false SpacesInAngles: false
SpaceInEmptyParentheses: false SpaceInEmptyParentheses: false
SpacesInCStyleCastParentheses: false SpacesInCStyleCastParentheses: false
SpaceAfterCStyleCast: false SpaceAfterCStyleCast: false
SpacesInContainerLiterals: true SpacesInContainerLiterals: true
SpaceBeforeAssignmentOperators: true SpaceBeforeAssignmentOperators: true
ContinuationIndentWidth: 4 ContinuationIndentWidth: 4
CommentPragmas: '^ IWYU pragma:' ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
SpaceBeforeParens: ControlStatements SpaceBeforeParens: ControlStatements
DisableFormat: false DisableFormat: false
AlignConsecutiveAssignments: Consecutive
... ...

View File

@@ -18,7 +18,7 @@ Entity ent_Platform;
Entity ent_Block; Entity ent_Block;
int EntityApplyGravity(Entity e) { int EntityApplyGravity(Entity e) {
float grav = 10.0f; float grav = 10.0f;
float vTerminal = 50.0f; float vTerminal = 50.0f;
vec2 vGrav; vec2 vGrav;
@@ -35,9 +35,9 @@ int EntityApplyGravity(Entity e) {
} }
void Player_Proc(Entity e, int ft) { void Player_Proc(Entity e, int ft) {
float acel = 8.0f; float acel = 8.0f;
float maxVel = 30.0f; float maxVel = 30.0f;
float jumpVel = 50.0f; float jumpVel = 50.0f;
float airMovementFactor = 0.1f; float airMovementFactor = 0.1f;
// Process elasticity // Process elasticity
@@ -48,8 +48,7 @@ void Player_Proc(Entity e, int ft) {
Entity_SetScale(e, entityScale); Entity_SetScale(e, entityScale);
if (e->A > 0) { if (e->A > 0) {
if (Input_GetKey(InputKey_Jump) == InputKey_Pressed || if (Input_GetKey(InputKey_Jump) == InputKey_Pressed || Input_GetKey(InputKey_Up) == InputKey_Pressed) {
Input_GetKey(InputKey_Up) == InputKey_Pressed) {
// Apply jump // Apply jump
if (e->vel[1] > (-jumpVel)) { if (e->vel[1] > (-jumpVel)) {
@@ -91,8 +90,7 @@ void Player_Proc(Entity e, int ft) {
Entity_AddVelLimit(e, right, maxVel * airMovementFactor); Entity_AddVelLimit(e, right, maxVel * airMovementFactor);
} }
} }
if (Input_GetKey(InputKey_Action1) == InputKey_Pressed || if (Input_GetKey(InputKey_Action1) == InputKey_Pressed || Input_GetKey(InputKey_Action2) == InputKey_Pressed) {
Input_GetKey(InputKey_Action2) == InputKey_Pressed) {
Entity_SetScale(e, (float[2]){1.0f, 1.0f}); Entity_SetScale(e, (float[2]){1.0f, 1.0f});
} }
@@ -114,14 +112,12 @@ int Player_Collision(Entity ent, Entity ent2, float t, vec2 n) {
if (fabs(n[0]) > fabs(n[1])) { if (fabs(n[0]) > fabs(n[1])) {
float intensity = (fabs(ent->vel[0]) - 10.0f) / 40.0f; float intensity = (fabs(ent->vel[0]) - 10.0f) / 40.0f;
if (intensity > 0) { if (intensity > 0) {
Entity_SetScale(ent, (float[2]){1.0f - (0.3f * intensity), Entity_SetScale(ent, (float[2]){1.0f - (0.3f * intensity), 1.0f + (0.3f * intensity)});
1.0f + (0.3f * intensity)});
} }
} else { } else {
float intensity = (fabs(ent->vel[1]) - 10.0f) / 40.0f; float intensity = (fabs(ent->vel[1]) - 10.0f) / 40.0f;
if (intensity > 0) { if (intensity > 0) {
Entity_SetScale(ent, (float[2]){1.0f + (0.3f * intensity), Entity_SetScale(ent, (float[2]){1.0f + (0.3f * intensity), 1.0f - (0.3f * intensity)});
1.0f - (0.3f * intensity)});
} }
} }
return -1; return -1;
@@ -133,52 +129,52 @@ void GameEnts_Init() {
// Load and initialize media. // Load and initialize media.
// //
img_player = Draw_LoadImage("data/player.png"); img_player = Draw_LoadImage("data/player.png");
img_platform = Draw_LoadImage("data/platform.png"); img_platform = Draw_LoadImage("data/platform.png");
img_block = Draw_LoadImage("data/block.png"); img_block = Draw_LoadImage("data/block.png");
///////////////////////// /////////////////////////
// Initialize entity types. // Initialize entity types.
// //
ent_Player = Entity_New(); ent_Player = Entity_New();
ent_Player->type = Ent_Player; ent_Player->type = Ent_Player;
// ent_Player->flags=EntityFlag_Light; // ent_Player->flags=EntityFlag_Light;
// Entity_SetLight(ent_Player,.2,.2,.2,200); // Entity_SetLight(ent_Player,.2,.2,.2,200);
ent_Player->flags = EntityFlag_Collision | EntityFlag_Overlap; ent_Player->flags = EntityFlag_Collision | EntityFlag_Overlap;
ent_Player->zorder = 0; ent_Player->zorder = 0;
AnimPlay_SetImg(&ent_Player->anim, img_player); AnimPlay_SetImg(&ent_Player->anim, img_player);
ent_Player->proc = Player_Proc; ent_Player->proc = Player_Proc;
ent_Player->postproc = Player_PostProc; ent_Player->postproc = Player_PostProc;
ent_Player->collision = Player_Collision; ent_Player->collision = Player_Collision;
ent_Player->mass = 1.0f; ent_Player->mass = 1.0f;
ent_Player->radius = 12; ent_Player->radius = 12;
ent_Player->width = 24; ent_Player->width = 24;
ent_Player->height = 24; ent_Player->height = 24;
ent_Player->fric_static = 0.0f; ent_Player->fric_static = 0.0f;
ent_Player->fric_dynamic = 0.2f; ent_Player->fric_dynamic = 0.2f;
ent_Platform = Entity_New(); ent_Platform = Entity_New();
ent_Platform->type = Ent_Platform; ent_Platform->type = Ent_Platform;
ent_Platform->flags = EntityFlag_PlatformCollision; ent_Platform->flags = EntityFlag_PlatformCollision;
ent_Platform->zorder = -1; ent_Platform->zorder = -1;
AnimPlay_SetImg(&ent_Platform->anim, img_platform); AnimPlay_SetImg(&ent_Platform->anim, img_platform);
ent_Platform->mass = 0.0f; ent_Platform->mass = 0.0f;
ent_Platform->radius = 12; ent_Platform->radius = 12;
ent_Platform->width = 64; ent_Platform->width = 64;
ent_Platform->height = 16; ent_Platform->height = 16;
ent_Platform->fric_static = 0.0f; ent_Platform->fric_static = 0.0f;
ent_Platform->fric_dynamic = 0.2f; ent_Platform->fric_dynamic = 0.2f;
ent_Block = Entity_New(); ent_Block = Entity_New();
ent_Block->type = Ent_Block; ent_Block->type = Ent_Block;
ent_Block->flags = EntityFlag_BlockCollision; ent_Block->flags = EntityFlag_BlockCollision;
ent_Block->zorder = -1; ent_Block->zorder = -1;
AnimPlay_SetImg(&ent_Block->anim, img_block); AnimPlay_SetImg(&ent_Block->anim, img_block);
ent_Block->mass = 0.0f; ent_Block->mass = 0.0f;
ent_Block->radius = 32; ent_Block->radius = 32;
ent_Block->width = 64; ent_Block->width = 64;
ent_Block->height = 64; ent_Block->height = 64;
ent_Block->fric_static = 0.0f; ent_Block->fric_static = 0.0f;
ent_Block->fric_dynamic = 0.2f; ent_Block->fric_dynamic = 0.2f;
} }

View File

@@ -59,7 +59,7 @@ int GameMap_LoadLevel(char *filename, int res) {
} }
// Read the file to determine sizes // Read the file to determine sizes
width = 0; width = 0;
height = 0; height = 0;
do { do {
len = ReadLine(file, line, MaxLineLen); len = ReadLine(file, line, MaxLineLen);

View File

@@ -44,7 +44,7 @@ int main(int argc, char *argv[]) {
///////////////////////////// /////////////////////////////
// Load and initialize media. // Load and initialize media.
// //
font = Draw_DefaultFont(255, 255, 255, 255); font = Draw_DefaultFont(255, 255, 255, 255);
imgBackground = Draw_LoadImage("data/background.png"); imgBackground = Draw_LoadImage("data/background.png");
Draw_SetOffset(imgBackground, 0, 0); Draw_SetOffset(imgBackground, 0, 0);
GameEnts_Init(); GameEnts_Init();
@@ -59,8 +59,7 @@ int main(int argc, char *argv[]) {
// Run the world. // Run the world.
// //
GameLib_CleanParallaxBackgrounds(); GameLib_CleanParallaxBackgrounds();
GameLib_AddParallaxBackground(imgBackground, (int[2]){512, 512}, GameLib_AddParallaxBackground(imgBackground, (int[2]){512, 512}, (int[2]){0, 0}, (float[2]){0.5f, 0.0f});
(int[2]){0, 0}, (float[2]){0.5f, 0.0f});
GameLib_Loop(ProcGame, PostProcGame, PreDrawGame, DrawGame); GameLib_Loop(ProcGame, PostProcGame, PreDrawGame, DrawGame);
return (0); return (0);

View File

@@ -5,8 +5,8 @@
Feel free to customize this file to suit your needs Feel free to customize this file to suit your needs
*/ */
#include <SDL.h>
#import <Cocoa/Cocoa.h> #import <Cocoa/Cocoa.h>
#include <SDL.h>
@interface SDLMain : NSObject @interface SDLMain : NSObject
@end @end
@@ -17,48 +17,47 @@
/* For some reaon, Apple removed setAppleMenu from the headers in 10.4, /* For some reaon, Apple removed setAppleMenu from the headers in 10.4,
but the method still is there and works. To avoid warnings, we declare but the method still is there and works. To avoid warnings, we declare
it ourselves here. */ it ourselves here. */
@interface NSApplication(SDL_Missing_Methods) @interface NSApplication (SDL_Missing_Methods)
- (void)setAppleMenu:(NSMenu *)menu; - (void)setAppleMenu:(NSMenu *)menu;
@end @end
/* Use this flag to determine whether we use SDLMain.nib or not */ /* Use this flag to determine whether we use SDLMain.nib or not */
#define SDL_USE_NIB_FILE 0 #define SDL_USE_NIB_FILE 0
/* Use this flag to determine whether we use CPS (docking) or not */ /* Use this flag to determine whether we use CPS (docking) or not */
#define SDL_USE_CPS 1 #define SDL_USE_CPS 1
#ifdef SDL_USE_CPS #ifdef SDL_USE_CPS
/* Portions of CPS.h */ /* Portions of CPS.h */
typedef struct CPSProcessSerNum typedef struct CPSProcessSerNum {
{ UInt32 lo;
UInt32 lo; UInt32 hi;
UInt32 hi;
} CPSProcessSerNum; } CPSProcessSerNum;
extern OSErr CPSGetCurrentProcess( CPSProcessSerNum *psn); extern OSErr CPSGetCurrentProcess(CPSProcessSerNum *psn);
extern OSErr CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5); extern OSErr
extern OSErr CPSSetFrontProcess( CPSProcessSerNum *psn); CPSEnableForegroundOperation(CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5);
extern OSErr CPSSetFrontProcess(CPSProcessSerNum *psn);
#endif /* SDL_USE_CPS */ #endif /* SDL_USE_CPS */
static int gArgc; static int gArgc;
static char **gArgv; static char **gArgv;
static BOOL gFinderLaunch; static BOOL gFinderLaunch;
static BOOL gCalledAppMainline = FALSE; static BOOL gCalledAppMainline = FALSE;
static NSString *getApplicationName(void) static NSString *getApplicationName(void) {
{ const NSDictionary *dict;
const NSDictionary *dict; NSString *appName = 0;
NSString *appName = 0;
/* Determine the application name */ /* Determine the application name */
dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle()); dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle());
if (dict) if (dict)
appName = [dict objectForKey: @"CFBundleName"]; appName = [dict objectForKey:@"CFBundleName"];
if (![appName length]) if (![appName length])
appName = [[NSProcessInfo processInfo] processName]; appName = [[NSProcessInfo processInfo] processName];
return appName; return appName;
} }
#if SDL_USE_NIB_FILE #if SDL_USE_NIB_FILE
@@ -73,12 +72,11 @@ static NSString *getApplicationName(void)
@implementation NSApplication (SDLApplication) @implementation NSApplication (SDLApplication)
/* Invoked from the Quit menu item */ /* Invoked from the Quit menu item */
- (void)terminate:(id)sender - (void)terminate:(id)sender {
{ /* Post a SDL_QUIT event */
/* Post a SDL_QUIT event */ SDL_Event event;
SDL_Event event; event.type = SDL_QUIT;
event.type = SDL_QUIT; SDL_PushEvent(&event);
SDL_PushEvent(&event);
} }
@end @end
@@ -86,157 +84,150 @@ static NSString *getApplicationName(void)
@implementation SDLMain @implementation SDLMain
/* Set the working directory to the .app's parent directory */ /* Set the working directory to the .app's parent directory */
- (void) setupWorkingDirectory:(BOOL)shouldChdir - (void)setupWorkingDirectory:(BOOL)shouldChdir {
{ if (shouldChdir) {
if (shouldChdir) char parentdir[MAXPATHLEN];
{ CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle());
char parentdir[MAXPATHLEN]; CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url);
CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle()); if (CFURLGetFileSystemRepresentation(url2, 1, (UInt8 *)parentdir, MAXPATHLEN)) {
CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url); chdir(parentdir); /* chdir to the binary app's parent */
if (CFURLGetFileSystemRepresentation(url2, 1, (UInt8 *)parentdir, MAXPATHLEN)) { }
chdir(parentdir); /* chdir to the binary app's parent */ CFRelease(url);
} CFRelease(url2);
CFRelease(url); }
CFRelease(url2);
}
} }
#if SDL_USE_NIB_FILE #if SDL_USE_NIB_FILE
/* Fix menu to contain the real app name instead of "SDL App" */ /* Fix menu to contain the real app name instead of "SDL App" */
- (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName - (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName {
{ NSRange aRange;
NSRange aRange; NSEnumerator *enumerator;
NSEnumerator *enumerator; NSMenuItem *menuItem;
NSMenuItem *menuItem;
aRange = [[aMenu title] rangeOfString:@"SDL App"]; aRange = [[aMenu title] rangeOfString:@"SDL App"];
if (aRange.length != 0) if (aRange.length != 0)
[aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]]; [aMenu setTitle:[[aMenu title] stringByReplacingRange:aRange with:appName]];
enumerator = [[aMenu itemArray] objectEnumerator]; enumerator = [[aMenu itemArray] objectEnumerator];
while ((menuItem = [enumerator nextObject])) while ((menuItem = [enumerator nextObject])) {
{ aRange = [[menuItem title] rangeOfString:@"SDL App"];
aRange = [[menuItem title] rangeOfString:@"SDL App"]; if (aRange.length != 0)
if (aRange.length != 0) [menuItem setTitle:[[menuItem title] stringByReplacingRange:aRange with:appName]];
[menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]]; if ([menuItem hasSubmenu])
if ([menuItem hasSubmenu]) [self fixMenu:[menuItem submenu] withAppName:appName];
[self fixMenu:[menuItem submenu] withAppName:appName]; }
}
} }
#else #else
static void setApplicationMenu(void) static void setApplicationMenu(void) {
{ /* warning: this code is very odd */
/* warning: this code is very odd */ NSMenu *appleMenu;
NSMenu *appleMenu; NSMenuItem *menuItem;
NSMenuItem *menuItem; NSString *title;
NSString *title; NSString *appName;
NSString *appName;
appName = getApplicationName(); appName = getApplicationName();
appleMenu = [[NSMenu alloc] initWithTitle:@""]; appleMenu = [[NSMenu alloc] initWithTitle:@""];
/* Add menu items */ /* Add menu items */
title = [@"About " stringByAppendingString:appName]; title = [@"About " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""]; [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
[appleMenu addItem:[NSMenuItem separatorItem]]; [appleMenu addItem:[NSMenuItem separatorItem]];
title = [@"Hide " stringByAppendingString:appName]; title = [@"Hide " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"]; [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others"
[menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)]; action:@selector(hideOtherApplications:)
keyEquivalent:@"h"];
[menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask | NSCommandKeyMask)];
[appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
[appleMenu addItem:[NSMenuItem separatorItem]]; [appleMenu addItem:[NSMenuItem separatorItem]];
title = [@"Quit " stringByAppendingString:appName]; title = [@"Quit " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"]; [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
/* Put menu into the menubar */
menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
[menuItem setSubmenu:appleMenu];
[[NSApp mainMenu] addItem:menuItem];
/* Put menu into the menubar */ /* Tell the application object that this is now the application menu */
menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""]; [NSApp setAppleMenu:appleMenu];
[menuItem setSubmenu:appleMenu];
[[NSApp mainMenu] addItem:menuItem];
/* Tell the application object that this is now the application menu */ /* Finally give up our references to the objects */
[NSApp setAppleMenu:appleMenu]; [appleMenu release];
[menuItem release];
/* Finally give up our references to the objects */
[appleMenu release];
[menuItem release];
} }
/* Create a window menu */ /* Create a window menu */
static void setupWindowMenu(void) static void setupWindowMenu(void) {
{ NSMenu *windowMenu;
NSMenu *windowMenu; NSMenuItem *windowMenuItem;
NSMenuItem *windowMenuItem; NSMenuItem *menuItem;
NSMenuItem *menuItem;
windowMenu = [[NSMenu alloc] initWithTitle:@"Window"]; windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
/* "Minimize" item */ /* "Minimize" item */
menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
[windowMenu addItem:menuItem]; [windowMenu addItem:menuItem];
[menuItem release]; [menuItem release];
/* Put menu into the menubar */ /* Put menu into the menubar */
windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""]; windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
[windowMenuItem setSubmenu:windowMenu]; [windowMenuItem setSubmenu:windowMenu];
[[NSApp mainMenu] addItem:windowMenuItem]; [[NSApp mainMenu] addItem:windowMenuItem];
/* Tell the application object that this is now the window menu */ /* Tell the application object that this is now the window menu */
[NSApp setWindowsMenu:windowMenu]; [NSApp setWindowsMenu:windowMenu];
/* Finally give up our references to the objects */ /* Finally give up our references to the objects */
[windowMenu release]; [windowMenu release];
[windowMenuItem release]; [windowMenuItem release];
} }
/* Replacement for NSApplicationMain */ /* Replacement for NSApplicationMain */
static void CustomApplicationMain (int argc, char **argv) static void CustomApplicationMain(int argc, char **argv) {
{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; SDLMain *sdlMain;
SDLMain *sdlMain;
/* Ensure the application object is initialised */ /* Ensure the application object is initialised */
[NSApplication sharedApplication]; [NSApplication sharedApplication];
#ifdef SDL_USE_CPS #ifdef SDL_USE_CPS
{ {
CPSProcessSerNum PSN; CPSProcessSerNum PSN;
/* Tell the dock about us */ /* Tell the dock about us */
if (!CPSGetCurrentProcess(&PSN)) if (!CPSGetCurrentProcess(&PSN))
if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103)) if (!CPSEnableForegroundOperation(&PSN, 0x03, 0x3C, 0x2C, 0x1103))
if (!CPSSetFrontProcess(&PSN)) if (!CPSSetFrontProcess(&PSN))
[NSApplication sharedApplication]; [NSApplication sharedApplication];
} }
#endif /* SDL_USE_CPS */ #endif /* SDL_USE_CPS */
/* Set up the menubar */ /* Set up the menubar */
[NSApp setMainMenu:[[NSMenu alloc] init]]; [NSApp setMainMenu:[[NSMenu alloc] init]];
setApplicationMenu(); setApplicationMenu();
setupWindowMenu(); setupWindowMenu();
/* Create SDLMain and make it the app delegate */ /* Create SDLMain and make it the app delegate */
sdlMain = [[SDLMain alloc] init]; sdlMain = [[SDLMain alloc] init];
[NSApp setDelegate:sdlMain]; [NSApp setDelegate:sdlMain];
/* Start the main event loop */ /* Start the main event loop */
[NSApp run]; [NSApp run];
[sdlMain release]; [sdlMain release];
[pool release]; [pool release];
} }
#endif #endif
/* /*
* Catch document open requests...this lets us notice files when the app * Catch document open requests...this lets us notice files when the app
* was launched by double-clicking a document, or when a document was * was launched by double-clicking a document, or when a document was
@@ -252,133 +243,123 @@ static void CustomApplicationMain (int argc, char **argv)
* *
* This message is ignored once the app's mainline has been called. * This message is ignored once the app's mainline has been called.
*/ */
- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename - (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename {
{ const char *temparg;
const char *temparg; size_t arglen;
size_t arglen; char *arg;
char *arg; char **newargv;
char **newargv;
if (!gFinderLaunch) /* MacOS is passing command line args. */ if (!gFinderLaunch) /* MacOS is passing command line args. */
return FALSE; return FALSE;
if (gCalledAppMainline) /* app has started, ignore this document. */ if (gCalledAppMainline) /* app has started, ignore this document. */
return FALSE; return FALSE;
temparg = [filename UTF8String]; temparg = [filename UTF8String];
arglen = SDL_strlen(temparg) + 1; arglen = SDL_strlen(temparg) + 1;
arg = (char *) SDL_malloc(arglen); arg = (char *)SDL_malloc(arglen);
if (arg == NULL) if (arg == NULL)
return FALSE; return FALSE;
newargv = (char **) realloc(gArgv, sizeof (char *) * (gArgc + 2)); newargv = (char **)realloc(gArgv, sizeof(char *) * (gArgc + 2));
if (newargv == NULL) if (newargv == NULL) {
{ SDL_free(arg);
SDL_free(arg); return FALSE;
return FALSE; }
} gArgv = newargv;
gArgv = newargv;
SDL_strlcpy(arg, temparg, arglen); SDL_strlcpy(arg, temparg, arglen);
gArgv[gArgc++] = arg; gArgv[gArgc++] = arg;
gArgv[gArgc] = NULL; gArgv[gArgc] = NULL;
return TRUE; return TRUE;
} }
/* Called when the internal event loop has just started running */ /* Called when the internal event loop has just started running */
- (void) applicationDidFinishLaunching: (NSNotification *) note - (void)applicationDidFinishLaunching:(NSNotification *)note {
{ int status;
int status;
/* Set the working directory to the .app's parent directory */ /* Set the working directory to the .app's parent directory */
[self setupWorkingDirectory:gFinderLaunch]; [self setupWorkingDirectory:gFinderLaunch];
#if SDL_USE_NIB_FILE #if SDL_USE_NIB_FILE
/* Set the main menu to contain the real app name instead of "SDL App" */ /* Set the main menu to contain the real app name instead of "SDL App" */
[self fixMenu:[NSApp mainMenu] withAppName:getApplicationName()]; [self fixMenu:[NSApp mainMenu] withAppName:getApplicationName()];
#endif #endif
/* Hand off to main application code */ /* Hand off to main application code */
gCalledAppMainline = TRUE; gCalledAppMainline = TRUE;
status = SDL_main (gArgc, gArgv); status = SDL_main(gArgc, gArgv);
/* We're done, thank you for playing */ /* We're done, thank you for playing */
exit(status); exit(status);
} }
@end @end
@implementation NSString (ReplaceSubString) @implementation NSString (ReplaceSubString)
- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString - (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString {
{ unsigned int bufferSize;
unsigned int bufferSize; unsigned int selfLen = [self length];
unsigned int selfLen = [self length]; unsigned int aStringLen = [aString length];
unsigned int aStringLen = [aString length]; unichar *buffer;
unichar *buffer; NSRange localRange;
NSRange localRange; NSString *result;
NSString *result;
bufferSize = selfLen + aStringLen - aRange.length; bufferSize = selfLen + aStringLen - aRange.length;
buffer = (unichar *)NSAllocateMemoryPages(bufferSize*sizeof(unichar)); buffer = (unichar *)NSAllocateMemoryPages(bufferSize * sizeof(unichar));
/* Get first part into buffer */ /* Get first part into buffer */
localRange.location = 0; localRange.location = 0;
localRange.length = aRange.location; localRange.length = aRange.location;
[self getCharacters:buffer range:localRange]; [self getCharacters:buffer range:localRange];
/* Get middle part into buffer */ /* Get middle part into buffer */
localRange.location = 0; localRange.location = 0;
localRange.length = aStringLen; localRange.length = aStringLen;
[aString getCharacters:(buffer+aRange.location) range:localRange]; [aString getCharacters:(buffer + aRange.location) range:localRange];
/* Get last part into buffer */ /* Get last part into buffer */
localRange.location = aRange.location + aRange.length; localRange.location = aRange.location + aRange.length;
localRange.length = selfLen - localRange.location; localRange.length = selfLen - localRange.location;
[self getCharacters:(buffer+aRange.location+aStringLen) range:localRange]; [self getCharacters:(buffer + aRange.location + aStringLen) range:localRange];
/* Build output string */ /* Build output string */
result = [NSString stringWithCharacters:buffer length:bufferSize]; result = [NSString stringWithCharacters:buffer length:bufferSize];
NSDeallocateMemoryPages(buffer, bufferSize); NSDeallocateMemoryPages(buffer, bufferSize);
return result; return result;
} }
@end @end
#ifdef main #ifdef main
# undef main #undef main
#endif #endif
/* Main entry point to executable - should *not* be SDL_main! */ /* Main entry point to executable - should *not* be SDL_main! */
int main (int argc, char **argv) int main(int argc, char **argv) {
{ /* Copy the arguments into a global variable */
/* Copy the arguments into a global variable */ /* This is passed if we are launched by double-clicking */
/* This is passed if we are launched by double-clicking */ if (argc >= 2 && strncmp(argv[1], "-psn", 4) == 0) {
if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) { gArgv = (char **)SDL_malloc(sizeof(char *) * 2);
gArgv = (char **) SDL_malloc(sizeof (char *) * 2); gArgv[0] = argv[0];
gArgv[0] = argv[0]; gArgv[1] = NULL;
gArgv[1] = NULL; gArgc = 1;
gArgc = 1; gFinderLaunch = YES;
gFinderLaunch = YES; } else {
} else { int i;
int i; gArgc = argc;
gArgc = argc; gArgv = (char **)SDL_malloc(sizeof(char *) * (argc + 1));
gArgv = (char **) SDL_malloc(sizeof (char *) * (argc+1)); for (i = 0; i <= argc; i++)
for (i = 0; i <= argc; i++) gArgv[i] = argv[i];
gArgv[i] = argv[i]; gFinderLaunch = NO;
gFinderLaunch = NO; }
}
#if SDL_USE_NIB_FILE #if SDL_USE_NIB_FILE
NSApplicationMain (argc, argv); NSApplicationMain(argc, argv);
#else #else
CustomApplicationMain (argc, argv); CustomApplicationMain(argc, argv);
#endif #endif
return 0; return 0;
} }

View File

@@ -36,16 +36,16 @@ Anim Anim_LoadAnim(char *fichero, int width, int frames, float fps) {
Draw_SetOffset(img, -(width / 2), -(h / 2)); Draw_SetOffset(img, -(width / 2), -(h / 2));
// Create the animation container // Create the animation container
anim = malloc(sizeof(Animation)); anim = malloc(sizeof(Animation));
anim->img = img; anim->img = img;
anim->w = width; anim->w = width;
if (width <= 0) { if (width <= 0) {
anim->w = w / frames; anim->w = w / frames;
} }
anim->fps = fps; anim->fps = fps;
anim->frames = frames; anim->frames = frames;
anim->ftime = 1000 / fps; anim->ftime = 1000 / fps;
anim->time = anim->ftime * frames; anim->time = anim->ftime * frames;
return ((Anim)anim); return ((Anim)anim);
} }
@@ -124,12 +124,12 @@ void AnimPlay_Copy(AnimPlay *ad, AnimPlay *ao) {
ad->img = ao->img; ad->img = ao->img;
ad->imgPart = ao->imgPart; ad->imgPart = ao->imgPart;
ad->w = ao->w; ad->w = ao->w;
ad->h = ao->h; ad->h = ao->h;
ad->i = ao->i; ad->i = ao->i;
ad->j = ao->j; ad->j = ao->j;
ad->anim = ao->anim; ad->anim = ao->anim;
ad->time_ms = ao->time_ms; ad->time_ms = ao->time_ms;
} }
@@ -140,7 +140,7 @@ void AnimPlay_Copy(AnimPlay *ad, AnimPlay *ao) {
// //
// //
void AnimPlay_SetImg(AnimPlay *ap, DrawImg img) { void AnimPlay_SetImg(AnimPlay *ap, DrawImg img) {
ap->anim = NULL; ap->anim = NULL;
ap->time_ms = 0; ap->time_ms = 0;
ap->img = img; ap->img = img;
@@ -152,25 +152,24 @@ void AnimPlay_SetAnim(AnimPlay *ap, Anim ani) {
if (ap->anim == ani) { if (ap->anim == ani) {
return; return;
} }
ap->anim = ani; ap->anim = ani;
ap->time_ms = 0; ap->time_ms = 0;
ap->img = NULL; ap->img = NULL;
ap->imgPart = NULL; ap->imgPart = NULL;
} }
void AnimPlay_SetImgPart(AnimPlay *ap, DrawImg img, int w, int h, int i, void AnimPlay_SetImgPart(AnimPlay *ap, DrawImg img, int w, int h, int i, int j) {
int j) { ap->anim = NULL;
ap->anim = NULL;
ap->time_ms = 0; ap->time_ms = 0;
ap->img = NULL; ap->img = NULL;
ap->imgPart = img; ap->imgPart = img;
ap->w = w; ap->w = w;
ap->h = h; ap->h = h;
ap->i = i; ap->i = i;
ap->j = j; ap->j = j;
} }
///////////////////////////// /////////////////////////////
@@ -187,8 +186,7 @@ void AnimPlay_Draw(AnimPlay *ani, int x, int y, float scale[2]) {
return; return;
} }
if (ani->imgPart) { if (ani->imgPart) {
Draw_DrawImgPart(ani->imgPart, x, y, ani->w, ani->h, ani->i, ani->j, Draw_DrawImgPart(ani->imgPart, x, y, ani->w, ani->h, ani->i, ani->j, scale);
scale);
return; return;
} }
} }

View File

@@ -47,7 +47,7 @@ struct TAudioChan {
AudioChan next; AudioChan next;
}; };
AudioChan _channels = NULL; AudioChan _channels = NULL;
AudioChan _free_channels = NULL; AudioChan _free_channels = NULL;
static SDL_AudioDeviceID _audioDeviceID = 0; static SDL_AudioDeviceID _audioDeviceID = 0;
@@ -68,11 +68,11 @@ int Audio_Init() {
} }
// Open the audio device using the desired parameters // Open the audio device using the desired parameters
as.freq = 44100; as.freq = 44100;
as.format = AUDIO_S16SYS; as.format = AUDIO_S16SYS;
as.channels = 2; as.channels = 2;
as.samples = 2048; as.samples = 2048;
as.callback = Audio_MixerCallback; as.callback = Audio_MixerCallback;
_audioDeviceID = SDL_OpenAudioDevice(NULL, 0, &as, &as2, 0); _audioDeviceID = SDL_OpenAudioDevice(NULL, 0, &as, &as2, 0);
if (_audioDeviceID == 0) { if (_audioDeviceID == 0) {
Print("Audio_Init: Failure opening audio.\n"); Print("Audio_Init: Failure opening audio.\n");
@@ -112,14 +112,14 @@ static void Audio_MixerCallback(void *ud, Uint8 *stream, int l) {
// Mix all the channels // Mix all the channels
prevchan = NULL; prevchan = NULL;
chan = _channels; chan = _channels;
while (chan) { while (chan) {
if (!chan->wave) { if (!chan->wave) {
// Remove finished channels // Remove finished channels
AudioChan aux_chan = chan->next; AudioChan aux_chan = chan->next;
chan->next = _free_channels; chan->next = _free_channels;
_free_channels = chan; _free_channels = chan;
chan = aux_chan; chan = aux_chan;
if (prevchan) { if (prevchan) {
prevchan->next = chan; prevchan->next = chan;
} else { } else {
@@ -129,9 +129,9 @@ static void Audio_MixerCallback(void *ud, Uint8 *stream, int l) {
} }
// Prepare the pointers // Prepare the pointers
ptr_out = (signed short *)stream; ptr_out = (signed short *)stream;
ptr_wave = ((signed short *)chan->wave->buffer) + chan->pos; ptr_wave = ((signed short *)chan->wave->buffer) + chan->pos;
wave = chan->wave; wave = chan->wave;
// Determine mixing lenght // Determine mixing lenght
chan_remain = wave->len - chan->pos; chan_remain = wave->len - chan->pos;
@@ -174,8 +174,7 @@ static void Audio_MixerCallback(void *ud, Uint8 *stream, int l) {
// Next sample // Next sample
ptr_out += 2; ptr_out += 2;
if (ptr_wave >= if (ptr_wave >= (((signed short *)wave->buffer) + (wave->len - 1))) {
(((signed short *)wave->buffer) + (wave->len - 1))) {
ptr_wave = ((signed short *)wave->buffer); ptr_wave = ((signed short *)wave->buffer);
} else { } else {
ptr_wave++; ptr_wave++;
@@ -192,7 +191,7 @@ static void Audio_MixerCallback(void *ud, Uint8 *stream, int l) {
// Next channel // Next channel
prevchan = chan; prevchan = chan;
chan = chan->next; chan = chan->next;
} }
} }
@@ -260,9 +259,12 @@ AudioSnd Audio_LoadSound(char *filename) {
// Assert sound format // Assert sound format
if (sampleRate != 44100 || channels != 1 || bitsPerSample != 2) { if (sampleRate != 44100 || channels != 1 || bitsPerSample != 2) {
Print("Audio_LoadSound: Format not supported: " Print(
"sampleRate:%d; channels:%d; BPB:%d\n", "Audio_LoadSound: Format not supported: "
sampleRate, channels, bitsPerSample); "sampleRate:%d; channels:%d; BPB:%d\n",
sampleRate,
channels,
bitsPerSample);
fclose(f); fclose(f);
return (NULL); return (NULL);
} }
@@ -294,17 +296,17 @@ AudioSnd Audio_LoadSound(char *filename) {
fclose(f); fclose(f);
// Build the wave object // Build the wave object
AudioWave wave = malloc(sizeof(TAudioWave)); AudioWave wave = malloc(sizeof(TAudioWave));
wave->sampleRate = sampleRate; wave->sampleRate = sampleRate;
wave->channels = channels; wave->channels = channels;
wave->buffer = (Uint8 *)sndBuffer; wave->buffer = (Uint8 *)sndBuffer;
wave->BPB = bitsPerSample; wave->BPB = bitsPerSample;
wave->bpb = wave->BPB * 8; wave->bpb = wave->BPB * 8;
wave->len = dataSize / (wave->BPB * wave->channels); wave->len = dataSize / (wave->BPB * wave->channels);
// Take a reference // Take a reference
wave->next = _waves; wave->next = _waves;
_waves = wave; _waves = wave;
return (wave); return (wave);
} }
@@ -313,8 +315,7 @@ AudioSnd Audio_LoadSound(char *filename) {
// Audio_PlaySound // Audio_PlaySound
// //
// Loads a sound, giving a reference. // Loads a sound, giving a reference.
AudioChn Audio_PlaySound(AudioSnd snd, float leftvol, float rightvol, AudioChn Audio_PlaySound(AudioSnd snd, float leftvol, float rightvol, int loop) {
int loop) {
AudioChan chan; AudioChan chan;
AudioWave wave; AudioWave wave;
if (!snd) { if (!snd) {
@@ -326,24 +327,24 @@ AudioChn Audio_PlaySound(AudioSnd snd, float leftvol, float rightvol,
// Get a free channel // Get a free channel
if (_free_channels) { if (_free_channels) {
chan = _free_channels; chan = _free_channels;
_free_channels = chan->next; _free_channels = chan->next;
chan->next = NULL; chan->next = NULL;
} else { } else {
chan = malloc(sizeof(TAudioChan)); chan = malloc(sizeof(TAudioChan));
chan->next = NULL; chan->next = NULL;
} }
// Initialize the channel // Initialize the channel
chan->wave = wave; chan->wave = wave;
chan->pos = 0; chan->pos = 0;
chan->rightvol = (rightvol * 255); chan->rightvol = (rightvol * 255);
chan->leftvol = (leftvol * 255); chan->leftvol = (leftvol * 255);
chan->loop = loop; chan->loop = loop;
// Include in sounds list // Include in sounds list
chan->next = _channels; chan->next = _channels;
_channels = chan; _channels = chan;
return chan; return chan;
} }

View File

@@ -60,16 +60,16 @@ struct TDrawImage {
}; };
// Globals // Globals
static SDL_Window *_window = NULL; static SDL_Window *_window = NULL;
static SDL_GLContext _glcontext = NULL; static SDL_GLContext _glcontext = NULL;
static SDL_Renderer *_renderer = NULL; static SDL_Renderer *_renderer = NULL;
int _width; int _width;
int _height; int _height;
long long proc_t_frame = 33333; long long proc_t_frame = 33333;
long long draw_t_frame = 16667; long long draw_t_frame = 16667;
int _fps = 60; int _fps = 60;
QuadArray2D _quadArray = NULL; QuadArray2D _quadArray = NULL;
DrawImage _currentImg = NULL; DrawImage _currentImg = NULL;
float _color[4]; float _color[4];
#if USE_OpenGLES #if USE_OpenGLES
@@ -77,9 +77,9 @@ float _color[4];
GLuint _whiteTex; GLuint _whiteTex;
GLuint Draw_CompileShader(GLenum type, const char *source) { GLuint Draw_CompileShader(GLenum type, const char *source) {
char *strType = type == GL_VERTEX_SHADER ? "VertexShader" char *strType = type == GL_VERTEX_SHADER ? "VertexShader"
: type == GL_FRAGMENT_SHADER ? "fragmentShader" : type == GL_FRAGMENT_SHADER ? "fragmentShader"
: "unknownShader"; : "unknownShader";
GLuint shader = glCreateShader(type); GLuint shader = glCreateShader(type);
if (shader == 0) { if (shader == 0) {
Print("Error creating shader of type: %s\n", strType); Print("Error creating shader of type: %s\n", strType);
@@ -109,7 +109,7 @@ GLuint Draw_CompileShader(GLenum type, const char *source) {
GLuint Draw_BuildProgram(const char *vertexShaderSource, const char *fragmentShaderSource) { GLuint Draw_BuildProgram(const char *vertexShaderSource, const char *fragmentShaderSource) {
// Compile shaders // Compile shaders
GLuint vertexShader = Draw_CompileShader(GL_VERTEX_SHADER, vertexShaderSource); GLuint vertexShader = Draw_CompileShader(GL_VERTEX_SHADER, vertexShaderSource);
GLuint fragmentShader = Draw_CompileShader(GL_FRAGMENT_SHADER, fragmentShaderSource); GLuint fragmentShader = Draw_CompileShader(GL_FRAGMENT_SHADER, fragmentShaderSource);
if (vertexShader == 0 || fragmentShader == 0) { if (vertexShader == 0 || fragmentShader == 0) {
return 0; return 0;
@@ -175,9 +175,9 @@ int Draw_Init(int width, int height, char *title, int pfps, int fps) {
// Set globals // Set globals
proc_t_frame = 1000000 / pfps; proc_t_frame = 1000000 / pfps;
draw_t_frame = 1000000 / fps; draw_t_frame = 1000000 / fps;
_fps = fps; _fps = fps;
_width = width; _width = width;
_height = height; _height = height;
// Initialize SDL // Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) < 0) { if (SDL_Init(SDL_INIT_VIDEO) < 0) {
@@ -260,11 +260,11 @@ int Draw_Init(int width, int height, char *title, int pfps, int fps) {
} }
glUseProgram(programObject); glUseProgram(programObject);
vertPosLoc = glGetAttribLocation(programObject, "aPosition"); vertPosLoc = glGetAttribLocation(programObject, "aPosition");
vertTexLoc = glGetAttribLocation(programObject, "aTexCoord"); vertTexLoc = glGetAttribLocation(programObject, "aTexCoord");
vertColorLoc = glGetAttribLocation(programObject, "aColor"); vertColorLoc = glGetAttribLocation(programObject, "aColor");
textureLoc = glGetUniformLocation(programObject, "sTexture"); textureLoc = glGetUniformLocation(programObject, "sTexture");
projectionMatrixLoc = glGetUniformLocation(programObject, "sProjectionMatrix"); projectionMatrixLoc = glGetUniformLocation(programObject, "sProjectionMatrix");
glUniform1i(textureLoc, 0); glUniform1i(textureLoc, 0);
@@ -275,30 +275,30 @@ int Draw_Init(int width, int height, char *title, int pfps, int fps) {
glBindBuffer(GL_ARRAY_BUFFER, vertexObject); glBindBuffer(GL_ARRAY_BUFFER, vertexObject);
glVertexAttribPointer(vertPosLoc, 2, GL_FLOAT, GL_FALSE, Vertex2D_Length * sizeof(float), glVertexAttribPointer(
(void *)(0 * sizeof(float))); vertPosLoc, 2, GL_FLOAT, GL_FALSE, Vertex2D_Length * sizeof(float), (void *)(0 * sizeof(float)));
glVertexAttribPointer(vertTexLoc, 2, GL_FLOAT, GL_FALSE, Vertex2D_Length * sizeof(float), glVertexAttribPointer(
(void *)(2 * sizeof(float))); vertTexLoc, 2, GL_FLOAT, GL_FALSE, Vertex2D_Length * sizeof(float), (void *)(2 * sizeof(float)));
glVertexAttribPointer(vertColorLoc, 4, GL_FLOAT, GL_FALSE, Vertex2D_Length * sizeof(float), glVertexAttribPointer(
(void *)(4 * sizeof(float))); vertColorLoc, 4, GL_FLOAT, GL_FALSE, Vertex2D_Length * sizeof(float), (void *)(4 * sizeof(float)));
glEnableVertexAttribArray(vertPosLoc); glEnableVertexAttribArray(vertPosLoc);
glEnableVertexAttribArray(vertTexLoc); glEnableVertexAttribArray(vertTexLoc);
glEnableVertexAttribArray(vertColorLoc); glEnableVertexAttribArray(vertColorLoc);
unsigned char whiteTexData[4] = {255, 255, 255, 255}; unsigned char whiteTexData[4] = {255, 255, 255, 255};
_whiteTex = Draw_UploadGLTexture(1, 1, whiteTexData); _whiteTex = Draw_UploadGLTexture(1, 1, whiteTexData);
#endif #endif
// Set the proyection (2D) // Set the proyection (2D)
glViewport(0, 0, _width, _height); glViewport(0, 0, _width, _height);
float projectionMatrix[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}; float projectionMatrix[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
projectionMatrix[0] = (2.0f / _width); projectionMatrix[0] = (2.0f / _width);
projectionMatrix[5] = -(2.0f / _height); projectionMatrix[5] = -(2.0f / _height);
projectionMatrix[10] = -0.001f; projectionMatrix[10] = -0.001f;
projectionMatrix[3] = -1.0f; projectionMatrix[3] = -1.0f;
projectionMatrix[7] = 1.0f; projectionMatrix[7] = 1.0f;
Draw_SetMatrix(projectionMatrix); Draw_SetMatrix(projectionMatrix);
// Enable Alpha blending // Enable Alpha blending
@@ -342,8 +342,23 @@ void Draw_ShowInfo() {
// Sets the render matrix // Sets the render matrix
void Draw_SetMatrix(float matrix[16]) { void Draw_SetMatrix(float matrix[16]) {
#if USE_OpenGL #if USE_OpenGL
float tempMatrix[16] = {matrix[0], matrix[4], matrix[8], matrix[12], matrix[1], matrix[5], matrix[9], matrix[13], float tempMatrix[16] = {
matrix[2], matrix[6], matrix[10], matrix[14], matrix[3], matrix[7], matrix[11], matrix[15]}; matrix[0],
matrix[4],
matrix[8],
matrix[12],
matrix[1],
matrix[5],
matrix[9],
matrix[13],
matrix[2],
matrix[6],
matrix[10],
matrix[14],
matrix[3],
matrix[7],
matrix[11],
matrix[15]};
glLoadMatrixf(tempMatrix); glLoadMatrixf(tempMatrix);
#endif #endif
#if USE_OpenGLES #if USE_OpenGLES
@@ -420,33 +435,33 @@ void Draw_Clean(unsigned char r, unsigned char g, unsigned char b) {
glClear(GL_COLOR_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT);
#else #else
Draw_Flush(); Draw_Flush();
float fr = r / 255.0f; float fr = r / 255.0f;
float fg = g / 255.0f; float fg = g / 255.0f;
float fb = b / 255.0f; float fb = b / 255.0f;
GLfloat vVertices[] = { GLfloat vVertices[] = {
0.0, 0.0, // Position 0 0.0, 0.0, // Position 0
0.0, 0.0, // TexCoord 0 0.0, 0.0, // TexCoord 0
fr, fg, fb, 1.0, // Color fr, fg, fb, 1.0, // Color
0.0, _height, // Position 1 0.0, _height, // Position 1
0.0, 1.0, // TexCoord 1 0.0, 1.0, // TexCoord 1
fr, fg, fb, 1.0, // Color fr, fg, fb, 1.0, // Color
_width, _height, // Position 2 _width, _height, // Position 2
1.0, 1.0, // TexCoord 2 1.0, 1.0, // TexCoord 2
fr, fg, fb, 1.0, // Color fr, fg, fb, 1.0, // Color
_width, _height, // Position 2 _width, _height, // Position 2
1.0, 1.0, // TexCoord 2 1.0, 1.0, // TexCoord 2
fr, fg, fb, 1.0, // Color fr, fg, fb, 1.0, // Color
_width, 0.0, // Position 3 _width, 0.0, // Position 3
1.0, 0.0, // TexCoord 3 1.0, 0.0, // TexCoord 3
fr, fg, fb, 1.0, // Color fr, fg, fb, 1.0, // Color
0.0, 0.0, // Position 0 0.0, 0.0, // Position 0
0.0, 0.0, // TexCoord 0 0.0, 0.0, // TexCoord 0
fr, fg, fb, 1.0, // Color fr, fg, fb, 1.0, // Color
}; };
glBindTexture(GL_TEXTURE_2D, _whiteTex); glBindTexture(GL_TEXTURE_2D, _whiteTex);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vVertices), vVertices); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vVertices), vVertices);
@@ -458,11 +473,11 @@ void Draw_Clean(unsigned char r, unsigned char g, unsigned char b) {
// Draw_LoopIteration // Draw_LoopIteration
// //
// One iteracion of the loop updating the game window. // One iteracion of the loop updating the game window.
void (*_proc_func)(void *data) = NULL; void (*_proc_func)(void *data) = NULL;
void (*_draw_func)(void *data, float f) = NULL; void (*_draw_func)(void *data, float f) = NULL;
void *_data = NULL; void *_data = NULL;
int _draw_looping = 0; int _draw_looping = 0;
int _draw_exitoverrided = 0; int _draw_exitoverrided = 0;
long long _accTime; long long _accTime;
int Draw_LoopIteration() { int Draw_LoopIteration() {
SDL_Event event; SDL_Event event;
@@ -578,14 +593,14 @@ void Draw_Loop(void (*proc)(void *data), void (*draw)(void *data, float f), void
_proc_func = proc; _proc_func = proc;
_draw_func = draw; _draw_func = draw;
_data = data; _data = data;
if (_draw_looping) { if (_draw_looping) {
return; return;
} }
_draw_looping = 1; _draw_looping = 1;
#ifndef EMSCRIPTEN #ifndef EMSCRIPTEN
long long procTime1, procTime2, drawTime1, drawTime2; long long procTime1, procTime2, drawTime1, drawTime2;
_accTime = proc_t_frame; _accTime = proc_t_frame;
procTime1 = drawTime1 = Time_GetTime(); procTime1 = drawTime1 = Time_GetTime();
while (Draw_LoopIteration()) { while (Draw_LoopIteration()) {
@@ -601,7 +616,7 @@ void Draw_Loop(void (*proc)(void *data), void (*draw)(void *data, float f), void
procTime1 = procTime2; procTime1 = procTime2;
} }
#else #else
_accTime = proc_t_frame; _accTime = proc_t_frame;
_procTime1 = Time_GetTime(); _procTime1 = Time_GetTime();
if (_fps <= 50) { if (_fps <= 50) {
emscripten_set_main_loop(Draw_LoopIterationAux, _fps, 1); emscripten_set_main_loop(Draw_LoopIterationAux, _fps, 1);
@@ -634,14 +649,14 @@ DrawImg Draw_CreateImage(int w, int h) {
DrawImage image; DrawImage image;
// Create the image container // Create the image container
image = malloc(sizeof(TDrawImage)); image = malloc(sizeof(TDrawImage));
image->data = malloc(w * h * 4); image->data = malloc(w * h * 4);
image->x = 0; image->x = 0;
image->y = 0; image->y = 0;
image->w = w; image->w = w;
image->h = h; image->h = h;
image->flip = 0; image->flip = 0;
image->tex = -1; image->tex = -1;
return ((DrawImg)image); return ((DrawImg)image);
} }
@@ -655,16 +670,16 @@ DrawImg Draw_LoadImage(char *filename) {
// Try loading PNG images // Try loading PNG images
if (EndsWith(filename, ".png") || EndsWith(filename, ".PNG")) { if (EndsWith(filename, ".png") || EndsWith(filename, ".PNG")) {
image = malloc(sizeof(TDrawImage)); image = malloc(sizeof(TDrawImage));
unsigned error = lodepng_decode32_file(&image->data, (unsigned *)&image->w, (unsigned *)&image->h, filename); unsigned error = lodepng_decode32_file(&image->data, (unsigned *)&image->w, (unsigned *)&image->h, filename);
if (error) { if (error) {
Print("Draw_LoadImage: PNG decoder error %u: %s on file %s\n", error, lodepng_error_text(error), filename); Print("Draw_LoadImage: PNG decoder error %u: %s on file %s\n", error, lodepng_error_text(error), filename);
return (NULL); return (NULL);
} }
image->x = -(int)(image->w / 2); image->x = -(int)(image->w / 2);
image->y = -(int)(image->h / 2); image->y = -(int)(image->h / 2);
image->flip = 0; image->flip = 0;
image->tex = -1; image->tex = -1;
return (DrawImg)image; return (DrawImg)image;
} }
@@ -711,7 +726,7 @@ void Draw_GetOffset(DrawImg img, int *x, int *y) {
// //
void Draw_SetFlip(DrawImg img, int flip) { void Draw_SetFlip(DrawImg img, int flip) {
DrawImage image = img; DrawImage image = img;
image->flip = flip; image->flip = flip;
} }
int Draw_GetFlip(DrawImg img) { int Draw_GetFlip(DrawImg img) {
DrawImage image = img; DrawImage image = img;
@@ -737,13 +752,13 @@ void Draw_DrawImg(DrawImg img, int x, int y, float scale[2]) {
// Apply flipping // Apply flipping
if (image->flip & 1) { if (image->flip & 1) {
float t = u1; float t = u1;
u1 = u2; u1 = u2;
u2 = t; u2 = t;
} }
if (image->flip & 2) { if (image->flip & 2) {
float t = v1; float t = v1;
v1 = v2; v1 = v2;
v2 = t; v2 = t;
} }
// Draw a quad // Draw a quad
@@ -773,13 +788,13 @@ void Draw_DrawImgResized(DrawImg img, int x, int y, float w, float h) {
// Apply flipping // Apply flipping
if (image->flip & 1) { if (image->flip & 1) {
float t = u1; float t = u1;
u1 = u2; u1 = u2;
u2 = t; u2 = t;
} }
if (image->flip & 2) { if (image->flip & 2) {
float t = v1; float t = v1;
v1 = v2; v1 = v2;
v2 = t; v2 = t;
} }
// Draw a quad // Draw a quad
@@ -817,13 +832,13 @@ void Draw_DrawImgPart(DrawImg img, int x, int y, int w, int h, int i, int j, flo
// Apply flipping // Apply flipping
if (image->flip & 1) { if (image->flip & 1) {
float t = u1; float t = u1;
u1 = u2; u1 = u2;
u2 = t; u2 = t;
} }
if (image->flip & 2) { if (image->flip & 2) {
float t = v1; float t = v1;
v1 = v2; v1 = v2;
v2 = t; v2 = t;
} }
// Draw a quad // Draw a quad
@@ -858,13 +873,13 @@ void Draw_DrawImgPartHoriz(DrawImg img, int x, int y, int w, int i, float scale[
// Apply flipping // Apply flipping
if (image->flip & 1) { if (image->flip & 1) {
float t = u1; float t = u1;
u1 = u2; u1 = u2;
u2 = t; u2 = t;
} }
if (image->flip & 2) { if (image->flip & 2) {
float t = v1; float t = v1;
v1 = v2; v1 = v2;
v2 = t; v2 = t;
} }
// Draw a quad // Draw a quad
@@ -879,8 +894,8 @@ void Draw_DrawImgPartHoriz(DrawImg img, int x, int y, int w, int i, float scale[
// Draw_ImgParallax // Draw_ImgParallax
// //
// //
void Draw_ImgParallax(DrawImg img, int imgSize[2], int imgOffset[2], float parallaxFactor[2], int gamePos[2], void Draw_ImgParallax(
int gameSize[2]) { DrawImg img, int imgSize[2], int imgOffset[2], float parallaxFactor[2], int gamePos[2], int gameSize[2]) {
int paralaxPos[2]; int paralaxPos[2];
int mult[2]; int mult[2];
int x, y; int x, y;
@@ -946,7 +961,7 @@ DrawImage Draw_DefaultFontImage(unsigned char r, unsigned char g, unsigned char
for (c = 0; c < 256; c++) { for (c = 0; c < 256; c++) {
for (y = 0; y < 8; y++) { for (y = 0; y < 8; y++) {
for (x = 0; x < 8; x++) { for (x = 0; x < 8; x++) {
int offset = ((c * 8 + x) + (8 * 256 * y)) * 4; int offset = ((c * 8 + x) + (8 * 256 * y)) * 4;
img->data[offset + 0] = r; img->data[offset + 0] = r;
img->data[offset + 1] = g; img->data[offset + 1] = g;
img->data[offset + 2] = b; img->data[offset + 2] = b;
@@ -970,12 +985,12 @@ DrawFnt Draw_DefaultFont(unsigned char r, unsigned char g, unsigned char b, unsi
DrawFont *font; DrawFont *font;
// Create the default font // Create the default font
font = malloc(sizeof(DrawFont)); font = malloc(sizeof(DrawFont));
font->img = Draw_DefaultFontImage(r, g, b, a); font->img = Draw_DefaultFontImage(r, g, b, a);
font->w = 8; font->w = 8;
font->h = 8; font->h = 8;
font->min = 0; font->min = 0;
font->max = 256; font->max = 256;
font->scale[0] = 1.0f; font->scale[0] = 1.0f;
font->scale[1] = 1.0f; font->scale[1] = 1.0f;
@@ -990,12 +1005,12 @@ DrawFnt Draw_LoadFont(char *fichero, int min, int max) {
DrawFont *font; DrawFont *font;
// Create the font form the image // Create the font form the image
font = malloc(sizeof(DrawFont)); font = malloc(sizeof(DrawFont));
font->img = Draw_LoadImage(fichero); font->img = Draw_LoadImage(fichero);
font->w = font->img->w / (max - min); font->w = font->img->w / (max - min);
font->h = font->img->h; font->h = font->img->h;
font->min = min; font->min = min;
font->max = max; font->max = max;
font->scale[0] = 1.0f; font->scale[0] = 1.0f;
font->scale[1] = 1.0f; font->scale[1] = 1.0f;
@@ -1039,8 +1054,8 @@ void Draw_SaveRGBAToBMP(char *filename, unsigned char *data, int width, int heig
SDL_Surface *surf; SDL_Surface *surf;
// Create the surface // Create the surface
surf = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 32, 0, 0, 0, 0); surf = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 32, 0, 0, 0, 0);
surf->format->Amask = 0xFF000000; surf->format->Amask = 0xFF000000;
surf->format->Ashift = 24; surf->format->Ashift = 24;
// SDL_SetAlpha(surf, GL_SRC_ALPHA, 255); // SDL_SetAlpha(surf, GL_SRC_ALPHA, 255);
SDL_LockSurface(surf); SDL_LockSurface(surf);
@@ -1049,13 +1064,13 @@ void Draw_SaveRGBAToBMP(char *filename, unsigned char *data, int width, int heig
// Swap RGB to BGR // Swap RGB to BGR
Uint32 *ptr, *ptr_end; Uint32 *ptr, *ptr_end;
ptr = (Uint32 *)surf->pixels; ptr = (Uint32 *)surf->pixels;
ptr_end = ptr + (surf->w * surf->h); ptr_end = ptr + (surf->w * surf->h);
while (ptr < ptr_end) { while (ptr < ptr_end) {
unsigned char temp; unsigned char temp;
unsigned char *pixel; unsigned char *pixel;
pixel = (unsigned char *)ptr; pixel = (unsigned char *)ptr;
temp = pixel[2]; temp = pixel[2];
pixel[2] = pixel[0]; pixel[2] = pixel[0];
pixel[0] = temp; pixel[0] = temp;
ptr++; ptr++;
@@ -1094,9 +1109,9 @@ void Draw_SaveScreenshoot(char *filename) {
glReadPixels(0, 0, _width, _height, GL_RGBA, GL_UNSIGNED_BYTE, pixelData); glReadPixels(0, 0, _width, _height, GL_RGBA, GL_UNSIGNED_BYTE, pixelData);
// Flip the image data // Flip the image data
line_size = _width * 4; line_size = _width * 4;
half_height = _height / 2; half_height = _height / 2;
image_line = malloc(line_size); image_line = malloc(line_size);
for (i = 0; i < half_height; i++) { for (i = 0; i < half_height; i++) {
memcpy(image_line, pixelData + i * line_size, line_size); memcpy(image_line, pixelData + i * line_size, line_size);
memcpy(pixelData + i * line_size, pixelData + (_height - (i + 1)) * line_size, line_size); memcpy(pixelData + i * line_size, pixelData + (_height - (i + 1)) * line_size, line_size);

View File

@@ -19,8 +19,7 @@ void Draw_Clean(unsigned char r, unsigned char g, unsigned char b);
// Draw_Loop // Draw_Loop
// //
// Loops updating the game window. // Loops updating the game window.
void Draw_Loop(void (*proc)(void *data), void (*draw)(void *data, float f), void Draw_Loop(void (*proc)(void *data), void (*draw)(void *data, float f), void *data);
void *data);
///////////////////////////// /////////////////////////////
// Draw_BreakLoop // Draw_BreakLoop
@@ -95,22 +94,20 @@ void Draw_DrawImgResized(DrawImg img, int x, int y, float w, float h);
// Draw_DrawImgPart // Draw_DrawImgPart
// //
// Draws an image part. // Draws an image part.
void Draw_DrawImgPart(DrawImg img, int x, int y, int w, int h, int i, int j, void Draw_DrawImgPart(DrawImg img, int x, int y, int w, int h, int i, int j, float scale[2]);
float scale[2]);
///////////////////////////// /////////////////////////////
// Draw_DrawImgPartHoriz // Draw_DrawImgPartHoriz
// //
// Draws an image part horizontally. // Draws an image part horizontally.
void Draw_DrawImgPartHoriz(DrawImg img, int x, int y, int w, int i, void Draw_DrawImgPartHoriz(DrawImg img, int x, int y, int w, int i, float scale[2]);
float scale[2]);
///////////////////////////// /////////////////////////////
// Draw_ImgParallax // Draw_ImgParallax
// //
// //
void Draw_ImgParallax(DrawImg img, int imgSize[2], int imgOffset[2], void Draw_ImgParallax(
float parallaxFactor[2], int gamePos[2], int gameSize[2]); DrawImg img, int imgSize[2], int imgOffset[2], float parallaxFactor[2], int gamePos[2], int gameSize[2]);
///////////////////////////// /////////////////////////////
// Draw_SetColor // Draw_SetColor
@@ -128,8 +125,7 @@ typedef void *DrawFnt;
// Draw_DefaultFont // Draw_DefaultFont
// //
// Creates the default font. // Creates the default font.
DrawFnt Draw_DefaultFont(unsigned char r, unsigned char g, unsigned char b, DrawFnt Draw_DefaultFont(unsigned char r, unsigned char g, unsigned char b, unsigned char a);
unsigned char a);
///////////////////////////// /////////////////////////////
// Draw_LoadFont // Draw_LoadFont
@@ -152,15 +148,13 @@ void Draw_DrawText(DrawFnt f, char *text, int x, int y);
// Draw_SaveRGBAToBMP // Draw_SaveRGBAToBMP
// //
// //
void Draw_SaveRGBAToBMP(char *filename, unsigned char *data, int width, void Draw_SaveRGBAToBMP(char *filename, unsigned char *data, int width, int height);
int height);
///////////////////////////// /////////////////////////////
// Draw_SaveRGBAToPNG // Draw_SaveRGBAToPNG
// //
// //
void Draw_SaveRGBAToPNG(char *filename, unsigned char *data, int width, void Draw_SaveRGBAToPNG(char *filename, unsigned char *data, int width, int height);
int height);
///////////////////////////// /////////////////////////////
// Draw_SaveScreenshoot // Draw_SaveScreenshoot

View File

@@ -26,7 +26,7 @@ Entity Entity_New() {
if (!_free_entity) { if (!_free_entity) {
// Allocate a big block of entities // Allocate a big block of entities
int n = 1024, i; int n = 1024, i;
TEntity *newEnts = malloc(sizeof(TEntity) * n); TEntity *newEnts = malloc(sizeof(TEntity) * n);
for (i = 0; i < n; i++) { for (i = 0; i < n; i++) {
if (i < (n - 1)) { if (i < (n - 1)) {
@@ -37,31 +37,31 @@ Entity Entity_New() {
} }
_free_entity = newEnts; _free_entity = newEnts;
} }
e = _free_entity; e = _free_entity;
_free_entity = e->next; _free_entity = e->next;
e->base = NULL; e->base = NULL;
e->type = 0; e->type = 0;
vec2_set(e->pos0, 0.0f, 0.0f); vec2_set(e->pos0, 0.0f, 0.0f);
vec2_set(e->pos, 0.0f, 0.0f); vec2_set(e->pos, 0.0f, 0.0f);
e->flags = EntityFlag_Collision | EntityFlag_Overlap; e->flags = EntityFlag_Collision | EntityFlag_Overlap;
e->internalFlags = EntityIntFlag_UpdateColor; e->internalFlags = EntityIntFlag_UpdateColor;
e->zorder = 1; e->zorder = 1;
e->sortYOffset = 0; e->sortYOffset = 0;
vec2_set(e->dir, 0.0f, 0.0f); vec2_set(e->dir, 0.0f, 0.0f);
vec2_set(e->vel, 0.0f, 0.0f); vec2_set(e->vel, 0.0f, 0.0f);
e->radius = 1.0f; e->radius = 1.0f;
e->width = 1.0f; e->width = 1.0f;
e->height = 1.0f; e->height = 1.0f;
e->mass = 1.0f; e->mass = 1.0f;
e->elast = 0.0f; e->elast = 0.0f;
e->backFric_static = 0.0f; e->backFric_static = 0.0f;
e->backFric_dynamic = 0.0f; e->backFric_dynamic = 0.0f;
e->fric_static = 0.0f; e->fric_static = 0.0f;
e->fric_dynamic = 0.0f; e->fric_dynamic = 0.0f;
AnimPlay_SetImg(&e->anim, NULL); AnimPlay_SetImg(&e->anim, NULL);
@@ -69,27 +69,26 @@ Entity Entity_New() {
e->color[0] = e->color[1] = e->color[2] = e->color[3] = 1.0f; e->color[0] = e->color[1] = e->color[2] = e->color[3] = 1.0f;
e->light[0] = e->light[1] = e->light[2] = e->light[3] = 1.0f; e->light[0] = e->light[1] = e->light[2] = e->light[3] = 1.0f;
e->defaultColor[0] = e->defaultColor[1] = e->defaultColor[2] = e->defaultColor[0] = e->defaultColor[1] = e->defaultColor[2] = e->defaultColor[3] = 1.0f;
e->defaultColor[3] = 1.0f;
e->scale0[0] = 1.0f; e->scale0[0] = 1.0f;
e->scale0[1] = 1.0f; e->scale0[1] = 1.0f;
e->scale[0] = 1.0f; e->scale[0] = 1.0f;
e->scale[1] = 1.0f; e->scale[1] = 1.0f;
e->oncopy = NULL; e->oncopy = NULL;
e->oninit = NULL; e->oninit = NULL;
e->ondelete = NULL; e->ondelete = NULL;
e->proc = NULL; e->proc = NULL;
e->postproc = NULL; e->postproc = NULL;
e->collision = NULL; e->collision = NULL;
e->overlap = NULL; e->overlap = NULL;
e->A = 0; e->A = 0;
e->B = 0; e->B = 0;
e->C = 0; e->C = 0;
e->D = 0; e->D = 0;
e->E = 0; e->E = 0;
e->child = NULL; e->child = NULL;
e->next = NULL; e->next = NULL;
@@ -115,7 +114,7 @@ void Entity_Destroy(Entity e) {
if (e->ondelete) { if (e->ondelete) {
e->ondelete(e); e->ondelete(e);
} }
e->next = _free_entity; e->next = _free_entity;
_free_entity = e; _free_entity = e;
} }
@@ -131,35 +130,35 @@ Entity Entity_Copy(Entity e) {
n->base = e; n->base = e;
n->type = e->type; n->type = e->type;
vec2_set(n->pos, e->pos[0], e->pos[1]); vec2_set(n->pos, e->pos[0], e->pos[1]);
n->flags = e->flags; n->flags = e->flags;
n->internalFlags = e->internalFlags; n->internalFlags = e->internalFlags;
n->zorder = e->zorder; n->zorder = e->zorder;
n->sortYOffset = e->sortYOffset; n->sortYOffset = e->sortYOffset;
vec2_set(n->vel, e->vel[0], e->vel[1]); vec2_set(n->vel, e->vel[0], e->vel[1]);
n->radius = e->radius; n->radius = e->radius;
n->width = e->width; n->width = e->width;
n->height = e->height; n->height = e->height;
n->mass = e->mass; n->mass = e->mass;
n->elast = e->elast; n->elast = e->elast;
n->backFric_static = e->backFric_static; n->backFric_static = e->backFric_static;
n->backFric_dynamic = e->backFric_dynamic; n->backFric_dynamic = e->backFric_dynamic;
n->fric_static = e->fric_static; n->fric_static = e->fric_static;
n->fric_dynamic = e->fric_dynamic; n->fric_dynamic = e->fric_dynamic;
AnimPlay_Copy(&n->anim, &e->anim); AnimPlay_Copy(&n->anim, &e->anim);
n->color0[0] = e->color0[0]; n->color0[0] = e->color0[0];
n->color0[1] = e->color0[1]; n->color0[1] = e->color0[1];
n->color0[2] = e->color0[2]; n->color0[2] = e->color0[2];
n->color0[3] = e->color0[3]; n->color0[3] = e->color0[3];
n->color[0] = e->color[0]; n->color[0] = e->color[0];
n->color[1] = e->color[1]; n->color[1] = e->color[1];
n->color[2] = e->color[2]; n->color[2] = e->color[2];
n->color[3] = e->color[3]; n->color[3] = e->color[3];
n->light[0] = e->light[0]; n->light[0] = e->light[0];
n->light[1] = e->light[1]; n->light[1] = e->light[1];
n->light[2] = e->light[2]; n->light[2] = e->light[2];
n->light[3] = e->light[3]; n->light[3] = e->light[3];
n->defaultColor[0] = e->defaultColor[0]; n->defaultColor[0] = e->defaultColor[0];
n->defaultColor[1] = e->defaultColor[1]; n->defaultColor[1] = e->defaultColor[1];
n->defaultColor[2] = e->defaultColor[2]; n->defaultColor[2] = e->defaultColor[2];
@@ -167,22 +166,22 @@ Entity Entity_Copy(Entity e) {
n->scale0[0] = e->scale[0]; n->scale0[0] = e->scale[0];
n->scale0[1] = e->scale[1]; n->scale0[1] = e->scale[1];
n->scale[0] = e->scale[0]; n->scale[0] = e->scale[0];
n->scale[1] = e->scale[1]; n->scale[1] = e->scale[1];
n->oncopy = e->oncopy; n->oncopy = e->oncopy;
n->oninit = e->oninit; n->oninit = e->oninit;
n->ondelete = e->ondelete; n->ondelete = e->ondelete;
n->proc = e->proc; n->proc = e->proc;
n->postproc = e->postproc; n->postproc = e->postproc;
n->collision = e->collision; n->collision = e->collision;
n->overlap = e->overlap; n->overlap = e->overlap;
n->A = e->A; n->A = e->A;
n->B = e->B; n->B = e->B;
n->C = e->C; n->C = e->C;
n->D = e->D; n->D = e->D;
n->E = e->E; n->E = e->E;
n->child = e->child; n->child = e->child;
Entity_CalcBBox(n); Entity_CalcBBox(n);
@@ -203,7 +202,7 @@ Entity Entity_Copy(Entity e) {
#define max(a, b) ((a) > (b) ? (a) : (b)) #define max(a, b) ((a) > (b) ? (a) : (b))
void Entity_CalcBBox(Entity e) { void Entity_CalcBBox(Entity e) {
float hHeight = (max(e->height, e->radius) / 2) + BBox_ExtraMargin; float hHeight = (max(e->height, e->radius) / 2) + BBox_ExtraMargin;
float hWidth = (max(e->width, e->radius) / 2) + BBox_ExtraMargin; float hWidth = (max(e->width, e->radius) / 2) + BBox_ExtraMargin;
if (e->vel[0] > 0) { if (e->vel[0] > 0) {
e->maxX = e->pos[0] + e->vel[0] + hWidth; e->maxX = e->pos[0] + e->vel[0] + hWidth;
e->minX = e->pos[0] - hWidth; e->minX = e->pos[0] - hWidth;
@@ -225,8 +224,7 @@ void Entity_CalcBBox(Entity e) {
// //
// //
int Entity_BBoxIntersect(Entity ent1, Entity ent2) { int Entity_BBoxIntersect(Entity ent1, Entity ent2) {
if (ent1->maxX >= ent2->minX && ent1->minX <= ent2->maxX && if (ent1->maxX >= ent2->minX && ent1->minX <= ent2->maxX && ent1->maxY >= ent2->minY && ent1->minY <= ent2->maxY) {
ent1->maxY >= ent2->minY && ent1->minY <= ent2->maxY) {
return (1); return (1);
} }
return (0); return (0);
@@ -240,10 +238,11 @@ void Entity_Draw(Entity e, int x, int y, float f) {
vec2 fPos; vec2 fPos;
float scale[2]; float scale[2];
if (e->internalFlags & EntityIntFlag_UpdatedColor) { if (e->internalFlags & EntityIntFlag_UpdatedColor) {
Draw_SetColor(e->color0[0] - f * (e->color0[0] - e->color[0]), Draw_SetColor(
e->color0[1] - f * (e->color0[1] - e->color[1]), e->color0[0] - f * (e->color0[0] - e->color[0]),
e->color0[2] - f * (e->color0[2] - e->color[2]), e->color0[1] - f * (e->color0[1] - e->color[1]),
e->color0[3] - f * (e->color0[3] - e->color[3])); e->color0[2] - f * (e->color0[2] - e->color[2]),
e->color0[3] - f * (e->color0[3] - e->color[3]));
} else { } else {
Draw_SetColor(e->color[0], e->color[1], e->color[2], e->color[3]); Draw_SetColor(e->color[0], e->color[1], e->color[2], e->color[3]);
} }
@@ -278,8 +277,7 @@ int Entity_IsVisible(Entity e, int x, int y, int w, int h) {
ymin = y - ih; ymin = y - ih;
ymax = y + h + ih; ymax = y + h + ih;
if (e->pos[0] < xmin || e->pos[0] > xmax || e->pos[1] < ymin || if (e->pos[0] < xmin || e->pos[0] > xmax || e->pos[1] < ymin || e->pos[1] > ymax) {
e->pos[1] > ymax) {
return (0); return (0);
} }
return (1); return (1);
@@ -336,9 +334,7 @@ void Entity_PostProcess(Entity e, int ft) {
vec2_set(e->vel, 0, 0); vec2_set(e->vel, 0, 0);
} else { } else {
// Apply dynamic friction // Apply dynamic friction
vec2_scale(e->vel, e->vel, vec2_scale(e->vel, e->vel, 1.0f - (e->backFric_dynamic + (e->backFric_static / len)));
1.0f -
(e->backFric_dynamic + (e->backFric_static / len)));
} }
// Mark the update of the position. // Mark the update of the position.
@@ -362,22 +358,21 @@ void Entity_PostProcess(Entity e, int ft) {
// //
// //
CollisionInfo _free_collInfo = NULL; CollisionInfo _free_collInfo = NULL;
CollisionInfo CollisionInfo_New(int responseType, Entity ent1, Entity ent2, CollisionInfo CollisionInfo_New(int responseType, Entity ent1, Entity ent2, float t, vec2 n, int applyFriction) {
float t, vec2 n, int applyFriction) {
CollisionInfo collInfo; CollisionInfo collInfo;
if (!_free_collInfo) { if (!_free_collInfo) {
collInfo = malloc(sizeof(TCollisionInfo)); collInfo = malloc(sizeof(TCollisionInfo));
} else { } else {
collInfo = _free_collInfo; collInfo = _free_collInfo;
_free_collInfo = collInfo->next; _free_collInfo = collInfo->next;
} }
collInfo->next = NULL; collInfo->next = NULL;
collInfo->responseType = responseType; collInfo->responseType = responseType;
collInfo->ent1 = ent1; collInfo->ent1 = ent1;
collInfo->ent2 = ent2; collInfo->ent2 = ent2;
collInfo->t = t; collInfo->t = t;
vec2_copy(collInfo->n, n); vec2_copy(collInfo->n, n);
collInfo->applyFriction = applyFriction; collInfo->applyFriction = applyFriction;
@@ -396,10 +391,10 @@ void CollisionInfo_Destroy(CollisionInfo *collInfoRef) {
CollisionInfo collInfo = collInfoRef[0]; CollisionInfo collInfo = collInfoRef[0];
CollisionInfo nextCollInfo; CollisionInfo nextCollInfo;
while (collInfo != NULL) { while (collInfo != NULL) {
nextCollInfo = collInfo->next; nextCollInfo = collInfo->next;
collInfo->next = _free_collInfo; collInfo->next = _free_collInfo;
_free_collInfo = collInfo; _free_collInfo = collInfo;
collInfo = nextCollInfo; collInfo = nextCollInfo;
} }
collInfoRef[0] = NULL; collInfoRef[0] = NULL;
} }
@@ -408,20 +403,18 @@ void CollisionInfo_Destroy(CollisionInfo *collInfoRef) {
// CollisionInfo_Add // CollisionInfo_Add
// //
// //
void CollisionInfo_Add(CollisionInfo *collInfoRef, int responseType, void CollisionInfo_Add(
Entity ent1, Entity ent2, float t, vec2 n, CollisionInfo *collInfoRef, int responseType, Entity ent1, Entity ent2, float t, vec2 n, int applyFriction) {
int applyFriction) {
if (collInfoRef == NULL) { if (collInfoRef == NULL) {
return; return;
} }
CollisionInfo prevCollInfo = NULL; CollisionInfo prevCollInfo = NULL;
CollisionInfo collInfo = collInfoRef[0]; CollisionInfo collInfo = collInfoRef[0];
CollisionInfo newCollInfo = CollisionInfo newCollInfo = CollisionInfo_New(responseType, ent1, ent2, t, n, applyFriction);
CollisionInfo_New(responseType, ent1, ent2, t, n, applyFriction);
while (collInfo != NULL && collInfo->t < t) { while (collInfo != NULL && collInfo->t < t) {
prevCollInfo = collInfo; prevCollInfo = collInfo;
collInfo = collInfo->next; collInfo = collInfo->next;
} }
if (prevCollInfo == NULL) { if (prevCollInfo == NULL) {
collInfoRef[0] = newCollInfo; collInfoRef[0] = newCollInfo;
@@ -435,11 +428,9 @@ void CollisionInfo_Add(CollisionInfo *collInfoRef, int responseType,
// CollisionInfo_CheckRepetition // CollisionInfo_CheckRepetition
// //
// //
int CollisionInfo_CheckRepetition(CollisionInfo collInfo, Entity ent1, int CollisionInfo_CheckRepetition(CollisionInfo collInfo, Entity ent1, Entity ent2) {
Entity ent2) {
while (collInfo != NULL) { while (collInfo != NULL) {
if ((collInfo->ent1 == ent1 && collInfo->ent2 == ent2) || if ((collInfo->ent1 == ent1 && collInfo->ent2 == ent2) || (collInfo->ent1 == ent2 && collInfo->ent2 == ent1)) {
(collInfo->ent1 == ent2 && collInfo->ent2 == ent1)) {
return (1); return (1);
} }
collInfo = collInfo->next; collInfo = collInfo->next;
@@ -451,8 +442,7 @@ int CollisionInfo_CheckRepetition(CollisionInfo collInfo, Entity ent1,
// Entity_CheckCollisions // Entity_CheckCollisions
// //
// //
int Entity_CheckCollision(Entity ent1, Entity ent2, int Entity_CheckCollision(Entity ent1, Entity ent2, CollisionInfo *collInfoRef) {
CollisionInfo *collInfoRef) {
float t; float t;
vec2 n; vec2 n;
vec2 vel; vec2 vel;
@@ -467,10 +457,10 @@ int Entity_CheckCollision(Entity ent1, Entity ent2,
// Decide who is the block and who is the ent // Decide who is the block and who is the ent
if (ent1->mass <= 0.0f && ent2->mass > 0.0f) { if (ent1->mass <= 0.0f && ent2->mass > 0.0f) {
ent = ent2; ent = ent2;
ent_block = ent1; ent_block = ent1;
} else if (ent2->mass <= 0.0f && ent1->mass > 0.0f) { } else if (ent2->mass <= 0.0f && ent1->mass > 0.0f) {
ent = ent1; ent = ent1;
ent_block = ent2; ent_block = ent2;
} else { } else {
// Two static or two dinamic entities?!? // Two static or two dinamic entities?!?
@@ -478,19 +468,17 @@ int Entity_CheckCollision(Entity ent1, Entity ent2,
} }
// Prepare some variables // Prepare some variables
t = 1.0f; t = 1.0f;
applyFriction = 1; applyFriction = 1;
if (flags & EntityFlag_BlockTop) { if (flags & EntityFlag_BlockTop) {
vec2_set(auxN, 0, -1); vec2_set(auxN, 0, -1);
vec2_scaleadd(p, ent_block->pos, auxN, vec2_scaleadd(p, ent_block->pos, auxN, (ent->height + ent_block->height) / 2);
(ent->height + ent_block->height) / 2);
block_len = ent_block->width + ent->width; block_len = ent_block->width + ent->width;
if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, &auxT)) {
&auxT)) {
if (auxT < t) { if (auxT < t) {
vec2_copy(n, auxN); vec2_copy(n, auxN);
t = auxT; t = auxT;
applyFriction = 1; applyFriction = 1;
} }
} }
@@ -498,14 +486,12 @@ int Entity_CheckCollision(Entity ent1, Entity ent2,
if (flags & EntityFlag_BlockBottom) { if (flags & EntityFlag_BlockBottom) {
vec2_set(auxN, 0, 1); vec2_set(auxN, 0, 1);
vec2_scaleadd(p, ent_block->pos, auxN, vec2_scaleadd(p, ent_block->pos, auxN, (ent->height + ent_block->height) / 2);
(ent->height + ent_block->height) / 2);
block_len = ent_block->width + ent->width; block_len = ent_block->width + ent->width;
if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, &auxT)) {
&auxT)) {
if (auxT < t) { if (auxT < t) {
vec2_copy(n, auxN); vec2_copy(n, auxN);
t = auxT; t = auxT;
applyFriction = 1; applyFriction = 1;
} }
} }
@@ -513,14 +499,12 @@ int Entity_CheckCollision(Entity ent1, Entity ent2,
if (flags & EntityFlag_BlockRight) { if (flags & EntityFlag_BlockRight) {
vec2_set(auxN, 1, 0); vec2_set(auxN, 1, 0);
vec2_scaleadd(p, ent_block->pos, auxN, vec2_scaleadd(p, ent_block->pos, auxN, (ent->width + ent_block->width) / 2);
(ent->width + ent_block->width) / 2);
block_len = ent_block->height + ent->height; block_len = ent_block->height + ent->height;
if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, &auxT)) {
&auxT)) {
if (auxT < t) { if (auxT < t) {
vec2_copy(n, auxN); vec2_copy(n, auxN);
t = auxT; t = auxT;
applyFriction = 0; applyFriction = 0;
} }
} }
@@ -528,22 +512,19 @@ int Entity_CheckCollision(Entity ent1, Entity ent2,
if (flags & EntityFlag_BlockLeft) { if (flags & EntityFlag_BlockLeft) {
vec2_set(auxN, -1, 0); vec2_set(auxN, -1, 0);
vec2_scaleadd(p, ent_block->pos, auxN, vec2_scaleadd(p, ent_block->pos, auxN, (ent->width + ent_block->width) / 2);
(ent->width + ent_block->width) / 2);
block_len = ent_block->height + ent->height; block_len = ent_block->height + ent->height;
if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, &auxT)) {
&auxT)) {
if (auxT < t) { if (auxT < t) {
vec2_copy(n, auxN); vec2_copy(n, auxN);
t = auxT; t = auxT;
applyFriction = 0; applyFriction = 0;
} }
} }
} }
if (t < 1.0f) { if (t < 1.0f) {
CollisionInfo_Add(collInfoRef, CollisionResponse_Line, ent, CollisionInfo_Add(collInfoRef, CollisionResponse_Line, ent, ent_block, t, n, applyFriction);
ent_block, t, n, applyFriction);
return (1); return (1);
} }
@@ -552,10 +533,8 @@ int Entity_CheckCollision(Entity ent1, Entity ent2,
// Circle-Circle test from ent1 // Circle-Circle test from ent1
vec2_minus(vel, ent1->vel, ent2->vel); vec2_minus(vel, ent1->vel, ent2->vel);
if (Colision_CircleCircle(ent1->pos, ent1->radius, vel, ent2->pos, if (Colision_CircleCircle(ent1->pos, ent1->radius, vel, ent2->pos, ent2->radius, &t, n)) {
ent2->radius, &t, n)) { CollisionInfo_Add(collInfoRef, CollisionResponse_Circle, ent1, ent2, t, n, 0);
CollisionInfo_Add(collInfoRef, CollisionResponse_Circle, ent1, ent2, t,
n, 0);
return (1); return (1);
} }
return (0); return (0);
@@ -572,13 +551,11 @@ void Entity_CollisionResponseCircle(Entity b1, Entity b2, float t, vec2 n) {
if (b1->mass > 0.0f && b2->mass > 0.0f) { if (b1->mass > 0.0f && b2->mass > 0.0f) {
// Calculate elasticity // Calculate elasticity
elast = (b1->mass * b1->elast + b2->mass * b2->elast) / elast = (b1->mass * b1->elast + b2->mass * b2->elast) / (b1->mass + b2->mass);
(b1->mass + b2->mass);
// Collision between two massed balls // Collision between two massed balls
moment = ((1.0f + elast) * b1->mass * b2->mass * moment = ((1.0f + elast) * b1->mass * b2->mass * (fabs(vec2_dot(b1->vel, n)) + fabs(vec2_dot(b2->vel, n)))) /
(fabs(vec2_dot(b1->vel, n)) + fabs(vec2_dot(b2->vel, n)))) / (b1->mass + b2->mass);
(b1->mass + b2->mass);
vec2_scale(temp, n, moment / b1->mass); vec2_scale(temp, n, moment / b1->mass);
vec2_minus(b1->vel, b1->vel, temp); vec2_minus(b1->vel, b1->vel, temp);
Entity_CalcBBox(b1); Entity_CalcBBox(b1);
@@ -612,8 +589,7 @@ void Entity_CollisionResponseCircle(Entity b1, Entity b2, float t, vec2 n) {
// Entity_CollisionResponseLine // Entity_CollisionResponseLine
// //
// Normal response to a collision with a line. // Normal response to a collision with a line.
void Entity_CollisionResponseLine(Entity ent, Entity ent2, float t, vec2 norm, void Entity_CollisionResponseLine(Entity ent, Entity ent2, float t, vec2 norm, int applyFriction) {
int applyFriction) {
vec2 pos2, vel2, velFric, intersection; vec2 pos2, vel2, velFric, intersection;
float dist, fric_static, fric_dynamic, fricLen; float dist, fric_static, fric_dynamic, fricLen;
@@ -628,7 +604,7 @@ void Entity_CollisionResponseLine(Entity ent, Entity ent2, float t, vec2 norm,
if (applyFriction) { if (applyFriction) {
// Calculate friction // Calculate friction
fric_static = (ent->fric_static + ent2->fric_static) / 2; fric_static = (ent->fric_static + ent2->fric_static) / 2;
fric_dynamic = (ent->fric_dynamic + ent2->fric_dynamic) / 2; fric_dynamic = (ent->fric_dynamic + ent2->fric_dynamic) / 2;
// Apply friction // Apply friction
@@ -640,8 +616,7 @@ void Entity_CollisionResponseLine(Entity ent, Entity ent2, float t, vec2 norm,
} else { } else {
// Apply dynamic friction // Apply dynamic friction
if (fricLen > 0.0f) { if (fricLen > 0.0f) {
vec2_scaleadd(pos2, intersection, velFric, vec2_scaleadd(pos2, intersection, velFric, 1.0f - (fric_dynamic + (fric_static / fricLen)));
1.0f - (fric_dynamic + (fric_static / fricLen)));
} else { } else {
vec2_scaleadd(pos2, intersection, velFric, 1.0f - fric_dynamic); vec2_scaleadd(pos2, intersection, velFric, 1.0f - fric_dynamic);
} }
@@ -671,16 +646,14 @@ int Entity_CollisionInfoResponse(CollisionInfo collInfo) {
// Check the collision methods // Check the collision methods
if (collInfo->ent1->collision) { if (collInfo->ent1->collision) {
rc = collInfo->ent1->collision(collInfo->ent1, collInfo->ent2, rc = collInfo->ent1->collision(collInfo->ent1, collInfo->ent2, collInfo->t, n1);
collInfo->t, n1);
if (rc == 0) if (rc == 0)
response = 0; response = 0;
if (rc > 1) if (rc > 1)
response = 2; response = 2;
} }
if (collInfo->ent2->collision) { if (collInfo->ent2->collision) {
rc = collInfo->ent2->collision(collInfo->ent2, collInfo->ent1, rc = collInfo->ent2->collision(collInfo->ent2, collInfo->ent1, collInfo->t, n2);
collInfo->t, n2);
if (rc == 0) if (rc == 0)
response = 0; response = 0;
if (rc > 1) if (rc > 1)
@@ -690,17 +663,14 @@ int Entity_CollisionInfoResponse(CollisionInfo collInfo) {
// Collision response // Collision response
if (response == 1) { if (response == 1) {
if (collInfo->responseType == CollisionResponse_Line) { if (collInfo->responseType == CollisionResponse_Line) {
Entity_CollisionResponseLine(collInfo->ent1, collInfo->ent2, Entity_CollisionResponseLine(
collInfo->t, collInfo->n, collInfo->ent1, collInfo->ent2, collInfo->t, collInfo->n, collInfo->applyFriction);
collInfo->applyFriction);
} else if (collInfo->responseType == CollisionResponse_Circle) { } else if (collInfo->responseType == CollisionResponse_Circle) {
if (vec2_dot(collInfo->ent1->vel, collInfo->ent1->vel) > if (vec2_dot(collInfo->ent1->vel, collInfo->ent1->vel) >
vec2_dot(collInfo->ent2->vel, collInfo->ent2->vel)) { vec2_dot(collInfo->ent2->vel, collInfo->ent2->vel)) {
Entity_CollisionResponseCircle( Entity_CollisionResponseCircle(collInfo->ent1, collInfo->ent2, collInfo->t, n2);
collInfo->ent1, collInfo->ent2, collInfo->t, n2);
} else { } else {
Entity_CollisionResponseCircle( Entity_CollisionResponseCircle(collInfo->ent2, collInfo->ent1, collInfo->t, n1);
collInfo->ent2, collInfo->ent1, collInfo->t, n1);
} }
} }
return (1); return (1);
@@ -873,10 +843,10 @@ void Entity_AddVelLimitV(Entity e, float v, float limit) {
// //
// //
void Entity_SetColor(Entity e, float r, float g, float b, float a) { void Entity_SetColor(Entity e, float r, float g, float b, float a) {
e->color[0] = r; e->color[0] = r;
e->color[1] = g; e->color[1] = g;
e->color[2] = b; e->color[2] = b;
e->color[3] = a; e->color[3] = a;
e->color0[0] = r; e->color0[0] = r;
e->color0[1] = g; e->color0[1] = g;
e->color0[2] = b; e->color0[2] = b;
@@ -970,8 +940,7 @@ void Entity_Iluminate(Entity e, Entity *elist, int n) {
float qrad; float qrad;
if (e->flags & EntityFlag_Light) { if (e->flags & EntityFlag_Light) {
Entity_SetColor(e, e->defaultColor[0], e->defaultColor[1], Entity_SetColor(e, e->defaultColor[0], e->defaultColor[1], e->defaultColor[2], e->defaultColor[3]);
e->defaultColor[2], e->defaultColor[3]);
return; return;
} }
@@ -987,16 +956,14 @@ void Entity_Iluminate(Entity e, Entity *elist, int n) {
vec2_minus(vdist, e->pos, elist[i]->pos); vec2_minus(vdist, e->pos, elist[i]->pos);
qdist = vec2_dot(vdist, vdist); qdist = vec2_dot(vdist, vdist);
qrad = elist[i]->light[3] * elist[i]->light[3]; qrad = elist[i]->light[3] * elist[i]->light[3];
if (qdist < qrad) { if (qdist < qrad) {
f = 1.0f - qdist / qrad; f = 1.0f - qdist / qrad;
Entity_AddColor(e, f * elist[i]->light[0], f * elist[i]->light[1], Entity_AddColor(e, f * elist[i]->light[0], f * elist[i]->light[1], f * elist[i]->light[2], 0.0f);
f * elist[i]->light[2], 0.0f);
} }
} }
Entity_MultColor(e, e->defaultColor[0], e->defaultColor[1], Entity_MultColor(e, e->defaultColor[0], e->defaultColor[1], e->defaultColor[2], e->defaultColor[3]);
e->defaultColor[2], e->defaultColor[3]);
e->internalFlags &= ~EntityIntFlag_UpdateLight; e->internalFlags &= ~EntityIntFlag_UpdateLight;
if (e->internalFlags & EntityIntFlag_UpdateColor) { if (e->internalFlags & EntityIntFlag_UpdateColor) {
@@ -1032,9 +999,8 @@ void Entity_MarkUpdateLight(Entity e, Entity *elist, int n) {
max[1] = e->pos0[1] + e->light[3]; max[1] = e->pos0[1] + e->light[3];
} }
for (i = 0; i < n; i++) { for (i = 0; i < n; i++) {
if (elist[i] != NULL && min[0] <= elist[i]->pos0[0] && if (elist[i] != NULL && min[0] <= elist[i]->pos0[0] && max[0] >= elist[i]->pos0[0] &&
max[0] >= elist[i]->pos0[0] && min[1] <= elist[i]->pos0[1] && min[1] <= elist[i]->pos0[1] && max[1] >= elist[i]->pos0[1]) {
max[1] >= elist[i]->pos0[1]) {
elist[i]->internalFlags |= EntityIntFlag_UpdateLight; elist[i]->internalFlags |= EntityIntFlag_UpdateLight;
} }
} }
@@ -1051,13 +1017,9 @@ int Entity_IsLight(Entity e) { return (e->flags & EntityFlag_Light); }
///////////////////////////// /////////////////////////////
// Entity_IsUpdateLight // Entity_IsUpdateLight
// //
int Entity_IsUpdateLight(Entity e) { int Entity_IsUpdateLight(Entity e) { return (e->internalFlags & EntityIntFlag_UpdateLight); }
return (e->internalFlags & EntityIntFlag_UpdateLight);
}
///////////////////////////// /////////////////////////////
// Entity_IsMoving // Entity_IsMoving
// //
int Entity_IsMoving(Entity e) { int Entity_IsMoving(Entity e) { return (e->internalFlags & EntityIntFlag_UpdatedPos); }
return (e->internalFlags & EntityIntFlag_UpdatedPos);
}

View File

@@ -153,8 +153,7 @@ struct TCollisionInfo {
// CollisionInfo_New // CollisionInfo_New
// //
// //
CollisionInfo CollisionInfo_New(int responseType, Entity ent1, Entity ent2, CollisionInfo CollisionInfo_New(int responseType, Entity ent1, Entity ent2, float t, vec2 n, int applyFriction);
float t, vec2 n, int applyFriction);
///////////////////////////// /////////////////////////////
// CollisionInfo_Destroy // CollisionInfo_Destroy
@@ -166,15 +165,14 @@ void CollisionInfo_Destroy(CollisionInfo *collInfoRef);
// CollisionInfo_Add // CollisionInfo_Add
// //
// //
void CollisionInfo_Add(CollisionInfo *collInfo, int responseType, Entity ent1, void CollisionInfo_Add(
Entity ent2, float t, vec2 n, int applyFriction); CollisionInfo *collInfo, int responseType, Entity ent1, Entity ent2, float t, vec2 n, int applyFriction);
///////////////////////////// /////////////////////////////
// CollisionInfo_CheckRepetition // CollisionInfo_CheckRepetition
// //
// //
int CollisionInfo_CheckRepetition(CollisionInfo collInfo, Entity ent1, int CollisionInfo_CheckRepetition(CollisionInfo collInfo, Entity ent1, Entity ent2);
Entity ent2);
///////////////////////////// /////////////////////////////
// Entity_CheckCollision // Entity_CheckCollision
@@ -192,8 +190,7 @@ void Entity_CollisionResponseCircle(Entity b1, Entity b2, float t, vec2 n);
// Entity_CollisionResponseLine // Entity_CollisionResponseLine
// //
// Normal response to a collision with a line. // Normal response to a collision with a line.
void Entity_CollisionResponseLine(Entity ent, Entity ent2, float t, vec2 n, void Entity_CollisionResponseLine(Entity ent, Entity ent2, float t, vec2 n, int applyFriction);
int applyFriction);
///////////////////////////// /////////////////////////////
// Entity_CollisionInfoResponse // Entity_CollisionInfoResponse

View File

@@ -18,16 +18,16 @@
#include "GameLib.h" #include "GameLib.h"
// Globals // Globals
Entity *_entity = NULL; Entity *_entity = NULL;
int *_entity_flag = NULL; int *_entity_flag = NULL;
int _n_entities = 0; int _n_entities = 0;
int _n_entities_res = 0; int _n_entities_res = 0;
int _entities_lock = 0; int _entities_lock = 0;
int _entities_compactate = 0; int _entities_compactate = 0;
void (*_gameproc)() = NULL; void (*_gameproc)() = NULL;
void (*_gamepostproc)() = NULL; void (*_gamepostproc)() = NULL;
void (*_gamepredraw)(float f) = NULL; void (*_gamepredraw)(float f) = NULL;
void (*_gamedraw)(float f) = NULL; void (*_gamedraw)(float f) = NULL;
int _pft; int _pft;
int _game_size[2]; int _game_size[2];
int _game_pos0[2]; int _game_pos0[2];
@@ -95,22 +95,22 @@ void GameLib_AddEntity(Entity e) {
_n_entities_res = 32; _n_entities_res = 32;
else else
_n_entities_res *= 2; _n_entities_res *= 2;
entity_aux = malloc(sizeof(Entity) * _n_entities_res); entity_aux = malloc(sizeof(Entity) * _n_entities_res);
entity_flag_aux = malloc(sizeof(int) * _n_entities_res); entity_flag_aux = malloc(sizeof(int) * _n_entities_res);
for (i = 0; i < _n_entities; i++) { for (i = 0; i < _n_entities; i++) {
entity_aux[i] = _entity[i]; entity_aux[i] = _entity[i];
entity_flag_aux[i] = _entity_flag[i]; entity_flag_aux[i] = _entity_flag[i];
} }
if (_entity) { if (_entity) {
free(_entity); free(_entity);
free(_entity_flag); free(_entity_flag);
} }
_entity = entity_aux; _entity = entity_aux;
_entity_flag = entity_flag_aux; _entity_flag = entity_flag_aux;
} }
// Add the entity // Add the entity
_entity[_n_entities] = e; _entity[_n_entities] = e;
_entity_flag[_n_entities] = 1; _entity_flag[_n_entities] = 1;
_n_entities++; _n_entities++;
@@ -134,7 +134,7 @@ int GameLib_UnrefEntity(Entity e) {
if (_entities_lock) { if (_entities_lock) {
_entity_flag[i] = -2; _entity_flag[i] = -2;
} else { } else {
_entity[i] = NULL; _entity[i] = NULL;
_entity_flag[i] = 0; _entity_flag[i] = 0;
} }
_entities_compactate = 1; _entities_compactate = 1;
@@ -158,7 +158,7 @@ int GameLib_DelEntity(Entity e) {
} }
if (_entities_lock) { if (_entities_lock) {
// Delete latter // Delete latter
_entity[i] = e; _entity[i] = e;
_entity_flag[i] = -1; _entity_flag[i] = -1;
} else { } else {
// Delete now // Delete now
@@ -184,12 +184,12 @@ void GameLib_Compactate() {
continue; continue;
} }
if (i > j) { if (i > j) {
_entity[j] = _entity[i]; _entity[j] = _entity[i];
_entity_flag[j] = _entity_flag[i]; _entity_flag[j] = _entity_flag[i];
} }
j++; j++;
} }
_n_entities = j; _n_entities = j;
_entities_compactate = 0; _entities_compactate = 0;
} }
@@ -207,7 +207,7 @@ void GameLib_ProcLoop(void *data) {
_game_pos0[1] = _game_pos1[1] + _game_posOffset[1]; _game_pos0[1] = _game_pos1[1] + _game_posOffset[1];
// Process // Process
time = Time_GetTime(); time = Time_GetTime();
_entities_lock = 1; _entities_lock = 1;
if (_gameproc) { if (_gameproc) {
_gameproc(); _gameproc();
@@ -222,25 +222,23 @@ void GameLib_ProcLoop(void *data) {
t_proc += Time_GetTime() - time; t_proc += Time_GetTime() - time;
// Colisions between entities // Colisions between entities
time = Time_GetTime(); time = Time_GetTime();
_entities_lock = 1; _entities_lock = 1;
count = 0; count = 0;
do { do {
repeat = 0; repeat = 0;
CollisionInfo collInfo = NULL; CollisionInfo collInfo = NULL;
for (i = 0; i < _n_entities; i++) { for (i = 0; i < _n_entities; i++) {
if (!(_entity[i]->flags & EntityFlag_Collision) || if (!(_entity[i]->flags & EntityFlag_Collision) || _entity[i]->mass < 0.0f)
_entity[i]->mass < 0.0f)
continue; continue;
if (_entity[i]->vel[0] <= 0.0f && _entity[i]->vel[0] >= -0.0f && if (_entity[i]->vel[0] <= 0.0f && _entity[i]->vel[0] >= -0.0f && _entity[i]->vel[1] <= 0.0f &&
_entity[i]->vel[1] <= 0.0f && _entity[i]->vel[1] >= -0.0f) { _entity[i]->vel[1] >= -0.0f) {
continue; continue;
} }
for (j = 0; j < _n_entities; j++) { for (j = 0; j < _n_entities; j++) {
if (i == j || !(_entity[j]->flags & EntityFlag_Collision) || if (i == j || !(_entity[j]->flags & EntityFlag_Collision) ||
CollisionInfo_CheckRepetition(collInfo, _entity[i], CollisionInfo_CheckRepetition(collInfo, _entity[i], _entity[j]) ||
_entity[j]) || !Entity_BBoxIntersect(_entity[i], _entity[j])) {
!Entity_BBoxIntersect(_entity[i], _entity[j])) {
continue; continue;
} }
Entity_CheckCollision(_entity[i], _entity[j], &collInfo); Entity_CheckCollision(_entity[i], _entity[j], &collInfo);
@@ -256,12 +254,11 @@ void GameLib_ProcLoop(void *data) {
// Stop remaining collisions // Stop remaining collisions
if (count == 10) { if (count == 10) {
for (i = 0; i < _n_entities; i++) { for (i = 0; i < _n_entities; i++) {
if (!(_entity[i]->flags & EntityFlag_Collision) || if (!(_entity[i]->flags & EntityFlag_Collision) || _entity[i]->mass < 0.0f)
_entity[i]->mass < 0.0f)
continue; continue;
for (j = 0; j < _n_entities; j++) { for (j = 0; j < _n_entities; j++) {
if (i == j || !(_entity[j]->flags & EntityFlag_Collision) || if (i == j || !(_entity[j]->flags & EntityFlag_Collision) ||
!Entity_BBoxIntersect(_entity[i], _entity[j])) { !Entity_BBoxIntersect(_entity[i], _entity[j])) {
continue; continue;
} }
if (Entity_CheckCollision(_entity[i], _entity[j], NULL)) { if (Entity_CheckCollision(_entity[i], _entity[j], NULL)) {
@@ -278,11 +275,10 @@ void GameLib_ProcLoop(void *data) {
t_col += Time_GetTime() - time; t_col += Time_GetTime() - time;
// Process Overlaps // Process Overlaps
time = Time_GetTime(); time = Time_GetTime();
_entities_lock = 1; _entities_lock = 1;
for (i = 0; i < _n_entities; i++) { for (i = 0; i < _n_entities; i++) {
if (!(_entity[i]->flags & EntityFlag_Overlap) || if (!(_entity[i]->flags & EntityFlag_Overlap) || _entity[i]->mass < 0.0f)
_entity[i]->mass < 0.0f)
continue; continue;
for (j = 0; j < _n_entities; j++) { for (j = 0; j < _n_entities; j++) {
if (!(_entity[j]->flags & EntityFlag_Overlap) || i == j) if (!(_entity[j]->flags & EntityFlag_Overlap) || i == j)
@@ -302,7 +298,7 @@ void GameLib_ProcLoop(void *data) {
for (i = 1; i < n; i++) { for (i = 1; i < n; i++) {
Entity ent1 = _entity[i - 1]; Entity ent1 = _entity[i - 1];
Entity ent2 = _entity[i]; Entity ent2 = _entity[i];
swap = 0; swap = 0;
if (ent1->zorder > ent2->zorder) { if (ent1->zorder > ent2->zorder) {
// Lower level // Lower level
swap = 1; swap = 1;
@@ -322,17 +318,17 @@ void GameLib_ProcLoop(void *data) {
} }
if (swap) { if (swap) {
Entity ent; Entity ent;
ent = _entity[i]; ent = _entity[i];
_entity[i] = _entity[i - 1]; _entity[i] = _entity[i - 1];
_entity[i - 1] = ent; _entity[i - 1] = ent;
n2 = i; n2 = i;
} }
} }
n = n2; n = n2;
} while (n > 0); } while (n > 0);
// PostProcess // PostProcess
time = Time_GetTime(); time = Time_GetTime();
_entities_lock = 1; _entities_lock = 1;
for (i = 0; i < _n_entities; i++) { for (i = 0; i < _n_entities; i++) {
Entity_PostProcess(_entity[i], _pft); Entity_PostProcess(_entity[i], _pft);
@@ -376,9 +372,12 @@ void GameLib_DrawLoop(void *data, float f) {
// Draw parallax backgrounds // Draw parallax backgrounds
for (i = 0; i < _nParallaxBackgrounds; i++) { for (i = 0; i < _nParallaxBackgrounds; i++) {
Draw_ImgParallax( Draw_ImgParallax(
_parallaxBackground[i].img, _parallaxBackground[i].imgSize, _parallaxBackground[i].img,
_parallaxBackground[i].imgSize,
_parallaxBackground[i].imgOffset, _parallaxBackground[i].imgOffset,
_parallaxBackground[i].parallaxFactor, game_pos, _game_size); _parallaxBackground[i].parallaxFactor,
game_pos,
_game_size);
} }
// Draw entities // Draw entities
@@ -387,8 +386,7 @@ void GameLib_DrawLoop(void *data, float f) {
Entity e = _entity[i]; Entity e = _entity[i];
// Check visivility // Check visivility
if (!Entity_IsVisible(e, game_pos[0], game_pos[1], _game_size[0], if (!Entity_IsVisible(e, game_pos[0], game_pos[1], _game_size[0], _game_size[1])) {
_game_size[1])) {
continue; continue;
} }
@@ -425,8 +423,7 @@ void GameLib_DrawLoop(void *data, float f) {
} }
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
if (Input_GetKey(InputKey_DumpProfiling) == InputKey_Pressed && if (Input_GetKey(InputKey_DumpProfiling) == InputKey_Pressed && fproc_count > 0 && fdraw_count > 0) {
fproc_count > 0 && fdraw_count > 0) {
Print("Profiling:::::::::\n"); Print("Profiling:::::::::\n");
Print("t_proc.....:%6lldus\n", t_proc / fproc_count); Print("t_proc.....:%6lldus\n", t_proc / fproc_count);
Print("t_col......:%6lldus\n", t_col / fproc_count); Print("t_col......:%6lldus\n", t_col / fproc_count);
@@ -434,11 +431,11 @@ void GameLib_DrawLoop(void *data, float f) {
Print("t_postproc.:%6lldus\n", t_postproc / fproc_count); Print("t_postproc.:%6lldus\n", t_postproc / fproc_count);
Print("t_draw.....:%6lldus\n", t_draw / fdraw_count); Print("t_draw.....:%6lldus\n", t_draw / fdraw_count);
Print("n_ents.....:%6lld\n", _n_entities); Print("n_ents.....:%6lld\n", _n_entities);
t_proc = 0; t_proc = 0;
t_col = 0; t_col = 0;
t_over = 0; t_over = 0;
t_postproc = 0; t_postproc = 0;
t_draw = 0; t_draw = 0;
fproc_count = 0; fproc_count = 0;
fdraw_count = 0; fdraw_count = 0;
} }
@@ -448,19 +445,18 @@ void GameLib_DrawLoop(void *data, float f) {
// GameLib_Loop // GameLib_Loop
// //
// Loops the game. // Loops the game.
void GameLib_Loop(void (*gameproc)(), void (*gamepostproc)(), void GameLib_Loop(void (*gameproc)(), void (*gamepostproc)(), void (*gamepredraw)(float f), void (*gamedraw)(float f)) {
void (*gamepredraw)(float f), void (*gamedraw)(float f)) { _gameproc = gameproc;
_gameproc = gameproc;
_gamepostproc = gamepostproc; _gamepostproc = gamepostproc;
_gamepredraw = gamepredraw; _gamepredraw = gamepredraw;
_gamedraw = gamedraw; _gamedraw = gamedraw;
t_proc = 0; t_proc = 0;
t_col = 0; t_col = 0;
t_over = 0; t_over = 0;
t_postproc = 0; t_postproc = 0;
t_draw = 0; t_draw = 0;
fproc_count = 0; fproc_count = 0;
fdraw_count = 0; fdraw_count = 0;
Draw_Loop(GameLib_ProcLoop, GameLib_DrawLoop, NULL); Draw_Loop(GameLib_ProcLoop, GameLib_DrawLoop, NULL);
} }
@@ -492,10 +488,8 @@ void GameLib_GetSize(int size[2]) {
size[1] = _game_size[1]; size[1] = _game_size[1];
} }
void GameLib_GetPosInstant(int pos[2], float f) { void GameLib_GetPosInstant(int pos[2], float f) {
pos[0] = _game_pos0[0] + pos[0] = _game_pos0[0] + f * ((_game_pos1[0] + _game_posOffset[0]) - _game_pos0[0]);
f * ((_game_pos1[0] + _game_posOffset[0]) - _game_pos0[0]); pos[1] = _game_pos0[1] + f * ((_game_pos1[1] + _game_posOffset[1]) - _game_pos0[1]);
pos[1] = _game_pos0[1] +
f * ((_game_pos1[1] + _game_posOffset[1]) - _game_pos0[1]);
} }
void GameLib_SetPosOffset(int posOffset[2]) { void GameLib_SetPosOffset(int posOffset[2]) {
_game_posOffset[0] = posOffset[0]; _game_posOffset[0] = posOffset[0];
@@ -513,12 +507,10 @@ void GameLib_MoveToPos(vec2 pos, float f) {
GameLib_MoveToPosV(pos, f); GameLib_MoveToPosV(pos, f);
} }
void GameLib_MoveToPosH(vec2 pos, float f) { void GameLib_MoveToPosH(vec2 pos, float f) {
_game_pos1[0] = _game_pos1[0] = _game_pos1[0] + (pos[0] - (_game_pos1[0] + (_game_size[0] / 2.0f))) * f;
_game_pos1[0] + (pos[0] - (_game_pos1[0] + (_game_size[0] / 2.0f))) * f;
} }
void GameLib_MoveToPosV(vec2 pos, float f) { void GameLib_MoveToPosV(vec2 pos, float f) {
_game_pos1[1] = _game_pos1[1] = _game_pos1[1] + (pos[1] - (_game_pos1[1] + (_game_size[1] / 2.0f))) * f;
_game_pos1[1] + (pos[1] - (_game_pos1[1] + (_game_size[1] / 2.0f))) * f;
} }
///////////////////////////// /////////////////////////////
@@ -574,7 +566,7 @@ Entity GameLib_SearchEnt(int (*func)(Entity ent, void *d), void *d) {
// //
// //
int GameLib_EntityCustomCheckCollision(Entity ent, vec2 vel) { int GameLib_EntityCustomCheckCollision(Entity ent, vec2 vel) {
int collision = 0; int collision = 0;
CollisionInfo collInfo = NULL; CollisionInfo collInfo = NULL;
vec2 originalVel; vec2 originalVel;
int j; int j;
@@ -584,8 +576,7 @@ int GameLib_EntityCustomCheckCollision(Entity ent, vec2 vel) {
Entity_CalcBBox(ent); Entity_CalcBBox(ent);
for (j = 0; j < _n_entities; j++) { for (j = 0; j < _n_entities; j++) {
if (!(_entity[j]->flags & EntityFlag_Collision) || if (!(_entity[j]->flags & EntityFlag_Collision) || !Entity_BBoxIntersect(ent, _entity[j])) {
!Entity_BBoxIntersect(ent, _entity[j])) {
continue; continue;
} }
Entity_CheckCollision(ent, _entity[j], &collInfo); Entity_CheckCollision(ent, _entity[j], &collInfo);
@@ -618,16 +609,16 @@ void GameLib_PlaySound(AudioSnd snd, int x, int y) {
} else { } else {
r = _game_size[1] / 2; r = _game_size[1] / 2;
} }
r = r * 1.2f; r = r * 1.2f;
off = r / 10.0f; off = r / 10.0f;
// Calculate volumes // Calculate volumes
dx = x - (cx + off); dx = x - (cx + off);
dy = y - (cy); dy = y - (cy);
vright = 1.0f - (sqrtf(dx * dx + dy * dy) / (float)r); vright = 1.0f - (sqrtf(dx * dx + dy * dy) / (float)r);
dx = x - (cx - off); dx = x - (cx - off);
dy = y - (cy); dy = y - (cy);
vleft = 1.0f - (sqrtf(dx * dx + dy * dy) / (float)r); vleft = 1.0f - (sqrtf(dx * dx + dy * dy) / (float)r);
// Clamp to 0 // Clamp to 0
if (vleft < 0.0f) if (vleft < 0.0f)
@@ -669,14 +660,11 @@ void GameLib_EntitySetLight(Entity e, float r, float g, float b, float rad) {
// GameLib_ConvertScreenPositionToGamePosition // GameLib_ConvertScreenPositionToGamePosition
// //
// //
void GameLib_ConvertScreenPositionToGamePosition(vec2 screenPos, vec2 gamePos, void GameLib_ConvertScreenPositionToGamePosition(vec2 screenPos, vec2 gamePos, float f) {
float f) {
int game_pos[2]; int game_pos[2];
game_pos[0] = _game_pos0[0] + game_pos[0] = _game_pos0[0] + f * ((_game_pos1[0] + _game_posOffset[0]) - _game_pos0[0]);
f * ((_game_pos1[0] + _game_posOffset[0]) - _game_pos0[0]); game_pos[1] = _game_pos0[1] + f * ((_game_pos1[1] + _game_posOffset[1]) - _game_pos0[1]);
game_pos[1] = _game_pos0[1] +
f * ((_game_pos1[1] + _game_posOffset[1]) - _game_pos0[1]);
gamePos[0] = (screenPos[0] * _game_size[0]) + game_pos[0]; gamePos[0] = (screenPos[0] * _game_size[0]) + game_pos[0];
gamePos[1] = (screenPos[1] * _game_size[1]) + game_pos[1]; gamePos[1] = (screenPos[1] * _game_size[1]) + game_pos[1];
@@ -686,18 +674,17 @@ void GameLib_ConvertScreenPositionToGamePosition(vec2 screenPos, vec2 gamePos,
// GameLib_AddParallaxBackground // GameLib_AddParallaxBackground
// //
// //
void GameLib_AddParallaxBackground(DrawImg img, int imgSize[2], void GameLib_AddParallaxBackground(DrawImg img, int imgSize[2], int imgOffset[2], float parallaxFactor[2]) {
int imgOffset[2], float parallaxFactor[2]) {
int idx = _nParallaxBackgrounds; int idx = _nParallaxBackgrounds;
if ((idx + 1) >= MaxParallaxBackgrounds) { if ((idx + 1) >= MaxParallaxBackgrounds) {
Print("GameLib: Can't add parallaxBackground, limit reached."); Print("GameLib: Can't add parallaxBackground, limit reached.");
return; return;
} }
_parallaxBackground[idx].img = img; _parallaxBackground[idx].img = img;
_parallaxBackground[idx].imgSize[0] = imgSize[0]; _parallaxBackground[idx].imgSize[0] = imgSize[0];
_parallaxBackground[idx].imgSize[1] = imgSize[1]; _parallaxBackground[idx].imgSize[1] = imgSize[1];
_parallaxBackground[idx].imgOffset[0] = imgOffset[0]; _parallaxBackground[idx].imgOffset[0] = imgOffset[0];
_parallaxBackground[idx].imgOffset[1] = imgOffset[1]; _parallaxBackground[idx].imgOffset[1] = imgOffset[1];
_parallaxBackground[idx].parallaxFactor[0] = parallaxFactor[0]; _parallaxBackground[idx].parallaxFactor[0] = parallaxFactor[0];
_parallaxBackground[idx].parallaxFactor[1] = parallaxFactor[1]; _parallaxBackground[idx].parallaxFactor[1] = parallaxFactor[1];
_nParallaxBackgrounds++; _nParallaxBackgrounds++;

View File

@@ -39,8 +39,7 @@ int GameLib_DelEntity(Entity e);
// GameLib_Loop // GameLib_Loop
// //
// Loops the game. // Loops the game.
void GameLib_Loop(void (*gameproc)(), void (*gamepostproc)(), void GameLib_Loop(void (*gameproc)(), void (*gamepostproc)(), void (*gamepredraw)(float f), void (*gamedraw)(float f));
void (*gamepredraw)(float f), void (*gamedraw)(float f));
///////////////////////////// /////////////////////////////
// GameLib_GetPos // GameLib_GetPos
@@ -114,15 +113,13 @@ void GameLib_EntitySetLight(Entity e, float r, float g, float b, float rad);
// GameLib_ConvertScreenPositionToGamePosition // GameLib_ConvertScreenPositionToGamePosition
// //
// //
void GameLib_ConvertScreenPositionToGamePosition(vec2 screenPos, vec2 gamePos, void GameLib_ConvertScreenPositionToGamePosition(vec2 screenPos, vec2 gamePos, float f);
float f);
///////////////////////////// /////////////////////////////
// GameLib_AddParallaxBackground // GameLib_AddParallaxBackground
// //
// //
void GameLib_AddParallaxBackground(DrawImg img, int imgSize[2], void GameLib_AddParallaxBackground(DrawImg img, int imgSize[2], int imgOffset[2], float parallaxFactor[2]);
int imgOffset[2], float parallaxFactor[2]);
///////////////////////////// /////////////////////////////
// GameLib_CleanParallaxBackgrounds // GameLib_CleanParallaxBackgrounds

View File

@@ -13,10 +13,10 @@
InputKeyStatus _keys[InputKey_Max]; InputKeyStatus _keys[InputKey_Max];
int _pointerDown = 0; int _pointerDown = 0;
float _pointerX = 0; float _pointerX = 0;
float _pointerY = 0; float _pointerY = 0;
int _clicked = 0; int _clicked = 0;
float _clickedPositionX = 0; float _clickedPositionX = 0;
float _clickedPositionY = 0; float _clickedPositionY = 0;
@@ -53,8 +53,9 @@ void Input_Frame() {
Input_SetKey(InputKey_Left, keys[SDL_SCANCODE_LEFT] | keys[SDL_SCANCODE_A]); Input_SetKey(InputKey_Left, keys[SDL_SCANCODE_LEFT] | keys[SDL_SCANCODE_A]);
Input_SetKey(InputKey_Right, keys[SDL_SCANCODE_RIGHT] | keys[SDL_SCANCODE_D]); Input_SetKey(InputKey_Right, keys[SDL_SCANCODE_RIGHT] | keys[SDL_SCANCODE_D]);
Input_SetKey(InputKey_Jump, keys[SDL_SCANCODE_SPACE]); Input_SetKey(InputKey_Jump, keys[SDL_SCANCODE_SPACE]);
Input_SetKey(InputKey_Continue, Input_SetKey(
keys[SDL_SCANCODE_RETURN] | keys[SDL_SCANCODE_RETURN2] | keys[SDL_SCANCODE_KP_ENTER] | _pointerDown); InputKey_Continue,
keys[SDL_SCANCODE_RETURN] | keys[SDL_SCANCODE_RETURN2] | keys[SDL_SCANCODE_KP_ENTER] | _pointerDown);
Input_SetKey(InputKey_DumpProfiling, keys[SDL_SCANCODE_M]); Input_SetKey(InputKey_DumpProfiling, keys[SDL_SCANCODE_M]);
Input_SetKey(InputKey_Screenshot, keys[SDL_SCANCODE_F12]); Input_SetKey(InputKey_Screenshot, keys[SDL_SCANCODE_F12]);
@@ -104,7 +105,7 @@ void Input_SetPointerPosition(float x, float y) {
// //
void Input_SetPointerDown(int pointerDown) { void Input_SetPointerDown(int pointerDown) {
if (pointerDown == 0 && _pointerDown == 1) { if (pointerDown == 0 && _pointerDown == 1) {
_clicked = 1; _clicked = 1;
_clickedPositionX = _pointerX; _clickedPositionX = _pointerX;
_clickedPositionY = _pointerY; _clickedPositionY = _pointerY;
} }

View File

@@ -54,11 +54,7 @@ void Input_SetKey(InputKey key, int status);
// InputKeyStatus // // InputKeyStatus //
/////////////////// ///////////////////
// Key status enumeration. // Key status enumeration.
typedef enum { typedef enum { InputKey_Released, InputKey_Pressed, InputKey_Holded } InputKeyStatus;
InputKey_Released,
InputKey_Pressed,
InputKey_Holded
} InputKeyStatus;
///////////////////////////// /////////////////////////////
// Input_GetKey // Input_GetKey

View File

@@ -12,8 +12,8 @@ QuadArray2D QuadArray2D_Create(int resVertex) {
quadArray = malloc(sizeof(TQuadArray2D)); quadArray = malloc(sizeof(TQuadArray2D));
quadArray->vertexData = malloc(sizeof(float) * Vertex2D_Length * resVertex); quadArray->vertexData = malloc(sizeof(float) * Vertex2D_Length * resVertex);
quadArray->nVertex = 0; quadArray->nVertex = 0;
quadArray->resVertex = resVertex; quadArray->resVertex = resVertex;
return quadArray; return quadArray;
} }
@@ -35,23 +35,20 @@ void QuadArray2D_AddVertex(QuadArray2D quadArray, float v[]) {
if (quadArray->resVertex <= quadArray->nVertex) { if (quadArray->resVertex <= quadArray->nVertex) {
// Grow vertexData // Grow vertexData
quadArray->resVertex *= 2; quadArray->resVertex *= 2;
float *newVertexData = float *newVertexData = malloc(sizeof(float) * Vertex2D_Length * quadArray->resVertex);
malloc(sizeof(float) * Vertex2D_Length * quadArray->resVertex); memcpy(newVertexData, quadArray->vertexData, sizeof(float) * Vertex2D_Length * quadArray->nVertex);
memcpy(newVertexData, quadArray->vertexData,
sizeof(float) * Vertex2D_Length * quadArray->nVertex);
free(quadArray->vertexData); free(quadArray->vertexData);
quadArray->vertexData = newVertexData; quadArray->vertexData = newVertexData;
} }
// Add the vertex // Add the vertex
memcpy(quadArray->vertexData + (Vertex2D_Length * quadArray->nVertex), v, memcpy(quadArray->vertexData + (Vertex2D_Length * quadArray->nVertex), v, sizeof(float) * Vertex2D_Length);
sizeof(float) * Vertex2D_Length);
quadArray->nVertex++; quadArray->nVertex++;
} }
void QuadArray2D_AddQuad(QuadArray2D quadArray, float x0, float y0, float u0, void QuadArray2D_AddQuad(
float v0, float x1, float y1, float u1, float v1, QuadArray2D quadArray, float x0, float y0, float u0, float v0, float x1, float y1, float u1, float v1,
float color[]) { float color[]) {
float v[Vertex2D_Length]; float v[Vertex2D_Length];
// Set the color // Set the color

View File

@@ -24,8 +24,8 @@ void QuadArray2D_Clean(QuadArray2D quadArray);
void QuadArray2D_AddVertex(QuadArray2D quadArray, float v[]); void QuadArray2D_AddVertex(QuadArray2D quadArray, float v[]);
void QuadArray2D_AddQuad(QuadArray2D quadArray, float x0, float y0, float u0, void QuadArray2D_AddQuad(
float v0, float x1, float y1, float u1, float v1, QuadArray2D quadArray, float x0, float y0, float u0, float v0, float x1, float y1, float u1, float v1,
float color[]); float color[]);
#endif #endif

View File

@@ -32,7 +32,7 @@ long long Time_GetTime() {
void Time_Pause(int pausa) { void Time_Pause(int pausa) {
long long tend, t, diff; long long tend, t, diff;
t = Time_GetTime(); t = Time_GetTime();
tend = t + pausa; tend = t + pausa;
do { do {
diff = tend - t; diff = tend - t;
@@ -55,7 +55,7 @@ long long Time_GetTime() {
} }
void Time_Pause(int pausa) { void Time_Pause(int pausa) {
struct timeval tv; struct timeval tv;
tv.tv_sec = (long long)pausa / 1000000; tv.tv_sec = (long long)pausa / 1000000;
tv.tv_usec = (long long)pausa % 1000000; tv.tv_usec = (long long)pausa % 1000000;
select(0, NULL, NULL, NULL, &tv); select(0, NULL, NULL, NULL, &tv);
} }

View File

@@ -38,9 +38,7 @@ void Rect_UnionRect(Rect r0, Rect r1, Rect rd) {
rd->y1 = MaximumInt(r0->y1, r1->y1); rd->y1 = MaximumInt(r0->y1, r1->y1);
} }
int Rect_PointInside(Rect r, int x, int y) { int Rect_PointInside(Rect r, int x, int y) { return (x >= r->x0 && x < r->x1 && y >= r->y0 && y < r->y1); }
return (x >= r->x0 && x < r->x1 && y >= r->y0 && y < r->y1);
}
int Rect_PointInsideAny(TRect r[], int rCount, int x, int y) { int Rect_PointInsideAny(TRect r[], int rCount, int x, int y) {
int insideAny = 0; int insideAny = 0;
@@ -62,7 +60,7 @@ int SolveQuadratic(float a, float b, float c, float *Rmin, float *Rmax) {
float root; float root;
float divisor; float divisor;
float b2; float b2;
b2 = b * b; b2 = b * b;
root = b2 - 4.0 * a * c; root = b2 - 4.0 * a * c;
if (root < 0) { if (root < 0) {
// Complex // Complex
@@ -73,7 +71,7 @@ int SolveQuadratic(float a, float b, float c, float *Rmin, float *Rmax) {
// +inf -inf // +inf -inf
return (0); return (0);
} }
root = sqrtf(root); root = sqrtf(root);
Rmin[0] = (float)((-b - root) / divisor); Rmin[0] = (float)((-b - root) / divisor);
Rmax[0] = (float)((-b + root) / divisor); Rmax[0] = (float)((-b + root) / divisor);
return (1); return (1);
@@ -183,8 +181,7 @@ int Intersec_RayUnitCircle(vec2 orig, vec2 vel, vec2 center, float *t) {
// Colision_CircleCircle // Colision_CircleCircle
// //
// Colision point of a circle against another circle. // Colision point of a circle against another circle.
int Colision_CircleCircle(vec2 cir1, float rad1, vec2 vel, vec2 cir2, int Colision_CircleCircle(vec2 cir1, float rad1, vec2 vel, vec2 cir2, float rad2, float *t, vec2 n) {
float rad2, float *t, vec2 n) {
vec2 vel_a, orig_a, cen_a, temp; vec2 vel_a, orig_a, cen_a, temp;
float rads, invrads; float rads, invrads;
float maxx, minx; float maxx, minx;
@@ -230,8 +227,7 @@ int Colision_CircleCircle(vec2 cir1, float rad1, vec2 vel, vec2 cir2,
// Intersect_RayEdge // Intersect_RayEdge
// //
// Intersection between a ray and a edge. // Intersection between a ray and a edge.
int Intersect_RayEdge(vec2 pos, vec2 vel, vec2 norm, vec2 edgePos, float len, int Intersect_RayEdge(vec2 pos, vec2 vel, vec2 norm, vec2 edgePos, float len, float *t) {
float *t) {
vec2 pos2, intersection, perp, edgePos2; vec2 pos2, intersection, perp, edgePos2;
float delta, d1, d2, hLen; float delta, d1, d2, hLen;
@@ -240,8 +236,8 @@ int Intersect_RayEdge(vec2 pos, vec2 vel, vec2 norm, vec2 edgePos, float len,
// Check intersection against the line // Check intersection against the line
delta = vec2_dot(norm, edgePos); delta = vec2_dot(norm, edgePos);
d1 = vec2_dot(pos, norm) - delta; d1 = vec2_dot(pos, norm) - delta;
d2 = vec2_dot(pos2, norm) - delta; d2 = vec2_dot(pos2, norm) - delta;
if (d1 >= -0.0001f && d2 <= 0.0001f) { if (d1 >= -0.0001f && d2 <= 0.0001f) {
// Intersection with line, Calculate intersection point // Intersection with line, Calculate intersection point
*t = d1 / (d1 - d2); *t = d1 / (d1 - d2);
@@ -253,11 +249,11 @@ int Intersect_RayEdge(vec2 pos, vec2 vel, vec2 norm, vec2 edgePos, float len,
// Check sides // Check sides
vec2_scaleadd(edgePos2, edgePos, perp, -hLen); vec2_scaleadd(edgePos2, edgePos, perp, -hLen);
delta = -vec2_dot(perp, edgePos2); delta = -vec2_dot(perp, edgePos2);
d1 = (-vec2_dot(perp, intersection)) - delta; d1 = (-vec2_dot(perp, intersection)) - delta;
vec2_scaleadd(edgePos2, edgePos, perp, hLen); vec2_scaleadd(edgePos2, edgePos, perp, hLen);
delta = vec2_dot(perp, edgePos2); delta = vec2_dot(perp, edgePos2);
d2 = vec2_dot(perp, intersection) - delta; d2 = vec2_dot(perp, intersection) - delta;
if (d1 <= 0.0f && d2 <= 0.0f) { if (d1 <= 0.0f && d2 <= 0.0f) {
// Intersection inside Edge. // Intersection inside Edge.
@@ -305,7 +301,7 @@ int IsBigEndian() {
int EndsWith(char *str, char *suffix) { int EndsWith(char *str, char *suffix) {
if (!str || !suffix) if (!str || !suffix)
return 0; return 0;
int lenStr = strlen(str); int lenStr = strlen(str);
int lenSuffix = strlen(suffix); int lenSuffix = strlen(suffix);
if (lenSuffix > lenStr) if (lenSuffix > lenStr)
return 0; return 0;
@@ -322,9 +318,9 @@ int EndsWith(char *str, char *suffix) {
#define __seed_b 5 #define __seed_b 5
#define __seed_c 10 #define __seed_c 10
#define __seed_d 15 #define __seed_d 15
//#define __LGC_a 1664525ul // #define __LGC_a 1664525ul
//#define __LGC_c 1013904223ul // #define __LGC_c 1013904223ul
//#define __LGC_m 4294967296ul // #define __LGC_m 4294967296ul
#define __LGC_a 16807ul #define __LGC_a 16807ul
#define __LGC_c 2 #define __LGC_c 2
#define __LGC_m 2147483647ul #define __LGC_m 2147483647ul
@@ -344,7 +340,7 @@ void Rand_Seed(unsigned seed) {
__seed_i = 29; __seed_i = 29;
// Cambio de semilla // Cambio de semilla
__rand_count = 0; __rand_count = 0;
__rand_orig_seed = seed; __rand_orig_seed = seed;
} }
unsigned Rand_Get() { unsigned Rand_Get() {

View File

@@ -45,32 +45,32 @@ int SolveQuadratic(float a, float b, float c, float *Rmin, float *Rmax);
////////// //////////
// A 2D vector. // A 2D vector.
typedef float vec2[2]; typedef float vec2[2];
#define vec2_set(v, x, y) \ #define vec2_set(v, x, y) \
(v)[0] = (x); \ (v)[0] = (x); \
(v)[1] = (y); (v)[1] = (y);
#define vec2_copy(v1, v2) \ #define vec2_copy(v1, v2) \
(v1)[0] = (v2)[0]; \ (v1)[0] = (v2)[0]; \
(v1)[1] = (v2)[1]; (v1)[1] = (v2)[1];
#define vec2_plus(v, v1, v2) \ #define vec2_plus(v, v1, v2) \
(v)[0] = (v1)[0] + (v2)[0]; \ (v)[0] = (v1)[0] + (v2)[0]; \
(v)[1] = (v1)[1] + (v2)[1]; (v)[1] = (v1)[1] + (v2)[1];
#define vec2_minus(v, v1, v2) \ #define vec2_minus(v, v1, v2) \
(v)[0] = (v1)[0] - (v2)[0]; \ (v)[0] = (v1)[0] - (v2)[0]; \
(v)[1] = (v1)[1] - (v2)[1]; (v)[1] = (v1)[1] - (v2)[1];
#define vec2_scale(v, v1, s) \ #define vec2_scale(v, v1, s) \
(v)[0] = (v1)[0] * (s); \ (v)[0] = (v1)[0] * (s); \
(v)[1] = (v1)[1] * (s); (v)[1] = (v1)[1] * (s);
#define vec2_dot(v1, v2) ((v1)[0] * (v2)[0] + (v1)[1] * (v2)[1]) #define vec2_dot(v1, v2) ((v1)[0] * (v2)[0] + (v1)[1] * (v2)[1])
#define vec2_len(v) sqrtf((v)[0] * (v)[0] + (v)[1] * (v)[1]) #define vec2_len(v) sqrtf((v)[0] * (v)[0] + (v)[1] * (v)[1])
#define vec2_perp(v, n) \ #define vec2_perp(v, n) \
(v)[0] = -(n)[1]; \ (v)[0] = -(n)[1]; \
(v)[1] = (n)[0]; (v)[1] = (n)[0];
#define vec2_scaleadd(v, v1, v2, s) \ #define vec2_scaleadd(v, v1, v2, s) \
(v)[0] = (v2)[0] * (s) + (v1)[0]; \ (v)[0] = (v2)[0] * (s) + (v1)[0]; \
(v)[1] = (v2)[1] * (s) + (v1)[1]; (v)[1] = (v2)[1] * (s) + (v1)[1];
float vec2_norm(vec2 v); float vec2_norm(vec2 v);
#define vec2_interpol(v, v1, v2, f) \ #define vec2_interpol(v, v1, v2, f) \
(v)[0] = (v1)[0] - f * ((v1)[0] - (v2)[0]); \ (v)[0] = (v1)[0] - f * ((v1)[0] - (v2)[0]); \
(v)[1] = (v1)[1] - f * ((v1)[1] - (v2)[1]); (v)[1] = (v1)[1] - f * ((v1)[1] - (v2)[1]);
void vec2_orthogonalize4(vec2 v); void vec2_orthogonalize4(vec2 v);
void vec2_orthogonalize8(vec2 v); void vec2_orthogonalize8(vec2 v);
@@ -85,15 +85,13 @@ int Intersec_RayUnitCircle(vec2 orig, vec2 vel, vec2 center, float *t);
// Intersect_CircleCircle // Intersect_CircleCircle
// //
// Colision point of a circle against another circle. // Colision point of a circle against another circle.
int Colision_CircleCircle(vec2 cir1, float ra, vec2 vel, vec2 cb, float rb, int Colision_CircleCircle(vec2 cir1, float ra, vec2 vel, vec2 cb, float rb, float *t, vec2 n);
float *t, vec2 n);
///////////////////////////// /////////////////////////////
// Intersect_RayEdge // Intersect_RayEdge
// //
// Intersection between a ray and a edge. // Intersection between a ray and a edge.
int Intersect_RayEdge(vec2 pos, vec2 vel, vec2 norm, vec2 edgePos, float len, int Intersect_RayEdge(vec2 pos, vec2 vel, vec2 norm, vec2 edgePos, float len, float *t);
float *t);
///////////////////////////// /////////////////////////////
// absmod // absmod

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff