diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..9bc28aa --- /dev/null +++ b/.clang-format @@ -0,0 +1,65 @@ +--- +Language: Cpp +# BasedOnStyle: LLVM +AccessModifierOffset: -2 +AlignAfterOpenBracket: true +AlignEscapedNewlinesLeft: false +AlignOperands: true +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AllowShortFunctionsOnASingleLine: All +AlwaysBreakAfterDefinitionReturnType: false +AlwaysBreakTemplateDeclarations: false +AlwaysBreakBeforeMultilineStrings: false +BreakBeforeBinaryOperators: None +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BinPackParameters: true +BinPackArguments: true +ColumnLimit: 80 +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 4 +DerivePointerAlignment: false +ExperimentalAutoDetectBinPacking: false +IndentCaseLabels: false +IndentWrappedFunctionNames: false +IndentFunctionDeclarationAfterType: false +MaxEmptyLinesToKeep: 1 +KeepEmptyLinesAtTheStartOfBlocks: true +NamespaceIndentation: None +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakString: 1000 +PenaltyBreakFirstLessLess: 120 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Right +SpacesBeforeTrailingComments: 1 +Cpp11BracedListStyle: true +Standard: Cpp11 +IndentWidth: 4 +TabWidth: 4 +UseTab: true +BreakBeforeBraces: Attach +SpacesInParentheses: false +SpacesInSquareBrackets: false +SpacesInAngles: false +SpaceInEmptyParentheses: false +SpacesInCStyleCastParentheses: false +SpaceAfterCStyleCast: false +SpacesInContainerLiterals: true +SpaceBeforeAssignmentOperators: true +ContinuationIndentWidth: 4 +CommentPragmas: '^ IWYU pragma:' +ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] +SpaceBeforeParens: ControlStatements +DisableFormat: false +... + diff --git a/Game/GameEnts.c b/Game/GameEnts.c index bfbfae9..249325e 100644 --- a/Game/GameEnts.c +++ b/Game/GameEnts.c @@ -17,139 +17,116 @@ Entity ent_Player; Entity ent_Platform; Entity ent_Block; - - - -int EntityApplyGravity(Entity e){ - float grav=10.0f; - float vTerminal=50.0f; +int EntityApplyGravity(Entity e) { + float grav = 10.0f; + float vTerminal = 50.0f; vec2 vGrav; // Only apply gravity to some entity types - if(!( - e->type==Ent_Player || - 0 - )) - { - return(1); + if (!(e->type == Ent_Player || 0)) { + return (1); } // Apply gravity - vec2_set(vGrav,0.0f,grav); - Entity_AddVelLimit(e,vGrav,vTerminal); + vec2_set(vGrav, 0.0f, grav); + Entity_AddVelLimit(e, vGrav, vTerminal); - - return(1); + return (1); } +void player_proc(Entity e, int ft) { + float acel = 8.0f; + float maxVel = 30.0f; + float jumpVel = 50.0f; + float shootVel = 50.0f; - - -void player_proc(Entity e,int ft){ - float acel=8.0f; - float maxVel=30.0f; - float jumpVel=50.0f; - float shootVel=50.0f; - - if(Input_GetKey(InputKey_Jump)==InputKey_Pressed || - Input_GetKey(InputKey_Up)==InputKey_Pressed) - { + if (Input_GetKey(InputKey_Jump) == InputKey_Pressed || + Input_GetKey(InputKey_Up) == InputKey_Pressed) { vec2 jump; // Apply jump - if(e->vel[1]>(-jumpVel)){ - e->vel[1]=-jumpVel; + if (e->vel[1] > (-jumpVel)) { + e->vel[1] = -jumpVel; } Entity_CalcBBox(e); // FIXME: play sound } - if(Input_GetKey(InputKey_Left)){ + if (Input_GetKey(InputKey_Left)) { vec2 left; // Apply left movement - vec2_set(left,-acel,0.0f); - Entity_AddVelLimit(e,left,maxVel); + vec2_set(left, -acel, 0.0f); + Entity_AddVelLimit(e, left, maxVel); - e->A=0; + e->A = 0; } - if(Input_GetKey(InputKey_Right)){ + if (Input_GetKey(InputKey_Right)) { vec2 right; // Apply right movement - vec2_set(right,acel,0.0f) - Entity_AddVelLimit(e,right,maxVel); + vec2_set(right, acel, 0.0f) Entity_AddVelLimit(e, right, maxVel); - e->A=1; + e->A = 1; } - if(Input_GetKey(InputKey_Action1)==InputKey_Pressed || - Input_GetKey(InputKey_Action2)==InputKey_Pressed) - { - + if (Input_GetKey(InputKey_Action1) == InputKey_Pressed || + Input_GetKey(InputKey_Action2) == InputKey_Pressed) { } - // Scroll View - GameLib_MoveToPos(e->pos,0.6f); + GameLib_MoveToPos(e->pos, 0.6f); } - - - -void GameEnts_Init(){ - +void GameEnts_Init() { ///////////////////////////// // Load and initialize media. // - img_player=Draw_LoadImage("data/player.png"); - img_platform=Draw_LoadImage("data/platform.png"); - img_block=Draw_LoadImage("data/block.png"); - + img_player = Draw_LoadImage("data/player.png"); + img_platform = Draw_LoadImage("data/platform.png"); + img_block = Draw_LoadImage("data/block.png"); ///////////////////////// // Initialize entity types. // - ent_Player=Entity_New(); - ent_Player->type=Ent_Player; - //ent_Player->flags=EntityFlag_Light; - //Entity_SetLight(ent_Player,.2,.2,.2,200); - ent_Player->flags=EntityFlag_Collision|EntityFlag_Overlap; - ent_Player->zorder=0; - AnimPlay_SetImg(&ent_Player->anim,img_player); - ent_Player->proc=player_proc; - ent_Player->mass=1.0f; - ent_Player->radius=12; - ent_Player->width=24; - ent_Player->height=24; - ent_Player->fric_static=0.0f; - ent_Player->fric_dynamic=0.2f; + ent_Player = Entity_New(); + ent_Player->type = Ent_Player; + // ent_Player->flags=EntityFlag_Light; + // Entity_SetLight(ent_Player,.2,.2,.2,200); + ent_Player->flags = EntityFlag_Collision | EntityFlag_Overlap; + ent_Player->zorder = 0; + AnimPlay_SetImg(&ent_Player->anim, img_player); + ent_Player->proc = player_proc; + ent_Player->mass = 1.0f; + ent_Player->radius = 12; + ent_Player->width = 24; + ent_Player->height = 24; + ent_Player->fric_static = 0.0f; + ent_Player->fric_dynamic = 0.2f; - ent_Platform=Entity_New(); - ent_Platform->type=Ent_Platform; - ent_Platform->flags=EntityFlag_PlatformCollision; - ent_Platform->zorder=-1; - AnimPlay_SetImg(&ent_Platform->anim,img_platform); - ent_Platform->mass=0.0f; - ent_Platform->radius=12; - ent_Platform->width=64; - ent_Platform->height=16; - ent_Platform->fric_static=0.0f; - ent_Platform->fric_dynamic=0.2f; - - ent_Block=Entity_New(); - ent_Block->type=Ent_Block; - ent_Block->flags=EntityFlag_BlockCollision; - ent_Block->zorder=-1; - AnimPlay_SetImg(&ent_Block->anim,img_block); - ent_Block->mass=0.0f; - ent_Block->radius=32; - ent_Block->width=64; - ent_Block->height=64; - ent_Block->fric_static=0.0f; - ent_Block->fric_dynamic=0.2f; + ent_Platform = Entity_New(); + ent_Platform->type = Ent_Platform; + ent_Platform->flags = EntityFlag_PlatformCollision; + ent_Platform->zorder = -1; + AnimPlay_SetImg(&ent_Platform->anim, img_platform); + ent_Platform->mass = 0.0f; + ent_Platform->radius = 12; + ent_Platform->width = 64; + ent_Platform->height = 16; + ent_Platform->fric_static = 0.0f; + ent_Platform->fric_dynamic = 0.2f; + ent_Block = Entity_New(); + ent_Block->type = Ent_Block; + ent_Block->flags = EntityFlag_BlockCollision; + ent_Block->zorder = -1; + AnimPlay_SetImg(&ent_Block->anim, img_block); + ent_Block->mass = 0.0f; + ent_Block->radius = 32; + ent_Block->width = 64; + ent_Block->height = 64; + ent_Block->fric_static = 0.0f; + ent_Block->fric_dynamic = 0.2f; } - diff --git a/Game/GameEnts.h b/Game/GameEnts.h index 09036ae..778b177 100644 --- a/Game/GameEnts.h +++ b/Game/GameEnts.h @@ -3,8 +3,6 @@ #ifndef _GAMEENTS_H_ #define _GAMEENTS_H_ - - enum { Ent_Player, Ent_Platform, @@ -22,4 +20,3 @@ int EntityApplyGravity(Entity e); void GameEnts_Init(); #endif - diff --git a/Game/GameMap.c b/Game/GameMap.c index 6aec4e9..f561034 100644 --- a/Game/GameMap.c +++ b/Game/GameMap.c @@ -10,119 +10,108 @@ #include "GameEnts.h" #include "GameMap.h" - -int ReadLine(FILE *f,char *line,int max){ +int ReadLine(FILE *f, char *line, int max) { int c; - int i=0; - while(i<(max-1)){ - c=fgetc(f); - if(c==EOF){ - line[i]=0; - return(-1); + int i = 0; + while (i < (max - 1)) { + c = fgetc(f); + if (c == EOF) { + line[i] = 0; + return (-1); } - if(c=='\r'){ + if (c == '\r') { continue; } - if(c=='\n'){ - line[i]=0; - return(i); + if (c == '\n') { + line[i] = 0; + return (i); } - line[i]=c; + line[i] = c; i++; } - line[i]=0; - return(i); + line[i] = 0; + return (i); } - -Entity GameMapAux_CreateEnt(Entity ent,int i,int j,int res){ +Entity GameMapAux_CreateEnt(Entity ent, int i, int j, int res) { Entity e; vec2 pos; - e=Entity_Copy(ent); - vec2_set(pos,(res/2)+i*res,(res/2)+j*res); - vec2_plus(e->pos,e->pos,pos); + e = Entity_Copy(ent); + vec2_set(pos, (res / 2) + i * res, (res / 2) + j * res); + vec2_plus(e->pos, e->pos, pos); Entity_CalcBBox(e); GameLib_AddEntity(e); - return(e); + return (e); } - #define MaxLineLen 1024 -int GameMap_LoadLevel(char *filename,int res){ +int GameMap_LoadLevel(char *filename, int res) { FILE *file; char line[MaxLineLen]; - int len,i,j; - int width,height; + int len, i, j; + int width, height; char *map; - // Open the file - file=fopen(filename,"rb"); - if(!file){ - return(0); + file = fopen(filename, "rb"); + if (!file) { + return (0); } // Read the file to determine sizes - width=0; - height=0; - do{ - len=ReadLine(file,line,MaxLineLen); - if(len>-1){ - if(len>height){ - height=len; + width = 0; + height = 0; + do { + len = ReadLine(file, line, MaxLineLen); + if (len > -1) { + if (len > height) { + height = len; } width++; } - }while(len>-1); - fseek(file,0,SEEK_SET); - + } while (len > -1); + fseek(file, 0, SEEK_SET); // Build the map - map=malloc(sizeof(char)*width*height); - memset(map,0,width*height); - #define MAP(x,y) map[(x)+((y)*width)] - j=0; - do{ - len=ReadLine(file,line,MaxLineLen); - for(i=0;i-1); - + } while (len > -1); // Close the file fclose(file); - // Parse the map - for(j=0;j1) { - if (!strcmp(argv[1],"debug")) { - gamelib_debug=1; + if (argc > 1) { + if (!strcmp(argv[1], "debug")) { + gamelib_debug = 1; printf("Debug Mode Activated!\n"); } } - GameLib_Init(640,480,"Game",20,60); + GameLib_Init(640, 480, "Game", 20, 60); ///////////////////////////// // Load and initialize media. // - font=Draw_DefaultFont(255,255,255,255); - imgBackground=Draw_LoadImage("data/background.png"); - Draw_SetOffset(imgBackground,0,0); + font = Draw_DefaultFont(255, 255, 255, 255); + imgBackground = Draw_LoadImage("data/background.png"); + Draw_SetOffset(imgBackground, 0, 0); GameEnts_Init(); ///////////////////////// // Initialize world. // GameLib_DelEnts(); - GameMap_LoadLevel("data/level_01.txt",64); + GameMap_LoadLevel("data/level_01.txt", 64); ///////////////////////// // Run the world. // GameLib_CleanParallaxBackgrounds(); - GameLib_AddParallaxBackground(imgBackground, (int[2]){512, 512}, (int[2]){0, 0}, (float[2]){0.5f, 0.0f}); - GameLib_Loop(ProcGame,PostProcGame,PreDrawGame,DrawGame); + GameLib_AddParallaxBackground(imgBackground, (int[2]){512, 512}, + (int[2]){0, 0}, (float[2]){0.5f, 0.0f}); + GameLib_Loop(ProcGame, PostProcGame, PreDrawGame, DrawGame); - return(0); + return (0); } \ No newline at end of file diff --git a/GameLib/Anim.c b/GameLib/Anim.c index 9ed1ae3..5e7a293 100644 --- a/GameLib/Anim.c +++ b/GameLib/Anim.c @@ -6,7 +6,6 @@ #include "Draw.h" #include "Anim.h" - //////////////////////////////////////////////// // Animation // /////////////// @@ -20,242 +19,226 @@ typedef struct { int time; } Animation; - ///////////////////////////// // Anim_LoadAnim // // -Anim Anim_LoadAnim(char *fichero,int width,int frames,float fps){ +Anim Anim_LoadAnim(char *fichero, int width, int frames, float fps) { DrawImg img; Animation *anim; - int w,h; + int w, h; - img=Draw_LoadImage(fichero); - if(!img){ - return(NULL); + img = Draw_LoadImage(fichero); + if (!img) { + return (NULL); } - Draw_GetSize(img,&w,&h); - Draw_SetOffset(img,-(width/2),-(h/2)); + Draw_GetSize(img, &w, &h); + Draw_SetOffset(img, -(width / 2), -(h / 2)); // Create the animation container - anim=malloc(sizeof(Animation)); - anim->img=img; - anim->w=width; - if(width<=0){ - anim->w=w/frames; + anim = malloc(sizeof(Animation)); + anim->img = img; + anim->w = width; + if (width <= 0) { + anim->w = w / frames; } - anim->fps=fps; - anim->frames=frames; - anim->ftime=1000/fps; - anim->time=anim->ftime*frames; + anim->fps = fps; + anim->frames = frames; + anim->ftime = 1000 / fps; + anim->time = anim->ftime * frames; - return((Anim)anim); + return ((Anim)anim); } - ///////////////////////////// // Anim_GetTime // // -int Anim_GetTime(Anim a){ - Animation *anim=a; +int Anim_GetTime(Anim a) { + Animation *anim = a; - return(anim->time); + return (anim->time); } - ///////////////////////////// // Anim_GetSize // // Gets the animation size. -void Anim_GetSize(Anim a,int *w,int *h){ - Animation *anim=a; +void Anim_GetSize(Anim a, int *w, int *h) { + Animation *anim = a; int waux; - *w=anim->w; - Draw_GetSize(anim->img,&waux,h); + *w = anim->w; + Draw_GetSize(anim->img, &waux, h); } - ///////////////////////////// // Anim_SetOffset // Anim_GetOffset // // -void Anim_SetOffset(Anim a,int x,int y){ - Animation *anim=a; +void Anim_SetOffset(Anim a, int x, int y) { + Animation *anim = a; - Draw_SetOffset(anim->img,x,y); + Draw_SetOffset(anim->img, x, y); } -void Anim_GetOffset(Anim a,int *x,int *y){ - Animation *anim=a; +void Anim_GetOffset(Anim a, int *x, int *y) { + Animation *anim = a; - Draw_GetOffset(anim->img,x,y); + Draw_GetOffset(anim->img, x, y); } - ///////////////////////////// // Anim_SetFlip // Anim_GetFlip // // -void Anim_SetFlip(Anim a,int flip){ - Animation *anim=a; +void Anim_SetFlip(Anim a, int flip) { + Animation *anim = a; - Draw_SetFlip(anim->img,flip); + Draw_SetFlip(anim->img, flip); } -int Anim_GetFlip(Anim a){ - Animation *anim=a; +int Anim_GetFlip(Anim a) { + Animation *anim = a; return Draw_GetFlip(anim->img); } - ///////////////////////////// // Anim_Draw // // -void Anim_Draw(Anim a,int time_ms,int x,int y){ - Animation *anim=a; +void Anim_Draw(Anim a, int time_ms, int x, int y) { + Animation *anim = a; int frame; - frame=(time_ms/anim->ftime)%anim->frames; - Draw_DrawImgPartHoriz(anim->img,x,y,anim->w,frame); + frame = (time_ms / anim->ftime) % anim->frames; + Draw_DrawImgPartHoriz(anim->img, x, y, anim->w, frame); } - ///////////////////////////// // AnimPlay_Copy // // -void AnimPlay_Copy(AnimPlay *ad,AnimPlay *ao){ - ad->img=ao->img; +void AnimPlay_Copy(AnimPlay *ad, AnimPlay *ao) { + ad->img = ao->img; - ad->imgPart=ao->imgPart; - ad->w=ao->w; - ad->h=ao->h; - ad->i=ao->i; - ad->j=ao->j; + ad->imgPart = ao->imgPart; + ad->w = ao->w; + ad->h = ao->h; + ad->i = ao->i; + ad->j = ao->j; - ad->anim=ao->anim; - ad->time_ms=ao->time_ms; + ad->anim = ao->anim; + ad->time_ms = ao->time_ms; } - ///////////////////////////// // AnimPlay_SetImg // AnimPlay_SetAnim // AnimPlay_SetImgPart // // -void AnimPlay_SetImg(AnimPlay *ap,DrawImg img){ - ap->anim=NULL; - ap->time_ms=0; +void AnimPlay_SetImg(AnimPlay *ap, DrawImg img) { + ap->anim = NULL; + ap->time_ms = 0; - ap->img=img; + ap->img = img; - ap->imgPart=NULL; + ap->imgPart = NULL; } -void AnimPlay_SetAnim(AnimPlay *ap,Anim ani){ - ap->pause=0; - if(ap->anim==ani){ +void AnimPlay_SetAnim(AnimPlay *ap, Anim ani) { + ap->pause = 0; + if (ap->anim == ani) { return; } - ap->anim=ani; - ap->time_ms=0; + ap->anim = ani; + 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,int j){ - ap->anim=NULL; - ap->time_ms=0; +void AnimPlay_SetImgPart(AnimPlay *ap, DrawImg img, int w, int h, int i, + int j) { + ap->anim = NULL; + ap->time_ms = 0; - ap->img=NULL; + ap->img = NULL; - ap->imgPart=img; - ap->w=w; - ap->h=h; - ap->i=i; - ap->j=j; + ap->imgPart = img; + ap->w = w; + ap->h = h; + ap->i = i; + ap->j = j; } - ///////////////////////////// // AnimPlay_Draw // // -void AnimPlay_Draw(AnimPlay *ani,int x,int y){ - if(ani->anim){ - Anim_Draw(ani->anim,ani->time_ms,x,y); +void AnimPlay_Draw(AnimPlay *ani, int x, int y) { + if (ani->anim) { + Anim_Draw(ani->anim, ani->time_ms, x, y); return; } - if(ani->img){ - Draw_DrawImg(ani->img,x,y); + if (ani->img) { + Draw_DrawImg(ani->img, x, y); return; } - if(ani->imgPart){ - Draw_DrawImgPart(ani->imgPart,x,y,ani->w,ani->h,ani->i,ani->j); + if (ani->imgPart) { + Draw_DrawImgPart(ani->imgPart, x, y, ani->w, ani->h, ani->i, ani->j); return; } } - ///////////////////////////// // AnimPlay_GetOffset // AnimPlay_GetSize // // -void AnimPlay_GetOffset(AnimPlay *ani,int *x,int *y){ - if(ani->anim){ - Anim_GetOffset(ani->anim,x,y); +void AnimPlay_GetOffset(AnimPlay *ani, int *x, int *y) { + if (ani->anim) { + Anim_GetOffset(ani->anim, x, y); return; } - if(ani->img){ - Draw_GetOffset(ani->img,x,y); + if (ani->img) { + Draw_GetOffset(ani->img, x, y); return; } - if(ani->imgPart){ - Draw_GetOffset(ani->imgPart,x,y); + if (ani->imgPart) { + Draw_GetOffset(ani->imgPart, x, y); return; } } -void AnimPlay_GetSize(AnimPlay *ani,int *w,int *h){ - if(ani->anim){ - Anim_GetSize(ani->anim,w,h); +void AnimPlay_GetSize(AnimPlay *ani, int *w, int *h) { + if (ani->anim) { + Anim_GetSize(ani->anim, w, h); return; - }else - if(ani->img){ - Draw_GetSize(ani->img,w,h); + } else if (ani->img) { + Draw_GetSize(ani->img, w, h); return; } - if(ani->imgPart){ - Draw_GetSize(ani->imgPart,w,h); + if (ani->imgPart) { + Draw_GetSize(ani->imgPart, w, h); return; } } - - ///////////////////////////// // AnimPlay_SetPause // // -void AnimPlay_SetPause(AnimPlay *ani,int p){ - ani->pause=p; -} - +void AnimPlay_SetPause(AnimPlay *ani, int p) { ani->pause = p; } ///////////////////////////// // AnimPlay_IncTime // // -void AnimPlay_IncTime(AnimPlay *ani,int t){ - if(ani->anim){ - if(!ani->pause){ - ani->time_ms+=t; +void AnimPlay_IncTime(AnimPlay *ani, int t) { + if (ani->anim){ + if (!ani->pause) { + ani->time_ms += t; } } } - diff --git a/GameLib/Anim.h b/GameLib/Anim.h index 684bcd1..1335913 100644 --- a/GameLib/Anim.h +++ b/GameLib/Anim.h @@ -5,20 +5,17 @@ #include "Draw.h" - //////////////////////////////////////////////// // Anim // ////////// // typedef void *Anim; - ///////////////////////////// // Anim_LoadAnim // // -Anim Anim_LoadAnim(char *fichero,int width,int frames,float fps); - +Anim Anim_LoadAnim(char *fichero, int width, int frames, float fps); ///////////////////////////// // Anim_GetTime @@ -26,38 +23,33 @@ Anim Anim_LoadAnim(char *fichero,int width,int frames,float fps); // int Anim_GetTime(Anim anim); - ///////////////////////////// // Anim_GetSize // // Gets the animation size. -void Anim_GetSize(Anim anim,int *w,int *h); - +void Anim_GetSize(Anim anim, int *w, int *h); ///////////////////////////// // Anim_SetOffset // Anim_GetOffset // // -void Anim_SetOffset(Anim anim,int x,int y); -void Anim_GetOffset(Anim anim,int *x,int *y); - +void Anim_SetOffset(Anim anim, int x, int y); +void Anim_GetOffset(Anim anim, int *x, int *y); ///////////////////////////// // Anim_SetFlip // Draw_GetFlip // // -void Anim_SetFlip(Anim anim,int flip); +void Anim_SetFlip(Anim anim, int flip); int Anim_GetFlip(Anim anim); - ///////////////////////////// // Anim_Draw // // -void Anim_Draw(Anim anim,int time_ms,int x,int y); - +void Anim_Draw(Anim anim, int time_ms, int x, int y); //////////////////////////////////////////////// // AnimPlay // @@ -71,17 +63,15 @@ typedef struct { DrawImg img; DrawImg imgPart; - int w,h,i,j; + int w, h, i, j; } AnimPlay; - ///////////////////////////// // AnimPlay_Copy // // -void AnimPlay_Copy(AnimPlay *ad,AnimPlay *ao); - +void AnimPlay_Copy(AnimPlay *ad, AnimPlay *ao); ///////////////////////////// // AnimPlay_SetImg @@ -89,38 +79,34 @@ void AnimPlay_Copy(AnimPlay *ad,AnimPlay *ao); // AnimPlay_SetImgPart // // -void AnimPlay_SetImg(AnimPlay *ap,DrawImg img); -void AnimPlay_SetAnim(AnimPlay *ap,Anim ani); -void AnimPlay_SetImgPart(AnimPlay *ap,DrawImg img,int w,int h,int i,int j); - +void AnimPlay_SetImg(AnimPlay *ap, DrawImg img); +void AnimPlay_SetAnim(AnimPlay *ap, Anim ani); +void AnimPlay_SetImgPart(AnimPlay *ap, DrawImg img, int w, int h, int i, int j); ///////////////////////////// // AnimPlay_Draw // // -void AnimPlay_Draw(AnimPlay *ani,int x,int y); - +void AnimPlay_Draw(AnimPlay *ani, int x, int y); ///////////////////////////// // AnimPlay_GetOffset // AnimPlay_GetSize // // -void AnimPlay_GetOffset(AnimPlay *ani,int *x,int *y); -void AnimPlay_GetSize(AnimPlay *ani,int *w,int *h); - +void AnimPlay_GetOffset(AnimPlay *ani, int *x, int *y); +void AnimPlay_GetSize(AnimPlay *ani, int *w, int *h); ///////////////////////////// // AnimPlay_SetPause // // -void AnimPlay_SetPause(AnimPlay *ani,int p); +void AnimPlay_SetPause(AnimPlay *ani, int p); ///////////////////////////// // AnimPlay_IncTime // // -void AnimPlay_IncTime(AnimPlay *ani,int t); - +void AnimPlay_IncTime(AnimPlay *ani, int t); #endif diff --git a/GameLib/Audio.c b/GameLib/Audio.c index dd4bb13..652cdef 100644 --- a/GameLib/Audio.c +++ b/GameLib/Audio.c @@ -1,8 +1,8 @@ // Copyright (C) 2011 Valeriano Alfonso Rodriguez (Kableado) #ifdef WIN32 - #define _WIN32_WINNT 0x0501 - #include +#define _WIN32_WINNT 0x0501 +#include #endif #include #include @@ -12,8 +12,7 @@ #include "Audio.h" -static void Audio_MixerCallback(void *ud,Uint8 *stream,int l); - +static void Audio_MixerCallback(void *ud, Uint8 *stream, int l); //////////////////////////////////////////////// // AudioWave // @@ -30,8 +29,7 @@ struct TAudioWave { AudioWave next; }; -AudioWave _waves=NULL; - +AudioWave _waves = NULL; //////////////////////////////////////////////// // AudioChan // @@ -45,29 +43,29 @@ struct TAudioChan { unsigned char leftvol; int loop; - + AudioChan next; }; -AudioChan _channels=NULL; -AudioChan _free_channels=NULL; +AudioChan _channels = NULL; +AudioChan _free_channels = NULL; ///////////////////////////// // Audio_Init // // Initializes the game audio. -int Audio_Init(){ +int Audio_Init() { SDL_AudioSpec as; SDL_AudioSpec as2; - // Initialize audio subsistem +// Initialize audio subsistem #ifdef WIN32 // Force DSound Driver on win32 putenv("SDL_AUDIODRIVER=dsound"); #endif - if(SDL_InitSubSystem(SDL_INIT_AUDIO) < 0){ + if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) { Print("Audio_Init: Failure initializing SDL Audio.\n"); - Print("\tSDL Error: %s\n",SDL_GetError()); - return(0); + Print("\tSDL Error: %s\n", SDL_GetError()); + return (0); } // Open the audio device using the desired parameters @@ -76,155 +74,148 @@ int Audio_Init(){ as.channels = 2; as.samples = 2048; as.callback = Audio_MixerCallback; - if(SDL_OpenAudio(&as, &as2) < 0){ + if (SDL_OpenAudio(&as, &as2) < 0) { Print("Audio_Init: Failure opening audio.\n"); - Print("\tSDL Error: %s\n",SDL_GetError()); - return(0); + Print("\tSDL Error: %s\n", SDL_GetError()); + return (0); } // Asert results - if( as2.format != AUDIO_S16SYS || - as2.freq != 44100 || - as2.channels != 2 ) - { + if (as2.format != AUDIO_S16SYS || as2.freq != 44100 || as2.channels != 2) { Print("Audio_Init: Failure opening audio. (44.1Khz/16b/2c).\n"); SDL_CloseAudio(); - return(0); + return (0); } // Unpause and ready to go SDL_PauseAudio(0); - return(1); + return (1); } - ///////////////////////////// // Audio_MixerCallback // // Mixes the audio channels. -static void Audio_MixerCallback(void *ud,Uint8 *stream,int l){ - signed short *ptr_out,*ptr_wave; +static void Audio_MixerCallback(void *ud, Uint8 *stream, int l) { + signed short *ptr_out, *ptr_wave; AudioChan prevchan; AudioChan chan; AudioWave wave; - int len=l/4; // Asume 16bpb and 2 output chan + int len = l / 4; // Asume 16bpb and 2 output chan int chan_remain; int len_mix; int i; // Clean - memset(stream,0,l); + memset(stream, 0, l); // Mix all the channels - prevchan=NULL; - chan=_channels; - while(chan){ - if(!chan->wave){ + prevchan = NULL; + chan = _channels; + while (chan) { + if (!chan->wave) { // Remove finished channels - AudioChan aux_chan=chan->next; - chan->next=_free_channels; - _free_channels=chan; - chan=aux_chan; - if(prevchan){ - prevchan->next=chan; - }else{ - _channels=chan; + AudioChan aux_chan = chan->next; + chan->next = _free_channels; + _free_channels = chan; + chan = aux_chan; + if (prevchan) { + prevchan->next = chan; + } else { + _channels = chan; } continue; } // Prepare the pointers - ptr_out=(signed short *)stream; - ptr_wave=((signed short *)chan->wave->buffer)+chan->pos; - wave=chan->wave; + ptr_out = (signed short *)stream; + ptr_wave = ((signed short *)chan->wave->buffer) + chan->pos; + wave = chan->wave; // Determine mixing lenght - chan_remain=wave->len-chan->pos; - if(chan_remain>len){ - len_mix=len; - }else{ - if(chan->loop){ - len_mix=len; - }else{ - len_mix=chan_remain; + chan_remain = wave->len - chan->pos; + if (chan_remain > len) { + len_mix = len; + } else { + if (chan->loop) { + len_mix = len; + } else { + len_mix = chan_remain; } - chan->wave=NULL; + chan->wave = NULL; } // Mix the buffer - for(i=0;ileftvol)>>8; - if(temp>(1<<14)){ - ptr_out[0]=1<<14; - }else if(temp<-(1<<14)){ - ptr_out[0]=-(1<<14); - }else{ - ptr_out[0]=temp; + temp = ptr_out[0]; + temp += (ptr_wave[0] * chan->leftvol) >> 8; + if (temp > (1 << 14)) { + ptr_out[0] = 1 << 14; + } else if (temp < -(1 << 14)) { + ptr_out[0] = -(1 << 14); + } else { + ptr_out[0] = temp; } // Right Channel - temp=ptr_out[1]; - temp+=(ptr_wave[0]*chan->rightvol)>>8; - if(temp>(1<<14)){ - ptr_out[1]=1<<14; - }else if(temp<-(1<<14)){ - ptr_out[1]=-(1<<14); - }else{ - ptr_out[1]=temp; + temp = ptr_out[1]; + temp += (ptr_wave[0] * chan->rightvol) >> 8; + if (temp > (1 << 14)) { + ptr_out[1] = 1 << 14; + } else if (temp < -(1 << 14)) { + ptr_out[1] = -(1 << 14); + } else { + ptr_out[1] = temp; } // Next sample - ptr_out+=2; - if(ptr_wave>=(((signed short *)wave->buffer)+(wave->len-1))){ - ptr_wave=((signed short *)wave->buffer); - }else{ + ptr_out += 2; + if (ptr_wave >= + (((signed short *)wave->buffer) + (wave->len - 1))) { + ptr_wave = ((signed short *)wave->buffer); + } else { ptr_wave++; } } - chan->pos+=len_mix; + chan->pos += len_mix; - if(chan->wave==NULL && chan->loop==1){ - chan->wave=wave; - while(chan->pos>wave->len){ - chan->pos-=wave->len; + if (chan->wave == NULL && chan->loop == 1) { + chan->wave = wave; + while (chan->pos > wave->len) { + chan->pos -= wave->len; } } - + // Next channel - prevchan=chan; - chan=chan->next; + prevchan = chan; + chan = chan->next; } } - ///////////////////////////// // Audio_Frame // // Notify a frame update to the audio subsystem. -void Audio_Frame(){ - -} - +void Audio_Frame() {} ///////////////////////////// // Audio_LoadSound // // Loads a sound, giving a reference. -AudioSnd Audio_LoadSound(char *filename){ +AudioSnd Audio_LoadSound(char *filename) { FILE *f; - char id[5] = { 0, 0, 0, 0, 0 }, *sndBuffer = NULL; + char id[5] = {0, 0, 0, 0, 0}, *sndBuffer = NULL; short formatTag, channels, bitsPerSample; int formatLen, sampleRate, dataSize; f = fopen(filename, "rb"); if (!f) { Print("Audio_LoadSound: Failure opening file.\n"); - return(NULL); + return (NULL); } // Read id "RIFF" @@ -232,7 +223,7 @@ AudioSnd Audio_LoadSound(char *filename){ if (strcmp(id, "RIFF")) { Print("Audio_LoadSound: File is not RIFF.\n"); fclose(f); - return(NULL); + return (NULL); } // File size (-"RIFF") @@ -243,7 +234,7 @@ AudioSnd Audio_LoadSound(char *filename){ if (strcmp(id, "WAVE")) { Print("Audio_LoadSound: File is not WAVE.\n"); fclose(f); - return(NULL); + return (NULL); } // Read the format @@ -252,13 +243,13 @@ AudioSnd Audio_LoadSound(char *filename){ if (formatLen < 14) { Print("Audio_LoadSound: File too short.\n"); fclose(f); - return (NULL ); + return (NULL); } fread(&formatTag, 1, sizeof(short), f); // 1=PCM if (formatTag != 1) { Print("Audio_LoadSound: Not PCM format.\n"); fclose(f); - return (NULL ); + return (NULL); } fread(&channels, 1, sizeof(short), f); fread(&sampleRate, 1, sizeof(int), f); @@ -268,34 +259,36 @@ AudioSnd Audio_LoadSound(char *filename){ fseek(f, formatLen - 14, SEEK_CUR); // Align read // Assert sound format - if (sampleRate!=44100 || channels!=1 || bitsPerSample!=2) { + if (sampleRate != 44100 || channels != 1 || bitsPerSample != 2) { Print("Audio_LoadSound: Format not supported: " - "sampleRate:%d; channels:%d; BPB:%d\n", - sampleRate, channels, bitsPerSample); + "sampleRate:%d; channels:%d; BPB:%d\n", + sampleRate, channels, bitsPerSample); fclose(f); - return(NULL); + return (NULL); } // Skip no "data" blocks - do{ - int lenRead=fread(id, 1, sizeof(char) * 4, f); - if(lenRead<4){ break; } + do { + int lenRead = fread(id, 1, sizeof(char) * 4, f); + if (lenRead < 4) { + break; + } if (strcmp(id, "data")) { fread(&dataSize, 1, sizeof(int), f); fseek(f, dataSize, SEEK_CUR); - }else{ + } else { break; } - }while(1); + } while (1); if (strcmp(id, "data")) { Print("Audio_LoadSound: DATA block not found\n"); fclose(f); - return (NULL ); + return (NULL); } // Read the "data" block fread(&dataSize, 1, sizeof(int), f); - sndBuffer = malloc(sizeof(char)*dataSize); + sndBuffer = malloc(sizeof(char) * dataSize); fread(sndBuffer, dataSize, sizeof(char), f); fclose(f); @@ -304,69 +297,67 @@ AudioSnd Audio_LoadSound(char *filename){ AudioWave wave = malloc(sizeof(TAudioWave)); wave->sampleRate = sampleRate; wave->channels = channels; - wave->buffer = (Uint8 *) sndBuffer; + wave->buffer = (Uint8 *)sndBuffer; wave->BPB = bitsPerSample; wave->bpb = wave->BPB * 8; wave->len = dataSize / (wave->BPB * wave->channels); // Take a reference - wave->next=_waves; - _waves=wave; + wave->next = _waves; + _waves = wave; return (wave); } - ///////////////////////////// // Audio_PlaySound // // Loads a sound, giving a reference. -AudioChn Audio_PlaySound(AudioSnd snd, - float leftvol, float rightvol,int loop) -{ +AudioChn Audio_PlaySound(AudioSnd snd, float leftvol, float rightvol, + int loop) { AudioChan chan; AudioWave wave; - if(!snd){ - return(NULL); + if (!snd) { + return (NULL); } // Cast AudioSnd to AudioWave - wave=snd; + wave = snd; // Get a free channel - if(_free_channels){ - chan=_free_channels; - _free_channels=chan->next; - chan->next=NULL; - }else{ - chan=malloc(sizeof(TAudioChan)); - chan->next=NULL; + if (_free_channels) { + chan = _free_channels; + _free_channels = chan->next; + chan->next = NULL; + } else { + chan = malloc(sizeof(TAudioChan)); + chan->next = NULL; } // Initialize the channel - chan->wave=wave; - chan->pos=0; - chan->rightvol=(rightvol*255); - chan->leftvol=(leftvol*255); - chan->loop=loop; - + chan->wave = wave; + chan->pos = 0; + chan->rightvol = (rightvol * 255); + chan->leftvol = (leftvol * 255); + chan->loop = loop; + // Include in sounds list - chan->next=_channels; - _channels=chan; - + chan->next = _channels; + _channels = chan; + return chan; } - ///////////////////////////// // Audio_StopChan // // Stops an audio chanel -void Audio_StopChan(AudioChn c){ +void Audio_StopChan(AudioChn c) { AudioChan chan; - chan=c; - if(c==NULL){return;} - chan->loop=0; - chan->wave=NULL; + chan = c; + if (c == NULL) { + return; + } + chan->loop = 0; + chan->wave = NULL; } - diff --git a/GameLib/Audio.h b/GameLib/Audio.h index 061b423..55355c9 100644 --- a/GameLib/Audio.h +++ b/GameLib/Audio.h @@ -3,55 +3,46 @@ #ifndef _AUDIO_H_ #define _AUDIO_H_ - ///////////////////////////// // Audio_Init // // Initializes the game audio. int Audio_Init(); - ///////////////////////////// // Audio_Frame // // Notify a frame update to the audio subsystem. void Audio_Frame(); - //////////////////////////////////////////////// // AudioSnd // ////////////// // Reference to a sound. typedef void *AudioSnd; - //////////////////////////////////////////////// // AudioChn // ////////////// // Reference to a playing sound. typedef void *AudioChn; - ///////////////////////////// // Audio_LoadSound // // Loads a sound, giving a reference. AudioSnd Audio_LoadSound(char *filename); - ///////////////////////////// // Audio_PlaySound // // Loads a sound, giving a reference. -AudioChn Audio_PlaySound(AudioSnd snd, - float leftvol, float rightvol,int loop); - +AudioChn Audio_PlaySound(AudioSnd snd, float leftvol, float rightvol, int loop); ///////////////////////////// // Audio_StopChan // // Stops an audio chanel void Audio_StopChan(AudioChn chan); - #endif diff --git a/GameLib/Draw.c b/GameLib/Draw.c index dbd9b80..50631c4 100644 --- a/GameLib/Draw.c +++ b/GameLib/Draw.c @@ -2,43 +2,43 @@ #ifdef WIN32 // Windows -# define _WIN32_WINNT 0x0501 -# include -# include -# include -# include -# include -# include -# include -# define USE_OpenGL 1 -# define USE_OpenGLES 0 -# define GL_CLAMP_TO_EDGE 0x812F -# include +#define _WIN32_WINNT 0x0501 +#include +#include +#include +#include +#include +#include +#include +#define USE_OpenGL 1 +#define USE_OpenGLES 0 +#define GL_CLAMP_TO_EDGE 0x812F +#include #else #ifdef EMSCRIPTEN // Emscripten -# include -# include -# include -# include -# include -# define GL_GLEXT_PROTOTYPES 1 -# include -# include -# define USE_OpenGL 0 -# define USE_OpenGLES 1 -# define SDL_GetKeyState SDL_GetKeyboardState -# include +#include +#include +#include +#include +#include +#define GL_GLEXT_PROTOTYPES 1 +#include +#include +#define USE_OpenGL 0 +#define USE_OpenGLES 1 +#define SDL_GetKeyState SDL_GetKeyboardState +#include #else // UNIX -# include -# include -# include -# include -# include -# define USE_OpenGL 1 -# define USE_OpenGLES 0 -# include +#include +#include +#include +#include +#include +#define USE_OpenGL 1 +#define USE_OpenGLES 0 +#include #endif #endif #include "lodepng.c" @@ -51,7 +51,6 @@ #include "Input.h" #include "Draw.h" - //////////////////////////////////////////////// // DrawImage // /////////////// @@ -59,40 +58,38 @@ typedef struct TDrawImage TDrawImage, *DrawImage; struct TDrawImage { unsigned char *data; - int x,y; - int w,h; + int x, y; + int w, h; int flip; GLuint tex; }; - - // Globals -SDL_Surface *_screen=NULL; +SDL_Surface *_screen = NULL; int _width; int _height; -long long proc_t_frame=33333; -long long draw_t_frame=16667; -int _fps=60; -QuadArray2D _quadArray=NULL; -DrawImage _currentImg=NULL; +long long proc_t_frame = 33333; +long long draw_t_frame = 16667; +int _fps = 60; +QuadArray2D _quadArray = NULL; +DrawImage _currentImg = NULL; float _color[4]; #if USE_OpenGLES GLuint _whiteTex; -GLuint Draw_CompileShader(GLenum type, const char *source){ +GLuint Draw_CompileShader(GLenum type, const char *source) { GLuint shader = glCreateShader(type); if (shader == 0) { return 0; } - //load the shader source to the shader object and compile it + // load the shader source to the shader object and compile it glShaderSource(shader, 1, &source, NULL); glCompileShader(shader); - //check if the shader compiled successfully + // check if the shader compiled successfully GLint compiled; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (!compiled) { @@ -103,29 +100,27 @@ GLuint Draw_CompileShader(GLenum type, const char *source){ return shader; } - -GLuint Draw_BuildProgram( - const char *vertexShaderSource, - const char *fragmentShaderSource) -{ +GLuint Draw_BuildProgram(const char *vertexShaderSource, + const char *fragmentShaderSource) { // Compile shaders - GLuint vertexShader = Draw_CompileShader(GL_VERTEX_SHADER, vertexShaderSource); - GLuint fragmentShader = Draw_CompileShader(GL_FRAGMENT_SHADER, fragmentShaderSource); - if(vertexShader==0 || fragmentShader==0){ + GLuint vertexShader = + Draw_CompileShader(GL_VERTEX_SHADER, vertexShaderSource); + GLuint fragmentShader = + Draw_CompileShader(GL_FRAGMENT_SHADER, fragmentShaderSource); + if (vertexShader == 0 || fragmentShader == 0) { return 0; } - //create a GL program and link it + // create a GL program and link it GLuint programObject = glCreateProgram(); glAttachShader(programObject, vertexShader); glAttachShader(programObject, fragmentShader); glLinkProgram(programObject); - //check if the program linked successfully + // check if the program linked successfully GLint linked; glGetProgramiv(programObject, GL_LINK_STATUS, &linked); - if (!linked) - { + if (!linked) { glDeleteProgram(programObject); return 0; } @@ -155,28 +150,28 @@ GLuint Draw_UploadGLTexture(int w, int h, unsigned char *pixels); // Draw_Init // // Initializes the game window. -int Draw_Init(int width,int height,char *title,int pfps,int fps){ +int Draw_Init(int width, int height, char *title, int pfps, int fps) { // Set globals - proc_t_frame=1000000/pfps; - draw_t_frame=1000000/fps; - _fps=fps; - _width=width; - _height=height; + proc_t_frame = 1000000 / pfps; + draw_t_frame = 1000000 / fps; + _fps = fps; + _width = width; + _height = height; // Initialize SDL - if(SDL_Init(SDL_INIT_VIDEO)<0){ + if (SDL_Init(SDL_INIT_VIDEO) < 0) { Print("Draw_Init: Failure initializing SDL.\n"); - Print("\tSDL Error: %s\n",SDL_GetError()); - return(0); + Print("\tSDL Error: %s\n", SDL_GetError()); + return (0); } // Initialize video mode - _screen=SDL_SetVideoMode(width,height,32,SDL_HWSURFACE|SDL_OPENGL); - if( _screen == NULL){ + _screen = SDL_SetVideoMode(width, height, 32, SDL_HWSURFACE | SDL_OPENGL); + if (_screen == NULL) { Print("Draw_Init: Failure initializing video mode.\n"); - Print("\tSDL Error: %s\n",SDL_GetError()); - return(0); + Print("\tSDL Error: %s\n", SDL_GetError()); + return (0); } SDL_WM_SetCaption(title, NULL); Draw_ShowInfo(); @@ -188,7 +183,7 @@ int Draw_Init(int width,int height,char *title,int pfps,int fps){ glEnable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); - glDepthMask( GL_FALSE); + glDepthMask(GL_FALSE); // Triplebuffer swap glClear(GL_COLOR_BUFFER_BIT); @@ -199,7 +194,6 @@ int Draw_Init(int width,int height,char *title,int pfps,int fps){ SDL_GL_SwapBuffers(); glClear(GL_COLOR_BUFFER_BIT); - glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); @@ -208,19 +202,18 @@ int Draw_Init(int width,int height,char *title,int pfps,int fps){ #if USE_OpenGLES - const char vertexShaderSource[] = - "attribute vec4 aPosition; \n" - "attribute vec2 aTexCoord; \n" - "attribute vec4 aColor; \n" - "varying vec2 vTexCoord; \n" - "varying vec4 vColor; \n" - "uniform mat4 sProjectionMatrix; \n" - "void main() { \n" - " gl_Position = aPosition * \n" - " sProjectionMatrix; \n" - " vTexCoord = aTexCoord; \n" - " vColor = aColor; \n" - "} \n"; + const char vertexShaderSource[] = "attribute vec4 aPosition; \n" + "attribute vec2 aTexCoord; \n" + "attribute vec4 aColor; \n" + "varying vec2 vTexCoord; \n" + "varying vec4 vColor; \n" + "uniform mat4 sProjectionMatrix; \n" + "void main() { \n" + " gl_Position = aPosition * \n" + " sProjectionMatrix; \n" + " vTexCoord = aTexCoord; \n" + " vColor = aColor; \n" + "} \n"; const char fragmentShaderSource[] = "precision mediump float; \n" @@ -231,9 +224,7 @@ int Draw_Init(int width,int height,char *title,int pfps,int fps){ " gl_FragColor = texture2D(sTexture, vTexCoord)*vColor; \n" "} \n"; - programObject=Draw_BuildProgram( - vertexShaderSource, - fragmentShaderSource); + programObject = Draw_BuildProgram(vertexShaderSource, fragmentShaderSource); glUseProgram(programObject); vertPosLoc = glGetAttribLocation(programObject, "aPosition"); @@ -241,40 +232,42 @@ int Draw_Init(int width,int height,char *title,int pfps,int fps){ vertColorLoc = glGetAttribLocation(programObject, "aColor"); textureLoc = glGetUniformLocation(programObject, "sTexture"); - projectionMatrixLoc = glGetUniformLocation(programObject, "sProjectionMatrix"); + projectionMatrixLoc = + glGetUniformLocation(programObject, "sProjectionMatrix"); glUniform1i(textureLoc, 0); glGenBuffers(1, &vertexObject); - glBindBuffer(GL_ARRAY_BUFFER, vertexObject ); - glBufferData(GL_ARRAY_BUFFER, Vertex2D_Length*sizeof(float)*Max_Vertices, - NULL, GL_DYNAMIC_DRAW); + glBindBuffer(GL_ARRAY_BUFFER, vertexObject); + glBufferData(GL_ARRAY_BUFFER, + Vertex2D_Length * sizeof(float) * Max_Vertices, NULL, + GL_DYNAMIC_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, vertexObject ); + glBindBuffer(GL_ARRAY_BUFFER, vertexObject); - glVertexAttribPointer(vertPosLoc, 2, GL_FLOAT,GL_FALSE, - Vertex2D_Length*sizeof(float), (void*)(0*sizeof(float))); + glVertexAttribPointer(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), (void*)(2*sizeof(float))); + Vertex2D_Length * sizeof(float), + (void *)(2 * sizeof(float))); glVertexAttribPointer(vertColorLoc, 4, GL_FLOAT, GL_FALSE, - Vertex2D_Length*sizeof(float), (void*)(4*sizeof(float))); + Vertex2D_Length * sizeof(float), + (void *)(4 * sizeof(float))); glEnableVertexAttribArray(vertPosLoc); glEnableVertexAttribArray(vertTexLoc); glEnableVertexAttribArray(vertColorLoc); - unsigned char whiteTexData[4]={255,255,255,255}; - _whiteTex=Draw_UploadGLTexture(1, 1, whiteTexData); + unsigned char whiteTexData[4] = {255, 255, 255, 255}; + _whiteTex = Draw_UploadGLTexture(1, 1, whiteTexData); #endif // Set the proyection (2D) 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[5] = -(2.0f / _height); projectionMatrix[10] = -0.001f; @@ -284,114 +277,108 @@ int Draw_Init(int width,int height,char *title,int pfps,int fps){ // Enable Alpha blending glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Initialize the triangle array - _quadArray=QuadArray2D_Create(400); + _quadArray = QuadArray2D_Create(400); - Draw_SetColor(1.0f,1.0f,1.0f,1.0f); + Draw_SetColor(1.0f, 1.0f, 1.0f, 1.0f); - return(1); + return (1); } - ///////////////////////////// // Draw_ShowInfo // // Show device information -void Draw_ShowInfo(){ +void Draw_ShowInfo() { char *str; Print("\n*********************************\n"); Print("*** Draw Info\n"); - str=(char *)glGetString(GL_VENDOR); - Print(" Vendor: %s\n",str); - str=(char *)glGetString(GL_RENDERER); - Print(" Renderer: %s\n",str); - str=(char *)glGetString(GL_VERSION); - Print(" Version: %s\n",str); + str = (char *)glGetString(GL_VENDOR); + Print(" Vendor: %s\n", str); + str = (char *)glGetString(GL_RENDERER); + Print(" Renderer: %s\n", str); + str = (char *)glGetString(GL_VERSION); + Print(" Version: %s\n", str); Print("*********************************\n"); } - ///////////////////////////// // Draw_SetMatrix // // Sets the render matrix -void Draw_SetMatrix(float matrix[16]){ +void Draw_SetMatrix(float matrix[16]) { #if USE_OpenGL - float tempMatrix[16] = { - 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]}; + float tempMatrix[16] = {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); #endif #if USE_OpenGLES - glUniformMatrix4fv(projectionMatrixLoc, - 1, GL_FALSE, matrix); + glUniformMatrix4fv(projectionMatrixLoc, 1, GL_FALSE, matrix); #endif } - ///////////////////////////// // Draw_UploadGLTexture // // Uploads a OpenGL texture. -GLuint Draw_UploadGLTexture(int w, int h, unsigned char *pixels){ +GLuint Draw_UploadGLTexture(int w, int h, unsigned char *pixels) { GLuint tex; // Generate OpenGL texture glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); - glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Load OpenGL texture glBindTexture(GL_TEXTURE_2D, tex); #if USE_OpenGL - glPixelStorei( GL_UNPACK_ROW_LENGTH, w ); + glPixelStorei(GL_UNPACK_ROW_LENGTH, w); #endif - glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, - w, h, 0, - GL_RGBA, GL_UNSIGNED_BYTE, pixels); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, + pixels); - return(tex); + return (tex); } - ///////////////////////////// // Draw_Flush // // Performs all the queued draw actions. -void Draw_Flush(){ - if(_currentImg==NULL || _quadArray->nVertex<=0){ +void Draw_Flush() { + if (_currentImg == NULL || _quadArray->nVertex <= 0) { return; } - if(_currentImg->tex==-1){ - _currentImg->tex=Draw_UploadGLTexture(_currentImg->w, _currentImg->h, _currentImg->data); + if (_currentImg->tex == -1) { + _currentImg->tex = Draw_UploadGLTexture(_currentImg->w, _currentImg->h, + _currentImg->data); } #if USE_OpenGL // Draw the quad array glBindTexture(GL_TEXTURE_2D, _currentImg->tex); - glColorPointer( 4, GL_FLOAT, Vertex2D_Length*sizeof(float), - (GLvoid *)(_quadArray->vertexData+4) ); - glTexCoordPointer( 2, GL_FLOAT, Vertex2D_Length*sizeof(float), - (GLvoid *)(_quadArray->vertexData+2) ); - glVertexPointer( 2, GL_FLOAT, Vertex2D_Length*sizeof(float), - (GLvoid *)(_quadArray->vertexData) ); - glDrawArrays(GL_TRIANGLES,0,_quadArray->nVertex); + glColorPointer(4, GL_FLOAT, Vertex2D_Length * sizeof(float), + (GLvoid *)(_quadArray->vertexData + 4)); + glTexCoordPointer(2, GL_FLOAT, Vertex2D_Length * sizeof(float), + (GLvoid *)(_quadArray->vertexData + 2)); + glVertexPointer(2, GL_FLOAT, Vertex2D_Length * sizeof(float), + (GLvoid *)(_quadArray->vertexData)); + glDrawArrays(GL_TRIANGLES, 0, _quadArray->nVertex); #else // Draw the quad array glBindTexture(GL_TEXTURE_2D, _currentImg->tex); glBufferSubData(GL_ARRAY_BUFFER, 0, - Vertex2D_Length*sizeof(float)*_quadArray->nVertex, - _quadArray->vertexData); + Vertex2D_Length * sizeof(float) * _quadArray->nVertex, + _quadArray->vertexData); glDrawArrays(GL_TRIANGLES, 0, _quadArray->nVertex); #endif @@ -400,48 +387,43 @@ void Draw_Flush(){ QuadArray2D_Clean(_quadArray); } - ///////////////////////////// // Draw_Clean // // Cleans the game window. -void Draw_Clean( - unsigned char r, - unsigned char g, - unsigned char b) -{ +void Draw_Clean(unsigned char r, unsigned char g, unsigned char b) { #ifndef EMSCRIPTEN - glClearColor(r/255.0f,g/255.0f,b/255.0f,1.0f); + glClearColor(r / 255.0f, g / 255.0f, b / 255.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); #else Draw_Flush(); - float fr=r/255.0f; - float fg=g/255.0f; - float fb=b/255.0f; + float fr = r / 255.0f; + float fg = g / 255.0f; + float fb = b / 255.0f; GLfloat vVertices[] = { - 0.0, 0.0, // Position 0 - 0.0, 0.0, // TexCoord 0 - fr, fg, fb, 1.0, // Color + 0.0, 0.0, // Position 0 + 0.0, 0.0, // TexCoord 0 + fr, fg, fb, 1.0, // Color - 0.0, _height, // Position 1 - 0.0, 1.0, // TexCoord 1 - fr, fg, fb, 1.0, // Color + 0.0, _height, // Position 1 + 0.0, 1.0, // TexCoord 1 + fr, fg, fb, 1.0, // Color - _width, _height, // Position 2 - 1.0, 1.0, // TexCoord 2 - fr, fg, fb, 1.0, // Color + _width, _height, // Position 2 + 1.0, 1.0, // TexCoord 2 + fr, fg, fb, 1.0, // Color - _width, _height, // Position 2 - 1.0, 1.0, // TexCoord 2 - fr, fg, fb, 1.0, // Color + _width, _height, // Position 2 + 1.0, 1.0, // TexCoord 2 + fr, fg, fb, 1.0, // Color - _width, 0.0, // Position 3 - 1.0, 0.0, // TexCoord 3 - fr, fg, fb, 1.0, // Color + _width, 0.0, // Position 3 + 1.0, 0.0, // TexCoord 3 + fr, fg, fb, 1.0, // Color - 0.0, 0.0, // Position 0 - 0.0, 0.0, // TexCoord 0 - fr, fg, fb, 1.0, // Color + 0.0, 0.0, // Position 0 + 0.0, 0.0, // TexCoord 0 + fr, fg, fb, 1.0, // Color }; glBindTexture(GL_TEXTURE_2D, _whiteTex); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vVertices), vVertices); @@ -449,109 +431,92 @@ void Draw_Clean( #endif } - ///////////////////////////// // Draw_LoopIteration // // One iteracion of the loop updating the game window. -void (*_proc_func)(void *data)=NULL; -void (*_draw_func)(void *data,float f)=NULL; -void *_data=NULL; -int _draw_looping=0; -int _draw_exitoverrided=0; +void (*_proc_func)(void *data) = NULL; +void (*_draw_func)(void *data, float f) = NULL; +void *_data = NULL; +int _draw_looping = 0; +int _draw_exitoverrided = 0; long long _accTime; -int Draw_LoopIteration(){ +int Draw_LoopIteration() { SDL_Event event; - // Process Events +// Process Events #ifdef EMSCRIPTEN - while(SDL_PollEvent(&event) ){ - if(event.type == SDL_QUIT ){ - Input_SetKey(InputKey_Exit,1); + while (SDL_PollEvent(&event)) { + if (event.type == SDL_QUIT) { + Input_SetKey(InputKey_Exit, 1); } - if(event.type == SDL_KEYDOWN ){ - if(event.key.keysym.sym == SDLK_ESCAPE ) { - Input_SetKey(InputKey_Exit,1); + if (event.type == SDL_KEYDOWN) { + if (event.key.keysym.sym == SDLK_ESCAPE) { + Input_SetKey(InputKey_Exit, 1); } } - if(event.type==SDL_MOUSEMOTION){ - Input_SetPointerPosition( - event.motion.x/(float)_width, - event.motion.y/(float)_height); + if (event.type == SDL_MOUSEMOTION) { + Input_SetPointerPosition(event.motion.x / (float)_width, + event.motion.y / (float)_height); } - if(event.type==SDL_MOUSEBUTTONDOWN){ - Input_SetPointerPosition( - event.button.x/(float)_width, - event.button.y/(float)_height); + if (event.type == SDL_MOUSEBUTTONDOWN) { + Input_SetPointerPosition(event.button.x / (float)_width, + event.button.y / (float)_height); Input_SetPointerDown(1); } - if(event.type==SDL_FINGERMOTION){ - Input_SetPointerPosition( - event.tfinger.x, - event.tfinger.y); + if (event.type == SDL_FINGERMOTION) { + Input_SetPointerPosition(event.tfinger.x, event.tfinger.y); } - if(event.type==SDL_FINGERDOWN){ - Input_SetPointerPosition( - event.tfinger.x, - event.tfinger.y); + if (event.type == SDL_FINGERDOWN) { + Input_SetPointerPosition(event.tfinger.x, event.tfinger.y); Input_SetPointerDown(1); } - if(event.type==SDL_TOUCHBUTTONDOWN){ - Input_SetPointerPosition( - event.tfinger.x, - event.tfinger.y); + if (event.type == SDL_TOUCHBUTTONDOWN) { + Input_SetPointerPosition(event.tfinger.x, event.tfinger.y); Input_SetPointerDown(1); } - if(event.type==SDL_MOUSEBUTTONUP){ - Input_SetPointerPosition( - event.button.x/(float)_width, - event.button.y/(float)_height); + if (event.type == SDL_MOUSEBUTTONUP) { + Input_SetPointerPosition(event.button.x / (float)_width, + event.button.y / (float)_height); Input_SetPointerDown(0); } - if(event.type==SDL_FINGERUP){ - Input_SetPointerPosition( - event.tfinger.x, - event.tfinger.y); + if (event.type == SDL_FINGERUP) { + Input_SetPointerPosition(event.tfinger.x, event.tfinger.y); Input_SetPointerDown(0); } - if(event.type==SDL_TOUCHBUTTONUP){ - Input_SetPointerPosition( - event.tfinger.x, - event.tfinger.y); + if (event.type == SDL_TOUCHBUTTONUP) { + Input_SetPointerPosition(event.tfinger.x, event.tfinger.y); Input_SetPointerDown(0); } } #else - while(SDL_PollEvent(&event) ){ - if(event.type == SDL_QUIT ){ - Input_SetKey(InputKey_Exit,1); - if(!_draw_exitoverrided){ - _draw_looping=0; + while (SDL_PollEvent(&event)) { + if (event.type == SDL_QUIT) { + Input_SetKey(InputKey_Exit, 1); + if (!_draw_exitoverrided) { + _draw_looping = 0; } } - if(event.type == SDL_KEYDOWN ){ - if(event.key.keysym.sym == SDLK_ESCAPE ) { - Input_SetKey(InputKey_Exit,1); - if(!_draw_exitoverrided){ - _draw_looping=0; + if (event.type == SDL_KEYDOWN) { + if (event.key.keysym.sym == SDLK_ESCAPE) { + Input_SetKey(InputKey_Exit, 1); + if (!_draw_exitoverrided) { + _draw_looping = 0; } } } - if(event.type==SDL_MOUSEMOTION){ - Input_SetPointerPosition( - event.motion.x/(float)_width, - event.motion.y/(float)_height); + if (event.type == SDL_MOUSEMOTION) { + Input_SetPointerPosition(event.motion.x / (float)_width, + event.motion.y / (float)_height); } - if(event.type==SDL_MOUSEBUTTONDOWN){ - Input_SetPointerPosition( - event.button.x/(float)_width, - event.button.y/(float)_height); + if (event.type == SDL_MOUSEBUTTONDOWN) { + Input_SetPointerPosition(event.button.x / (float)_width, + event.button.y / (float)_height); Input_SetPointerDown(1); } - if(event.type==SDL_MOUSEBUTTONUP){ - Input_SetPointerPosition( - event.button.x/(float)_width, - event.button.y/(float)_height); + if (event.type == SDL_MOUSEBUTTONUP) { + Input_SetPointerPosition(event.button.x / (float)_width, + event.button.y / (float)_height); Input_SetPointerDown(0); } } @@ -559,9 +524,9 @@ int Draw_LoopIteration(){ #ifndef EMSCRIPTEN // Process keys for Draw - Uint8* keys; - keys=(Uint8 *)SDL_GetKeyState(NULL); - if(keys[SDLK_F12]){ + Uint8 *keys; + keys = (Uint8 *)SDL_GetKeyState(NULL); + if (keys[SDLK_F12]) { // Screenshot key char strFile[255]; int idx = -1; @@ -574,14 +539,14 @@ int Draw_LoopIteration(){ #endif // Process - if(_proc_func){ - if(_accTime>100000){ - _accTime=100000; + if (_proc_func) { + if (_accTime > 100000) { + _accTime = 100000; } - while(_accTime>=proc_t_frame && _draw_looping){ + while (_accTime >= proc_t_frame && _draw_looping) { Input_Frame(); _proc_func(_data); - _accTime-=proc_t_frame; + _accTime -= proc_t_frame; Input_PostFrame(); } } @@ -591,8 +556,8 @@ int Draw_LoopIteration(){ // Draw SDL_GL_SwapBuffers(); - if(_draw_func){ - _draw_func(_data, (float)_accTime/(float)proc_t_frame); + if (_draw_func) { + _draw_func(_data, (float)_accTime / (float)proc_t_frame); Draw_Flush(); } @@ -602,13 +567,13 @@ int Draw_LoopIteration(){ #ifdef EMSCRIPTEN long long _procTime1; long long _procTime2; -void Draw_LoopIterationAux(){ +void Draw_LoopIterationAux() { Draw_LoopIteration(); // Update time - _procTime2=Time_GetTime(); - _accTime+=_procTime2-_procTime1; - _procTime1=_procTime2; + _procTime2 = Time_GetTime(); + _accTime += _procTime2 - _procTime1; + _procTime1 = _procTime2; } #endif @@ -616,340 +581,334 @@ void Draw_LoopIterationAux(){ // Draw_Loop // // Loops updating the game window. -void Draw_Loop( - void (*proc)(void *data), - void (*draw)(void *data,float f), - void *data) -{ +void Draw_Loop(void (*proc)(void *data), void (*draw)(void *data, float f), + void *data) { - _proc_func=proc; - _draw_func=draw; - _data=data; - if(_draw_looping){return;} - _draw_looping=1; + _proc_func = proc; + _draw_func = draw; + _data = data; + if (_draw_looping) { + return; + } + _draw_looping = 1; #ifndef EMSCRIPTEN - long long procTime1,procTime2,drawTime1,drawTime2; - _accTime=proc_t_frame; - procTime1=drawTime1=Time_GetTime(); - while(Draw_LoopIteration()){ + long long procTime1, procTime2, drawTime1, drawTime2; + _accTime = proc_t_frame; + procTime1 = drawTime1 = Time_GetTime(); + while (Draw_LoopIteration()) { // Wait to round draw_t_frame - drawTime2=Time_GetTime(); - Time_Pause(draw_t_frame-(drawTime2-drawTime1)); - drawTime2=Time_GetTime(); - drawTime1=drawTime2; + drawTime2 = Time_GetTime(); + Time_Pause(draw_t_frame - (drawTime2 - drawTime1)); + drawTime2 = Time_GetTime(); + drawTime1 = drawTime2; // Update time - procTime2=Time_GetTime(); - _accTime+=procTime2-procTime1; - procTime1=procTime2; + procTime2 = Time_GetTime(); + _accTime += procTime2 - procTime1; + procTime1 = procTime2; } #else - _accTime=proc_t_frame; - _procTime1=Time_GetTime(); - if(_fps<=50){ + _accTime = proc_t_frame; + _procTime1 = Time_GetTime(); + if (_fps <= 50) { emscripten_set_main_loop(Draw_LoopIterationAux, _fps, 1); - }else{ + } else { emscripten_set_main_loop(Draw_LoopIterationAux, 0, 1); } #endif } - ///////////////////////////// // Draw_BreakLoop // // Breaks the drawing loop -void Draw_BreakLoop(){ +void Draw_BreakLoop() { #ifndef EMSCRIPTEN - _draw_looping=0; + _draw_looping = 0; #endif } - ///////////////////////////// // Draw_OverrideExit // // Overrides the default exit mechanism -void Draw_OverrideExit(int override){ - _draw_exitoverrided=override; -} - +void Draw_OverrideExit(int override) { _draw_exitoverrided = override; } ///////////////////////////// // Draw_CreateImage // -DrawImg Draw_CreateImage(int w,int h){ +DrawImg Draw_CreateImage(int w, int h) { DrawImage image; // Create the image container - image=malloc(sizeof(TDrawImage)); - image->data=malloc(w*h*4); - image->x=0; - image->y=0; - image->w=w; - image->h=h; - image->flip=0; - image->tex=-1; + image = malloc(sizeof(TDrawImage)); + image->data = malloc(w * h * 4); + image->x = 0; + image->y = 0; + image->w = w; + image->h = h; + image->flip = 0; + image->tex = -1; - return((DrawImg)image); + return ((DrawImg)image); } - ///////////////////////////// // Draw_LoadImage // // Loads a image, giving a reference. -DrawImg Draw_LoadImage(char *filename){ +DrawImg Draw_LoadImage(char *filename) { DrawImage image; // Try loading PNG images - if(EndsWith(filename,".png") || EndsWith(filename,".PNG")){ - image=malloc(sizeof(TDrawImage)); - unsigned error = lodepng_decode32_file( - &image->data, - (unsigned*)&image->w, - (unsigned*)&image->h, - filename); - if(error){ - Print("Draw_LoadImage: PNG decoder error %u: %s on file %s\n", error, lodepng_error_text(error),filename); - return(NULL); + if (EndsWith(filename, ".png") || EndsWith(filename, ".PNG")) { + image = malloc(sizeof(TDrawImage)); + unsigned error = + lodepng_decode32_file(&image->data, (unsigned *)&image->w, + (unsigned *)&image->h, filename); + if (error) { + Print("Draw_LoadImage: PNG decoder error %u: %s on file %s\n", + error, lodepng_error_text(error), filename); + return (NULL); } - image->x=-(int)(image->w/2); - image->y=-(int)(image->h/2); - image->flip=0; - image->tex=-1; + image->x = -(int)(image->w / 2); + image->y = -(int)(image->h / 2); + image->flip = 0; + image->tex = -1; return (DrawImg)image; } - Print("Draw_LoadImage: Image type not supported: %s\n",filename); - return(NULL); + Print("Draw_LoadImage: Image type not supported: %s\n", filename); + return (NULL); } - ///////////////////////////// // Draw_GetSize // // Gets the image size. -void Draw_GetSize(DrawImg img,int *w,int *h){ - DrawImage image=img; +void Draw_GetSize(DrawImg img, int *w, int *h) { + DrawImage image = img; // Gets the image size - *w=image->w; - *h=image->h; + *w = image->w; + *h = image->h; } - ///////////////////////////// // Draw_SetOffset // Draw_GetOffset // // Sets and Gets the image offset. -void Draw_SetOffset(DrawImg img,int x,int y){ - DrawImage image=img; +void Draw_SetOffset(DrawImg img, int x, int y) { + DrawImage image = img; // Sets the image offset - image->x=x; - image->y=y; + image->x = x; + image->y = y; } -void Draw_GetOffset(DrawImg img,int *x,int *y){ - DrawImage image=img; +void Draw_GetOffset(DrawImg img, int *x, int *y) { + DrawImage image = img; // Gets the image offset - *x=image->x; - *y=image->y; + *x = image->x; + *y = image->y; } - ///////////////////////////// // Draw_SetFlip // Draw_GetFlip // // -void Draw_SetFlip(DrawImg img,int flip){ - DrawImage image=img; - image->flip=flip; +void Draw_SetFlip(DrawImg img, int flip) { + DrawImage image = img; + image->flip = flip; } -int Draw_GetFlip(DrawImg img){ - DrawImage image=img; +int Draw_GetFlip(DrawImg img) { + DrawImage image = img; return image->flip; } - ///////////////////////////// // Draw_DrawImg // // Draws an image. -void Draw_DrawImg(DrawImg img,int x,int y){ - DrawImage image=img; - float x1,x2,y1,y2; - float u1=0.0f,u2=1.0f; - float v1=0.0f,v2=1.0f; +void Draw_DrawImg(DrawImg img, int x, int y) { + DrawImage image = img; + float x1, x2, y1, y2; + float u1 = 0.0f, u2 = 1.0f; + float v1 = 0.0f, v2 = 1.0f; // Prepare - x1=x+image->x; - y1=y+image->y; - x2=(x+image->x)+image->w; - y2=(y+image->y)+image->h; + x1 = x + image->x; + y1 = y + image->y; + x2 = (x + image->x) + image->w; + y2 = (y + image->y) + image->h; // Apply flipping - if(image->flip&1){ - float t=u1; u1=u2; u2=t; + if (image->flip & 1) { + float t = u1; + u1 = u2; + u2 = t; } - if(image->flip&2){ - float t=v1; v1=v2; v2=t; + if (image->flip & 2) { + float t = v1; + v1 = v2; + v2 = t; } // Draw a quad - if(_currentImg!=image){ + if (_currentImg != image) { Draw_Flush(); - _currentImg=image; + _currentImg = image; } - QuadArray2D_AddQuad(_quadArray, - x1,y1,u1,v1, - x2,y2,u2,v2, - _color); + QuadArray2D_AddQuad(_quadArray, x1, y1, u1, v1, x2, y2, u2, v2, _color); } - ///////////////////////////// // Draw_DrawImgResized // // Draws an image, resizing. -void Draw_DrawImgResized(DrawImg img,int x,int y,float w,float h){ - DrawImage image=img; - int x1,x2,y1,y2; - float u1=0.0f,u2=1.0f; - float v1=0.0f,v2=1.0f; +void Draw_DrawImgResized(DrawImg img, int x, int y, float w, float h) { + DrawImage image = img; + int x1, x2, y1, y2; + float u1 = 0.0f, u2 = 1.0f; + float v1 = 0.0f, v2 = 1.0f; // Prepare - x1=x+image->x; - y1=y+image->y; - x2=(x+image->x)+w; - y2=(y+image->y)+h; + x1 = x + image->x; + y1 = y + image->y; + x2 = (x + image->x) + w; + y2 = (y + image->y) + h; // Apply flipping - if(image->flip&1){ - float t=u1; u1=u2; u2=t; + if (image->flip & 1) { + float t = u1; + u1 = u2; + u2 = t; } - if(image->flip&2){ - float t=v1; v1=v2; v2=t; + if (image->flip & 2) { + float t = v1; + v1 = v2; + v2 = t; } // Draw a quad - if(_currentImg!=image){ + if (_currentImg != image) { Draw_Flush(); - _currentImg=image; + _currentImg = image; } - QuadArray2D_AddQuad(_quadArray, - x1,y1,u1,v1, - x2,y2,u2,v2, - _color); + QuadArray2D_AddQuad(_quadArray, x1, y1, u1, v1, x2, y2, u2, v2, _color); } - ///////////////////////////// // Draw_DrawImgPart // // Draws an image part. -void Draw_DrawImgPart(DrawImg img,int x,int y,int w,int h,int i,int j){ - DrawImage image=img; - int x1,x2,y1,y2; - float us,u1,u2; - float vs,v1,v2; +void Draw_DrawImgPart(DrawImg img, int x, int y, int w, int h, int i, int j) { + DrawImage image = img; + int x1, x2, y1, y2; + float us, u1, u2; + float vs, v1, v2; // Prepare - x1=x+image->x; - y1=y+image->y; - x2=(x+image->x)+w; - y2=(y+image->y)+h; - us=1.0f/image->w; - u1=us*i*w; - u2=u1+(us*w); - vs=1.0f/image->h; - v1=vs*j*h; - v2=v1+(vs*h); + x1 = x + image->x; + y1 = y + image->y; + x2 = (x + image->x) + w; + y2 = (y + image->y) + h; + us = 1.0f / image->w; + u1 = us * i * w; + u2 = u1 + (us * w); + vs = 1.0f / image->h; + v1 = vs * j * h; + v2 = v1 + (vs * h); // Apply flipping - if(image->flip&1){ - float t=u1; u1=u2; u2=t; + if (image->flip & 1) { + float t = u1; + u1 = u2; + u2 = t; } - if(image->flip&2){ - float t=v1; v1=v2; v2=t; + if (image->flip & 2) { + float t = v1; + v1 = v2; + v2 = t; } // Draw a quad - if(_currentImg!=image){ + if (_currentImg != image) { Draw_Flush(); - _currentImg=image; + _currentImg = image; } - QuadArray2D_AddQuad(_quadArray, - x1,y1,u1,v1, - x2,y2,u2,v2, - _color); + QuadArray2D_AddQuad(_quadArray, x1, y1, u1, v1, x2, y2, u2, v2, _color); } - ///////////////////////////// // Draw_DrawImgPartHoriz // // Draws an image part horizontally. -void Draw_DrawImgPartHoriz(DrawImg img,int x,int y,int w,int i){ - DrawImage image=img; - int x1,x2,y1,y2; - float us,u1,u2; - float v1=0.0f,v2=1.0f; +void Draw_DrawImgPartHoriz(DrawImg img, int x, int y, int w, int i) { + DrawImage image = img; + int x1, x2, y1, y2; + float us, u1, u2; + float v1 = 0.0f, v2 = 1.0f; // Prepare - x1=x+image->x; - y1=y+image->y; - x2=(x+image->x)+w; - y2=(y+image->y)+image->h; - us=1.0f/image->w; - u1=us*i*w; - u2=u1+us*w; + x1 = x + image->x; + y1 = y + image->y; + x2 = (x + image->x) + w; + y2 = (y + image->y) + image->h; + us = 1.0f / image->w; + u1 = us * i * w; + u2 = u1 + us * w; // Apply flipping - if(image->flip&1){ - float t=u1; u1=u2; u2=t; + if (image->flip & 1) { + float t = u1; + u1 = u2; + u2 = t; } - if(image->flip&2){ - float t=v1; v1=v2; v2=t; + if (image->flip & 2) { + float t = v1; + v1 = v2; + v2 = t; } // Draw a quad - if(_currentImg!=image){ + if (_currentImg != image) { Draw_Flush(); - _currentImg=image; + _currentImg = image; } - QuadArray2D_AddQuad(_quadArray, - x1,y1,u1,v1, - x2,y2,u2,v2, - _color); + QuadArray2D_AddQuad(_quadArray, x1, y1, u1, v1, x2, y2, u2, v2, _color); } - ///////////////////////////// // Draw_ImgParallax // // -void Draw_ImgParallax(DrawImg img, int imgSize[2], int imgOffset[2], float parallaxFactor[2], int gamePos[2], int gameSize[2]){ +void Draw_ImgParallax(DrawImg img, int imgSize[2], int imgOffset[2], + float parallaxFactor[2], int gamePos[2], + int gameSize[2]) { int paralaxPos[2]; int mult[2]; int x, y; - + paralaxPos[0] = (gamePos[0] * parallaxFactor[0]) + imgOffset[0]; paralaxPos[1] = (gamePos[1] * parallaxFactor[1]) + imgOffset[1]; - + mult[0] = floor(paralaxPos[0] / imgSize[0]); - if(paralaxPos[0] < 0 ){ mult[0]--; } + if (paralaxPos[0] < 0) { + mult[0]--; + } mult[1] = floor(paralaxPos[1] / imgSize[1]); - if(paralaxPos[1] < 0 ){ mult[1]--; } - + if (paralaxPos[1] < 0) { + mult[1]--; + } + y = (mult[1] * imgSize[1]) - paralaxPos[1]; - while(y < gameSize[1]){ + while (y < gameSize[1]) { x = (mult[0] * imgSize[0]) - paralaxPos[0]; - while(x < gameSize[0]){ + while (x < gameSize[0]) { Draw_DrawImgResized(img, x, y, imgSize[0], imgSize[1]); x += imgSize[0]; } @@ -957,189 +916,172 @@ void Draw_ImgParallax(DrawImg img, int imgSize[2], int imgOffset[2], float paral } } - ///////////////////////////// // Draw_SetColor // // -void Draw_SetColor(float r,float g,float b,float a){ - _color[0]=r; - _color[1]=g; - _color[2]=b; - _color[3]=a; +void Draw_SetColor(float r, float g, float b, float a) { + _color[0] = r; + _color[1] = g; + _color[2] = b; + _color[3] = a; } - //////////////////////////////////////////////// // DrawFnt // ///////////// // Reference to a Font. typedef struct { DrawImage img; - int w,h; - int min,max; + int w, h; + int min, max; } DrawFont; - ///////////////////////////// // Draw_DefaultImage // // Creates a image with the default font. #include "FontData.h" -DrawImage Draw_DefaultFontImage( - unsigned char r, - unsigned char g, - unsigned char b, - unsigned char a) -{ +DrawImage Draw_DefaultFontImage(unsigned char r, unsigned char g, + unsigned char b, unsigned char a) { DrawImage img; - int x,y,c; + int x, y, c; // Create the image and colors - img=Draw_CreateImage(8*256,8); + img = Draw_CreateImage(8 * 256, 8); // Draw the font - for(c=0;c<256;c++){ - for(y=0;y<8;y++){ - for(x=0;x<8;x++){ - int offset=((c*8+x)+(8*256*y))*4; - img->data[offset+0]=r; - img->data[offset+1]=g; - img->data[offset+2]=b; - if(((fontdata_8x8[c*8+y]>>(7-x)) & 0x01)==1){ - img->data[offset+3]=a; - }else{ - img->data[offset+3]=0x00; + for (c = 0; c < 256; c++) { + for (y = 0; y < 8; y++) { + for (x = 0; x < 8; x++) { + int offset = ((c * 8 + x) + (8 * 256 * y)) * 4; + img->data[offset + 0] = r; + img->data[offset + 1] = g; + img->data[offset + 2] = b; + if (((fontdata_8x8[c * 8 + y] >> (7 - x)) & 0x01) == 1) { + img->data[offset + 3] = a; + } else { + img->data[offset + 3] = 0x00; } } } } - return(img); + return (img); } - ///////////////////////////// // Draw_DefaultFont // // Creates the default font. -DrawFnt Draw_DefaultFont( - unsigned char r, - unsigned char g, - unsigned char b, - unsigned char a) -{ +DrawFnt Draw_DefaultFont(unsigned char r, unsigned char g, unsigned char b, + unsigned char a) { DrawFont *font; // Create the default font - font=malloc(sizeof(DrawFont)); - font->img=Draw_DefaultFontImage(r,g,b,a); - font->w=8; - font->h=8; - font->min=0; - font->max=256; + font = malloc(sizeof(DrawFont)); + font->img = Draw_DefaultFontImage(r, g, b, a); + font->w = 8; + font->h = 8; + font->min = 0; + font->max = 256; - return((DrawFnt)font); + return ((DrawFnt)font); } ///////////////////////////// // Draw_LoadFont // // Load a font from a file. -DrawFnt Draw_LoadFont(char *fichero,int min,int max){ +DrawFnt Draw_LoadFont(char *fichero, int min, int max) { DrawFont *font; // Create the font form the image - font=malloc(sizeof(DrawFont)); - font->img=Draw_LoadImage(fichero); - font->w=font->img->w/(max-min); - font->h=font->img->h; - font->min=min; - font->max=max; + font = malloc(sizeof(DrawFont)); + font->img = Draw_LoadImage(fichero); + font->w = font->img->w / (max - min); + font->h = font->img->h; + font->min = min; + font->max = max; - return((DrawFnt)font); + return ((DrawFnt)font); } - ///////////////////////////// // Draw_DrawText // // Draws text using a font. -void Draw_DrawText(DrawFnt f,char *text,int x,int y){ - DrawFont *font=f; +void Draw_DrawText(DrawFnt f, char *text, int x, int y) { + DrawFont *font = f; char *ptr; // Iterate the string - ptr=text; - while(*ptr){ - if((*ptr)max){ - Draw_DrawImgPartHoriz(font->img,x,y,font->w,(*ptr)-font->min); + ptr = text; + while (*ptr) { + if ((*ptr) < font->max) { + Draw_DrawImgPartHoriz(font->img, x, y, font->w, (*ptr) - font->min); } - x+=font->w; + x += font->w; ptr++; } } - ///////////////////////////// // Draw_SaveScreenshoot // // -void Draw_SaveScreenshoot(char *filename){ +void Draw_SaveScreenshoot(char *filename) { #if USE_OpenGL SDL_Surface *surf; unsigned char *image_line; - int i,half_height,line_size; + int i, half_height, line_size; // Create the surface - surf = SDL_CreateRGBSurface(SDL_SWSURFACE, - _width, _height, 32,0,0,0,0); - surf->format->Amask=0xFF000000; - surf->format->Ashift=24; + surf = SDL_CreateRGBSurface(SDL_SWSURFACE, _width, _height, 32, 0, 0, 0, 0); + surf->format->Amask = 0xFF000000; + surf->format->Ashift = 24; SDL_SetAlpha(surf, SDL_SRCALPHA, 255); // Get the screenshot SDL_LockSurface(surf); - glReadPixels(0, 0, - _width, _height, GL_RGBA, - GL_UNSIGNED_BYTE, surf->pixels); + glReadPixels(0, 0, _width, _height, GL_RGBA, GL_UNSIGNED_BYTE, + surf->pixels); SDL_UnlockSurface(surf); // Flip the image data - line_size=_width*4; - half_height=_height/2; - image_line=malloc(line_size); - for(i=0;ipixels+i*line_size,line_size); - memcpy(surf->pixels+i*line_size,surf->pixels+(_height-(i+1))*line_size,line_size); - memcpy(surf->pixels+(_height-(i+1))*line_size,image_line,line_size); + line_size = _width * 4; + half_height = _height / 2; + image_line = malloc(line_size); + for (i = 0; i < half_height; i++) { + memcpy(image_line, surf->pixels + i * line_size, line_size); + memcpy(surf->pixels + i * line_size, + surf->pixels + (_height - (i + 1)) * line_size, line_size); + memcpy(surf->pixels + (_height - (i + 1)) * line_size, image_line, + line_size); } // Swap RGB to BGR - Uint32 *ptr,*ptr_end; - ptr=(Uint32 *)surf->pixels; - ptr_end=ptr+(surf->w*surf->h); - while (ptrpixels; + ptr_end = ptr + (surf->w * surf->h); + while (ptr < ptr_end) { unsigned char temp; unsigned char *pixel; - pixel=(unsigned char *)ptr; - temp=pixel[2]; - pixel[2]=pixel[0]; - pixel[0]=temp; + pixel = (unsigned char *)ptr; + temp = pixel[2]; + pixel[2] = pixel[0]; + pixel[0] = temp; ptr++; } // Save the image - if(EndsWith(filename,".bmp") || EndsWith(filename,".BMP")){ - SDL_SaveBMP(surf,filename); - }else if(EndsWith(filename,".png") || EndsWith(filename,".PNG")){ - //FIXME: Save PNG + if (EndsWith(filename, ".bmp") || EndsWith(filename, ".BMP")) { + SDL_SaveBMP(surf, filename); + } else if (EndsWith(filename, ".png") || EndsWith(filename, ".PNG")) { + // FIXME: Save PNG } // Cleanup SDL_FreeSurface(surf); #endif } - - - diff --git a/GameLib/Draw.h b/GameLib/Draw.h index 4ce6b41..afd3e2c 100644 --- a/GameLib/Draw.h +++ b/GameLib/Draw.h @@ -3,33 +3,24 @@ #ifndef _DRAW_H_ #define _DRAW_H_ - ///////////////////////////// // Draw_Init // // Initializes the game window. -int Draw_Init(int width,int height,char *title,int pfps,int fps); - +int Draw_Init(int width, int height, char *title, int pfps, int fps); ///////////////////////////// // Draw_Clean // // Cleans the game window. -void Draw_Clean( - unsigned char r, - unsigned char g, - unsigned char b); - +void Draw_Clean(unsigned char r, unsigned char g, unsigned char b); ///////////////////////////// // Draw_Loop // // Loops updating the game window. -void Draw_Loop( - void (*proc)(void *data), - void (*draw)(void *data,float f), - void *data); - +void Draw_Loop(void (*proc)(void *data), void (*draw)(void *data, float f), + void *data); ///////////////////////////// // Draw_BreakLoop @@ -37,33 +28,28 @@ void Draw_Loop( // Breaks the drawing loop void Draw_BreakLoop(); - ///////////////////////////// // Draw_OverrideExit // // Overrides the default exit mechanism void Draw_OverrideExit(int override); - ///////////////////////////// // Draw_Flush // // Performs all the queued draw actions. void Draw_Flush(); - //////////////////////////////////////////////// // DrawImg // ///////////// // Reference to a image. typedef void *DrawImg; - ///////////////////////////// // Draw_CreateImage // -DrawImg Draw_CreateImage(int w,int h); - +DrawImg Draw_CreateImage(int w, int h); ///////////////////////////// // Draw_LoadImage @@ -71,73 +57,64 @@ DrawImg Draw_CreateImage(int w,int h); // Loads a image, giving a reference. DrawImg Draw_LoadImage(char *filename); - ///////////////////////////// // Draw_GetSize // // Gets the image size. -void Draw_GetSize(DrawImg img,int *w,int *h); - +void Draw_GetSize(DrawImg img, int *w, int *h); ///////////////////////////// // Draw_SetOffset // Draw_GetOffset // // Sets and Gets the image offset. -void Draw_SetOffset(DrawImg img,int x,int y); -void Draw_GetOffset(DrawImg img,int *x,int *y); - +void Draw_SetOffset(DrawImg img, int x, int y); +void Draw_GetOffset(DrawImg img, int *x, int *y); ///////////////////////////// // Draw_SetFlip // Draw_GetFlip // // -void Draw_SetFlip(DrawImg img,int flip); +void Draw_SetFlip(DrawImg img, int flip); int Draw_GetFlip(DrawImg img); - ///////////////////////////// // Draw_DrawImg // // Draws an image. -void Draw_DrawImg(DrawImg img,int x,int y); - +void Draw_DrawImg(DrawImg img, int x, int y); ///////////////////////////// // Draw_DrawImgResized // // Draws an image, resizing. -void Draw_DrawImgResized(DrawImg img,int x,int y,float w,float h); - +void Draw_DrawImgResized(DrawImg img, int x, int y, float w, float h); ///////////////////////////// // Draw_DrawImgPart // // 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); ///////////////////////////// // Draw_DrawImgPartHoriz // // 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); ///////////////////////////// // Draw_ImgParallax // // -void Draw_ImgParallax(DrawImg img, int imgSize[2], int imgOffset[2], float parallaxFactor[2], int gamePos[2], int gameSize[2]); - +void Draw_ImgParallax(DrawImg img, int imgSize[2], int imgOffset[2], + float parallaxFactor[2], int gamePos[2], int gameSize[2]); ///////////////////////////// // Draw_SetColor // // -void Draw_SetColor(float r,float g,float b,float a); - +void Draw_SetColor(float r, float g, float b, float a); //////////////////////////////////////////////// // DrawFnt // @@ -145,31 +122,24 @@ void Draw_SetColor(float r,float g,float b,float a); // Reference to a Font. typedef void *DrawFnt; - ///////////////////////////// // Draw_DefaultFont // // Creates the default font. -DrawFnt Draw_DefaultFont( - unsigned char r, - unsigned char g, - unsigned char b, - unsigned char a); - +DrawFnt Draw_DefaultFont(unsigned char r, unsigned char g, unsigned char b, + unsigned char a); ///////////////////////////// // Draw_LoadFont // // Load a font from a file. -DrawFnt Draw_LoadFont(char *fichero,int min,int max); - +DrawFnt Draw_LoadFont(char *fichero, int min, int max); ///////////////////////////// // Draw_DrawText // // Draws text using a font -void Draw_DrawText(DrawFnt f,char *text,int x,int y); - +void Draw_DrawText(DrawFnt f, char *text, int x, int y); ///////////////////////////// // Draw_SaveScreenshoot @@ -177,5 +147,4 @@ void Draw_DrawText(DrawFnt f,char *text,int x,int y); // void Draw_SaveScreenshoot(char *filename); - #endif diff --git a/GameLib/Entity.c b/GameLib/Entity.c index 305c23c..7d46b27 100644 --- a/GameLib/Entity.c +++ b/GameLib/Entity.c @@ -10,21 +10,17 @@ #include "Entity.h" - - #define EntityIntFlag_UpdateLight 1 #define EntityIntFlag_UpdatedPos 2 #define EntityIntFlag_UpdatedColor 4 #define EntityIntFlag_UpdateColor 8 - - ///////////////////////////// // Entity_New // // -Entity _free_entity=NULL; -Entity Entity_New(){ +Entity _free_entity = NULL; +Entity Entity_New() { Entity e; #if 0 @@ -35,1061 +31,993 @@ Entity Entity_New(){ _free_entity=e->next; } #else - if(!_free_entity){ + if (!_free_entity) { // Allocate a big block of entities - int n=1024,i; - TEntity *newEnts=malloc(sizeof(TEntity)*n); - for(i=0;inext; + e = _free_entity; + _free_entity = e->next; #endif - e->base=NULL; - e->type=0; - vec2_set(e->pos0,0.0f,0.0f); - vec2_set(e->pos,0.0f,0.0f); - e->flags=EntityFlag_Collision|EntityFlag_Overlap; - e->internalFlags=EntityIntFlag_UpdateColor; - e->zorder=1; - e->sortYOffset=0; + e->base = NULL; + e->type = 0; + vec2_set(e->pos0, 0.0f, 0.0f); + vec2_set(e->pos, 0.0f, 0.0f); + e->flags = EntityFlag_Collision | EntityFlag_Overlap; + e->internalFlags = EntityIntFlag_UpdateColor; + e->zorder = 1; + 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); - e->radius=1.0f; - e->width=1.0f; - e->height=1.0f; - e->mass=1.0f; - e->elast=0.0f; - e->backFric_static=0.0f; + vec2_set(e->vel, 0.0f, 0.0f); + e->radius = 1.0f; + e->width = 1.0f; + e->height = 1.0f; + e->mass = 1.0f; + e->elast = 0.0f; + e->backFric_static = 0.0f; - e->backFric_dynamic=0.0f; - e->fric_static=0.0f; - e->fric_dynamic=0.0f; + e->backFric_dynamic = 0.0f; + e->fric_static = 0.0f; + e->fric_dynamic = 0.0f; - AnimPlay_SetImg(&e->anim,NULL); + AnimPlay_SetImg(&e->anim, NULL); - e->color0[0]=e->color0[1]=e->color0[2]=e->color0[3]=1.0f; - e->color[0]=e->color[1]=e->color[2]=e->color[3]=1.0f; + e->color0[0] = e->color0[1] = e->color0[2] = e->color0[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->defaultColor[0]=e->defaultColor[1]= - e->defaultColor[2]=e->defaultColor[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[3] = 1.0f; - e->oncopy=NULL; - e->oninit=NULL; - e->ondelete=NULL; - e->proc=NULL; - e->postproc=NULL; - e->collision=NULL; - e->overlap=NULL; + e->oncopy = NULL; + e->oninit = NULL; + e->ondelete = NULL; + e->proc = NULL; + e->postproc = NULL; + e->collision = NULL; + e->overlap = NULL; - e->A=0; - e->B=0; - e->C=0; - e->D=0; - e->child=NULL; + e->A = 0; + e->B = 0; + e->C = 0; + e->D = 0; + e->child = NULL; - e->next=NULL; + e->next = NULL; - return(e); + return (e); } - ///////////////////////////// // Entity_Init // -Entity Entity_Init(Entity e){ - if(e->oninit){ +Entity Entity_Init(Entity e) { + if (e->oninit) { e->oninit(e); } } - ///////////////////////////// // Entity_Destroy // // -void Entity_Destroy(Entity e){ - if(e->ondelete){ +void Entity_Destroy(Entity e) { + if (e->ondelete) { e->ondelete(e); } - e->next=_free_entity; - _free_entity=e; + e->next = _free_entity; + _free_entity = e; } - ///////////////////////////// // Entity_Copy // // -Entity Entity_Copy(Entity e){ +Entity Entity_Copy(Entity e) { Entity n; - n=Entity_New(); + n = Entity_New(); - n->base=e; - n->type=e->type; - vec2_set(n->pos,e->pos[0],e->pos[1]); - n->flags=e->flags; - n->internalFlags=e->internalFlags; - n->zorder=e->zorder; - n->sortYOffset=e->sortYOffset; + n->base = e; + n->type = e->type; + vec2_set(n->pos, e->pos[0], e->pos[1]); + n->flags = e->flags; + n->internalFlags = e->internalFlags; + n->zorder = e->zorder; + n->sortYOffset = e->sortYOffset; - vec2_set(n->vel,e->vel[0],e->vel[1]); - n->radius=e->radius; - n->width=e->width; - n->height=e->height; - n->mass=e->mass; - n->elast=e->elast; - n->backFric_static=e->backFric_static; - n->backFric_dynamic=e->backFric_dynamic; - n->fric_static=e->fric_static; - n->fric_dynamic=e->fric_dynamic; + vec2_set(n->vel, e->vel[0], e->vel[1]); + n->radius = e->radius; + n->width = e->width; + n->height = e->height; + n->mass = e->mass; + n->elast = e->elast; + n->backFric_static = e->backFric_static; + n->backFric_dynamic = e->backFric_dynamic; + n->fric_static = e->fric_static; + n->fric_dynamic = e->fric_dynamic; - AnimPlay_Copy(&n->anim,&e->anim); - n->color0[0]=e->color0[0]; - n->color0[1]=e->color0[1]; - n->color0[2]=e->color0[2]; - n->color0[3]=e->color0[3]; - n->color[0]=e->color[0]; - n->color[1]=e->color[1]; - n->color[2]=e->color[2]; - n->color[3]=e->color[3]; - n->light[0]=e->light[0]; - n->light[1]=e->light[1]; - n->light[2]=e->light[2]; - n->light[3]=e->light[3]; - n->defaultColor[0]=e->defaultColor[0]; - n->defaultColor[1]=e->defaultColor[1]; - n->defaultColor[2]=e->defaultColor[2]; - n->defaultColor[3]=e->defaultColor[3]; + AnimPlay_Copy(&n->anim, &e->anim); + n->color0[0] = e->color0[0]; + n->color0[1] = e->color0[1]; + n->color0[2] = e->color0[2]; + n->color0[3] = e->color0[3]; + n->color[0] = e->color[0]; + n->color[1] = e->color[1]; + n->color[2] = e->color[2]; + n->color[3] = e->color[3]; + n->light[0] = e->light[0]; + n->light[1] = e->light[1]; + n->light[2] = e->light[2]; + n->light[3] = e->light[3]; + n->defaultColor[0] = e->defaultColor[0]; + n->defaultColor[1] = e->defaultColor[1]; + n->defaultColor[2] = e->defaultColor[2]; + n->defaultColor[3] = e->defaultColor[3]; - n->oncopy=e->oncopy; - n->oninit=e->oninit; - n->ondelete=e->ondelete; - n->proc=e->proc; - n->postproc=e->postproc; - n->collision=e->collision; - n->overlap=e->overlap; + n->oncopy = e->oncopy; + n->oninit = e->oninit; + n->ondelete = e->ondelete; + n->proc = e->proc; + n->postproc = e->postproc; + n->collision = e->collision; + n->overlap = e->overlap; - n->A=e->A; - n->B=e->B; - n->C=e->C; - n->D=e->D; - n->child=e->child; + n->A = e->A; + n->B = e->B; + n->C = e->C; + n->D = e->D; + n->child = e->child; Entity_CalcBBox(n); // Call the copy event - if(n->oncopy){ + if (n->oncopy) { n->oncopy(n); } - return(n); + return (n); } - ///////////////////////////// // Entity_CalcBBox // // #define BBox_ExtraMargin 10 -#define max(a,b) ((a)>(b)?(a):(b)) -void Entity_CalcBBox(Entity e){ - float hHeight=(max(e->height,e->radius)/2)+BBox_ExtraMargin; - float hWidth=(max(e->width,e->radius)/2)+BBox_ExtraMargin; - if(e->vel[0]>0){ - e->maxX=e->pos[0]+e->vel[0]+hWidth; - e->minX=e->pos[0]-hWidth; - }else{ - e->minX=(e->pos[0]+e->vel[0])-hWidth; - e->maxX=e->pos[0]+hWidth; +#define max(a, b) ((a) > (b) ? (a) : (b)) +void Entity_CalcBBox(Entity e) { + float hHeight = (max(e->height, e->radius) / 2) + BBox_ExtraMargin; + float hWidth = (max(e->width, e->radius) / 2) + BBox_ExtraMargin; + if (e->vel[0] > 0) { + e->maxX = e->pos[0] + e->vel[0] + hWidth; + e->minX = e->pos[0] - hWidth; + } else { + e->minX = (e->pos[0] + e->vel[0]) - hWidth; + e->maxX = e->pos[0] + hWidth; } - if(e->vel[1]>0){ - e->maxY=e->pos[1]+e->vel[1]+hHeight; - e->minY=e->pos[1]-hHeight; - }else{ - e->minY=(e->pos[1]+e->vel[1])-hHeight; - e->maxY=e->pos[1]+hHeight; + if (e->vel[1] > 0) { + e->maxY = e->pos[1] + e->vel[1] + hHeight; + e->minY = e->pos[1] - hHeight; + } else { + e->minY = (e->pos[1] + e->vel[1]) - hHeight; + e->maxY = e->pos[1] + hHeight; } } - ///////////////////////////// // Entity_BBoxIntersect // // -int Entity_BBoxIntersect(Entity ent1,Entity ent2){ - if( ent1->maxX>=ent2->minX && ent1->minX<=ent2->maxX && - ent1->maxY>=ent2->minY && ent1->minY<=ent2->maxY ) - { - return(1); +int Entity_BBoxIntersect(Entity ent1, Entity ent2) { + if (ent1->maxX >= ent2->minX && ent1->minX <= ent2->maxX && + ent1->maxY >= ent2->minY && ent1->minY <= ent2->maxY) { + return (1); } - return(0); + return (0); } - ///////////////////////////// // Entity_Draw // // -void Entity_Draw(Entity e,int x,int y,float f){ +void Entity_Draw(Entity e, int x, int y, float f) { vec2 fPos; - if(e->internalFlags&EntityIntFlag_UpdatedColor){ - Draw_SetColor( - e->color0[0]-f*(e->color0[0]-e->color[0]), - e->color0[1]-f*(e->color0[1]-e->color[1]), - e->color0[2]-f*(e->color0[2]-e->color[2]), - e->color0[3]-f*(e->color0[3]-e->color[3]) - ); - }else{ - Draw_SetColor(e->color[0],e->color[1],e->color[2],e->color[3]); + if (e->internalFlags & EntityIntFlag_UpdatedColor) { + Draw_SetColor(e->color0[0] - f * (e->color0[0] - e->color[0]), + e->color0[1] - f * (e->color0[1] - e->color[1]), + e->color0[2] - f * (e->color0[2] - e->color[2]), + e->color0[3] - f * (e->color0[3] - e->color[3])); + } else { + Draw_SetColor(e->color[0], e->color[1], e->color[2], e->color[3]); } - if(e->internalFlags&EntityIntFlag_UpdatedPos){ - vec2_interpol(fPos,e->pos0,e->pos,f); - AnimPlay_Draw(&e->anim,fPos[0]+x,fPos[1]+y); - }else{ - AnimPlay_Draw(&e->anim,e->pos[0]+x,e->pos[1]+y); + if (e->internalFlags & EntityIntFlag_UpdatedPos) { + vec2_interpol(fPos, e->pos0, e->pos, f); + AnimPlay_Draw(&e->anim, fPos[0] + x, fPos[1] + y); + } else { + AnimPlay_Draw(&e->anim, e->pos[0] + x, e->pos[1] + y); } } - ///////////////////////////// // Entity_IsVisible // // -int Entity_IsVisible(Entity e,int x,int y,int w,int h){ - int xmax,xmin; - int ymax,ymin; - int ih,iw; +int Entity_IsVisible(Entity e, int x, int y, int w, int h) { + int xmax, xmin; + int ymax, ymin; + int ih, iw; - AnimPlay_GetSize(&e->anim,&iw,&ih); + AnimPlay_GetSize(&e->anim, &iw, &ih); - xmin=x-iw; - xmax=x+w+iw; - ymin=y-ih; - ymax=y+h+ih; + xmin = x - iw; + xmax = x + w + iw; + ymin = y - ih; + ymax = y + h + ih; - if(e->pos[0]pos[0]>xmax || - e->pos[1]pos[1]>ymax) - { - return(0); + if (e->pos[0] < xmin || e->pos[0] > xmax || e->pos[1] < ymin || + e->pos[1] > ymax) { + return (0); } - return(1); + return (1); } - - ///////////////////////////// // Entity_Process // // -void Entity_Process(Entity b,int ft){ - b->internalFlags&=~EntityIntFlag_UpdatedPos; +void Entity_Process(Entity b, int ft) { + b->internalFlags &= ~EntityIntFlag_UpdatedPos; // Launch method - if(b->proc){ - b->proc(b,ft); + if (b->proc) { + b->proc(b, ft); } } - ///////////////////////////// // Entity_PostProcess // // -void Entity_PostProcess(Entity e,int ft){ - float qlen,len; +void Entity_PostProcess(Entity e, int ft) { + float qlen, len; - vec2_copy(e->pos0,e->pos); + vec2_copy(e->pos0, e->pos); - e->color0[0]=e->color[0]; - e->color0[1]=e->color[1]; - e->color0[2]=e->color[2]; - e->color0[3]=e->color[3]; - e->internalFlags&=~EntityIntFlag_UpdatedColor; + e->color0[0] = e->color[0]; + e->color0[1] = e->color[1]; + e->color0[2] = e->color[2]; + e->color0[3] = e->color[3]; + e->internalFlags &= ~EntityIntFlag_UpdatedColor; // Determine if there is movement - qlen=vec2_dot(e->vel,e->vel); - if(qlen>0.0f){ + qlen = vec2_dot(e->vel, e->vel); + if (qlen > 0.0f) { // Update position - vec2_plus(e->pos,e->pos,e->vel); + vec2_plus(e->pos, e->pos, e->vel); // Apply friction - len=sqrtf(qlen); - if(lenbackFric_static){ + len = sqrtf(qlen); + if (len < e->backFric_static) { // Stopped by static friction - vec2_set(e->vel,0,0); - }else{ + vec2_set(e->vel, 0, 0); + } else { // Apply dynamic friction - vec2_scale(e->vel,e->vel, - 1.0f-(e->backFric_dynamic+(e->backFric_static/len))); + vec2_scale(e->vel, e->vel, 1.0f - (e->backFric_dynamic + + (e->backFric_static / len))); } // Mark the update of the position. - vec2_copy(e->oldpos,e->pos); - e->internalFlags|=EntityIntFlag_UpdatedPos; + vec2_copy(e->oldpos, e->pos); + e->internalFlags |= EntityIntFlag_UpdatedPos; Entity_CalcBBox(e); } // Launch method - if(e->postproc){ - e->postproc(e,ft); + if (e->postproc) { + e->postproc(e, ft); } // Animate - AnimPlay_IncTime(&e->anim,ft); + AnimPlay_IncTime(&e->anim, ft); } - ///////////////////////////// // CollisionInfo_New // // -CollisionInfo _free_collInfo=NULL; -CollisionInfo CollisionInfo_New(int responseType,Entity ent1,Entity ent2,float t,vec2 n,int applyFriction){ +CollisionInfo _free_collInfo = NULL; +CollisionInfo CollisionInfo_New(int responseType, Entity ent1, Entity ent2, + float t, vec2 n, int applyFriction) { CollisionInfo collInfo; - if(!_free_collInfo){ - collInfo=malloc(sizeof(TCollisionInfo)); - }else{ - collInfo=_free_collInfo; - _free_collInfo=collInfo->next; + if (!_free_collInfo) { + collInfo = malloc(sizeof(TCollisionInfo)); + } else { + collInfo = _free_collInfo; + _free_collInfo = collInfo->next; } - collInfo->next=NULL; + collInfo->next = NULL; - collInfo->responseType=responseType; - collInfo->ent1=ent1; - collInfo->ent2=ent2; - collInfo->t=t; - vec2_copy(collInfo->n,n); - collInfo->applyFriction=applyFriction; + collInfo->responseType = responseType; + collInfo->ent1 = ent1; + collInfo->ent2 = ent2; + collInfo->t = t; + vec2_copy(collInfo->n, n); + collInfo->applyFriction = applyFriction; return collInfo; } - ///////////////////////////// // CollisionInfo_Destroy // // -void CollisionInfo_Destroy(CollisionInfo *collInfoRef){ - if(collInfoRef==NULL || collInfoRef[0]==NULL){return;} - - CollisionInfo collInfo=collInfoRef[0]; - CollisionInfo nextCollInfo; - while(collInfo!=NULL){ - nextCollInfo=collInfo->next; - collInfo->next=_free_collInfo; - _free_collInfo=collInfo; - collInfo=nextCollInfo; +void CollisionInfo_Destroy(CollisionInfo *collInfoRef) { + if (collInfoRef == NULL || collInfoRef[0] == NULL) { + return; } - collInfoRef[0]=NULL; -} + CollisionInfo collInfo = collInfoRef[0]; + CollisionInfo nextCollInfo; + while (collInfo != NULL) { + nextCollInfo = collInfo->next; + collInfo->next = _free_collInfo; + _free_collInfo = collInfo; + collInfo = nextCollInfo; + } + collInfoRef[0] = NULL; +} ///////////////////////////// // CollisionInfo_Add // // -void CollisionInfo_Add(CollisionInfo *collInfoRef, - int responseType,Entity ent1,Entity ent2,float t,vec2 n,int applyFriction) -{ - if(collInfoRef==NULL){return;} - CollisionInfo prevCollInfo=NULL; - CollisionInfo collInfo=collInfoRef[0]; - CollisionInfo newCollInfo=CollisionInfo_New(responseType,ent1,ent2,t,n,applyFriction); +void CollisionInfo_Add(CollisionInfo *collInfoRef, int responseType, + Entity ent1, Entity ent2, float t, vec2 n, + int applyFriction) { + if (collInfoRef == NULL) { + return; + } + CollisionInfo prevCollInfo = NULL; + CollisionInfo collInfo = collInfoRef[0]; + CollisionInfo newCollInfo = + CollisionInfo_New(responseType, ent1, ent2, t, n, applyFriction); - while(collInfo!=NULL && collInfo->tnext; + while (collInfo != NULL && collInfo->t < t) { + prevCollInfo = collInfo; + collInfo = collInfo->next; } - if(prevCollInfo==NULL){ - collInfoRef[0]=newCollInfo; - }else{ - prevCollInfo->next=newCollInfo; + if (prevCollInfo == NULL) { + collInfoRef[0] = newCollInfo; + } else { + prevCollInfo->next = newCollInfo; } - newCollInfo->next=collInfo; + newCollInfo->next = collInfo; } - ///////////////////////////// // CollisionInfo_CheckRepetition // // -int CollisionInfo_CheckRepetition(CollisionInfo collInfo,Entity ent1,Entity ent2) -{ - while(collInfo!=NULL){ - if((collInfo->ent1==ent1 && collInfo->ent2==ent2) || - (collInfo->ent1==ent2 && collInfo->ent2==ent1)) - { - return(1); +int CollisionInfo_CheckRepetition(CollisionInfo collInfo, Entity ent1, + Entity ent2) { + while (collInfo != NULL) { + if ((collInfo->ent1 == ent1 && collInfo->ent2 == ent2) || + (collInfo->ent1 == ent2 && collInfo->ent2 == ent1)) { + return (1); } - collInfo=collInfo->next; + collInfo = collInfo->next; } - return(0); + return (0); } - ///////////////////////////// // Entity_CheckCollisions // // -int Entity_CheckCollision(Entity ent1,Entity ent2,CollisionInfo *collInfoRef){ +int Entity_CheckCollision(Entity ent1, Entity ent2, + CollisionInfo *collInfoRef) { float t; vec2 n; vec2 vel; - int flags=ent1->flags|ent2->flags; + int flags = ent1->flags | ent2->flags; - - if(flags&EntityFlag_Block ){ + if (flags & EntityFlag_Block) { // One of the entities is a block and none is a platform - Entity ent,ent_block; - float auxT,block_len; - vec2 auxN,p; + Entity ent, ent_block; + float auxT, block_len; + vec2 auxN, p; int applyFriction; // Decide who is the block and who is the ent - if(ent1->mass<=0.0f && ent2->mass>0.0f){ - ent=ent2; - ent_block=ent1; - }else - if(ent2->mass<=0.0f && ent1->mass>0.0f){ - ent=ent1; - ent_block=ent2; - }else{ + if (ent1->mass <= 0.0f && ent2->mass > 0.0f) { + ent = ent2; + ent_block = ent1; + } else if (ent2->mass <= 0.0f && ent1->mass > 0.0f) { + ent = ent1; + ent_block = ent2; + } else { // Two static or two dinamic entities?!? - return(0); + return (0); } // Prepare some variables - t=1.0f; - applyFriction=1; + t = 1.0f; + applyFriction = 1; - if(flags&EntityFlag_BlockTop){ - vec2_set(auxN,0,-1); - vec2_scaleadd(p,ent_block->pos,auxN,(ent->height+ent_block->height)/2); - block_len=ent_block->width+ent->width; - if(Intersect_RayEdge(ent->pos,ent->vel, - auxN,p,block_len,&auxT)) - { - if(auxTpos, auxN, + (ent->height + ent_block->height) / 2); + block_len = ent_block->width + ent->width; + if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, + &auxT)) { + if (auxT < t) { + vec2_copy(n, auxN); + t = auxT; + applyFriction = 1; } } } - if(flags&EntityFlag_BlockBottom){ - vec2_set(auxN,0,1); - vec2_scaleadd(p,ent_block->pos,auxN,(ent->height+ent_block->height)/2); - block_len=ent_block->width+ent->width; - if(Intersect_RayEdge(ent->pos,ent->vel, - auxN,p,block_len,&auxT)) - { - if(auxTpos, auxN, + (ent->height + ent_block->height) / 2); + block_len = ent_block->width + ent->width; + if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, + &auxT)) { + if (auxT < t) { + vec2_copy(n, auxN); + t = auxT; + applyFriction = 1; } } } - if(flags&EntityFlag_BlockRight){ - vec2_set(auxN,1,0); - vec2_scaleadd(p,ent_block->pos,auxN,(ent->width+ent_block->width)/2); - block_len=ent_block->height+ent->height; - if(Intersect_RayEdge(ent->pos,ent->vel, - auxN,p,block_len,&auxT)) - { - if(auxTpos, auxN, + (ent->width + ent_block->width) / 2); + block_len = ent_block->height + ent->height; + if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, + &auxT)) { + if (auxT < t) { + vec2_copy(n, auxN); + t = auxT; + applyFriction = 0; } } } - if(flags&EntityFlag_BlockLeft){ - vec2_set(auxN,-1,0); - vec2_scaleadd(p,ent_block->pos,auxN,(ent->width+ent_block->width)/2); - block_len=ent_block->height+ent->height; - if(Intersect_RayEdge(ent->pos,ent->vel, - auxN,p,block_len,&auxT)) - { - if(auxTpos, auxN, + (ent->width + ent_block->width) / 2); + block_len = ent_block->height + ent->height; + if (Intersect_RayEdge(ent->pos, ent->vel, auxN, p, block_len, + &auxT)) { + if (auxT < t) { + vec2_copy(n, auxN); + t = auxT; + applyFriction = 0; } } } - if(t<1.0f){ - CollisionInfo_Add(collInfoRef, - CollisionResponse_Line,ent,ent_block,t,n,applyFriction); - return(1); + if (t < 1.0f) { + CollisionInfo_Add(collInfoRef, CollisionResponse_Line, ent, + ent_block, t, n, applyFriction); + return (1); } - return(0); + return (0); } // Circle-Circle test from ent1 - vec2_minus(vel,ent1->vel,ent2->vel); - if(Colision_CircleCircle(ent1->pos,ent1->radius,vel,ent2->pos,ent2->radius,&t,n)){ - CollisionInfo_Add(collInfoRef, - CollisionResponse_Circle,ent1,ent2,t,n,0); - return(1); + vec2_minus(vel, ent1->vel, ent2->vel); + if (Colision_CircleCircle(ent1->pos, ent1->radius, vel, ent2->pos, + ent2->radius, &t, n)) { + CollisionInfo_Add(collInfoRef, CollisionResponse_Circle, ent1, ent2, t, + n, 0); + return (1); } - return(0); + return (0); } - ///////////////////////////// // Entity_CollisionResponseCircle // // Normal response to a collision between circles. -void Entity_CollisionResponseCircle( - Entity b1,Entity b2,float t,vec2 n) -{ +void Entity_CollisionResponseCircle(Entity b1, Entity b2, float t, vec2 n) { float moment; vec2 temp; float elast; - if(b1->mass>0.0f && b2->mass>0.0f){ + if (b1->mass > 0.0f && b2->mass > 0.0f) { // Calculate elasticity - elast=(b1->mass*b1->elast+b2->mass*b2->elast)/ - (b1->mass+b2->mass); + elast = (b1->mass * b1->elast + b2->mass * b2->elast) / + (b1->mass + b2->mass); // Collision between two massed balls - moment=((1.0f+elast)*b1->mass*b2->mass* - (fabs(vec2_dot(b1->vel,n))+fabs(vec2_dot(b2->vel,n)))) - /(b1->mass+b2->mass); - vec2_scale(temp,n,moment/b1->mass); - vec2_minus(b1->vel,b1->vel,temp); + moment = ((1.0f + elast) * b1->mass * b2->mass * + (fabs(vec2_dot(b1->vel, n)) + fabs(vec2_dot(b2->vel, n)))) / + (b1->mass + b2->mass); + vec2_scale(temp, n, moment / b1->mass); + vec2_minus(b1->vel, b1->vel, temp); Entity_CalcBBox(b1); - vec2_scale(temp,n,moment/b2->mass); - vec2_plus(b2->vel,b2->vel,temp); + vec2_scale(temp, n, moment / b2->mass); + vec2_plus(b2->vel, b2->vel, temp); Entity_CalcBBox(b2); - }else - if(b1->mass>0.0f && b2->mass<=0.0f){ + } else if (b1->mass > 0.0f && b2->mass <= 0.0f) { // Collision between a massed ball and a fixed ball - moment=(1.0f+b1->elast)* - (vec2_dot(b1->vel,n)); - vec2_scale(temp,n,moment); - vec2_minus(b1->vel,b1->vel,temp); + moment = (1.0f + b1->elast) * (vec2_dot(b1->vel, n)); + vec2_scale(temp, n, moment); + vec2_minus(b1->vel, b1->vel, temp); Entity_CalcBBox(b1); - }else - if(b1->mass<=0.0f && b2->mass>0.0f){ + } else if (b1->mass <= 0.0f && b2->mass > 0.0f) { // Collision between a massed ball and a fixed ball // (imposible, but better safe) - moment=(1.0f+b2->elast)* - (vec2_dot(b2->vel,n)); - vec2_scale(temp,n,moment); - vec2_plus(b2->vel,b2->vel,temp); + moment = (1.0f + b2->elast) * (vec2_dot(b2->vel, n)); + vec2_scale(temp, n, moment); + vec2_plus(b2->vel, b2->vel, temp); Entity_CalcBBox(b2); - }else{ + } else { // Collision between 2 fixed balls // (imposible, but better safe) - vec2_set(b1->vel,0,0); + vec2_set(b1->vel, 0, 0); Entity_CalcBBox(b1); - vec2_set(b2->vel,0,0); + vec2_set(b2->vel, 0, 0); Entity_CalcBBox(b2); } } - ///////////////////////////// // Entity_CollisionResponseLine // // Normal response to a collision with a line. -void Entity_CollisionResponseLine( - Entity ent,Entity ent2,float t,vec2 norm,int applyFriction) -{ - vec2 pos2,vel2,velFric,intersection; - float dist,fric_static,fric_dynamic,fricLen; +void Entity_CollisionResponseLine(Entity ent, Entity ent2, float t, vec2 norm, + int applyFriction) { + vec2 pos2, vel2, velFric, intersection; + float dist, fric_static, fric_dynamic, fricLen; // Calculate end position - vec2_scale(vel2,ent->vel,1.0f-t); - dist=-vec2_dot(norm,vel2); - vec2_plus(pos2,ent->pos,ent->vel); - vec2_scaleadd(pos2,pos2,norm,dist); + vec2_scale(vel2, ent->vel, 1.0f - t); + dist = -vec2_dot(norm, vel2); + vec2_plus(pos2, ent->pos, ent->vel); + vec2_scaleadd(pos2, pos2, norm, dist); // Calculate intersection - vec2_scaleadd(intersection,ent->pos,ent->vel,t); + vec2_scaleadd(intersection, ent->pos, ent->vel, t); - if(applyFriction){ + if (applyFriction) { // Calculate friction - fric_static=(ent->fric_static+ent2->fric_static)/2; - fric_dynamic=(ent->fric_dynamic+ent2->fric_dynamic)/2; + fric_static = (ent->fric_static + ent2->fric_static) / 2; + fric_dynamic = (ent->fric_dynamic + ent2->fric_dynamic) / 2; // Apply friction - vec2_minus(velFric,pos2,intersection); - fricLen=sqrtf(vec2_dot(velFric,velFric)); - if(fricLen0.0f){ - vec2_scaleadd(pos2,intersection,velFric, - 1.0f-(fric_dynamic+(fric_static/fricLen))); - }else{ - vec2_scaleadd(pos2,intersection,velFric, - 1.0f-fric_dynamic); + if (fricLen > 0.0f) { + vec2_scaleadd(pos2, intersection, velFric, + 1.0f - (fric_dynamic + (fric_static / fricLen))); + } else { + vec2_scaleadd(pos2, intersection, velFric, 1.0f - fric_dynamic); } } } // Apply to velocity - vec2_scaleadd(pos2,pos2,norm,0.1f); - vec2_minus(ent->vel,pos2,ent->pos); + vec2_scaleadd(pos2, pos2, norm, 0.1f); + vec2_minus(ent->vel, pos2, ent->pos); Entity_CalcBBox(ent); } - ///////////////////////////// // Entity_CollisionInfoResponse // // -int Entity_CollisionInfoResponse(CollisionInfo collInfo){ - while(collInfo!=NULL){ +int Entity_CollisionInfoResponse(CollisionInfo collInfo) { + while (collInfo != NULL) { // Handle colision - int response=1; + int response = 1; int rc; vec2 n1; vec2 n2; - vec2_copy(n1,collInfo->n); - vec2_scale(n2,collInfo->n,-1.0f); + vec2_copy(n1, collInfo->n); + vec2_scale(n2, collInfo->n, -1.0f); // Check the collision methods - if(collInfo->ent1->collision){ - rc=collInfo->ent1->collision(collInfo->ent1,collInfo->ent2,collInfo->t,n1); - if (rc==0) - response=0; - if (rc>1) - response=2; + if (collInfo->ent1->collision) { + rc = collInfo->ent1->collision(collInfo->ent1, collInfo->ent2, + collInfo->t, n1); + if (rc == 0) + response = 0; + if (rc > 1) + response = 2; } - if(collInfo->ent2->collision){ - rc=collInfo->ent2->collision(collInfo->ent2,collInfo->ent1,collInfo->t,n2); - if (rc==0) - response=0; - if (rc>1) - response=2; + if (collInfo->ent2->collision) { + rc = collInfo->ent2->collision(collInfo->ent2, collInfo->ent1, + collInfo->t, n2); + if (rc == 0) + response = 0; + if (rc > 1) + response = 2; } // Collision response - if(response==1){ - if(collInfo->responseType==CollisionResponse_Line){ - Entity_CollisionResponseLine( - collInfo->ent1,collInfo->ent2,collInfo->t,collInfo->n,collInfo->applyFriction); - }else - if(collInfo->responseType==CollisionResponse_Circle){ - if(vec2_dot(collInfo->ent1->vel,collInfo->ent1->vel)> - vec2_dot(collInfo->ent2->vel,collInfo->ent2->vel)) - { - Entity_CollisionResponseCircle(collInfo->ent1,collInfo->ent2,collInfo->t,n2); - }else{ - Entity_CollisionResponseCircle(collInfo->ent2,collInfo->ent1,collInfo->t,n1); + if (response == 1) { + if (collInfo->responseType == CollisionResponse_Line) { + Entity_CollisionResponseLine(collInfo->ent1, collInfo->ent2, + collInfo->t, collInfo->n, + collInfo->applyFriction); + } else if (collInfo->responseType == CollisionResponse_Circle) { + if (vec2_dot(collInfo->ent1->vel, collInfo->ent1->vel) > + vec2_dot(collInfo->ent2->vel, collInfo->ent2->vel)) { + Entity_CollisionResponseCircle( + collInfo->ent1, collInfo->ent2, collInfo->t, n2); + } else { + Entity_CollisionResponseCircle( + collInfo->ent2, collInfo->ent1, collInfo->t, n1); } } - return(1); + return (1); } - if (response==2) { - return(1); + if (response == 2) { + return (1); } - collInfo=collInfo->next; + collInfo = collInfo->next; } - return(0); + return (0); } - ///////////////////////////// // Entity_Overlaps // // -void Entity_Overlaps(Entity b1,Entity b2){ +void Entity_Overlaps(Entity b1, Entity b2) { vec2 len; - vec2_minus(len,b1->pos,b2->pos); + vec2_minus(len, b1->pos, b2->pos); - vec2_set(len,fabs(b1->pos[0]-b2->pos[0]),fabs(b1->pos[1]-b2->pos[1])); - if(b1->overlap){ - if( len[0]<=b1->radius && - len[1]<=b1->radius) - { - b1->overlap(b1,b2); + vec2_set(len, fabs(b1->pos[0] - b2->pos[0]), fabs(b1->pos[1] - b2->pos[1])); + if (b1->overlap) { + if (len[0] <= b1->radius && len[1] <= b1->radius) { + b1->overlap(b1, b2); } } - if(b2->overlap){ - if( len[0]<=b2->radius && - len[1]<=b2->radius) - { - b2->overlap(b2,b1); + if (b2->overlap) { + if (len[0] <= b2->radius && len[1] <= b2->radius) { + b2->overlap(b2, b1); } } } - ///////////////////////////// // Entity_GetPos // // -void Entity_GetPos(Entity e,vec2 pos){ - vec2_copy(pos,e->pos); -} - +void Entity_GetPos(Entity e, vec2 pos) { vec2_copy(pos, e->pos); } ///////////////////////////// // Entity_SetPos // // -void Entity_SetPos(Entity e,vec2 pos){ - vec2_copy(e->pos,pos); - vec2_copy(e->oldpos,pos); - vec2_copy(e->pos0,pos); +void Entity_SetPos(Entity e, vec2 pos) { + vec2_copy(e->pos, pos); + vec2_copy(e->oldpos, pos); + vec2_copy(e->pos0, pos); Entity_CalcBBox(e); } - ///////////////////////////// // Entity_AddPos // // -void Entity_AddPos(Entity e,vec2 pos){ - vec2_plus(e->pos,e->pos,pos); - vec2_copy(e->oldpos,e->pos); - vec2_copy(e->pos0,e->pos); +void Entity_AddPos(Entity e, vec2 pos) { + vec2_plus(e->pos, e->pos, pos); + vec2_copy(e->oldpos, e->pos); + vec2_copy(e->pos0, e->pos); Entity_CalcBBox(e); } - ///////////////////////////// // Entity_UpdatePos // // -void Entity_UpdatePos(Entity e,vec2 pos){ +void Entity_UpdatePos(Entity e, vec2 pos) { // Mark the update of the position. - vec2_copy(e->oldpos,e->pos); - e->internalFlags|=EntityIntFlag_UpdatedPos; + vec2_copy(e->oldpos, e->pos); + e->internalFlags |= EntityIntFlag_UpdatedPos; - vec2_copy(e->pos,pos); + vec2_copy(e->pos, pos); } - ///////////////////////////// // Entity_AddVel // -void Entity_AddVel(Entity e,vec2 vel){ - vec2_plus(e->vel,e->vel,vel); +void Entity_AddVel(Entity e, vec2 vel) { + vec2_plus(e->vel, e->vel, vel); Entity_CalcBBox(e); } - ///////////////////////////// // Entity_SetVel // -void Entity_SetVel(Entity e,vec2 vel){ - vec2_copy(e->vel,vel); +void Entity_SetVel(Entity e, vec2 vel) { + vec2_copy(e->vel, vel); Entity_CalcBBox(e); } - ///////////////////////////// // Entity_SetVelH // -void Entity_SetVelH(Entity e,float v){ - e->vel[0]=v; +void Entity_SetVelH(Entity e, float v) { + e->vel[0] = v; Entity_CalcBBox(e); } - ///////////////////////////// // Entity_SetVelV // -void Entity_SetVelV(Entity e,float v){ - e->vel[1]=v; +void Entity_SetVelV(Entity e, float v) { + e->vel[1] = v; Entity_CalcBBox(e); } - ///////////////////////////// // Entity_AddVelLimit // // -void Entity_AddVelLimit(Entity e,vec2 vel,float limit){ - float vlen_orig,vlen; - vec2 dir,vel_temp; +void Entity_AddVelLimit(Entity e, vec2 vel, float limit) { + float vlen_orig, vlen; + vec2 dir, vel_temp; // Normalize vel getting vel - vlen_orig=sqrtf(vec2_dot(vel,vel)); - vec2_scale(dir,vel,1.0f/vlen_orig); + vlen_orig = sqrtf(vec2_dot(vel, vel)); + vec2_scale(dir, vel, 1.0f / vlen_orig); // Limit velocity - vlen=vec2_dot(e->vel,dir); - if(vlenvlen_orig){ - vlen=vlen_orig; + vlen = vec2_dot(e->vel, dir); + if (vlen < limit) { + vlen = limit - vlen; + if (vlen > vlen_orig) { + vlen = vlen_orig; } - vec2_scale(vel_temp,dir,vlen); - vec2_plus(e->vel,e->vel,vel_temp); + vec2_scale(vel_temp, dir, vlen); + vec2_plus(e->vel, e->vel, vel_temp); } Entity_CalcBBox(e); } - ///////////////////////////// // Entity_AddVelLimitH // -void Entity_AddVelLimitH(Entity e,float v,float limit){ - e->vel[0]+=v; - if(e->vel[0]>0.0f){ - if(e->vel[0]>limit){ - e->vel[0]=limit; +void Entity_AddVelLimitH(Entity e, float v, float limit) { + e->vel[0] += v; + if (e->vel[0] > 0.0f) { + if (e->vel[0] > limit) { + e->vel[0] = limit; } - }else{ - if(e->vel[0]<-limit){ - e->vel[0]=-limit; + } else { + if (e->vel[0] < -limit) { + e->vel[0] = -limit; } } Entity_CalcBBox(e); } - ///////////////////////////// // Entity_AddVelLimitH // -void Entity_AddVelLimitV(Entity e,float v,float limit){ - e->vel[1]+=v; - if(e->vel[1]>0.0f){ - if(e->vel[1]>limit){ - e->vel[1]=limit; +void Entity_AddVelLimitV(Entity e, float v, float limit) { + e->vel[1] += v; + if (e->vel[1] > 0.0f) { + if (e->vel[1] > limit) { + e->vel[1] = limit; } - }else{ - if(e->vel[1]<-limit){ - e->vel[1]=-limit; + } else { + if (e->vel[1] < -limit) { + e->vel[1] = -limit; } } Entity_CalcBBox(e); } - ///////////////////////////// // Entity_SetColor // // -void Entity_SetColor(Entity e,float r,float g,float b,float a){ - e->color[0]=r; - e->color[1]=g; - e->color[2]=b; - e->color[3]=a; - e->color0[0]=r; - e->color0[1]=g; - e->color0[2]=b; - e->color0[3]=a; - e->internalFlags&=~EntityIntFlag_UpdatedColor; +void Entity_SetColor(Entity e, float r, float g, float b, float a) { + e->color[0] = r; + e->color[1] = g; + e->color[2] = b; + e->color[3] = a; + e->color0[0] = r; + e->color0[1] = g; + e->color0[2] = b; + e->color0[3] = a; + e->internalFlags &= ~EntityIntFlag_UpdatedColor; } - ///////////////////////////// // Entity_AddColor // // -void Entity_AddColor(Entity e,float r,float g,float b,float a){ - e->color[0]+=r; - if(e->color[0]>1.0f) - e->color[0]=1.0f; - e->color[1]+=g; - if(e->color[1]>1.0f) - e->color[1]=1.0f; - e->color[2]+=b; - if(e->color[2]>1.0f) - e->color[2]=1.0f; - e->color[3]+=a; - if(e->color[3]>1.0f) - e->color[3]=1.0f; - e->internalFlags|=EntityIntFlag_UpdatedColor; +void Entity_AddColor(Entity e, float r, float g, float b, float a) { + e->color[0] += r; + if (e->color[0] > 1.0f) + e->color[0] = 1.0f; + e->color[1] += g; + if (e->color[1] > 1.0f) + e->color[1] = 1.0f; + e->color[2] += b; + if (e->color[2] > 1.0f) + e->color[2] = 1.0f; + e->color[3] += a; + if (e->color[3] > 1.0f) + e->color[3] = 1.0f; + e->internalFlags |= EntityIntFlag_UpdatedColor; } ///////////////////////////// // Entity_MultColor // // -void Entity_MultColor(Entity e,float r,float g,float b,float a){ - e->color[0]*=r; - e->color[1]*=g; - e->color[2]*=b; - e->color[3]*=a; - e->internalFlags|=EntityIntFlag_UpdatedColor; +void Entity_MultColor(Entity e, float r, float g, float b, float a) { + e->color[0] *= r; + e->color[1] *= g; + e->color[2] *= b; + e->color[3] *= a; + e->internalFlags |= EntityIntFlag_UpdatedColor; } - ///////////////////////////// // Entity_SetLight // // -void Entity_SetLight(Entity e,float r,float g,float b,float rad){ - e->light[0]=r; - e->light[1]=g; - e->light[2]=b; - e->light[3]=rad; +void Entity_SetLight(Entity e, float r, float g, float b, float rad) { + e->light[0] = r; + e->light[1] = g; + e->light[2] = b; + e->light[3] = rad; - if(!(e->flags&EntityFlag_Light)){ - e->internalFlags|=EntityIntFlag_UpdateLight; + if (!(e->flags & EntityFlag_Light)) { + e->internalFlags |= EntityIntFlag_UpdateLight; } } - ///////////////////////////// // Entity_SetDefaultColor // // -void Entity_SetDefaultColor(Entity e,float r,float g,float b,float a){ - e->defaultColor[0]=r; - e->defaultColor[1]=g; - e->defaultColor[2]=b; - e->defaultColor[3]=a; +void Entity_SetDefaultColor(Entity e, float r, float g, float b, float a) { + e->defaultColor[0] = r; + e->defaultColor[1] = g; + e->defaultColor[2] = b; + e->defaultColor[3] = a; } - ///////////////////////////// // Entity_Iluminate // // -void Entity_Iluminate(Entity e,Entity *elist,int n){ +void Entity_Iluminate(Entity e, Entity *elist, int n) { int i; vec2 vdist; - float qdist,f; + float qdist, f; float qrad; - if(e->flags&EntityFlag_Light){ - Entity_SetColor(e, - e->defaultColor[0], - e->defaultColor[1], - e->defaultColor[2], - e->defaultColor[3]); + if (e->flags & EntityFlag_Light) { + Entity_SetColor(e, e->defaultColor[0], e->defaultColor[1], + e->defaultColor[2], e->defaultColor[3]); return; } - e->color[0]=e->light[0]; - e->color[1]=e->light[1]; - e->color[2]=e->light[2]; - e->color[3]=1.0f; + e->color[0] = e->light[0]; + e->color[1] = e->light[1]; + e->color[2] = e->light[2]; + e->color[3] = 1.0f; - for(i=0;iflags&EntityFlag_Light)) + for (i = 0; i < n; i++) { + if (e == elist[i] || !(elist[i]->flags & EntityFlag_Light)) continue; - vec2_minus(vdist,e->pos,elist[i]->pos); - qdist=vec2_dot(vdist,vdist); - qrad=elist[i]->light[3]*elist[i]->light[3]; - if(qdistlight[0], - f*elist[i]->light[1], - f*elist[i]->light[2], - 0.0f); + vec2_minus(vdist, e->pos, elist[i]->pos); + qdist = vec2_dot(vdist, vdist); + qrad = elist[i]->light[3] * elist[i]->light[3]; + if (qdist < qrad) { + f = 1.0f - qdist / qrad; + Entity_AddColor(e, f * elist[i]->light[0], f * elist[i]->light[1], + f * elist[i]->light[2], 0.0f); } } - Entity_MultColor(e, - e->defaultColor[0], - e->defaultColor[1], - e->defaultColor[2], - e->defaultColor[3]); - e->internalFlags&=~EntityIntFlag_UpdateLight; + Entity_MultColor(e, e->defaultColor[0], e->defaultColor[1], + e->defaultColor[2], e->defaultColor[3]); + e->internalFlags &= ~EntityIntFlag_UpdateLight; - if(e->internalFlags&EntityIntFlag_UpdateColor){ - e->color0[0]=e->color[0]; - e->color0[1]=e->color[1]; - e->color0[2]=e->color[2]; - e->color0[3]=e->color[3]; - e->internalFlags&=~EntityIntFlag_UpdateColor; + if (e->internalFlags & EntityIntFlag_UpdateColor) { + e->color0[0] = e->color[0]; + e->color0[1] = e->color[1]; + e->color0[2] = e->color[2]; + e->color0[3] = e->color[3]; + e->internalFlags &= ~EntityIntFlag_UpdateColor; } } - ///////////////////////////// // Entity_MarkUpdateLight // // -void Entity_MarkUpdateLight(Entity e,Entity *elist,int n){ - if(e->flags&EntityFlag_Light){ +void Entity_MarkUpdateLight(Entity e, Entity *elist, int n) { + if (e->flags & EntityFlag_Light) { int i; - vec2 max,min; + vec2 max, min; - if(e->pos0[0]oldpos[0]){ - min[0]=e->pos0[0]-e->light[3]; - max[0]=e->oldpos[0]+e->light[3]; - }else{ - min[0]=e->oldpos[0]-e->light[3]; - max[0]=e->pos0[0]+e->light[3]; + if (e->pos0[0] < e->oldpos[0]) { + min[0] = e->pos0[0] - e->light[3]; + max[0] = e->oldpos[0] + e->light[3]; + } else { + min[0] = e->oldpos[0] - e->light[3]; + max[0] = e->pos0[0] + e->light[3]; } - if(e->pos0[1]oldpos[1]){ - min[1]=e->pos0[1]-e->light[3]; - max[1]=e->oldpos[1]+e->light[3]; - }else{ - min[1]=e->oldpos[1]-e->light[3]; - max[1]=e->pos0[1]+e->light[3]; + if (e->pos0[1] < e->oldpos[1]) { + min[1] = e->pos0[1] - e->light[3]; + max[1] = e->oldpos[1] + e->light[3]; + } else { + min[1] = e->oldpos[1] - e->light[3]; + max[1] = e->pos0[1] + e->light[3]; } - for(i=0;ipos0[0] && - max[0]>=elist[i]->pos0[0] && - min[1]<=elist[i]->pos0[1] && - max[1]>=elist[i]->pos0[1]) - { - elist[i]->internalFlags|=EntityIntFlag_UpdateLight; + for (i = 0; i < n; i++) { + if (elist[i] != NULL && min[0] <= elist[i]->pos0[0] && + max[0] >= elist[i]->pos0[0] && min[1] <= elist[i]->pos0[1] && + max[1] >= elist[i]->pos0[1]) { + elist[i]->internalFlags |= EntityIntFlag_UpdateLight; } } - }else{ - e->internalFlags|=EntityIntFlag_UpdateLight; + } else { + e->internalFlags |= EntityIntFlag_UpdateLight; } } - ///////////////////////////// // Entity_IsLight // -int Entity_IsLight(Entity e){ - return (e->flags&EntityFlag_Light); -} - +int Entity_IsLight(Entity e) { return (e->flags & EntityFlag_Light); } ///////////////////////////// // Entity_IsUpdateLight // -int Entity_IsUpdateLight(Entity e){ - return (e->internalFlags&EntityIntFlag_UpdateLight); +int Entity_IsUpdateLight(Entity e) { + return (e->internalFlags & EntityIntFlag_UpdateLight); } - ///////////////////////////// // Entity_IsMoving // -int Entity_IsMoving(Entity e){ - return (e->internalFlags&EntityIntFlag_UpdatedPos); +int Entity_IsMoving(Entity e) { + return (e->internalFlags & EntityIntFlag_UpdatedPos); } - - - diff --git a/GameLib/Entity.h b/GameLib/Entity.h index 1fe9dae..317abb9 100644 --- a/GameLib/Entity.h +++ b/GameLib/Entity.h @@ -7,7 +7,6 @@ #include "Draw.h" #include "Anim.h" - //////////////////////////////////////////////// // Entity // @@ -60,9 +59,9 @@ struct TEntity { void (*oncopy)(Entity ent); void (*oninit)(Entity ent); void (*ondelete)(Entity ent); - void (*proc)(Entity ent,int ft); - void (*postproc)(Entity ent,int ft); - int (*collision)(Entity ent, Entity ent2, float t,vec2 n); + void (*proc)(Entity ent, int ft); + void (*postproc)(Entity ent, int ft); + int (*collision)(Entity ent, Entity ent2, float t, vec2 n); void (*overlap)(Entity ent, Entity ent2); int A; @@ -71,81 +70,70 @@ struct TEntity { int D; Entity child; - float maxX,minX; - float maxY,minY; + float maxX, minX; + float maxY, minY; Entity next; }; - ///////////////////////////// // Entity_New // Entity Entity_New(); - ///////////////////////////// // Entity_Init // Entity Entity_Init(Entity e); - ///////////////////////////// // Entity_Destroy // void Entity_Destroy(Entity e); - ///////////////////////////// // Entity_Copy // Entity Entity_Copy(Entity e); - ///////////////////////////// // Entity_CalcBBox // // void Entity_CalcBBox(Entity e); - ///////////////////////////// // Entity_BBoxIntersect // // -int Entity_BBoxIntersect(Entity ent1,Entity ent2); - +int Entity_BBoxIntersect(Entity ent1, Entity ent2); ///////////////////////////// // Entity_Draw // -void Entity_Draw(Entity e,int x,int y,float f); - +void Entity_Draw(Entity e, int x, int y, float f); ///////////////////////////// // Entity_IsVisible // -int Entity_IsVisible(Entity e,int x,int y,int w,int h); - +int Entity_IsVisible(Entity e, int x, int y, int w, int h); ///////////////////////////// // Entity_Process // -void Entity_Process(Entity e,int ft); - +void Entity_Process(Entity e, int ft); ///////////////////////////// // Entity_PostProcess // -void Entity_PostProcess(Entity e,int ft); - +void Entity_PostProcess(Entity e, int ft); //////////////////////////////////////////////// // CollisionInfo // #define CollisionResponse_Circle 1 #define CollisionResponse_Line 2 -typedef struct TCollisionInfo TCollisionInfo,*CollisionInfo; +typedef struct TCollisionInfo TCollisionInfo, *CollisionInfo; struct TCollisionInfo { int responseType; Entity ent1; @@ -157,13 +145,12 @@ struct TCollisionInfo { CollisionInfo next; }; - ///////////////////////////// // CollisionInfo_New // // -CollisionInfo CollisionInfo_New(int responseType,Entity ent1,Entity ent2,float t,vec2 n,int applyFriction); - +CollisionInfo CollisionInfo_New(int responseType, Entity ent1, Entity ent2, + float t, vec2 n, int applyFriction); ///////////////////////////// // CollisionInfo_Destroy @@ -171,44 +158,38 @@ CollisionInfo CollisionInfo_New(int responseType,Entity ent1,Entity ent2,float t // void CollisionInfo_Destroy(CollisionInfo *collInfoRef); - ///////////////////////////// // CollisionInfo_Add // // -void CollisionInfo_Add(CollisionInfo *collInfo, - int responseType,Entity ent1,Entity ent2,float t,vec2 n,int applyFriction); - +void CollisionInfo_Add(CollisionInfo *collInfo, int responseType, Entity ent1, + Entity ent2, float t, vec2 n, int applyFriction); ///////////////////////////// // CollisionInfo_CheckRepetition // // -int CollisionInfo_CheckRepetition(CollisionInfo collInfo,Entity ent1,Entity ent2); - +int CollisionInfo_CheckRepetition(CollisionInfo collInfo, Entity ent1, + Entity ent2); ///////////////////////////// // Entity_CheckCollision // // -int Entity_CheckCollision(Entity ent1,Entity ent2,CollisionInfo *collInfoRef); - +int Entity_CheckCollision(Entity ent1, Entity ent2, CollisionInfo *collInfoRef); ///////////////////////////// // Entity_CollisionResponseClircle // // Normal response to a collision of spheres. -void Entity_CollisionResponseCircle( - Entity b1,Entity b2,float t,vec2 n); - +void Entity_CollisionResponseCircle(Entity b1, Entity b2, float t, vec2 n); ///////////////////////////// // Entity_CollisionResponseLine // // Normal response to a collision with a line. -void Entity_CollisionResponseLine( - Entity ent,Entity ent2,float t,vec2 n,int applyFriction); - +void Entity_CollisionResponseLine(Entity ent, Entity ent2, float t, vec2 n, + int applyFriction); ///////////////////////////// // Entity_CollisionInfoResponse @@ -216,141 +197,117 @@ void Entity_CollisionResponseLine( // int Entity_CollisionInfoResponse(CollisionInfo collInfo); - ///////////////////////////// // Entity_Overlaps // -void Entity_Overlaps(Entity b1,Entity b2); - +void Entity_Overlaps(Entity b1, Entity b2); ///////////////////////////// // Entity_GetPos // -void Entity_GetPos(Entity e,vec2 pos); - +void Entity_GetPos(Entity e, vec2 pos); ///////////////////////////// // Entity_SetPos // // -void Entity_SetPos(Entity e,vec2 pos); - +void Entity_SetPos(Entity e, vec2 pos); ///////////////////////////// // Entity_AddPos // // -void Entity_AddPos(Entity e,vec2 pos); - +void Entity_AddPos(Entity e, vec2 pos); ///////////////////////////// // Entity_UpdatePos // -void Entity_UpdatePos(Entity e,vec2 pos); - +void Entity_UpdatePos(Entity e, vec2 pos); ///////////////////////////// // Entity_AddVel // -void Entity_AddVel(Entity e,vec2 vel); - +void Entity_AddVel(Entity e, vec2 vel); ///////////////////////////// // Entity_SetVel // -void Entity_SetVel(Entity e,vec2 vel); - +void Entity_SetVel(Entity e, vec2 vel); ///////////////////////////// // Entity_SetVelH // -void Entity_SetVelH(Entity e,float v); - +void Entity_SetVelH(Entity e, float v); ///////////////////////////// // Entity_SetVelV // -void Entity_SetVelV(Entity e,float v); - +void Entity_SetVelV(Entity e, float v); ///////////////////////////// // Entity_AddVelLimit // -void Entity_AddVelLimit(Entity e,vec2 vel,float limit); - +void Entity_AddVelLimit(Entity e, vec2 vel, float limit); ///////////////////////////// // Entity_AddVelLimitH // -void Entity_AddVelLimitH(Entity e,float v,float limit); - +void Entity_AddVelLimitH(Entity e, float v, float limit); ///////////////////////////// // Entity_AddVelLimitH // -void Entity_AddVelLimitV(Entity e,float v,float limit); - +void Entity_AddVelLimitV(Entity e, float v, float limit); ///////////////////////////// // Entity_SetColor // -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); ///////////////////////////// // Entity_AddColor // -void Entity_AddColor(Entity e,float r,float g,float b,float a); - +void Entity_AddColor(Entity e, float r, float g, float b, float a); ///////////////////////////// // Entity_MultColor // // -void Entity_MultColor(Entity e,float r,float g,float b,float a); - +void Entity_MultColor(Entity e, float r, float g, float b, float a); ///////////////////////////// // Entity_AddColor // -void Entity_SetLight(Entity e,float r,float g,float b,float rad); - +void Entity_SetLight(Entity e, float r, float g, float b, float rad); ///////////////////////////// // Entity_SetDefaultColor // -void Entity_SetDefaultColor(Entity e,float r,float g,float b,float a); - +void Entity_SetDefaultColor(Entity e, float r, float g, float b, float a); ///////////////////////////// // Entity_Iluminate // -void Entity_Iluminate(Entity e,Entity *elist,int n); - +void Entity_Iluminate(Entity e, Entity *elist, int n); ///////////////////////////// // Entity_MarkUpdateLight // -void Entity_MarkUpdateLight(Entity e,Entity *elist,int n); - +void Entity_MarkUpdateLight(Entity e, Entity *elist, int n); ///////////////////////////// // Entity_IsLight // int Entity_IsLight(Entity e); - ///////////////////////////// // Entity_IsUpdateLight // int Entity_IsUpdateLight(Entity e); - ///////////////////////////// // Entity_IsMoving // int Entity_IsMoving(Entity e); - #endif - diff --git a/GameLib/GameLib.c b/GameLib/GameLib.c index 6528958..f345dc4 100644 --- a/GameLib/GameLib.c +++ b/GameLib/GameLib.c @@ -17,16 +17,16 @@ #include "GameLib.h" // Globals -Entity *_entity=NULL; -int *_entity_flag=NULL; -int _n_entities=0; -int _n_entities_res=0; -int _entities_lock=0; -int _entities_compactate=0; -void (*_gameproc)()=NULL; -void (*_gamepostproc)()=NULL; -void (*_gamepredraw)(float f)=NULL; -void (*_gamedraw)(float f)=NULL; +Entity *_entity = NULL; +int *_entity_flag = NULL; +int _n_entities = 0; +int _n_entities_res = 0; +int _entities_lock = 0; +int _entities_compactate = 0; +void (*_gameproc)() = NULL; +void (*_gamepostproc)() = NULL; +void (*_gamepredraw)(float f) = NULL; +void (*_gamedraw)(float f) = NULL; int _pft; int _game_size[2]; int _game_pos0[2]; @@ -49,421 +49,400 @@ struct TParallaxBackground { }; #define MaxParallaxBackgrounds 10 TParallaxBackground _parallaxBackground[MaxParallaxBackgrounds]; -int _nParallaxBackgrounds=0; - -int gamelib_debug=0; +int _nParallaxBackgrounds = 0; +int gamelib_debug = 0; ///////////////////////////// // GameLib_Init // // Initializes the game. -int GameLib_Init(int w,int h,char *title,int pfps,int fps){ - if(!Draw_Init(w,h,title,pfps,fps)){ - return(0); +int GameLib_Init(int w, int h, char *title, int pfps, int fps) { + if (!Draw_Init(w, h, title, pfps, fps)) { + return (0); } - if(!Input_Init()){ - return(0); + if (!Input_Init()) { + return (0); } Audio_Init(); - _game_size[0]=w; - _game_size[1]=h; - _game_pos0[0]=0; - _game_pos0[1]=0; - _game_pos1[0]=0; - _game_pos1[1]=0; + _game_size[0] = w; + _game_size[1] = h; + _game_pos0[0] = 0; + _game_pos0[1] = 0; + _game_pos1[0] = 0; + _game_pos1[1] = 0; - _pft=1000/pfps; + _pft = 1000 / pfps; - return(1); + return (1); } - ///////////////////////////// // GameLib_AddEntity // // Adds an entity to the game. -void GameLib_AddEntity(Entity e){ - if(_n_entities>=_n_entities_res){ +void GameLib_AddEntity(Entity e) { + if (_n_entities >= _n_entities_res) { Entity *entity_aux; int *entity_flag_aux; int i; // Grow the array - if(_n_entities_res==0) - _n_entities_res=32; + if (_n_entities_res == 0) + _n_entities_res = 32; else - _n_entities_res*=2; - entity_aux=malloc(sizeof(Entity)*_n_entities_res); - entity_flag_aux=malloc(sizeof(int)*_n_entities_res); - for(i=0;i<_n_entities;i++){ - entity_aux[i]=_entity[i]; - entity_flag_aux[i]=_entity_flag[i]; + _n_entities_res *= 2; + entity_aux = malloc(sizeof(Entity) * _n_entities_res); + entity_flag_aux = malloc(sizeof(int) * _n_entities_res); + for (i = 0; i < _n_entities; i++) { + entity_aux[i] = _entity[i]; + entity_flag_aux[i] = _entity_flag[i]; } - if(_entity){ + if (_entity) { free(_entity); free(_entity_flag); } - _entity=entity_aux; - _entity_flag=entity_flag_aux; + _entity = entity_aux; + _entity_flag = entity_flag_aux; } // Add the entity - _entity[_n_entities]=e; - _entity_flag[_n_entities]=1; + _entity[_n_entities] = e; + _entity_flag[_n_entities] = 1; _n_entities++; // Mark for light update - Entity_MarkUpdateLight(e,_entity,_n_entities); + Entity_MarkUpdateLight(e, _entity, _n_entities); Entity_CalcBBox(e); - + Entity_Init(e); } - ///////////////////////////// // GameLib_UnrefEntity // // removes the reference to the entity. -int GameLib_UnrefEntity(Entity e){ +int GameLib_UnrefEntity(Entity e) { int i; - for(i=0;i<_n_entities;i++){ - if(e==_entity[i]){ + for (i = 0; i < _n_entities; i++) { + if (e == _entity[i]) { // Mark or unref - if(_entities_lock){ - _entity_flag[i]=-2; - }else{ - _entity[i]=NULL; - _entity_flag[i]=0; + if (_entities_lock) { + _entity_flag[i] = -2; + } else { + _entity[i] = NULL; + _entity_flag[i] = 0; } - _entities_compactate=1; + _entities_compactate = 1; // Mark for light update - Entity_MarkUpdateLight(e,_entity,_n_entities); - return(i); + Entity_MarkUpdateLight(e, _entity, _n_entities); + return (i); } } - return(-1); + return (-1); } - ///////////////////////////// // GameLib_DelEntity // // Adds an entity to the game. -int GameLib_DelEntity(Entity e){ +int GameLib_DelEntity(Entity e) { int i; - if((i=GameLib_UnrefEntity(e))==-1){ - return(0); + if ((i = GameLib_UnrefEntity(e)) == -1) { + return (0); } - if(_entities_lock){ + if (_entities_lock) { // Delete latter - _entity[i]=e; - _entity_flag[i]=-1; - }else{ + _entity[i] = e; + _entity_flag[i] = -1; + } else { // Delete now Entity_Destroy(e); } - return(1); + return (1); } - ///////////////////////////// // GameLib_Compactate // // -void GameLib_Compactate(){ - int i,j; - j=0; - if(!_entities_compactate) +void GameLib_Compactate() { + int i, j; + j = 0; + if (!_entities_compactate) return; - for(i=0;i<_n_entities;i++){ - if(!_entity[i] || _entity_flag[i]==-2) + for (i = 0; i < _n_entities; i++) { + if (!_entity[i] || _entity_flag[i] == -2) continue; - if(_entity_flag[i]==-1){ + if (_entity_flag[i] == -1) { Entity_Destroy(_entity[i]); continue; } - if(i>j){ - _entity[j]=_entity[i]; - _entity_flag[j]=_entity_flag[i]; + if (i > j) { + _entity[j] = _entity[i]; + _entity_flag[j] = _entity_flag[i]; } j++; } - _n_entities=j; - _entities_compactate=0; + _n_entities = j; + _entities_compactate = 0; } - ///////////////////////////// // GameLib_ProcLoop // // Process the loop. -void GameLib_ProcLoop(void *data){ - int i,j; - int repeat,count; +void GameLib_ProcLoop(void *data) { + int i, j; + int repeat, count; long long time; // Step the gamePosition - _game_pos0[0]=_game_pos1[0]; - _game_pos0[1]=_game_pos1[1]; + _game_pos0[0] = _game_pos1[0]; + _game_pos0[1] = _game_pos1[1]; // Process - time=Time_GetTime(); - _entities_lock=1; - if(_gameproc){ + time = Time_GetTime(); + _entities_lock = 1; + if (_gameproc) { _gameproc(); } - for(i=0;i<_n_entities;i++){ - if(!_entity[i]) + for (i = 0; i < _n_entities; i++) { + if (!_entity[i]) continue; - Entity_Process(_entity[i],_pft); + Entity_Process(_entity[i], _pft); } GameLib_Compactate(); - _entities_lock=0; - t_proc+=Time_GetTime()-time; + _entities_lock = 0; + t_proc += Time_GetTime() - time; // Colisions between entities - time=Time_GetTime(); - _entities_lock=1; - count=0; - do{ - repeat=0; - CollisionInfo collInfo=NULL; - for(i=0;i<_n_entities;i++){ - if(!(_entity[i]->flags&EntityFlag_Collision) || _entity[i]->mass<0.0f) + time = Time_GetTime(); + _entities_lock = 1; + count = 0; + do { + repeat = 0; + CollisionInfo collInfo = NULL; + for (i = 0; i < _n_entities; i++) { + if (!(_entity[i]->flags & EntityFlag_Collision) || + _entity[i]->mass < 0.0f) continue; - 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) - { + 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) { continue; } - for(j=0;j<_n_entities;j++){ - if( i==j || - !(_entity[j]->flags&EntityFlag_Collision) || - CollisionInfo_CheckRepetition(collInfo,_entity[i],_entity[j]) || - !Entity_BBoxIntersect(_entity[i],_entity[j])) - { + for (j = 0; j < _n_entities; j++) { + if (i == j || !(_entity[j]->flags & EntityFlag_Collision) || + CollisionInfo_CheckRepetition(collInfo, _entity[i], + _entity[j]) || + !Entity_BBoxIntersect(_entity[i], _entity[j])) { continue; } - Entity_CheckCollision(_entity[i],_entity[j],&collInfo); + Entity_CheckCollision(_entity[i], _entity[j], &collInfo); } } - if(Entity_CollisionInfoResponse(collInfo)){ - repeat=1; + if (Entity_CollisionInfoResponse(collInfo)) { + repeat = 1; } CollisionInfo_Destroy(&collInfo); count++; - }while(repeat && count<50); + } while (repeat && count < 50); // Stop remaining collisions - if(count==10){ - for(i=0;i<_n_entities;i++){ - if(!(_entity[i]->flags&EntityFlag_Collision) || _entity[i]->mass<0.0f) + if (count == 10) { + for (i = 0; i < _n_entities; i++) { + if (!(_entity[i]->flags & EntityFlag_Collision) || + _entity[i]->mass < 0.0f) continue; - for(j=0;j<_n_entities;j++){ - if(i==j || - !(_entity[j]->flags&EntityFlag_Collision) || - !Entity_BBoxIntersect(_entity[i],_entity[j])) - { + for (j = 0; j < _n_entities; j++) { + if (i == j || !(_entity[j]->flags & EntityFlag_Collision) || + !Entity_BBoxIntersect(_entity[i], _entity[j])) { continue; } - if(Entity_CheckCollision(_entity[i],_entity[j],NULL)){ - vec2_set(_entity[i]->vel,0,0); + if (Entity_CheckCollision(_entity[i], _entity[j], NULL)) { + vec2_set(_entity[i]->vel, 0, 0); Entity_CalcBBox(_entity[i]); - vec2_set(_entity[j]->vel,0,0); + vec2_set(_entity[j]->vel, 0, 0); Entity_CalcBBox(_entity[j]); } } } } GameLib_Compactate(); - _entities_lock=0; - t_col+=Time_GetTime()-time; + _entities_lock = 0; + t_col += Time_GetTime() - time; // Process Overlaps - time=Time_GetTime(); - _entities_lock=1; - for(i=0;i<_n_entities;i++){ - if(!(_entity[i]->flags&EntityFlag_Overlap) || _entity[i]->mass<0.0f) + time = Time_GetTime(); + _entities_lock = 1; + for (i = 0; i < _n_entities; i++) { + if (!(_entity[i]->flags & EntityFlag_Overlap) || + _entity[i]->mass < 0.0f) continue; - for(j=0;j<_n_entities;j++){ - if(!(_entity[j]->flags&EntityFlag_Overlap) || i==j) + for (j = 0; j < _n_entities; j++) { + if (!(_entity[j]->flags & EntityFlag_Overlap) || i == j) continue; - Entity_Overlaps(_entity[i],_entity[j]); + Entity_Overlaps(_entity[i], _entity[j]); } } GameLib_Compactate(); - _entities_lock=0; - t_over+=Time_GetTime()-time; + _entities_lock = 0; + t_over += Time_GetTime() - time; // Sort - int n,n2,swap; - n=_n_entities; - do{ - n2=0; - for(i=1;izorder > ent2->zorder){ + int n, n2, swap; + n = _n_entities; + do { + n2 = 0; + for (i = 1; i < n; i++) { + Entity ent1 = _entity[i - 1]; + Entity ent2 = _entity[i]; + swap = 0; + if (ent1->zorder > ent2->zorder) { // Lower level - swap=1; - }else - if(ent1->zorder < ent2->zorder){ + swap = 1; + } else if (ent1->zorder < ent2->zorder) { // Upper level - }else{ + } else { // Same level - float y1=ent1->pos[1]+ent1->sortYOffset; - float y2=ent2->pos[1]+ent2->sortYOffset; - if(y1 > y2){ - swap=1; + float y1 = ent1->pos[1] + ent1->sortYOffset; + float y2 = ent2->pos[1] + ent2->sortYOffset; + if (y1 > y2) { + swap = 1; } } - if(swap){ + if (swap) { Entity ent; - ent=_entity[i]; - _entity[i]=_entity[i-1]; - _entity[i-1]=ent; - n2=i; + ent = _entity[i]; + _entity[i] = _entity[i - 1]; + _entity[i - 1] = ent; + n2 = i; } } - n=n2; - }while(n>0); + n = n2; + } while (n > 0); // PostProcess - time=Time_GetTime(); - _entities_lock=1; - for(i=0;i<_n_entities;i++){ - Entity_PostProcess(_entity[i],_pft); - if(Entity_IsMoving(_entity[i])){ - Entity_MarkUpdateLight(_entity[i],_entity,_n_entities); + time = Time_GetTime(); + _entities_lock = 1; + for (i = 0; i < _n_entities; i++) { + Entity_PostProcess(_entity[i], _pft); + if (Entity_IsMoving(_entity[i])) { + Entity_MarkUpdateLight(_entity[i], _entity, _n_entities); } } - if(_gamepostproc){ + if (_gamepostproc) { _gamepostproc(); } GameLib_Compactate(); - _entities_lock=0; - t_postproc+=Time_GetTime()-time; + _entities_lock = 0; + t_postproc += Time_GetTime() - time; fproc_count++; } - ///////////////////////////// // GameLib_DrawLoop // // -void GameLib_DrawLoop(void *data, float f){ +void GameLib_DrawLoop(void *data, float f) { long long time; int i; int game_pos[2]; - GameLib_GetPosInstant(game_pos,f); + GameLib_GetPosInstant(game_pos, f); - time=Time_GetTime(); + time = Time_GetTime(); // PreDraw - if(_gamepredraw){ + if (_gamepredraw) { _gamepredraw(f); - }else{ - if(_nParallaxBackgrounds==0){ + } else { + if (_nParallaxBackgrounds == 0) { // Clean screen - Draw_Clean(0,0,0); + Draw_Clean(0, 0, 0); } } - + // Draw parallax backgrounds - for(i=0;i<_nParallaxBackgrounds;i++){ + for (i = 0; i < _nParallaxBackgrounds; i++) { Draw_ImgParallax( - _parallaxBackground[i].img, - _parallaxBackground[i].imgSize, + _parallaxBackground[i].img, _parallaxBackground[i].imgSize, _parallaxBackground[i].imgOffset, - _parallaxBackground[i].parallaxFactor, - game_pos, - _game_size); + _parallaxBackground[i].parallaxFactor, game_pos, _game_size); } - + // Draw entities GameLib_Compactate(); - for(i=0;i<_n_entities;i++){ - Entity e=_entity[i]; + for (i = 0; i < _n_entities; i++) { + Entity e = _entity[i]; // Check visivility - if(!Entity_IsVisible(e, - game_pos[0],game_pos[1], - _game_size[0],_game_size[1])) - { + if (!Entity_IsVisible(e, game_pos[0], game_pos[1], _game_size[0], + _game_size[1])) { continue; } // Update ilumination of this entity - if(Entity_IsUpdateLight(e)){ - Entity_Iluminate(e,_entity,_n_entities); + if (Entity_IsUpdateLight(e)) { + Entity_Iluminate(e, _entity, _n_entities); } - Entity_Draw(e,-game_pos[0],-game_pos[1],f); + Entity_Draw(e, -game_pos[0], -game_pos[1], f); } - Draw_SetColor(1,1,1,1); - _entities_lock=1; - if(_gamedraw){ + Draw_SetColor(1, 1, 1, 1); + _entities_lock = 1; + if (_gamedraw) { _gamedraw(f); } GameLib_Compactate(); - _entities_lock=0; + _entities_lock = 0; - t_draw+=Time_GetTime()-time; + t_draw += Time_GetTime() - time; fdraw_count++; - if(Input_GetKey(InputKey_DumpProfiling)==InputKey_Pressed && - fproc_count>0 && fdraw_count>0) - { + if (Input_GetKey(InputKey_DumpProfiling) == InputKey_Pressed && + fproc_count > 0 && fdraw_count > 0) { Print("Profiling:::::::::\n"); - Print("t_proc.....:%6lld\n",t_proc/fproc_count); - Print("t_col......:%6lld\n",t_col/fproc_count); - Print("t_over.....:%6lld\n",t_over/fproc_count); - Print("t_postproc.:%6lld\n",t_postproc/fproc_count); - Print("t_draw.....:%6lld\n",t_draw/fdraw_count); - t_proc=0; - t_col=0; - t_over=0; - t_postproc=0; - t_draw=0; - fproc_count=0; - fdraw_count=0; + Print("t_proc.....:%6lld\n", t_proc / fproc_count); + Print("t_col......:%6lld\n", t_col / fproc_count); + Print("t_over.....:%6lld\n", t_over / fproc_count); + Print("t_postproc.:%6lld\n", t_postproc / fproc_count); + Print("t_draw.....:%6lld\n", t_draw / fdraw_count); + t_proc = 0; + t_col = 0; + t_over = 0; + t_postproc = 0; + t_draw = 0; + fproc_count = 0; + fdraw_count = 0; } } - ///////////////////////////// // GameLib_Loop // // Loops the game. -void GameLib_Loop( - void (*gameproc)(), - void (*gamepostproc)(), - void (*gamepredraw)(float f), - void (*gamedraw)(float f)) -{ - _gameproc=gameproc; - _gamepostproc=gamepostproc; - _gamepredraw=gamepredraw; - _gamedraw=gamedraw; - t_proc=0; - t_col=0; - t_over=0; - t_postproc=0; - t_draw=0; - fproc_count=0; - fdraw_count=0; - Draw_Loop(GameLib_ProcLoop,GameLib_DrawLoop,NULL); +void GameLib_Loop(void (*gameproc)(), void (*gamepostproc)(), + void (*gamepredraw)(float f), void (*gamedraw)(float f)) { + _gameproc = gameproc; + _gamepostproc = gamepostproc; + _gamepredraw = gamepredraw; + _gamedraw = gamedraw; + t_proc = 0; + t_col = 0; + t_over = 0; + t_postproc = 0; + t_draw = 0; + fproc_count = 0; + fdraw_count = 0; + Draw_Loop(GameLib_ProcLoop, GameLib_DrawLoop, NULL); } - ///////////////////////////// // GameLib_GetPos // GameLib_SetPos @@ -472,248 +451,230 @@ void GameLib_Loop( // GameLib_GetPosInstant // // -void GameLib_GetPos(int pos[2]){ - pos[0]=_game_pos1[0]; - pos[1]=_game_pos1[1]; +void GameLib_GetPos(int pos[2]) { + pos[0] = _game_pos1[0]; + pos[1] = _game_pos1[1]; } -void GameLib_SetPos(int pos[2]){ - _game_pos0[0]=pos[0]; - _game_pos0[1]=pos[1]; - _game_pos1[0]=pos[0]; - _game_pos1[1]=pos[1]; +void GameLib_SetPos(int pos[2]) { + _game_pos0[0] = pos[0]; + _game_pos0[1] = pos[1]; + _game_pos1[0] = pos[0]; + _game_pos1[1] = pos[1]; } -void GameLib_UpdatePos(int pos[2]){ - _game_pos1[0]=pos[0]; - _game_pos1[1]=pos[1]; +void GameLib_UpdatePos(int pos[2]) { + _game_pos1[0] = pos[0]; + _game_pos1[1] = pos[1]; } -void GameLib_GetSize(int size[2]){ - size[0]=_game_size[0]; - size[1]=_game_size[1]; +void GameLib_GetSize(int size[2]) { + size[0] = _game_size[0]; + size[1] = _game_size[1]; } -void GameLib_GetPosInstant(int pos[2],float f){ - pos[0]=_game_pos0[0]+f*(_game_pos1[0]-_game_pos0[0]); - pos[1]=_game_pos0[1]+f*(_game_pos1[1]-_game_pos0[1]); +void GameLib_GetPosInstant(int pos[2], float f) { + pos[0] = _game_pos0[0] + f * (_game_pos1[0] - _game_pos0[0]); + pos[1] = _game_pos0[1] + f * (_game_pos1[1] - _game_pos0[1]); } - - - ///////////////////////////// // GameLib_MoveToPos // GameLib_MoveToPosH // GameLib_MoveToPosV // // -void GameLib_MoveToPos(vec2 pos,float f){ - GameLib_MoveToPosH(pos,f); - GameLib_MoveToPosV(pos,f); +void GameLib_MoveToPos(vec2 pos, float f) { + GameLib_MoveToPosH(pos, f); + GameLib_MoveToPosV(pos, f); } -void GameLib_MoveToPosH(vec2 pos,float f){ - _game_pos1[0]=_game_pos1[0]+(pos[0]-(_game_pos1[0]+(_game_size[0]/2.0f)))*f; +void GameLib_MoveToPosH(vec2 pos, float f) { + _game_pos1[0] = + _game_pos1[0] + (pos[0] - (_game_pos1[0] + (_game_size[0] / 2.0f))) * f; } -void GameLib_MoveToPosV(vec2 pos,float f){ - _game_pos1[1]=_game_pos1[1]+(pos[1]-(_game_pos1[1]+(_game_size[1]/2.0f)))*f; +void GameLib_MoveToPosV(vec2 pos, float f) { + _game_pos1[1] = + _game_pos1[1] + (pos[1] - (_game_pos1[1] + (_game_size[1] / 2.0f))) * f; } - - - ///////////////////////////// // GameLib_ForEachEn // // Deletes every entity. -void GameLib_DelEnts(){ +void GameLib_DelEnts() { int i; - for(i=0;i<_n_entities;i++){ - if(!_entity[i]) + for (i = 0; i < _n_entities; i++) { + if (!_entity[i]) continue; Entity_Destroy(_entity[i]); } - _n_entities=0; + _n_entities = 0; } - ///////////////////////////// // GameLib_ForEachEn // // Iterates every entity. -void GameLib_ForEachEnt(int (*func)(Entity ent)){ +void GameLib_ForEachEnt(int (*func)(Entity ent)) { int i; - for(i=0;i<_n_entities;i++){ - if(!_entity[i]) + for (i = 0; i < _n_entities; i++) { + if (!_entity[i]) continue; - if(!func(_entity[i])){ + if (!func(_entity[i])) { break; } } } - ///////////////////////////// // GameLib_SearchEnt // // Searches throught the entities. -Entity GameLib_SearchEnt(int (*func)(Entity ent,void *d),void *d){ +Entity GameLib_SearchEnt(int (*func)(Entity ent, void *d), void *d) { int i; - Entity ent=NULL; - for(i=0;i<_n_entities;i++){ - if(!_entity[i]) + Entity ent = NULL; + for (i = 0; i < _n_entities; i++) { + if (!_entity[i]) continue; - if(func(_entity[i],d)){ - ent=_entity[i]; + if (func(_entity[i], d)) { + ent = _entity[i]; break; } } return ent; } - ///////////////////////////// // GameLib_EntityCustomCheckCollision // // -int GameLib_EntityCustomCheckCollision(Entity ent,vec2 vel){ - int collision=0; - CollisionInfo collInfo=NULL; +int GameLib_EntityCustomCheckCollision(Entity ent, vec2 vel) { + int collision = 0; + CollisionInfo collInfo = NULL; vec2 originalVel; int j; - vec2_copy(originalVel,ent->vel); - vec2_copy(ent->vel,vel); + vec2_copy(originalVel, ent->vel); + vec2_copy(ent->vel, vel); Entity_CalcBBox(ent); - for(j=0;j<_n_entities;j++){ - if(!(_entity[j]->flags&EntityFlag_Collision) || - !Entity_BBoxIntersect(ent,_entity[j])) - { + for (j = 0; j < _n_entities; j++) { + if (!(_entity[j]->flags & EntityFlag_Collision) || + !Entity_BBoxIntersect(ent, _entity[j])) { continue; } - Entity_CheckCollision(ent,_entity[j],&collInfo); - if(collInfo!=NULL){ - collision=1; + Entity_CheckCollision(ent, _entity[j], &collInfo); + if (collInfo != NULL) { + collision = 1; break; } } - vec2_copy(ent->vel,originalVel); + vec2_copy(ent->vel, originalVel); Entity_CalcBBox(ent); CollisionInfo_Destroy(&collInfo); return collision; } - ///////////////////////////// // GameLib_PlaySound // // -void GameLib_PlaySound(AudioSnd snd,int x,int y){ - float vleft,vright,dx,dy; - int r,cx,cy,off; +void GameLib_PlaySound(AudioSnd snd, int x, int y) { + float vleft, vright, dx, dy; + int r, cx, cy, off; // Get the screen context - cx=_game_pos1[0]+_game_size[0]/2; - cy=_game_pos1[1]+_game_size[1]/2; - if(_game_size[0]>_game_size[1]){ - r=_game_size[0]/2; - }else{ - r=_game_size[1]/2; + cx = _game_pos1[0] + _game_size[0] / 2; + cy = _game_pos1[1] + _game_size[1] / 2; + if (_game_size[0] > _game_size[1]) { + r = _game_size[0] / 2; + } else { + r = _game_size[1] / 2; } - r=r*1.2f; - off=r/10.0f; + r = r * 1.2f; + off = r / 10.0f; // Calculate volumes - dx=x-(cx+off); - dy=y-(cy); - vright=1.0f-(sqrtf(dx*dx+dy*dy)/(float)r); - dx=x-(cx-off); - dy=y-(cy); - vleft=1.0f-(sqrtf(dx*dx+dy*dy)/(float)r); + dx = x - (cx + off); + dy = y - (cy); + vright = 1.0f - (sqrtf(dx * dx + dy * dy) / (float)r); + dx = x - (cx - off); + dy = y - (cy); + vleft = 1.0f - (sqrtf(dx * dx + dy * dy) / (float)r); // Clamp to 0 - if(vleft<0.0f) - vleft=0.0f; - if(vright<0.0f) - vright=0.0f; - if(vleft<=0.0f && vright<=0.0f){ + if (vleft < 0.0f) + vleft = 0.0f; + if (vright < 0.0f) + vright = 0.0f; + if (vleft <= 0.0f && vright <= 0.0f) { return; } // PLAY! - Audio_PlaySound(snd,vleft,vright,0); + Audio_PlaySound(snd, vleft, vright, 0); } - ///////////////////////////// // GameLib_PlayLoopingSound // // -AudioChn GameLib_PlayLoopingSound(AudioSnd snd){ +AudioChn GameLib_PlayLoopingSound(AudioSnd snd) { // PLAY! - return Audio_PlaySound(snd,1.0f,1.0f,1); + return Audio_PlaySound(snd, 1.0f, 1.0f, 1); } - ///////////////////////////// // GameLib_EntitySetLight // // -void GameLib_EntitySetLight(Entity e,float r,float g,float b,float rad){ - if(Entity_IsLight(e)){ - Entity_MarkUpdateLight(e,_entity,_n_entities); - Entity_SetLight(e,r,g,b,rad); - Entity_MarkUpdateLight(e,_entity,_n_entities); - }else{ - Entity_SetLight(e,r,g,b,rad); +void GameLib_EntitySetLight(Entity e, float r, float g, float b, float rad) { + if (Entity_IsLight(e)) { + Entity_MarkUpdateLight(e, _entity, _n_entities); + Entity_SetLight(e, r, g, b, rad); + Entity_MarkUpdateLight(e, _entity, _n_entities); + } else { + Entity_SetLight(e, r, g, b, rad); } } - ///////////////////////////// // GameLib_ConvertScreenPositionToGamePosition // // -void GameLib_ConvertScreenPositionToGamePosition( - vec2 screenPos, vec2 gamePos) -{ +void GameLib_ConvertScreenPositionToGamePosition(vec2 screenPos, vec2 gamePos) { float f; int game_pos[2]; - game_pos[0]=_game_pos0[0]+f*(_game_pos1[0]-_game_pos0[0]); - game_pos[1]=_game_pos0[1]+f*(_game_pos1[1]-_game_pos0[1]); + game_pos[0] = _game_pos0[0] + f * (_game_pos1[0] - _game_pos0[0]); + game_pos[1] = _game_pos0[1] + f * (_game_pos1[1] - _game_pos0[1]); - gamePos[0]=(screenPos[0]*_game_size[0])+game_pos[0]; - gamePos[1]=(screenPos[1]*_game_size[1])+game_pos[1]; + gamePos[0] = (screenPos[0] * _game_size[0]) + game_pos[0]; + gamePos[1] = (screenPos[1] * _game_size[1]) + game_pos[1]; } - ///////////////////////////// // GameLib_AddParallaxBackground // // -void GameLib_AddParallaxBackground(DrawImg img, int imgSize[2], int imgOffset[2], float parallaxFactor[2]){ +void GameLib_AddParallaxBackground(DrawImg img, int imgSize[2], + int imgOffset[2], float parallaxFactor[2]) { int idx = _nParallaxBackgrounds; - if((idx+1)>=MaxParallaxBackgrounds){ + if ((idx + 1) >= MaxParallaxBackgrounds) { Print("GameLib: Can't add parallaxBackground, limit reached."); return; } - _parallaxBackground[idx].img=img; - _parallaxBackground[idx].imgSize[0]=imgSize[0]; - _parallaxBackground[idx].imgSize[1]=imgSize[1]; - _parallaxBackground[idx].imgOffset[0]=imgOffset[0]; - _parallaxBackground[idx].imgOffset[1]=imgOffset[1]; - _parallaxBackground[idx].parallaxFactor[0]=parallaxFactor[0]; - _parallaxBackground[idx].parallaxFactor[1]=parallaxFactor[1]; + _parallaxBackground[idx].img = img; + _parallaxBackground[idx].imgSize[0] = imgSize[0]; + _parallaxBackground[idx].imgSize[1] = imgSize[1]; + _parallaxBackground[idx].imgOffset[0] = imgOffset[0]; + _parallaxBackground[idx].imgOffset[1] = imgOffset[1]; + _parallaxBackground[idx].parallaxFactor[0] = parallaxFactor[0]; + _parallaxBackground[idx].parallaxFactor[1] = parallaxFactor[1]; _nParallaxBackgrounds++; } - ///////////////////////////// // GameLib_CleanParallaxBackgrounds // // -void GameLib_CleanParallaxBackgrounds(){ - _nParallaxBackgrounds=0; -} - +void GameLib_CleanParallaxBackgrounds() { _nParallaxBackgrounds = 0; } diff --git a/GameLib/GameLib.h b/GameLib/GameLib.h index 842c562..b512265 100644 --- a/GameLib/GameLib.h +++ b/GameLib/GameLib.h @@ -11,13 +11,11 @@ #include "Anim.h" #include "Entity.h" - ///////////////////////////// // GameLib_Init // // Initializes the game. -int GameLib_Init(int w,int h,char *title,int pfps,int fps); - +int GameLib_Init(int w, int h, char *title, int pfps, int fps); ///////////////////////////// // GameLib_AddEntity @@ -25,31 +23,24 @@ int GameLib_Init(int w,int h,char *title,int pfps,int fps); // Adds an entity to the game. void GameLib_AddEntity(Entity e); - ///////////////////////////// // GameLib_UnrefEntity // // removes the reference to the entity. int GameLib_UnrefEntity(Entity e); - ///////////////////////////// // GameLib_DelEntity // // Adds an entity to the game. int GameLib_DelEntity(Entity e); - ///////////////////////////// // GameLib_Loop // // Loops the game. -void GameLib_Loop( - void (*gameproc)(), - void (*gamepostproc)(), - void (*gamepredraw)(float f), - void (*gamedraw)(float f)); - +void GameLib_Loop(void (*gameproc)(), void (*gamepostproc)(), + void (*gamepredraw)(float f), void (*gamedraw)(float f)); ///////////////////////////// // GameLib_GetPos @@ -63,8 +54,7 @@ void GameLib_GetPos(int pos[2]); void GameLib_SetPos(int pos[2]); void GameLib_UpdatePos(int pos[2]); void GameLib_GetSize(int size[2]); -void GameLib_GetPosInstant(int pos[2],float f); - +void GameLib_GetPosInstant(int pos[2], float f); ///////////////////////////// // GameLib_MoveToPos @@ -72,10 +62,9 @@ void GameLib_GetPosInstant(int pos[2],float f); // GameLib_MoveToPosV // // -void GameLib_MoveToPos(vec2 pos,float f); -void GameLib_MoveToPosH(vec2 pos,float f); -void GameLib_MoveToPosV(vec2 pos,float f); - +void GameLib_MoveToPos(vec2 pos, float f); +void GameLib_MoveToPosH(vec2 pos, float f); +void GameLib_MoveToPosV(vec2 pos, float f); ///////////////////////////// // GameLib_ForEachEn @@ -83,34 +72,29 @@ void GameLib_MoveToPosV(vec2 pos,float f); // Deletes every entity. void GameLib_DelEnts(); - ///////////////////////////// // GameLib_ForEachEnt // // Iterates every entity. void GameLib_ForEachEnt(int (*func)(Entity ent)); - ///////////////////////////// // GameLib_SearchEnt // // Searches throught the entities. -Entity GameLib_SearchEnt(int (*func)(Entity ent,void *d),void *d); - +Entity GameLib_SearchEnt(int (*func)(Entity ent, void *d), void *d); ///////////////////////////// // GameLib_EntityCustomCheckCollision // // -int GameLib_EntityCustomCheckCollision(Entity ent,vec2 vel); - +int GameLib_EntityCustomCheckCollision(Entity ent, vec2 vel); ///////////////////////////// // GameLib_PlaySound // // Play a sound position aware. -void GameLib_PlaySound(AudioSnd snd,int x,int y); - +void GameLib_PlaySound(AudioSnd snd, int x, int y); ///////////////////////////// // GameLib_PlayLoopingSound @@ -118,28 +102,24 @@ void GameLib_PlaySound(AudioSnd snd,int x,int y); // Play a sound looping AudioChn GameLib_PlayLoopingSound(AudioSnd snd); - ///////////////////////////// // GameLib_EntitySetLight // // -void GameLib_EntitySetLight(Entity e,float r,float g,float b,float rad); - +void GameLib_EntitySetLight(Entity e, float r, float g, float b, float rad); ///////////////////////////// // GameLib_ConvertScreenPositionToGamePosition // // -void GameLib_ConvertScreenPositionToGamePosition( - vec2 screenPos, vec2 gamePos); - +void GameLib_ConvertScreenPositionToGamePosition(vec2 screenPos, vec2 gamePos); ///////////////////////////// // GameLib_AddParallaxBackground // // -void GameLib_AddParallaxBackground(DrawImg img, int imgSize[2], int imgOffset[2], float parallaxFactor[2]); - +void GameLib_AddParallaxBackground(DrawImg img, int imgSize[2], + int imgOffset[2], float parallaxFactor[2]); ///////////////////////////// // GameLib_CleanParallaxBackgrounds diff --git a/GameLib/Input.c b/GameLib/Input.c index d9fc136..fe30c43 100644 --- a/GameLib/Input.c +++ b/GameLib/Input.c @@ -9,194 +9,180 @@ #include "Util.h" #include "Input.h" - - // Globals InputKeyStatus _keys[InputKey_Max]; -int _pointerDown=0; -float _pointerX=0; -float _pointerY=0; - -int _clicked=0; -float _clickedPositionX=0; -float _clickedPositionY=0; +int _pointerDown = 0; +float _pointerX = 0; +float _pointerY = 0; +int _clicked = 0; +float _clickedPositionX = 0; +float _clickedPositionY = 0; ///////////////////////////// // Input_Init // // Initializes the game input. -int Input_Init(){ +int Input_Init() { int i; // Mark released all the keys - for(i=0;i=InputKey_Pressed){ - _keys[key]=InputKey_Holded; - }else{ - _keys[key]=InputKey_Pressed; +void Input_SetKey(InputKey key, int status) { + if (!status) { + _keys[key] = InputKey_Released; + } else { + if (_keys[key] >= InputKey_Pressed) { + _keys[key] = InputKey_Holded; + } else { + _keys[key] = InputKey_Pressed; } } } - ///////////////////////////// // Input_GetKey // // Reports a the status of a key. -InputKeyStatus Input_GetKey(InputKey key){ - return(_keys[key]); -} - +InputKeyStatus Input_GetKey(InputKey key) { return (_keys[key]); } ///////////////////////////// // Input_SetPointerPosition // -void Input_SetPointerPosition(float x, float y){ - _pointerX=x; - _pointerY=y; +void Input_SetPointerPosition(float x, float y) { + _pointerX = x; + _pointerY = y; } - ///////////////////////////// // Input_SetPointerDown // -void Input_SetPointerDown(int pointerDown){ - if(pointerDown==0 && _pointerDown==1){ - _clicked=1; - _clickedPositionX=_pointerX; - _clickedPositionY=_pointerY; +void Input_SetPointerDown(int pointerDown) { + if (pointerDown == 0 && _pointerDown == 1) { + _clicked = 1; + _clickedPositionX = _pointerX; + _clickedPositionY = _pointerY; } - _pointerDown=pointerDown; + _pointerDown = pointerDown; } - ///////////////////////////// // Input_GetPointerPosition // -int Input_GetPointerPosition(vec2 pointer){ - pointer[0]=_pointerX; - pointer[1]=_pointerY; +int Input_GetPointerPosition(vec2 pointer) { + pointer[0] = _pointerX; + pointer[1] = _pointerY; return _pointerDown; } - ///////////////////////////// // Input_GetClickedPosition // -int Input_GetClickedPosition(vec2 clickPosition){ - clickPosition[0]=_clickedPositionX; - clickPosition[1]=_clickedPositionY; +int Input_GetClickedPosition(vec2 clickPosition) { + clickPosition[0] = _clickedPositionX; + clickPosition[1] = _clickedPositionY; return _clicked; } - ///////////////////////////// // Input_AnyKey // // -int Input_AnyKey(){ +int Input_AnyKey() { int i; - for(i=0;i0.0f){ - vlen=sqrtf(vlen); - vec2_scale(dir,dir,1.0f/vlen); - return(1); - }else{ - return(0); + vlen = vec2_dot(dir, dir); + if (vlen > 0.0f) { + vlen = sqrtf(vlen); + vec2_scale(dir, dir, 1.0f / vlen); + return (1); + } else { + return (0); } } } diff --git a/GameLib/Input.h b/GameLib/Input.h index e2a32a3..2620355 100644 --- a/GameLib/Input.h +++ b/GameLib/Input.h @@ -5,28 +5,24 @@ #include "Util.h" - ///////////////////////////// // Input_Init // // Initializes the game input. int Input_Init(); - ///////////////////////////// // Input_Frame // // Notify a frame update to the input subsystem. void Input_Frame(); - ///////////////////////////// // Input_PostFrame // // Notify a frame update end to the input subsystem. void Input_PostFrame(); - //////////////////////////////////////////////// // InputKey // ////////////// @@ -47,13 +43,11 @@ typedef enum { InputKey_Max } InputKey; - ///////////////////////////// // Input_SetKey // // Notify a key press to the input subsystem. -void Input_SetKey(InputKey key,int status); - +void Input_SetKey(InputKey key, int status); //////////////////////////////////////////////// // InputKeyStatus // @@ -65,50 +59,42 @@ typedef enum { InputKey_Holded } InputKeyStatus; - ///////////////////////////// // Input_GetKey // // Reports a the status of a key. InputKeyStatus Input_GetKey(InputKey key); - ///////////////////////////// // Input_SetPointerPosition // void Input_SetPointerPosition(float x, float y); - ///////////////////////////// // Input_SetPointerDown // void Input_SetPointerDown(int pointerDown); - ///////////////////////////// // Input_GetPointerPosition // int Input_GetPointerPosition(vec2 pointer); - ///////////////////////////// // Input_GetClickedPosition // int Input_GetClickedPosition(vec2 clickPosition); - ///////////////////////////// // Input_AnyKey // // int Input_AnyKey(); - ///////////////////////////// // Input_GetDir // // Reports the direction of the dpad. int Input_GetDir(vec2 dir); - #endif diff --git a/GameLib/QuadArray2D.c b/GameLib/QuadArray2D.c index ff98778..d87b863 100644 --- a/GameLib/QuadArray2D.c +++ b/GameLib/QuadArray2D.c @@ -6,73 +6,91 @@ #include "QuadArray2D.h" +QuadArray2D QuadArray2D_Create(int resVertex) { + QuadArray2D quadArray = NULL; -QuadArray2D QuadArray2D_Create(int resVertex){ - QuadArray2D quadArray=NULL; + quadArray = malloc(sizeof(TQuadArray2D)); - quadArray=malloc(sizeof(TQuadArray2D)); - - quadArray->vertexData=malloc(sizeof(float)*Vertex2D_Length*resVertex); - quadArray->nVertex=0; - quadArray->resVertex=resVertex; + quadArray->vertexData = malloc(sizeof(float) * Vertex2D_Length * resVertex); + quadArray->nVertex = 0; + quadArray->resVertex = resVertex; return quadArray; } -void QuadArray2D_Destroy(QuadArray2D *quadArray){ - if(!quadArray) return; - if(!quadArray[0]) return; +void QuadArray2D_Destroy(QuadArray2D *quadArray) { + if (!quadArray) + return; + if (!quadArray[0]) + return; free(quadArray[0]->vertexData); free(quadArray[0]); - quadArray[0]=NULL; + quadArray[0] = NULL; } -void QuadArray2D_Clean(QuadArray2D quadArray){ - quadArray->nVertex=0; -} +void QuadArray2D_Clean(QuadArray2D quadArray) { quadArray->nVertex = 0; } -void QuadArray2D_AddVertex(QuadArray2D quadArray,float v[]){ - if(quadArray->resVertex<=quadArray->nVertex){ +void QuadArray2D_AddVertex(QuadArray2D quadArray, float v[]) { + if (quadArray->resVertex <= quadArray->nVertex) { // Grow vertexData - quadArray->resVertex*=2; - float *newVertexData=malloc(sizeof(float)*Vertex2D_Length* - quadArray->resVertex); - memcpy(newVertexData,quadArray->vertexData, - sizeof(float)*Vertex2D_Length*quadArray->nVertex); + quadArray->resVertex *= 2; + float *newVertexData = + malloc(sizeof(float) * Vertex2D_Length * quadArray->resVertex); + memcpy(newVertexData, quadArray->vertexData, + sizeof(float) * Vertex2D_Length * quadArray->nVertex); free(quadArray->vertexData); - quadArray->vertexData=newVertexData; + quadArray->vertexData = newVertexData; } // Add the vertex - memcpy( - quadArray->vertexData+ - (Vertex2D_Length*quadArray->nVertex), - v,sizeof(float)*Vertex2D_Length); + memcpy(quadArray->vertexData + (Vertex2D_Length * quadArray->nVertex), v, + sizeof(float) * Vertex2D_Length); quadArray->nVertex++; } -void QuadArray2D_AddQuad(QuadArray2D quadArray, - float x0, float y0,float u0, float v0, - float x1, float y1,float u1, float v1, - float color[]) -{ +void QuadArray2D_AddQuad(QuadArray2D quadArray, float x0, float y0, float u0, + float v0, float x1, float y1, float u1, float v1, + float color[]) { float v[Vertex2D_Length]; - int firstIndex=quadArray->nVertex; + int firstIndex = quadArray->nVertex; // Set the color - v[4]=color[0]; - v[5]=color[1]; - v[6]=color[2]; - v[7]=color[3]; + v[4] = color[0]; + v[5] = color[1]; + v[6] = color[2]; + v[7] = color[3]; // Add the vertexes - v[0]=x0; v[1]=y0; v[2]=u0; v[3]=v0; QuadArray2D_AddVertex(quadArray,v); - v[0]=x1; v[1]=y0; v[2]=u1; v[3]=v0; QuadArray2D_AddVertex(quadArray,v); - v[0]=x1; v[1]=y1; v[2]=u1; v[3]=v1; QuadArray2D_AddVertex(quadArray,v); + v[0] = x0; + v[1] = y0; + v[2] = u0; + v[3] = v0; + QuadArray2D_AddVertex(quadArray, v); + v[0] = x1; + v[1] = y0; + v[2] = u1; + v[3] = v0; + QuadArray2D_AddVertex(quadArray, v); + v[0] = x1; + v[1] = y1; + v[2] = u1; + v[3] = v1; + QuadArray2D_AddVertex(quadArray, v); - v[0]=x1; v[1]=y1; v[2]=u1; v[3]=v1; QuadArray2D_AddVertex(quadArray,v); - v[0]=x0; v[1]=y1; v[2]=u0; v[3]=v1; QuadArray2D_AddVertex(quadArray,v); - v[0]=x0; v[1]=y0; v[2]=u0; v[3]=v0; QuadArray2D_AddVertex(quadArray,v); + v[0] = x1; + v[1] = y1; + v[2] = u1; + v[3] = v1; + QuadArray2D_AddVertex(quadArray, v); + v[0] = x0; + v[1] = y1; + v[2] = u0; + v[3] = v1; + QuadArray2D_AddVertex(quadArray, v); + v[0] = x0; + v[1] = y0; + v[2] = u0; + v[3] = v0; + QuadArray2D_AddVertex(quadArray, v); } - diff --git a/GameLib/QuadArray2D.h b/GameLib/QuadArray2D.h index 716424b..94e8656 100644 --- a/GameLib/QuadArray2D.h +++ b/GameLib/QuadArray2D.h @@ -6,7 +6,6 @@ // Vertex2D -> (x,y) (u,v) (r,g,b,a) #define Vertex2D_Length 8 - //////////////////////////////////////////////// // QuadArray2D // @@ -17,19 +16,16 @@ struct TQuadArray2D { int resVertex; }; - QuadArray2D QuadArray2D_Create(int resVertex); void QuadArray2D_Destroy(QuadArray2D *quadArray); 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, float v0, - float x1, float y1,float u1, float v1, - float color[]); +void QuadArray2D_AddQuad(QuadArray2D quadArray, float x0, float y0, float u0, + float v0, float x1, float y1, float u1, float v1, + float color[]); #endif - diff --git a/GameLib/Time.c b/GameLib/Time.c index acb78f1..0da8138 100644 --- a/GameLib/Time.c +++ b/GameLib/Time.c @@ -8,7 +8,6 @@ #include "Time.h" - ///////////////////////////// // Time_GetTime // @@ -20,46 +19,44 @@ #if WIN32 #include // WIN32 -long long Time_GetTime(){ +long long Time_GetTime() { LARGE_INTEGER freq; LARGE_INTEGER tim; long long int microt; QueryPerformanceFrequency(&freq); QueryPerformanceCounter(&tim); - microt=(tim.QuadPart*1000000)/freq.QuadPart; - return(microt); + microt = (tim.QuadPart * 1000000) / freq.QuadPart; + return (microt); } -void Time_Pause(int pausa){ - long long tend,t,diff; +void Time_Pause(int pausa) { + long long tend, t, diff; - t=Time_GetTime(); - tend=t+pausa; - do{ - diff=tend-t; - if(diff>1000){ - Sleep(diff/1000); - }else{ + t = Time_GetTime(); + tend = t + pausa; + do { + diff = tend - t; + if (diff > 1000) { + Sleep(diff / 1000); + } else { Sleep(0); } - t=Time_GetTime(); - }while(tend>=t); + t = Time_GetTime(); + } while (tend >= t); } #else // UNIX -long long Time_GetTime(){ +long long Time_GetTime() { struct timeval t; long long usecs; - gettimeofday(&t,NULL); - usecs=(t.tv_sec*1000000ll)+(t.tv_usec); - return(usecs); + gettimeofday(&t, NULL); + usecs = (t.tv_sec * 1000000ll) + (t.tv_usec); + return (usecs); } -void Time_Pause(int pausa){ +void Time_Pause(int pausa) { struct timeval tv; - tv.tv_sec=(long long)pausa/1000000; - tv.tv_usec=(long long)pausa%1000000; + tv.tv_sec = (long long)pausa / 1000000; + tv.tv_usec = (long long)pausa % 1000000; select(0, NULL, NULL, NULL, &tv); } #endif // if WIN32 - - diff --git a/GameLib/Time.h b/GameLib/Time.h index aeb06ac..d25dfe1 100644 --- a/GameLib/Time.h +++ b/GameLib/Time.h @@ -9,7 +9,6 @@ // Gets the current time in usecs. long long Time_GetTime(); - ///////////////////////////// // Time_Pause // diff --git a/GameLib/Util.c b/GameLib/Util.c index 485b908..4ef33d4 100644 --- a/GameLib/Util.c +++ b/GameLib/Util.c @@ -8,42 +8,40 @@ #include "Util.h" - ///////////////////////////// // SolveQuadratic // // Solves a Quadratic equation using a, b and c coeficients. -int SolveQuadratic(float a,float b,float c,float *Rmin,float *Rmax){ +int SolveQuadratic(float a, float b, float c, float *Rmin, float *Rmax) { float root; float divisor; float b2; - b2=b*b; - root=b2-4.0*a*c; - if(root<0){ + b2 = b * b; + root = b2 - 4.0 * a * c; + if (root < 0) { // Complex - return(0); + return (0); } - divisor=(2.0*a); - if(fabs(divisor)==0.0f){ + divisor = (2.0 * a); + if (fabs(divisor) == 0.0f) { // +inf -inf - return(0); + return (0); } - root=sqrtf(root); - Rmin[0]=(float)((-b-root)/divisor); - Rmax[0]=(float)((-b+root)/divisor); - return(1); + root = sqrtf(root); + Rmin[0] = (float)((-b - root) / divisor); + Rmax[0] = (float)((-b + root) / divisor); + return (1); } - //////////////////////////////////////////////// // vec2 // ////////// // A 2D vector. -float vec2_norm(vec2 v){ +float vec2_norm(vec2 v) { float len; - len=vec2_len(v); - vec2_scale(v,v,1.0f/len); - return(len); + len = vec2_len(v); + vec2_scale(v, v, 1.0f / len); + return (len); } void vec2_orthogonalize4(vec2 v) { @@ -100,187 +98,174 @@ void vec2_orthogonalize8(vec2 v) { } } - ///////////////////////////// // Intersec_RayUnitCircle // // Intersection between a ray and a Unit Circle. -int Intersec_RayUnitCircle(vec2 orig,vec2 vel,vec2 center,float *t){ - float a,b,c; - float Rmin,Rmax; +int Intersec_RayUnitCircle(vec2 orig, vec2 vel, vec2 center, float *t) { + float a, b, c; + float Rmin, Rmax; vec2 distv; float qlvel; float qdistv; // Check if the collision is even posible - qlvel=vec2_dot(vel,vel); - if(fabs(qlvel)<=0.0f) - return(0); - vec2_minus(distv,orig,center); - qdistv=vec2_dot(distv,distv); + qlvel = vec2_dot(vel, vel); + if (fabs(qlvel) <= 0.0f) + return (0); + vec2_minus(distv, orig, center); + qdistv = vec2_dot(distv, distv); // Solve as a unit circle - a=qlvel; - b=2.0f*vec2_dot(distv,vel); - c=qdistv-1.0f; - if(SolveQuadratic(a,b,c,&Rmin,&Rmax)){ - if(Rmin>=-0.0f && Rmin= -0.0f && Rmin < Rmax && Rmin <= 1.0f) { + *t = Rmin; + return (1); } - if(Rmax>=-0.0f && Rmin>Rmax && Rmax<=1.0f){ - *t=Rmax; - return(1); + if (Rmax >= -0.0f && Rmin > Rmax && Rmax <= 1.0f) { + *t = Rmax; + return (1); } } - return(0); + return (0); } - ///////////////////////////// // Colision_CircleCircle // // Colision point of a circle against another circle. -int Colision_CircleCircle( - vec2 cir1,float rad1,vec2 vel, - vec2 cir2,float rad2, - float *t,vec2 n) -{ - vec2 vel_a,orig_a,cen_a,temp; - float rads,invrads; - float maxx,minx; - float maxy,miny; +int Colision_CircleCircle(vec2 cir1, float rad1, vec2 vel, vec2 cir2, + float rad2, float *t, vec2 n) { + vec2 vel_a, orig_a, cen_a, temp; + float rads, invrads; + float maxx, minx; + float maxy, miny; // Check if the collision is even posible - rads=rad1+rad2; - minx=cir1[0]-rads; - maxx=cir1[0]+rads; - if(vel[0]>0){ - maxx+=vel[0]; - }else{ - minx+=vel[0]; + rads = rad1 + rad2; + minx = cir1[0] - rads; + maxx = cir1[0] + rads; + if (vel[0] > 0) { + maxx += vel[0]; + } else { + minx += vel[0]; } - if(cir2[0]maxx) - return(0); - miny=cir1[1]-rads; - maxy=cir1[1]+rads; - if(vel[1]>0){ - maxy+=vel[1]; - }else{ - miny+=vel[1]; + if (cir2[0] < minx || cir2[0] > maxx) + return (0); + miny = cir1[1] - rads; + maxy = cir1[1] + rads; + if (vel[1] > 0) { + maxy += vel[1]; + } else { + miny += vel[1]; } - if(cir2[1]maxy) - return(0); + if (cir2[1] < miny || cir2[1] > maxy) + return (0); // Convert to a unit circle vs ray - invrads=1.0f/rads; - vec2_scale(vel_a,vel,invrads); - vec2_scale(orig_a,cir1,invrads); - vec2_scale(cen_a,cir2,invrads); - if(Intersec_RayUnitCircle(orig_a,vel_a,cen_a,t)){ + invrads = 1.0f / rads; + vec2_scale(vel_a, vel, invrads); + vec2_scale(orig_a, cir1, invrads); + vec2_scale(cen_a, cir2, invrads); + if (Intersec_RayUnitCircle(orig_a, vel_a, cen_a, t)) { // Calculate n - vec2_scaleadd(temp,cir1,vel,*t); - vec2_minus(n,temp,cir2); - vec2_scale(n,n,invrads); - return(1); + vec2_scaleadd(temp, cir1, vel, *t); + vec2_minus(n, temp, cir2); + vec2_scale(n, n, invrads); + return (1); } - return(0); + return (0); } - ///////////////////////////// // Intersect_RayEdge // // Intersection between a ray and a edge. -int Intersect_RayEdge( - vec2 pos,vec2 vel, - vec2 norm,vec2 edgePos,float len, - float *t) -{ - vec2 pos2,intersection,perp,edgePos2; - float delta,d1,d2,hLen; +int Intersect_RayEdge(vec2 pos, vec2 vel, vec2 norm, vec2 edgePos, float len, + float *t) { + vec2 pos2, intersection, perp, edgePos2; + float delta, d1, d2, hLen; - vec2_plus(pos2,pos,vel); - hLen=len/2; + vec2_plus(pos2, pos, vel); + hLen = len / 2; // Check intersection against the line - delta=vec2_dot(norm,edgePos); - d1=vec2_dot(pos ,norm)-delta; - d2=vec2_dot(pos2,norm)-delta; - if(d1>=-0.0001f && d2<=0.0001f){ + delta = vec2_dot(norm, edgePos); + d1 = vec2_dot(pos, norm) - delta; + d2 = vec2_dot(pos2, norm) - delta; + if (d1 >= -0.0001f && d2 <= 0.0001f) { // Intersection with line, Calculate intersection point - *t=d1/(d1-d2); - vec2_scaleadd(intersection,pos,vel,*t); + *t = d1 / (d1 - d2); + vec2_scaleadd(intersection, pos, vel, *t); // Perpendicular - vec2_perp(perp,norm); + vec2_perp(perp, norm); // Check sides - vec2_scaleadd(edgePos2,edgePos,perp,-hLen); - delta=-vec2_dot(perp,edgePos2); - d1=(-vec2_dot(perp,intersection))-delta; + vec2_scaleadd(edgePos2, edgePos, perp, -hLen); + delta = -vec2_dot(perp, edgePos2); + d1 = (-vec2_dot(perp, intersection)) - delta; - vec2_scaleadd(edgePos2,edgePos,perp,hLen); - delta=vec2_dot(perp,edgePos2); - d2=vec2_dot(perp,intersection)-delta; + vec2_scaleadd(edgePos2, edgePos, perp, hLen); + delta = vec2_dot(perp, edgePos2); + d2 = vec2_dot(perp, intersection) - delta; - if(d1<=0.0f && d2<=0.0f){ + if (d1 <= 0.0f && d2 <= 0.0f) { // Intersection inside Edge. - return(1); + return (1); } } - return(0); + return (0); } - ///////////////////////////// // absmod // -int absmod(int v,int d){ - if(v<0){ - v+=d*(((v/d)*(-1))+1); - return(v); - }else{ - return(v%d); +int absmod(int v, int d) { + if (v < 0) { + v += d * (((v / d) * (-1)) + 1); + return (v); + } else { + return (v % d); } } -float fabsmod(float v,int d){ - if(v<0){ - v+=d*((((int)(v/d))*(-1))+1); - return(v); - }else{ - v-=d*(((int)(v/d))+1); - return(v); +float fabsmod(float v, int d) { + if (v < 0) { + v += d * ((((int)(v / d)) * (-1)) + 1); + return (v); + } else { + v -= d * (((int)(v / d)) + 1); + return (v); } } - ///////////////////////////// // IsBigEndian // -int IsBigEndian(){ - union{ +int IsBigEndian() { + union { unsigned int i; char c[4]; - } bint={0x01020304}; - return bint.c[0]==1; + } bint = {0x01020304}; + return bint.c[0] == 1; } - ///////////////////////////// // EndsWith // -int EndsWith(char *str, char *suffix){ - if (!str || !suffix) - return 0; - int lenStr = strlen(str); - int lenSuffix = strlen(suffix); - if (lenSuffix > lenStr) - return 0; - return strncmp(str+lenStr-lenSuffix, suffix, lenSuffix)==0; +int EndsWith(char *str, char *suffix) { + if (!str || !suffix) + return 0; + int lenStr = strlen(str); + int lenSuffix = strlen(suffix); + if (lenSuffix > lenStr) + return 0; + return strncmp(str + lenStr - lenSuffix, suffix, lenSuffix) == 0; } - ///////////////////////////// // Rand // @@ -356,7 +341,6 @@ unsigned Rand_Get() { return (val); } - ///////////////////////////// // Print // @@ -372,6 +356,5 @@ int Print(char *fmt, ...) { // Flush fflush(stdout); - return(n); + return (n); } - diff --git a/GameLib/Util.h b/GameLib/Util.h index 2a1414d..b20a6ae 100644 --- a/GameLib/Util.h +++ b/GameLib/Util.h @@ -10,84 +10,85 @@ // SolveQuadratic // // Solves a Quadratic equation using a, b and c coeficients. -int SolveQuadratic(float a,float b,float c,float *Rmin,float *Rmax); - +int SolveQuadratic(float a, float b, float c, float *Rmin, float *Rmax); //////////////////////////////////////////////// // vec2 // ////////// // A 2D vector. typedef float vec2[2]; -#define vec2_set(v,x,y) (v)[0]=(x);(v)[1]=(y); -#define vec2_copy(v1,v2) (v1)[0]=(v2)[0];(v1)[1]=(v2)[1]; -#define vec2_plus(v,v1,v2) (v)[0]=(v1)[0]+(v2)[0];(v)[1]=(v1)[1]+(v2)[1]; -#define vec2_minus(v,v1,v2) (v)[0]=(v1)[0]-(v2)[0];(v)[1]=(v1)[1]-(v2)[1]; -#define vec2_scale(v,v1,s) (v)[0]=(v1)[0]*(s);(v)[1]=(v1)[1]*(s); -#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_perp(v,n) (v)[0]=-(n)[1];(v)[1]=(n)[0]; -#define vec2_scaleadd(v,v1,v2,s) (v)[0]=(v2)[0]*(s)+(v1)[0];(v)[1]=(v2)[1]*(s)+(v1)[1]; +#define vec2_set(v, x, y) \ + (v)[0] = (x); \ + (v)[1] = (y); +#define vec2_copy(v1, v2) \ + (v1)[0] = (v2)[0]; \ + (v1)[1] = (v2)[1]; +#define vec2_plus(v, v1, v2) \ + (v)[0] = (v1)[0] + (v2)[0]; \ + (v)[1] = (v1)[1] + (v2)[1]; +#define vec2_minus(v, v1, v2) \ + (v)[0] = (v1)[0] - (v2)[0]; \ + (v)[1] = (v1)[1] - (v2)[1]; +#define vec2_scale(v, v1, s) \ + (v)[0] = (v1)[0] * (s); \ + (v)[1] = (v1)[1] * (s); +#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_perp(v, n) \ + (v)[0] = -(n)[1]; \ + (v)[1] = (n)[0]; +#define vec2_scaleadd(v, v1, v2, s) \ + (v)[0] = (v2)[0] * (s) + (v1)[0]; \ + (v)[1] = (v2)[1] * (s) + (v1)[1]; float vec2_norm(vec2 v); -#define vec2_interpol(v,v1,v2,f) \ - (v)[0]=(v1)[0]-f*((v1)[0]-(v2)[0]);\ - (v)[1]=(v1)[1]-f*((v1)[1]-(v2)[1]); +#define vec2_interpol(v, v1, v2, f) \ + (v)[0] = (v1)[0] - f * ((v1)[0] - (v2)[0]); \ + (v)[1] = (v1)[1] - f * ((v1)[1] - (v2)[1]); void vec2_orthogonalize4(vec2 v); void vec2_orthogonalize8(vec2 v); - ///////////////////////////// // Intersec_RayUnitCircle // // Intersection between a ray and a Unit Circle. -int Intersec_RayUnitCircle(vec2 orig,vec2 vel,vec2 center,float *t); - +int Intersec_RayUnitCircle(vec2 orig, vec2 vel, vec2 center, float *t); ///////////////////////////// // Intersect_CircleCircle // // Colision point of a circle against another circle. -int Colision_CircleCircle( - vec2 cir1,float ra,vec2 vel, - vec2 cb,float rb, - float *t,vec2 n); - +int Colision_CircleCircle(vec2 cir1, float ra, vec2 vel, vec2 cb, float rb, + float *t, vec2 n); ///////////////////////////// // Intersect_RayEdge // // Intersection between a ray and a edge. -int Intersect_RayEdge( - vec2 pos,vec2 vel, - vec2 norm,vec2 edgePos,float len, - float *t); - +int Intersect_RayEdge(vec2 pos, vec2 vel, vec2 norm, vec2 edgePos, float len, + float *t); ///////////////////////////// // absmod // -int absmod(int v,int d); -float fabsmod(float v,int d); - +int absmod(int v, int d); +float fabsmod(float v, int d); ///////////////////////////// // IsBigEndian // int IsBigEndian(); - ///////////////////////////// // EndsWith // int EndsWith(char *str, char *suffix); - ///////////////////////////// // Rand // void Rand_Seed(unsigned seed); unsigned Rand_Get(); -#define Rand_GetFloat(x) (((float)(Rand_Get()%1048576))/1048576.0f) - +#define Rand_GetFloat(x) (((float)(Rand_Get() % 1048576)) / 1048576.0f) ///////////////////////////// // Print @@ -95,5 +96,4 @@ unsigned Rand_Get(); // Prints the formated text int Print(char *fmt, ...); - #endif